Merge remote-tracking branch 'origin/main' into feat/suggest-code-review

# Conflicts:
#	packages/opencode/src/tool/registry.ts
This commit is contained in:
Alex Alecu
2026-04-14 16:00:08 +03:00
99 changed files with 3385 additions and 1405 deletions
@@ -0,0 +1,6 @@
---
"@kilocode/cli": patch
"kilo-code": patch
---
Fixed default model falling back to the free model after login or org switch by invalidating cached provider state when auth changes.
@@ -0,0 +1,5 @@
---
"@kilocode/kilo-gateway": patch
---
Include the feature header when requesting the models list from Kilo Gateway
+5
View File
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---
Reduce git process load via visibility-aware polling and resolution caching in GitStatsPoller
+5
View File
@@ -0,0 +1,5 @@
---
"kilo-code": minor
---
Add @terminal context mention support to the chat input. Type @terminal to include your active VS Code terminal output as context, with output safety limits (500 lines / 50K chars) and truncation. Works in both the sidebar chat and Agent Manager.
+6
View File
@@ -171,6 +171,12 @@ Tests MUST test actual implementation, do not duplicate logic into a test.
[Conventional Commits](https://www.conventionalcommits.org/) with scopes matching packages: `vscode`, `cli`, `agent-manager`, `sdk`, `ui`, `i18n`, `kilo-docs`, `gateway`, `telemetry`, `desktop`. Omit scope when spanning multiple packages.
## Changesets
User-facing changes (features, fixes, breaking changes) require a changeset file for release notes. Run `bunx changeset add` or manually create `.changeset/<slug>.md`. Use `patch` for bug fixes, `minor` for new features, `major` for breaking changes. See `.changeset/README.md` for details.
Changeset descriptions appear directly in release notes and are read by end users. Keep them concise and feature-oriented — describe **what changed from the user's perspective**, not implementation details. Write in imperative mood (e.g. "Support exporting conversations as markdown" not "Add a new export handler that serializes session messages to .md files").
## Pull Requests
PR descriptions should be 2-3 lines covering **what** changed and **why**. Focus on intent and context a reviewer can't get from the diff — skip file-by-file inventories, test result summaries, and anything obvious from the code itself.
+7 -3
View File
@@ -187,7 +187,7 @@
"@clack/prompts": "1.0.0-alpha.1",
"@kilocode/plugin": "workspace:*",
"@kilocode/sdk": "workspace:*",
"@openrouter/ai-sdk-provider": "2.3.3",
"@openrouter/ai-sdk-provider": "2.5.1",
"ai": "catalog:",
"open": "10.1.2",
"zod": "catalog:",
@@ -382,7 +382,7 @@
"@openauthjs/openauth": "catalog:",
"@opencode-ai/script": "workspace:*",
"@opencode-ai/util": "workspace:*",
"@openrouter/ai-sdk-provider": "2.3.3",
"@openrouter/ai-sdk-provider": "2.5.1",
"@opentui/core": "0.1.96",
"@opentui/solid": "0.1.96",
"@parcel/watcher": "2.5.1",
@@ -413,6 +413,7 @@
"jsonc-parser": "3.3.1",
"mime-types": "3.0.2",
"minimatch": "10.2.5",
"npm-package-arg": "13.0.2",
"open": "10.1.2",
"opencode-gitlab-auth": "2.0.1",
"opencode-poe-auth": "0.0.1",
@@ -457,6 +458,7 @@
"@types/bun": "catalog:",
"@types/cross-spawn": "catalog:",
"@types/mime-types": "3.0.1",
"@types/npm-package-arg": "6.1.4",
"@types/npmcli__arborist": "6.3.3",
"@types/semver": "^7.5.8",
"@types/turndown": "5.0.5",
@@ -1485,7 +1487,7 @@
"@opencode-ai/util": ["@opencode-ai/util@workspace:packages/util"],
"@openrouter/ai-sdk-provider": ["@openrouter/ai-sdk-provider@2.3.3", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-4fVteGkVedc7fGoA9+qJs4tpYwALezMq14m2Sjub3KmyRlksCbK+WJf67NPdGem8+NZrV2tAN42A1NU3+SiV3w=="],
"@openrouter/ai-sdk-provider": ["@openrouter/ai-sdk-provider@2.5.1", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-r1fJL1Cb3gQDa2MpWH/sfx1BsEW0uzlRriJM6eihaKqbtKDmZoBisF32VcVaQYassighX7NGCkF68EsrZA43uQ=="],
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
@@ -5079,6 +5081,8 @@
"ai-gateway-provider/@ai-sdk/xai": ["@ai-sdk/xai@3.0.74", "", { "dependencies": { "@ai-sdk/openai-compatible": "2.0.37", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-HDDLsT+QrzE3c2QZLRV/HKAwMtXDb0PMDdk1PYUXLJ3r9Qv76zGKGyvJLX7Pu6c8TOHD1mwLrOVYrsTpC/eTMw=="],
"ai-gateway-provider/@openrouter/ai-sdk-provider": ["@openrouter/ai-sdk-provider@2.3.3", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-4fVteGkVedc7fGoA9+qJs4tpYwALezMq14m2Sjub3KmyRlksCbK+WJf67NPdGem8+NZrV2tAN42A1NU3+SiV3w=="],
"ajv-keywords/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="],
"app-builder-lib/@electron/get": ["@electron/get@3.1.0", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ=="],
+4 -4
View File
@@ -1,8 +1,8 @@
{
"nodeModules": {
"x86_64-linux": "sha256-QozPRHFapCgdinNYAc2Yk+8sk/w7lJN2StBSjeXh5Rc=",
"aarch64-linux": "sha256-da239x4X+qs1EFGKJnSZu1bsqRVbKQVOvOYzzORokyI=",
"aarch64-darwin": "sha256-vp+jfpceTQjalxYIUh1ewxDis8mcTJNh6phbyHn/ucA=",
"x86_64-darwin": "sha256-cQgLcQGTUizoMIZ+KMj9HNEmogL84bJYakWGlXxWvkk="
"x86_64-linux": "sha256-wRgRi939a/0RPCKthLccnBjYbiRcWhCOhbHd0HgyUhs=",
"aarch64-linux": "sha256-oYqoGtXLp9/GE5yU9l6RLoK8sVLxZKgp1BMcpmDhFe0=",
"aarch64-darwin": "sha256-zTpY9iM/Vp/OmQ35rybhRgoN7neXzNeugZD+0a5O+LU=",
"x86_64-darwin": "sha256-H/5W9FKEK/N9m11+N0sIZgr9LMQuhKaErrxYyQBEhtM="
}
}
+4 -6
View File
@@ -16,9 +16,7 @@
"random": "echo 'Random script'",
"hello": "echo 'Hello World!'",
"test": "echo 'do not run tests from root' && exit 1",
"extension": "bun --cwd packages/kilo-vscode script/launch.ts",
"changeset": "bunx changeset",
"changeset:version": "bunx changeset version && bun install --lockfile-only"
"extension": "bun --cwd packages/kilo-vscode script/launch.ts"
},
"workspaces": {
"packages": [
@@ -76,8 +74,6 @@
},
"devDependencies": {
"@actions/artifact": "5.0.1",
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.27.10",
"@tsconfig/bun": "catalog:",
"@types/mime-types": "3.0.1",
"@typescript/native-preview": "catalog:",
@@ -86,7 +82,9 @@
"prettier": "3.6.2",
"semver": "^7.6.0",
"sst": "3.18.10",
"turbo": "2.8.13"
"turbo": "2.8.13",
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.27.10"
},
"dependencies": {
"@aws-sdk/client-s3": "3.1025.0",
+4 -2
View File
@@ -398,7 +398,8 @@ export const dict = {
"toast.session.unshare.failed.description": "Une erreur s'est produite lors de l'annulation du partage de la session",
"toast.session.listFailed.title": "Échec du chargement des sessions pour {{project}}",
"toast.update.title": "Mise à jour disponible",
"toast.update.description": "Une nouvelle version d'Kilo ({{version}}) est maintenant disponible pour installation.",
"toast.update.description":
"Une nouvelle version d'Kilo ({{version}}) est maintenant disponible pour installation.",
"toast.update.action.installRestart": "Installer et redémarrer",
"toast.update.action.notYet": "Pas encore",
"error.page.title": "Quelque chose s'est mal passé",
@@ -548,7 +549,8 @@ export const dict = {
"sidebar.workspaces.enable": "Activer les espaces de travail",
"sidebar.workspaces.disable": "Désactiver les espaces de travail",
"sidebar.gettingStarted.title": "Commencer",
"sidebar.gettingStarted.line1": "Kilo inclut des modèles gratuits pour que vous puissiez commencer immédiatement.",
"sidebar.gettingStarted.line1":
"Kilo inclut des modèles gratuits pour que vous puissiez commencer immédiatement.",
"sidebar.gettingStarted.line2":
"Connectez n'importe quel fournisseur pour utiliser des modèles, y compris Claude, GPT, Gemini etc.",
"sidebar.project.recentSessions": "Sessions récentes",
+2 -1
View File
@@ -149,7 +149,8 @@ export const dict = {
"provider.connect.oauth.code.invalid": "รหัสการอนุญาตไม่ถูกต้อง",
"provider.connect.oauth.auto.visit.prefix": "เยี่ยมชม ",
"provider.connect.oauth.auto.visit.link": "ลิงก์นี้",
"provider.connect.oauth.auto.visit.suffix": " และป้อนรหัสด้านล่างเพื่อเชื่อมต่อบัญชีและใช้โมเดล {{provider}} ใน Kilo",
"provider.connect.oauth.auto.visit.suffix":
" และป้อนรหัสด้านล่างเพื่อเชื่อมต่อบัญชีและใช้โมเดล {{provider}} ใน Kilo",
"provider.connect.oauth.auto.confirmationCode": "รหัสยืนยัน",
"provider.connect.toast.connected.title": "{{provider}} ที่เชื่อมต่อแล้ว",
"provider.connect.toast.connected.description": "โมเดล {{provider}} พร้อมใช้งานแล้ว",
+2 -1
View File
@@ -150,7 +150,8 @@ export const dict = {
"provider.connect.oauth.code.invalid": "授權碼無效",
"provider.connect.oauth.auto.visit.prefix": "造訪 ",
"provider.connect.oauth.auto.visit.link": "此連結",
"provider.connect.oauth.auto.visit.suffix": " 並輸入以下程式碼,以連線你的帳戶並在 Kilo 中使用 {{provider}} 模型。",
"provider.connect.oauth.auto.visit.suffix":
" 並輸入以下程式碼,以連線你的帳戶並在 Kilo 中使用 {{provider}} 模型。",
"provider.connect.oauth.auto.confirmationCode": "確認碼",
"provider.connect.toast.connected.title": "{{provider}} 已連線",
"provider.connect.toast.connected.description": "現在可以使用 {{provider}} 模型了。",
@@ -44,7 +44,9 @@ export const ProjectIcon = (props: { project: LocalProject; class?: string; noti
<div class="size-full rounded overflow-clip">
<Avatar
fallback={name()}
src={props.project.id === KILO_PROJECT_ID ? "https://kilo.ai/favicon.svg" : props.project.icon?.override}
src={
props.project.id === KILO_PROJECT_ID ? "https://kilo.ai/favicon.svg" : props.project.icon?.override
}
{...getAvatarColors(props.project.icon?.color)}
class="size-full rounded"
classList={{ "badge-mask": notify() }}
+6 -6
View File
@@ -1,7 +1,7 @@
id = "kilo"
name = "Kilo"
description = "The open source coding agent."
version = "7.2.5"
version = "1.3.17"
schema_version = 1
authors = ["Anomaly"]
repository = "https://github.com/Kilo-Org/kilocode"
@@ -11,26 +11,26 @@ name = "Kilo"
icon = "./icons/opencode.svg"
[agent_servers.opencode.targets.darwin-aarch64]
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v7.2.5/opencode-darwin-arm64.zip"
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v1.3.17/opencode-darwin-arm64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.darwin-x86_64]
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v7.2.5/opencode-darwin-x64.zip"
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v1.3.17/opencode-darwin-x64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.linux-aarch64]
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v7.2.5/opencode-linux-arm64.tar.gz"
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v1.3.17/opencode-linux-arm64.tar.gz"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.linux-x86_64]
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v7.2.5/opencode-linux-x64.tar.gz"
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v1.3.17/opencode-linux-x64.tar.gz"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.windows-x86_64]
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v7.2.5/opencode-windows-x64.zip"
archive = "https://github.com/Kilo-Org/kilocode/releases/download/v1.3.17/opencode-windows-x64.zip"
cmd = "./opencode.exe"
args = ["acp"]
@@ -74,7 +74,7 @@ Find the Kilo Code icon ({% kiloCodeIcon /%}) in VS Code's Primary Side Bar. Cli
**Providing context:**
The extension automatically passes context from your editor, including your open tabs and active file. You can type `@` in the chat input to get file autocomplete suggestions, or mention file paths naturally in your message (e.g., "update src/utils.ts to add a helper function"). The agent can also discover files on its own using its built-in tools.
The extension automatically passes context from your editor, including your open tabs and active file. You can type `@` in the chat input to get file and terminal autocomplete suggestions — use `@filename` to attach a file or `@terminal` to include your active terminal output. You can also mention file paths naturally in your message (e.g., "update src/utils.ts to add a helper function"). The agent can also discover files on its own using its built-in tools.
{% /tab %}
{% tab label="CLI" %}
@@ -18,7 +18,14 @@ When you describe a task, the agent uses its tools — `read`, `grep`, `glob`, a
### @-Mention Autocomplete
Type `@` in the chat input followed by a filename to get autocomplete suggestions. Selecting a file attaches its contents to your message. This is the quickest way to reference a specific file.
Type `@` in the chat input to get autocomplete suggestions. You can mention:
| Mention | Description | Example |
| ------------ | ------------------------------------------- | --------------- |
| **File** | Attach a file's contents to your message | `@src/utils.ts` |
| **Terminal** | Include your active VS Code terminal output | `@terminal` |
Selecting a suggestion inserts the mention and highlights it in the input. File contents and terminal output are attached as context when you send the message.
### Automatic Editor Context
+2 -4
View File
@@ -1,7 +1,7 @@
# Source Code Links
<!-- Auto-generated by script/extract-source-links.ts — DO NOT EDIT -->
<!-- 78 unique URLs extracted from extension and CLI source -->
<!-- 77 unique URLs extracted from extension and CLI source -->
- <https://api.apertis.ai/v1>
<!-- packages/opencode/src/provider/model-cache.ts -->
@@ -59,8 +59,6 @@
<!-- packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx -->
- <https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip>
<!-- packages/opencode/src/lsp/server.ts -->
- <https://github.com/OpenRouterTeam/ai-sdk-provider/pull/344/>
<!-- packages/opencode/src/provider/transform.ts -->
- <https://github.com/oven-sh/bun/issues/16682>
<!-- packages/opencode/src/provider/provider.ts -->
- <https://github.com/vercel/ai/blob/2dc67e0ef538307f21368db32d5a12345d98831b/packages/ai/src/logger/log-warnings.ts#L85>
@@ -85,7 +83,7 @@
- <https://kilo.ai/docs/providers/#custom-provider>
<!-- packages/kilo-vscode/webview-ui/src/components/settings/CustomProviderDialog.tsx -->
- <https://kilo.ai/gateway>
<!-- packages/opencode/src/cli/cmd/tui/component/dialog-provider.tsx -->
<!-- packages/opencode/src/kilocode/cli/cmd/tui/component/dialog-provider.tsx -->
- <https://kilo.ai/install>
<!-- packages/opencode/src/installation/index.ts -->
- <https://kilo.ai/kiloclaw>
+1 -1
View File
@@ -32,7 +32,7 @@
"@ai-sdk/anthropic": "3.0.64",
"@ai-sdk/openai": "3.0.48",
"@ai-sdk/openai-compatible": "2.0.37",
"@openrouter/ai-sdk-provider": "2.3.3",
"@openrouter/ai-sdk-provider": "2.5.1",
"@clack/prompts": "1.0.0-alpha.1",
"ai": "catalog:",
"open": "10.1.2",
+2 -1
View File
@@ -1,6 +1,6 @@
import { z } from "zod"
import { getKiloUrlFromToken } from "../auth/token.js"
import { getDefaultHeaders } from "../headers.js"
import { getDefaultHeaders, buildKiloHeaders } from "../headers.js"
import { KILO_API_BASE, KILO_OPENROUTER_BASE, MODELS_FETCH_TIMEOUT_MS, PROMPTS, AI_SDK_PROVIDERS } from "./constants.js"
/**
@@ -89,6 +89,7 @@ export async function fetchKiloModels(options?: {
const response = await fetch(modelsURL, {
headers: {
...getDefaultHeaders(),
...buildKiloHeaders(undefined, { kilocodeOrganizationId: organizationId }),
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
signal: AbortSignal.timeout(MODELS_FETCH_TIMEOUT_MS),
@@ -32,6 +32,7 @@ interface KiloRoutesDeps extends ImportDeps {
Auth: Auth
ModelCache: ModelCache
z: Z
Instance: ImportDeps["Instance"] & { disposeAll(): Promise<void> }
}
/**
@@ -206,6 +207,7 @@ export function createKiloRoutes(deps: KiloRoutesDeps) {
ModelCache.clear("kilo")
clearModesCache()
await Instance.disposeAll()
return c.json(true)
},
+9 -2
View File
@@ -303,6 +303,13 @@ async function launch() {
args.push("--wait")
}
// Strip Electron/VS Code env vars so the spawned instance doesn't attach
// to the current Electron process (e.g. when launched from a VS Code task).
const env = { ...process.env }
for (const key of Object.keys(env)) {
if (key.startsWith("ELECTRON_") || key.startsWith("VSCODE_")) delete env[key]
}
console.log(`[launch] Starting VS Code (${mode} mode)`)
console.log(`[launch] Executable: ${app}`)
console.log(`[launch] Workspace: ${workspace}`)
@@ -311,7 +318,7 @@ async function launch() {
if (blocking) {
const result = Bun.spawnSync([app, ...args], {
cwd: workspace,
env: process.env,
env,
stdio: ["ignore", "inherit", "inherit"],
})
console.log(`[launch] VS Code exited (code ${result.exitCode})`)
@@ -321,7 +328,7 @@ async function launch() {
const child = spawn(app, args, {
cwd: workspace,
detached: !win,
env: process.env,
env,
stdio: "ignore",
...(win ? { shell: true } : {}),
})
+47 -12
View File
@@ -44,7 +44,8 @@ import { getBusySessionCount, seedSessionStatuses } from "./session-status"
import { retry } from "./services/cli-backend/retry"
import { slimPart, slimParts } from "./kilo-provider/slim-metadata"
import { handleContinueInWorktree } from "./kilo-provider/continue-worktree"
import { parseMessageFiles } from "./kilo-provider/message-files"
import { parseMessageFiles, type MessageFile } from "./kilo-provider/message-files"
import { getTerminalContents } from "./services/terminal/context"
import { matchFollowup, recordFollowup, type Followup } from "./kilo-provider/followup-session"
import { childID } from "./kilo-provider/task-session"
import { handleNetworkEvent, clearNetworkWaits } from "./kilo-provider/network"
@@ -121,6 +122,7 @@ const mapAgent = (a: Agent) => ({
color: a.color,
deprecated: a.deprecated,
permission: a.permission,
model: a.model,
})
export class KiloProvider implements vscode.WebviewViewProvider, TelemetryPropertiesProvider {
@@ -399,7 +401,10 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.visibilityDisposable?.dispose()
this.visibilityDisposable = webviewView.onDidChangeVisibility(() => {
vscode.commands.executeCommand("setContext", "kilo-code.new.sidebarVisible", webviewView.visible)
this.statsPoller?.setEnabled(webviewView.visible)
if (this.statsPoller) {
this.statsPoller.setEnabled(webviewView.visible)
this.statsPoller.setVisible(webviewView.visible)
}
this.focusSession(webviewView.visible ? this.currentSession?.id : undefined)
})
this.initializeConnection()
@@ -831,15 +836,12 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}
break
}
case "requestTerminalContext":
void this.handleTerminalContext(message.requestId)
break
case "chatCompletionAccepted":
this.chatAutocomplete?.telemetry.captureAcceptSuggestion(message.suggestionLength)
break
case "deleteSession":
await this.handleDeleteSession(message.sessionID)
break
case "renameSession":
await this.handleRenameSession(message.sessionID, message.title)
break
case "toggleRemote":
case "setRemoteEnabled":
case "requestRemoteStatus":
@@ -850,6 +852,12 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
})
.catch((err) => console.error("[Kilo New] remote message failed:", err))
break
case "deleteSession":
await this.handleDeleteSession(message.sessionID)
break
case "renameSession":
await this.handleRenameSession(message.sessionID, message.title)
break
case "updateSetting":
await this.handleUpdateSetting(message.key, message.value)
break
@@ -1488,6 +1496,25 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.pendingSessionRefresh = ctx.pendingSessionRefresh
}
private async handleTerminalContext(requestId: string): Promise<void> {
try {
const output = await getTerminalContents(-1)
this.postMessage({
type: "terminalContextResult",
requestId,
content: output.content,
truncated: output.truncated,
})
} catch (error) {
console.error("[Kilo New] Failed to capture terminal context:", error)
this.postMessage({
type: "terminalContextError",
requestId,
error: getErrorMessage(error) || "Failed to capture terminal output",
})
}
}
/**
* Handle deleting a session.
*/
@@ -2394,7 +2421,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
modelID?: string,
agent?: string,
variant?: string,
files?: Array<{ mime: string; url: string }>,
files?: MessageFile[],
): Promise<void> {
if (!this.client) {
this.postMessage({
@@ -2416,7 +2443,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
const parts: Array<TextPartInput | FilePartInput> = []
if (files) {
for (const f of files) {
parts.push({ type: "file", mime: f.mime, url: f.url })
parts.push({ type: "file", mime: f.mime, url: f.url, filename: f.filename, source: f.source })
}
}
parts.push({ type: "text", text })
@@ -2470,7 +2497,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
modelID?: string,
agent?: string,
variant?: string,
files?: Array<{ mime: string; url: string }>,
files?: MessageFile[],
): Promise<void> {
if (!this.client) {
this.postMessage({
@@ -2493,7 +2520,13 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.connectionService.recordMessageSessionId(messageID, resolved!.sid)
}
const parts = files?.map((f) => ({ type: "file" as const, mime: f.mime, url: f.url }))
const parts = files?.map((f) => ({
type: "file" as const,
mime: f.mime,
url: f.url,
filename: f.filename,
source: f.source,
}))
const sid = resolved!.sid
const dir = resolved!.dir
@@ -3287,8 +3320,10 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.postMessage(msg)
},
log: () => {},
hiddenIntervalMs: 60000,
})
this.statsPoller.setEnabled(true)
this.statsPoller.setVisible(true)
}
/**
@@ -188,6 +188,11 @@ export class AgentManagerProvider implements Disposable {
}
this.panel = ctx
this.statsPoller.setVisible(ctx.visible)
ctx.onDidChangeVisibility((visible) => {
this.statsPoller.setVisible(visible)
})
this.stateReady = this.initializeState()
void this.sendRepoInfo()
this.sendKeybindings()
@@ -326,6 +331,11 @@ export class AgentManagerProvider implements Disposable {
return msg
}
if (m.type === "requestTerminalContext") {
if (m.sessionID) this.terminalManager.showExisting(m.sessionID)
return msg
}
if (m.type === "loadMessages") {
this.activeSessionId = m.sessionID
this.connectionService.registerFocused("agent-manager", m.sessionID)
@@ -67,6 +67,9 @@ export class GitOps {
private readonly runGit: (args: string[], cwd: string) => Promise<string>
private readonly controller = new AbortController()
private readonly semaphore: Semaphore | undefined
private readonly resolutionCache = new Map<string, { value: string; expires: number }>()
private static readonly CACHE_TTL_MS = 60000
private static readonly MAX_CACHE_SIZE = 100
get disposed(): boolean {
return this.controller.signal.aborted
@@ -87,6 +90,30 @@ export class GitOps {
if (!this.controller.signal.aborted) {
this.controller.abort()
}
this.resolutionCache.clear()
}
private getCached(key: string): string | undefined {
const entry = this.resolutionCache.get(key)
if (entry && entry.expires > Date.now()) {
return entry.value
}
return undefined
}
private setCached(key: string, value: string): void {
if (this.resolutionCache.size >= GitOps.MAX_CACHE_SIZE) {
let oldestKey: string | undefined
let oldestExpiry = Infinity
for (const [k, v] of this.resolutionCache) {
if (v.expires < oldestExpiry) {
oldestExpiry = v.expires
oldestKey = k
}
}
if (oldestKey) this.resolutionCache.delete(oldestKey)
}
this.resolutionCache.set(key, { value, expires: Date.now() + GitOps.CACHE_TTL_MS })
}
private raw(args: string[], cwd: string): Promise<string> {
@@ -122,38 +149,68 @@ export class GitOps {
* 3. Falls back to `origin`
*/
async resolveRemote(cwd: string, branch?: string): Promise<string> {
const cacheKey = `remote:${cwd}:${branch}`
const cached = this.getCached(cacheKey)
if (cached) return cached
const upstream = await this.raw(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], cwd).catch(
() => "",
)
if (upstream.includes("/")) return upstream.split("/")[0]
if (upstream.includes("/")) {
const result = upstream.split("/")[0]
this.setCached(cacheKey, result)
return result
}
const name = branch || (await this.raw(["branch", "--show-current"], cwd).catch(() => ""))
if (name) {
const configured = await this.raw(["config", `branch.${name}.remote`], cwd).catch(() => "")
if (configured) return configured
if (configured) {
this.setCached(cacheKey, configured)
return configured
}
}
return "origin"
const result = "origin"
this.setCached(cacheKey, result)
return result
}
/** Resolve the upstream tracking ref for `branch`, or `undefined` if none is set. Note: the `@{upstream}` check uses the current HEAD, not `branch`. */
async resolveTrackingBranch(cwd: string, branch: string): Promise<string | undefined> {
const cacheKey = `tracking:${cwd}:${branch}`
const cached = this.getCached(cacheKey)
if (cached !== undefined) return cached === "" ? undefined : cached
const upstream = await this.raw(["rev-parse", "--abbrev-ref", "@{upstream}"], cwd).catch(() => "")
if (upstream) return upstream
if (upstream) {
this.setCached(cacheKey, upstream)
return upstream
}
const remote = await this.resolveRemote(cwd, branch)
const ref = `${remote}/${branch}`
const resolved = await this.raw(["rev-parse", "--verify", ref], cwd).catch(() => "")
if (resolved) return ref
if (resolved) {
this.setCached(cacheKey, ref)
return ref
}
this.setCached(cacheKey, "")
return undefined
}
/** Resolve the repo's default branch via <remote>/HEAD. */
async resolveDefaultBranch(cwd: string, branch?: string): Promise<string | undefined> {
const remote = await this.resolveRemote(cwd, branch)
const cacheKey = `default-branch:${cwd}:${remote}`
const cached = this.getCached(cacheKey)
if (cached !== undefined) return cached
const head = await this.raw(["symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`], cwd).catch(() => "")
return head || undefined
const result = head || undefined
this.setCached(cacheKey, result ?? "")
return result
}
async hasRemoteRef(cwd: string, ref: string): Promise<boolean> {
@@ -48,6 +48,7 @@ interface GitStatsPollerOptions {
intervalMs?: number
/** Shared concurrency gate for child process spawning. */
semaphore?: Semaphore
hiddenIntervalMs?: number
}
export class GitStatsPoller {
@@ -62,14 +63,27 @@ export class GitStatsPoller {
{ files: number; additions: number; deletions: number; ahead: number; behind: number }
> = {}
private readonly intervalMs: number
private readonly hiddenIntervalMs: number
private readonly git: GitOps
private skipWorktreeIds = new Set<string>()
private visible = true
constructor(private readonly options: GitStatsPollerOptions) {
this.intervalMs = options.intervalMs ?? 5000
this.hiddenIntervalMs = options.hiddenIntervalMs ?? 60000
this.git = options.git
}
setVisible(visible: boolean): void {
if (this.visible === visible) return
this.visible = visible
if (this.active && this.timer) {
clearTimeout(this.timer)
this.timer = undefined
this.schedule(this.visible ? this.intervalMs : this.hiddenIntervalMs)
}
}
skipWorktree(id: string): void {
this.skipWorktreeIds.add(id)
}
@@ -81,7 +95,8 @@ export class GitStatsPoller {
setEnabled(enabled: boolean): void {
if (enabled) {
if (this.active) return
this.start()
this.active = true
void this.poll()
return
}
this.stop()
@@ -100,10 +115,8 @@ export class GitStatsPoller {
this.lastStats = {}
}
private start(): void {
this.stop()
this.active = true
void this.poll()
private currentInterval(): number {
return this.visible ? this.intervalMs : this.hiddenIntervalMs
}
private schedule(delay: number): void {
@@ -119,7 +132,7 @@ export class GitStatsPoller {
this.busy = true
return this.fetch().finally(() => {
this.busy = false
this.schedule(this.intervalMs)
this.schedule(this.currentInterval())
})
}
@@ -534,6 +534,16 @@ interface LoadMessagesIn {
sessionID: string
}
interface FileSourceIn {
type: "file"
path: string
text: {
value: string
start: number
end: number
}
}
interface SendMessageIn {
type: "sendMessage"
text: string
@@ -544,7 +554,7 @@ interface SendMessageIn {
modelID?: string
agent?: string
variant?: string
files?: Array<{ mime: string; url: string; filename?: string }>
files?: Array<{ mime: string; url: string; filename?: string; source?: FileSourceIn }>
}
interface SendCommandIn {
@@ -558,7 +568,13 @@ interface SendCommandIn {
modelID?: string
agent?: string
variant?: string
files?: Array<{ mime: string; url: string; filename?: string }>
files?: Array<{ mime: string; url: string; filename?: string; source?: FileSourceIn }>
}
interface RequestTerminalContextIn {
type: "requestTerminalContext"
requestId: string
sessionID?: string
}
interface ClearSessionIn {
@@ -673,6 +689,7 @@ export type AgentManagerInMessage =
| LoadMessagesIn
| SendMessageIn
| SendCommandIn
| RequestTerminalContextIn
| ClearSessionIn
| AbortIn
| ContinueInWorktreeIn
@@ -206,10 +206,9 @@ export async function loadSessions(ctx: SessionRefreshContext): Promise<string |
const seen = new Set(sessions.map((s) => s.id))
for (const batch of extra) {
for (const s of batch) {
if (!seen.has(s.id) && (!projectID || s.projectID === projectID)) {
sessions.push(s)
seen.add(s.id)
}
if (seen.has(s.id)) continue
sessions.push(s)
seen.add(s.id)
}
}
@@ -218,7 +217,7 @@ export async function loadSessions(ctx: SessionRefreshContext): Promise<string |
sessions: sessions.map((s) => sessionToWebview(s)),
})
return sessions[0]?.projectID
return projectID
}
/**
@@ -8,6 +8,7 @@
import type { KiloClient, Session, TextPartInput, FilePartInput } from "@kilocode/sdk/v2/client"
import type { CloudSessionData, EditorContext } from "../../services/cli-backend/types"
import { getErrorMessage, sessionToWebview, mapCloudSessionMessageToWebviewMessage } from "../../kilo-provider-utils"
import type { MessageFile } from "../message-files"
export interface CloudSessionContext {
readonly client: KiloClient | null
@@ -115,7 +116,7 @@ export async function handleImportAndSend(
modelID?: string,
agent?: string,
variant?: string,
files?: Array<{ mime: string; url: string }>,
files?: MessageFile[],
command?: string,
commandArgs?: string,
): Promise<void> {
@@ -177,7 +178,13 @@ export async function handleImportAndSend(
}
if (command) {
const parts = files?.map((f) => ({ type: "file" as const, mime: f.mime, url: f.url }))
const parts = files?.map((f) => ({
type: "file" as const,
mime: f.mime,
url: f.url,
filename: f.filename,
source: f.source,
}))
await client.session.command(
{
sessionID: session.id,
@@ -198,7 +205,7 @@ export async function handleImportAndSend(
const parts: Array<TextPartInput | FilePartInput> = []
if (files) {
for (const f of files) {
parts.push({ type: "file", mime: f.mime, url: f.url })
parts.push({ type: "file", mime: f.mime, url: f.url, filename: f.filename, source: f.source })
}
}
parts.push({ type: "text", text })
@@ -1,11 +1,24 @@
import { z } from "zod"
const source = z.object({
type: z.literal("file"),
path: z.string(),
text: z.object({
value: z.string(),
start: z.number(),
end: z.number(),
}),
})
const file = z.object({
mime: z.string(),
url: z.string().refine((url) => url.startsWith("file://") || url.startsWith("data:")),
filename: z.string().optional(),
source: source.optional(),
})
export type MessageFile = z.infer<typeof file>
export function parseMessageFiles(value: unknown) {
return z.array(file).optional().catch(undefined).parse(value)
}
@@ -2,52 +2,7 @@ import * as vscode from "vscode"
import type { KiloProvider } from "../../KiloProvider"
import type { AgentManagerProvider } from "../../agent-manager/AgentManagerProvider"
import { createPrompt } from "./support-prompt"
/**
* Read terminal content via clipboard.
* When `commands` is negative, selects all terminal content.
* When positive, selects the last N commands.
*/
async function getTerminalContents(commands = -1): Promise<string> {
const saved = await vscode.env.clipboard.readText()
try {
if (commands < 0) {
await vscode.commands.executeCommand("workbench.action.terminal.selectAll")
} else {
for (let i = 0; i < commands; i++) {
await vscode.commands.executeCommand("workbench.action.terminal.selectToPreviousCommand")
}
}
await vscode.commands.executeCommand("workbench.action.terminal.copySelection")
await vscode.commands.executeCommand("workbench.action.terminal.clearSelection")
let content = (await vscode.env.clipboard.readText()).trim()
await vscode.env.clipboard.writeText(saved)
if (saved === content) {
return ""
}
// Trim duplicate trailing prompt line
const lines = content.split("\n")
const last = lines.pop()?.trim()
if (last) {
let i = lines.length - 1
while (i >= 0 && !lines[i].trim().startsWith(last)) {
i--
}
content = lines.slice(Math.max(i, 0)).join("\n")
}
return content
} catch (err) {
await vscode.env.clipboard.writeText(saved)
throw err
}
}
import { getTerminalContents } from "../terminal/context"
export function registerTerminalActions(
context: vscode.ExtensionContext,
@@ -60,7 +15,7 @@ export function registerTerminalActions(
vscode.commands.registerCommand("kilo-code.new.terminalAddToContext", async (args: any) => {
let content = args?.selection as string | undefined
if (!content) {
content = await getTerminalContents(-1)
content = (await getTerminalContents(-1)).content
}
if (!content) {
vscode.window.showInformationMessage("No terminal content available. Select text in the terminal first.")
@@ -77,7 +32,7 @@ export function registerTerminalActions(
vscode.commands.registerCommand("kilo-code.new.terminalFixCommand", async (args: any) => {
let content = args?.selection as string | undefined
if (!content) {
content = await getTerminalContents(1)
content = (await getTerminalContents(1)).content
}
if (!content) {
vscode.window.showInformationMessage("No terminal content available. Select text in the terminal first.")
@@ -93,7 +48,7 @@ export function registerTerminalActions(
vscode.commands.registerCommand("kilo-code.new.terminalExplainCommand", async (args: any) => {
let content = args?.selection as string | undefined
if (!content) {
content = await getTerminalContents(1)
content = (await getTerminalContents(1)).content
}
if (!content) {
vscode.window.showInformationMessage("No terminal content available. Select text in the terminal first.")
@@ -0,0 +1,39 @@
import * as vscode from "vscode"
import { truncateTerminalOutput, type TerminalLimitOptions, type TerminalOutput } from "./truncate"
function trimPrompt(content: string) {
const lines = content.split("\n")
const last = lines.pop()?.trim()
if (!last) return content
const idx = lines.reduce((found, line, index) => (line.trim().startsWith(last) ? index : found), -1)
return lines.slice(Math.max(idx, 0)).join("\n")
}
async function selectPrevious(count: number): Promise<void> {
if (count <= 0) return
await vscode.commands.executeCommand("workbench.action.terminal.selectToPreviousCommand")
await selectPrevious(count - 1)
}
export async function getTerminalContents(commands = -1, opts?: TerminalLimitOptions): Promise<TerminalOutput> {
const saved = await vscode.env.clipboard.readText()
try {
if (commands < 0) {
await vscode.commands.executeCommand("workbench.action.terminal.selectAll")
} else {
await selectPrevious(commands)
}
await vscode.commands.executeCommand("workbench.action.terminal.copySelection")
await vscode.commands.executeCommand("workbench.action.terminal.clearSelection")
const copied = (await vscode.env.clipboard.readText()).trim()
if (saved === copied) return { content: "", truncated: false }
return truncateTerminalOutput(trimPrompt(copied), opts)
} finally {
await vscode.env.clipboard.writeText(saved)
}
}
@@ -0,0 +1,39 @@
export const TERMINAL_OUTPUT_LINE_LIMIT = 500
export const TERMINAL_OUTPUT_CHARACTER_LIMIT = 50_000
export type TerminalLimitOptions = {
lineLimit?: number
characterLimit?: number
}
export type TerminalOutput = {
content: string
truncated: boolean
}
export function truncateTerminalOutput(content: string, opts: TerminalLimitOptions = {}): TerminalOutput {
const chars = opts.characterLimit ?? TERMINAL_OUTPUT_CHARACTER_LIMIT
if (chars > 0 && content.length > chars) {
const before = Math.floor(chars * 0.2)
const after = chars - before
const omitted = content.length - chars
return {
content: `${content.slice(0, before)}\n[...${omitted} characters omitted...]\n${content.slice(-after)}`,
truncated: true,
}
}
const limit = opts.lineLimit ?? TERMINAL_OUTPUT_LINE_LIMIT
if (limit <= 0) return { content, truncated: false }
const lines = content.split("\n")
if (lines.length <= limit) return { content, truncated: false }
const before = Math.floor(limit * 0.2)
const after = limit - before
const omitted = lines.length - limit
return {
content: `${lines.slice(0, before).join("\n")}\n\n[...${omitted} lines omitted...]\n\n${lines.slice(-after).join("\n")}`,
truncated: true,
}
}
@@ -4,6 +4,7 @@ import {
syncMentionedPaths,
buildTextAfterMentionSelect,
buildFileAttachments,
buildMentionResults,
} from "../../webview-ui/src/hooks/file-mention-utils"
describe("AT_PATTERN", () => {
@@ -29,6 +30,28 @@ describe("AT_PATTERN", () => {
})
})
describe("buildMentionResults", () => {
it("includes terminal for empty mention query", () => {
const result = buildMentionResults("", [])
expect(result[0]).toEqual({
type: "terminal",
value: "terminal",
label: "Terminal",
description: "Active terminal output",
})
})
it("includes terminal for matching prefix", () => {
const result = buildMentionResults("term", ["src/terminal.ts"])
expect(result.map((item) => item.type)).toEqual(["terminal", "file"])
})
it("omits terminal for unrelated query", () => {
const result = buildMentionResults("src", ["src/index.ts"])
expect(result.map((item) => item.type)).toEqual(["file"])
})
})
describe("syncMentionedPaths", () => {
it("keeps paths still referenced in text", () => {
const paths = new Set(["foo.ts", "bar.ts"])
@@ -93,6 +93,70 @@ function createConnection(client: ReturnType<typeof createClient>) {
}
describe("KiloProvider pending session refresh", () => {
it("keeps worktree sessions with legacy project ids", async () => {
const sent: unknown[] = []
const ctx = createContext({
connectionState: "connected",
sessionDirectories: new Map([["ses_worktree", "/worktree"]]),
listSessions: async (dir) => {
if (dir === "/repo") {
return [
{
id: "ses_root",
projectID: "project-new",
title: "root",
directory: "/repo",
time: { created: 1, updated: 1 },
},
] as never
}
return [
{
id: "ses_worktree",
projectID: "project-old",
title: "worktree",
directory: "/worktree",
time: { created: 2, updated: 2 },
},
] as never
},
postMessage: (msg) => sent.push(msg),
})
const project = await loadSessions(ctx)
expect(project).toBe("project-new")
expect(sent).toHaveLength(1)
expect((sent[0] as { sessions: { id: string }[] }).sessions.map((s) => s.id)).toEqual(["ses_root", "ses_worktree"])
})
it("does not use legacy worktree sessions as canonical project", async () => {
const sent: unknown[] = []
const ctx = createContext({
connectionState: "connected",
sessionDirectories: new Map([["ses_worktree", "/worktree"]]),
listSessions: async (dir) => {
if (dir === "/repo") return [] as never
return [
{
id: "ses_worktree",
projectID: "project-old",
title: "worktree",
directory: "/worktree",
time: { created: 2, updated: 2 },
},
] as never
},
postMessage: (msg) => sent.push(msg),
})
const project = await loadSessions(ctx)
expect(project).toBeUndefined()
expect(sent).toHaveLength(1)
expect((sent[0] as { sessions: { id: string }[] }).sessions.map((s) => s.id)).toEqual(["ses_worktree"])
})
it("flushes deferred refresh via flushPendingSessionRefresh", async () => {
const { calls, fn } = createListSessions()
const ctx = createContext()
@@ -0,0 +1,26 @@
import { describe, expect, it } from "bun:test"
import { parseMessageFiles } from "../../src/kilo-provider/message-files"
describe("parseMessageFiles", () => {
it("accepts terminal text attachments with source metadata", () => {
const files = parseMessageFiles([
{
mime: "text/plain",
url: "data:text/plain;charset=utf-8,terminal%20output",
filename: "terminal-output.txt",
source: {
type: "file",
path: "terminal-output.txt",
text: { value: "@terminal", start: 0, end: 9 },
},
},
])
expect(files?.[0]?.filename).toBe("terminal-output.txt")
expect(files?.[0]?.source?.text.value).toBe("@terminal")
})
it("rejects unsupported URLs", () => {
expect(parseMessageFiles([{ mime: "text/plain", url: "https://example.com/file.txt" }])).toBeUndefined()
})
})
@@ -0,0 +1,41 @@
import { describe, expect, it } from "bun:test"
import fs from "node:fs"
import path from "node:path"
const ROOT = path.resolve(import.meta.dir, "../..")
const src = (file: string) => fs.readFileSync(path.join(ROOT, file), "utf-8")
describe("terminal context architecture", () => {
it("keeps VS Code terminal command capture in the terminal service", () => {
const helper = src("src/services/terminal/context.ts")
const provider = src("src/KiloProvider.ts")
const actions = src("src/services/code-actions/register-terminal-actions.ts")
expect(helper).toContain("workbench.action.terminal.selectAll")
expect(provider).not.toContain("workbench.action.terminal.selectAll")
expect(actions).not.toContain("workbench.action.terminal.selectAll")
})
it("keeps webview terminal attachment logic outside PromptInput", () => {
const prompt = src("webview-ui/src/components/chat/PromptInput.tsx")
const hook = src("webview-ui/src/hooks/useTerminalContext.ts")
const util = src("webview-ui/src/hooks/terminal-context-utils.ts")
expect(prompt).toContain("useTerminalContext")
expect(prompt).not.toContain("requestTerminalContext")
expect(prompt).not.toContain("data:text/plain")
expect(hook).toContain("requestTerminalContext")
expect(util).toContain("data:text/plain")
})
it("keeps terminal output limits in the shared truncation helper", () => {
const helper = src("src/services/terminal/truncate.ts")
const provider = src("src/KiloProvider.ts")
const prompt = src("webview-ui/src/components/chat/PromptInput.tsx")
expect(helper).toContain("TERMINAL_OUTPUT_LINE_LIMIT = 500")
expect(helper).toContain("TERMINAL_OUTPUT_CHARACTER_LIMIT = 50_000")
expect(provider).not.toContain("TERMINAL_OUTPUT_LINE_LIMIT")
expect(prompt).not.toContain("TERMINAL_OUTPUT_LINE_LIMIT")
})
})
@@ -0,0 +1,26 @@
import { describe, expect, it } from "bun:test"
import {
buildTerminalAttachment,
findTerminalMention,
hasTerminalMention,
} from "../../webview-ui/src/hooks/terminal-context-utils"
describe("terminal context utils", () => {
it("detects standalone terminal mentions", () => {
expect(hasTerminalMention("see @terminal output")).toBe(true)
expect(hasTerminalMention("see foo@terminal output")).toBe(false)
expect(hasTerminalMention("see @terminal-output")).toBe(false)
})
it("returns mention source range", () => {
expect(findTerminalMention("hello @terminal")!).toEqual({ value: "@terminal", start: 6, end: 15 })
})
it("builds a text attachment with source metadata", () => {
const attachment = buildTerminalAttachment("check @terminal", "npm failed")!
expect(attachment.mime).toBe("text/plain")
expect(attachment.filename).toBe("terminal-output.txt")
expect(attachment.url).toBe("data:text/plain;charset=utf-8,npm%20failed")
expect(attachment.source?.text).toEqual({ value: "@terminal", start: 6, end: 15 })
})
})
@@ -0,0 +1,24 @@
import { describe, expect, it } from "bun:test"
import { truncateTerminalOutput } from "../../src/services/terminal/truncate"
describe("truncateTerminalOutput", () => {
it("returns content within limits", () => {
expect(truncateTerminalOutput("one\ntwo", { lineLimit: 5, characterLimit: 100 })).toEqual({
content: "one\ntwo",
truncated: false,
})
})
it("truncates by character limit first", () => {
const result = truncateTerminalOutput("a".repeat(20), { lineLimit: 1, characterLimit: 10 })
expect(result.truncated).toBe(true)
expect(result.content).toContain("[...10 characters omitted...]")
})
it("truncates by line limit", () => {
const result = truncateTerminalOutput("1\n2\n3\n4\n5", { lineLimit: 3, characterLimit: 100 })
expect(result.truncated).toBe(true)
expect(result.content).toContain("[...2 lines omitted...]")
expect(result.content.endsWith("3\n4\n5")).toBe(true)
})
})
@@ -145,10 +145,14 @@ export const PermissionDock: Component<{
}
}
// Auto-focus the dock when it appears so keyboard shortcuts work immediately
// Keep keyboard shortcuts when the webview already has focus, but do not
// steal focus from the editor, terminal, or other VS Code surfaces.
createEffect(() => {
void props.request.id
requestAnimationFrame(() => root?.focus())
requestAnimationFrame(() => {
if (!document.hasFocus()) return
root?.focus()
})
})
return (
@@ -9,6 +9,8 @@ import { Dialog } from "@kilocode/kilo-ui/dialog"
import { IconButton } from "@kilocode/kilo-ui/icon-button"
import { Tooltip } from "@kilocode/kilo-ui/tooltip"
import { FileIcon } from "@kilocode/kilo-ui/file-icon"
import { Icon } from "@kilocode/kilo-ui/icon"
import { showToast } from "@kilocode/kilo-ui/toast"
import { useDialog } from "@kilocode/kilo-ui/context/dialog"
import { useSession } from "../../context/session"
import { useServer } from "../../context/server"
@@ -19,6 +21,8 @@ import { ModelSelector } from "../shared/ModelSelector"
import { ModeSwitcher } from "../shared/ModeSwitcher"
import { ThinkingSelector } from "../shared/ThinkingSelector"
import { useFileMention } from "../../hooks/useFileMention"
import { useTerminalContext } from "../../hooks/useTerminalContext"
import { hasTerminalMention } from "../../hooks/terminal-context-utils"
import { useSlashCommand } from "../../hooks/useSlashCommand"
import { useGhostText } from "../../hooks/useGhostText"
import { useImageAttachments, type ImageAttachment } from "../../hooks/useImageAttachments"
@@ -58,6 +62,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
const worktree = useWorktreeMode()
const dialog = useDialog()
const mention = useFileMention(vscode)
const terminal = useTerminalContext(vscode)
const excluded = worktree ? new Set(["sessions"]) : undefined
const slash = useSlashCommand(vscode, excluded)
const imageAttach = useImageAttachments()
@@ -266,10 +271,15 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
const isBusy = () => session.status() !== "idle"
const isDisabled = () => !server.isConnected()
const hasInput = () => text().trim().length > 0 || imageAttach.images().length > 0 || reviewComments().length > 0
const canSend = () => hasInput() && !isDisabled() && !props.blocked?.()
const canSend = () => hasInput() && !isDisabled() && !terminal.pending() && !props.blocked?.()
const showStop = () => isBusy() && !hasInput()
const isAtEnd = () =>
textareaRef ? atEnd(textareaRef.selectionStart, textareaRef.selectionEnd, textareaRef.value.length) : false
const highlightMentions = () => {
const paths = new Set(mention.mentionedPaths())
if (hasTerminalMention(text())) paths.add("terminal")
return paths
}
const placeholder = () => {
switch (server.connectionState()) {
case "connecting":
@@ -309,7 +319,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
const merged = mergeReviewComments(reviewComments(), message.comments)
replaceReviewComments(merged)
if (message.autoSend && empty && !isDisabled() && !props.blocked?.()) {
handleSend()
void handleSend()
} else {
textareaRef?.focus()
}
@@ -567,7 +577,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
vscode.postMessage({ type: "enhancePrompt", text: draft, requestId: `enhance-${draftKey()}-${enhanceCounter}` })
}
const handleSend = () => {
const handleSend = async () => {
const draft = text().trim()
// Detect slash command (hoisted for both client and server command checks).
@@ -598,17 +608,24 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
const pending = reviewComments()
const review = pending.length > 0 ? formatReviewCommentsMarkdown(pending) : ""
const message = draft && review ? `${review}\n\n${draft}` : draft || review
if ((!message && imgs.length === 0) || isDisabled() || props.blocked?.()) return
if ((!message && imgs.length === 0) || isDisabled() || terminal.pending() || props.blocked?.()) return
const mentionFiles = mention.parseFileAttachments(draft)
const imgFiles = imgs.map((img) => ({ mime: img.mime, url: img.dataUrl, filename: img.filename }))
const allFiles = [...mentionFiles, ...imgFiles]
const sel = session.selected()
const pendingId = props.pendingSessionID ?? session.draftSessionID()
const sid = session.currentSessionID()
const terminalFile = await terminal.resolveAttachment(message, sid).catch((err: Error) => {
showToast({ variant: "error", title: "Terminal context unavailable", description: err.message })
return undefined
})
if (hasTerminalMention(message) && !terminalFile) return
const allFiles = [...mentionFiles, ...imgFiles, ...(terminalFile ? [terminalFile] : [])]
const attachments = allFiles.length > 0 ? allFiles : undefined
const key = draftKey()
const pendingId = props.pendingSessionID ?? session.draftSessionID()
// Server-side slash command (cmdMatch/matched already computed above)
if (matched) {
const rest = draft.slice(cmdMatch![0].length).trim()
@@ -697,19 +714,29 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
fallback={<div class="file-mention-empty">No files found</div>}
>
<For each={mention.mentionResults()}>
{(path, index) => (
{(item, index) => (
<div
class="file-mention-item"
classList={{ "file-mention-item--active": index() === mention.mentionIndex() }}
onMouseDown={(e) => {
e.preventDefault()
if (textareaRef) mention.selectFile(path, textareaRef, setText, adjustHeight)
if (textareaRef) mention.selectMention(item, textareaRef, setText, adjustHeight)
}}
onMouseEnter={() => mention.setMentionIndex(index())}
>
<FileIcon node={{ path, type: "file" }} class="file-mention-icon" />
<span class="file-mention-name">{fileName(path)}</span>
<span class="file-mention-dir">{dirName(path)}</span>
{item.type === "terminal" ? (
<>
<Icon name="console" class="file-mention-icon" />
<span class="file-mention-name">{item.label}</span>
<span class="file-mention-dir">{item.description}</span>
</>
) : (
<>
<FileIcon node={{ path: item.value, type: "file" }} class="file-mention-icon" />
<span class="file-mention-name">{fileName(item.value)}</span>
<span class="file-mention-dir">{dirName(item.value)}</span>
</>
)}
</div>
)}
</For>
@@ -806,7 +833,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
<div class="prompt-input-wrapper">
<div class="prompt-input-ghost-wrapper">
<div class="prompt-input-highlight-overlay" ref={highlightRef} aria-hidden="true">
<Index each={buildHighlightSegments(text(), mention.mentionedPaths())}>
<Index each={buildHighlightSegments(text(), highlightMentions())}>
{(seg) => (
<Show when={seg().highlight} fallback={<span>{seg().text}</span>}>
<span class="prompt-input-file-mention">{seg().text}</span>
@@ -879,7 +906,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
<Button
variant="ghost"
size="small"
onClick={handleSend}
onClick={() => void handleSend()}
disabled={!canSend()}
aria-label={language.t("prompt.action.send")}
>
@@ -245,11 +245,13 @@ export const QuestionDock: Component<{ request: QuestionRequest }> = (props) =>
}
}
// Auto-focus first option when dock appears, tab changes, or editing ends
// Keep keyboard navigation when the webview already has focus, but do not
// steal focus from the editor, terminal, or other VS Code surfaces.
createEffect(() => {
void store.tab
if (store.collapsed || store.editing || confirm()) return
requestAnimationFrame(() => {
if (!document.hasFocus()) return
const btn = root?.querySelector<HTMLButtonElement>("button[data-slot='question-option']:not(:disabled)")
btn?.focus()
})
@@ -376,7 +378,12 @@ export const QuestionDock: Component<{ request: QuestionRequest }> = (props) =>
<Show when={store.editing}>
<form data-slot="custom-input-form" onSubmit={handleCustomSubmit}>
<input
ref={(el) => setTimeout(() => el.focus(), 0)}
ref={(el) => {
setTimeout(() => {
if (!document.hasFocus()) return
el.focus()
}, 0)
}}
type="text"
data-slot="custom-input"
placeholder={language.t("ui.question.custom.placeholder")}
@@ -1457,6 +1457,7 @@ export const SessionProvider: ParentComponent = (props) => {
mime: file.mime,
url: file.url,
filename: file.filename,
source: file.source,
})
}
@@ -1,7 +1,19 @@
import type { FileAttachment } from "../types/messages"
import { TERMINAL_MENTION } from "./terminal-context-utils"
export const AT_PATTERN = /(?:^|\s)@(\S*)$/
export type MentionResult =
| { type: "terminal"; value: typeof TERMINAL_MENTION; label: string; description: string }
| { type: "file"; value: string }
export const TERMINAL_RESULT: MentionResult = {
type: "terminal",
value: TERMINAL_MENTION,
label: "Terminal",
description: "Active terminal output",
}
/**
* Escape special regex characters in a string so it can be used in a RegExp.
*/
@@ -9,6 +21,16 @@ function escape(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
export function getTerminalMentionResult(query: string): MentionResult[] {
const normalized = query.toLowerCase()
if (!TERMINAL_MENTION.startsWith(normalized)) return []
return [TERMINAL_RESULT]
}
export function buildMentionResults(query: string, paths: string[]): MentionResult[] {
return [...getTerminalMentionResult(query), ...paths.map((path) => ({ type: "file" as const, value: path }))]
}
/**
* Sync the set of mentioned paths against the current text.
* Removes any paths that are no longer present in the text as @path mentions.
@@ -0,0 +1,42 @@
import type { FileAttachment } from "../types/messages"
export const TERMINAL_MENTION = "terminal"
export const TERMINAL_FILENAME = "terminal-output.txt"
export const TERMINAL_PATTERN = /(^|\s)@terminal(?=\s|$)/g
export type TerminalMention = {
value: string
start: number
end: number
}
export function findTerminalMention(text: string): TerminalMention | undefined {
TERMINAL_PATTERN.lastIndex = 0
const match = TERMINAL_PATTERN.exec(text)
if (!match) return undefined
const prefix = match[1] ?? ""
const start = match.index + prefix.length
const value = `@${TERMINAL_MENTION}`
return { value, start, end: start + value.length }
}
export function hasTerminalMention(text: string): boolean {
return findTerminalMention(text) !== undefined
}
export function buildTerminalAttachment(text: string, content: string): FileAttachment | undefined {
const mention = findTerminalMention(text)
if (!mention) return undefined
return {
mime: "text/plain",
url: `data:text/plain;charset=utf-8,${encodeURIComponent(content)}`,
filename: TERMINAL_FILENAME,
source: {
type: "file",
path: TERMINAL_FILENAME,
text: mention,
},
}
}
@@ -6,6 +6,8 @@ import {
syncMentionedPaths as _syncMentionedPaths,
buildTextAfterMentionSelect,
buildFileAttachments,
buildMentionResults,
type MentionResult,
} from "./file-mention-utils"
const FILE_SEARCH_DEBOUNCE_MS = 150
@@ -17,7 +19,7 @@ interface VSCodeContext {
export interface FileMention {
mentionedPaths: Accessor<Set<string>>
mentionResults: Accessor<string[]>
mentionResults: Accessor<MentionResult[]>
mentionIndex: Accessor<number>
showMention: Accessor<boolean>
onInput: (val: string, cursor: number) => void
@@ -27,8 +29,8 @@ export interface FileMention {
setText: (text: string) => void,
onSelect?: () => void,
) => boolean
selectFile: (
path: string,
selectMention: (
result: MentionResult,
textarea: HTMLTextAreaElement,
setText: (text: string) => void,
onSelect?: () => void,
@@ -43,7 +45,7 @@ export interface FileMention {
export function useFileMention(vscode: VSCodeContext): FileMention {
const [mentionedPaths, setMentionedPaths] = createSignal<Set<string>>(new Set())
const [mentionQuery, setMentionQuery] = createSignal<string | null>(null)
const [mentionResults, setMentionResults] = createSignal<string[]>([])
const [mentionResults, setMentionResults] = createSignal<MentionResult[]>([])
const [mentionIndex, setMentionIndex] = createSignal(0)
let workspaceDir = ""
@@ -61,7 +63,7 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
const result = message as { type: "fileSearchResult"; paths: string[]; dir: string; requestId: string }
if (result.requestId === `file-search-${fileSearchCounter}`) {
workspaceDir = result.dir
setMentionResults(result.paths)
setMentionResults(buildMentionResults(mentionQuery() ?? "", result.paths))
setMentionIndex(0)
}
})
@@ -88,8 +90,8 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
setMentionedPaths((prev) => _syncMentionedPaths(prev, text))
}
const selectMentionFile = (
path: string,
const selectMention = (
result: MentionResult,
textarea: HTMLTextAreaElement,
setText: (text: string) => void,
onSelect?: () => void,
@@ -99,16 +101,16 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
const before = val.substring(0, cursor)
const after = val.substring(cursor)
const result = buildTextAfterMentionSelect(before, after, path)
textarea.value = result
setText(result)
const text = buildTextAfterMentionSelect(before, after, result.value)
textarea.value = text
setText(text)
// Position cursor right after the inserted @path
const pos = result.length - after.length
// Position cursor right after the inserted @mention
const pos = text.length - after.length
textarea.setSelectionRange(pos, pos)
textarea.focus()
setMentionedPaths((prev) => new Set([...prev, path]))
if (result.type === "file") setMentionedPaths((prev) => new Set([...prev, result.value]))
closeMention()
onSelect?.()
}
@@ -118,8 +120,10 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
const before = val.substring(0, cursor)
const match = before.match(AT_PATTERN)
if (match) {
setMentionQuery(match[1])
requestFileSearch(match[1])
const query = match[1] ?? ""
setMentionQuery(query)
setMentionResults(buildMentionResults(query, []))
requestFileSearch(query)
} else {
closeMention()
}
@@ -136,7 +140,7 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
if (e.key === "ArrowDown") {
e.preventDefault()
setMentionIndex((i) => Math.min(i + 1, mentionResults().length - 1))
setMentionIndex((i) => Math.min(i + 1, Math.max(mentionResults().length - 1, 0)))
return true
}
if (e.key === "ArrowUp") {
@@ -145,10 +149,10 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
return true
}
if (e.key === "Enter" || e.key === "Tab") {
const path = mentionResults()[mentionIndex()]
if (!path) return false
const result = mentionResults()[mentionIndex()]
if (!result) return false
e.preventDefault()
if (textarea) selectMentionFile(path, textarea, setText, onSelect)
if (textarea) selectMention(result, textarea, setText, onSelect)
return true
}
if (e.key === "Escape") {
@@ -180,7 +184,7 @@ export function useFileMention(vscode: VSCodeContext): FileMention {
showMention,
onInput,
onKeyDown,
selectFile: selectMentionFile,
selectMention,
setMentionIndex,
closeMention,
parseFileAttachments,
@@ -0,0 +1,81 @@
import { createSignal, onCleanup } from "solid-js"
import type { Accessor } from "solid-js"
import type { ExtensionMessage, FileAttachment, WebviewMessage } from "../types/messages"
import { buildTerminalAttachment, hasTerminalMention } from "./terminal-context-utils"
const TERMINAL_CONTEXT_TIMEOUT_MS = 10_000
type Pending = {
resolve: (content: string) => void
reject: (err: Error) => void
timer: ReturnType<typeof setTimeout>
}
interface VSCodeContext {
postMessage: (message: WebviewMessage) => void
onMessage: (handler: (message: ExtensionMessage) => void) => () => void
}
export interface TerminalContext {
pending: Accessor<boolean>
resolveAttachment: (text: string, sessionID?: string) => Promise<FileAttachment | undefined>
}
export function useTerminalContext(vscode: VSCodeContext): TerminalContext {
const [pending, setPending] = createSignal(false)
const requests = new Map<string, Pending>()
let counter = 0
const settle = (requestId: string, run: (req: Pending) => void) => {
const req = requests.get(requestId)
if (!req) return
clearTimeout(req.timer)
requests.delete(requestId)
setPending(requests.size > 0)
run(req)
}
const unsubscribe = vscode.onMessage((message) => {
if (message.type === "terminalContextResult") {
settle(message.requestId, (req) => req.resolve(message.content))
return
}
if (message.type === "terminalContextError") {
settle(message.requestId, (req) => req.reject(new Error(message.error)))
}
})
onCleanup(() => {
unsubscribe()
for (const req of requests.values()) {
clearTimeout(req.timer)
req.reject(new Error("Terminal context request cancelled"))
}
requests.clear()
})
const request = (sessionID?: string) =>
new Promise<string>((resolve, reject) => {
counter++
const requestId = `terminal-context-${counter}`
const timer = setTimeout(() => {
settle(requestId, (req) => req.reject(new Error("Timed out while reading terminal output")))
}, TERMINAL_CONTEXT_TIMEOUT_MS)
requests.set(requestId, { resolve, reject, timer })
setPending(true)
vscode.postMessage({ type: "requestTerminalContext", requestId, sessionID })
})
const resolveAttachment = async (text: string, sessionID?: string) => {
if (!hasTerminalMention(text)) return undefined
const content = await request(sessionID)
if (!content.trim()) throw new Error("No terminal content available")
return buildTerminalAttachment(text, content)
}
return { pending, resolveAttachment }
}
@@ -37,11 +37,22 @@ export interface TextPart extends BasePart {
text: string
}
export interface FilePartSource {
type: "file"
path: string
text: {
value: string
start: number
end: number
}
}
export interface FilePart extends BasePart {
type: "file"
mime: string
url: string
filename?: string
source?: FilePartSource
}
export interface ToolPart extends BasePart {
@@ -739,6 +750,19 @@ export interface FileSearchResultMessage {
requestId: string
}
export interface TerminalContextResultMessage {
type: "terminalContextResult"
requestId: string
content: string
truncated?: boolean
}
export interface TerminalContextErrorMessage {
type: "terminalContextError"
requestId: string
error: string
}
export interface QuestionRequestMessage {
type: "questionRequest"
question: QuestionRequest
@@ -1494,6 +1518,8 @@ export type ExtensionMessage =
| AutocompleteSettingsLoadedMessage
| ChatCompletionResultMessage
| FileSearchResultMessage
| TerminalContextResultMessage
| TerminalContextErrorMessage
| QuestionRequestMessage
| QuestionResolvedMessage
| QuestionErrorMessage
@@ -1578,6 +1604,7 @@ export interface FileAttachment {
mime: string
url: string
filename?: string
source?: FilePartSource
}
export interface SendMessageRequest {
@@ -1854,6 +1881,12 @@ export interface RequestFileSearchMessage {
requestId: string
}
export interface RequestTerminalContextMessage {
type: "requestTerminalContext"
requestId: string
sessionID?: string
}
export interface ChatCompletionAcceptedMessage {
type: "chatCompletionAccepted"
suggestionLength?: number
@@ -2459,6 +2492,7 @@ export type WebviewMessage =
| UpdateAutocompleteSettingMessage
| RequestChatCompletionMessage
| RequestFileSearchMessage
| RequestTerminalContextMessage
| ChatCompletionAcceptedMessage
| UpdateSettingRequest
| RequestTimelineSettingMessage
+14 -12
View File
@@ -55,6 +55,7 @@
"@types/bun": "catalog:",
"@types/cross-spawn": "catalog:",
"@types/mime-types": "3.0.1",
"@types/npm-package-arg": "6.1.4",
"@types/npmcli__arborist": "6.3.3",
"@types/semver": "^7.5.8",
"@types/turndown": "5.0.5",
@@ -94,23 +95,18 @@
"@aws-sdk/credential-providers": "3.1025.0",
"@clack/prompts": "1.0.0-alpha.1",
"@effect/platform-node": "catalog:",
"@gitlab/gitlab-ai-provider": "3.6.0",
"@gitlab/opencode-gitlab-auth": "1.3.3",
"@hono/standard-validator": "0.1.5",
"@hono/zod-validator": "catalog:",
"@kilocode/kilo-gateway": "workspace:*",
"@kilocode/kilo-telemetry": "workspace:*",
"@kilocode/plugin": "workspace:*",
"@kilocode/sdk": "workspace:*",
"@modelcontextprotocol/sdk": "1.29.0",
"@morphllm/morphsdk": "0.2.148",
"@npmcli/arborist": "9.4.0",
"@octokit/graphql": "9.0.2",
"@octokit/rest": "catalog:",
"@openauthjs/openauth": "catalog:",
"@kilocode/plugin": "workspace:*",
"@opencode-ai/script": "workspace:*",
"@kilocode/sdk": "workspace:*",
"@opencode-ai/util": "workspace:*",
"@openrouter/ai-sdk-provider": "2.3.3",
"@openrouter/ai-sdk-provider": "2.5.1",
"@opentui/core": "0.1.96",
"@opentui/solid": "0.1.96",
"@parcel/watcher": "2.5.1",
@@ -141,17 +137,15 @@
"jsonc-parser": "3.3.1",
"mime-types": "3.0.2",
"minimatch": "10.2.5",
"npm-package-arg": "13.0.2",
"open": "10.1.2",
"opencode-gitlab-auth": "2.0.1",
"opencode-poe-auth": "0.0.1",
"opentui-spinner": "0.0.6",
"partial-json": "0.1.7",
"remeda": "catalog:",
"rotating-file-stream": "3.2.9",
"semver": "^7.6.3",
"simple-git": "3.35.2",
"solid-js": "catalog:",
"stream-chat": "9.38.0",
"strip-ansi": "7.1.2",
"tree-sitter-bash": "0.25.0",
"tree-sitter-powershell": "0.25.10",
@@ -164,7 +158,15 @@
"xdg-basedir": "5.1.0",
"yargs": "18.0.0",
"zod": "catalog:",
"zod-to-json-schema": "3.24.5"
"zod-to-json-schema": "3.24.5",
"@gitlab/gitlab-ai-provider": "3.6.0",
"@gitlab/opencode-gitlab-auth": "1.3.3",
"@kilocode/kilo-gateway": "workspace:*",
"@kilocode/kilo-telemetry": "workspace:*",
"@morphllm/morphsdk": "0.2.148",
"rotating-file-stream": "3.2.9",
"simple-git": "3.35.2",
"stream-chat": "9.38.0"
},
"overrides": {
"drizzle-orm": "catalog:"
+1
View File
@@ -217,6 +217,7 @@ for (const item of targets) {
conditions: ["browser"],
tsconfig: "./tsconfig.json",
plugins: [plugin],
external: ["node-gyp"],
compile: {
autoloadBunfig: false,
autoloadDotenv: false,
+17 -1
View File
@@ -235,11 +235,27 @@ Once individual tools are effectified, change `Tool.Info` (`tool/tool.ts`) so `i
2. Update `Tool.define()` factory to work with Effects
3. Update `SessionPrompt` to `yield*` tool results instead of `await`ing
### Tool migration details
Until the tool interface itself returns `Effect`, use this transitional pattern for migrated tools:
- `Tool.defineEffect(...)` should `yield*` the services the tool depends on and close over them in the returned tool definition.
- Keep the bridge at the Promise boundary only. Prefer a single `Effect.runPromise(...)` in the temporary `async execute(...)` implementation, and move the inner logic into `Effect.fn(...)` helpers instead of scattering `runPromise` islands through the tool body.
- If a tool starts requiring new services, wire them into `ToolRegistry.defaultLayer` so production callers resolve the same dependencies as tests.
Tool tests should use the existing Effect helpers in `packages/opencode/test/lib/effect.ts`:
- Use `testEffect(...)` / `it.live(...)` instead of creating fake local wrappers around effectful tools.
- Yield the real tool export, then initialize it: `const info = yield* ReadTool`, `const tool = yield* Effect.promise(() => info.init())`.
- Run tests inside a real instance with `provideTmpdirInstance(...)` or `provideInstance(tmpdirScoped(...))` so instance-scoped services resolve exactly as they do in production.
This keeps migrated tool tests aligned with the production service graph today, and makes the eventual `Tool.Info` → `Effect` cleanup mostly mechanical later.
Individual tools, ordered by value:
- [ ] `apply_patch.ts` — HIGH: multi-step orchestration, error accumulation, Bus events
- [ ] `bash.ts` — HIGH: shell orchestration, quoting, timeout handling, output capture
- [ ] `read.ts` — HIGH: streaming I/O, readline, binary detection → FileSystem + Stream
- [x] `read.ts` — HIGH: streaming I/O, readline, binary detection → FileSystem + Stream
- [ ] `edit.ts` — HIGH: multi-step diff/format/publish pipeline, FileWatcher lock
- [ ] `grep.ts` — MEDIUM: spawns ripgrep → ChildProcessSpawner, timeout handling
- [ ] `write.ts` — MEDIUM: permission checks, diagnostics polling, Bus events
+47 -8
View File
@@ -52,6 +52,11 @@ export type AccountOrgs = {
orgs: readonly Org[]
}
export type ActiveOrg = {
account: Info
org: Org
}
class RemoteConfig extends Schema.Class<RemoteConfig>("RemoteConfig")({
config: Schema.Record(Schema.String, Schema.Json),
}) {}
@@ -137,6 +142,7 @@ const mapAccountServiceError =
export namespace Account {
export interface Interface {
readonly active: () => Effect.Effect<Option.Option<Info>, AccountError>
readonly activeOrg: () => Effect.Effect<Option.Option<ActiveOrg>, AccountError>
readonly list: () => Effect.Effect<Info[], AccountError>
readonly orgsByAccount: () => Effect.Effect<readonly AccountOrgs[], AccountError>
readonly remove: (accountID: AccountID) => Effect.Effect<void, AccountError>
@@ -279,19 +285,31 @@ export namespace Account {
resolveAccess(accountID).pipe(Effect.map(Option.map((r) => r.accessToken))),
)
const activeOrg = Effect.fn("Account.activeOrg")(function* () {
const activeAccount = yield* repo.active()
if (Option.isNone(activeAccount)) return Option.none<ActiveOrg>()
const account = activeAccount.value
if (!account.active_org_id) return Option.none<ActiveOrg>()
const accountOrgs = yield* orgs(account.id)
const org = accountOrgs.find((item) => item.id === account.active_org_id)
if (!org) return Option.none<ActiveOrg>()
return Option.some({ account, org })
})
const orgsByAccount = Effect.fn("Account.orgsByAccount")(function* () {
const accounts = yield* repo.list()
const [errors, results] = yield* Effect.partition(
return yield* Effect.forEach(
accounts,
(account) => orgs(account.id).pipe(Effect.map((orgs) => ({ account, orgs }))),
(account) =>
orgs(account.id).pipe(
Effect.catch(() => Effect.succeed([] as readonly Org[])),
Effect.map((orgs) => ({ account, orgs })),
),
{ concurrency: 3 },
)
for (const error of errors) {
yield* Effect.logWarning("failed to fetch orgs for account").pipe(
Effect.annotateLogs({ error: String(error) }),
)
}
return results
})
const orgs = Effect.fn("Account.orgs")(function* (accountID: AccountID) {
@@ -396,6 +414,7 @@ export namespace Account {
return Service.of({
active: repo.active,
activeOrg,
list: repo.list,
orgsByAccount,
remove: repo.remove,
@@ -417,6 +436,26 @@ export namespace Account {
return Option.getOrUndefined(await runPromise((service) => service.active()))
}
export async function list(): Promise<Info[]> {
return runPromise((service) => service.list())
}
export async function activeOrg(): Promise<ActiveOrg | undefined> {
return Option.getOrUndefined(await runPromise((service) => service.activeOrg()))
}
export async function orgsByAccount(): Promise<readonly AccountOrgs[]> {
return runPromise((service) => service.orgsByAccount())
}
export async function orgs(accountID: AccountID): Promise<readonly Org[]> {
return runPromise((service) => service.orgs(accountID))
}
export async function switchOrg(accountID: AccountID, orgID: OrgID) {
return runPromise((service) => service.use(accountID, Option.some(orgID)))
}
export async function token(accountID: AccountID): Promise<AccessToken | undefined> {
const t = await runPromise((service) => service.token(accountID))
return Option.getOrUndefined(t)
+84
View File
@@ -21,6 +21,9 @@ import {
type Role,
type SessionInfo,
type SetSessionModelRequest,
type SessionConfigOption,
type SetSessionConfigOptionRequest,
type SetSessionConfigOptionResponse,
type SetSessionModeRequest,
type SetSessionModeResponse,
type ToolCallContent,
@@ -605,6 +608,7 @@ export namespace ACP {
return {
sessionId,
configOptions: load.configOptions,
models: load.models,
modes: load.modes,
_meta: load._meta,
@@ -664,6 +668,11 @@ export namespace ACP {
result.modes.currentModeId = lastUser.agent
this.sessionManager.setMode(sessionId, lastUser.agent)
}
result.configOptions = buildConfigOptions({
currentModelId: result.models.currentModelId,
availableModels: result.models.availableModels,
modes: result.modes,
})
}
for (const msg of messages ?? []) {
@@ -1270,6 +1279,11 @@ export namespace ACP {
availableModels,
},
modes,
configOptions: buildConfigOptions({
currentModelId: formatModelIdWithVariant(model, currentVariant, availableVariants, true),
availableModels,
modes,
}),
_meta: buildVariantMeta({
model,
variant: this.sessionManager.getVariant(sessionId),
@@ -1309,6 +1323,44 @@ export namespace ACP {
this.sessionManager.setMode(params.sessionId, params.modeId)
}
async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse> {
const session = this.sessionManager.get(params.sessionId)
const providers = await this.sdk.config
.providers({ directory: session.cwd }, { throwOnError: true })
.then((x) => x.data!.providers)
const entries = sortProvidersByName(providers)
if (params.configId === "model") {
if (typeof params.value !== "string") throw RequestError.invalidParams("model value must be a string")
const selection = parseModelSelection(params.value, providers)
this.sessionManager.setModel(session.id, selection.model)
this.sessionManager.setVariant(session.id, selection.variant)
} else if (params.configId === "mode") {
if (typeof params.value !== "string") throw RequestError.invalidParams("mode value must be a string")
const availableModes = await this.loadAvailableModes(session.cwd)
if (!availableModes.some((mode) => mode.id === params.value)) {
throw RequestError.invalidParams(JSON.stringify({ error: `Mode not found: ${params.value}` }))
}
this.sessionManager.setMode(session.id, params.value)
} else {
throw RequestError.invalidParams(JSON.stringify({ error: `Unknown config option: ${params.configId}` }))
}
const updatedSession = this.sessionManager.get(session.id)
const model = updatedSession.model ?? (await defaultModel(this.config, session.cwd))
const availableVariants = modelVariantsFromProviders(entries, model)
const currentModelId = formatModelIdWithVariant(model, updatedSession.variant, availableVariants, true)
const availableModels = buildAvailableModels(entries, { includeVariants: true })
const modeState = await this.resolveModeState(session.cwd, session.id)
const modes = modeState.currentModeId
? { availableModes: modeState.availableModes, currentModeId: modeState.currentModeId }
: undefined
return {
configOptions: buildConfigOptions({ currentModelId, availableModels, modes }),
}
}
async prompt(params: PromptRequest) {
const sessionID = params.sessionId
const session = this.sessionManager.get(sessionID)
@@ -1774,4 +1826,36 @@ export namespace ACP {
return { model: parsed, variant: undefined }
}
function buildConfigOptions(input: {
currentModelId: string
availableModels: ModelOption[]
modes?: { availableModes: ModeOption[]; currentModeId: string } | undefined
}): SessionConfigOption[] {
const options: SessionConfigOption[] = [
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: input.currentModelId,
options: input.availableModels.map((m) => ({ value: m.modelId, name: m.name })),
},
]
if (input.modes) {
options.push({
id: "mode",
name: "Session Mode",
category: "mode",
type: "select",
currentValue: input.modes.currentModeId,
options: input.modes.availableModes.map((m) => ({
value: m.id,
name: m.name,
...(m.description ? { description: m.description } : {}),
})),
})
}
return options
}
}
+1
View File
@@ -25,6 +25,7 @@ export namespace Auth {
export class Api extends Schema.Class<Api>("ApiAuth")({
type: Schema.Literal("api"),
key: Schema.String,
metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
}) {}
export class WellKnown extends Schema.Class<WellKnown>("WellKnownAuth")({
+87 -89
View File
@@ -224,95 +224,93 @@ export const RunCommand = cmd({
command: "run [message..]",
describe: "run kilo with a message", // kilocode_change
builder: (yargs: Argv) => {
return (
yargs
.positional("message", {
describe: "message to send",
type: "string",
array: true,
default: [],
})
.option("command", {
describe: "the command to run, use message for args",
type: "string",
})
.option("continue", {
alias: ["c"],
describe: "continue the last session",
type: "boolean",
})
.option("session", {
alias: ["s"],
describe: "session id to continue",
type: "string",
})
.option("fork", {
describe: "fork the session before continuing (requires --continue or --session)",
type: "boolean",
})
.option("share", {
type: "boolean",
describe: "share the session",
})
.option("model", {
type: "string",
alias: ["m"],
describe: "model to use in the format of provider/model",
})
.option("agent", {
type: "string",
describe: "agent to use",
})
.option("format", {
type: "string",
choices: ["default", "json"],
default: "default",
describe: "format: default (formatted) or json (raw JSON events)",
})
.option("file", {
alias: ["f"],
type: "string",
array: true,
describe: "file(s) to attach to message",
})
.option("title", {
type: "string",
describe: "title for the session (uses truncated prompt if no value provided)",
})
.option("attach", {
type: "string",
describe: "attach to a running opencode server (e.g., http://localhost:4096)",
})
.option("password", {
alias: ["p"],
type: "string",
describe: "basic auth password (defaults to KILO_SERVER_PASSWORD)",
})
.option("dir", {
type: "string",
describe: "directory to run in, path on remote server if attaching",
})
.option("port", {
type: "number",
describe: "port for the local server (defaults to random port if no value provided)",
})
.option("variant", {
type: "string",
describe: "model variant (provider-specific reasoning effort, e.g., high, max, minimal)",
})
// kilocode_change start - auto approve all permissions
.option("auto", {
type: "boolean",
describe: "auto-approve all permissions (for autonomous/pipeline usage)",
default: false,
})
// kilocode_change end
.option("thinking", {
type: "boolean",
describe: "show thinking blocks",
default: false,
})
)
return yargs
.positional("message", {
describe: "message to send",
type: "string",
array: true,
default: [],
})
.option("command", {
describe: "the command to run, use message for args",
type: "string",
})
.option("continue", {
alias: ["c"],
describe: "continue the last session",
type: "boolean",
})
.option("session", {
alias: ["s"],
describe: "session id to continue",
type: "string",
})
.option("fork", {
describe: "fork the session before continuing (requires --continue or --session)",
type: "boolean",
})
.option("share", {
type: "boolean",
describe: "share the session",
})
.option("model", {
type: "string",
alias: ["m"],
describe: "model to use in the format of provider/model",
})
.option("agent", {
type: "string",
describe: "agent to use",
})
.option("format", {
type: "string",
choices: ["default", "json"],
default: "default",
describe: "format: default (formatted) or json (raw JSON events)",
})
.option("file", {
alias: ["f"],
type: "string",
array: true,
describe: "file(s) to attach to message",
})
.option("title", {
type: "string",
describe: "title for the session (uses truncated prompt if no value provided)",
})
.option("attach", {
type: "string",
describe: "attach to a running opencode server (e.g., http://localhost:4096)",
})
.option("password", {
alias: ["p"],
type: "string",
describe: "basic auth password (defaults to KILO_SERVER_PASSWORD)",
})
.option("dir", {
type: "string",
describe: "directory to run in, path on remote server if attaching",
})
.option("port", {
type: "number",
describe: "port for the local server (defaults to random port if no value provided)",
})
.option("variant", {
type: "string",
describe: "model variant (provider-specific reasoning effort, e.g., high, max, minimal)",
})
// kilocode_change start - auto approve all permissions
.option("auto", {
type: "boolean",
describe: "auto-approve all permissions (for autonomous/pipeline usage)",
default: false,
})
// kilocode_change end
.option("thinking", {
type: "boolean",
describe: "show thinking blocks",
default: false,
})
},
handler: async (args) => {
let message = [...args.message, ...(args["--"] || [])]
+23 -1
View File
@@ -36,6 +36,7 @@ import { CommandProvider, useCommandDialog } from "@tui/component/dialog-command
import { DialogAgent } from "@tui/component/dialog-agent"
import { DialogSessionList } from "@tui/component/dialog-session-list"
import { DialogWorkspaceList } from "@tui/component/dialog-workspace-list"
import { DialogConsoleOrg } from "@tui/component/dialog-console-org"
import { KeybindProvider, useKeybind } from "@tui/context/keybind"
import { ThemeProvider, useTheme } from "@tui/context/theme"
import { Home } from "@tui/routes/home"
@@ -127,14 +128,17 @@ import type { EventSource } from "./context/sdk"
import { DialogVariant } from "./component/dialog-variant"
function rendererConfig(_config: TuiConfig.Info): CliRendererConfig {
const mouseEnabled = !Flag.KILO_DISABLE_MOUSE && (_config.mouse ?? true)
return {
externalOutputMode: "passthrough",
targetFps: 60,
gatherStats: false,
exitOnCtrlC: false,
useKittyKeyboard: { events: process.platform === "win32" },
useKittyKeyboard: {},
autoFocus: false,
openConsoleOnError: false,
useMouse: mouseEnabled,
consoleOptions: {
keyBindings: [{ name: "y", ctrl: true, action: "copy-selection" }],
onCopySelection: (text) => {
@@ -641,6 +645,23 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
},
category: "Provider",
},
...(sync.data.console_state.switchableOrgCount > 1
? [
{
title: "Switch org",
value: "console.org.switch",
suggested: Boolean(sync.data.console_state.activeOrgName),
slash: {
name: "org",
aliases: ["orgs", "switch-org"],
},
onSelect: () => {
dialog.replace(() => <DialogConsoleOrg />)
},
category: "Provider",
},
]
: []),
{
title: "View status",
keybind: "status_view",
@@ -752,6 +773,7 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
keybind: "terminal_suspend",
category: "System",
hidden: true,
enabled: tuiConfig.keybinds?.terminal_suspend !== "none",
onSelect: () => {
process.once("SIGCONT", () => {
renderer.resume()
@@ -0,0 +1,103 @@
import { createResource, createMemo } from "solid-js"
import { DialogSelect } from "@tui/ui/dialog-select"
import { useSDK } from "@tui/context/sdk"
import { useDialog } from "@tui/ui/dialog"
import { useToast } from "@tui/ui/toast"
import { useTheme } from "@tui/context/theme"
import type { ExperimentalConsoleListOrgsResponse } from "@kilocode/sdk/v2"
type OrgOption = ExperimentalConsoleListOrgsResponse["orgs"][number]
const accountHost = (url: string) => {
try {
return new URL(url).host
} catch {
return url
}
}
const accountLabel = (item: Pick<OrgOption, "accountEmail" | "accountUrl">) =>
`${item.accountEmail} ${accountHost(item.accountUrl)}`
export function DialogConsoleOrg() {
const sdk = useSDK()
const dialog = useDialog()
const toast = useToast()
const { theme } = useTheme()
const [orgs] = createResource(async () => {
const result = await sdk.client.experimental.console.listOrgs({}, { throwOnError: true })
return result.data?.orgs ?? []
})
const current = createMemo(() => orgs()?.find((item) => item.active))
const options = createMemo(() => {
const listed = orgs()
if (listed === undefined) {
return [
{
title: "Loading orgs...",
value: "loading",
onSelect: () => {},
},
]
}
if (listed.length === 0) {
return [
{
title: "No orgs found",
value: "empty",
onSelect: () => {},
},
]
}
return listed
.toSorted((a, b) => {
const activeAccountA = a.active ? 0 : 1
const activeAccountB = b.active ? 0 : 1
if (activeAccountA !== activeAccountB) return activeAccountA - activeAccountB
const accountCompare = accountLabel(a).localeCompare(accountLabel(b))
if (accountCompare !== 0) return accountCompare
return a.orgName.localeCompare(b.orgName)
})
.map((item) => ({
title: item.orgName,
value: item,
category: accountLabel(item),
categoryView: (
<box flexDirection="row" gap={2}>
<text fg={theme.accent}>{item.accountEmail}</text>
<text fg={theme.textMuted}>{accountHost(item.accountUrl)}</text>
</box>
),
onSelect: async () => {
if (item.active) {
dialog.clear()
return
}
await sdk.client.experimental.console.switchOrg(
{
accountID: item.accountID,
orgID: item.orgID,
},
{ throwOnError: true },
)
await sdk.client.instance.dispose()
toast.show({
message: `Switched to ${item.orgName}`,
variant: "info",
})
dialog.clear()
},
}))
})
return <DialogSelect<string | OrgOption> title="Switch org" options={options()} current={current()} />
}
@@ -8,6 +8,7 @@ import { createDialogProviderOptions, DialogProvider } from "./dialog-provider"
import { DialogVariant } from "./dialog-variant"
import { useKeybind } from "../context/keybind"
import * as fuzzysort from "fuzzysort"
import { consoleManagedProviderLabel } from "@tui/util/provider-origin"
export function useConnected() {
const sync = useSync()
@@ -58,7 +59,11 @@ export function DialogModel(props: { providerID?: string }) {
key: item,
value: { providerID: provider.id, modelID: model.id },
title: model.name ?? item.modelID,
description: provider.name,
description: consoleManagedProviderLabel(
sync.data.console_state.consoleManagedProviders,
provider.id,
provider.name,
),
category,
disabled: provider.id === "opencode" && model.id.includes("-nano"),
footer: model.cost?.input === 0 && provider.id === "opencode" ? "Free" : undefined,
@@ -100,7 +105,11 @@ export function DialogModel(props: { providerID?: string }) {
category: connected()
? provider.id === "kilo" && info.recommendedIndex !== undefined
? "Recommended"
: provider.name
: consoleManagedProviderLabel(
sync.data.console_state.consoleManagedProviders,
provider.id,
provider.name,
)
: undefined,
// kilocode_change end
disabled: provider.id === "opencode" && model.includes("-nano"),
@@ -156,7 +165,11 @@ export function DialogModel(props: { providerID?: string }) {
props.providerID ? sync.data.provider.find((x) => x.id === props.providerID) : null,
)
const title = createMemo(() => provider()?.name ?? "Select model")
const title = createMemo(() => {
const value = provider()
if (!value) return "Select model"
return consoleManagedProviderLabel(sync.data.console_state.consoleManagedProviders, value.id, value.name)
})
function onSelect(providerID: string, modelID: string) {
local.model.set({ providerID, modelID }, { recent: true })
@@ -13,109 +13,92 @@ import { DialogModel } from "./dialog-model"
import { useKeyboard } from "@opentui/solid"
import { Clipboard } from "@tui/util/clipboard"
import { useToast } from "../ui/toast"
import { KiloAutoMethod } from "@/kilocode/components/dialog-kilo-auto-method" // kilocode_change
import { CONSOLE_MANAGED_ICON, isConsoleManagedProvider } from "@tui/util/provider-origin"
import * as KiloProvider from "@/kilocode/cli/cmd/tui/component/dialog-provider" // kilocode_change
const PROVIDER_PRIORITY: Record<string, number> = {
kilo: -1, // kilocode_change - Kilo Gateway at top
// kilocode_change - removed opencode from popular providers
anthropic: 0,
"github-copilot": 1,
openai: 2,
google: 3,
}
const PROVIDER_PRIORITY: Record<string, number> = KiloProvider.PROVIDER_PRIORITY // kilocode_change
export function createDialogProviderOptions() {
const sync = useSync()
const dialog = useDialog()
const sdk = useSDK()
const toast = useToast()
const { theme } = useTheme()
const options = createMemo(() => {
return pipe(
sync.data.provider_next.all,
sortBy((x) => PROVIDER_PRIORITY[x.id] ?? 99),
map((provider) => ({
title: provider.name,
value: provider.id,
description: {
kilo: "(Recommended)", // kilocode_change
anthropic: "(Claude Max or API key)",
openai: "(ChatGPT Plus/Pro or API key)",
// "opencode-go": "(Low cost)", // kilocode_change
}[provider.id],
category: provider.id in PROVIDER_PRIORITY ? "Popular" : "Other",
async onSelect() {
const methods = sync.data.provider_auth[provider.id] ?? [
{
type: "api",
label: "API key",
},
]
let index: number | null = 0
if (methods.length > 1) {
index = await new Promise<number | null>((resolve) => {
dialog.replace(
() => (
<DialogSelect
title="Select auth method"
options={methods.map((x, index) => ({
title: x.label,
value: index,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
}
if (index == null) return
const method = methods[index]
if (method.type === "oauth") {
let inputs: Record<string, string> | undefined
if (method.prompts?.length) {
const value = await PromptsMethod({
dialog,
prompts: method.prompts,
})
if (!value) return
inputs = value
}
map((provider) => {
const consoleManaged = isConsoleManagedProvider(sync.data.console_state.consoleManagedProviders, provider.id)
const connected = sync.data.provider_next.connected.includes(provider.id)
const result = await sdk.client.provider.oauth.authorize({
providerID: provider.id,
method: index,
inputs,
})
if (result.error) {
toast.show({
variant: "error",
message: JSON.stringify(result.error),
return {
title: provider.name,
value: provider.id,
description: KiloProvider.PROVIDER_DESCRIPTIONS[provider.id], // kilocode_change
footer: consoleManaged ? sync.data.console_state.activeOrgName : undefined,
category: provider.id in PROVIDER_PRIORITY ? "Popular" : "Other",
gutter: consoleManaged ? (
<text fg={theme.textMuted}>{CONSOLE_MANAGED_ICON}</text>
) : connected ? (
<text fg={theme.success}>✓</text>
) : undefined,
async onSelect() {
if (consoleManaged) return
const methods = sync.data.provider_auth[provider.id] ?? [
{
type: "api",
label: "API key",
},
]
let index: number | null = 0
if (methods.length > 1) {
index = await new Promise<number | null>((resolve) => {
dialog.replace(
() => (
<DialogSelect
title="Select auth method"
options={methods.map((x, index) => ({
title: x.label,
value: index,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
dialog.clear()
return
}
if (result.data?.method === "code") {
dialog.replace(() => (
<CodeMethod providerID={provider.id} title={method.label} index={index} authorization={result.data!} />
))
}
if (result.data?.method === "auto") {
// kilocode_change start - Use custom handler for Kilo Gateway
if (provider.id === "kilo") {
if (index == null) return
const method = methods[index]
if (method.type === "oauth") {
let inputs: Record<string, string> | undefined
if (method.prompts?.length) {
const value = await PromptsMethod({
dialog,
prompts: method.prompts,
})
if (!value) return
inputs = value
}
const result = await sdk.client.provider.oauth.authorize({
providerID: provider.id,
method: index,
inputs,
})
if (result.error) {
toast.show({
variant: "error",
message: JSON.stringify(result.error),
})
dialog.clear()
return
}
if (result.data?.method === "code") {
dialog.replace(() => (
<KiloAutoMethod
providerID={provider.id}
title={method.label}
index={index}
authorization={result.data!}
useSDK={useSDK}
useTheme={useTheme}
DialogModel={DialogModel}
/>
))
} else {
dialog.replace(() => (
<AutoMethod
<CodeMethod
providerID={provider.id}
title={method.label}
index={index}
@@ -123,14 +106,46 @@ export function createDialogProviderOptions() {
/>
))
}
// kilocode_change end
if (result.data?.method === "auto") {
// kilocode_change start
const kilo = KiloProvider.renderAutoMethod({
providerID: provider.id,
title: method.label,
index,
authorization: result.data!,
useSDK,
useTheme,
DialogModel,
})
if (kilo) {
dialog.replace(kilo)
} else {
// kilocode_change end
dialog.replace(() => (
<AutoMethod
providerID={provider.id}
title={method.label}
index={index}
authorization={result.data!}
/>
))
} // kilocode_change
}
}
}
if (method.type === "api") {
return dialog.replace(() => <ApiMethod providerID={provider.id} title={method.label} />)
}
},
})),
if (method.type === "api") {
let metadata: Record<string, string> | undefined
if (method.prompts?.length) {
const value = await PromptsMethod({ dialog, prompts: method.prompts })
if (!value) return
metadata = value
}
return dialog.replace(() => (
<ApiMethod providerID={provider.id} title={method.label} metadata={metadata} />
))
}
},
}
}),
)
})
return options
@@ -246,6 +261,7 @@ function CodeMethod(props: CodeMethodProps) {
interface ApiMethodProps {
providerID: string
title: string
metadata?: Record<string, string>
}
function ApiMethod(props: ApiMethodProps) {
const dialog = useDialog()
@@ -257,23 +273,7 @@ function ApiMethod(props: ApiMethodProps) {
<DialogPrompt
title={props.title}
placeholder="API key"
description={
{
kilo: (
<box gap={1}>
{/* kilocode_change start */}
<text fg={theme.textMuted}>
Kilo Gateway gives you access to all the best coding models at the cheapest prices with a single API
key.
</text>
<text fg={theme.text}>
Go to <span style={{ fg: theme.primary }}>https://kilo.ai/gateway</span> to get a key
</text>
{/* kilocode_change end */}
</box>
),
}[props.providerID] ?? undefined
}
description={KiloProvider.renderApiDescription(props.providerID, theme)} // kilocode_change
onConfirm={async (value) => {
if (!value) return
await sdk.client.auth.set({
@@ -281,6 +281,7 @@ function ApiMethod(props: ApiMethodProps) {
auth: {
type: "api",
key: value,
...(props.metadata ? { metadata: props.metadata } : {}),
},
})
await sdk.client.instance.dispose()
@@ -18,7 +18,7 @@ import { usePromptStash } from "./stash"
import { DialogStash } from "../dialog-stash"
import { type AutocompleteRef, Autocomplete } from "./autocomplete"
import { useCommandDialog } from "../dialog-command"
import { useKeyboard, useRenderer, type JSX } from "@opentui/solid"
import { useRenderer, type JSX } from "@opentui/solid"
import { Editor } from "@tui/util/editor"
import { useExit } from "../../context/exit"
import { Clipboard } from "../../util/clipboard"
@@ -36,6 +36,7 @@ import { useKV } from "../../context/kv"
import { useTextareaKeybindings } from "../textarea-keybindings"
import { DialogSkill } from "../dialog-skill"
import { shouldSummarize as shouldPasteSummary } from "@/kilocode/paste-summary"
import { CONSOLE_MANAGED_ICON, consoleManagedProviderLabel } from "@tui/util/provider-origin"
export type PromptProps = {
sessionID?: string
@@ -95,6 +96,15 @@ export function Prompt(props: PromptProps) {
const list = createMemo(() => props.placeholders?.normal ?? [])
const shell = createMemo(() => props.placeholders?.shell ?? [])
const [auto, setAuto] = createSignal<AutocompleteRef>()
const activeOrgName = createMemo(() => sync.data.console_state.activeOrgName)
const canSwitchOrgs = createMemo(() => sync.data.console_state.switchableOrgCount > 1)
const currentProviderLabel = createMemo(() => {
const current = local.model.current()
const provider = local.model.parsed().provider
if (!current) return provider
return consoleManagedProviderLabel(sync.data.console_state.consoleManagedProviders, current.providerID, provider)
})
const hasRightContent = createMemo(() => Boolean(props.right || activeOrgName()))
function promptModelWarning() {
toast.show({
@@ -391,20 +401,6 @@ export function Prompt(props: PromptProps) {
]
})
// Windows Terminal 1.25+ handles Ctrl+V on keydown when kitty events are
// enabled, but still reports the kitty key-release event. Probe on release.
if (process.platform === "win32") {
useKeyboard(
(evt) => {
if (!input.focused) return
if (evt.name === "v" && evt.ctrl && evt.eventType === "release") {
command.trigger("prompt.paste")
}
},
{ release: true },
)
}
const ref: PromptRef = {
get focused() {
return input.focused
@@ -1120,7 +1116,7 @@ export function Prompt(props: PromptProps) {
<text flexShrink={0} fg={keybind.leader ? theme.textMuted : theme.text}>
{local.model.parsed().model}
</text>
<text fg={theme.textMuted}>{local.model.parsed().provider}</text>
<text fg={theme.textMuted}>{currentProviderLabel()}</text>
<Show when={showVariant()}>
<text fg={theme.textMuted}>·</text>
<text>
@@ -1130,7 +1126,22 @@ export function Prompt(props: PromptProps) {
</box>
</Show>
</box>
{props.right}
<Show when={hasRightContent()}>
<box flexDirection="row" gap={1} alignItems="center">
{props.right}
<Show when={activeOrgName()}>
<text
fg={theme.textMuted}
onMouseUp={() => {
if (!canSwitchOrgs()) return
command.trigger("console.org.switch")
}}
>
{`${CONSOLE_MANAGED_ICON} ${activeOrgName()}`}
</text>
</Show>
</box>
</Show>
</box>
</box>
</box>
@@ -33,6 +33,7 @@ import { Log } from "@/util/log"
import { useToast } from "@tui/ui/toast" // kilocode_change
import type { Path } from "@kilocode/sdk"
import type { Workspace } from "@kilocode/sdk/v2"
import { ConsoleState, emptyConsoleState, type ConsoleState as ConsoleStateType } from "@/config/console-state"
export const { use: useSync, provider: SyncProvider } = createSimpleContext({
name: "Sync",
@@ -42,6 +43,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
provider: Provider[]
provider_default: Record<string, string>
provider_next: ProviderListResponse
console_state: ConsoleStateType
provider_auth: Record<string, ProviderAuthMethod[]>
agent: Agent[]
command: Command[]
@@ -93,6 +95,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
default: {},
connected: [],
},
console_state: emptyConsoleState,
provider_auth: {},
config: {},
status: "loading",
@@ -494,6 +497,10 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
// blocking - include session.list when continuing a session
const providersPromise = sdk.client.config.providers({}, { throwOnError: true })
const providerListPromise = sdk.client.provider.list({}, { throwOnError: true })
const consoleStatePromise = sdk.client.experimental.console
.get({}, { throwOnError: true })
.then((x) => ConsoleState.parse(x.data))
.catch(() => emptyConsoleState)
const agentsPromise = sdk.client.app.agents({}, { throwOnError: true })
const configPromise = sdk.client.config.get({}, { throwOnError: true })
const blockingRequests: Promise<unknown>[] = [
@@ -508,6 +515,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
.then(() => {
const providersResponse = providersPromise.then((x) => x.data!)
const providerListResponse = providerListPromise.then((x) => x.data!)
const consoleStateResponse = consoleStatePromise
const agentsResponse = agentsPromise.then((x) => x.data ?? [])
const configResponse = configPromise.then((x) => x.data!)
const sessionListResponse = args.continue ? sessionListPromise : undefined
@@ -515,20 +523,23 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
return Promise.all([
providersResponse,
providerListResponse,
consoleStateResponse,
agentsResponse,
configResponse,
...(sessionListResponse ? [sessionListResponse] : []),
]).then((responses) => {
const providers = responses[0]
const providerList = responses[1]
const agents = responses[2]
const config = responses[3]
const sessions = responses[4]
const consoleState = responses[2]
const agents = responses[3]
const config = responses[4]
const sessions = responses[5]
batch(() => {
setStore("provider", reconcile(providers.providers))
setStore("provider_default", reconcile(providers.default))
setStore("provider_next", reconcile(providerList))
setStore("console_state", reconcile(consoleState))
setStore("agent", reconcile(agents))
setStore("config", reconcile(config))
if (sessions !== undefined) setStore("session", reconcile(sessions))
@@ -540,6 +551,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
// non-blocking
Promise.all([
...(args.continue ? [] : [sessionListPromise.then((sessions) => setStore("session", reconcile(sessions)))]),
consoleStatePromise.then((consoleState) => setStore("console_state", reconcile(consoleState))),
sdk.client.command.list().then((x) => setStore("command", reconcile(x.data ?? []))),
sdk.client.lsp.status().then((x) => setStore("lsp", reconcile(x.data!))),
sdk.client.mcp.status().then((x) => setStore("mcp", reconcile(x.data!))),
@@ -152,5 +152,7 @@ const TIPS = [
"Use {highlight}/review{/highlight} to review uncommitted changes, branches, or PRs",
"Run {highlight}/help{/highlight} or {highlight}Ctrl+X H{/highlight} to show the help dialog",
"Use {highlight}/rename{/highlight} to rename the current session",
"Press {highlight}Ctrl+Z{/highlight} to suspend the terminal and return to your shell",
...(process.platform === "win32"
? ["Press {highlight}Ctrl+Z{/highlight} to undo changes in your prompt"]
: ["Press {highlight}Ctrl+Z{/highlight} to suspend the terminal and return to your shell"]),
]
@@ -21,7 +21,15 @@ import { Spinner } from "@tui/component/spinner"
import { selectedForeground, useTheme } from "@tui/context/theme"
import { BoxRenderable, ScrollBoxRenderable, addDefaultParsers, TextAttributes, RGBA } from "@opentui/core"
import { Prompt, type PromptRef } from "@tui/component/prompt"
import type { AssistantMessage, Part, Provider, ToolPart, UserMessage, TextPart, ReasoningPart } from "@kilocode/sdk/v2"
import type {
AssistantMessage,
Part,
Provider,
ToolPart,
UserMessage,
TextPart,
ReasoningPart,
} from "@kilocode/sdk/v2"
import { useLocal } from "@tui/context/local"
import { Locale } from "@/util/locale"
import type { Tool } from "@/tool/tool"
@@ -38,6 +38,7 @@ export interface DialogSelectOption<T = any> {
description?: string
footer?: JSX.Element | string
category?: string
categoryView?: JSX.Element
disabled?: boolean
bg?: RGBA
gutter?: JSX.Element
@@ -291,9 +292,16 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
<>
<Show when={category}>
<box paddingTop={index() > 0 ? 1 : 0} paddingLeft={3}>
<text fg={theme.accent} attributes={TextAttributes.BOLD}>
{category}
</text>
<Show
when={options[0]?.categoryView}
fallback={
<text fg={theme.accent} attributes={TextAttributes.BOLD}>
{category}
</text>
}
>
{options[0]?.categoryView}
</Show>
</box>
</Show>
<For each={options}>
@@ -0,0 +1,20 @@
export const CONSOLE_MANAGED_ICON = "⌂"
const contains = (consoleManagedProviders: string[] | ReadonlySet<string>, providerID: string) =>
Array.isArray(consoleManagedProviders)
? consoleManagedProviders.includes(providerID)
: consoleManagedProviders.has(providerID)
export const isConsoleManagedProvider = (consoleManagedProviders: string[] | ReadonlySet<string>, providerID: string) =>
contains(consoleManagedProviders, providerID)
export const consoleManagedProviderSuffix = (
consoleManagedProviders: string[] | ReadonlySet<string>,
providerID: string,
) => (contains(consoleManagedProviders, providerID) ? ` ${CONSOLE_MANAGED_ICON}` : "")
export const consoleManagedProviderLabel = (
consoleManagedProviders: string[] | ReadonlySet<string>,
providerID: string,
providerName: string,
) => `${providerName}${consoleManagedProviderSuffix(consoleManagedProviders, providerID)}`
+35 -11
View File
@@ -38,6 +38,7 @@ import { Account } from "@/account"
import { isRecord } from "@/util/record"
import { ConfigPaths } from "./paths"
import { Filesystem } from "@/util/filesystem"
import type { ConsoleState } from "./console-state"
import { AppFileSystem } from "@/filesystem"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
@@ -1148,11 +1149,13 @@ export namespace Config {
directories: string[]
deps: Promise<void>[]
warnings: Warning[] // kilocode_change
consoleState: ConsoleState
}
export interface Interface {
readonly get: () => Effect.Effect<Info>
readonly getGlobal: () => Effect.Effect<Info>
readonly getConsoleState: () => Effect.Effect<ConsoleState>
readonly update: (config: Info) => Effect.Effect<void>
readonly updateGlobal: (config: Info, options?: { dispose?: boolean }) => Effect.Effect<Info> // kilocode_change
readonly invalidate: (wait?: boolean) => Effect.Effect<void>
@@ -1390,6 +1393,8 @@ export namespace Config {
const auth = yield* authSvc.all().pipe(Effect.orDie)
let result: Info = {}
const consoleManagedProviders = new Set<string>()
let activeOrgName: string | undefined
// kilocode_change start — load Kilocode legacy configs (lowest precedence)
const legacy = yield* Effect.promise(() =>
@@ -1588,26 +1593,31 @@ export namespace Config {
// kilocode_change end
}
const active = Option.getOrUndefined(yield* accountSvc.active().pipe(Effect.orDie))
if (active?.active_org_id) {
const activeOrg = Option.getOrUndefined(
yield* accountSvc.activeOrg().pipe(Effect.catch(() => Effect.succeed(Option.none()))),
)
if (activeOrg) {
yield* Effect.gen(function* () {
const [configOpt, tokenOpt] = yield* Effect.all(
[accountSvc.config(active.id, active.active_org_id!), accountSvc.token(active.id)],
[accountSvc.config(activeOrg.account.id, activeOrg.org.id), accountSvc.token(activeOrg.account.id)],
{ concurrency: 2 },
)
const token = Option.getOrUndefined(tokenOpt)
if (token) {
process.env["KILO_CONSOLE_TOKEN"] = token
Env.set("KILO_CONSOLE_TOKEN", token)
if (Option.isSome(tokenOpt)) {
process.env["KILO_CONSOLE_TOKEN"] = tokenOpt.value
Env.set("KILO_CONSOLE_TOKEN", tokenOpt.value)
}
const config = Option.getOrUndefined(configOpt)
if (config) {
const source = `${active.url}/api/config`
const next = yield* loadConfig(JSON.stringify(config), {
activeOrgName = activeOrg.org.name
if (Option.isSome(configOpt)) {
const source = `${activeOrg.account.url}/api/config`
const next = yield* loadConfig(JSON.stringify(configOpt.value), {
dir: path.dirname(source),
source,
})
for (const providerID of Object.keys(next.provider ?? {})) {
consoleManagedProviders.add(providerID)
}
merge(source, next, "global")
}
}).pipe(
@@ -1675,6 +1685,11 @@ export namespace Config {
directories,
deps,
warnings, // kilocode_change
consoleState: {
consoleManagedProviders: Array.from(consoleManagedProviders),
activeOrgName,
switchableOrgCount: 0,
},
}
})
@@ -1692,6 +1707,10 @@ export namespace Config {
return yield* InstanceState.use(state, (s) => s.directories)
})
const getConsoleState = Effect.fn("Config.getConsoleState")(function* () {
return yield* InstanceState.use(state, (s) => s.consoleState)
})
const waitForDependencies = Effect.fn("Config.waitForDependencies")(function* () {
yield* InstanceState.useEffect(state, (s) => Effect.promise(() => Promise.all(s.deps).then(() => undefined)))
})
@@ -1779,6 +1798,7 @@ export namespace Config {
return Service.of({
get,
getGlobal,
getConsoleState,
update,
updateGlobal,
invalidate,
@@ -1805,6 +1825,10 @@ export namespace Config {
return runPromise((svc) => svc.getGlobal())
}
export async function getConsoleState() {
return runPromise((svc) => svc.getConsoleState())
}
export async function update(config: Info) {
return runPromise((svc) => svc.update(config))
}
@@ -0,0 +1,15 @@
import z from "zod"
export const ConsoleState = z.object({
consoleManagedProviders: z.array(z.string()),
activeOrgName: z.string().optional(),
switchableOrgCount: z.number().int().nonnegative(),
})
export type ConsoleState = z.infer<typeof ConsoleState>
export const emptyConsoleState: ConsoleState = {
consoleManagedProviders: [],
activeOrgName: undefined,
switchableOrgCount: 0,
}
@@ -22,6 +22,7 @@ export const TuiOptions = z.object({
.enum(["auto", "stacked"])
.optional()
.describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),
mouse: z.boolean().optional().describe("Enable or disable mouse capture (default: true)"),
})
export const TuiInfo = z
+9 -1
View File
@@ -111,7 +111,15 @@ export namespace TuiConfig {
}
}
acc.result.keybinds = Config.Keybinds.parse(acc.result.keybinds ?? {})
const keybinds = { ...(acc.result.keybinds ?? {}) }
if (process.platform === "win32") {
// Native Windows terminals do not support POSIX suspend, so prefer prompt undo.
keybinds.terminal_suspend = "none"
keybinds.input_undo ??= unique(["ctrl+z", ...Config.Keybinds.shape.input_undo.parse(undefined).split(",")]).join(
",",
)
}
acc.result.keybinds = Config.Keybinds.parse(keybinds)
const deps: Promise<void>[] = []
if (acc.result.plugin?.length) {
+12 -2
View File
@@ -188,13 +188,23 @@ export namespace AppFileSystem {
export function normalizePath(p: string): string {
if (process.platform !== "win32") return p
const resolved = pathResolve(windowsPath(p))
try {
return realpathSync.native(p)
return realpathSync.native(resolved)
} catch {
return p
return resolved
}
}
export function normalizePathPattern(p: string): string {
if (process.platform !== "win32") return p
if (p === "*") return p
const match = p.match(/^(.*)[\\/]\*$/)
if (!match) return normalizePath(p)
const dir = /^[A-Za-z]:$/.test(match[1]) ? match[1] + "\\" : match[1]
return join(normalizePath(dir), "*")
}
export function resolve(p: string): string {
const resolved = pathResolve(windowsPath(p))
try {
+14 -8
View File
@@ -31,10 +31,14 @@ export namespace Flag {
export const KILO_ENABLE_EXPERIMENTAL_MODELS = truthy("KILO_ENABLE_EXPERIMENTAL_MODELS")
export const KILO_DISABLE_AUTOCOMPACT = truthy("KILO_DISABLE_AUTOCOMPACT")
export const KILO_DISABLE_MODELS_FETCH = truthy("KILO_DISABLE_MODELS_FETCH")
export const KILO_DISABLE_MOUSE = truthy("KILO_DISABLE_MOUSE")
export const KILO_DISABLE_CLAUDE_CODE = truthy("KILO_DISABLE_CLAUDE_CODE")
export const KILO_DISABLE_CLAUDE_CODE_PROMPT = KILO_DISABLE_CLAUDE_CODE || truthy("KILO_DISABLE_CLAUDE_CODE_PROMPT")
export const KILO_DISABLE_CLAUDE_CODE_SKILLS = KILO_DISABLE_CLAUDE_CODE || truthy("KILO_DISABLE_CLAUDE_CODE_SKILLS")
export const KILO_DISABLE_EXTERNAL_SKILLS = KILO_DISABLE_CLAUDE_CODE_SKILLS || truthy("KILO_DISABLE_EXTERNAL_SKILLS")
export const KILO_DISABLE_CLAUDE_CODE_PROMPT =
KILO_DISABLE_CLAUDE_CODE || truthy("KILO_DISABLE_CLAUDE_CODE_PROMPT")
export const KILO_DISABLE_CLAUDE_CODE_SKILLS =
KILO_DISABLE_CLAUDE_CODE || truthy("KILO_DISABLE_CLAUDE_CODE_SKILLS")
export const KILO_DISABLE_EXTERNAL_SKILLS =
KILO_DISABLE_CLAUDE_CODE_SKILLS || truthy("KILO_DISABLE_EXTERNAL_SKILLS")
export declare const KILO_DISABLE_PROJECT_CONFIG: boolean
export const KILO_FAKE_VCS = process.env["KILO_FAKE_VCS"]
export declare const KILO_CLIENT: string
@@ -47,15 +51,17 @@ export namespace Flag {
export const KILO_EXPERIMENTAL_FILEWATCHER = Config.boolean("KILO_EXPERIMENTAL_FILEWATCHER").pipe(
Config.withDefault(false),
)
export const KILO_EXPERIMENTAL_DISABLE_FILEWATCHER = Config.boolean("KILO_EXPERIMENTAL_DISABLE_FILEWATCHER").pipe(
Config.withDefault(false),
)
export const KILO_EXPERIMENTAL_ICON_DISCOVERY = KILO_EXPERIMENTAL || truthy("KILO_EXPERIMENTAL_ICON_DISCOVERY")
export const KILO_EXPERIMENTAL_DISABLE_FILEWATCHER = Config.boolean(
"KILO_EXPERIMENTAL_DISABLE_FILEWATCHER",
).pipe(Config.withDefault(false))
export const KILO_EXPERIMENTAL_ICON_DISCOVERY =
KILO_EXPERIMENTAL || truthy("KILO_EXPERIMENTAL_ICON_DISCOVERY")
const copy = process.env["KILO_EXPERIMENTAL_DISABLE_COPY_ON_SELECT"]
export const KILO_EXPERIMENTAL_DISABLE_COPY_ON_SELECT =
copy === undefined ? process.platform === "win32" : truthy("KILO_EXPERIMENTAL_DISABLE_COPY_ON_SELECT")
export const KILO_ENABLE_EXA = truthy("KILO_ENABLE_EXA") || KILO_EXPERIMENTAL || truthy("KILO_EXPERIMENTAL_EXA")
export const KILO_ENABLE_EXA =
truthy("KILO_ENABLE_EXA") || KILO_EXPERIMENTAL || truthy("KILO_EXPERIMENTAL_EXA")
export const KILO_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS = number("KILO_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS")
export const KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX = number("KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX")
export const KILO_EXPERIMENTAL_OXFMT = KILO_EXPERIMENTAL || truthy("KILO_EXPERIMENTAL_OXFMT")
@@ -0,0 +1,93 @@
// kilocode_change - new file
/**
* Kilo-specific overrides for the provider dialog.
*
* Exports constants and renderers consumed by the shared upstream
* `dialog-provider.tsx` so the upstream diff stays minimal.
*/
import type { JSX } from "solid-js"
import type { RGBA } from "@opentui/core"
import type { ProviderAuthAuthorization } from "@kilocode/sdk/v2"
import { KiloAutoMethod } from "@/kilocode/components/dialog-kilo-auto-method"
// ---------------------------------------------------------------------------
// Provider priority (replaces upstream map entirely)
// ---------------------------------------------------------------------------
export const PROVIDER_PRIORITY: Record<string, number> = {
kilo: -1,
anthropic: 0,
"github-copilot": 1,
openai: 2,
google: 3,
}
// ---------------------------------------------------------------------------
// Provider descriptions shown next to the name in the selection list
// ---------------------------------------------------------------------------
export const PROVIDER_DESCRIPTIONS: Record<string, string> = {
kilo: "(Recommended)",
anthropic: "(Claude Max or API key)",
openai: "(ChatGPT Plus/Pro or API key)",
}
// ---------------------------------------------------------------------------
// Auto-method renderer
// ---------------------------------------------------------------------------
/**
* If the provider is Kilo Gateway, renders the custom `KiloAutoMethod`
* component that handles device-auth + org selection.
*
* Returns `undefined` for every other provider so the caller can fall
* through to the default `AutoMethod`.
*/
export function renderAutoMethod(opts: {
providerID: string
title: string
index: number
authorization: ProviderAuthAuthorization
useSDK: () => any
useTheme: () => any
DialogModel: any
}): (() => JSX.Element) | undefined {
if (opts.providerID !== "kilo") return undefined
return () => (
<KiloAutoMethod
providerID={opts.providerID}
title={opts.title}
index={opts.index}
authorization={opts.authorization}
useSDK={opts.useSDK}
useTheme={opts.useTheme}
DialogModel={opts.DialogModel}
/>
)
}
// ---------------------------------------------------------------------------
// API-key dialog description
// ---------------------------------------------------------------------------
/**
* Returns a custom description element for the API-key dialog when the
* provider is Kilo Gateway. Returns `undefined` otherwise.
*/
export function renderApiDescription(
providerID: string,
theme: { textMuted: RGBA; text: RGBA; primary: RGBA },
): (() => JSX.Element) | undefined {
if (providerID !== "kilo") return undefined
return () => (
<box gap={1}>
<text fg={theme.textMuted}>
Kilo Gateway gives you access to all the best coding models at the cheapest prices with a single API key.
</text>
<text fg={theme.text}>
Go to <span style={{ fg: theme.primary }}>https://kilo.ai/gateway</span> to get a key
</text>
</box>
)
}
@@ -3,6 +3,7 @@
// Imported by ../../server/server.ts with minimal kilocode_change markers.
import { ModelCache } from "../../provider/model-cache"
import { Instance } from "../../project/instance"
/** Extra paths to skip request logging for */
export function skipLogging(path: string): boolean {
@@ -17,9 +18,10 @@ export function corsOrigin(input: string): string | undefined {
return undefined
}
/** Invalidate model cache after auth change */
export function authChanged(providerID: string) {
/** Invalidate model cache and provider state after auth change */
export async function authChanged(providerID: string) {
ModelCache.clear(providerID)
await Instance.disposeAll()
}
export const DOC_TITLE = "kilo"
@@ -1,7 +1,7 @@
// kilocode_change - new file
import z from "zod"
import { BusEvent } from "@/bus/bus-event"
import { Database, eq, and, gte, isNull, desc, like, inArray, lt } from "@/storage/db"
import { Database, eq, and, gte, isNull, desc, like, inArray, lt, or } from "@/storage/db"
import type { SQL } from "@/storage/db"
import { ProjectTable } from "@/project/project.sql"
import { ProjectID } from "@/project/schema"
@@ -79,6 +79,15 @@ export namespace KiloSession {
return ids.length ? ids : [id]
}
export function filters(input: { projectID: ProjectID; directory?: string }): SQL[] {
const dir = input.directory ? Filesystem.resolve(input.directory) : undefined
if (!dir) return [eq(SessionTable.project_id, input.projectID)]
return [
or(eq(SessionTable.project_id, input.projectID), eq(SessionTable.directory, dir)),
eq(SessionTable.directory, dir),
].filter((item): item is SQL => item !== undefined)
}
// ---------------------------------------------------------------------------
// Provider-reported cost (OpenRouter / Kilo)
// ---------------------------------------------------------------------------
@@ -0,0 +1,49 @@
// kilocode_change - new file
import { CodebaseSearchTool } from "../../tool/warpgrep"
import { RecallTool } from "../../tool/recall"
import { Tool } from "../../tool/tool"
import { Flag } from "@/flag/flag"
import { ProviderID } from "../../provider/schema"
import { Env } from "../../env"
import { Effect } from "effect"
export namespace KiloToolRegistry {
/** Build Kilo-specific tools (CodebaseSearch, Recall) */
export function build(
fn: <T extends Tool.Info>(tool: T | Effect.Effect<T, never, any>) => Effect.Effect<T, never, any>,
) {
return Effect.gen(function* () {
const codebase = yield* fn(CodebaseSearchTool)
const recall = yield* fn(RecallTool)
return { codebase, recall }
})
}
/** Override question-tool client gating (adds "vscode" to allowed clients) */
export function question(): boolean {
return ["app", "cli", "desktop", "vscode"].includes(Flag.KILO_CLIENT) || Flag.KILO_ENABLE_QUESTION_TOOL
}
/** Plan tool is always registered in Kilo (gated by agent permission instead) */
export function plan(tool: Tool.Info): Tool.Info[] {
return [tool]
}
/** Kilo-specific tools to append to the all() list */
export function extra(
tools: { codebase: Tool.Info; recall: Tool.Info },
cfg: { experimental?: { codebase_search?: boolean } },
): Tool.Info[] {
return [...(cfg.experimental?.codebase_search === true ? [tools.codebase] : []), tools.recall]
}
/** Check whether exa-based tools (codesearch/websearch) are enabled for a provider */
export function exa(providerID: ProviderID): boolean {
return providerID === ProviderID.kilo || Flag.KILO_ENABLE_EXA
}
/** Check for E2E LLM URL (uses KILO_E2E_LLM_URL env var) */
export function e2e(): boolean {
return !!Env.get("KILO_E2E_LLM_URL")
}
}
+9 -1
View File
@@ -11,6 +11,7 @@ import { Arborist } from "@npmcli/arborist"
export namespace Npm {
const log = Log.create({ service: "npm" })
const illegal = process.platform === "win32" ? new Set(["<", ">", ":", '"', "|", "?", "*"]) : undefined
export const InstallFailedError = NamedError.create(
"NpmInstallFailedError",
@@ -19,8 +20,13 @@ export namespace Npm {
}),
)
export function sanitize(pkg: string) {
if (!illegal) return pkg
return Array.from(pkg, (char) => (illegal.has(char) || char.charCodeAt(0) < 32 ? "_" : char)).join("")
}
function directory(pkg: string) {
return path.join(Global.Path.cache, "packages", pkg)
return path.join(Global.Path.cache, "packages", sanitize(pkg))
}
function resolveEntryPoint(name: string, dir: string) {
@@ -67,6 +73,7 @@ export namespace Npm {
binLinks: true,
progress: false,
savePrefix: "",
ignoreScripts: true,
})
const tree = await arborist.loadVirtual().catch(() => {})
if (tree) {
@@ -106,6 +113,7 @@ export namespace Npm {
binLinks: true,
progress: false,
savePrefix: "",
ignoreScripts: true,
})
await arb.reify().catch(() => {})
}
@@ -0,0 +1,67 @@
import type { Hooks, PluginInput } from "@kilocode/plugin"
export async function CloudflareWorkersAuthPlugin(_input: PluginInput): Promise<Hooks> {
const prompts = [
...(!process.env.CLOUDFLARE_ACCOUNT_ID
? [
{
type: "text" as const,
key: "accountId",
message: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
},
]
: []),
]
return {
auth: {
provider: "cloudflare-workers-ai",
methods: [
{
type: "api",
label: "API key",
prompts,
},
],
},
}
}
export async function CloudflareAIGatewayAuthPlugin(_input: PluginInput): Promise<Hooks> {
const prompts = [
...(!process.env.CLOUDFLARE_ACCOUNT_ID
? [
{
type: "text" as const,
key: "accountId",
message: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
},
]
: []),
...(!process.env.CLOUDFLARE_GATEWAY_ID
? [
{
type: "text" as const,
key: "gatewayId",
message: "Enter your Cloudflare AI Gateway ID",
placeholder: "e.g. my-gateway",
},
]
: []),
]
return {
auth: {
provider: "cloudflare-ai-gateway",
methods: [
{
type: "api",
label: "Gateway API token",
prompts,
},
],
},
}
}
+3
View File
@@ -10,6 +10,7 @@ import { NamedError } from "@opencode-ai/util/error"
import { CopilotAuthPlugin } from "./github-copilot/copilot"
import { gitlabAuthPlugin as GitlabAuthPlugin } from "opencode-gitlab-auth"
import { PoeAuthPlugin } from "opencode-poe-auth"
import { CloudflareAIGatewayAuthPlugin, CloudflareWorkersAuthPlugin } from "./cloudflare"
import { Effect, Layer, ServiceMap, Stream } from "effect"
import { InstanceState } from "@/effect/instance-state"
import { KiloAuthPlugin } from "@kilocode/kilo-gateway" // kilocode_change
@@ -54,6 +55,8 @@ export namespace Plugin {
CopilotAuthPlugin,
GitlabAuthPlugin as unknown as PluginInstance,
PoeAuthPlugin as unknown as PluginInstance,
CloudflareWorkersAuthPlugin as unknown as PluginInstance,
CloudflareAIGatewayAuthPlugin as unknown as PluginInstance,
] // kilocode_change end
function isServerPlugin(value: unknown): value is PluginInstance {
+22 -6
View File
@@ -1,5 +1,6 @@
import path from "path"
import { fileURLToPath, pathToFileURL } from "url"
import npa from "npm-package-arg"
import semver from "semver"
import { Npm } from "@/npm"
import { Filesystem } from "@/util/filesystem"
@@ -12,11 +13,24 @@ export function isDeprecatedPlugin(spec: string) {
return DEPRECATED_PLUGIN_PACKAGES.some((pkg) => spec.includes(pkg))
}
function parse(spec: string) {
try {
return npa(spec)
} catch {}
}
export function parsePluginSpecifier(spec: string) {
const lastAt = spec.lastIndexOf("@")
const pkg = lastAt > 0 ? spec.substring(0, lastAt) : spec
const version = lastAt > 0 ? spec.substring(lastAt + 1) : "latest"
return { pkg, version }
const hit = parse(spec)
if (hit?.type === "alias" && !hit.name) {
const sub = (hit as npa.AliasResult).subSpec
if (sub?.name) {
const version = !sub.rawSpec || sub.rawSpec === "*" ? "latest" : sub.rawSpec
return { pkg: sub.name, version }
}
}
if (!hit?.name) return { pkg: spec, version: "" }
if (hit.raw === hit.name) return { pkg: hit.name, version: "latest" }
return { pkg: hit.name, version: hit.rawSpec }
}
export type PluginSource = "file" | "npm"
@@ -190,9 +204,11 @@ export async function checkPluginCompatibility(target: string, opencodeVersion:
}
}
export async function resolvePluginTarget(spec: string, parsed = parsePluginSpecifier(spec)) {
export async function resolvePluginTarget(spec: string) {
if (isPathPluginSpec(spec)) return resolvePathPluginTarget(spec)
const result = await Npm.add(parsed.pkg + "@" + parsed.version)
const hit = parse(spec)
const pkg = hit?.name && hit.raw === hit.name ? `${hit.name}@latest` : spec
const result = await Npm.add(pkg)
return result.directory
}
+2 -1
View File
@@ -260,7 +260,8 @@ export namespace Project {
time: { created: Date.now(), updated: Date.now() },
}
if (Flag.KILO_EXPERIMENTAL_ICON_DISCOVERY) yield* discover(existing).pipe(Effect.ignore, Effect.forkIn(scope))
if (Flag.KILO_EXPERIMENTAL_ICON_DISCOVERY)
yield* discover(existing).pipe(Effect.ignore, Effect.forkIn(scope))
const result: Info = {
...existing,
+2
View File
@@ -10,6 +10,7 @@ import z from "zod"
import { Telemetry } from "@kilocode/kilo-telemetry" // kilocode_change
import { ModelCache } from "./model-cache" // kilocode_change
import { Instance } from "@/project/instance" // kilocode_change
export namespace ProviderAuth {
export const Method = z
@@ -263,6 +264,7 @@ export namespace ProviderAuth {
}
Telemetry.trackAuthSuccess(input.providerID)
ModelCache.clear(input.providerID)
await Instance.disposeAll()
// kilocode_change end
}
}
+39 -8
View File
@@ -686,13 +686,26 @@ export namespace Provider {
}
}),
"cloudflare-workers-ai": Effect.fnUntraced(function* (input: Info) {
const accountId = Env.get("CLOUDFLARE_ACCOUNT_ID")
if (!accountId) return { autoload: false }
// When baseURL is already configured (e.g. corporate config routing through a proxy/gateway),
// skip the account ID check because the URL is already fully specified.
if (input.options?.baseURL) return { autoload: false }
const auth = yield* dep.auth(input.id)
const accountId =
Env.get("CLOUDFLARE_ACCOUNT_ID") || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
if (!accountId)
return {
autoload: false,
async getModel() {
throw new Error(
"CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>",
)
},
}
const apiKey = yield* Effect.gen(function* () {
const envToken = Env.get("CLOUDFLARE_API_KEY")
if (envToken) return envToken
const auth = yield* dep.auth(input.id)
if (auth?.type === "api") return auth.key
return undefined
})
@@ -716,16 +729,34 @@ export namespace Provider {
}
}),
"cloudflare-ai-gateway": Effect.fnUntraced(function* (input: Info) {
const accountId = Env.get("CLOUDFLARE_ACCOUNT_ID")
const gateway = Env.get("CLOUDFLARE_GATEWAY_ID")
// When baseURL is already configured (e.g. corporate config), skip the ID checks.
if (input.options?.baseURL) return { autoload: false }
if (!accountId || !gateway) return { autoload: false }
const auth = yield* dep.auth(input.id)
const accountId =
Env.get("CLOUDFLARE_ACCOUNT_ID") || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
const gateway =
Env.get("CLOUDFLARE_GATEWAY_ID") || (auth?.type === "api" ? auth.metadata?.gatewayId : undefined)
if (!accountId || !gateway) {
const missing = [
!accountId ? "CLOUDFLARE_ACCOUNT_ID" : undefined,
!gateway ? "CLOUDFLARE_GATEWAY_ID" : undefined,
].filter((x): x is string => Boolean(x))
return {
autoload: false,
async getModel() {
throw new Error(
`${missing.join(" and ")} missing. Set with: ${missing.map((x) => `export ${x}=<value>`).join(" && ")}`,
)
},
}
}
// Get API token from env or auth - required for authenticated gateways
const apiToken = yield* Effect.gen(function* () {
const envToken = Env.get("CLOUDFLARE_API_TOKEN") || Env.get("CF_AIG_TOKEN")
if (envToken) return envToken
const auth = yield* dep.auth(input.id)
if (auth?.type === "api") return auth.key
return undefined
})
@@ -1278,7 +1309,7 @@ export namespace Provider {
(providerID === ProviderID.openrouter && modelID === "openai/gpt-5-chat")
)
delete provider.models[modelID]
if (model.status === "alpha" && !Flag.KILO_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID] // kilocode_change
if (model.status === "alpha" && !Flag.KILO_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
if (model.status === "deprecated") delete provider.models[modelID]
if (
(configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
+6 -46
View File
@@ -282,56 +282,10 @@ export namespace ProviderTransform {
})
}
// kilocode_change - function added
function fixDuplicateReasoning(msgs: ModelMessage[], model: Provider.Model) {
for (const msg of msgs) {
if (!Array.isArray(msg.content)) {
continue
}
const encryptedDataSet = new Set<string>()
const textSet = new Set<string>()
for (const part of msg.content) {
if (!("providerOptions" in part)) continue // kilocode_change - ToolApprovalRequest lacks providerOptions
const openrouterProviderOptions = part.providerOptions?.openrouter as
| {
reasoning_details?: { data?: string; text?: string; signature?: string }[]
}
| undefined
if (!openrouterProviderOptions || !openrouterProviderOptions.reasoning_details) {
continue
}
openrouterProviderOptions.reasoning_details = openrouterProviderOptions.reasoning_details.filter((rd) => {
if (rd.data) {
if (!encryptedDataSet.has(rd.data)) {
encryptedDataSet.add(rd.data)
return true
}
return false
}
if (rd.text) {
if ((model.family === "claude" || model.id.includes("claude")) && !rd.signature) return false
if (!textSet.has(rd.text)) {
textSet.add(rd.text)
return true
}
return false
}
return true
})
}
}
}
export function message(msgs: ModelMessage[], model: Provider.Model, options: Record<string, unknown>) {
msgs = unsupportedParts(msgs, model)
msgs = normalizeMessages(msgs, model, options)
// kilocode_change - workaround for @openrouter/ai-sdk-provider v1 duplicating reasoning
// fixed in https://github.com/OpenRouterTeam/ai-sdk-provider/pull/344/
if (model.api.npm === "@openrouter/ai-sdk-provider") {
fixDuplicateReasoning(msgs, model)
}
if (
(model.providerID === "anthropic" ||
model.providerID === "google-vertex-anthropic" ||
@@ -1027,6 +981,12 @@ export namespace ProviderTransform {
// kilocode_change end
const key = sdkKey(model.api.npm) ?? model.providerID
// @ai-sdk/azure delegates to OpenAIChatLanguageModel which reads from
// providerOptions["openai"], but OpenAIResponsesLanguageModel checks
// "azure" first. Pass both so model options work on either code path.
if (model.api.npm === "@ai-sdk/azure") {
return { openai: options, azure: options }
}
return { [key]: options }
}
@@ -8,6 +8,9 @@ import { Instance } from "../../project/instance"
import { Project } from "../../project/project"
import { MCP } from "../../mcp"
import { Session } from "../../session"
import { Config } from "../../config/config"
import { ConsoleState } from "../../config/console-state"
import { Account, AccountID, OrgID } from "../../account"
import { zodToJsonSchema } from "zod-to-json-schema"
import { errors } from "../error"
import { lazy } from "../../util/lazy"
@@ -20,8 +23,108 @@ import { WorkspaceRoutes } from "./workspace"
import { Filesystem } from "../../util/filesystem" // kilocode_change
import path from "path" // kilocode_change
const ConsoleOrgOption = z.object({
accountID: z.string(),
accountEmail: z.string(),
accountUrl: z.string(),
orgID: z.string(),
orgName: z.string(),
active: z.boolean(),
})
const ConsoleOrgList = z.object({
orgs: z.array(ConsoleOrgOption),
})
const ConsoleSwitchBody = z.object({
accountID: z.string(),
orgID: z.string(),
})
export const ExperimentalRoutes = lazy(() =>
new Hono()
.get(
"/console",
describeRoute({
summary: "Get active Console provider metadata",
description: "Get the active Console org name and the set of provider IDs managed by that Console org.",
operationId: "experimental.console.get",
responses: {
200: {
description: "Active Console provider metadata",
content: {
"application/json": {
schema: resolver(ConsoleState),
},
},
},
},
}),
async (c) => {
const [consoleState, groups] = await Promise.all([Config.getConsoleState(), Account.orgsByAccount()])
return c.json({
...consoleState,
switchableOrgCount: groups.reduce((count, group) => count + group.orgs.length, 0),
})
},
)
.get(
"/console/orgs",
describeRoute({
summary: "List switchable Console orgs",
description: "Get the available Console orgs across logged-in accounts, including the current active org.",
operationId: "experimental.console.listOrgs",
responses: {
200: {
description: "Switchable Console orgs",
content: {
"application/json": {
schema: resolver(ConsoleOrgList),
},
},
},
},
}),
async (c) => {
const [groups, active] = await Promise.all([Account.orgsByAccount(), Account.active()])
const orgs = groups.flatMap((group) =>
group.orgs.map((org) => ({
accountID: group.account.id,
accountEmail: group.account.email,
accountUrl: group.account.url,
orgID: org.id,
orgName: org.name,
active: !!active && active.id === group.account.id && active.active_org_id === org.id,
})),
)
return c.json({ orgs })
},
)
.post(
"/console/switch",
describeRoute({
summary: "Switch active Console org",
description: "Persist a new active Console account/org selection for the current local OpenCode state.",
operationId: "experimental.console.switchOrg",
responses: {
200: {
description: "Switch success",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
},
}),
validator("json", ConsoleSwitchBody),
async (c) => {
const body = c.req.valid("json")
await Account.switchOrg(AccountID.make(body.accountID), OrgID.make(body.orgID))
return c.json(true)
},
)
.get(
"/tool/ids",
describeRoute({
+2 -2
View File
@@ -132,7 +132,7 @@ export namespace Server {
const providerID = c.req.valid("param").providerID
const info = c.req.valid("json")
await Auth.set(providerID, info)
KiloServer.authChanged(providerID) // kilocode_change
await KiloServer.authChanged(providerID) // kilocode_change
return c.json(true)
},
)
@@ -163,7 +163,7 @@ export namespace Server {
async (c) => {
const providerID = c.req.valid("param").providerID
await Auth.remove(providerID)
KiloServer.authChanged(providerID) // kilocode_change
await KiloServer.authChanged(providerID) // kilocode_change
return c.json(true)
},
)
+2 -8
View File
@@ -25,7 +25,6 @@ import { Snapshot } from "@/snapshot"
import { ProjectID } from "../project/schema"
import { WorkspaceID } from "../control-plane/schema"
import { SessionID, MessageID, PartID } from "./schema"
import { Filesystem } from "../util/filesystem" // kilocode_change: normalize directory for Windows drive-letter casing
import { KiloSession } from "@/kilocode/session" // kilocode_change
import type { Provider } from "@/provider/provider"
@@ -294,7 +293,7 @@ export namespace Session {
const tokens = {
total,
input: adjustedInputTokens,
output: outputTokens,
output: outputTokens - reasoningTokens,
reasoning: reasoningTokens,
cache: {
write: cacheWriteInputTokens,
@@ -790,16 +789,11 @@ export namespace Session {
limit?: number
}) {
const project = Instance.project
const conditions = [eq(SessionTable.project_id, project.id)]
const conditions = KiloSession.filters({ projectID: project.id, directory: input?.directory }) // kilocode_change
if (input?.workspaceID) {
conditions.push(eq(SessionTable.workspace_id, input.workspaceID))
}
if (input?.directory) {
// kilocode_change start: vscode uri.fsPath gives lowercase drive letter on Windows; resolve() canonicalises to match stored path
conditions.push(eq(SessionTable.directory, Filesystem.resolve(input.directory)))
// kilocode_change end
}
if (input?.roots) {
conditions.push(isNull(SessionTable.parent_id))
}
@@ -82,25 +82,6 @@ If the `AGENTS.md` is empty or insufficient, you may check `README`/`README.md`
If you modified any files/styles/structures/configurations/workflows/... mentioned in `AGENTS.md` files, you MUST update the corresponding `AGENTS.md` files to keep them up-to-date.
# Skills
Skills are reusable, composable capabilities that enhance your abilities. Each skill is a self-contained directory with a `SKILL.md` file that contains instructions, examples, and/or reference material.
## What are skills?
Skills are modular extensions that provide:
- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)
- Workflow patterns: Best practices for common tasks
- Tool integrations: Pre-configured tool chains for specific operations
- Reference material: Documentation, templates, and examples
## How to use skills
Identify the skills that are likely to be useful for the tasks you are currently working on, use the `skill` tool to load a skill for detailed instructions, guidelines, scripts and more.
Only load skill details when needed to conserve the context window.
# Ultimate Reminders
At any time, you should be HELPFUL, CONCISE, and ACCURATE. Be thorough in your actions — test what you build, verify what you change — not in your explanations.
@@ -1,7 +1,8 @@
import path from "path"
import { Effect } from "effect"
import type { Tool } from "./tool"
import { Instance } from "../project/instance"
import { Filesystem } from "@/util/filesystem"
import { AppFileSystem } from "../filesystem"
type Kind = "file" | "directory"
@@ -15,14 +16,14 @@ export async function assertExternalDirectory(ctx: Tool.Context, target?: string
if (options?.bypass) return
const full = process.platform === "win32" ? Filesystem.normalizePath(target) : target
const full = process.platform === "win32" ? AppFileSystem.normalizePath(target) : target
if (Instance.containsPath(full)) return
const kind = options?.kind ?? "file"
const dir = kind === "directory" ? full : path.dirname(full)
const glob =
process.platform === "win32"
? Filesystem.normalizePathPattern(path.join(dir, "*"))
? AppFileSystem.normalizePathPattern(path.join(dir, "*"))
: path.join(dir, "*").replaceAll("\\", "/")
await ctx.ask({
@@ -35,3 +36,11 @@ export async function assertExternalDirectory(ctx: Tool.Context, target?: string
},
})
}
export const assertExternalDirectoryEffect = Effect.fn("Tool.assertExternalDirectory")(function* (
ctx: Tool.Context,
target?: string,
options?: Options,
) {
yield* Effect.promise(() => assertExternalDirectory(ctx, target, options))
})
+228 -192
View File
@@ -1,16 +1,17 @@
import z from "zod"
import { Effect, Scope } from "effect"
import { createReadStream } from "fs"
import * as fs from "fs/promises"
import { open } from "fs/promises"
import * as path from "path"
import { createInterface } from "readline"
import { Tool } from "./tool"
import { AppFileSystem } from "../filesystem"
import { LSP } from "../lsp"
import { FileTime } from "../file/time"
import DESCRIPTION from "./read.txt"
import { Instance } from "../project/instance"
import { assertExternalDirectory } from "./external-directory"
import { assertExternalDirectoryEffect } from "./external-directory"
import { Instruction } from "../session/instruction"
import { Filesystem } from "../util/filesystem"
const DEFAULT_READ_LIMIT = 2000
const MAX_LINE_LENGTH = 2000
@@ -18,222 +19,257 @@ const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)`
const MAX_BYTES = 50 * 1024
const MAX_BYTES_LABEL = `${MAX_BYTES / 1024} KB`
export const ReadTool = Tool.define("read", {
description: DESCRIPTION,
parameters: z.object({
filePath: z.string().describe("The absolute path to the file or directory to read"),
offset: z.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),
limit: z.coerce.number().describe("The maximum number of lines to read (defaults to 2000)").optional(),
}),
async execute(params, ctx) {
if (params.offset !== undefined && params.offset < 1) {
throw new Error("offset must be greater than or equal to 1")
}
let filepath = params.filePath
if (!path.isAbsolute(filepath)) {
filepath = path.resolve(Instance.directory, filepath)
}
if (process.platform === "win32") {
filepath = Filesystem.normalizePath(filepath)
}
const title = path.relative(Instance.worktree, filepath)
const parameters = z.object({
filePath: z.string().describe("The absolute path to the file or directory to read"),
offset: z.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),
limit: z.coerce.number().describe("The maximum number of lines to read (defaults to 2000)").optional(),
})
const stat = Filesystem.stat(filepath)
export const ReadTool = Tool.defineEffect(
"read",
Effect.gen(function* () {
const fs = yield* AppFileSystem.Service
const instruction = yield* Instruction.Service
const lsp = yield* LSP.Service
const time = yield* FileTime.Service
const scope = yield* Scope.Scope
await assertExternalDirectory(ctx, filepath, {
bypass: Boolean(ctx.extra?.["bypassCwdCheck"]),
kind: stat?.isDirectory() ? "directory" : "file",
})
await ctx.ask({
permission: "read",
patterns: [filepath],
always: ["*"],
metadata: {},
})
if (!stat) {
const miss = Effect.fn("ReadTool.miss")(function* (filepath: string) {
const dir = path.dirname(filepath)
const base = path.basename(filepath)
const suggestions = await fs
.readdir(dir)
.then((entries) =>
entries
const items = yield* fs.readDirectory(dir).pipe(
Effect.map((items) =>
items
.filter(
(entry) =>
entry.toLowerCase().includes(base.toLowerCase()) || base.toLowerCase().includes(entry.toLowerCase()),
(item) =>
item.toLowerCase().includes(base.toLowerCase()) || base.toLowerCase().includes(item.toLowerCase()),
)
.map((entry) => path.join(dir, entry))
.map((item) => path.join(dir, item))
.slice(0, 3),
)
.catch(() => [])
),
Effect.catch(() => Effect.succeed([] as string[])),
)
if (suggestions.length > 0) {
throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`)
if (items.length > 0) {
return yield* Effect.fail(
new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${items.join("\n")}`),
)
}
throw new Error(`File not found: ${filepath}`)
}
return yield* Effect.fail(new Error(`File not found: ${filepath}`))
})
if (stat.isDirectory()) {
const dirents = await fs.readdir(filepath, { withFileTypes: true })
const entries = await Promise.all(
dirents.map(async (dirent) => {
if (dirent.isDirectory()) return dirent.name + "/"
if (dirent.isSymbolicLink()) {
const target = await fs.stat(path.join(filepath, dirent.name)).catch(() => undefined)
if (target?.isDirectory()) return dirent.name + "/"
}
return dirent.name
const list = Effect.fn("ReadTool.list")(function* (filepath: string) {
const items = yield* fs.readDirectoryEntries(filepath)
return yield* Effect.forEach(
items,
Effect.fnUntraced(function* (item) {
if (item.type === "directory") return item.name + "/"
if (item.type !== "symlink") return item.name
const target = yield* fs
.stat(path.join(filepath, item.name))
.pipe(Effect.catch(() => Effect.succeed(undefined)))
if (target?.type === "Directory") return item.name + "/"
return item.name
}),
{ concurrency: "unbounded" },
).pipe(Effect.map((items: string[]) => items.sort((a, b) => a.localeCompare(b))))
})
const warm = Effect.fn("ReadTool.warm")(function* (filepath: string, sessionID: Tool.Context["sessionID"]) {
yield* lsp.touchFile(filepath, false).pipe(Effect.ignore, Effect.forkIn(scope))
yield* time.read(sessionID, filepath)
})
const run = Effect.fn("ReadTool.execute")(function* (params: z.infer<typeof parameters>, ctx: Tool.Context) {
if (params.offset !== undefined && params.offset < 1) {
return yield* Effect.fail(new Error("offset must be greater than or equal to 1"))
}
let filepath = params.filePath
if (!path.isAbsolute(filepath)) {
filepath = path.resolve(Instance.directory, filepath)
}
if (process.platform === "win32") {
filepath = AppFileSystem.normalizePath(filepath)
}
const title = path.relative(Instance.worktree, filepath)
const stat = yield* fs.stat(filepath).pipe(
Effect.catchIf(
(err) => "reason" in err && err.reason._tag === "NotFound",
() => Effect.succeed(undefined),
),
)
yield* assertExternalDirectoryEffect(ctx, filepath, {
bypass: Boolean(ctx.extra?.["bypassCwdCheck"]),
kind: stat?.type === "Directory" ? "directory" : "file",
})
yield* Effect.promise(() =>
ctx.ask({
permission: "read",
patterns: [filepath],
always: ["*"],
metadata: {},
}),
)
entries.sort((a, b) => a.localeCompare(b))
const limit = params.limit ?? DEFAULT_READ_LIMIT
const offset = params.offset ?? 1
const start = offset - 1
const sliced = entries.slice(start, start + limit)
const truncated = start + sliced.length < entries.length
if (!stat) return yield* miss(filepath)
const output = [
`<path>${filepath}</path>`,
`<type>directory</type>`,
`<entries>`,
sliced.join("\n"),
truncated
? `\n(Showing ${sliced.length} of ${entries.length} entries. Use 'offset' parameter to read beyond entry ${offset + sliced.length})`
: `\n(${entries.length} entries)`,
`</entries>`,
].join("\n")
if (stat.type === "Directory") {
const items = yield* list(filepath)
const limit = params.limit ?? DEFAULT_READ_LIMIT
const offset = params.offset ?? 1
const start = offset - 1
const sliced = items.slice(start, start + limit)
const truncated = start + sliced.length < items.length
return {
title,
output: [
`<path>${filepath}</path>`,
`<type>directory</type>`,
`<entries>`,
sliced.join("\n"),
truncated
? `\n(Showing ${sliced.length} of ${items.length} entries. Use 'offset' parameter to read beyond entry ${offset + sliced.length})`
: `\n(${items.length} entries)`,
`</entries>`,
].join("\n"),
metadata: {
preview: sliced.slice(0, 20).join("\n"),
truncated,
loaded: [] as string[],
},
}
}
const loaded = yield* instruction.resolve(ctx.messages, filepath, ctx.messageID)
const mime = AppFileSystem.mimeType(filepath)
const isImage = mime.startsWith("image/") && mime !== "image/svg+xml" && mime !== "image/vnd.fastbidsheet"
const isPdf = mime === "application/pdf"
if (isImage || isPdf) {
const msg = `${isImage ? "Image" : "PDF"} read successfully`
return {
title,
output: msg,
metadata: {
preview: msg,
truncated: false,
loaded: loaded.map((item) => item.filepath),
},
attachments: [
{
type: "file" as const,
mime,
url: `data:${mime};base64,${Buffer.from(yield* fs.readFile(filepath)).toString("base64")}`,
},
],
}
}
if (yield* Effect.promise(() => isBinaryFile(filepath, Number(stat.size)))) {
return yield* Effect.fail(new Error(`Cannot read binary file: ${filepath}`))
}
const file = yield* Effect.promise(() =>
lines(filepath, { limit: params.limit ?? DEFAULT_READ_LIMIT, offset: params.offset ?? 1 }),
)
if (file.count < file.offset && !(file.count === 0 && file.offset === 1)) {
return yield* Effect.fail(
new Error(`Offset ${file.offset} is out of range for this file (${file.count} lines)`),
)
}
let output = [`<path>${filepath}</path>`, `<type>file</type>`, "<content>" + "\n"].join("\n")
output += file.raw.map((line, i) => `${i + file.offset}: ${line}`).join("\n")
const last = file.offset + file.raw.length - 1
const next = last + 1
const truncated = file.more || file.cut
if (file.cut) {
output += `\n\n(Output capped at ${MAX_BYTES_LABEL}. Showing lines ${file.offset}-${last}. Use offset=${next} to continue.)`
} else if (file.more) {
output += `\n\n(Showing lines ${file.offset}-${last} of ${file.count}. Use offset=${next} to continue.)`
} else {
output += `\n\n(End of file - total ${file.count} lines)`
}
output += "\n</content>"
yield* warm(filepath, ctx.sessionID)
if (loaded.length > 0) {
output += `\n\n<system-reminder>\n${loaded.map((item) => item.content).join("\n\n")}\n</system-reminder>`
}
return {
title,
output,
metadata: {
preview: sliced.slice(0, 20).join("\n"),
preview: file.raw.slice(0, 20).join("\n"),
truncated,
loaded: [] as string[],
loaded: loaded.map((item) => item.filepath),
},
}
}
const instructions = await Instruction.resolve(ctx.messages, filepath, ctx.messageID)
// Exclude SVG (XML-based) and vnd.fastbidsheet (.fbs extension, commonly FlatBuffers schema files)
const mime = Filesystem.mimeType(filepath)
const isImage = mime.startsWith("image/") && mime !== "image/svg+xml" && mime !== "image/vnd.fastbidsheet"
const isPdf = mime === "application/pdf"
if (isImage || isPdf) {
const msg = `${isImage ? "Image" : "PDF"} read successfully`
return {
title,
output: msg,
metadata: {
preview: msg,
truncated: false,
loaded: instructions.map((i) => i.filepath),
},
attachments: [
{
type: "file",
mime,
url: `data:${mime};base64,${Buffer.from(await Filesystem.readBytes(filepath)).toString("base64")}`,
},
],
}
}
const isBinary = await isBinaryFile(filepath, Number(stat.size))
if (isBinary) throw new Error(`Cannot read binary file: ${filepath}`)
const stream = createReadStream(filepath, { encoding: "utf8" })
const rl = createInterface({
input: stream,
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in file as a single line break.
crlfDelay: Infinity,
})
const limit = params.limit ?? DEFAULT_READ_LIMIT
const offset = params.offset ?? 1
const start = offset - 1
const raw: string[] = []
let bytes = 0
let lines = 0
let truncatedByBytes = false
let hasMoreLines = false
try {
for await (const text of rl) {
lines += 1
if (lines <= start) continue
if (raw.length >= limit) {
hasMoreLines = true
continue
}
const line = text.length > MAX_LINE_LENGTH ? text.substring(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX : text
const size = Buffer.byteLength(line, "utf-8") + (raw.length > 0 ? 1 : 0)
if (bytes + size > MAX_BYTES) {
truncatedByBytes = true
hasMoreLines = true
break
}
raw.push(line)
bytes += size
}
} finally {
rl.close()
stream.destroy()
}
if (lines < offset && !(lines === 0 && offset === 1)) {
throw new Error(`Offset ${offset} is out of range for this file (${lines} lines)`)
}
const content = raw.map((line, index) => {
return `${index + offset}: ${line}`
})
const preview = raw.slice(0, 20).join("\n")
let output = [`<path>${filepath}</path>`, `<type>file</type>`, "<content>"].join("\n")
output += content.join("\n")
const totalLines = lines
const lastReadLine = offset + raw.length - 1
const nextOffset = lastReadLine + 1
const truncated = hasMoreLines || truncatedByBytes
if (truncatedByBytes) {
output += `\n\n(Output capped at ${MAX_BYTES_LABEL}. Showing lines ${offset}-${lastReadLine}. Use offset=${nextOffset} to continue.)`
} else if (hasMoreLines) {
output += `\n\n(Showing lines ${offset}-${lastReadLine} of ${totalLines}. Use offset=${nextOffset} to continue.)`
} else {
output += `\n\n(End of file - total ${totalLines} lines)`
}
output += "\n</content>"
// just warms the lsp client
LSP.touchFile(filepath, false)
await FileTime.read(ctx.sessionID, filepath)
if (instructions.length > 0) {
output += `\n\n<system-reminder>\n${instructions.map((i) => i.content).join("\n\n")}\n</system-reminder>`
}
return {
title,
output,
metadata: {
preview,
truncated,
loaded: instructions.map((i) => i.filepath),
description: DESCRIPTION,
parameters,
async execute(params: z.infer<typeof parameters>, ctx) {
return Effect.runPromise(run(params, ctx).pipe(Effect.orDie))
},
}
},
})
}),
)
async function lines(filepath: string, opts: { limit: number; offset: number }) {
const stream = createReadStream(filepath, { encoding: "utf8" })
const rl = createInterface({
input: stream,
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in file as a single line break.
crlfDelay: Infinity,
})
const start = opts.offset - 1
const raw: string[] = []
let bytes = 0
let count = 0
let cut = false
let more = false
try {
for await (const text of rl) {
count += 1
if (count <= start) continue
if (raw.length >= opts.limit) {
more = true
continue
}
const line = text.length > MAX_LINE_LENGTH ? text.substring(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX : text
const size = Buffer.byteLength(line, "utf-8") + (raw.length > 0 ? 1 : 0)
if (bytes + size > MAX_BYTES) {
cut = true
more = true
break
}
raw.push(line)
bytes += size
}
} finally {
rl.close()
stream.destroy()
}
return { raw, count, cut, more, offset: opts.offset }
}
async function isBinaryFile(filepath: string, fileSize: number): Promise<boolean> {
const ext = path.extname(filepath).toLowerCase()
@@ -274,7 +310,7 @@ async function isBinaryFile(filepath: string, fileSize: number): Promise<boolean
if (fileSize === 0) return false
const fh = await fs.open(filepath, "r")
const fh = await open(filepath, "r")
try {
const sampleSize = Math.min(4096, fileSize)
const bytes = Buffer.alloc(sampleSize)
+175 -175
View File
@@ -17,19 +17,18 @@ import type { Agent } from "../agent/agent"
import { Tool } from "./tool"
import { Config } from "../config/config"
import path from "path"
import { type ToolContext as PluginToolContext, type ToolDefinition } from "@kilocode/plugin"
import { type ToolContext as PluginToolContext, type ToolDefinition } from "@kilocode/plugin" // kilocode_change
import z from "zod"
import { Plugin } from "../plugin"
import { ProviderID, type ModelID } from "../provider/schema"
import { WebSearchTool } from "./websearch"
import { CodeSearchTool } from "./codesearch"
import { CodebaseSearchTool } from "./warpgrep" // kilocode_change
import { KiloToolRegistry } from "../kilocode/tool/registry" // kilocode_change
import { Flag } from "@/flag/flag"
import { Log } from "@/util/log"
import { LspTool } from "./lsp"
import { Truncate } from "./truncate"
import { ApplyPatchTool } from "./apply_patch"
import { RecallTool } from "./recall" // kilocode_change
import { Glob } from "../util/glob"
import { pathToFileURL } from "url"
import { Effect, Layer, ServiceMap } from "effect"
@@ -38,6 +37,10 @@ import { makeRuntime } from "@/effect/run-service"
import { Env } from "../env"
import { Question } from "../question"
import { Todo } from "../session/todo"
import { LSP } from "../lsp"
import { FileTime } from "../file/time"
import { Instruction } from "../session/instruction"
import { AppFileSystem } from "../filesystem"
export namespace ToolRegistry {
const log = Log.create({ service: "tool.registry" })
@@ -60,185 +63,178 @@ export namespace ToolRegistry {
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/ToolRegistry") {}
export const layer: Layer.Layer<Service, never, Config.Service | Plugin.Service | Question.Service | Todo.Service> =
Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const plugin = yield* Plugin.Service
export const layer: Layer.Layer<
Service,
never,
| Config.Service
| Plugin.Service
| Question.Service
| Todo.Service
| LSP.Service
| FileTime.Service
| Instruction.Service
| AppFileSystem.Service
> = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const plugin = yield* Plugin.Service
const build = <T extends Tool.Info>(tool: T | Effect.Effect<T, never, any>) =>
Effect.isEffect(tool) ? tool : Effect.succeed(tool)
const build = <T extends Tool.Info>(tool: T | Effect.Effect<T, never, any>) =>
Effect.isEffect(tool) ? tool : Effect.succeed(tool)
const state = yield* InstanceState.make<State>(
Effect.fn("ToolRegistry.state")(function* (ctx) {
const custom: Tool.Info[] = []
const state = yield* InstanceState.make<State>(
Effect.fn("ToolRegistry.state")(function* (ctx) {
const custom: Tool.Info[] = []
function fromPlugin(id: string, def: ToolDefinition): Tool.Info {
return {
id,
init: async (initCtx) => ({
parameters: z.object(def.args),
description: def.description,
execute: async (args, toolCtx) => {
const pluginCtx = {
...toolCtx,
directory: ctx.directory,
worktree: ctx.worktree,
} as unknown as PluginToolContext
const result = await def.execute(args as any, pluginCtx)
const out = await Truncate.output(result, {}, initCtx?.agent)
return {
title: "",
output: out.truncated ? out.content : result,
metadata: { truncated: out.truncated, outputPath: out.truncated ? out.outputPath : undefined },
}
},
}),
}
function fromPlugin(id: string, def: ToolDefinition): Tool.Info {
return {
id,
init: async (initCtx) => ({
parameters: z.object(def.args),
description: def.description,
execute: async (args, toolCtx) => {
const pluginCtx = {
...toolCtx,
directory: ctx.directory,
worktree: ctx.worktree,
} as unknown as PluginToolContext
const result = await def.execute(args as any, pluginCtx)
const out = await Truncate.output(result, {}, initCtx?.agent)
return {
title: "",
output: out.truncated ? out.content : result,
metadata: { truncated: out.truncated, outputPath: out.truncated ? out.outputPath : undefined },
}
},
}),
}
}
const dirs = yield* config.directories()
const matches = dirs.flatMap((dir) =>
Glob.scanSync("{tool,tools}/*.{js,ts}", { cwd: dir, absolute: true, dot: true, symlink: true }),
)
if (matches.length) yield* config.waitForDependencies()
for (const match of matches) {
const namespace = path.basename(match, path.extname(match))
const mod = yield* Effect.promise(
() => import(process.platform === "win32" ? match : pathToFileURL(match).href),
)
for (const [id, def] of Object.entries<ToolDefinition>(mod)) {
custom.push(fromPlugin(id === "default" ? namespace : `${namespace}_${id}`, def))
}
}
const plugins = yield* plugin.list()
for (const p of plugins) {
for (const [id, def] of Object.entries(p.tool ?? {})) {
custom.push(fromPlugin(id, def))
}
}
return { custom }
}),
)
// kilocode_change start
const codebase = yield* build(CodebaseSearchTool)
const recall = yield* build(RecallTool)
const suggest = yield* build(SuggestTool)
// kilocode_change end
const invalid = yield* build(InvalidTool)
const ask = yield* build(QuestionTool)
const bash = yield* build(BashTool)
const read = yield* build(ReadTool)
const glob = yield* build(GlobTool)
const grep = yield* build(GrepTool)
const edit = yield* build(EditTool)
const write = yield* build(WriteTool)
const task = yield* build(TaskTool)
const fetch = yield* build(WebFetchTool)
const todo = yield* build(TodoWriteTool)
const search = yield* build(WebSearchTool)
const code = yield* build(CodeSearchTool)
const skill = yield* build(SkillTool)
const patch = yield* build(ApplyPatchTool)
const lsp = yield* build(LspTool)
const batch = yield* build(BatchTool)
const plan = yield* build(PlanExitTool)
const all = Effect.fn("ToolRegistry.all")(function* (custom: Tool.Info[]) {
const cfg = yield* config.get()
// kilocode_change start
const question =
["app", "cli", "desktop", "vscode"].includes(Flag.KILO_CLIENT) || Flag.KILO_ENABLE_QUESTION_TOOL
// kilocode_change end
return [
invalid,
...(question ? [ask] : []),
bash,
read,
glob,
grep,
edit,
write,
task,
fetch,
todo,
search,
code,
skill,
patch,
...(Flag.KILO_EXPERIMENTAL_LSP_TOOL ? [lsp] : []),
...(cfg.experimental?.batch_tool === true ? [batch] : []),
// kilocode_change start - always registered; gated by agent permission instead
// ...(Flag.KILO_EXPERIMENTAL_PLAN_MODE && Flag.KILO_CLIENT === "cli" ? [plan] : []),
plan,
// killocode_change end
// kilocode_change start
...(cfg.experimental?.codebase_search === true ? [codebase] : []),
recall,
...(["cli", "vscode"].includes(Flag.KILO_CLIENT) ? [suggest] : []),
// kilocode_change end
...custom,
]
})
const ids = Effect.fn("ToolRegistry.ids")(function* () {
const s = yield* InstanceState.get(state)
const tools = yield* all(s.custom)
return tools.map((t) => t.id)
})
const tools = Effect.fn("ToolRegistry.tools")(function* (
model: { providerID: ProviderID; modelID: ModelID },
agent?: Agent.Info,
) {
const s = yield* InstanceState.get(state)
const allTools = yield* all(s.custom)
const filtered = allTools.filter((tool) => {
if (tool.id === "codesearch" || tool.id === "websearch") {
return model.providerID === ProviderID.kilo || Flag.KILO_ENABLE_EXA
}
const usePatch =
!!Env.get("KILO_E2E_LLM_URL") ||
(model.modelID.includes("gpt-") && !model.modelID.includes("oss") && !model.modelID.includes("gpt-4"))
if (tool.id === "apply_patch") return usePatch
if (tool.id === "edit" || tool.id === "write") return !usePatch
return true
})
return yield* Effect.forEach(
filtered,
Effect.fnUntraced(function* (tool: Tool.Info) {
using _ = log.time(tool.id)
const next = yield* Effect.promise(() => tool.init({ agent }))
const output = {
description: next.description,
parameters: next.parameters,
}
yield* plugin.trigger("tool.definition", { toolID: tool.id }, output)
return {
id: tool.id,
description: output.description,
parameters: output.parameters,
execute: next.execute,
formatValidationError: next.formatValidationError,
}
}),
{ concurrency: "unbounded" },
const dirs = yield* config.directories()
const matches = dirs.flatMap((dir) =>
Glob.scanSync("{tool,tools}/*.{js,ts}", { cwd: dir, absolute: true, dot: true, symlink: true }),
)
})
if (matches.length) yield* config.waitForDependencies()
for (const match of matches) {
const namespace = path.basename(match, path.extname(match))
const mod = yield* Effect.promise(
() => import(process.platform === "win32" ? match : pathToFileURL(match).href),
)
for (const [id, def] of Object.entries<ToolDefinition>(mod)) {
custom.push(fromPlugin(id === "default" ? namespace : `${namespace}_${id}`, def))
}
}
return Service.of({ ids, named: { task, read }, tools })
}),
)
const plugins = yield* plugin.list()
for (const p of plugins) {
for (const [id, def] of Object.entries(p.tool ?? {})) {
custom.push(fromPlugin(id, def))
}
}
return { custom }
}),
)
const invalid = yield* build(InvalidTool)
const ask = yield* build(QuestionTool)
const bash = yield* build(BashTool)
const read = yield* build(ReadTool)
const glob = yield* build(GlobTool)
const grep = yield* build(GrepTool)
const edit = yield* build(EditTool)
const write = yield* build(WriteTool)
const task = yield* build(TaskTool)
const fetch = yield* build(WebFetchTool)
const todo = yield* build(TodoWriteTool)
const search = yield* build(WebSearchTool)
const code = yield* build(CodeSearchTool)
const skill = yield* build(SkillTool)
const patch = yield* build(ApplyPatchTool)
const lsp = yield* build(LspTool)
const batch = yield* build(BatchTool)
const plan = yield* build(PlanExitTool)
const kilo = yield* KiloToolRegistry.build(build) // kilocode_change
const all = Effect.fn("ToolRegistry.all")(function* (custom: Tool.Info[]) {
const cfg = yield* config.get()
const question = KiloToolRegistry.question() // kilocode_change
return [
invalid,
...(question ? [ask] : []),
bash,
read,
glob,
grep,
edit,
write,
task,
fetch,
todo,
search,
code,
skill,
patch,
...(Flag.KILO_EXPERIMENTAL_LSP_TOOL ? [lsp] : []),
...(cfg.experimental?.batch_tool === true ? [batch] : []),
...KiloToolRegistry.plan(plan), // kilocode_change
...KiloToolRegistry.extra(kilo, cfg), // kilocode_change
...custom,
]
})
const ids = Effect.fn("ToolRegistry.ids")(function* () {
const s = yield* InstanceState.get(state)
const tools = yield* all(s.custom)
return tools.map((t) => t.id)
})
const tools = Effect.fn("ToolRegistry.tools")(function* (
model: { providerID: ProviderID; modelID: ModelID },
agent?: Agent.Info,
) {
const s = yield* InstanceState.get(state)
const allTools = yield* all(s.custom)
const filtered = allTools.filter((tool) => {
if (tool.id === "codesearch" || tool.id === "websearch") {
return KiloToolRegistry.exa(model.providerID) // kilocode_change
}
const usePatch =
KiloToolRegistry.e2e() || // kilocode_change
(model.modelID.includes("gpt-") && !model.modelID.includes("oss") && !model.modelID.includes("gpt-4"))
if (tool.id === "apply_patch") return usePatch
if (tool.id === "edit" || tool.id === "write") return !usePatch
return true
})
return yield* Effect.forEach(
filtered,
Effect.fnUntraced(function* (tool: Tool.Info) {
using _ = log.time(tool.id)
const next = yield* Effect.promise(() => tool.init({ agent }))
const output = {
description: next.description,
parameters: next.parameters,
}
yield* plugin.trigger("tool.definition", { toolID: tool.id }, output)
return {
id: tool.id,
description: output.description,
parameters: output.parameters,
execute: next.execute,
formatValidationError: next.formatValidationError,
}
}),
{ concurrency: "unbounded" },
)
})
return Service.of({ ids, named: { task, read }, tools })
}),
)
export const defaultLayer = Layer.unwrap(
Effect.sync(() =>
@@ -247,6 +243,10 @@ export namespace ToolRegistry {
Layer.provide(Plugin.defaultLayer),
Layer.provide(Question.defaultLayer),
Layer.provide(Todo.defaultLayer),
Layer.provide(LSP.defaultLayer),
Layer.provide(FileTime.defaultLayer),
Layer.provide(Instruction.defaultLayer),
Layer.provide(AppFileSystem.defaultLayer),
),
),
)
@@ -25,6 +25,7 @@ import { Npm } from "../../src/npm"
const emptyAccount = Layer.mock(Account.Service)({
active: () => Effect.succeed(Option.none()),
activeOrg: () => Effect.succeed(Option.none()),
})
const emptyAuth = Layer.mock(Auth.Service)({
@@ -311,6 +312,21 @@ test("resolves env templates in account config with account token", async () =>
active_org_id: OrgID.make("org-1"),
}),
),
activeOrg: () =>
Effect.succeed(
Option.some({
account: {
id: AccountID.make("account-1"),
email: "user@example.com",
url: "https://control.example.com",
active_org_id: OrgID.make("org-1"),
},
org: {
id: OrgID.make("org-1"),
name: "Example Org",
},
}),
),
config: () =>
Effect.succeed(
Option.some({
+48
View File
@@ -9,6 +9,7 @@ import { Global } from "../../src/global"
import { Filesystem } from "../../src/util/filesystem"
const managedConfigDir = process.env.KILO_TEST_MANAGED_CONFIG_DIR!
const wintest = process.platform === "win32" ? test : test.skip
beforeEach(async () => {
await Config.invalidate(true)
@@ -445,6 +446,53 @@ test("merges keybind overrides across precedence layers", async () => {
})
})
wintest("defaults Ctrl+Z to input undo on Windows", async () => {
await using tmp = await tmpdir()
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await TuiConfig.get()
expect(config.keybinds?.terminal_suspend).toBe("none")
expect(config.keybinds?.input_undo).toBe("ctrl+z,ctrl+-,super+z")
},
})
})
wintest("keeps explicit input undo overrides on Windows", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "tui.json"), JSON.stringify({ keybinds: { input_undo: "ctrl+y" } }))
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await TuiConfig.get()
expect(config.keybinds?.terminal_suspend).toBe("none")
expect(config.keybinds?.input_undo).toBe("ctrl+y")
},
})
})
wintest("ignores terminal suspend bindings on Windows", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "tui.json"), JSON.stringify({ keybinds: { terminal_suspend: "alt+z" } }))
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await TuiConfig.get()
expect(config.keybinds?.terminal_suspend).toBe("none")
expect(config.keybinds?.input_undo).toBe("ctrl+z,ctrl+-,super+z")
},
})
})
test("KILO_TUI_CONFIG provides settings when no project config exists", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
@@ -0,0 +1,46 @@
import { afterEach, describe, expect, test } from "bun:test"
import { Instance } from "../../src/project/instance"
import { ProjectTable } from "../../src/project/project.sql"
import { ProjectID } from "../../src/project/schema"
import { Session } from "../../src/session"
import { SessionTable } from "../../src/session/session.sql"
import { Database, eq } from "../../src/storage/db"
import { Log } from "../../src/util/log"
import { tmpdir } from "../fixture/fixture"
Log.init({ print: false })
afterEach(async () => {
await Instance.disposeAll()
})
describe("Kilo Session.list", () => {
test("includes directory matches from legacy project ids", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const session = await Session.create({ title: "legacy-session" })
const project = ProjectID.make("legacy-project")
Database.use((db) => {
db.insert(ProjectTable)
.values({
id: project,
worktree: tmp.path,
vcs: "git",
time_created: Date.now(),
time_updated: Date.now(),
sandboxes: [],
})
.run()
db.update(SessionTable).set({ project_id: project }).where(eq(SessionTable.id, session.id)).run()
})
const sessions = [...Session.list({ directory: tmp.path })]
const ids = sessions.map((item) => item.id)
expect(ids).toContain(session.id)
},
})
})
})
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, test } from "bun:test"
import { Npm } from "../src/npm"
const win = process.platform === "win32"
describe("Npm.sanitize", () => {
test("keeps normal scoped package specs unchanged", () => {
expect(Npm.sanitize("@opencode/acme")).toBe("@opencode/acme")
expect(Npm.sanitize("@opencode/acme@1.0.0")).toBe("@opencode/acme@1.0.0")
expect(Npm.sanitize("prettier")).toBe("prettier")
})
test("handles git https specs", () => {
const spec = "acme@git+https://github.com/opencode/acme.git"
const expected = win ? "acme@git+https_//github.com/opencode/acme.git" : spec
expect(Npm.sanitize(spec)).toBe(expected)
})
})
@@ -0,0 +1,88 @@
import { describe, expect, test } from "bun:test"
import { parsePluginSpecifier } from "../../src/plugin/shared"
describe("parsePluginSpecifier", () => {
test("parses standard npm package without version", () => {
expect(parsePluginSpecifier("acme")).toEqual({
pkg: "acme",
version: "latest",
})
})
test("parses standard npm package with version", () => {
expect(parsePluginSpecifier("acme@1.0.0")).toEqual({
pkg: "acme",
version: "1.0.0",
})
})
test("parses scoped npm package without version", () => {
expect(parsePluginSpecifier("@opencode/acme")).toEqual({
pkg: "@opencode/acme",
version: "latest",
})
})
test("parses scoped npm package with version", () => {
expect(parsePluginSpecifier("@opencode/acme@1.0.0")).toEqual({
pkg: "@opencode/acme",
version: "1.0.0",
})
})
test("parses package with git+https url", () => {
expect(parsePluginSpecifier("acme@git+https://github.com/opencode/acme.git")).toEqual({
pkg: "acme",
version: "git+https://github.com/opencode/acme.git",
})
})
test("parses scoped package with git+https url", () => {
expect(parsePluginSpecifier("@opencode/acme@git+https://github.com/opencode/acme.git")).toEqual({
pkg: "@opencode/acme",
version: "git+https://github.com/opencode/acme.git",
})
})
test("parses package with git+ssh url containing another @", () => {
expect(parsePluginSpecifier("acme@git+ssh://git@github.com/opencode/acme.git")).toEqual({
pkg: "acme",
version: "git+ssh://git@github.com/opencode/acme.git",
})
})
test("parses scoped package with git+ssh url containing another @", () => {
expect(parsePluginSpecifier("@opencode/acme@git+ssh://git@github.com/opencode/acme.git")).toEqual({
pkg: "@opencode/acme",
version: "git+ssh://git@github.com/opencode/acme.git",
})
})
test("parses unaliased git+ssh url", () => {
expect(parsePluginSpecifier("git+ssh://git@github.com/opencode/acme.git")).toEqual({
pkg: "git+ssh://git@github.com/opencode/acme.git",
version: "",
})
})
test("parses npm alias using the alias name", () => {
expect(parsePluginSpecifier("acme@npm:@opencode/acme@1.0.0")).toEqual({
pkg: "acme",
version: "npm:@opencode/acme@1.0.0",
})
})
test("parses bare npm protocol specifier using the target package", () => {
expect(parsePluginSpecifier("npm:@opencode/acme@1.0.0")).toEqual({
pkg: "@opencode/acme",
version: "1.0.0",
})
})
test("parses unversioned npm protocol specifier", () => {
expect(parsePluginSpecifier("npm:@opencode/acme")).toEqual({
pkg: "@opencode/acme",
version: "latest",
})
})
})
@@ -1080,7 +1080,7 @@ describe("session.getUsage", () => {
expect(result.tokens.cache.read).toBe(200)
})
test("handles reasoning tokens", () => {
test("separates reasoning tokens from output tokens", () => {
const model = createModel({ context: 100_000, output: 32_000 })
const result = Session.getUsage({
model,
@@ -1092,7 +1092,35 @@ describe("session.getUsage", () => {
},
})
expect(result.tokens.input).toBe(1000)
expect(result.tokens.output).toBe(400)
expect(result.tokens.reasoning).toBe(100)
expect(result.tokens.total).toBe(1500)
})
test("does not double count reasoning tokens in cost", () => {
const model = createModel({
context: 100_000,
output: 32_000,
cost: {
input: 0,
output: 15,
cache: { read: 0, write: 0 },
},
})
const result = Session.getUsage({
model,
usage: {
inputTokens: 0,
outputTokens: 1_000_000,
totalTokens: 1_000_000,
reasoningTokens: 250_000,
},
})
expect(result.tokens.output).toBe(750_000)
expect(result.tokens.reasoning).toBe(250_000)
expect(result.cost).toBe(15)
})
test("handles undefined optional values gracefully", () => {
@@ -1,3 +1,4 @@
// kilocode_change - all agent: "build" references renamed to agent: "code"
import { NodeFileSystem } from "@effect/platform-node"
import { expect, spyOn } from "bun:test"
import { Cause, Effect, Exit, Fiber, Layer } from "effect"
@@ -241,7 +242,7 @@ const user = Effect.fn("test.user")(function* (sessionID: SessionID, text: strin
id: MessageID.ascending(),
role: "user",
sessionID,
agent: "build",
agent: "code",
model: ref,
time: { created: Date.now() },
})
@@ -264,7 +265,7 @@ const seed = Effect.fn("test.seed")(function* (sessionID: SessionID, opts?: { fi
parentID: msg.id,
sessionID,
mode: "build",
agent: "build",
agent: "code",
cost: 0,
path: { cwd: "/tmp", root: "/tmp" },
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
@@ -336,7 +337,7 @@ it.live("loop calls LLM and returns assistant message", () =>
})
yield* prompt.prompt({
sessionID: chat.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello" }],
})
@@ -365,7 +366,7 @@ it.live("static loop returns assistant text through local provider", () =>
yield* Effect.promise(() =>
SessionPrompt.prompt({
sessionID: session.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello" }],
}),
@@ -396,7 +397,7 @@ it.live("static loop consumes queued replies across turns", () =>
yield* Effect.promise(() =>
SessionPrompt.prompt({
sessionID: session.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello one" }],
}),
@@ -411,7 +412,7 @@ it.live("static loop consumes queued replies across turns", () =>
yield* Effect.promise(() =>
SessionPrompt.prompt({
sessionID: session.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello two" }],
}),
@@ -441,7 +442,7 @@ it.live("loop continues when finish is tool-calls", () =>
})
yield* prompt.prompt({
sessionID: session.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello" }],
})
@@ -471,7 +472,7 @@ it.live("loop continues when finish is stop but assistant has tool parts", () =>
})
yield* prompt.prompt({
sessionID: session.id,
agent: "build",
agent: "code",
noReply: true,
parts: [{ type: "text", text: "hello" }],
})
@@ -775,7 +776,7 @@ it.live(
const a = yield* prompt
.prompt({
sessionID: chat.id,
agent: "build",
agent: "code",
model: ref,
parts: [{ type: "text", text: "first" }],
})
@@ -788,7 +789,7 @@ it.live(
.prompt({
sessionID: chat.id,
messageID: id,
agent: "build",
agent: "code",
model: ref,
parts: [{ type: "text", text: "second" }],
})
@@ -888,7 +889,7 @@ it.live(
const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
yield* llm.wait(1)
const exit = yield* prompt.shell({ sessionID: chat.id, agent: "build", command: "echo hi" }).pipe(Effect.exit)
const exit = yield* prompt.shell({ sessionID: chat.id, agent: "code", command: "echo hi" }).pipe(Effect.exit)
expect(Exit.isFailure(exit)).toBe(true)
if (Exit.isFailure(exit)) {
expect(Cause.squash(exit.cause)).toBeInstanceOf(Session.BusyError)
@@ -909,7 +910,7 @@ unix("shell captures stdout and stderr in completed tool output", () =>
const { prompt, chat } = yield* boot()
const result = yield* prompt.shell({
sessionID: chat.id,
agent: "build",
agent: "code",
command: "printf out && printf err >&2",
})
@@ -934,7 +935,7 @@ unix("shell completes a fast command on the preferred shell", () =>
const { prompt, chat } = yield* boot()
const result = yield* prompt.shell({
sessionID: chat.id,
agent: "build",
agent: "code",
command: "pwd",
})
@@ -960,7 +961,7 @@ unix("shell lists files from the project directory", () =>
const result = yield* prompt.shell({
sessionID: chat.id,
agent: "build",
agent: "code",
command: "command ls",
})
@@ -984,7 +985,7 @@ unix("shell captures stderr from a failing command", () =>
const { prompt, chat } = yield* boot()
const result = yield* prompt.shell({
sessionID: chat.id,
agent: "build",
agent: "code",
command: "command -v __nonexistent_cmd_e2e__ || echo 'not found' >&2; exit 1",
})
@@ -1010,7 +1011,7 @@ unix(
const { prompt, chat } = yield* boot()
const fiber = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "printf first && sleep 0.2 && printf second" })
.shell({ sessionID: chat.id, agent: "code", command: "printf first && sleep 0.2 && printf second" })
.pipe(Effect.forkChild)
yield* Effect.promise(async () => {
@@ -1048,7 +1049,7 @@ it.live(
yield* llm.text("after-shell")
const sh = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "sleep 0.2" })
.shell({ sessionID: chat.id, agent: "code", command: "sleep 0.2" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
@@ -1086,7 +1087,7 @@ it.live(
yield* llm.text("done")
const sh = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "sleep 0.2" })
.shell({ sessionID: chat.id, agent: "code", command: "sleep 0.2" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
@@ -1122,7 +1123,7 @@ unix(
const { prompt, chat } = yield* boot()
const sh = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "sleep 30" })
.shell({ sessionID: chat.id, agent: "code", command: "sleep 30" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
@@ -1159,7 +1160,7 @@ unix(
const { prompt, chat } = yield* boot()
const sh = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "trap '' TERM; sleep 30" })
.shell({ sessionID: chat.id, agent: "code", command: "trap '' TERM; sleep 30" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
@@ -1190,7 +1191,7 @@ unix(
const { prompt, chat } = yield* boot()
const sh = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "sleep 30" })
.shell({ sessionID: chat.id, agent: "code", command: "sleep 30" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
@@ -1219,12 +1220,12 @@ unix(
const { prompt, chat } = yield* boot()
const a = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "sleep 30" })
.shell({ sessionID: chat.id, agent: "code", command: "sleep 30" })
.pipe(Effect.forkChild)
yield* Effect.sleep(50)
const exit = yield* prompt
.shell({ sessionID: chat.id, agent: "build", command: "echo hi" })
.shell({ sessionID: chat.id, agent: "code", command: "echo hi" })
.pipe(Effect.exit)
expect(Exit.isFailure(exit)).toBe(true)
if (Exit.isFailure(exit)) {
+390 -468
View File
@@ -1,12 +1,20 @@
import { afterEach, describe, expect, test } from "bun:test"
import { afterEach, describe, expect } from "bun:test"
import { Cause, Effect, Exit, Layer } from "effect"
import path from "path"
import { ReadTool } from "../../src/tool/read"
import { Instance } from "../../src/project/instance"
import { Filesystem } from "../../src/util/filesystem"
import { tmpdir } from "../fixture/fixture"
import { Permission } from "../../src/permission"
import { Agent } from "../../src/agent/agent"
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
import { AppFileSystem } from "../../src/filesystem"
import { FileTime } from "../../src/file/time"
import { LSP } from "../../src/lsp"
import { Permission } from "../../src/permission"
import { Instance } from "../../src/project/instance"
import { SessionID, MessageID } from "../../src/session/schema"
import { Instruction } from "../../src/session/instruction"
import { ReadTool } from "../../src/tool/read"
import { Tool } from "../../src/tool/tool"
import { Filesystem } from "../../src/util/filesystem"
import { provideInstance, tmpdirScoped } from "../fixture/fixture"
import { testEffect } from "../lib/effect"
const FIXTURES_DIR = path.join(import.meta.dir, "fixtures")
@@ -25,173 +33,171 @@ const ctx = {
ask: async () => {},
}
const it = testEffect(
Layer.mergeAll(
Agent.defaultLayer,
AppFileSystem.defaultLayer,
CrossSpawnSpawner.defaultLayer,
FileTime.defaultLayer,
Instruction.defaultLayer,
LSP.defaultLayer,
),
)
const init = Effect.fn("ReadToolTest.init")(function* () {
const info = yield* ReadTool
return yield* Effect.promise(() => info.init())
})
const run = Effect.fn("ReadToolTest.run")(function* (
args: Tool.InferParameters<typeof ReadTool>,
next: Tool.Context = ctx,
) {
const tool = yield* init()
return yield* Effect.promise(() => tool.execute(args, next))
})
const exec = Effect.fn("ReadToolTest.exec")(function* (
dir: string,
args: Tool.InferParameters<typeof ReadTool>,
next: Tool.Context = ctx,
) {
return yield* provideInstance(dir)(run(args, next))
})
const fail = Effect.fn("ReadToolTest.fail")(function* (
dir: string,
args: Tool.InferParameters<typeof ReadTool>,
next: Tool.Context = ctx,
) {
const exit = yield* exec(dir, args, next).pipe(Effect.exit)
if (Exit.isFailure(exit)) {
const err = Cause.squash(exit.cause)
return err instanceof Error ? err : new Error(String(err))
}
throw new Error("expected read to fail")
})
const full = (p: string) => (process.platform === "win32" ? Filesystem.normalizePath(p) : p)
const glob = (p: string) =>
process.platform === "win32" ? Filesystem.normalizePathPattern(p) : p.replaceAll("\\", "/")
const put = Effect.fn("ReadToolTest.put")(function* (p: string, content: string | Buffer | Uint8Array) {
const fs = yield* AppFileSystem.Service
yield* fs.writeWithDirs(p, content)
})
const load = Effect.fn("ReadToolTest.load")(function* (p: string) {
const fs = yield* AppFileSystem.Service
return yield* fs.readFileString(p)
})
const asks = () => {
const items: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
return {
items,
next: {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
items.push(req)
},
},
}
}
describe("tool.read external_directory permission", () => {
test("allows reading absolute path inside project directory", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "test.txt"), "hello world")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "test.txt") }, ctx)
expect(result.output).toContain("hello world")
},
})
})
it.live("allows reading absolute path inside project directory", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "test.txt"), "hello world")
test("allows reading file in subdirectory inside project directory", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "subdir", "test.txt"), "nested content")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "subdir", "test.txt") }, ctx)
expect(result.output).toContain("nested content")
},
})
})
const result = yield* exec(dir, { filePath: path.join(dir, "test.txt") })
expect(result.output).toContain("hello world")
}),
)
test("asks for external_directory permission when reading absolute path outside project", async () => {
await using outerTmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "secret.txt"), "secret data")
},
})
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const testCtx = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
requests.push(req)
},
}
await read.execute({ filePath: path.join(outerTmp.path, "secret.txt") }, testCtx)
const extDirReq = requests.find((r) => r.permission === "external_directory")
expect(extDirReq).toBeDefined()
expect(extDirReq!.patterns).toContain(glob(path.join(outerTmp.path, "*")))
},
})
})
it.live("allows reading file in subdirectory inside project directory", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "subdir", "test.txt"), "nested content")
const result = yield* exec(dir, { filePath: path.join(dir, "subdir", "test.txt") })
expect(result.output).toContain("nested content")
}),
)
it.live("asks for external_directory permission when reading absolute path outside project", () =>
Effect.gen(function* () {
const outer = yield* tmpdirScoped()
const dir = yield* tmpdirScoped({ git: true })
yield* put(path.join(outer, "secret.txt"), "secret data")
const { items, next } = asks()
yield* exec(dir, { filePath: path.join(outer, "secret.txt") }, next)
const ext = items.find((item) => item.permission === "external_directory")
expect(ext).toBeDefined()
expect(ext!.patterns).toContain(glob(path.join(outer, "*")))
}),
)
if (process.platform === "win32") {
test("normalizes read permission paths on Windows", async () => {
await using tmp = await tmpdir({
git: true,
init: async (dir) => {
await Bun.write(path.join(dir, "test.txt"), "hello world")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const testCtx = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
requests.push(req)
},
}
const target = path.join(tmp.path, "test.txt")
const alt = target
.replace(/^[A-Za-z]:/, "")
.replaceAll("\\", "/")
.toLowerCase()
await read.execute({ filePath: alt }, testCtx)
const readReq = requests.find((r) => r.permission === "read")
expect(readReq).toBeDefined()
expect(readReq!.patterns).toEqual([full(target)])
},
})
})
it.live("normalizes read permission paths on Windows", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped({ git: true })
yield* put(path.join(dir, "test.txt"), "hello world")
const { items, next } = asks()
const target = path.join(dir, "test.txt")
const alt = target
.replace(/^[A-Za-z]:/, "")
.replaceAll("\\", "/")
.toLowerCase()
yield* exec(dir, { filePath: alt }, next)
const read = items.find((item) => item.permission === "read")
expect(read).toBeDefined()
expect(read!.patterns).toEqual([full(target)])
}),
)
}
test("asks for directory-scoped external_directory permission when reading external directory", async () => {
await using outerTmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "external", "a.txt"), "a")
},
})
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const testCtx = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
requests.push(req)
},
}
await read.execute({ filePath: path.join(outerTmp.path, "external") }, testCtx)
const extDirReq = requests.find((r) => r.permission === "external_directory")
expect(extDirReq).toBeDefined()
expect(extDirReq!.patterns).toContain(glob(path.join(outerTmp.path, "external", "*")))
},
})
})
it.live("asks for directory-scoped external_directory permission when reading external directory", () =>
Effect.gen(function* () {
const outer = yield* tmpdirScoped()
const dir = yield* tmpdirScoped({ git: true })
yield* put(path.join(outer, "external", "a.txt"), "a")
test("asks for external_directory permission when reading relative path outside project", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const testCtx = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
requests.push(req)
},
}
// This will fail because file doesn't exist, but we can check if permission was asked
await read.execute({ filePath: "../outside.txt" }, testCtx).catch(() => {})
const extDirReq = requests.find((r) => r.permission === "external_directory")
expect(extDirReq).toBeDefined()
},
})
})
const { items, next } = asks()
test("does not ask for external_directory permission when reading inside project", async () => {
await using tmp = await tmpdir({
git: true,
init: async (dir) => {
await Bun.write(path.join(dir, "internal.txt"), "internal content")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const testCtx = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
requests.push(req)
},
}
await read.execute({ filePath: path.join(tmp.path, "internal.txt") }, testCtx)
const extDirReq = requests.find((r) => r.permission === "external_directory")
expect(extDirReq).toBeUndefined()
},
})
})
yield* exec(dir, { filePath: path.join(outer, "external") }, next)
const ext = items.find((item) => item.permission === "external_directory")
expect(ext).toBeDefined()
expect(ext!.patterns).toContain(glob(path.join(outer, "external", "*")))
}),
)
it.live("asks for external_directory permission when reading relative path outside project", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped({ git: true })
const { items, next } = asks()
yield* fail(dir, { filePath: "../outside.txt" }, next)
const ext = items.find((item) => item.permission === "external_directory")
expect(ext).toBeDefined()
}),
)
it.live("does not ask for external_directory permission when reading inside project", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped({ git: true })
yield* put(path.join(dir, "internal.txt"), "internal content")
const { items, next } = asks()
yield* exec(dir, { filePath: path.join(dir, "internal.txt") }, next)
const ext = items.find((item) => item.permission === "external_directory")
expect(ext).toBeUndefined()
}),
)
})
describe("tool.read env file permissions", () => {
@@ -206,262 +212,205 @@ describe("tool.read env file permissions", () => {
]
// kilocode_change start - renamed from "build" to "code"
describe.each(["code", "plan"])("agent=%s", (agentName) => {
// kilocode_change end
test.each(cases)("%s asks=%s", async (filename, shouldAsk) => {
await using tmp = await tmpdir({
init: (dir) => Bun.write(path.join(dir, filename), "content"),
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agent = await Agent.get(agentName)
let askedForEnv = false
const ctxWithPermissions = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
for (const pattern of req.patterns) {
const rule = Permission.evaluate(req.permission, pattern, agent.permission)
if (rule.action === "ask" && req.permission === "read") {
askedForEnv = true
for (const agentName of ["code", "plan"] as const) {
// kilocode_change end
describe(`agent=${agentName}`, () => {
for (const [filename, shouldAsk] of cases) {
it.live(`${filename} asks=${shouldAsk}`, () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, filename), "content")
const asked = yield* provideInstance(dir)(
Effect.gen(function* () {
const agent = yield* Agent.Service
const info = yield* agent.get(agentName)
let asked = false
const next = {
...ctx,
ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
for (const pattern of req.patterns) {
const rule = Permission.evaluate(req.permission, pattern, info.permission)
if (rule.action === "ask" && req.permission === "read") {
asked = true
}
if (rule.action === "deny") {
throw new Permission.DeniedError({ ruleset: info.permission })
}
}
},
}
if (rule.action === "deny") {
throw new Permission.DeniedError({ ruleset: agent.permission })
}
}
},
}
const read = await ReadTool.init()
await read.execute({ filePath: path.join(tmp.path, filename) }, ctxWithPermissions)
expect(askedForEnv).toBe(shouldAsk)
},
})
yield* run({ filePath: path.join(dir, filename) }, next)
return asked
}),
)
expect(asked).toBe(shouldAsk)
}),
)
}
})
})
}
})
describe("tool.read truncation", () => {
test("truncates large file by bytes and sets truncated metadata", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const base = await Filesystem.readText(path.join(FIXTURES_DIR, "models-api.json"))
const target = 60 * 1024
const content = base.length >= target ? base : base.repeat(Math.ceil(target / base.length))
await Filesystem.write(path.join(dir, "large.json"), content)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "large.json") }, ctx)
expect(result.metadata.truncated).toBe(true)
expect(result.output).toContain("Output capped at")
expect(result.output).toContain("Use offset=")
},
})
})
it.live("truncates large file by bytes and sets truncated metadata", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const base = yield* load(path.join(FIXTURES_DIR, "models-api.json"))
const target = 60 * 1024
const content = base.length >= target ? base : base.repeat(Math.ceil(target / base.length))
yield* put(path.join(dir, "large.json"), content)
test("truncates by line count when limit is specified", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const lines = Array.from({ length: 100 }, (_, i) => `line${i}`).join("\n")
await Bun.write(path.join(dir, "many-lines.txt"), lines)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "many-lines.txt"), limit: 10 }, ctx)
expect(result.metadata.truncated).toBe(true)
expect(result.output).toContain("Showing lines 1-10 of 100")
expect(result.output).toContain("Use offset=11")
expect(result.output).toContain("line0")
expect(result.output).toContain("line9")
expect(result.output).not.toContain("line10")
},
})
})
const result = yield* exec(dir, { filePath: path.join(dir, "large.json") })
expect(result.metadata.truncated).toBe(true)
expect(result.output).toContain("Output capped at")
expect(result.output).toContain("Use offset=")
}),
)
test("does not truncate small file", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "small.txt"), "hello world")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "small.txt") }, ctx)
expect(result.metadata.truncated).toBe(false)
expect(result.output).toContain("End of file")
},
})
})
it.live("truncates by line count when limit is specified", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const lines = Array.from({ length: 100 }, (_, i) => `line${i}`).join("\n")
yield* put(path.join(dir, "many-lines.txt"), lines)
test("respects offset parameter", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const lines = Array.from({ length: 20 }, (_, i) => `line${i + 1}`).join("\n")
await Bun.write(path.join(dir, "offset.txt"), lines)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "offset.txt"), offset: 10, limit: 5 }, ctx)
expect(result.output).toContain("10: line10")
expect(result.output).toContain("14: line14")
expect(result.output).not.toContain("9: line10")
expect(result.output).not.toContain("15: line15")
expect(result.output).toContain("line10")
expect(result.output).toContain("line14")
expect(result.output).not.toContain("line0")
expect(result.output).not.toContain("line15")
},
})
})
const result = yield* exec(dir, { filePath: path.join(dir, "many-lines.txt"), limit: 10 })
expect(result.metadata.truncated).toBe(true)
expect(result.output).toContain("Showing lines 1-10 of 100")
expect(result.output).toContain("Use offset=11")
expect(result.output).toContain("line0")
expect(result.output).toContain("line9")
expect(result.output).not.toContain("line10")
}),
)
test("throws when offset is beyond end of file", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const lines = Array.from({ length: 3 }, (_, i) => `line${i + 1}`).join("\n")
await Bun.write(path.join(dir, "short.txt"), lines)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
await expect(
read.execute({ filePath: path.join(tmp.path, "short.txt"), offset: 4, limit: 5 }, ctx),
).rejects.toThrow("Offset 4 is out of range for this file (3 lines)")
},
})
})
it.live("does not truncate small file", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "small.txt"), "hello world")
test("allows reading empty file at default offset", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "empty.txt"), "")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "empty.txt") }, ctx)
expect(result.metadata.truncated).toBe(false)
expect(result.output).toContain("End of file - total 0 lines")
},
})
})
const result = yield* exec(dir, { filePath: path.join(dir, "small.txt") })
expect(result.metadata.truncated).toBe(false)
expect(result.output).toContain("End of file")
}),
)
test("throws when offset > 1 for empty file", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "empty.txt"), "")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
await expect(read.execute({ filePath: path.join(tmp.path, "empty.txt"), offset: 2 }, ctx)).rejects.toThrow(
"Offset 2 is out of range for this file (0 lines)",
)
},
})
})
it.live("respects offset parameter", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const lines = Array.from({ length: 20 }, (_, i) => `line${i + 1}`).join("\n")
yield* put(path.join(dir, "offset.txt"), lines)
test("does not mark final directory page as truncated", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Promise.all(
Array.from({ length: 10 }, (_, i) => Bun.write(path.join(dir, "dir", `file-${i + 1}.txt`), `line${i}`)),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "dir"), offset: 6, limit: 5 }, ctx)
expect(result.metadata.truncated).toBe(false)
expect(result.output).not.toContain("Showing 5 of 10 entries")
},
})
})
const result = yield* exec(dir, { filePath: path.join(dir, "offset.txt"), offset: 10, limit: 5 })
expect(result.output).toContain("10: line10")
expect(result.output).toContain("14: line14")
expect(result.output).not.toContain("9: line10")
expect(result.output).not.toContain("15: line15")
expect(result.output).toContain("line10")
expect(result.output).toContain("line14")
expect(result.output).not.toContain("line0")
expect(result.output).not.toContain("line15")
}),
)
test("truncates long lines", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const longLine = "x".repeat(3000)
await Bun.write(path.join(dir, "long-line.txt"), longLine)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "long-line.txt") }, ctx)
expect(result.output).toContain("(line truncated to 2000 chars)")
expect(result.output.length).toBeLessThan(3000)
},
})
})
it.live("throws when offset is beyond end of file", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const lines = Array.from({ length: 3 }, (_, i) => `line${i + 1}`).join("\n")
yield* put(path.join(dir, "short.txt"), lines)
test("image files set truncated to false", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
// 1x1 red PNG
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==",
"base64",
)
await Bun.write(path.join(dir, "image.png"), png)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "image.png") }, ctx)
expect(result.metadata.truncated).toBe(false)
expect(result.attachments).toBeDefined()
expect(result.attachments?.length).toBe(1)
expect(result.attachments?.[0]).not.toHaveProperty("id")
expect(result.attachments?.[0]).not.toHaveProperty("sessionID")
expect(result.attachments?.[0]).not.toHaveProperty("messageID")
},
})
})
const err = yield* fail(dir, { filePath: path.join(dir, "short.txt"), offset: 4, limit: 5 })
expect(err.message).toContain("Offset 4 is out of range for this file (3 lines)")
}),
)
test("large image files are properly attached without error", async () => {
await Instance.provide({
directory: FIXTURES_DIR,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(FIXTURES_DIR, "large-image.png") }, ctx)
expect(result.metadata.truncated).toBe(false)
expect(result.attachments).toBeDefined()
expect(result.attachments?.length).toBe(1)
expect(result.attachments?.[0].type).toBe("file")
expect(result.attachments?.[0]).not.toHaveProperty("id")
expect(result.attachments?.[0]).not.toHaveProperty("sessionID")
expect(result.attachments?.[0]).not.toHaveProperty("messageID")
},
})
})
it.live("allows reading empty file at default offset", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "empty.txt"), "")
test(".fbs files (FlatBuffers schema) are read as text, not images", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
// FlatBuffers schema content
const fbsContent = `namespace MyGame;
const result = yield* exec(dir, { filePath: path.join(dir, "empty.txt") })
expect(result.metadata.truncated).toBe(false)
expect(result.output).toContain("End of file - total 0 lines")
}),
)
it.live("throws when offset > 1 for empty file", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "empty.txt"), "")
const err = yield* fail(dir, { filePath: path.join(dir, "empty.txt"), offset: 2 })
expect(err.message).toContain("Offset 2 is out of range for this file (0 lines)")
}),
)
it.live("does not mark final directory page as truncated", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* Effect.forEach(
Array.from({ length: 10 }, (_, i) => i),
(i) => put(path.join(dir, "dir", `file-${i + 1}.txt`), `line${i}`),
{
concurrency: "unbounded",
},
)
const result = yield* exec(dir, { filePath: path.join(dir, "dir"), offset: 6, limit: 5 })
expect(result.metadata.truncated).toBe(false)
expect(result.output).not.toContain("Showing 5 of 10 entries")
}),
)
it.live("truncates long lines", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "long-line.txt"), "x".repeat(3000))
const result = yield* exec(dir, { filePath: path.join(dir, "long-line.txt") })
expect(result.output).toContain("(line truncated to 2000 chars)")
expect(result.output.length).toBeLessThan(3000)
}),
)
it.live("image files set truncated to false", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==",
"base64",
)
yield* put(path.join(dir, "image.png"), png)
const result = yield* exec(dir, { filePath: path.join(dir, "image.png") })
expect(result.metadata.truncated).toBe(false)
expect(result.attachments).toBeDefined()
expect(result.attachments?.length).toBe(1)
expect(result.attachments?.[0]).not.toHaveProperty("id")
expect(result.attachments?.[0]).not.toHaveProperty("sessionID")
expect(result.attachments?.[0]).not.toHaveProperty("messageID")
}),
)
it.live("large image files are properly attached without error", () =>
Effect.gen(function* () {
const result = yield* exec(FIXTURES_DIR, { filePath: path.join(FIXTURES_DIR, "large-image.png") })
expect(result.metadata.truncated).toBe(false)
expect(result.attachments).toBeDefined()
expect(result.attachments?.length).toBe(1)
expect(result.attachments?.[0].type).toBe("file")
expect(result.attachments?.[0]).not.toHaveProperty("id")
expect(result.attachments?.[0]).not.toHaveProperty("sessionID")
expect(result.attachments?.[0]).not.toHaveProperty("messageID")
}),
)
it.live(".fbs files (FlatBuffers schema) are read as text, not images", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const fbs = `namespace MyGame;
table Monster {
pos:Vec3;
@@ -470,79 +419,52 @@ table Monster {
}
root_type Monster;`
await Bun.write(path.join(dir, "schema.fbs"), fbsContent)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "schema.fbs") }, ctx)
// Should be read as text, not as image
expect(result.attachments).toBeUndefined()
expect(result.output).toContain("namespace MyGame")
expect(result.output).toContain("table Monster")
},
})
})
yield* put(path.join(dir, "schema.fbs"), fbs)
const result = yield* exec(dir, { filePath: path.join(dir, "schema.fbs") })
expect(result.attachments).toBeUndefined()
expect(result.output).toContain("namespace MyGame")
expect(result.output).toContain("table Monster")
}),
)
})
describe("tool.read loaded instructions", () => {
test("loads AGENTS.md from parent directory and includes in metadata", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "subdir", "AGENTS.md"), "# Test Instructions\nDo something special.")
await Bun.write(path.join(dir, "subdir", "nested", "test.txt"), "test content")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
const result = await read.execute({ filePath: path.join(tmp.path, "subdir", "nested", "test.txt") }, ctx)
expect(result.output).toContain("test content")
expect(result.output).toContain("system-reminder")
expect(result.output).toContain("Test Instructions")
expect(result.metadata.loaded).toBeDefined()
expect(result.metadata.loaded).toContain(path.join(tmp.path, "subdir", "AGENTS.md"))
},
})
})
it.live("loads AGENTS.md from parent directory and includes in metadata", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "subdir", "AGENTS.md"), "# Test Instructions\nDo something special.")
yield* put(path.join(dir, "subdir", "nested", "test.txt"), "test content")
const result = yield* exec(dir, { filePath: path.join(dir, "subdir", "nested", "test.txt") })
expect(result.output).toContain("test content")
expect(result.output).toContain("system-reminder")
expect(result.output).toContain("Test Instructions")
expect(result.metadata.loaded).toBeDefined()
expect(result.metadata.loaded).toContain(path.join(dir, "subdir", "AGENTS.md"))
}),
)
})
describe("tool.read binary detection", () => {
test("rejects text extension files with null bytes", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const bytes = Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x77, 0x6f, 0x72, 0x6c, 0x64])
await Bun.write(path.join(dir, "null-byte.txt"), bytes)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
await expect(read.execute({ filePath: path.join(tmp.path, "null-byte.txt") }, ctx)).rejects.toThrow(
"Cannot read binary file",
)
},
})
})
it.live("rejects text extension files with null bytes", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const bytes = Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x77, 0x6f, 0x72, 0x6c, 0x64])
yield* put(path.join(dir, "null-byte.txt"), bytes)
test("rejects known binary extensions", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(path.join(dir, "module.wasm"), "not really wasm")
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const read = await ReadTool.init()
await expect(read.execute({ filePath: path.join(tmp.path, "module.wasm") }, ctx)).rejects.toThrow(
"Cannot read binary file",
)
},
})
})
const err = yield* fail(dir, { filePath: path.join(dir, "null-byte.txt") })
expect(err.message).toContain("Cannot read binary file")
}),
)
it.live("rejects known binary extensions", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
yield* put(path.join(dir, "module.wasm"), "not really wasm")
const err = yield* fail(dir, { filePath: path.join(dir, "module.wasm") })
expect(err.message).toContain("Cannot read binary file")
}),
)
})
+130 -21
View File
@@ -29,6 +29,9 @@ import type {
EventTuiPromptAppend,
EventTuiSessionSelect,
EventTuiToastShow,
ExperimentalConsoleGetResponses,
ExperimentalConsoleListOrgsResponses,
ExperimentalConsoleSwitchOrgResponses,
ExperimentalResourceListResponses,
ExperimentalSessionListResponses,
ExperimentalWorkspaceCreateErrors,
@@ -1071,13 +1074,13 @@ export class Config2 extends HeyApiClient {
}
}
export class Tool extends HeyApiClient {
export class Console extends HeyApiClient {
/**
* List tool IDs
* Get active Console provider metadata
*
* Get a list of all available tool IDs, including both built-in tools and dynamically registered tools.
* Get the active Console org name and the set of provider IDs managed by that Console org.
*/
public ids<ThrowOnError extends boolean = false>(
public get<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
workspace?: string
@@ -1095,24 +1098,22 @@ export class Tool extends HeyApiClient {
},
],
)
return (options?.client ?? this.client).get<ToolIdsResponses, ToolIdsErrors, ThrowOnError>({
url: "/experimental/tool/ids",
return (options?.client ?? this.client).get<ExperimentalConsoleGetResponses, unknown, ThrowOnError>({
url: "/experimental/console",
...options,
...params,
})
}
/**
* List tools
* List switchable Console orgs
*
* Get a list of available tools with their JSON schema parameters for a specific provider and model combination.
* Get the available Console orgs across logged-in accounts, including the current active org.
*/
public list<ThrowOnError extends boolean = false>(
parameters: {
public listOrgs<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
workspace?: string
provider: string
model: string
},
options?: Options<never, ThrowOnError>,
) {
@@ -1123,18 +1124,55 @@ export class Tool extends HeyApiClient {
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
{ in: "query", key: "provider" },
{ in: "query", key: "model" },
],
},
],
)
return (options?.client ?? this.client).get<ToolListResponses, ToolListErrors, ThrowOnError>({
url: "/experimental/tool",
return (options?.client ?? this.client).get<ExperimentalConsoleListOrgsResponses, unknown, ThrowOnError>({
url: "/experimental/console/orgs",
...options,
...params,
})
}
/**
* Switch active Console org
*
* Persist a new active Console account/org selection for the current local OpenCode state.
*/
public switchOrg<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
workspace?: string
accountID?: string
orgID?: string
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
{ in: "body", key: "accountID" },
{ in: "body", key: "orgID" },
],
},
],
)
return (options?.client ?? this.client).post<ExperimentalConsoleSwitchOrgResponses, unknown, ThrowOnError>({
url: "/experimental/console/switch",
...options,
...params,
headers: {
"Content-Type": "application/json",
...options?.headers,
...params.headers,
},
})
}
}
export class Workspace extends HeyApiClient {
@@ -1333,6 +1371,11 @@ export class Resource extends HeyApiClient {
}
export class Experimental extends HeyApiClient {
private _console?: Console
get console(): Console {
return (this._console ??= new Console({ client: this.client }))
}
private _workspace?: Workspace
get workspace(): Workspace {
return (this._workspace ??= new Workspace({ client: this.client }))
@@ -1349,6 +1392,72 @@ export class Experimental extends HeyApiClient {
}
}
export class Tool extends HeyApiClient {
/**
* List tool IDs
*
* Get a list of all available tool IDs, including both built-in tools and dynamically registered tools.
*/
public ids<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
workspace?: string
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
],
},
],
)
return (options?.client ?? this.client).get<ToolIdsResponses, ToolIdsErrors, ThrowOnError>({
url: "/experimental/tool/ids",
...options,
...params,
})
}
/**
* List tools
*
* Get a list of available tools with their JSON schema parameters for a specific provider and model combination.
*/
public list<ThrowOnError extends boolean = false>(
parameters: {
directory?: string
workspace?: string
provider: string
model: string
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
{ in: "query", key: "provider" },
{ in: "query", key: "model" },
],
},
],
)
return (options?.client ?? this.client).get<ToolListResponses, ToolListErrors, ThrowOnError>({
url: "/experimental/tool",
...options,
...params,
})
}
}
export class Worktree extends HeyApiClient {
/**
* Remove worktree
@@ -5620,16 +5729,16 @@ export class KiloClient extends HeyApiClient {
return (this._config ??= new Config2({ client: this.client }))
}
private _tool?: Tool
get tool(): Tool {
return (this._tool ??= new Tool({ client: this.client }))
}
private _experimental?: Experimental
get experimental(): Experimental {
return (this._experimental ??= new Experimental({ client: this.client }))
}
private _tool?: Tool
get tool(): Tool {
return (this._tool ??= new Tool({ client: this.client }))
}
private _worktree?: Worktree
get worktree(): Worktree {
return (this._worktree ??= new Worktree({ client: this.client }))
+78
View File
@@ -1820,6 +1820,9 @@ export type OAuth = {
export type ApiAuth = {
type: "api"
key: string
metadata?: {
[key: string]: string
}
}
export type WellKnownAuth = {
@@ -2882,6 +2885,81 @@ export type ConfigProvidersResponses = {
export type ConfigProvidersResponse = ConfigProvidersResponses[keyof ConfigProvidersResponses]
export type ExperimentalConsoleGetData = {
body?: never
path?: never
query?: {
directory?: string
workspace?: string
}
url: "/experimental/console"
}
export type ExperimentalConsoleGetResponses = {
/**
* Active Console provider metadata
*/
200: {
consoleManagedProviders: Array<string>
activeOrgName?: string
switchableOrgCount: number
}
}
export type ExperimentalConsoleGetResponse = ExperimentalConsoleGetResponses[keyof ExperimentalConsoleGetResponses]
export type ExperimentalConsoleListOrgsData = {
body?: never
path?: never
query?: {
directory?: string
workspace?: string
}
url: "/experimental/console/orgs"
}
export type ExperimentalConsoleListOrgsResponses = {
/**
* Switchable Console orgs
*/
200: {
orgs: Array<{
accountID: string
accountEmail: string
accountUrl: string
orgID: string
orgName: string
active: boolean
}>
}
}
export type ExperimentalConsoleListOrgsResponse =
ExperimentalConsoleListOrgsResponses[keyof ExperimentalConsoleListOrgsResponses]
export type ExperimentalConsoleSwitchOrgData = {
body?: {
accountID: string
orgID: string
}
path?: never
query?: {
directory?: string
workspace?: string
}
url: "/experimental/console/switch"
}
export type ExperimentalConsoleSwitchOrgResponses = {
/**
* Switch success
*/
200: boolean
}
export type ExperimentalConsoleSwitchOrgResponse =
ExperimentalConsoleSwitchOrgResponses[keyof ExperimentalConsoleSwitchOrgResponses]
export type ToolIdsData = {
body?: never
path?: never
+197
View File
@@ -1276,6 +1276,194 @@
]
}
},
"/experimental/console": {
"get": {
"operationId": "experimental.console.get",
"parameters": [
{
"in": "query",
"name": "directory",
"schema": {
"type": "string"
}
},
{
"in": "query",
"name": "workspace",
"schema": {
"type": "string"
}
}
],
"summary": "Get active Console provider metadata",
"description": "Get the active Console org name and the set of provider IDs managed by that Console org.",
"responses": {
"200": {
"description": "Active Console provider metadata",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"consoleManagedProviders": {
"type": "array",
"items": {
"type": "string"
}
},
"activeOrgName": {
"type": "string"
},
"switchableOrgCount": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
}
},
"required": ["consoleManagedProviders", "switchableOrgCount"]
}
}
}
}
},
"x-codeSamples": [
{
"lang": "js",
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.experimental.console.get({\n ...\n})"
}
]
}
},
"/experimental/console/orgs": {
"get": {
"operationId": "experimental.console.listOrgs",
"parameters": [
{
"in": "query",
"name": "directory",
"schema": {
"type": "string"
}
},
{
"in": "query",
"name": "workspace",
"schema": {
"type": "string"
}
}
],
"summary": "List switchable Console orgs",
"description": "Get the available Console orgs across logged-in accounts, including the current active org.",
"responses": {
"200": {
"description": "Switchable Console orgs",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"orgs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"accountID": {
"type": "string"
},
"accountEmail": {
"type": "string"
},
"accountUrl": {
"type": "string"
},
"orgID": {
"type": "string"
},
"orgName": {
"type": "string"
},
"active": {
"type": "boolean"
}
},
"required": ["accountID", "accountEmail", "accountUrl", "orgID", "orgName", "active"]
}
}
},
"required": ["orgs"]
}
}
}
}
},
"x-codeSamples": [
{
"lang": "js",
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.experimental.console.listOrgs({\n ...\n})"
}
]
}
},
"/experimental/console/switch": {
"post": {
"operationId": "experimental.console.switchOrg",
"parameters": [
{
"in": "query",
"name": "directory",
"schema": {
"type": "string"
}
},
{
"in": "query",
"name": "workspace",
"schema": {
"type": "string"
}
}
],
"summary": "Switch active Console org",
"description": "Persist a new active Console account/org selection for the current local OpenCode state.",
"responses": {
"200": {
"description": "Switch success",
"content": {
"application/json": {
"schema": {
"type": "boolean"
}
}
}
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"accountID": {
"type": "string"
},
"orgID": {
"type": "string"
}
},
"required": ["accountID", "orgID"]
}
}
}
},
"x-codeSamples": [
{
"lang": "js",
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.experimental.console.switchOrg({\n ...\n})"
}
]
}
},
"/experimental/tool/ids": {
"get": {
"operationId": "tool.ids",
@@ -15033,6 +15221,15 @@
},
"key": {
"type": "string"
},
"metadata": {
"type": "object",
"propertyNames": {
"type": "string"
},
"additionalProperties": {
"type": "string"
}
}
},
"required": ["type", "key"]