diff --git a/.opencode-version b/.opencode-version index 2bc9bb1ba3e..fff8b777303 100644 --- a/.opencode-version +++ b/.opencode-version @@ -1 +1 @@ -v1.14.51 +v1.15.4 diff --git a/bun.lock b/bun.lock index 51ee026f0d1..2f523ed877e 100644 --- a/bun.lock +++ b/bun.lock @@ -578,9 +578,9 @@ "typescript": "catalog:", }, "peerDependencies": { - "@opentui/core": ">=0.2.10", - "@opentui/keymap": ">=0.2.10", - "@opentui/solid": ">=0.2.10", + "@opentui/core": ">=0.2.11", + "@opentui/keymap": ">=0.2.11", + "@opentui/solid": ">=0.2.11", }, "optionalPeers": [ "@opentui/core", @@ -746,9 +746,9 @@ "@npmcli/arborist": "9.4.0", "@octokit/rest": "22.0.0", "@openauthjs/openauth": "0.0.0-20250322224806", - "@opentui/core": "0.2.10", - "@opentui/keymap": "0.2.10", - "@opentui/solid": "0.2.10", + "@opentui/core": "0.2.11", + "@opentui/keymap": "0.2.11", + "@opentui/solid": "0.2.11", "@pierre/diffs": "1.1.22", "@playwright/test": "1.59.1", "@solid-primitives/storage": "4.3.3", @@ -1591,23 +1591,23 @@ "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.40.0", "", {}, "sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw=="], - "@opentui/core": ["@opentui/core@0.2.10", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.10", "@opentui/core-darwin-x64": "0.2.10", "@opentui/core-linux-arm64": "0.2.10", "@opentui/core-linux-x64": "0.2.10", "@opentui/core-win32-arm64": "0.2.10", "@opentui/core-win32-x64": "0.2.10" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-oviCtx0jYjc7F8X2b8+0IkQLg6WH47Nwl6CFeZo5dU0k6OpSbTbi07ZleObaiECAp+S1YLhAtVdgzHU7hBZlaw=="], + "@opentui/core": ["@opentui/core@0.2.11", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.11", "@opentui/core-darwin-x64": "0.2.11", "@opentui/core-linux-arm64": "0.2.11", "@opentui/core-linux-x64": "0.2.11", "@opentui/core-win32-arm64": "0.2.11", "@opentui/core-win32-x64": "0.2.11" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-X0zLmcDEvMrPzWYp769I7VEVb+og38vaete9tGZXu9HnJgu/paPUUplUT+6denBQccr2qx1rBYV6EtgbBpLEyw=="], - "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+lbDDj42Og+UtTZEwlHhGXichmOlkxSqn0J+Jqjat5/Tt5oZykj1NZjFIQ7ZSz4Miz7EmZwgYKE2CyOmmm9MoQ=="], + "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.11", "", { "os": "darwin", "cpu": "arm64" }, "sha512-h2MXtE2Cu3XlKVoQMXthnbhleO68zGXkoh/r1Q5pCoZh6RuXqns5/94D/aZThXBWwzPuEoyarMlxxR9OqrpvHw=="], - "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.2.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-5iAoA0aqMWWAQ93nh8Bb0ipwt9h+tvEFc88+YO9St43uUJ+XrXcmMj3T8wtl6dSu/SN0UoDWNaUMHUmtykiPtg=="], + "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.2.11", "", { "os": "darwin", "cpu": "x64" }, "sha512-Y0jbPClnOBTPSIy+2THG86MTqIG/jGFlOOKuw4JfCDqEjPBM3pLWIHnJb3WxHRi2LlvfyBxvrUTXWlW6JpI0QQ=="], - "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.2.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-EnrkxgH5K76Oi/Br1UHPZblXG5P60snmtySfnxuVaeECNZrbTkV6BV/A0WoBeWshJweGbx1D+eTF+sEEjQCi8w=="], + "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.2.11", "", { "os": "linux", "cpu": "arm64" }, "sha512-blQyyuTaW4q/OQ3whs7Kt7GCXhBUR5EQHHDdjOqQAr0HYpohUa6sbHMbiBcX2Ehc9ZWwtiaOoWiyZ5YXy2SAvg=="], - "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.2.10", "", { "os": "linux", "cpu": "x64" }, "sha512-fI+r3kCPqIxsWwPVGpKUQy4zHK8y+jkDRCwa3UbaUy48RQ44jMuf2RhVhmi4xmCvSc8UPJBbYsw1tLuh9kmXjg=="], + "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.2.11", "", { "os": "linux", "cpu": "x64" }, "sha512-0nEB5+MgzQRYiVcQd1vHXPWNPWGh4JEmQTJKyG3OHnTzPaJ1FVSQ/V71ECyRSl3ymY3F+U0eW9cFgw1hCieK2w=="], - "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.2.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-8F4z2hIRgkVWcr6CMVeJ9N4+1rmURPt2Pq2GBPko8ch6rxHR+a//KD1MfphyuLTHBS1tJ4vfZSWSoiaESImtrA=="], + "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.2.11", "", { "os": "win32", "cpu": "arm64" }, "sha512-+KKH77fzm0qF8py9G2pU32DzB1bAgDMfBajrs7gKL5NtSEnknrwfh7hIs/tq41aF6j9zvIzgtykByh26tcjFog=="], - "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.2.10", "", { "os": "win32", "cpu": "x64" }, "sha512-Ki+qNBlIFW5K2wcG/RHrlPp7yEQKXeiNX3mlje25iwX62Ac5w391HBpOmUjbPoq20McPyDRnhbLfbXQSPtickg=="], + "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.2.11", "", { "os": "win32", "cpu": "x64" }, "sha512-dMmb9DX0W0HWadLdgciMbonqIc1xdcKiVmaQSYxw5eGCzFRPZIOrKHByesP+2ipkMuLx85W/MJUFal/lW8XSNg=="], - "@opentui/keymap": ["@opentui/keymap@0.2.10", "", { "dependencies": { "@opentui/core": "0.2.10" }, "peerDependencies": { "@opentui/react": "0.2.10", "@opentui/solid": "0.2.10", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-80fU3Lr/98sNIpVYd8PApAeQw8A8D9BemyOGi6jGvTQCl0rxKgvaVBviDRGKxl1INTVjZy9By8UPncc2KJOuWQ=="], + "@opentui/keymap": ["@opentui/keymap@0.2.11", "", { "dependencies": { "@opentui/core": "0.2.11" }, "peerDependencies": { "@opentui/react": "0.2.11", "@opentui/solid": "0.2.11", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-pCrJrY3mTuXdDaaRneId1JsJCtGE+7prTtWihzOLZzVJTJYyYtT38gMI7MpyAoloVDfEL5cTe8C+v7wv+IYREw=="], - "@opentui/solid": ["@opentui/solid@0.2.10", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.2.10", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-+4/MB90yIQiPwg8Y4wY092yva9BvRTsJeeeEO3e2H7P8k8zxYk4G9bzuhqYLxA9mTVQ+zVDlrmFoPQhT7vpIRw=="], + "@opentui/solid": ["@opentui/solid@0.2.11", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.2.11", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-M3WHxBFORHVE0yqMJYpi9PfjXWlnRTw/LYuBhZaJv0HTo+zTs60P/ukGcwnHDWnMpTGf3BH9x0Yi2dIqjHRY6Q=="], "@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="], @@ -5049,6 +5049,10 @@ "openid-client/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], + "opentui-spinner/@opentui/core": ["@opentui/core@0.2.10", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.10", "@opentui/core-darwin-x64": "0.2.10", "@opentui/core-linux-arm64": "0.2.10", "@opentui/core-linux-x64": "0.2.10", "@opentui/core-win32-arm64": "0.2.10", "@opentui/core-win32-x64": "0.2.10" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-oviCtx0jYjc7F8X2b8+0IkQLg6WH47Nwl6CFeZo5dU0k6OpSbTbi07ZleObaiECAp+S1YLhAtVdgzHU7hBZlaw=="], + + "opentui-spinner/@opentui/solid": ["@opentui/solid@0.2.10", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.2.10", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-+4/MB90yIQiPwg8Y4wY092yva9BvRTsJeeeEO3e2H7P8k8zxYk4G9bzuhqYLxA9mTVQ+zVDlrmFoPQhT7vpIRw=="], + "ora/cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="], "ora/log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="], @@ -5557,6 +5561,20 @@ "opencontrol/@modelcontextprotocol/sdk/zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + "opentui-spinner/@opentui/core/@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+lbDDj42Og+UtTZEwlHhGXichmOlkxSqn0J+Jqjat5/Tt5oZykj1NZjFIQ7ZSz4Miz7EmZwgYKE2CyOmmm9MoQ=="], + + "opentui-spinner/@opentui/core/@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.2.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-5iAoA0aqMWWAQ93nh8Bb0ipwt9h+tvEFc88+YO9St43uUJ+XrXcmMj3T8wtl6dSu/SN0UoDWNaUMHUmtykiPtg=="], + + "opentui-spinner/@opentui/core/@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.2.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-EnrkxgH5K76Oi/Br1UHPZblXG5P60snmtySfnxuVaeECNZrbTkV6BV/A0WoBeWshJweGbx1D+eTF+sEEjQCi8w=="], + + "opentui-spinner/@opentui/core/@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.2.10", "", { "os": "linux", "cpu": "x64" }, "sha512-fI+r3kCPqIxsWwPVGpKUQy4zHK8y+jkDRCwa3UbaUy48RQ44jMuf2RhVhmi4xmCvSc8UPJBbYsw1tLuh9kmXjg=="], + + "opentui-spinner/@opentui/core/@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.2.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-8F4z2hIRgkVWcr6CMVeJ9N4+1rmURPt2Pq2GBPko8ch6rxHR+a//KD1MfphyuLTHBS1tJ4vfZSWSoiaESImtrA=="], + + "opentui-spinner/@opentui/core/@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.2.10", "", { "os": "win32", "cpu": "x64" }, "sha512-Ki+qNBlIFW5K2wcG/RHrlPp7yEQKXeiNX3mlje25iwX62Ac5w391HBpOmUjbPoq20McPyDRnhbLfbXQSPtickg=="], + + "opentui-spinner/@opentui/solid/@babel/core": ["@babel/core@7.28.0", "", { "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.0", "@babel/helper-compilation-targets": "^7.27.2", "@babel/helper-module-transforms": "^7.27.3", "@babel/helpers": "^7.27.6", "@babel/parser": "^7.28.0", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.0", "@babel/types": "^7.28.0", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-UlLAnTPrFdNGoFtbSXwcGFQBtQZJCNjaN6hQNP3UPvuNXT1i82N26KL3dZeIpNalWywr9IuQuncaAfUaS1g6sQ=="], + "ora/log-symbols/is-unicode-supported": ["is-unicode-supported@1.3.0", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="], "p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], @@ -5785,6 +5803,8 @@ "mocha/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + "opentui-spinner/@opentui/solid/@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "pkg-conf/find-up/locate-path/p-locate": ["p-locate@6.0.0", "", { "dependencies": { "p-limit": "^4.0.0" } }, "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw=="], "pkg-up/find-up/locate-path/p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="], diff --git a/package.json b/package.json index 96965ca3635..aa64605532c 100644 --- a/package.json +++ b/package.json @@ -32,8 +32,8 @@ "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@hono/zod-validator": "0.4.2", - "@opentui/core": "0.2.10", - "@opentui/solid": "0.2.10", + "@opentui/core": "0.2.11", + "@opentui/solid": "0.2.11", "ulid": "3.0.1", "@kobalte/core": "0.13.11", "@types/luxon": "3.7.1", @@ -78,7 +78,7 @@ "solid-js": "1.9.12", "vite-plugin-solid": "2.11.10", "@lydell/node-pty": "1.2.0-beta.10", - "@opentui/keymap": "0.2.10" + "@opentui/keymap": "0.2.11" } }, "devDependencies": { diff --git a/packages/core/src/catalog.ts b/packages/core/src/catalog.ts index 70cdba78563..d27f17bfb87 100644 --- a/packages/core/src/catalog.ts +++ b/packages/core/src/catalog.ts @@ -5,7 +5,8 @@ import { produce, type Draft } from "immer" import { ModelV2 } from "./model" import { PluginV2 } from "./plugin" import { ProviderV2 } from "./provider" -import { Instance } from "./instance" +import { Location } from "./location" +import { EventV2 } from "./event" type ProviderRecord = { provider: ProviderV2.Info @@ -24,6 +25,15 @@ export class ModelNotFoundError extends Schema.TaggedErrorClass Effect.Effect @@ -57,10 +67,11 @@ export class Service extends Context.Service()("@opencode/v2 export const layer = Layer.effect( Service, Effect.gen(function* () { - yield* Instance.Service + yield* Location.Service let records = HashMap.empty() let defaultModel: { providerID: ProviderV2.ID; modelID: ModelV2.ID } | undefined const plugin = yield* PluginV2.Service + const events = yield* EventV2.Service const resolve = (model: ModelV2.Info) => { const provider = Option.getOrThrow(HashMap.get(records, model.providerID)).provider @@ -157,14 +168,12 @@ export const layer = Layer.effect( ) const updated = yield* plugin.trigger("model.update", {}, { model, cancel: false }) if (updated.cancel) return + const next = new ModelV2.Info({ ...updated.model, id: modelID, providerID }) records = HashMap.set(records, providerID, { provider: record.provider, - models: HashMap.set( - record.models, - modelID, - new ModelV2.Info({ ...updated.model, id: modelID, providerID }), - ), + models: HashMap.set(record.models, modelID, next), }) + yield* events.publish(Event.ModelUpdated, { model: resolve(next) }) return }), @@ -257,4 +266,4 @@ export const layer = Layer.effect( const SMALL_MODEL_RE = /\b(nano|flash|lite|mini|haiku|small|fast)\b/ -export const defaultLayer = layer.pipe(Layer.provide(PluginV2.defaultLayer)) +export const defaultLayer = layer.pipe(Layer.provideMerge(EventV2.defaultLayer), Layer.provide(PluginV2.defaultLayer)) diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts new file mode 100644 index 00000000000..e01dc5b0d63 --- /dev/null +++ b/packages/core/src/event.ts @@ -0,0 +1,157 @@ +import { Context, Effect, Layer, Option, PubSub, Schema, Stream } from "effect" +import { Location } from "./location" +import { withStatics } from "./schema" +import { Identifier } from "./util/identifier" + +export const ID = Schema.String.pipe( + Schema.brand("Event.ID"), + withStatics((schema) => ({ create: () => schema.make("evt_" + Identifier.ascending()) })), +) +export type ID = typeof ID.Type + +export type Definition = { + readonly type: Type + readonly version?: number + readonly aggregate?: string + readonly data: DataSchema +} + +export type Data = Schema.Schema.Type + +export type Payload = { + readonly id: ID + readonly type: D["type"] + readonly data: Data + readonly version?: number + readonly location?: Location.Ref + readonly metadata?: Record +} + +export type Sync = (event: Payload) => Effect.Effect + +export const registry = new Map() + +export function define(input: { + readonly type: Type + readonly version?: number + readonly aggregate?: string + readonly schema: Fields +}): Schema.Schema>>> & Definition> { + const Data = Schema.Struct(input.schema) + const Payload = Schema.Struct({ + id: ID, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + type: Schema.Literal(input.type), + version: Schema.optional(Schema.Number), + location: Schema.optional(Location.Ref), + data: Data, + }).annotate({ identifier: input.type }) + + const definition = Object.assign(Payload, { + type: input.type, + ...(input.version === undefined ? {} : { version: input.version }), + ...(input.aggregate === undefined ? {} : { aggregate: input.aggregate }), + data: Data, + }) + registry.set(input.type, definition) + return definition as Schema.Schema>>> & + Definition> +} + +export function definitions() { + return registry.values().toArray() +} + +export interface PublishOptions { + readonly id?: ID + readonly metadata?: Record +} + +export type Unsubscribe = Effect.Effect + +export interface Interface { + readonly publish: ( + definition: D, + data: Data, + options?: PublishOptions, + ) => Effect.Effect> + readonly publishEvent: (event: Payload) => Effect.Effect> + readonly subscribe: (definition: D) => Stream.Stream> + readonly all: () => Stream.Stream + readonly sync: (handler: Sync) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/Event") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const all = yield* PubSub.unbounded() + const typed = new Map>() + const syncHandlers = new Array() + + const getOrCreate = (definition: Definition) => + Effect.gen(function* () { + const existing = typed.get(definition.type) + if (existing) return existing + const pubsub = yield* PubSub.unbounded() + typed.set(definition.type, pubsub) + return pubsub + }) + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* PubSub.shutdown(all) + yield* Effect.forEach(typed.values(), PubSub.shutdown, { discard: true }) + }), + ) + + function publishEvent(event: Payload) { + return Effect.gen(function* () { + for (const sync of syncHandlers) { + yield* sync(event as Payload) + } + const pubsub = typed.get(event.type) + if (pubsub) yield* PubSub.publish(pubsub, event as Payload) + yield* PubSub.publish(all, event as Payload) + return event + }) + } + + function publish(definition: D, data: Data, options?: PublishOptions) { + return Effect.gen(function* () { + const location = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service)) + const event = { + id: options?.id ?? ID.create(), + ...(options?.metadata ? { metadata: options.metadata } : {}), + type: definition.type, + ...(definition.version === undefined ? {} : { version: definition.version }), + ...(location ? { location } : {}), + data, + } as Payload + return yield* publishEvent(event) + }) + } + + const subscribe = (definition: D): Stream.Stream> => + Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe( + Stream.map((event) => event as Payload), + ) + + const streamAll = (): Stream.Stream => Stream.fromPubSub(all) + const sync = (handler: Sync): Effect.Effect => + Effect.sync(() => { + syncHandlers.push(handler) + return Effect.sync(() => { + const index = syncHandlers.indexOf(handler) + if (index >= 0) syncHandlers.splice(index, 1) + }) + }) + + return Service.of({ publish, publishEvent, subscribe, all: streamAll, sync }) + }), +) + +export const defaultLayer = layer + +export * as EventV2 from "./event" diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index ab0647c8af3..0ed6eb47700 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -53,7 +53,7 @@ export const Flag = { KILO_DISABLE_CLAUDE_CODE_PROMPT: KILO_DISABLE_CLAUDE_CODE || truthy("KILO_DISABLE_CLAUDE_CODE_PROMPT"), KILO_DISABLE_CLAUDE_CODE_SKILLS, KILO_DISABLE_EXTERNAL_SKILLS: truthy("KILO_DISABLE_EXTERNAL_SKILLS"), - KILO_EXPERIMENTAL_CUSTOMIZE_SKILL: unstableDefault("KILO_EXPERIMENTAL_CUSTOMIZE_SKILL"), + KILO_EXPERIMENTAL_CUSTOMIZE_SKILL: unstableDefault("KILO_EXPERIMENTAL_CUSTOMIZE_SKILL"), // kilocode_change KILO_FAKE_VCS: process.env["KILO_FAKE_VCS"], KILO_SERVER_PASSWORD: process.env["KILO_SERVER_PASSWORD"], KILO_SERVER_USERNAME: process.env["KILO_SERVER_USERNAME"], diff --git a/packages/core/src/instance-layer.ts b/packages/core/src/instance-layer.ts deleted file mode 100644 index 20e6ac1aceb..00000000000 --- a/packages/core/src/instance-layer.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Layer, LayerMap } from "effect" -import { Instance } from "./instance" -import { Catalog } from "./catalog" -import { PluginBoot } from "./plugin/boot" - -export class InstanceServiceMap extends LayerMap.Service()("@opencode/example/InstanceServiceMap", { - lookup: (ref: Instance.Ref) => { - const instance = Layer.succeed(Instance.Service, Instance.Service.of(ref)) - return Layer.mergeAll(Catalog.defaultLayer, PluginBoot.defaultLayer).pipe(Layer.provide(instance)) - }, - idleTimeToLive: "5 minutes", -}) {} diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts deleted file mode 100644 index af6de951be4..00000000000 --- a/packages/core/src/instance.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Context } from "effect" - -export * as Instance from "./instance" - -export type Ref = { - readonly directory: string - readonly workspaceID?: string -} - -export class Service extends Context.Service()("@opencode/Instance") {} diff --git a/packages/core/src/location-layer.ts b/packages/core/src/location-layer.ts new file mode 100644 index 00000000000..84dfb3dfae7 --- /dev/null +++ b/packages/core/src/location-layer.ts @@ -0,0 +1,12 @@ +import { Layer, LayerMap } from "effect" +import { Location } from "./location" +import { Catalog } from "./catalog" +import { PluginBoot } from "./plugin/boot" + +export class LocationServiceMap extends LayerMap.Service()("@opencode/example/LocationServiceMap", { + lookup: (ref: Location.Ref) => { + const location = Layer.succeed(Location.Service, Location.Service.of(ref)) + return Layer.mergeAll(Catalog.defaultLayer, PluginBoot.defaultLayer).pipe(Layer.provide(location)) + }, + idleTimeToLive: "5 minutes", +}) {} diff --git a/packages/core/src/location.ts b/packages/core/src/location.ts new file mode 100644 index 00000000000..00ff9cd3ea7 --- /dev/null +++ b/packages/core/src/location.ts @@ -0,0 +1,11 @@ +import { Context, Schema } from "effect" + +export * as Location from "./location" + +export const Ref = Schema.Struct({ + directory: Schema.String, + workspaceID: Schema.optional(Schema.String), +}).annotate({ identifier: "Location.Ref" }) +export type Ref = typeof Ref.Type + +export class Service extends Context.Service()("@opencode/Location") {} diff --git a/packages/opencode/src/v2/session-event.ts b/packages/core/src/session-event.ts similarity index 71% rename from packages/opencode/src/v2/session-event.ts rename to packages/core/src/session-event.ts index 1fd0f909d5a..a98d9cc0514 100644 --- a/packages/opencode/src/v2/session-event.ts +++ b/packages/core/src/session-event.ts @@ -1,12 +1,13 @@ -import { SessionID } from "@/session/schema" -import { NonNegativeInt } from "@opencode-ai/core/schema" -import { EventV2 } from "./event" -import { FileAttachment, Prompt } from "@opencode-ai/core/session-prompt" import { Schema } from "effect" +import { EventV2 } from "./event" +import { ModelV2 } from "./model" +import { NonNegativeInt } from "./schema" +import { Session } from "./session" +import { FileAttachment, Prompt } from "./session-prompt" +import { ToolOutput } from "./tool-output" +import { V2Schema } from "./v2-schema" + export { FileAttachment } -import { ToolOutput } from "@opencode-ai/core/tool-output" -import { V2Schema } from "@opencode-ai/core/v2-schema" -import { ModelV2 } from "@opencode-ai/core/model" export const Source = Schema.Struct({ start: NonNegativeInt, @@ -15,92 +16,94 @@ export const Source = Schema.Struct({ }).annotate({ identifier: "session.next.event.source", }) -export type Source = Schema.Schema.Type +export type Source = typeof Source.Type const Base = { timestamp: V2Schema.DateTimeUtcFromMillis, - sessionID: SessionID, + sessionID: Session.ID, } +const options = { + aggregate: "sessionID", + version: 1, +} as const + export const UnknownError = Schema.Struct({ type: Schema.Literal("unknown"), message: Schema.String, }).annotate({ identifier: "Session.Error.Unknown", }) -export type UnknownError = Schema.Schema.Type +export type UnknownError = typeof UnknownError.Type export const AgentSwitched = EventV2.define({ type: "session.next.agent.switched", - aggregate: "sessionID", - version: 1, + ...options, schema: { ...Base, agent: Schema.String, }, }) -export type AgentSwitched = Schema.Schema.Type +export type AgentSwitched = typeof AgentSwitched.Type export const ModelSwitched = EventV2.define({ type: "session.next.model.switched", - aggregate: "sessionID", - version: 1, + ...options, schema: { ...Base, model: ModelV2.Ref, }, }) -export type ModelSwitched = Schema.Schema.Type +export type ModelSwitched = typeof ModelSwitched.Type export const Prompted = EventV2.define({ type: "session.next.prompted", - aggregate: "sessionID", - version: 1, + ...options, schema: { ...Base, prompt: Prompt, }, }) -export type Prompted = Schema.Schema.Type +export type Prompted = typeof Prompted.Type export const Synthetic = EventV2.define({ type: "session.next.synthetic", - aggregate: "sessionID", + ...options, schema: { ...Base, text: Schema.String, }, }) -export type Synthetic = Schema.Schema.Type +export type Synthetic = typeof Synthetic.Type export namespace Shell { export const Started = EventV2.define({ type: "session.next.shell.started", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, command: Schema.String, }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Ended = EventV2.define({ type: "session.next.shell.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, output: Schema.String, }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type } export namespace Step { export const Started = EventV2.define({ type: "session.next.step.started", - aggregate: "sessionID", + ...options, schema: { ...Base, agent: Schema.String, @@ -108,11 +111,11 @@ export namespace Step { snapshot: Schema.String.pipe(Schema.optional), }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Ended = EventV2.define({ type: "session.next.step.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, finish: Schema.String, @@ -129,123 +132,123 @@ export namespace Step { snapshot: Schema.String.pipe(Schema.optional), }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type export const Failed = EventV2.define({ type: "session.next.step.failed", - aggregate: "sessionID", + ...options, schema: { ...Base, error: UnknownError, }, }) - export type Failed = Schema.Schema.Type + export type Failed = typeof Failed.Type } export namespace Text { export const Started = EventV2.define({ type: "session.next.text.started", - aggregate: "sessionID", + ...options, schema: { ...Base, }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Delta = EventV2.define({ type: "session.next.text.delta", - aggregate: "sessionID", + ...options, schema: { ...Base, delta: Schema.String, }, }) - export type Delta = Schema.Schema.Type + export type Delta = typeof Delta.Type export const Ended = EventV2.define({ type: "session.next.text.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, text: Schema.String, }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type } export namespace Reasoning { export const Started = EventV2.define({ type: "session.next.reasoning.started", - aggregate: "sessionID", + ...options, schema: { ...Base, reasoningID: Schema.String, }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Delta = EventV2.define({ type: "session.next.reasoning.delta", - aggregate: "sessionID", + ...options, schema: { ...Base, reasoningID: Schema.String, delta: Schema.String, }, }) - export type Delta = Schema.Schema.Type + export type Delta = typeof Delta.Type export const Ended = EventV2.define({ type: "session.next.reasoning.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, reasoningID: Schema.String, text: Schema.String, }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type } export namespace Tool { export namespace Input { export const Started = EventV2.define({ type: "session.next.tool.input.started", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, name: Schema.String, }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Delta = EventV2.define({ type: "session.next.tool.input.delta", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, delta: Schema.String, }, }) - export type Delta = Schema.Schema.Type + export type Delta = typeof Delta.Type export const Ended = EventV2.define({ type: "session.next.tool.input.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, text: Schema.String, }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type } export const Called = EventV2.define({ type: "session.next.tool.called", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, @@ -257,11 +260,11 @@ export namespace Tool { }), }, }) - export type Called = Schema.Schema.Type + export type Called = typeof Called.Type export const Progress = EventV2.define({ type: "session.next.tool.progress", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, @@ -269,11 +272,11 @@ export namespace Tool { content: Schema.Array(ToolOutput.Content), }, }) - export type Progress = Schema.Schema.Type + export type Progress = typeof Progress.Type export const Success = EventV2.define({ type: "session.next.tool.success", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, @@ -285,11 +288,11 @@ export namespace Tool { }), }, }) - export type Success = Schema.Schema.Type + export type Success = typeof Success.Type export const Failed = EventV2.define({ type: "session.next.tool.failed", - aggregate: "sessionID", + ...options, schema: { ...Base, callID: Schema.String, @@ -300,7 +303,7 @@ export namespace Tool { }), }, }) - export type Failed = Schema.Schema.Type + export type Failed = typeof Failed.Type } export const RetryError = Schema.Struct({ @@ -313,49 +316,50 @@ export const RetryError = Schema.Struct({ }).annotate({ identifier: "session.next.retry_error", }) -export type RetryError = Schema.Schema.Type +export type RetryError = typeof RetryError.Type export const Retried = EventV2.define({ type: "session.next.retried", - aggregate: "sessionID", + ...options, schema: { ...Base, attempt: Schema.Finite, error: RetryError, }, }) -export type Retried = Schema.Schema.Type +export type Retried = typeof Retried.Type export namespace Compaction { export const Started = EventV2.define({ type: "session.next.compaction.started", - aggregate: "sessionID", + ...options, schema: { ...Base, reason: Schema.Union([Schema.Literal("auto"), Schema.Literal("manual")]), }, }) - export type Started = Schema.Schema.Type + export type Started = typeof Started.Type export const Delta = EventV2.define({ type: "session.next.compaction.delta", - aggregate: "sessionID", + ...options, schema: { ...Base, text: Schema.String, }, }) + export type Delta = typeof Delta.Type export const Ended = EventV2.define({ type: "session.next.compaction.ended", - aggregate: "sessionID", + ...options, schema: { ...Base, text: Schema.String, include: Schema.String.pipe(Schema.optional), }, }) - export type Ended = Schema.Schema.Type + export type Ended = typeof Ended.Type } export const All = Schema.Union( @@ -392,16 +396,7 @@ export const All = Schema.Union( }, ).pipe(Schema.toTaggedUnion("type")) -// user -// assistant -// assistant -// assistant -// user -// compaction marker -// -> text -// assistant - -export type Event = Schema.Schema.Type +export type Event = typeof All.Type export type Type = Event["type"] export * as SessionEvent from "./session-event" diff --git a/packages/opencode/src/v2/session-message-updater.ts b/packages/core/src/session-message-updater.ts similarity index 100% rename from packages/opencode/src/v2/session-message-updater.ts rename to packages/core/src/session-message-updater.ts diff --git a/packages/opencode/src/v2/session-message.ts b/packages/core/src/session-message.ts similarity index 87% rename from packages/opencode/src/v2/session-message.ts rename to packages/core/src/session-message.ts index fa7c299ae57..73b6dd7da2b 100644 --- a/packages/opencode/src/v2/session-message.ts +++ b/packages/core/src/session-message.ts @@ -1,10 +1,10 @@ import { Schema } from "effect" -import { Prompt } from "@opencode-ai/core/session-prompt" +import { Prompt } from "./session-prompt" import { SessionEvent } from "./session-event" import { EventV2 } from "./event" -import { ToolOutput } from "@opencode-ai/core/tool-output" -import { V2Schema } from "@opencode-ai/core/v2-schema" -import { ModelV2 } from "@opencode-ai/core/model" +import { ToolOutput } from "./tool-output" +import { V2Schema } from "./v2-schema" +import { ModelV2 } from "./model" export const ID = EventV2.ID export type ID = Schema.Schema.Type @@ -20,7 +20,7 @@ const Base = { export class AgentSwitched extends Schema.Class("Session.Message.AgentSwitched")({ ...Base, type: Schema.Literal("agent-switched"), - agent: SessionEvent.AgentSwitched.fields.data.fields.agent, + agent: SessionEvent.AgentSwitched.data.fields.agent, }) {} export class ModelSwitched extends Schema.Class("Session.Message.ModelSwitched")({ @@ -43,16 +43,16 @@ export class User extends Schema.Class("Session.Message.User")({ export class Synthetic extends Schema.Class("Session.Message.Synthetic")({ ...Base, - sessionID: SessionEvent.Synthetic.fields.data.fields.sessionID, - text: SessionEvent.Synthetic.fields.data.fields.text, + sessionID: SessionEvent.Synthetic.data.fields.sessionID, + text: SessionEvent.Synthetic.data.fields.text, type: Schema.Literal("synthetic"), }) {} export class Shell extends Schema.Class("Session.Message.Shell")({ ...Base, type: Schema.Literal("shell"), - callID: SessionEvent.Shell.Started.fields.data.fields.callID, - command: SessionEvent.Shell.Started.fields.data.fields.command, + callID: SessionEvent.Shell.Started.data.fields.callID, + command: SessionEvent.Shell.Started.data.fields.command, output: Schema.String, time: Schema.Struct({ created: V2Schema.DateTimeUtcFromMillis, @@ -130,7 +130,7 @@ export class Assistant extends Schema.Class("Session.Message.Assistan ...Base, type: Schema.Literal("assistant"), agent: Schema.String, - model: SessionEvent.Step.Started.fields.data.fields.model, + model: SessionEvent.Step.Started.data.fields.model, content: AssistantContent.pipe(Schema.Array), snapshot: Schema.Struct({ start: Schema.String.pipe(Schema.optional), @@ -147,7 +147,7 @@ export class Assistant extends Schema.Class("Session.Message.Assistan write: Schema.Finite, }), }).pipe(Schema.optional), - error: SessionEvent.Step.Failed.fields.data.fields.error.pipe(Schema.optional), + error: SessionEvent.Step.Failed.data.fields.error.pipe(Schema.optional), time: Schema.Struct({ created: V2Schema.DateTimeUtcFromMillis, completed: V2Schema.DateTimeUtcFromMillis.pipe(Schema.optional), @@ -156,7 +156,7 @@ export class Assistant extends Schema.Class("Session.Message.Assistan export class Compaction extends Schema.Class("Session.Message.Compaction")({ type: Schema.Literal("compaction"), - reason: SessionEvent.Compaction.Started.fields.data.fields.reason, + reason: SessionEvent.Compaction.Started.data.fields.reason, summary: Schema.String, include: Schema.String.pipe(Schema.optional), ...Base, diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts new file mode 100644 index 00000000000..756531e3280 --- /dev/null +++ b/packages/core/src/session.ts @@ -0,0 +1,13 @@ +export * as Session from "./session" + +import { Schema } from "effect" +import { withStatics } from "./schema" +import { Identifier } from "./util/identifier" + +export const ID = Schema.String.check(Schema.isStartsWith("ses")).pipe( + Schema.brand("SessionID"), + withStatics((schema) => ({ + descending: (id?: string) => schema.make(id ?? "ses_" + Identifier.descending()), + })), +) +export type ID = typeof ID.Type diff --git a/packages/core/test/catalog.test.ts b/packages/core/test/catalog.test.ts index c5ac2c06cc4..594f42d1c8b 100644 --- a/packages/core/test/catalog.test.ts +++ b/packages/core/test/catalog.test.ts @@ -1,14 +1,21 @@ import { describe, expect } from "bun:test" -import { DateTime, Effect, Layer, Option } from "effect" +import { DateTime, Effect, Fiber, Layer, Option, Stream } from "effect" import { Catalog } from "@opencode-ai/core/catalog" -import { Instance } from "@opencode-ai/core/instance" +import { EventV2 } from "@opencode-ai/core/event" +import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { ProviderV2 } from "@opencode-ai/core/provider" import { testEffect } from "./lib/effect" -const instanceLayer = Layer.succeed(Instance.Service, Instance.Service.of({ directory: "test" })) -const it = testEffect(Catalog.layer.pipe(Layer.provideMerge(PluginV2.defaultLayer), Layer.provide(instanceLayer))) +const locationLayer = Layer.succeed(Location.Service, Location.Service.of({ directory: "test" })) +const it = testEffect( + Catalog.layer.pipe( + Layer.provideMerge(EventV2.defaultLayer), + Layer.provideMerge(PluginV2.defaultLayer), + Layer.provideMerge(locationLayer), + ), +) describe("CatalogV2", () => { it.effect("normalizes provider baseURL into endpoint url", () => @@ -69,6 +76,31 @@ describe("CatalogV2", () => { }), ) + it.effect("publishes model updated events", () => + Effect.gen(function* () { + const catalog = yield* Catalog.Service + const events = yield* EventV2.Service + const providerID = ProviderV2.ID.make("test") + const modelID = ModelV2.ID.make("model") + const fiber = yield* events + .subscribe(Catalog.Event.ModelUpdated) + .pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + + yield* Effect.yieldNow + yield* catalog.provider.update(providerID, () => {}) + yield* catalog.model.update(providerID, modelID, (model) => { + model.name = "Updated Model" + }) + const event = Array.from(yield* Fiber.join(fiber))[0] + + expect(event?.type).toBe("catalog.model.updated") + expect(event?.data.model.providerID).toBe(providerID) + expect(event?.data.model.id).toBe(modelID) + expect(event?.data.model.name).toBe("Updated Model") + expect(event?.location).toEqual({ directory: "test" }) + }), + ) + it.effect("resolves unknown model endpoint from provider endpoint", () => Effect.gen(function* () { const catalog = yield* Catalog.Service diff --git a/packages/core/test/event.test.ts b/packages/core/test/event.test.ts new file mode 100644 index 00000000000..b67b2897a1b --- /dev/null +++ b/packages/core/test/event.test.ts @@ -0,0 +1,132 @@ +import { describe, expect } from "bun:test" +import { Effect, Fiber, Layer, Schema, Stream } from "effect" +import { EventV2 } from "@opencode-ai/core/event" +import { Location } from "@opencode-ai/core/location" +import { testEffect } from "./lib/effect" + +const locationLayer = Layer.succeed( + Location.Service, + Location.Service.of({ directory: "project", workspaceID: "workspace" }), +) +const it = testEffect(EventV2.layer.pipe(Layer.provideMerge(locationLayer))) +const itWithoutLocation = testEffect(EventV2.layer) + +const Message = EventV2.define({ + type: "test.message", + schema: { + text: Schema.String, + }, +}) + +const GlobalMessage = EventV2.define({ + type: "test.global", + schema: { + text: Schema.String, + }, +}) + +const VersionedMessage = EventV2.define({ + type: "test.versioned", + version: 2, + schema: { + text: Schema.String, + }, +}) + +describe("EventV2", () => { + it.effect("publishes events with the current location", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const fiber = yield* events.subscribe(Message).pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + yield* Effect.yieldNow + const event = yield* events.publish(Message, { text: "hello" }) + const received = Array.from(yield* Fiber.join(fiber)) + + expect(received).toEqual([event]) + expect(event.type).toBe("test.message") + expect(event).not.toHaveProperty("version") + expect(event.data).toEqual({ text: "hello" }) + expect(event.location).toEqual({ directory: "project", workspaceID: "workspace" }) + }), + ) + + itWithoutLocation.effect("omits location when no location is available", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const event = yield* events.publish(GlobalMessage, { text: "hello" }) + + expect(event).not.toHaveProperty("location") + expect(event.type).toBe("test.global") + }), + ) + + it.effect("publishes definition version", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const event = yield* events.publish(VersionedMessage, { text: "hello" }) + + expect(event.type).toBe("test.versioned") + expect(event.version).toBe(2) + }), + ) + + it.effect("stores definitions in the exported registry", () => + Effect.sync(() => { + expect(EventV2.registry.get(Message.type)).toBe(Message) + }), + ) + + it.effect("publishes to typed and wildcard subscriptions", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const typed = yield* events.subscribe(Message).pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + const wildcard = yield* events.all().pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + yield* Effect.yieldNow + const event = yield* events.publish(Message, { text: "hello" }) + + expect(Array.from(yield* Fiber.join(typed))).toEqual([event]) + expect(Array.from(yield* Fiber.join(wildcard))).toEqual([event]) + }), + ) + + it.effect("runs sync handlers inline", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + const unsubscribe = yield* events.sync((event) => + Effect.sync(() => { + received.push(event) + }), + ) + + const event = yield* events.publish(Message, { text: "hello" }) + yield* unsubscribe + yield* events.publish(Message, { text: "after unsubscribe" }) + + expect(received).toEqual([event]) + }), + ) + + it.effect("runs sync handlers before publishing to streams", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + const fiber = yield* events.all().pipe( + Stream.take(1), + Stream.runForEach(() => Effect.sync(() => received.push("stream"))), + Effect.forkScoped, + ) + yield* events.sync((event) => + Effect.sync(() => { + received.push(event.type) + }), + ) + + yield* Effect.yieldNow + yield* events.publish(Message, { text: "hello" }) + yield* Fiber.join(fiber) + + expect(received).toEqual([Message.type, "stream"]) + }), + ) +}) diff --git a/packages/core/test/plugin/provider-opencode.test.ts b/packages/core/test/plugin/provider-opencode.test.ts index 8271a4a5c82..ed82686a21c 100644 --- a/packages/core/test/plugin/provider-opencode.test.ts +++ b/packages/core/test/plugin/provider-opencode.test.ts @@ -1,7 +1,7 @@ import { describe, expect } from "bun:test" import { DateTime, Effect, Layer, Option } from "effect" import { Catalog } from "@opencode-ai/core/catalog" -import { Instance } from "@opencode-ai/core/instance" +import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { OpencodePlugin } from "@opencode-ai/core/plugin/provider/opencode" @@ -9,7 +9,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider" import { it, model, provider, withEnv } from "./provider-helper" const cost = (input: number, output = 0) => [{ input, output, cache: { read: 0, write: 0 } }] -const instanceLayer = Layer.succeed(Instance.Service, Instance.Service.of({ directory: "test" })) +const locationLayer = Layer.succeed(Location.Service, Location.Service.of({ directory: "test" })) describe("OpencodePlugin", () => { it.effect("uses a public key and cancels paid models without credentials", () => @@ -192,6 +192,6 @@ describe("OpencodePlugin", () => { const selected = yield* catalog.model.small(providerID) expect(Option.getOrUndefined(selected)?.id).toBe(ModelV2.ID.make("gpt-5-nano")) - }).pipe(Effect.provide(Catalog.defaultLayer.pipe(Layer.provide(instanceLayer)))), + }).pipe(Effect.provide(Catalog.defaultLayer.pipe(Layer.provide(locationLayer)))), ) }) diff --git a/packages/kilo-docs/markdoc/partials/cli-commands-table.md b/packages/kilo-docs/markdoc/partials/cli-commands-table.md index 962447f0d12..877e4a17785 100644 --- a/packages/kilo-docs/markdoc/partials/cli-commands-table.md +++ b/packages/kilo-docs/markdoc/partials/cli-commands-table.md @@ -13,12 +13,14 @@ | `kilo upgrade [target]` | upgrade kilo to the latest or a specific version | | `kilo uninstall` | uninstall kilo and remove all related files | | `kilo serve` | starts a headless kilo server | +| `kilo web` | start kilo server and open web interface | | `kilo models [provider]` | list all available models | | `kilo roll-call ` | batch-test text models matching a filter for connectivity and latency | | `kilo profile` | show Kilo account profile | | `kilo stats` | show token usage and cost statistics | | `kilo export [sessionID]` | export session data as JSON | | `kilo import ` | import session data from JSON file or URL | +| `kilo github` | manage GitHub agent | | `kilo pr ` | fetch and checkout a GitHub PR branch, then run kilo | | `kilo session` | manage sessions | | `kilo remote` | enable remote connection for real-time session relay | diff --git a/packages/kilo-docs/pages/code-with-ai/platforms/cli-reference.md b/packages/kilo-docs/pages/code-with-ai/platforms/cli-reference.md index 67600a5e1e5..a62251c5d7b 100644 --- a/packages/kilo-docs/pages/code-with-ai/platforms/cli-reference.md +++ b/packages/kilo-docs/pages/code-with-ai/platforms/cli-reference.md @@ -682,6 +682,21 @@ Options: --cors additional domains to allow for CORS [array] [default: []] ``` +## kilo web + +``` +start kilo server and open web interface + +Options: + --help Show help [boolean] + --version Show version number [boolean] + --port port to listen on [number] [default: 0] + --hostname hostname to listen on [string] [default: "127.0.0.1"] + --mdns enable mDNS service discovery (defaults hostname to 0.0.0.0) [boolean] [default: false] + --mdns-domain custom domain name for mDNS service (default: kilo.local) [string] [default: "kilo.local"] + --cors additional domains to allow for CORS [array] [default: []] +``` + ## kilo models ``` @@ -768,6 +783,42 @@ Options: --version Show version number [boolean] ``` +## kilo github + +``` +manage GitHub agent + +Commands: + kilo github install install the GitHub agent + kilo github run run the GitHub agent + +Options: + --help Show help [boolean] + --version Show version number [boolean] +``` + +### kilo github install + +``` +install the GitHub agent + +Options: + --help Show help [boolean] + --version Show version number [boolean] +``` + +### kilo github run + +``` +run the GitHub agent + +Options: + --help Show help [boolean] + --version Show version number [boolean] + --event GitHub mock event to run the agent for [string] + --token GitHub personal access token (github_pat_********) [string] +``` + ## kilo pr ``` diff --git a/packages/opencode/script/build.ts b/packages/opencode/script/build.ts index 43bb1a5fabc..3542d40ecd4 100755 --- a/packages/opencode/script/build.ts +++ b/packages/opencode/script/build.ts @@ -382,6 +382,7 @@ for (const item of targets) { { name, version: Script.version, + preferUnplugged: true, os: [item.os], cpu: [item.arch], keywords: pkg.keywords, // kilocode_change diff --git a/packages/opencode/script/postinstall.mjs b/packages/opencode/script/postinstall.mjs index 9694b29d272..d158c645259 100644 --- a/packages/opencode/script/postinstall.mjs +++ b/packages/opencode/script/postinstall.mjs @@ -1,14 +1,15 @@ #!/usr/bin/env node -import fs from "fs" -import path from "path" -import os from "os" import childProcess from "child_process" -import { fileURLToPath } from "url" +import fs from "fs" +import os from "os" +import path from "path" import { createRequire } from "module" +import { fileURLToPath } from "url" const __dirname = path.dirname(fileURLToPath(import.meta.url)) const require = createRequire(import.meta.url) +const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf8")) // kilocode_change start - variant detection matching bin/kilo logic const platformMap = { @@ -22,14 +23,13 @@ const archMap = { arm: "arm", } -function detectPlatformAndArch() { - const platform = platformMap[os.platform()] || os.platform() - const arch = archMap[os.arch()] || os.arch() - return { platform, arch } -} +const platform = platformMap[os.platform()] ?? os.platform() +const arch = archMap[os.arch()] ?? os.arch() +const base = `@kilocode/cli-${platform}-${arch}` +const sourceBinary = platform === "windows" ? "kilo.exe" : "kilo" +const targetBinary = path.join(__dirname, "bin", ".kilo") function supportsAvx2() { - const { platform, arch } = detectPlatformAndArch() if (arch !== "x64") return false if (platform === "linux") { @@ -53,125 +53,152 @@ function supportsAvx2() { } } + if (platform === "windows") { + const command = + '(Add-Type -MemberDefinition "[DllImport(""kernel32.dll"")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);" -Name Kernel32 -Namespace Win32 -PassThru)::IsProcessorFeaturePresent(40)' + + for (const executable of ["powershell.exe", "pwsh.exe", "pwsh", "powershell"]) { + try { + const result = childProcess.spawnSync(executable, ["-NoProfile", "-NonInteractive", "-Command", command], { + encoding: "utf8", + timeout: 3000, + windowsHide: true, + }) + if (result.status !== 0) continue + const output = (result.stdout || "").trim().toLowerCase() + if (output === "true" || output === "1") return true + if (output === "false" || output === "0") return false + } catch { + continue + } + } + } + return false } function isMusl() { + if (platform !== "linux") return false + try { if (fs.existsSync("/etc/alpine-release")) return true } catch { - // ignore + // Ignore filesystem probes that are blocked by the host. } try { const result = childProcess.spawnSync("ldd", ["--version"], { encoding: "utf8" }) - const text = ((result.stdout || "") + (result.stderr || "")).toLowerCase() - if (text.includes("musl")) return true + return `${result.stdout || ""}${result.stderr || ""}`.toLowerCase().includes("musl") } catch { - // ignore + return false } - - return false } -function getPackageNames() { - const { platform, arch } = detectPlatformAndArch() - const base = `@kilocode/cli-${platform}-${arch}` - const avx2 = supportsAvx2() - const baseline = arch === "x64" && !avx2 +function packageNames() { + const baseline = arch === "x64" && !supportsAvx2() if (platform === "linux") { - const musl = isMusl() - if (musl) { - if (arch === "x64") { - if (baseline) return [`${base}-baseline-musl`, `${base}-musl`, `${base}-baseline`, base] - return [`${base}-musl`, `${base}-baseline-musl`, base, `${base}-baseline`] - } + if (isMusl()) { + if (arch === "x64") + return baseline + ? [`${base}-baseline-musl`, `${base}-musl`, `${base}-baseline`, base] + : [`${base}-musl`, `${base}-baseline-musl`, base, `${base}-baseline`] return [`${base}-musl`, base] } - if (arch === "x64") { - if (baseline) return [`${base}-baseline`, base, `${base}-baseline-musl`, `${base}-musl`] - return [base, `${base}-baseline`, `${base}-musl`, `${base}-baseline-musl`] - } + + if (arch === "x64") + return baseline + ? [`${base}-baseline`, base, `${base}-baseline-musl`, `${base}-musl`] + : [base, `${base}-baseline`, `${base}-musl`, `${base}-baseline-musl`] return [base, `${base}-musl`] } - if (arch === "x64") { - if (baseline) return [`${base}-baseline`, base] - return [base, `${base}-baseline`] - } + if (arch === "x64") return baseline ? [`${base}-baseline`, base] : [base, `${base}-baseline`] return [base] } -function findBinary() { - const { platform } = detectPlatformAndArch() - const binaryName = platform === "windows" ? "kilo.exe" : "kilo" - const names = getPackageNames() - - for (const packageName of names) { - try { - const packageJsonPath = require.resolve(`${packageName}/package.json`) - const packageDir = path.dirname(packageJsonPath) - const binaryPath = path.join(packageDir, "bin", binaryName) - - if (fs.existsSync(binaryPath)) { - return { binaryPath, binaryName } - } - } catch { - // package not installed, try next variant - } - } - - throw new Error(`Could not find any binary package. Tried: ${names.map((n) => `"${n}"`).join(", ")}`) +function resolveBinary(name) { + const packageJsonPath = require.resolve(`${name}/package.json`) + const binaryPath = path.join(path.dirname(packageJsonPath), "bin", sourceBinary) + if (!fs.existsSync(binaryPath)) throw new Error(`Binary not found at ${binaryPath}`) + return binaryPath } // kilocode_change end // kilocode_change start - copy runtime resources next to cached binary -function copyTreeSitterResources(binaryPath) { - const source = path.join(path.dirname(binaryPath), "tree-sitter") - const target = path.join(__dirname, "bin", "tree-sitter") - const runtime = path.join(source, "tree-sitter.wasm") - - if (!fs.existsSync(runtime)) return - - fs.rmSync(target, { recursive: true, force: true }) - fs.cpSync(source, target, { recursive: true }) +function copyResources(source) { + for (const [name, entry] of [ + ["tree-sitter", "tree-sitter.wasm"], + ["console", "index.html"], + ]) { + const dir = path.join(path.dirname(source), name) + if (!fs.existsSync(path.join(dir, entry))) continue + const target = path.join(__dirname, "bin", name) + fs.rmSync(target, { recursive: true, force: true }) + fs.cpSync(dir, target, { recursive: true }) + } } -function copyConsoleResources(binaryPath) { - const source = path.join(path.dirname(binaryPath), "console") - const target = path.join(__dirname, "bin", "console") - const index = path.join(source, "index.html") - - if (!fs.existsSync(index)) return - - fs.rmSync(target, { recursive: true, force: true }) - fs.cpSync(source, target, { recursive: true }) +function copyBinary(source) { + if (!fs.existsSync(source)) throw new Error(`Binary not found at ${source}`) + fs.mkdirSync(path.dirname(targetBinary), { recursive: true }) + if (fs.existsSync(targetBinary)) fs.unlinkSync(targetBinary) + try { + fs.linkSync(source, targetBinary) + } catch { + fs.copyFileSync(source, targetBinary) + } + copyResources(source) + fs.chmodSync(targetBinary, 0o755) } // kilocode_change end +function verifyBinary() { + const result = childProcess.spawnSync(targetBinary, ["--version"], { + stdio: "ignore", + windowsHide: true, + }) + return result.status === 0 +} + function main() { - if (os.platform() === "win32") { - // On Windows, the .exe is already included in the package and bin field points to it - console.log("Windows detected: binary setup not needed (using packaged .exe)") + if (platform === "windows") { + console.log("Windows detected: binary setup not needed (using packaged wrapper)") return } - const { binaryPath } = findBinary() - const target = path.join(__dirname, "bin", ".kilo") // kilocode_change - if (fs.existsSync(target)) fs.unlinkSync(target) - try { - fs.linkSync(binaryPath, target) - } catch { - fs.copyFileSync(binaryPath, target) + for (const name of packageNames()) { + try { + copyBinary(resolveBinary(name)) + if (verifyBinary()) return + } catch { + const temp = fs.mkdtempSync(path.join(os.tmpdir(), "kilo-install-")) + try { + const version = packageJson.optionalDependencies?.[name] + if (!version) continue + const result = childProcess.spawnSync( + "npm", + ["install", "--ignore-scripts", "--no-save", "--loglevel=error", "--prefix", temp, `${name}@${version}`], + { stdio: "inherit", windowsHide: true }, + ) + if (result.status !== 0) continue + copyBinary(path.join(temp, "node_modules", name, "bin", sourceBinary)) + if (verifyBinary()) return + } finally { + fs.rmSync(temp, { recursive: true, force: true }) + } + } } - copyTreeSitterResources(binaryPath) // kilocode_change - copyConsoleResources(binaryPath) // kilocode_change - fs.chmodSync(target, 0o755) + + throw new Error( + `It seems your package manager failed to install the right Kilo CLI package. Try manually installing ${packageNames() + .map((name) => JSON.stringify(name)) + .join(" or ")}.`, + ) } try { - void main() + main() } catch (error) { console.error("Failed to setup kilo binary:", error.message) process.exit(1) diff --git a/packages/opencode/script/publish.ts b/packages/opencode/script/publish.ts index 126f43a34ca..0d9ab24e2d5 100755 --- a/packages/opencode/script/publish.ts +++ b/packages/opencode/script/publish.ts @@ -50,12 +50,14 @@ await Bun.file(`./dist/${pkg.name}/package.json`).write( // kilocode_change end }, scripts: { - postinstall: "bun ./postinstall.mjs || node ./postinstall.mjs", + postinstall: "node ./postinstall.mjs", }, version: version, license: pkg.license, keywords: pkg.keywords, // kilocode_change private: pkg.private, // kilocode_change + os: ["darwin", "linux", "win32"], + cpu: ["arm64", "x64"], optionalDependencies: binaries, // kilocode_change start repository: { diff --git a/packages/opencode/specs/effect/errors.md b/packages/opencode/specs/effect/errors.md index 69298bde5ca..fe526c2faa7 100644 --- a/packages/opencode/specs/effect/errors.md +++ b/packages/opencode/specs/effect/errors.md @@ -70,11 +70,54 @@ Endpoint definitions declare which public errors can be emitted. Public HTTP error schemas carry their response status with `httpApiStatus` or the equivalent HttpApi schema annotation. +Effect's own HttpApi examples follow this pattern: + +```ts +export class Unauthorized extends Schema.TaggedErrorClass()( + "Unauthorized", + { message: Schema.String }, + { httpApiStatus: 401 }, +) {} + +export class Authorization extends HttpApiMiddleware.Service< + Authorization, + { + provides: CurrentUser + } +>()("app/Authorization", { + security: { bearer: HttpApiSecurity.bearer }, + error: Unauthorized, +}) {} +``` + +Endpoint-level errors use the same idea: + +```ts +export class ConfigApiError extends Schema.ErrorClass("ConfigApiError")( + { + name: Schema.Union(Schema.Literal("ConfigInvalidError"), Schema.Literal("ConfigJsonError")), + data: Schema.Struct({ message: Schema.optional(Schema.String), path: Schema.String }), + }, + { httpApiStatus: 400 }, +) {} + +HttpApiEndpoint.get("get", "/config", { + success: Config.Info, + error: ConfigApiError, +}) +``` + The service error and HTTP error may be the same class only when the wire shape is intentionally public. Use separate HTTP error schemas when the service error contains internals, low-level causes, retry hints, or data that should not be exposed to API clients. +Do not map every domain error into one universal HTTP error class. Prefer a +small public error vocabulary by route group: shared shapes like +`ApiNotFoundError`, route-specific shapes like `ConfigApiError`, and built-in +empty `HttpApiError.*` only when an empty/no-content body is the intended SDK +contract. + ## Mapping Guidance - Keep one-off translations inline in the handler. @@ -86,6 +129,35 @@ that should not be exposed to API clients. breaking API change. - Use built-in `HttpApiError.*` only when its generated body and SDK surface are intentionally the public contract. +- Prefer `Schema.ErrorClass` for public HTTP error bodies whose wire shape is + not the same as the internal domain error shape. +- Prefer `Schema.TaggedErrorClass` for service/domain errors and middleware + errors that are naturally tagged by `_tag`. +- If preserving a legacy `{ name, data }` body, model that shape explicitly in + the public API error schema instead of relying on `NamedError.toObject()` in + generic middleware. + +## User-Facing Rendering + +HTTP serialization and user rendering are separate boundaries. The server +should send structured public errors; CLI and TUI code should format those +structures through one shared formatter. + +For SDK calls using `{ throwOnError: true }`, the generated client may wrap the +decoded response body in an `Error`. The original body should remain available +under `error.cause.body`; `FormatError` is the right place to unwrap and render +that body. TUI aggregation helpers should call `FormatError` first, then fall +back to generic `Error.message` / string rendering. + +When several parallel startup requests fail from the same underlying issue, +group identical rendered messages and list the affected request names once. +For example: + +```text +Configuration is invalid at /path/to/opencode.json +↳ Expected object, got "not-object" provider.bad.options +Affected startup requests: config.providers, provider.list, app.agents, config.get +``` ## Middleware Guidance @@ -99,6 +171,15 @@ middleware should shrink. It should not gain new name checks. Unknown `500` responses should log full details server-side with `Cause.pretty(cause)` and return a safe public body. +The config startup regression in #27056 is the failure mode this rule is meant +to avoid: a user-authored invalid `opencode.json` crossed the HttpApi boundary +as a defect, so middleware replaced a useful `ConfigInvalidError` with a safe +generic `UnknownError`. The compatibility fix is to preserve config parse and +validation errors as client-visible `400`s. The target architecture is better: +config loading should fail on the typed error channel, config HTTP handlers +should map those errors to declared `ConfigApiError` responses, and the generic +middleware should never see them. + ## Migration Order Prefer small vertical slices: @@ -113,6 +194,9 @@ Prefer small vertical slices: Good early domains are storage not-found, worktree errors, and provider auth validation errors because they currently drive HTTP behavior. +Config parse and validation errors are also a good early slice because they +are startup-blocking and must be rendered clearly in both CLI and TUI flows. + ## Checklist For A PR - [ ] Expected failures are typed errors, not defects. diff --git a/packages/opencode/specs/effect/facades.md b/packages/opencode/specs/effect/facades.md index 8bf7d97badc..f7e3165f007 100644 --- a/packages/opencode/specs/effect/facades.md +++ b/packages/opencode/specs/effect/facades.md @@ -6,7 +6,6 @@ Current status on this branch: - `src/` has 5 `makeRuntime(...)` call sites total. - 2 are intentionally excluded from this checklist: `src/bus/index.ts` and `src/effect/cross-spawn-spawner.ts`. -- 1 is tracked primarily by the instance-context migration rather than facade removal: `src/project/instance.ts`. - That leaves 2 live runtime-backed service facades still worth tracking here: `src/npm/index.ts` and `src/cli/cmd/tui/config/tui.ts`. Recent progress: @@ -18,7 +17,6 @@ Recent progress: - `src/cli/cmd/tui/config/tui.ts` still exports `makeRuntime(...)` plus async facade helpers for `get()` and `waitForDependencies()`. - `src/npm/index.ts` still exports `makeRuntime(...)` plus async facade helpers for `install()`, `add()`, `outdated()`, and `which()`. -- `src/project/instance.ts` still uses a dedicated runtime for project boot, but that file is really part of the broader legacy instance-context transition tracked in `instance-context.md`. ## Completed Batches @@ -192,7 +190,6 @@ Most of the original facade-removal backlog is already done. The practical remai 1. remove the `Npm` runtime-backed facade from `src/npm/index.ts` 2. remove the `TuiConfig` runtime-backed facade from `src/cli/cmd/tui/config/tui.ts` -3. keep `src/project/instance.ts` in the separate instance-context migration, not this checklist ## Checklist diff --git a/packages/opencode/specs/effect/guide.md b/packages/opencode/specs/effect/guide.md index 5df02934485..e8a1a19c564 100644 --- a/packages/opencode/specs/effect/guide.md +++ b/packages/opencode/specs/effect/guide.md @@ -197,13 +197,9 @@ For background loops, use `Effect.repeat` or `Effect.schedule` with [`EffectBridge`](../../src/effect/bridge.ts) is the sanctioned helper for Promise/callback interop that needs to preserve instance/workspace context. -Keep it, but reduce its dependency on legacy `Instance.current` / -`Instance.restore` over time. - -`Instance.bind` / `Instance.restore` are transitional legacy tools. Use -them only for native callbacks that still require legacy ALS context. Do -not use them for `setTimeout`, `Promise.then`, `EventEmitter.on`, or -Effect fibers. +It preserves explicit `InstanceRef` / `WorkspaceRef` context for effects run +through the bridge. Plain JS callbacks that need instance data should receive +that data explicitly. ## Testing diff --git a/packages/opencode/specs/effect/instance-context.md b/packages/opencode/specs/effect/instance-context.md index 6d63715030f..94564004c9c 100644 --- a/packages/opencode/specs/effect/instance-context.md +++ b/packages/opencode/specs/effect/instance-context.md @@ -1,309 +1,13 @@ -# Instance context migration +# Instance Context -Practical plan for retiring the promise-backed / ALS-backed `Instance` helper in `src/project/instance.ts` and moving instance selection fully into Effect-provided scope. +Instance selection is now Effect-provided context. -## Goal +Use these APIs: -End state: +- `InstanceRef` for the current project context. +- `WorkspaceRef` for the current workspace id. +- `InstanceState.context` / `InstanceState.directory` inside Effect services that require an instance. +- `InstanceStore` at entry boundaries that need to load, reload, or dispose project contexts. +- `EffectBridge` for native, plugin, or plain JavaScript callback boundaries that need to re-enter Effect with captured refs. -- request, CLI, TUI, and tool entrypoints shift into an instance through Effect, not `Instance.provide(...)` -- Effect code reads the current instance from `InstanceRef` or its eventual replacement, not from ALS-backed sync getters -- per-directory boot, caching, and disposal are scoped Effect resources, not a module-level `Map>` -- ALS remains only as a temporary bridge for native callback APIs that fire outside the Effect fiber tree - -## Current split - -Today `src/project/instance.ts` still owns two separate concerns: - -- ambient current-instance context through `LocalContext` / `AsyncLocalStorage` -- per-directory boot and deduplication through `cache: Map>` - -At the same time, the Effect side already exists: - -- `src/effect/instance-ref.ts` provides `InstanceRef` and `WorkspaceRef` -- `src/effect/run-service.ts` already attaches those refs when a runtime starts inside an active instance ALS context -- `src/effect/instance-state.ts` already prefers `InstanceRef` and only falls back to ALS when needed - -That means the migration is not "invent instance context in Effect". The migration is "stop relying on the legacy helper as the primary source of truth". - -## End state shape - -Near-term target shape: - -```ts -InstanceScope.with({ directory, workspaceID }, effect) -``` - -Responsibilities of `InstanceScope.with(...)`: - -- resolve `directory`, `project`, and `worktree` -- acquire or reuse the scoped per-directory instance environment -- provide `InstanceRef` and `WorkspaceRef` -- run the caller's Effect inside that environment - -Code inside the boundary should then do one of these: - -```ts -const ctx = yield * InstanceState.context -const dir = yield * InstanceState.directory -``` - -Long-term, once `InstanceState` itself is replaced by keyed layers / `LayerMap`, those reads can move to an `InstanceContext` service without changing the outer migration order. - -## Migration phases - -### Phase 1: stop expanding the legacy surface - -Rules for all new code: - -- do not add new `Instance.directory`, `Instance.worktree`, `Instance.project`, or `Instance.current` reads inside Effect code -- do not add new `Instance.provide(...)` boundaries unless there is no Effect-native seam yet -- use `InstanceState.context`, `InstanceState.directory`, or an explicit `ctx` parameter inside Effect code - -Success condition: - -- the file inventory below only shrinks from here - -### Phase 2: remove direct sync getter reads from Effect services - -Convert Effect services first, before replacing the top-level boundary. These modules already run inside Effect and mostly need `yield* InstanceState.context` or a yielded `ctx` instead of ambient sync access. - -Primary batch, highest payoff: - -- `src/file/index.ts` -- `src/lsp/server.ts` -- `src/worktree/index.ts` -- `src/file/watcher.ts` -- `src/format/formatter.ts` -- `src/session/index.ts` -- `src/project/vcs.ts` - -Mechanical replacement rule: - -- `Instance.directory` -> `ctx.directory` or `yield* InstanceState.directory` -- `Instance.worktree` -> `ctx.worktree` -- `Instance.project` -> `ctx.project` - -Do not thread strings manually through every public method if the service already has access to Effect context. - -### Phase 3: convert entry boundaries to provide instance refs directly - -After the service bodies stop assuming ALS, move the top-level boundaries to shift into Effect explicitly. - -Main boundaries: - -- HTTP server middleware and experimental `HttpApi` entrypoints -- CLI commands -- TUI worker / attach / thread entrypoints -- tool execution entrypoints - -These boundaries should become Effect-native wrappers that: - -- decode directory / workspace inputs -- resolve the instance context once -- provide `InstanceRef` and `WorkspaceRef` -- run the requested Effect - -At that point `Instance.provide(...)` becomes a legacy adapter instead of the normal code path. - -### Phase 4: replace promise boot cache with scoped instance runtime - -Once boundaries and services both rely on Effect context, replace the module-level promise cache in `src/project/instance.ts`. - -Target replacement: - -- keyed scoped runtime or keyed layer acquisition for each directory -- reuse via `ScopedCache`, `LayerMap`, or another keyed Effect resource manager -- cleanup performed by scope finalizers instead of `disposeAll()` iterating a Promise map - -This phase should absorb the current responsibilities of: - -- `cache` in `src/project/instance.ts` -- `boot(...)` -- most of `disposeInstance(...)` -- manual `reload(...)` / `disposeAll()` fan-out logic - -### Phase 5: shrink ALS to callback bridges only - -Keep ALS only where a library invokes callbacks outside the Effect fiber tree and we still need to call code that reads instance context synchronously. - -Known bridge cases today: - -- `src/file/watcher.ts` -- `src/session/llm.ts` -- some LSP and plugin callback paths - -If those libraries become fully wrapped in Effect services, the remaining `Instance.bind(...)` uses can disappear too. - -### Phase 6: delete the legacy sync API - -Only after earlier phases land: - -- remove broad use of `Instance.current`, `Instance.directory`, `Instance.worktree`, `Instance.project` -- reduce `src/project/instance.ts` to a thin compatibility shim or delete it entirely -- remove the ALS fallback from `InstanceState.context` - -## Inventory of direct legacy usage - -Direct legacy usage means any source file that still calls one of: - -- `Instance.current` -- `Instance.directory` -- `Instance.worktree` -- `Instance.project` -- `Instance.provide(...)` -- `Instance.bind(...)` -- `Instance.restore(...)` -- `Instance.reload(...)` -- `Instance.dispose()` / `Instance.disposeAll()` - -Current total: `56` files in `packages/opencode/src`. - -### Core bridge and plumbing - -These files define or adapt the current bridge. They should change last, after callers have moved. - -- `src/project/instance.ts` -- `src/effect/run-service.ts` -- `src/effect/instance-state.ts` -- `src/project/bootstrap.ts` -- `src/config/config.ts` - -Migration rule: - -- keep these as compatibility glue until the outer boundaries and inner services stop depending on ALS - -### HTTP and server boundaries - -These are the current request-entry seams that still create or consume instance context through the legacy helper. - -- `src/server/routes/instance/middleware.ts` -- `src/server/routes/instance/index.ts` -- `src/server/routes/instance/project.ts` -- `src/server/routes/control/workspace.ts` -- `src/server/routes/instance/file.ts` -- `src/server/routes/instance/experimental.ts` -- `src/server/routes/global.ts` - -Migration rule: - -- move these to explicit Effect entrypoints that provide `InstanceRef` / `WorkspaceRef` -- do not move these first; first reduce the number of downstream handlers and services that still expect ambient ALS - -### CLI and TUI boundaries - -These commands still enter an instance through `Instance.provide(...)` or read sync getters directly. - -- `src/cli/bootstrap.ts` -- `src/cli/cmd/agent.ts` -- `src/cli/cmd/debug/agent.ts` -- `src/cli/cmd/debug/ripgrep.ts` -- `src/cli/cmd/github.ts` -- `src/cli/cmd/import.ts` -- `src/cli/cmd/mcp.ts` -- `src/cli/cmd/models.ts` -- `src/cli/cmd/plug.ts` -- `src/cli/cmd/pr.ts` -- `src/cli/cmd/providers.ts` -- `src/cli/cmd/stats.ts` -- `src/cli/cmd/tui/attach.ts` -- `src/cli/cmd/tui/plugin/runtime.ts` -- `src/cli/cmd/tui/thread.ts` -- `src/cli/cmd/tui/worker.ts` - -Migration rule: - -- converge these on one shared `withInstance(...)` Effect entry helper instead of open-coded `Instance.provide(...)` -- after that helper is proven, inline the legacy implementation behind an Effect-native scope provider - -### Tool boundary code - -These tools mostly use direct getters for path resolution and repo-relative display logic. - -- `src/tool/apply_patch.ts` -- `src/tool/bash.ts` -- `src/tool/edit.ts` -- `src/tool/lsp.ts` -- `src/tool/plan.ts` -- `src/tool/read.ts` -- `src/tool/write.ts` - -Migration rule: - -- expose the current instance as an explicit Effect dependency for tool execution -- keep path logic local; avoid introducing another global singleton for tool state - -### Effect services still reading ambient instance state - -These modules are already the best near-term migration targets because they are in Effect code but still read sync getters from the legacy helper. - -- `src/agent/agent.ts` -- `src/cli/cmd/tui/config/tui-migrate.ts` -- `src/file/index.ts` -- `src/file/watcher.ts` -- `src/format/formatter.ts` -- `src/lsp/client.ts` -- `src/lsp/index.ts` -- `src/lsp/server.ts` -- `src/mcp/index.ts` -- `src/project/vcs.ts` -- `src/provider/provider.ts` -- `src/pty/index.ts` -- `src/session/session.ts` -- `src/session/instruction.ts` -- `src/session/llm.ts` -- `src/session/system.ts` -- `src/sync/index.ts` -- `src/worktree/index.ts` - -Migration rule: - -- replace direct getter reads with `yield* InstanceState.context` or a yielded `ctx` -- isolate `Instance.bind(...)` callers and convert only the truly callback-driven edges to bridge mode - -### Highest-churn hotspots - -Current highest direct-usage counts by file: - -- `src/file/index.ts` - `18` -- `src/lsp/server.ts` - `14` -- `src/worktree/index.ts` - `12` -- `src/file/watcher.ts` - `9` -- `src/cli/cmd/mcp.ts` - `8` -- `src/format/formatter.ts` - `8` -- `src/tool/apply_patch.ts` - `8` -- `src/cli/cmd/github.ts` - `7` - -These files should drive the first measurable burn-down. - -## Recommended implementation order - -1. Migrate direct getter reads inside Effect services, starting with `file`, `lsp`, `worktree`, `format`, and `session`. -2. Add one shared Effect-native boundary helper for CLI / tool / HTTP entrypoints so we stop open-coding `Instance.provide(...)`. -3. Move experimental `HttpApi` entrypoints to that helper so the new server stack proves the pattern. -4. Convert remaining CLI and tool boundaries. -5. Replace the promise cache with a keyed scoped runtime or keyed layer map. -6. Delete ALS fallback paths once only callback bridges still depend on them. - -## Definition of done - -This migration is done when all of the following are true: - -- new requests and commands enter an instance by providing Effect context, not ALS -- Effect services no longer read `Instance.directory`, `Instance.worktree`, `Instance.project`, or `Instance.current` -- `Instance.provide(...)` is gone from normal request / CLI / tool execution -- per-directory boot and disposal are handled by scoped Effect resources -- `Instance.bind(...)` is either gone or confined to a tiny set of native callback adapters - -## Tracker and worktree - -Active tracker items: - -- `lh7l73` - overall `HttpApi` migration -- `yobwlk` - remove direct `Instance.*` reads inside Effect services -- `7irl1e` - replace `InstanceState` / legacy instance caching with keyed Effect layers - -Dedicated worktree for this transition: - -- path: `/Users/kit/code/open-source/opencode-worktrees/instance-effect-shift` -- branch: `kit/instance-effect-shift` +Do not add new ambient instance globals. Promise and callback boundaries should either stay in Effect, use `EffectBridge`, or pass the required context explicitly. diff --git a/packages/opencode/specs/effect/loose-ends.md b/packages/opencode/specs/effect/loose-ends.md index 4e7ada7ff91..d30efd18155 100644 --- a/packages/opencode/specs/effect/loose-ends.md +++ b/packages/opencode/specs/effect/loose-ends.md @@ -24,10 +24,6 @@ Small follow-ups that do not fit neatly into the main facade, route, tool, or sc - [ ] `cli/cmd/tui/config/tui.ts` - switch TUI config loading from async `ConfigPaths.*` wrappers to the `ConfigPaths.Service` once that service exists. - [ ] `cli/cmd/tui/config/tui-migrate.ts` - decide whether to leave this as a plain async module using wrapper functions or effectify it fully after `ConfigPaths.Service` lands. -## Instance cleanup - -- [ ] `project/instance.ts` - keep shrinking the legacy ALS / Promise cache after the remaining `Instance.*` callers move over. - ## Notes - Prefer small, semantics-preserving config migrations. Config precedence, legacy key migration, and plugin origin tracking are easy to break accidentally. diff --git a/packages/opencode/specs/effect/todo.md b/packages/opencode/specs/effect/todo.md index 68bcd0d7177..67fa49f8062 100644 --- a/packages/opencode/specs/effect/todo.md +++ b/packages/opencode/specs/effect/todo.md @@ -64,13 +64,11 @@ P6 OA explicit and testable instead of mutable module state. Shrinks: [`global.ts`](../../../core/src/global.ts) import-time side effects, mutable `Global.Path` overrides, and its `Flag` dependency. -- `INST` Instance shim — remove ambient `Instance` usage and old ALS - access patterns. - Shrinks: [`src/project/instance.ts`](../../src/project/instance.ts). +- `INST` Instance context — keep project context explicit through Effect refs + and bridge boundaries. - `BRIDGE` Promise/callback interop — keep bridge helpers, but reduce legacy ALS coupling. - Shrinks: [`src/effect/bridge.ts`](../../src/effect/bridge.ts) - dependency on [`project/instance.ts`](../../src/project/instance.ts). + Shrinks: ad hoc Promise/callback re-entry code. - `PROC` AppProcess migration — prefer `AppProcess.Service` over raw process wrappers. Shrinks: direct spawn callsites and legacy process helpers. @@ -221,74 +219,13 @@ Next PR candidates: ## P4: Instance And Bridge -[`project/instance.ts`](../../src/project/instance.ts) is the deletion -target. [`effect/bridge.ts`](../../src/effect/bridge.ts) is not a near-term -deletion target; Promise/callback interop will continue to exist. +Instance context migration is complete for the legacy sync shim. Promise and callback interop continues through [`effect/bridge.ts`](../../src/effect/bridge.ts). -Goal: +Current rules: -- Keep a sanctioned bridge for Promise/callback boundaries. -- Reduce bridge dependence on legacy `Instance.restore` / `Instance.current`. -- Move callers toward `InstanceRef`, `WorkspaceRef`, `InstanceState`, or - explicit context where practical. -- Delete `project/instance.ts` only after ambient Instance coupling is gone. - -Important distinction: - -- `InstanceState.context`, `InstanceState.directory`, and - `InstanceState.workspaceID` are acceptable inside normal Effect service - code when `InstanceRef` / `WorkspaceRef` are provided by the runtime. -- The deletion blockers are the fallback and callback paths that rely on - ambient ALS: direct `Instance.*` reads, `InstanceState.bind(...)`, - `AppRuntime.runPromise(...)` re-entry from plain JS, and bridge restore - code that installs legacy ALS before invoking callbacks. - -Current bottom-up inventory from `dev`: - -- Direct `Instance.*` value readers: - [`tool/repo_overview.ts`](../../src/tool/repo_overview.ts), - [`control-plane/adapters/worktree.ts`](../../src/control-plane/adapters/worktree.ts), - [`cli/bootstrap.ts`](../../src/cli/bootstrap.ts). -- `InstanceState.bind(...)` callback boundaries: - [`file/watcher.ts`](../../src/file/watcher.ts) native watcher callback, - [`storage/db.ts`](../../src/storage/db.ts) transaction/effect callbacks, - [`session/llm.ts`](../../src/session/llm.ts) workflow approval callback. -- `AppRuntime.runPromise(...)` / re-entry from plain JS: - [`project/with-instance.ts`](../../src/project/with-instance.ts), - [`project/instance-runtime.ts`](../../src/project/instance-runtime.ts), - [`control-plane/adapters/worktree.ts`](../../src/control-plane/adapters/worktree.ts), - [`cli/effect-cmd.ts`](../../src/cli/effect-cmd.ts), plus global/non-instance - callsites such as CLI upgrade and ACP agent defaults. -- Intentional bridge users to classify, not delete blindly: - workspace adapters in [`control-plane/workspace.ts`](../../src/control-plane/workspace.ts), - MCP, command execution, plugins, pty lifecycle, bus scope cleanup, task - cancellation, and HTTP lifecycle reload/dispose paths. -- Core fallback layer to shrink last: - [`effect/run-service.ts`](../../src/effect/run-service.ts), - [`effect/bridge.ts`](../../src/effect/bridge.ts), and - [`effect/instance-state.ts`](../../src/effect/instance-state.ts). - -Recommended PR order: - -- [ ] `INST-1` Remove direct `Instance.*` value readers. Start with - `repo_overview`, `worktree` adapter, and `cli/bootstrap`; pass context - explicitly or obtain it from an Effect boundary. -- [ ] `INST-2` Move type-only `InstanceContext` imports from - [`project/instance.ts`](../../src/project/instance.ts) to - [`project/instance-context.ts`](../../src/project/instance-context.ts). -- [ ] `INST-3` Audit each `InstanceState.bind(...)` callback from the inside - out: list what the callback calls (`Bus.publish`, database effects, - permission/session services), then replace ambient capture with explicit - `InstanceRef` / `WorkspaceRef` provision or an `EffectBridge` call. -- [ ] `INST-4` Classify `AppRuntime.runPromise(...)` callsites as global, - instance-scoped with explicit refs, or bridge-required. Eliminate the - instance-scoped callsites that rely on `run-service.attach()` falling - back to `Instance.current`. -- [ ] `INST-5` After consumers are explicit, remove `Instance.current` fallback - from `InstanceState.context` and `run-service.attach()`. -- [ ] `INST-6` Move any remaining `restore` / `bind` compatibility helpers to - the boundary that still needs them, then delete - [`project/instance.ts`](../../src/project/instance.ts). +- Effect services read instance data from `InstanceRef`, `WorkspaceRef`, `InstanceState`, or explicit arguments. +- Plain JavaScript callback boundaries use `EffectBridge` or explicit context arguments. +- Runtime entrypoints must provide refs explicitly when they are instance-scoped. ## Lower Priority Tracks diff --git a/packages/opencode/src/acp/agent.ts b/packages/opencode/src/acp/agent.ts index 683bc7df554..2a6817cbcc6 100644 --- a/packages/opencode/src/acp/agent.ts +++ b/packages/opencode/src/acp/agent.ts @@ -39,10 +39,9 @@ import { Filesystem } from "@/util/filesystem" import { Hash } from "@opencode-ai/core/util/hash" import { ACPSessionManager } from "./session" import type { ACPConfig } from "./types" +import { ACPRuntime } from "./runtime" import { Provider } from "@/provider/provider" import { ModelID, ProviderID } from "../provider/schema" -import { Agent as AgentModule } from "../agent/agent" -import { AppRuntime } from "@/effect/app-runtime" import { Installation } from "@/installation" import { MessageV2 } from "@/session/message-v2" import { Config } from "@/config/config" @@ -1119,7 +1118,7 @@ export class Agent implements ACPAgent { const currentModeId = await (async () => { if (!availableModes.length) return undefined - const defaultAgent = await AppRuntime.runPromise(AgentModule.Service.use((svc) => svc.defaultInfo())) + const defaultAgent = await ACPRuntime.defaultAgentInfo(directory) const resolvedModeId = availableModes.find((mode) => mode.name === defaultAgent.name)?.id ?? availableModes[0].id this.sessionManager.setMode(sessionId, resolvedModeId) return resolvedModeId @@ -1353,8 +1352,7 @@ export class Agent implements ACPAgent { if (!current) { this.sessionManager.setModel(session.id, model) } - const agent = - session.modeId ?? (await AppRuntime.runPromise(AgentModule.Service.use((svc) => svc.defaultInfo()))).name + const agent = session.modeId ?? (await ACPRuntime.defaultAgentInfo(directory)).name const parts: Array< | { type: "text"; text: string; synthetic?: boolean; ignored?: boolean } diff --git a/packages/opencode/src/acp/runtime.ts b/packages/opencode/src/acp/runtime.ts new file mode 100644 index 00000000000..b08c73cf2e2 --- /dev/null +++ b/packages/opencode/src/acp/runtime.ts @@ -0,0 +1,22 @@ +import { Agent } from "@/agent/agent" +import { AppRuntime, type AppServices } from "@/effect/app-runtime" +import { InstanceRef } from "@/effect/instance-ref" +import { InstanceRuntime } from "@/project/instance-runtime" +import { Effect } from "effect" + +// Global ACP Effect re-entry: no project InstanceRef is provided. +export const runGlobal = AppRuntime.runPromise + +// Directory-scoped ACP Effect re-entry: load the project instance and provide InstanceRef. +export async function runDirectory(input: { directory: string; effect: Effect.Effect }) { + const ctx = await InstanceRuntime.load({ directory: input.directory }) + return AppRuntime.runPromise(input.effect.pipe(Effect.provideService(InstanceRef, ctx))) +} + +export const defaultAgentInfo = (directory: string) => + runDirectory({ + directory, + effect: Agent.Service.use((svc) => svc.defaultInfo()), + }) + +export * as ACPRuntime from "./runtime" diff --git a/packages/opencode/src/bus/bus-event.ts b/packages/opencode/src/bus/bus-event.ts index 35337063185..5a9e52ef073 100644 --- a/packages/opencode/src/bus/bus-event.ts +++ b/packages/opencode/src/bus/bus-event.ts @@ -1,4 +1,5 @@ import { Schema } from "effect" +import { EventV2 } from "@opencode-ai/core/event" export type Definition = { type: Type @@ -17,16 +18,28 @@ export function define( } export function effectPayloads() { - return registry - .entries() - .map(([type, def]) => - Schema.Struct({ - id: Schema.String, - type: Schema.Literal(type), - properties: def.properties, - }).annotate({ identifier: `Event.${type}` }), - ) - .toArray() + return [ + ...registry + .entries() + .map(([type, def]) => + Schema.Struct({ + id: Schema.String, + type: Schema.Literal(type), + properties: def.properties, + }).annotate({ identifier: `Event.${type}` }), + ) + .toArray(), + ...EventV2.registry + .values() + .map((definition) => + Schema.Struct({ + id: Schema.String, + type: Schema.Literal(definition.type), + properties: definition.data, + }).annotate({ identifier: `Event.${definition.type}` }), + ) + .toArray(), + ] } export * as BusEvent from "./bus-event" diff --git a/packages/opencode/src/bus/index.ts b/packages/opencode/src/bus/index.ts index 449694a53a3..853a249880e 100644 --- a/packages/opencode/src/bus/index.ts +++ b/packages/opencode/src/bus/index.ts @@ -1,4 +1,4 @@ -import { Effect, Exit, Layer, PubSub, Scope, Context, Stream, Schema } from "effect" +import { Effect, Exit, Fiber, Layer, PubSub, Scope, Context, Stream, Schema } from "effect" import { EffectBridge } from "@/effect/bridge" import * as Log from "@opencode-ai/core/util/log" import { BusEvent } from "./bus-event" @@ -6,6 +6,9 @@ import { GlobalBus } from "./global" import { InstanceState } from "@/effect/instance-state" import { makeRuntime } from "@/effect/run-service" import { Identifier } from "@/id/id" +import { context as instanceContext, type InstanceContext } from "@/project/instance-context" +import { InstanceRef } from "@/effect/instance-ref" +import { LocalContext } from "@/util/local-context" // kilocode_change const log = Log.create({ service: "bus" }) @@ -185,19 +188,45 @@ export function createID() { } export async function publish( + ctx: InstanceContext, def: D, properties: BusProperties, options?: { id?: string }, ) { - return runPromise((svc) => svc.publish(def, properties, options)) + return runPromise((svc) => svc.publish(def, properties, options).pipe(Effect.provideService(InstanceRef, ctx))) +} + +// kilocode_change start - legacy callback facade inherits the active instance context +function active() { + const fiber = Fiber.getCurrent() + const current = fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined + if (current) return current + try { + return instanceContext.use() + } catch (err) { + if (!(err instanceof LocalContext.NotFound)) throw err + } } export function subscribe(def: D, callback: (event: Payload) => unknown) { - return runSync((svc) => svc.subscribeCallback(def, callback)) + const ctx = active() + if (!ctx) throw new Error("Instance context not available") + return runSync((svc) => + svc + .subscribeCallback(def, (event) => instanceContext.provide(ctx, () => callback(event))) + .pipe(Effect.provideService(InstanceRef, ctx)), + ) } export function subscribeAll(callback: (event: any) => unknown) { - return runSync((svc) => svc.subscribeAllCallback(callback)) + const ctx = active() + if (!ctx) throw new Error("Instance context not available") + return runSync((svc) => + svc + .subscribeAllCallback((event) => instanceContext.provide(ctx, () => callback(event))) + .pipe(Effect.provideService(InstanceRef, ctx)), + ) } +// kilocode_change end export * as Bus from "." diff --git a/packages/opencode/src/cli/bootstrap.ts b/packages/opencode/src/cli/bootstrap.ts index fa39ecb177b..2308c29199b 100644 --- a/packages/opencode/src/cli/bootstrap.ts +++ b/packages/opencode/src/cli/bootstrap.ts @@ -1,17 +1,11 @@ -import { Instance } from "../project/instance" import { InstanceRuntime } from "../project/instance-runtime" -import { WithInstance } from "../project/with-instance" +import { context } from "../project/instance-context" export async function bootstrap(directory: string, cb: () => Promise) { - return WithInstance.provide({ - directory, - fn: async () => { - try { - const result = await cb() - return result - } finally { - await InstanceRuntime.disposeInstance(Instance.current) - } - }, - }) + const ctx = await InstanceRuntime.load({ directory }) + try { + return await context.provide(ctx, cb) + } finally { + await InstanceRuntime.disposeInstance(ctx) + } } diff --git a/packages/opencode/src/cli/cmd/agent.ts b/packages/opencode/src/cli/cmd/agent.ts index c7151a2125a..d2c72c2c4db 100644 --- a/packages/opencode/src/cli/cmd/agent.ts +++ b/packages/opencode/src/cli/cmd/agent.ts @@ -66,6 +66,8 @@ const AgentCreateCommand = effectCmd({ if (!maybeCtx) return yield* Effect.die("InstanceRef not provided") const ctx = maybeCtx const agentSvc = yield* Agent.Service + const runLocalEffect = (effect: Effect.Effect) => + Effect.runPromise(effect.pipe(Effect.provideService(InstanceRef, ctx))) yield* Effect.promise(async () => { const cliPath = args.path const cliDescription = args.description @@ -130,7 +132,7 @@ const AgentCreateCommand = effectCmd({ const spinner = prompts.spinner() spinner.start("Generating agent configuration...") const model = args.model ? Provider.parseModel(args.model) : undefined - const generated = await Effect.runPromise(agentSvc.generate({ description, model })).catch((error) => { + const generated = await runLocalEffect(agentSvc.generate({ description, model })).catch((error) => { spinner.stop(`LLM failed to generate agent: ${error.message}`, 1) if (isFullyNonInteractive) process.exit(1) throw new UI.CancelledError() diff --git a/packages/opencode/src/cli/cmd/debug/agent.ts b/packages/opencode/src/cli/cmd/debug/agent.ts index 1a3f79396c0..ac9879ff891 100644 --- a/packages/opencode/src/cli/cmd/debug/agent.ts +++ b/packages/opencode/src/cli/cmd/debug/agent.ts @@ -11,7 +11,7 @@ import { Permission } from "../../../permission" import { iife } from "../../../util/iife" import { effectCmd, fail } from "../../effect-cmd" import { InstanceRef } from "@/effect/instance-ref" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" export const AgentCommand = effectCmd({ command: "agent ", diff --git a/packages/opencode/src/cli/cmd/debug/v2.ts b/packages/opencode/src/cli/cmd/debug/v2.ts index 507f82cdf53..836f5813672 100644 --- a/packages/opencode/src/cli/cmd/debug/v2.ts +++ b/packages/opencode/src/cli/cmd/debug/v2.ts @@ -1,11 +1,11 @@ import { EOL } from "os" import { Effect, Layer, Option } from "effect" import { Catalog } from "@opencode-ai/core/catalog" -import { InstanceServiceMap } from "@opencode-ai/core/instance-layer" +import { LocationServiceMap } from "@opencode-ai/core/location-layer" import { PluginBoot } from "@opencode-ai/core/plugin/boot" import { effectCmd } from "../../effect-cmd" -const Runtime = Layer.mergeAll(InstanceServiceMap.layer) +const Runtime = Layer.mergeAll(LocationServiceMap.layer) export const V2Command = effectCmd({ command: "v2", @@ -37,7 +37,7 @@ export const V2Command = effectCmd({ process.stdout.write(JSON.stringify(result, null, 2) + EOL) }, Effect.provide( - InstanceServiceMap.get({ + LocationServiceMap.get({ directory: process.cwd(), }), ), diff --git a/packages/opencode/src/cli/cmd/github.ts b/packages/opencode/src/cli/cmd/github.ts index 2cdffebc52c..6400575318e 100644 --- a/packages/opencode/src/cli/cmd/github.ts +++ b/packages/opencode/src/cli/cmd/github.ts @@ -442,6 +442,9 @@ export const GithubRunCommand = effectCmd({ const sessionSvc = yield* Session.Service const sessionShare = yield* SessionShare.Service const sessionPrompt = yield* SessionPrompt.Service + const busSvc = yield* Bus.Service + const runLocalEffect = (effect: Effect.Effect) => + Effect.runPromise(effect.pipe(Effect.provideService(InstanceRef, ctx))) yield* Effect.promise(async () => { const isMock = args.token || args.event @@ -555,7 +558,7 @@ export const GithubRunCommand = effectCmd({ // Setup kilo session // kilocode_change const repoData = await fetchRepo() - session = await Effect.runPromise( + session = await runLocalEffect( sessionSvc.create({ permission: [ { @@ -566,11 +569,11 @@ export const GithubRunCommand = effectCmd({ ], }), ) - subscribeSessionEvents() + await subscribeSessionEvents() shareId = await (async () => { if (share === false) return if (!share && repoData.data.private) return - await Effect.runPromise(sessionShare.share(session.id)) + await runLocalEffect(sessionShare.share(session.id)) return session.id.slice(-8) })() console.log("kilo session", session.id) // kilocode_change @@ -877,7 +880,7 @@ export const GithubRunCommand = effectCmd({ return { userPrompt: prompt, promptFiles: imgData } } - function subscribeSessionEvents() { + async function subscribeSessionEvents() { const TOOL: Record = { todowrite: ["Todo", UI.Style.TEXT_WARNING_BOLD], bash: ["Shell", UI.Style.TEXT_DANGER_BOLD], @@ -900,33 +903,35 @@ export const GithubRunCommand = effectCmd({ } let text = "" - Bus.subscribe(MessageV2.Event.PartUpdated, (evt) => { - if (evt.properties.part.sessionID !== session.id) return - //if (evt.properties.part.messageID === messageID) return - const part = evt.properties.part + await runLocalEffect( + busSvc.subscribeCallback(MessageV2.Event.PartUpdated, (evt) => { + if (evt.properties.part.sessionID !== session.id) return + //if (evt.properties.part.messageID === messageID) return + const part = evt.properties.part - if (part.type === "tool" && part.state.status === "completed") { - const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD] - const title = - part.state.title || Object.keys(part.state.input).length > 0 - ? JSON.stringify(part.state.input) - : "Unknown" - console.log() - printEvent(color, tool, title) - } - - if (part.type === "text") { - text = part.text - - if (part.time?.end) { - UI.empty() - UI.println(UI.markdown(text)) - UI.empty() - text = "" - return + if (part.type === "tool" && part.state.status === "completed") { + const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD] + const title = + part.state.title || Object.keys(part.state.input).length > 0 + ? JSON.stringify(part.state.input) + : "Unknown" + console.log() + printEvent(color, tool, title) } - } - }) + + if (part.type === "text") { + text = part.text + + if (part.time?.end) { + UI.empty() + UI.println(UI.markdown(text)) + UI.empty() + text = "" + return + } + } + }), + ) } async function summarize(response: string) { @@ -943,7 +948,7 @@ export const GithubRunCommand = effectCmd({ async function chat(message: string, files: PromptFiles = []) { console.log("Sending message to kilo...") // kilocode_change - return Effect.runPromise( + return runLocalEffect( Effect.gen(function* () { const prompt = sessionPrompt const result = yield* prompt.prompt({ diff --git a/packages/opencode/src/cli/cmd/prompt-display.ts b/packages/opencode/src/cli/cmd/prompt-display.ts index 7ec4bc0af55..4e8cb9046ac 100644 --- a/packages/opencode/src/cli/cmd/prompt-display.ts +++ b/packages/opencode/src/cli/cmd/prompt-display.ts @@ -1,11 +1,20 @@ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" }) +function promptOffsetWidth(value: string) { + let width = 0 + for (const part of graphemes.segment(value)) { + // Textarea offsets count newlines as one position; Bun.stringWidth counts them as zero. + width += part.segment === "\n" ? 1 : Bun.stringWidth(part.segment) + } + return width +} + function displayOffsetIndex(value: string, offset: number) { if (offset <= 0) return 0 let width = 0 for (const part of graphemes.segment(value)) { - const next = width + Bun.stringWidth(part.segment) + const next = width + promptOffsetWidth(part.segment) if (next > offset) return part.index width = next } @@ -13,20 +22,20 @@ function displayOffsetIndex(value: string, offset: number) { return value.length } -export function displaySlice(value: string, start = 0, end = Bun.stringWidth(value)) { +export function displaySlice(value: string, start = 0, end = promptOffsetWidth(value)) { return value.slice(displayOffsetIndex(value, start), displayOffsetIndex(value, end)) } export function displayCharAt(value: string, offset: number) { let width = 0 for (const part of graphemes.segment(value)) { - const next = width + Bun.stringWidth(part.segment) + const next = width + promptOffsetWidth(part.segment) if (offset === width || offset < next) return part.segment width = next } } -export function mentionTriggerIndex(value: string, offset = Bun.stringWidth(value)) { +export function mentionTriggerIndex(value: string, offset = promptOffsetWidth(value)) { const text = displaySlice(value, 0, offset) const index = text.lastIndexOf("@") if (index === -1) return @@ -34,6 +43,6 @@ export function mentionTriggerIndex(value: string, offset = Bun.stringWidth(valu const before = index === 0 ? undefined : text[index - 1] const query = text.slice(index) if ((before === undefined || /\s/.test(before)) && !/\s/.test(query)) { - return Bun.stringWidth(text.slice(0, index)) + return promptOffsetWidth(text.slice(0, index)) } } diff --git a/packages/opencode/src/cli/cmd/remote.ts b/packages/opencode/src/cli/cmd/remote.ts index 95459186d7c..51b222e0a77 100644 --- a/packages/opencode/src/cli/cmd/remote.ts +++ b/packages/opencode/src/cli/cmd/remote.ts @@ -2,7 +2,7 @@ import { cmd } from "./cmd" import { bootstrap } from "../bootstrap" import { KiloSessions } from "@/kilo-sessions/kilo-sessions" -import { Instance } from "@/project/instance" +import { context } from "@/project/instance-context" import { InstanceRuntime } from "@/project/instance-runtime" export const RemoteCommand = cmd({ @@ -18,7 +18,7 @@ export const RemoteCommand = cmd({ const shutdown = async () => { try { KiloSessions.disableRemote() - await InstanceRuntime.disposeInstance(Instance.current) + await InstanceRuntime.disposeInstance(context.use()) } finally { abort.abort() } diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index eb744e73625..acb26efa872 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -27,6 +27,7 @@ import { createKiloClient, type KiloClient, type ToolPart } from "@kilocode/sdk/ import { Agent } from "@/agent/agent" import { Permission } from "@/permission" import { RuntimeFlags } from "@/effect/runtime-flags" +import { InstanceRef } from "@/effect/instance-ref" import { FormatError, FormatUnknownError } from "../error" import { INTERACTIVE_INPUT_ERROR, resolveInteractiveStdin } from "./run/runtime.stdin" import { event as normalizeEvent } from "./run/event" @@ -256,6 +257,7 @@ export const RunCommand = effectCmd({ handler: Effect.fn("Cli.run")(function* (args) { const agentSvc = yield* Agent.Service const flags = yield* RuntimeFlags.Service + const localInstance = yield* InstanceRef yield* Effect.promise(async () => { const rawMessage = [...args.message, ...(args["--"] || [])].join(" ") const thinking = args.interactive ? (args.thinking ?? true) : (args.thinking ?? false) @@ -566,7 +568,9 @@ export const RunCommand = effectCmd({ if (!args.agent) return undefined const name = args.agent - const entry = await Effect.runPromise(agentSvc.get(name)) + const entry = await Effect.runPromise( + agentSvc.get(name).pipe(Effect.provideService(InstanceRef, localInstance)), + ) if (!entry) { UI.println( UI.Style.TEXT_WARNING_BOLD + "!", diff --git a/packages/opencode/src/cli/cmd/tui/app.tsx b/packages/opencode/src/cli/cmd/tui/app.tsx index 383a11b3de5..2ae583ddbc9 100644 --- a/packages/opencode/src/cli/cmd/tui/app.tsx +++ b/packages/opencode/src/cli/cmd/tui/app.tsx @@ -83,8 +83,6 @@ const appBindingCommands = [ "command.palette.show", "session.list", "session.new", - "session.cycle_recent", - "session.cycle_recent_reverse", "session.quick_switch.1", "session.quick_switch.2", "session.quick_switch.3", @@ -503,37 +501,15 @@ function App(props: { onSnapshot?: () => Promise }) { dialog.clear() }, }, - ...(Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING - ? [ - { - name: "session.cycle_recent", - title: "Cycle to previous recent session", - category: "Session", - hidden: true, - run: () => { - local.session.cycleRecent(1) - }, - }, - { - name: "session.cycle_recent_reverse", - title: "Cycle to next recent session", - category: "Session", - hidden: true, - run: () => { - local.session.cycleRecent(-1) - }, - }, - ...Array.from({ length: 9 }, (_, i) => ({ - name: `session.quick_switch.${i + 1}`, - title: `Switch to session in quick slot ${i + 1}`, - category: "Session", - hidden: true, - run: () => { - local.session.quickSwitch(i + 1) - }, - })), - ] - : []), + ...Array.from({ length: 9 }, (_, i) => ({ + name: `session.quick_switch.${i + 1}`, + title: `Switch to session in quick slot ${i + 1}`, + category: "Session", + hidden: true, + run: () => { + local.session.quickSwitch(i + 1) + }, + })), { name: "model.list", title: "Switch model", @@ -852,14 +828,7 @@ function App(props: { onSnapshot?: () => Promise }) { useBindings(() => ({ enabled: command.matcher, - bindings: tuiConfig.keybinds.gather( - "app", - Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING - ? appBindingCommands - : appBindingCommands.filter( - (c) => !c.startsWith("session.cycle_recent") && !c.startsWith("session.quick_switch"), - ), - ), + bindings: tuiConfig.keybinds.gather("app", appBindingCommands), })) useBindings(() => ({ @@ -914,6 +883,7 @@ function App(props: { onSnapshot?: () => Promise }) { }) event.on("installation.update-available", async (evt) => { + console.log("installation.update-available", evt) const version = evt.properties.version const skipped = kv.get("skipped_version") diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx index 0add96c2027..86c11e7d41c 100644 --- a/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx @@ -33,6 +33,8 @@ export function DialogSessionList() { const [search, setSearch] = createDebouncedSignal("", 150) const [global, setGlobal] = createSignal(true) // kilocode_change - show all worktrees by default const deleteHint = useCommandShortcut("session.delete") + const quickSwitch1 = useCommandShortcut("session.quick_switch.1") + const quickSwitch9 = useCommandShortcut("session.quick_switch.9") // kilocode_change start - always fetch from experimental endpoint (returns GlobalSession with worktree info) // TODO: extend /experimental/session to accept `scope`/`path` so this dialog can respect the @@ -154,10 +156,18 @@ export function DialogSessionList() { const [browseOrder] = createSignal(orderByRecency(sync.data.session)) - const RECENT_LIMIT = 5 + const quickSwitchHint = createMemo(() => { + const first = quickSwitch1() + const last = quickSwitch9() + if (!first || !last) return undefined + return quickSwitchRange(first, last) + }) + const quickSwitchFooterHints = createMemo(() => { + const hint = quickSwitchHint() + return hint && local.session.slots().length > 0 ? [{ title: "switch", label: hint }] : [] + }) const options = createMemo(() => { - const enabled = Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING const today = new Date().toDateString() const all = global() // kilocode_change const sessionMap = new Map( @@ -169,17 +179,9 @@ export function DialogSessionList() { const searchResult = searchResults() const displayOrder = searchResult ? orderByRecency(searchResult) : browseOrder() - const dismissed = enabled ? new Set(local.session.dismissedRecent()) : new Set() - const pinned = enabled ? local.session.pinned().filter((id) => sessionMap.has(id)) : [] + const pinned = local.session.pinned().filter((id) => sessionMap.has(id)) const pinnedSet = new Set(pinned) - const slotByID = enabled - ? new Map(local.session.slots().map((id, i) => [id, i + 1])) - : new Map() - - const recent = enabled - ? displayOrder.filter((id) => !pinnedSet.has(id) && !dismissed.has(id)).slice(0, RECENT_LIMIT) - : [] - const recentSet = new Set(recent) + const slotByID = new Map(local.session.slots().map((id, i) => [id, i + 1])) function buildOption(id: string, category: string) { const x = sessionMap.get(id) @@ -224,7 +226,7 @@ export function DialogSessionList() { } const remaining = displayOrder - .filter((id) => !pinnedSet.has(id) && !recentSet.has(id)) + .filter((id) => !pinnedSet.has(id)) .map((id) => { const x = sessionMap.get(id) if (!x) return undefined @@ -233,11 +235,7 @@ export function DialogSessionList() { }) .filter((x) => x !== undefined) - return [ - ...pinned.map((id) => buildOption(id, "Pinned")).filter((x) => x !== undefined), - ...recent.map((id) => buildOption(id, "Recent")).filter((x) => x !== undefined), - ...remaining, - ] + return [...pinned.map((id) => buildOption(id, "Pinned")).filter((x) => x !== undefined), ...remaining] }) onMount(() => { @@ -262,32 +260,13 @@ export function DialogSessionList() { dialog.clear() }} actions={[ - ...(Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING - ? [ - { - command: "session.pin.toggle", - title: "pin/unpin", - onTrigger: (option: { value: string }) => { - local.session.togglePin(option.value) - }, - }, - { - command: "session.toggle.recent", - title: "toggle recent", - onTrigger: (option: { value: string }) => { - if (local.session.isPinned(option.value)) { - toast.show({ - variant: "info", - message: "Unpin the session first to toggle it in Recent", - duration: 3000, - }) - return - } - local.session.toggleRecent(option.value) - }, - }, - ] - : []), + { + command: "session.pin.toggle", + title: "pin/unpin", + onTrigger: (option: { value: string }) => { + local.session.togglePin(option.value) + }, + }, { command: "session.delete", title: "delete", @@ -366,6 +345,13 @@ export function DialogSessionList() { // kilocode_change start - preserve Ctrl+A worktree scope toggle with the upstream keymap engine bindings={[{ key: "ctrl+a", cmd: "session.scope.toggle" }]} // kilocode_change end + footerHints={quickSwitchFooterHints()} /> ) } + +function quickSwitchRange(first: string, last: string) { + const prefix = first.slice(0, -1) + if (first.endsWith("1") && last === `${prefix}9`) return `${prefix}1-9` + return `${first} through ${last}` +} diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx b/packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx index 8b1f2ca3669..48dcc543700 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx @@ -27,6 +27,11 @@ export type PromptInfo = { const MAX_HISTORY_ENTRIES = 50 +export function isDuplicateEntry(previous: PromptInfo | undefined, next: PromptInfo): boolean { + if (!previous) return false + return JSON.stringify(previous) === JSON.stringify(next) +} + export const { use: usePromptHistory, provider: PromptHistoryProvider } = createSimpleContext({ name: "PromptHistory", init: () => { @@ -83,6 +88,10 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create }, append(item: PromptInfo) { const entry = structuredClone(unwrap(item)) + if (isDuplicateEntry(store.history.at(-1), entry)) { + setStore("index", 0) + return + } let trimmed = false setStore( produce((draft) => { diff --git a/packages/opencode/src/cli/cmd/tui/config/keybind.ts b/packages/opencode/src/cli/cmd/tui/config/keybind.ts index f6d05dd3110..5c7bd2507ef 100644 --- a/packages/opencode/src/cli/cmd/tui/config/keybind.ts +++ b/packages/opencode/src/cli/cmd/tui/config/keybind.ts @@ -87,9 +87,6 @@ export const Definitions = { session_child_cycle_reverse: keybind("left", "Go to previous child session"), session_parent: keybind("up", "Go to parent session"), session_pin_toggle: keybind("ctrl+f", "Pin or unpin session in the session list"), - session_toggle_recent: keybind("ctrl+h", "Show or hide session in the Recent group"), - session_cycle_recent: keybind("]", "Cycle to the previous recent session"), - session_cycle_recent_reverse: keybind("[", "Cycle to the next recent session"), session_quick_switch_1: keybind("1", "Switch to session in quick slot 1"), session_quick_switch_2: keybind("2", "Switch to session in quick slot 2"), session_quick_switch_3: keybind("3", "Switch to session in quick slot 3"), @@ -278,9 +275,6 @@ export const CommandMap = { session_child_cycle_reverse: "session.child.previous", session_parent: "session.parent", session_pin_toggle: "session.pin.toggle", - session_toggle_recent: "session.toggle.recent", - session_cycle_recent: "session.cycle_recent", - session_cycle_recent_reverse: "session.cycle_recent_reverse", session_quick_switch_1: "session.quick_switch.1", session_quick_switch_2: "session.quick_switch.2", session_quick_switch_3: "session.quick_switch.3", diff --git a/packages/opencode/src/cli/cmd/tui/context/aggregate-failures.ts b/packages/opencode/src/cli/cmd/tui/context/aggregate-failures.ts index 63b3fb44876..8b652b6512d 100644 --- a/packages/opencode/src/cli/cmd/tui/context/aggregate-failures.ts +++ b/packages/opencode/src/cli/cmd/tui/context/aggregate-failures.ts @@ -1,3 +1,5 @@ +import { FormatError } from "@/cli/error" + /** * Aggregate Promise.allSettled results into a single Error that names every * failed endpoint, or return null when all fulfilled. Used at TUI bootstrap @@ -15,7 +17,19 @@ export function aggregateFailures(labeled: LabeledSettled[]): Error | null { ) if (failed.length === 0) return null - const reasons = failed.map((f) => `${f.name}: ${reasonMessage(f.result.reason)}`).join("; ") + const reasons = Array.from( + failed + .map((f) => ({ name: f.name, message: reasonMessage(f.result.reason) })) + .reduce((grouped, failure) => { + grouped.set(failure.message, [...(grouped.get(failure.message) ?? []), failure.name]) + return grouped + }, new Map()) + .entries(), + ) + .map(([message, names]) => + names.length === 1 ? `${names[0]}: ${message}` : `${message}\nAffected startup requests: ${names.join(", ")}`, + ) + .join("; ") const summary = `${failed.length} of ${labeled.length} requests failed: ${reasons}` const err = new Error(summary) err.cause = { failures: failed.map((f) => ({ name: f.name, reason: f.result.reason })) } @@ -23,6 +37,9 @@ export function aggregateFailures(labeled: LabeledSettled[]): Error | null { } function reasonMessage(reason: unknown): string { + const formatted = FormatError(reason) + if (formatted) return formatted + if (reason instanceof Error) return reason.message if (typeof reason === "string") return reason if (reason && typeof reason === "object") { diff --git a/packages/opencode/src/cli/cmd/tui/context/local.tsx b/packages/opencode/src/cli/cmd/tui/context/local.tsx index 1c162fab798..cc86e39cc25 100644 --- a/packages/opencode/src/cli/cmd/tui/context/local.tsx +++ b/packages/opencode/src/cli/cmd/tui/context/local.tsx @@ -1,6 +1,6 @@ import { createStore } from "solid-js/store" import { createSimpleContext } from "./helper" -import { batch, createEffect, createMemo, on } from "solid-js" +import { batch, createEffect, createMemo } from "solid-js" import { useSync } from "@tui/context/sync" import { useTheme } from "@tui/context/theme" import { useRoute } from "@tui/context/route" @@ -8,7 +8,6 @@ import { useEvent } from "@tui/context/event" import { uniqueBy } from "remeda" import path from "path" import { Global } from "@opencode-ai/core/global" -import { Flag } from "@opencode-ai/core/flag/flag" import { iife } from "@/util/iife" import { useToast } from "../ui/toast" import { useArgs } from "./args" @@ -454,13 +453,9 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ const [sessionStore, setSessionStore] = createStore<{ ready: boolean pinned: string[] - dismissedRecent: string[] - recentOrder: string[] }>({ ready: false, pinned: [], - dismissedRecent: [], - recentOrder: [], }) const filePath = path.join(Global.Path.state, "session.json") @@ -476,16 +471,12 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ state.pending = false void Filesystem.writeJson(filePath, { pinned: sessionStore.pinned, - dismissedRecent: sessionStore.dismissedRecent, - recentOrder: sessionStore.recentOrder, }) } Filesystem.readJson(filePath) .then((x: any) => { if (Array.isArray(x.pinned)) setSessionStore("pinned", x.pinned) - if (Array.isArray(x.dismissedRecent)) setSessionStore("dismissedRecent", x.dismissedRecent) - if (Array.isArray(x.recentOrder)) setSessionStore("recentOrder", x.recentOrder) }) .catch(() => {}) .finally(() => { @@ -495,19 +486,10 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ const route = useRoute() const event = useEvent() - let cycling = false const slots = createMemo(() => { - const rootSessions = sync.data.session.filter((x) => x.parentID === undefined) - const existing = new Set(rootSessions.map((x) => x.id)) - const dismissed = new Set(sessionStore.dismissedRecent) - const pins = sessionStore.pinned.filter((id) => existing.has(id)) - const pinnedSet = new Set(pins) - const recent = rootSessions - .filter((x) => !pinnedSet.has(x.id) && !dismissed.has(x.id)) - .toSorted((a, b) => b.time.updated - a.time.updated) - .map((x) => x.id) - return [...pins, ...recent].slice(0, 9) + const existing = new Set(sync.data.session.filter((x) => x.parentID === undefined).map((x) => x.id)) + return sessionStore.pinned.filter((id) => existing.has(id)).slice(0, 9) }) function prune(sessionID: string) { @@ -518,18 +500,6 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ sessionStore.pinned.filter((x) => x !== sessionID), ) } - if (sessionStore.dismissedRecent.includes(sessionID)) { - setSessionStore( - "dismissedRecent", - sessionStore.dismissedRecent.filter((x) => x !== sessionID), - ) - } - if (sessionStore.recentOrder.includes(sessionID)) { - setSessionStore( - "recentOrder", - sessionStore.recentOrder.filter((x) => x !== sessionID), - ) - } save() }) } @@ -538,25 +508,6 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ prune(evt.data.sessionID) }) - if (Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING) { - createEffect( - on( - () => (sessionStore.ready && route.data.type === "session" ? route.data.sessionID : undefined), - (sessionID) => { - if (!sessionID) return - if (cycling) { - cycling = false - return - } - const filtered = sessionStore.recentOrder.filter((x) => x !== sessionID) - const next = [sessionID, ...filtered].slice(0, 20) - setSessionStore("recentOrder", next) - save() - }, - ), - ) - } - return { get ready() { return sessionStore.ready @@ -564,75 +515,26 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ pinned() { return sessionStore.pinned }, - dismissedRecent() { - return sessionStore.dismissedRecent - }, - recentOrder() { - return sessionStore.recentOrder - }, slots, isPinned(sessionID: string) { return sessionStore.pinned.includes(sessionID) }, - isDismissed(sessionID: string) { - return sessionStore.dismissedRecent.includes(sessionID) - }, togglePin(sessionID: string) { batch(() => { const exists = sessionStore.pinned.includes(sessionID) const next = exists ? sessionStore.pinned.filter((x) => x !== sessionID) - : [sessionID, ...sessionStore.pinned] + : [...sessionStore.pinned, sessionID] setSessionStore("pinned", next) save() }) }, - toggleRecent(sessionID: string) { - batch(() => { - const exists = sessionStore.dismissedRecent.includes(sessionID) - const next = exists - ? sessionStore.dismissedRecent.filter((x) => x !== sessionID) - : [sessionID, ...sessionStore.dismissedRecent] - setSessionStore("dismissedRecent", next) - save() - }) - }, quickSwitch(slot: number) { const target = slots()[slot - 1] if (!target) return if (route.data.type === "session" && route.data.sessionID === target) return route.navigate({ type: "session", sessionID: target }) }, - cycleRecent(direction: 1 | -1) { - if (route.data.type !== "session") { - toast.show({ - variant: "info", - message: "Open a session first to cycle between recent sessions", - duration: 3000, - }) - return - } - const current = route.data.sessionID - const order = sessionStore.recentOrder.filter((id) => - sync.data.session.some((s) => s.id === id && s.parentID === undefined), - ) - if (order.length < 2) { - toast.show({ - variant: "info", - message: "No other recent sessions to cycle to", - duration: 3000, - }) - return - } - const index = order.indexOf(current) - if (index === -1) return - const next = index + direction - if (next < 0 || next >= order.length) return - const target = order[next] - if (!target || target === current) return - cycling = true - route.navigate({ type: "session", sessionID: target }) - }, } }) diff --git a/packages/opencode/src/cli/cmd/tui/context/theme.tsx b/packages/opencode/src/cli/cmd/tui/context/theme.tsx index 6c0fee733f4..28bbbcf2f3b 100644 --- a/packages/opencode/src/cli/cmd/tui/context/theme.tsx +++ b/packages/opencode/src/cli/cmd/tui/context/theme.tsx @@ -984,6 +984,7 @@ function getSyntaxRules(theme: Theme) { style: { foreground: theme.markdownHeading, bold: true, + underline: true, }, }, { diff --git a/packages/opencode/src/cli/cmd/tui/context/thinking.ts b/packages/opencode/src/cli/cmd/tui/context/thinking.ts new file mode 100644 index 00000000000..55e995df11e --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/context/thinking.ts @@ -0,0 +1,66 @@ +import { createMemo, type Setter } from "solid-js" +import { useKV } from "./kv" + +export type ThinkingMode = "show" | "hide" + +const MODES: readonly ThinkingMode[] = ["show", "hide"] as const + +// OpenAI's Responses API surfaces reasoning summaries that start with a bolded +// title line: "**Inspecting PR workflow**\n\n". GitHub Copilot routes +// through the same shape, and the opencode provider relays it too. Pull the +// title out for a nicer label; return null for providers that don't follow +// this convention so the caller can fall back to a generic "Thinking" string. +export function reasoningTitle(text: string): string | null { + const match = text.trimStart().match(/^\*\*([^*\n]+)\*\*/) + return match ? match[1].trim() : null +} + +export function isThinkingMode(value: unknown): value is ThinkingMode { + return typeof value === "string" && (MODES as readonly string[]).includes(value) +} + +// Cycle order matches the slash command: show → hide → show. +export function nextThinkingMode(current: ThinkingMode): ThinkingMode { + const idx = MODES.indexOf(current) + return MODES[(idx + 1) % MODES.length] ?? "show" +} + +export function useThinkingMode() { + const kv = useKV() + // Capture pre-state before `kv.signal` seeds a default, so we can detect + // first-time users with a legacy `thinking_visibility` boolean and migrate. + // The KVProvider only renders children once kv.ready, so reads here are safe. + const hadStored = kv.get("thinking_mode") !== undefined + const legacy = kv.get("thinking_visibility") + const [stored, setStored] = kv.signal("thinking_mode", "hide") + + // The kv signal exposes its setter typed as `Setter` which carries Solid's + // overload set; passing an updater fn through a property access loses the + // bivariance trick the existing `setX((prev) => ...)` callsites rely on. + // Wrap it in a sane shape so consumers can just call `set(next)` or pass + // an updater. + const set = (next: ThinkingMode | ((prev: ThinkingMode) => ThinkingMode)) => { + if (typeof next === "function") setStored(next as Setter) + else setStored(() => next) + } + + // Preserve previous experience for users who had explicitly toggled the + // legacy `thinking_visibility` boolean. First-time users (no legacy key) + // get the new "hide" default (collapsed thinking). + if (!hadStored) { + if (legacy === true) set("show") + else if (legacy === false) set("hide") + } + + if ((stored() as string) === "minimal") set("hide") + + const mode = createMemo(() => { + const value = stored() + return isThinkingMode(value) ? value : "hide" + }) + + return { + mode, + set, + } +} diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx index 15489f2aab4..e4c01668cba 100644 --- a/packages/opencode/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx @@ -1,7 +1,6 @@ import type { TuiPluginApi } from "@kilocode/plugin/tui" import { createMemo, For, type Accessor } from "solid-js" import { DEFAULT_THEMES, useTheme } from "@tui/context/theme" -import { Flag } from "@opencode-ai/core/flag/flag" import { useCommandShortcut } from "../../keymap" const themeCount = Object.keys(DEFAULT_THEMES).length @@ -29,8 +28,6 @@ type Shortcuts = { messagesToggleConceal: TipShortcut modelCycleRecent: TipShortcut modelList: TipShortcut - sessionCycleRecent: TipShortcut - sessionCycleRecentReverse: TipShortcut sessionExport: TipShortcut sessionInterrupt: TipShortcut sessionList: TipShortcut @@ -41,7 +38,6 @@ type Shortcuts = { sessionQuickSwitch9: TipShortcut sessionSidebarToggle: TipShortcut sessionTimeline: TipShortcut - sessionToggleRecent: TipShortcut statusView: TipShortcut terminalSuspend: TipShortcut themeList: TipShortcut @@ -73,6 +69,7 @@ function parse(tip: string): TipPart[] { } const NO_MODELS_TIP = "Run {highlight}/connect{/highlight} to add an AI provider and start coding" +const NO_MODELS_PARTS = parse(NO_MODELS_TIP) function shortcutText(value: string) { return `{highlight}${value}{/highlight}` @@ -121,8 +118,6 @@ export function Tips(props: { api: TuiPluginApi; connected?: boolean }) { messagesToggleConceal: configShortcut(props.api, "session.toggle.conceal"), modelCycleRecent: useCommandShortcut("model.cycle_recent"), modelList: useCommandShortcut("model.list"), - sessionCycleRecent: useCommandShortcut("session.cycle_recent"), - sessionCycleRecentReverse: useCommandShortcut("session.cycle_recent_reverse"), sessionExport: configShortcut(props.api, "session.export"), sessionInterrupt: configShortcut(props.api, "session.interrupt"), sessionList: useCommandShortcut("session.list"), @@ -133,7 +128,6 @@ export function Tips(props: { api: TuiPluginApi; connected?: boolean }) { sessionQuickSwitch9: useCommandShortcut("session.quick_switch.9"), sessionSidebarToggle: configShortcut(props.api, "session.sidebar.toggle"), sessionTimeline: configShortcut(props.api, "session.timeline"), - sessionToggleRecent: configShortcut(props.api, "session.toggle.recent"), statusView: useCommandShortcut("opencode.status"), terminalSuspend: useCommandShortcut("terminal.suspend"), themeList: useCommandShortcut("theme.switch"), @@ -145,8 +139,13 @@ export function Tips(props: { api: TuiPluginApi; connected?: boolean }) { return value ? [value] : [] }) return tips[Math.floor(tipOffset * tips.length)] ?? NO_MODELS_TIP - }) - const parts = createMemo(() => parse(tip())) + }, NO_MODELS_TIP) + // Solid can expose a memo's initial value while a pure computation is pending. + const parts = createMemo(() => { + const value = tip() + if (typeof value === "string") return parse(value) + return NO_MODELS_PARTS + }, NO_MODELS_PARTS) return ( @@ -176,23 +175,12 @@ const TIPS: Tip[] = [ (shortcuts) => `Use ${commandText("/models", shortcuts.modelList())} to see and switch between available AI models`, (shortcuts) => `Use ${commandText("/themes", shortcuts.themeList())} to switch between ${themeCount} built-in themes`, (shortcuts) => `Use ${commandText("/new", shortcuts.sessionNew())} to start a fresh conversation session`, - (shortcuts) => `Use ${commandText("/sessions", shortcuts.sessionList())} to list and continue previous conversations`, - ...(Flag.KILO_EXPERIMENTAL_SESSION_SWITCHING - ? ([ - (shortcuts) => - press(shortcuts.sessionPinToggle(), "in the session list to pin a session so it stays at the top"), - (shortcuts) => - shortcuts.sessionQuickSwitch1() && shortcuts.sessionQuickSwitch9() - ? `Pinned and recent sessions are bound to ${shortcutText(shortcuts.sessionQuickSwitch1())} through ${shortcutText(shortcuts.sessionQuickSwitch9())} for one-press switching` - : undefined, - (shortcuts) => - shortcuts.sessionCycleRecent() && shortcuts.sessionCycleRecentReverse() - ? `Press ${shortcutText(shortcuts.sessionCycleRecent())} / ${shortcutText(shortcuts.sessionCycleRecentReverse())} to cycle through recently visited sessions` - : undefined, - (shortcuts) => - press(shortcuts.sessionToggleRecent(), "in the session list to show or hide a session in the Recent group"), - ] satisfies Tip[]) - : []), + (shortcuts) => `Use ${commandText("/sessions", shortcuts.sessionList())} to list, pin, and continue sessions`, + (shortcuts) => press(shortcuts.sessionPinToggle(), "in the session list to pin a session so it stays at the top"), + (shortcuts) => + shortcuts.sessionQuickSwitch1() && shortcuts.sessionQuickSwitch9() + ? `Pinned sessions are assigned quick slots; use ${shortcutText(shortcuts.sessionQuickSwitch1())} through ${shortcutText(shortcuts.sessionQuickSwitch9())} to switch` + : undefined, "Run {highlight}/compact{/highlight} to summarize long sessions near context limits", (shortcuts) => `Use ${commandText("/export", shortcuts.sessionExport())} to save the conversation as Markdown`, (shortcuts) => press(shortcuts.messagesCopy(), "to copy the assistant's last message to clipboard"), diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx index f3d29d9016c..130bfa71e33 100644 --- a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx @@ -5,6 +5,7 @@ import { SplitBorder } from "@tui/component/border" import { Spinner } from "@tui/component/spinner" import { useTheme } from "@tui/context/theme" import { useLocal } from "@tui/context/local" +import { reasoningTitle, useThinkingMode } from "@tui/context/thinking" import { useRenderer, useTerminalDimensions, type JSX } from "@opentui/solid" import { TextAttributes, type BoxRenderable, type SyntaxStyle } from "@opentui/core" import { useBindings } from "../../keymap" @@ -317,7 +318,11 @@ function AssistantMessage(props: { - + props.message.time.completed} + /> @@ -378,30 +383,64 @@ function AssistantText(props: { part: SessionMessageAssistantText; syntax: Synta ) } -function AssistantReasoning(props: { part: SessionMessageAssistantReasoning; subtleSyntax: SyntaxStyle }) { +function AssistantReasoning(props: { + part: SessionMessageAssistantReasoning + subtleSyntax: SyntaxStyle + completedAt: () => number | undefined +}) { const { theme } = useTheme() + const thinking = useThinkingMode() + const [expanded, setExpanded] = createSignal(false) const content = createMemo(() => props.part.text.replace("[REDACTED]", "").trim()) + const inMinimal = createMemo(() => thinking.mode() === "hide") + // v2 reasoning parts have no per-part `time.end` (see SessionMessageAssistantReasoning + // in the v2 SDK); we settle on parent-message completion instead. + const isDone = createMemo(() => props.completedAt() !== undefined) + const title = createMemo(() => reasoningTitle(content())) + + const toggle = () => { + if (!inMinimal()) return + setExpanded((prev) => !prev) + } + return ( - - - + + + + + + + + + + {title() ? "▶ Thought: " + title() : "▶ Thought"} + + + + + + {title() ? "Thinking: " + title() : "Thinking"} + + + ) } diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx index e299c6d7050..eaa25b74002 100644 --- a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx @@ -100,6 +100,7 @@ import { formatMarkdownTables } from "../../util/markdown" import { bell } from "@/kilocode/bell" import { submitFeedback } from "@/kilocode/cli/cmd/tui/feedback" // kilocode_change end +import { nextThinkingMode, reasoningTitle, useThinkingMode, type ThinkingMode } from "../../context/thinking" import { getScrollAcceleration } from "../../util/scroll" import { TuiPluginRuntime } from "@/cli/cmd/tui/plugin/runtime" import { DialogRetryAction } from "../../component/dialog-retry-action" @@ -179,6 +180,7 @@ const context = createContext<{ width: number sessionID: string conceal: () => boolean + thinkingMode: () => ThinkingMode showThinking: () => boolean showTimestamps: () => boolean showDetails: () => boolean @@ -310,7 +312,9 @@ export function Session() { const [sidebar, setSidebar] = kv.signal<"auto" | "hide">("sidebar", "auto") const [sidebarOpen, setSidebarOpen] = createSignal(false) const [conceal, setConceal] = createSignal(true) - const [showThinking, setShowThinking] = kv.signal("thinking_visibility", true) + const thinking = useThinkingMode() + const thinkingMode = thinking.mode + const showThinking = createMemo(() => true) const [timestamps, setTimestamps] = kv.signal<"hide" | "show">("timestamps", "hide") const [showDetails, setShowDetails] = kv.signal("tool_details_visibility", true) const [showAssistantMetadata, _setShowAssistantMetadata] = kv.signal("assistant_metadata_visibility", true) @@ -823,7 +827,11 @@ export function Session() { }, }, { - title: showThinking() ? "Hide thinking" : "Show thinking", + title: (() => { + const next = nextThinkingMode(thinkingMode()) + if (next === "hide") return "Collapse thinking" + return "Expand thinking" + })(), value: "session.toggle.thinking", category: "Session", slash: { @@ -831,7 +839,7 @@ export function Session() { aliases: ["toggle-thinking"], }, run: () => { - setShowThinking((prev) => !prev) + thinking.set(nextThinkingMode(thinkingMode())) dialog.clear() }, }, @@ -1253,6 +1261,7 @@ export function Session() { }, sessionID: route.sessionID, conceal, + thinkingMode, showThinking, showTimestamps, showDetails, @@ -1689,32 +1698,77 @@ const PART_MAPPING = { function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: AssistantMessage }) { const { theme, subtleSyntax } = useTheme() const ctx = use() + // Collapsed by default in hide mode: a single line throughout, so the + // layout never shifts. Click to open the full markdown block, click to close. + const [expanded, setExpanded] = createSignal(false) + const content = createMemo(() => { - // Filter out redacted reasoning chunks from OpenRouter - // OpenRouter sends encrypted reasoning data that appears as [REDACTED] + // OpenRouter encrypts some reasoning blocks; drop the placeholder. return props.part.text.replace("[REDACTED]", "").trim() }) + // Reasoning is finalized when the server sets `time.end` (see processor.ts). + // Flips independently of the parent message completing. + const isDone = createMemo(() => props.part.time.end !== undefined) + const inMinimal = createMemo(() => ctx.thinkingMode() === "hide") + const duration = createMemo(() => { + const end = props.part.time.end + return end === undefined ? 0 : Math.max(0, end - props.part.time.start) + }) + // OpenAI / Copilot / opencode-via-OpenAI emit `**Title**\n\n` summary + // blocks. Surface the title both while streaming and after settling so the + // collapsed line carries real signal, not just a duration. + const title = createMemo(() => reasoningTitle(content())) + + const toggle = () => { + if (!inMinimal()) return + setExpanded((prev) => !prev) + } + return ( - - - - + + + + {/* Full markdown block: `show` mode, or `hide` after the user opens it. */} + + + + + + {/* Settled: ▶ at the start as the click-to-expand cue. */} + + + {"▶ " + + (title() + ? "Thought: " + title() + " · " + Locale.duration(duration()) + : "Thought for " + Locale.duration(duration()))} + + + + + {/* Streaming: leading animated spinner, no disclosure arrow yet — it + snaps in once reasoning settles, signalling "done, click to expand". */} + + {title() ? "Thinking: " + title() : "Thinking"} + + + ) } @@ -1733,6 +1787,7 @@ function TextPart(props: { last: boolean; part: TextPart; message: AssistantMess streaming={true} internalBlockMode="top-level" content={props.part.text.trim()} + tableOptions={{ style: "grid" }} conceal={ctx.conceal()} fg={theme.markdownText} bg={theme.background} diff --git a/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx b/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx index a791aebc307..700735d38cb 100644 --- a/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx +++ b/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx @@ -38,6 +38,11 @@ export interface DialogSelectProps { disabled?: boolean onTrigger: (option: DialogSelectOption) => void }[] + footerHints?: { + title: string + label: string + side?: "left" | "right" + }[] bindings?: readonly Binding[] current?: T } @@ -334,11 +339,12 @@ export function DialogSelect(props: DialogSelectProps) { } props.ref?.(ref) - const visibleActions = createMemo(() => - actions() + const visibleActions = createMemo(() => [ + ...actions() .map((item) => ({ ...item, label: actionLabels().get(item.command) ?? "" })) .filter((item) => !item.disabled && item.label), - ) + ...(props.footerHints ?? []), + ]) const left = createMemo(() => visibleActions().filter((item) => item.side !== "right")) const right = createMemo(() => visibleActions().filter((item) => item.side === "right")) diff --git a/packages/opencode/src/cli/cmd/tui/worker.ts b/packages/opencode/src/cli/cmd/tui/worker.ts index c6198988768..fe989ac7643 100644 --- a/packages/opencode/src/cli/cmd/tui/worker.ts +++ b/packages/opencode/src/cli/cmd/tui/worker.ts @@ -2,7 +2,6 @@ import { Installation } from "@/installation" import { Server } from "@/server/server" import * as Log from "@opencode-ai/core/util/log" import { InstanceRuntime } from "@/project/instance-runtime" -import { WithInstance } from "@/project/with-instance" import { Rpc } from "@/util/rpc" import { upgrade } from "@/cli/upgrade" import { Config } from "@/config/config" @@ -77,12 +76,8 @@ export const rpc = { return { url: server.url.toString() } }, async checkUpgrade(input: { directory: string }) { - await WithInstance.provide({ - directory: input.directory, - fn: async () => { - await upgrade().catch(() => {}) - }, - }) + await InstanceRuntime.load({ directory: input.directory }) + await upgrade().catch(() => {}) }, async reload() { await AppRuntime.runPromise( diff --git a/packages/opencode/src/cli/effect-cmd.ts b/packages/opencode/src/cli/effect-cmd.ts index ada5f8677d7..c96bc99ac42 100644 --- a/packages/opencode/src/cli/effect-cmd.ts +++ b/packages/opencode/src/cli/effect-cmd.ts @@ -3,7 +3,6 @@ import { Effect, Schema } from "effect" import { AppRuntime, type AppServices } from "@/effect/app-runtime" import { InstanceStore } from "@/project/instance-store" import { InstanceRef } from "@/effect/instance-ref" -import { Instance } from "@/project/instance" import { cmd, type WithDoubleDash } from "./cmd/cmd" /** @@ -83,19 +82,11 @@ export const effectCmd = (opts: EffectCmdOpts) => return } const directory = opts.directory?.(args) ?? process.cwd() - // Two-phase: load ctx, then run body inside Instance.current ALS. - // Effect's InstanceRef is provided via fiber context, but that context is - // lost across `await` inside `Effect.promise(async () => ...)` callbacks - // — when handlers re-enter Effect via `AppRuntime.runPromise(svc.method())` - // there, attach() falls back to Instance.current ALS, which Node preserves - // across awaits. Matches the pre-effectCmd `bootstrap()` behavior. const { store, ctx } = await AppRuntime.runPromise( InstanceStore.Service.use((store) => store.load({ directory }).pipe(Effect.map((ctx) => ({ store, ctx })))), ) try { - await Instance.restore(ctx, () => - AppRuntime.runPromise(opts.handler(args).pipe(Effect.provideService(InstanceRef, ctx))), - ) + await AppRuntime.runPromise(opts.handler(args).pipe(Effect.provideService(InstanceRef, ctx))) } finally { await AppRuntime.runPromise(store.dispose(ctx)) } diff --git a/packages/opencode/src/cli/error.ts b/packages/opencode/src/cli/error.ts index c3bbc9968e1..f370505906a 100644 --- a/packages/opencode/src/cli/error.ts +++ b/packages/opencode/src/cli/error.ts @@ -2,16 +2,9 @@ import { NamedError } from "@opencode-ai/core/util/error" import { errorFormat } from "@/util/error" import { isRecord } from "@/util/record" -interface ErrorLike { - name?: string - _tag?: string - message?: string - data?: Record -} - type ConfigIssue = { message: string; path: string[] } -function isTaggedError(error: unknown, tag: string): boolean { +function isTaggedError(error: unknown, tag: string): error is Record { return isRecord(error) && error._tag === tag } @@ -39,22 +32,27 @@ function configIssues(input: Record): ConfigIssue[] { : [] } -export function FormatError(input: unknown) { +export function FormatError(input: unknown): string | undefined { + if (input instanceof Error && isRecord(input.cause) && "body" in input.cause) { + const formatted = FormatError(input.cause.body) + if (formatted) return formatted + } + // CliError: domain failure surfaced from an effectCmd handler via fail("...") if (isTaggedError(input, "CliError")) { - const data = input as ErrorLike & { exitCode?: number } - if (data.exitCode != null) process.exitCode = data.exitCode - return data.message ?? "" + if (typeof input.exitCode === "number") process.exitCode = input.exitCode + return stringField(input, "message") ?? "" } // MCPFailed: { name: string } if (NamedError.hasName(input, "MCPFailed")) { - return `MCP server "${(input as ErrorLike).data?.name}" failed. Note, opencode does not support MCP authentication yet.` + const data = isRecord(input) && isRecord(input.data) ? stringField(input.data, "name") : undefined + return `MCP server "${data}" failed. Note, opencode does not support MCP authentication yet.` } // AccountServiceError, AccountTransportError: TaggedErrorClass if (isTaggedError(input, "AccountServiceError") || isTaggedError(input, "AccountTransportError")) { - return (input as ErrorLike).message ?? "" + return stringField(input, "message") ?? "" } // ProviderModelNotFoundError: { providerID: string, modelID: string, suggestions?: string[] } @@ -64,7 +62,7 @@ export function FormatError(input: unknown) { ? providerModelNotFound.suggestions.filter((x) => typeof x === "string") : [] return [ - `Model not found: ${providerModelNotFound.providerID}/${providerModelNotFound.modelID}`, + `Model not found: ${stringField(providerModelNotFound, "providerID")}/${stringField(providerModelNotFound, "modelID")}`, ...(suggestions.length ? ["Did you mean: " + suggestions.join(", ")] : []), `Try: \`kilo models\` to list available models`, // kilocode_change `Or check your config (opencode.json) provider/model names`, @@ -112,6 +110,7 @@ export function FormatError(input: unknown) { if (isTaggedError(input, "UICancelledError") || NamedError.hasName(input, "UICancelledError")) { return "" } + return undefined } export function FormatUnknownError(input: unknown): string { diff --git a/packages/opencode/src/cli/upgrade.ts b/packages/opencode/src/cli/upgrade.ts index f177ce841a2..00ca70fb33f 100644 --- a/packages/opencode/src/cli/upgrade.ts +++ b/packages/opencode/src/cli/upgrade.ts @@ -1,9 +1,9 @@ -import { Bus } from "@/bus" import { Config } from "@/config/config" import { AppRuntime } from "@/effect/app-runtime" import { Flag } from "@opencode-ai/core/flag/flag" import { Installation } from "@/installation" import { InstallationVersion } from "@opencode-ai/core/installation/version" +import { GlobalBus } from "@/bus/global" export async function upgrade() { const config = await AppRuntime.runPromise(Config.Service.use((cfg) => cfg.getGlobal())) @@ -16,7 +16,13 @@ export async function upgrade() { if (!latest) return if (Flag.KILO_ALWAYS_NOTIFY_UPDATE) { - await Bus.publish(Installation.Event.UpdateAvailable, { version: latest }) + GlobalBus.emit("event", { + directory: "global", + payload: { + type: Installation.Event.UpdateAvailable.type, + properties: { version: latest }, + }, + }) return } @@ -25,11 +31,25 @@ export async function upgrade() { const kind = Installation.getReleaseType(InstallationVersion, latest) if (config.autoupdate === "notify" || kind !== "patch") { - await Bus.publish(Installation.Event.UpdateAvailable, { version: latest }) + GlobalBus.emit("event", { + directory: "global", + payload: { + type: Installation.Event.UpdateAvailable.type, + properties: { version: latest }, + }, + }) return } await Installation.upgrade(method, latest) - .then(() => Bus.publish(Installation.Event.Updated, { version: latest })) + .then(() => + GlobalBus.emit("event", { + directory: "global", + payload: { + type: Installation.Event.Updated.type, + properties: { version: latest }, + }, + }), + ) .catch(() => {}) } diff --git a/packages/opencode/src/command/index.ts b/packages/opencode/src/command/index.ts index 1c92d2aa20c..c52f79482d3 100644 --- a/packages/opencode/src/command/index.ts +++ b/packages/opencode/src/command/index.ts @@ -1,7 +1,7 @@ import { BusEvent } from "@/bus/bus-event" import { InstanceState } from "@/effect/instance-state" import { EffectBridge } from "@/effect/bridge" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" import { SessionID, MessageID } from "@/session/schema" import { Effect, Layer, Context, Schema } from "effect" import { Config } from "@/config/config" diff --git a/packages/opencode/src/config/agent.ts b/packages/opencode/src/config/agent.ts index 2ff636a1663..7191e89038a 100644 --- a/packages/opencode/src/config/agent.ts +++ b/packages/opencode/src/config/agent.ts @@ -1,11 +1,9 @@ export * as ConfigAgent from "./agent" import path from "path" // kilocode_change -import { Exit, Schema, SchemaGetter } from "effect" -import { Bus } from "@/bus" +import { Schema, SchemaGetter } from "effect" import { PositiveInt } from "@opencode-ai/core/schema" import * as Log from "@opencode-ai/core/util/log" -import { NamedError } from "@opencode-ai/core/util/error" import { Glob } from "@opencode-ai/core/util/glob" import { configEntryNameFromPath } from "./entry-name" import { ConfigError } from "./error" @@ -15,6 +13,8 @@ import { ConfigParse } from "./parse" import { ConfigPermission } from "./permission" import { ConfigVariable } from "./variable" // kilocode_change // kilocode_change start +import { Bus } from "@/bus" +import { NamedError } from "@opencode-ai/core/util/error" import { KilocodeConfig } from "@/kilocode/config/config" import type { Warning } from "./config" // kilocode_change end @@ -138,14 +138,18 @@ export async function load(dir: string, warnings?: Warning[]) { // kilocode_change start if (warnings) warnings.push({ path: item, message }) try { - const { Session } = await import("@/session/session") - Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) - } catch (e) { - log.warn("could not publish session error", { message, err: e }) + const { capture } = await import("@/kilocode/instance") + const ctx = capture() + if (ctx) { + const { Session } = await import("@/session/session") + await Bus.publish(ctx, Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) + } + } catch (error) { + log.warn("could not publish session error", { message, err: error }) } + // kilocode_change end log.error("failed to load agent", { agent: item, err }) return undefined - // kilocode_change end }) if (!md) continue @@ -210,14 +214,18 @@ export async function loadMode(dir: string, warnings?: Warning[]) { // kilocode_change start if (warnings) warnings.push({ path: item, message }) try { - const { Session } = await import("@/session/session") - Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) - } catch (e) { - log.warn("could not publish session error", { message, err: e }) + const { capture } = await import("@/kilocode/instance") + const ctx = capture() + if (ctx) { + const { Session } = await import("@/session/session") + await Bus.publish(ctx, Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) + } + } catch (error) { + log.warn("could not publish session error", { message, err: error }) } + // kilocode_change end log.error("failed to load mode", { mode: item, err }) return undefined - // kilocode_change end }) if (!md) continue diff --git a/packages/opencode/src/config/command.ts b/packages/opencode/src/config/command.ts index 92a044813e3..d83aaac4076 100644 --- a/packages/opencode/src/config/command.ts +++ b/packages/opencode/src/config/command.ts @@ -2,13 +2,13 @@ export * as ConfigCommand from "./command" import * as Log from "@opencode-ai/core/util/log" import { Cause, Exit, Schema, SchemaIssue } from "effect" -import { NamedError } from "@opencode-ai/core/util/error" import { Glob } from "@opencode-ai/core/util/glob" -import { Bus } from "@/bus" import { configEntryNameFromPath } from "./entry-name" import * as ConfigMarkdown from "./markdown" import { ConfigModelID } from "./model-id" // kilocode_change start +import { Bus } from "@/bus" +import { NamedError } from "@opencode-ai/core/util/error" import { KilocodeConfig } from "@/kilocode/config/config" import type { Warning } from "./config" // kilocode_change end @@ -44,14 +44,18 @@ export async function load(dir: string, warnings?: Warning[]) { // kilocode_change start if (warnings) warnings.push({ path: item, message }) try { - const { Session } = await import("@/session/session") - Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) - } catch (e) { - log.warn("could not publish session error", { message, err: e }) + const { capture } = await import("@/kilocode/instance") + const ctx = capture() + if (ctx) { + const { Session } = await import("@/session/session") + await Bus.publish(ctx, Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) + } + } catch (error) { + log.warn("could not publish session error", { message, err: error }) } + // kilocode_change end log.error("failed to load command", { command: item, err }) return undefined - // kilocode_change end }) if (!md) continue diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index cc3c38a99f7..4fdbf52025d 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -10,7 +10,6 @@ import { Flag } from "@opencode-ai/core/flag/flag" import { Auth } from "../auth" import { Env } from "../env" import { applyEdits, findNodeAtLocation, modify, parseTree } from "jsonc-parser" // kilocode_change - parseTree/findNodeAtLocation used in patchJsonc -import { type InstanceContext } from "../project/instance" import { InstallationLocal, InstallationVersion } from "@opencode-ai/core/installation/version" import { existsSync } from "fs" // kilocode_change start @@ -24,7 +23,7 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { InstanceState } from "@/effect/instance-state" import { Context, Duration, Effect, Exit, Fiber, Layer, Option, Schema } from "effect" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" -import { containsPath } from "../project/instance-context" +import { containsPath, type InstanceContext } from "../project/instance-context" import { NonNegativeInt, PositiveInt, type DeepMutable } from "@opencode-ai/core/schema" import { ConfigAgent } from "./agent" import { ConfigAttachment } from "./attachment" diff --git a/packages/opencode/src/control-plane/adapters/worktree.ts b/packages/opencode/src/control-plane/adapters/worktree.ts index 1c85d125a2d..87e30e1139b 100644 --- a/packages/opencode/src/control-plane/adapters/worktree.ts +++ b/packages/opencode/src/control-plane/adapters/worktree.ts @@ -1,5 +1,6 @@ -import { Schema } from "effect" -import { type WorkspaceAdapter, WorkspaceInfo } from "../types" +import { Effect, Schema } from "effect" +import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" +import { type WorkspaceAdapter, type WorkspaceAdapterContext, WorkspaceInfo } from "../types" const WorktreeConfig = Schema.Struct({ name: WorkspaceInfo.fields.name, @@ -9,53 +10,81 @@ const WorktreeConfig = Schema.Struct({ const decodeWorktreeConfig = Schema.decodeUnknownSync(WorktreeConfig) async function loadWorktree() { - const [{ AppRuntime }, { Instance }, { Worktree }] = await Promise.all([ - import("@/effect/app-runtime"), - import("@/project/instance"), - import("@/worktree"), - ]) - return { AppRuntime, Instance, Worktree } + const [{ AppRuntime }, { Worktree }] = await Promise.all([import("@/effect/app-runtime"), import("@/worktree")]) + return { AppRuntime, Worktree } } +function requireInstance(context: WorkspaceAdapterContext | undefined) { + if (!context?.instance) throw new Error("Worktree adapter requires an instance context") + return context.instance +} + +const provideContext = (effect: Effect.Effect, context: WorkspaceAdapterContext | undefined) => + effect.pipe( + Effect.provideService(InstanceRef, requireInstance(context)), + Effect.provideService(WorkspaceRef, context?.workspaceID), + ) + export const WorktreeAdapter: WorkspaceAdapter = { name: "Worktree", description: "Create a git worktree", - async configure(info) { + async configure(info, context) { const { AppRuntime, Worktree } = await loadWorktree() - const next = await AppRuntime.runPromise(Worktree.Service.use((svc) => svc.makeWorktreeInfo({ detached: true }))) + const next = await AppRuntime.runPromise( + provideContext( + Worktree.Service.use((svc) => svc.makeWorktreeInfo({ detached: true })), + context, + ), + ) return { ...info, name: next.name, directory: next.directory, } }, - async create(info) { + async create(info, _env, _from, context) { const { AppRuntime, Worktree } = await loadWorktree() const config = decodeWorktreeConfig(info) await AppRuntime.runPromise( - Worktree.Service.use((svc) => - svc.createFromInfo({ - name: config.name, - directory: config.directory, - ...(config.branch ? { branch: config.branch } : {}), - }), + provideContext( + Worktree.Service.use((svc) => + svc.createFromInfo({ + name: config.name, + directory: config.directory, + ...(config.branch ? { branch: config.branch } : {}), + }), + ), + context, ), ) }, - async list() { - const { AppRuntime, Instance, Worktree } = await loadWorktree() - return (await AppRuntime.runPromise(Worktree.Service.use((svc) => svc.list()))).map((info) => ({ + async list(context) { + const { AppRuntime, Worktree } = await loadWorktree() + const ctx = requireInstance(context) + return ( + await AppRuntime.runPromise( + provideContext( + Worktree.Service.use((svc) => svc.list()), + context, + ), + ) + ).map((info) => ({ type: "worktree", name: info.name, branch: info.branch, directory: info.directory, - projectID: Instance.project.id, + projectID: ctx.project.id, })) }, - async remove(info) { + async remove(info, context) { const { AppRuntime, Worktree } = await loadWorktree() const config = decodeWorktreeConfig(info) - await AppRuntime.runPromise(Worktree.Service.use((svc) => svc.remove({ directory: config.directory }))) + await AppRuntime.runPromise( + provideContext( + Worktree.Service.use((svc) => svc.remove({ directory: config.directory })), + context, + ), + ) }, target(info) { const config = decodeWorktreeConfig(info) diff --git a/packages/opencode/src/control-plane/types.ts b/packages/opencode/src/control-plane/types.ts index e55ae2194e4..daa83745302 100644 --- a/packages/opencode/src/control-plane/types.ts +++ b/packages/opencode/src/control-plane/types.ts @@ -1,5 +1,6 @@ import { Schema, Struct } from "effect" import { ProjectID } from "@/project/schema" +import type { InstanceContext } from "@/project/instance-context" import { WorkspaceID } from "./schema" import type { DeepMutable } from "@opencode-ai/core/schema" @@ -37,12 +38,22 @@ export type Target = headers?: HeadersInit } +export type WorkspaceAdapterContext = { + readonly instance?: InstanceContext + readonly workspaceID?: WorkspaceID +} + export type WorkspaceAdapter = { name: string description: string - configure(info: WorkspaceInfo): WorkspaceInfo | Promise - create(info: WorkspaceInfo, env: Record, from?: WorkspaceInfo): Promise - list?(): WorkspaceListedInfo[] | Promise - remove(info: WorkspaceInfo): Promise - target(info: WorkspaceInfo): Target | Promise + configure(info: WorkspaceInfo, context?: WorkspaceAdapterContext): WorkspaceInfo | Promise + create( + info: WorkspaceInfo, + env: Record, + from?: WorkspaceInfo, + context?: WorkspaceAdapterContext, + ): Promise + list?(context?: WorkspaceAdapterContext): WorkspaceListedInfo[] | Promise + remove(info: WorkspaceInfo, context?: WorkspaceAdapterContext): Promise + target(info: WorkspaceInfo, context?: WorkspaceAdapterContext): Target | Promise } diff --git a/packages/opencode/src/control-plane/workspace-adapter-runtime.ts b/packages/opencode/src/control-plane/workspace-adapter-runtime.ts new file mode 100644 index 00000000000..235edc9d22b --- /dev/null +++ b/packages/opencode/src/control-plane/workspace-adapter-runtime.ts @@ -0,0 +1,51 @@ +import { Effect } from "effect" +import { EffectBridge } from "@/effect/bridge" +import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" +import { getAdapter } from "./adapters" +import type { WorkspaceAdapter, WorkspaceInfo } from "./types" + +const context = Effect.gen(function* () { + return { + instance: yield* InstanceRef, + workspaceID: yield* WorkspaceRef, + } +}) + +export const target = (info: WorkspaceInfo) => + Effect.gen(function* () { + const adapter = getAdapter(info.projectID, info.type) + const ctx = yield* context + return yield* EffectBridge.fromPromise(() => adapter.target(info, ctx)) + }) + +export const configure = (adapter: WorkspaceAdapter, info: WorkspaceInfo) => + Effect.gen(function* () { + const ctx = yield* context + return yield* EffectBridge.fromPromise(() => adapter.configure(info, ctx)) + }) + +export const create = ( + adapter: WorkspaceAdapter, + info: WorkspaceInfo, + env: Record, + from?: WorkspaceInfo, +) => + Effect.gen(function* () { + const ctx = yield* context + return yield* EffectBridge.fromPromise(() => adapter.create(info, env, from, ctx)) + }) + +export const list = (adapter: WorkspaceAdapter) => + Effect.gen(function* () { + const ctx = yield* context + return yield* EffectBridge.fromPromise(() => Promise.resolve(adapter.list?.(ctx) ?? [])) + }) + +export const remove = (info: WorkspaceInfo) => + Effect.gen(function* () { + const adapter = getAdapter(info.projectID, info.type) + const ctx = yield* context + return yield* EffectBridge.fromPromise(() => adapter.remove(info, ctx)) + }) + +export * as WorkspaceAdapterRuntime from "./workspace-adapter-runtime" diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 3b3775a3007..09d7a51e7c8 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -26,11 +26,11 @@ import { SessionID } from "@/session/schema" import { NotFoundError } from "@/storage/storage" import { errorData } from "@/util/error" import { waitEvent } from "./util" -import { WorkspaceContext } from "./workspace-context" -import { EffectBridge } from "@/effect/bridge" +import { WorkspaceRef } from "@/effect/instance-ref" import { Vcs } from "@/project/vcs" import { InstanceStore } from "@/project/instance-store" import { InstanceBootstrap } from "@/project/bootstrap" +import { WorkspaceAdapterRuntime } from "./workspace-adapter-runtime" export const Info = Schema.Struct({ ...WorkspaceInfoSchema.fields, @@ -281,8 +281,7 @@ export const layer = Layer.effect( const workspace = yield* get(input.workspaceID) if (!workspace) return input.fallback - const adapter = getAdapter(workspace.projectID, workspace.type) - const target = yield* EffectBridge.fromPromise(() => adapter.target(workspace)) + const target = yield* WorkspaceAdapterRuntime.target(workspace) if (target.type === "local") { const store = yield* InstanceStore.Service @@ -375,35 +374,27 @@ export const layer = Layer.effect( events: events.length, }) - yield* Effect.promise(async () => { - await WorkspaceContext.provide({ - workspaceID: space.id, - async fn() { - await Effect.runPromise( - Effect.forEach( - events, - (event) => - sync.replay( - { - id: event.id, - aggregateID: event.aggregate_id, - seq: event.seq, - type: event.type, - data: event.data, - }, - { publish: true }, - ), - { discard: true }, - ), + yield* Effect.forEach( + events, + (event) => + sync + .replay( + { + id: event.id, + aggregateID: event.aggregate_id, + seq: event.seq, + type: event.type, + data: event.data, + }, + { publish: true }, ) - }, - }) - }) + .pipe(Effect.provideService(WorkspaceRef, space.id)), + { discard: true }, + ) }) const syncWorkspaceLoop = Effect.fn("Workspace.syncWorkspaceLoop")(function* (space: Info) { - const adapter = getAdapter(space.projectID, space.type) - const target = yield* EffectBridge.fromPromise(() => adapter.target(space)) + const target = yield* WorkspaceAdapterRuntime.target(space) if (target.type === "local") return @@ -486,8 +477,7 @@ export const layer = Layer.effect( const startSync = Effect.fn("Workspace.startSync")(function* (space: Info) { if (!flags.experimentalWorkspaces) return - const adapter = getAdapter(space.projectID, space.type) - const target = yield* EffectBridge.fromPromise(() => adapter.target(space)).pipe( + const target = yield* WorkspaceAdapterRuntime.target(space).pipe( Effect.catch((error) => Effect.sync(() => { setStatus(space.id, "error") @@ -538,15 +528,13 @@ export const layer = Layer.effect( const create = Effect.fn("Workspace.create")(function* (input: CreateInput) { const id = WorkspaceID.ascending(input.id) const adapter = getAdapter(input.projectID, input.type) - const config = yield* EffectBridge.fromPromise(() => - adapter.configure({ - ...input, - id, - name: Slug.create(), - directory: null, - extra: input.extra ?? null, - }), - ) + const config = yield* WorkspaceAdapterRuntime.configure(adapter, { + ...input, + id, + name: Slug.create(), + directory: null, + extra: input.extra ?? null, + }) const info: Info = { id, @@ -583,7 +571,7 @@ export const layer = Layer.effect( OTEL_RESOURCE_ATTRIBUTES: process.env.OTEL_RESOURCE_ATTRIBUTES, } - yield* EffectBridge.fromPromise(() => adapter.create(config, env)) + yield* WorkspaceAdapterRuntime.create(adapter, config, env) yield* Effect.all( [ waitEvent({ @@ -622,8 +610,7 @@ export const layer = Layer.effect( if (current?.workspaceID) { const previous = yield* get(current.workspaceID) if (previous) { - const adapter = getAdapter(previous.projectID, previous.type) - const target = yield* EffectBridge.fromPromise(() => adapter.target(previous)) + const target = yield* WorkspaceAdapterRuntime.target(previous) if (target.type === "remote") { yield* syncHistory(previous, target.url, target.headers).pipe( @@ -701,8 +688,7 @@ export const layer = Layer.effect( workspaceID, }) - const adapter = getAdapter(space.projectID, space.type) - const target = yield* EffectBridge.fromPromise(() => adapter.target(space)) + const target = yield* WorkspaceAdapterRuntime.target(space) if (target.type === "local") { yield* sync.run(Session.Event.Updated, { @@ -855,16 +841,14 @@ export const layer = Layer.effect( const discovered = yield* Effect.forEach( registeredAdapters(project.id), ([type, adapter]) => - adapter.list - ? EffectBridge.fromPromise(() => Promise.resolve(adapter.list?.() ?? [])).pipe( - Effect.catchCause((error) => - Effect.sync(() => { - log.warn("workspace adapter list failed", { type, error }) - return [] - }), - ), - ) - : Effect.succeed([]), + WorkspaceAdapterRuntime.list(adapter).pipe( + Effect.catchCause((error) => + Effect.sync(() => { + log.warn("workspace adapter list failed", { type, error }) + return [] + }), + ), + ), { concurrency: "unbounded" }, ).pipe(Effect.map((items) => items.flat())) @@ -937,8 +921,7 @@ export const layer = Layer.effect( const info = fromRow(row) yield* Effect.catchCause( Effect.gen(function* () { - const adapter = getAdapter(info.projectID, row.type) - yield* EffectBridge.fromPromise(() => adapter.remove(info)) + yield* WorkspaceAdapterRuntime.remove(info) }), () => Effect.sync(() => { diff --git a/packages/opencode/src/effect/app-runtime.ts b/packages/opencode/src/effect/app-runtime.ts index ee5bb53873d..3a2a08c3bc2 100644 --- a/packages/opencode/src/effect/app-runtime.ts +++ b/packages/opencode/src/effect/app-runtime.ts @@ -57,9 +57,10 @@ import { Npm } from "@opencode-ai/core/npm" import { memoMap } from "@opencode-ai/core/effect/memo-map" import { DataMigration } from "@/data-migration" import { BackgroundJob } from "@/background/job" +import { EventV2Bridge } from "@/event-v2-bridge" import { RuntimeFlags } from "@/effect/runtime-flags" -export const AppLayer = Layer.mergeAll( +const CoreLayer = Layer.mergeAll( Npm.defaultLayer, AppFileSystem.defaultLayer, Bus.defaultLayer, @@ -80,6 +81,9 @@ export const AppLayer = Layer.mergeAll( Agent.defaultLayer, Skill.defaultLayer, Discovery.defaultLayer, +) + +const SessionLayer = Layer.mergeAll( Question.defaultLayer, Permission.defaultLayer, Todo.defaultLayer, @@ -100,6 +104,9 @@ export const AppLayer = Layer.mergeAll( McpAuth.defaultLayer, Command.defaultLayer, Truncate.defaultLayer, +) + +const FeatureLayer = Layer.mergeAll( ToolRegistry.defaultLayer, Format.defaultLayer, Project.defaultLayer, @@ -113,8 +120,14 @@ export const AppLayer = Layer.mergeAll( ShareNext.defaultLayer, SessionShare.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, DataMigration.defaultLayer, -).pipe(Layer.provideMerge(InstanceLayer.layer), Layer.provideMerge(Observability.layer)) +) + +export const AppLayer = Layer.mergeAll(CoreLayer, SessionLayer, FeatureLayer).pipe( + Layer.provideMerge(InstanceLayer.layer), + Layer.provideMerge(Observability.layer), +) const rt = ManagedRuntime.make(AppLayer, { memoMap }) type Runtime = Pick diff --git a/packages/opencode/src/effect/bridge.ts b/packages/opencode/src/effect/bridge.ts index 16d8f93669c..99f16f43712 100644 --- a/packages/opencode/src/effect/bridge.ts +++ b/packages/opencode/src/effect/bridge.ts @@ -1,8 +1,6 @@ -import { Effect, Exit, Fiber } from "effect" +import { Context, Effect, Exit, Fiber } from "effect" import { WorkspaceContext } from "@/control-plane/workspace-context" -import { Instance, type InstanceContext } from "@/project/instance" import type { WorkspaceID } from "@/control-plane/schema" -import { LocalContext } from "@/util/local-context" import { InstanceRef, WorkspaceRef } from "./instance-ref" import { attachWith } from "./run-service" @@ -10,67 +8,75 @@ export interface Shape { readonly promise: (effect: Effect.Effect) => Promise readonly fork: (effect: Effect.Effect) => Fiber.Fiber readonly run: (effect: Effect.Effect) => Effect.Effect + readonly bind: (fn: (...args: Args) => Result) => (...args: Args) => Result } -function restore(instance: InstanceContext | undefined, workspace: WorkspaceID | undefined, fn: () => R): R { - if (instance && workspace !== undefined) { - return WorkspaceContext.restore(workspace, () => Instance.restore(instance, fn)) - } - if (instance) return Instance.restore(instance, fn) +function restoreWorkspace(workspace: WorkspaceID | undefined, fn: () => R): R { if (workspace !== undefined) return WorkspaceContext.restore(workspace, fn) return fn() } +function captureSync() { + const fiber = Fiber.getCurrent() + const instance = fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined + const workspace = + (fiber ? Context.getReferenceUnsafe(fiber.context, WorkspaceRef) : undefined) ?? WorkspaceContext.workspaceID + return { instance, workspace } +} + +export const bind = (fn: (...args: Args) => Result) => { + const captured = captureSync() + return (...args: Args) => + restoreWorkspace(captured.workspace, () => + Effect.runSync( + attachWith( + Effect.sync(() => fn(...args)), + captured, + ), + ), + ) +} + /** - * Bridge from Effect into a Promise-returning JS callback while installing - * legacy `Instance.context` and `WorkspaceContext` AsyncLocalStorage for - * the duration of the callback. Effect's `InstanceRef`/`WorkspaceRef` do - * not propagate across async/await boundaries inside `Effect.promise(() => - * async fn)` callbacks that re-enter Effect via `AppRuntime.runPromise`, - * but Node's AsyncLocalStorage does. Use this whenever an Effect crosses - * into JS that may itself spawn new Effect runtimes (workspace adapters, - * legacy plugins, etc.). + * Bridge from Effect into a Promise-returning JS callback while preserving + * `WorkspaceContext` AsyncLocalStorage for callback code that still reads it. + * `InstanceRef` is captured for effects run through the returned bridge APIs; + * plain JS callbacks that need it should receive the ref explicitly. * - * Mirrors `Effect.promise` but restores legacy ALS first. + * Mirrors `Effect.promise` but restores workspace ALS first. */ export const fromPromise = (fn: () => Promise | T): Effect.Effect => Effect.gen(function* () { - const instance = yield* InstanceRef const workspace = yield* WorkspaceRef - return yield* Effect.promise(() => Promise.resolve(restore(instance, workspace, () => fn()))) + return yield* Effect.promise(() => Promise.resolve(restoreWorkspace(workspace, () => fn()))) }) export function make(): Effect.Effect { return Effect.gen(function* () { const ctx = yield* Effect.context() - const value = yield* InstanceRef - const instance = - value ?? - (() => { - try { - return Instance.current - } catch (err) { - if (!(err instanceof LocalContext.NotFound)) throw err - } - })() - const workspace = (yield* WorkspaceRef) ?? WorkspaceContext.workspaceID - const attach = (effect: Effect.Effect) => attachWith(effect, { instance, workspace }) + const captured = captureSync() + const instance = (yield* InstanceRef) ?? captured.instance + const workspace = (yield* WorkspaceRef) ?? captured.workspace const wrap = (effect: Effect.Effect) => - attach(effect).pipe(Effect.provide(ctx)) as Effect.Effect + attachWith(effect.pipe(Effect.provide(ctx)) as Effect.Effect, { instance, workspace }) return { promise: (effect: Effect.Effect) => - restore(instance, workspace, () => Effect.runPromise(wrap(effect))), + restoreWorkspace(workspace, () => Effect.runPromise(wrap(effect))), fork: (effect: Effect.Effect) => - restore(instance, workspace, () => Effect.runFork(wrap(effect))), + restoreWorkspace(workspace, () => Effect.runFork(wrap(effect))), run: (effect: Effect.Effect) => Effect.callback((resume) => { - restore(instance, workspace, () => + restoreWorkspace(workspace, () => Effect.runPromiseExit(wrap(effect)).then((exit) => resume(Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause)), ), ) }), + bind: + (fn: (...args: Args) => Result) => + (...args: Args) => + restoreWorkspace(workspace, () => Effect.runSync(wrap(Effect.sync(() => fn(...args))))), } satisfies Shape }) } diff --git a/packages/opencode/src/effect/instance-ref.ts b/packages/opencode/src/effect/instance-ref.ts index effc560c580..d95932c2de6 100644 --- a/packages/opencode/src/effect/instance-ref.ts +++ b/packages/opencode/src/effect/instance-ref.ts @@ -1,5 +1,5 @@ import { Context } from "effect" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" import type { WorkspaceID } from "@/control-plane/schema" export const InstanceRef = Context.Reference("~opencode/InstanceRef", { diff --git a/packages/opencode/src/effect/instance-state.ts b/packages/opencode/src/effect/instance-state.ts index e467b6ef28b..75916f07def 100644 --- a/packages/opencode/src/effect/instance-state.ts +++ b/packages/opencode/src/effect/instance-state.ts @@ -1,7 +1,6 @@ -import { Effect, Fiber, ScopedCache, Scope, Context } from "effect" +import { Effect, ScopedCache, Scope } from "effect" import * as EffectLogger from "@opencode-ai/core/effect/logger" -import { Instance, type InstanceContext } from "@/project/instance" -import { LocalContext } from "@/util/local-context" +import { capture, type InstanceContext } from "@/kilocode/instance" // kilocode_change import { InstanceRef, WorkspaceRef } from "./instance-ref" import { registerDisposer } from "./instance-registry" import { WorkspaceContext } from "@/control-plane/workspace-context" @@ -13,20 +12,10 @@ export interface InstanceState { readonly cache: ScopedCache.ScopedCache } -export const bind = any>(fn: F): F => { - try { - return Instance.bind(fn) - } catch (err) { - if (!(err instanceof LocalContext.NotFound)) throw err - } - const fiber = Fiber.getCurrent() - const ctx = fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined - if (!ctx) return fn - return ((...args: any[]) => Instance.restore(ctx, () => fn(...args))) as F -} - export const context = Effect.gen(function* () { - return (yield* InstanceRef) ?? Instance.current + const ctx = (yield* InstanceRef) ?? capture() // kilocode_change + if (!ctx) return yield* Effect.die(new Error("InstanceRef not provided")) + return ctx }) export const workspaceID = Effect.gen(function* () { diff --git a/packages/opencode/src/effect/run-service.ts b/packages/opencode/src/effect/run-service.ts index 1f3802e80c4..8f719ae43b9 100644 --- a/packages/opencode/src/effect/run-service.ts +++ b/packages/opencode/src/effect/run-service.ts @@ -1,11 +1,11 @@ import { Effect, Fiber, Layer, ManagedRuntime } from "effect" import * as Context from "effect/Context" -import { Instance } from "@/project/instance" -import { LocalContext } from "@/util/local-context" import { InstanceRef, WorkspaceRef } from "./instance-ref" import * as Observability from "@opencode-ai/core/effect/observability" import { WorkspaceContext } from "@/control-plane/workspace-context" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" +import { context as instanceContext } from "@/project/instance-context" // kilocode_change +import { LocalContext } from "@/util/local-context" // kilocode_change import { memoMap } from "@opencode-ai/core/effect/memo-map" type Refs = { @@ -25,17 +25,20 @@ export function attachWith(effect: Effect.Effect, refs: Refs): export function attach(effect: Effect.Effect): Effect.Effect { const workspace = WorkspaceContext.workspaceID + const fiber = Fiber.getCurrent() + const current = fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined + // kilocode_change start - bridge legacy AsyncLocalStorage instance context into Effect runtimes const instance = (() => { + if (current) return current try { - return Instance.current + return instanceContext.use() } catch (err) { if (!(err instanceof LocalContext.NotFound)) throw err } })() - if (instance && workspace !== undefined) return attachWith(effect, { instance, workspace }) - const fiber = Fiber.getCurrent() + // kilocode_change end return attachWith(effect, { - instance: instance ?? (fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined), + instance, workspace: workspace ?? (fiber ? Context.getReferenceUnsafe(fiber.context, WorkspaceRef) : undefined), }) } diff --git a/packages/opencode/src/effect/runtime-flags.ts b/packages/opencode/src/effect/runtime-flags.ts index be3e198f9f1..84c8327d9a4 100644 --- a/packages/opencode/src/effect/runtime-flags.ts +++ b/packages/opencode/src/effect/runtime-flags.ts @@ -17,6 +17,13 @@ export class Service extends ConfigService.Service()("@opencode/Runtime disableDefaultPlugins: bool("KILO_DISABLE_DEFAULT_PLUGINS"), disableChannelDb: bool("KILO_DISABLE_CHANNEL_DB"), disableEmbeddedWebUi: bool("KILO_DISABLE_EMBEDDED_WEB_UI"), + disableExternalSkills: bool("KILO_DISABLE_EXTERNAL_SKILLS"), + disableLspDownload: bool("KILO_DISABLE_LSP_DOWNLOAD"), + skipMigrations: bool("KILO_SKIP_MIGRATIONS"), + disableClaudeCodePrompt: Config.all({ + broad: bool("KILO_DISABLE_CLAUDE_CODE"), + direct: bool("KILO_DISABLE_CLAUDE_CODE_PROMPT"), + }).pipe(Config.map((flags) => flags.broad || flags.direct)), disableClaudeCodeSkills: Config.all({ broad: bool("KILO_DISABLE_CLAUDE_CODE"), direct: bool("KILO_DISABLE_CLAUDE_CODE_SKILLS"), @@ -41,6 +48,7 @@ export class Service extends ConfigService.Service()("@opencode/Runtime experimentalEventSystem: enabledByExperimental("KILO_EXPERIMENTAL_EVENT_SYSTEM"), experimentalWorkspaces: enabledByExperimental("KILO_EXPERIMENTAL_WORKSPACES"), experimentalIconDiscovery: enabledByExperimental("KILO_EXPERIMENTAL_ICON_DISCOVERY"), + outputTokenMax: positiveInteger("KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX"), bashDefaultTimeoutMs: positiveInteger("KILO_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"), client: Config.string("KILO_CLIENT").pipe(Config.withDefault("cli")), }) {} diff --git a/packages/opencode/src/event-v2-bridge.ts b/packages/opencode/src/event-v2-bridge.ts new file mode 100644 index 00000000000..c8213254a5e --- /dev/null +++ b/packages/opencode/src/event-v2-bridge.ts @@ -0,0 +1,89 @@ +// Temporary V2 bridge: core events are the publish path, but the rest of +// opencode and the HTTP event stream still expect legacy bus/sync payloads. +// This layer goes away once consumers subscribe to core EventV2 directly. +import { Bus as ProjectBus } from "@/bus" +import { GlobalBus } from "@/bus/global" +import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" +import { InstanceStore } from "@/project/instance-store" +import { SyncEvent } from "@/sync" +import { EventV2 } from "@opencode-ai/core/event" +import "@opencode-ai/core/catalog" +import "@opencode-ai/core/session-event" +import { Context, Effect, Layer, Option } from "effect" + +export function toSyncDefinition(definition: D) { + const result = { + type: definition.type, + version: definition.version, + aggregate: definition.aggregate, + schema: definition.data, + properties: definition.data, + } + return result as SyncEvent.Definition +} + +export class Service extends Context.Service()("@opencode/EventV2Bridge") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const events = yield* EventV2.Service + const bus = yield* ProjectBus.Service + const sync = yield* SyncEvent.Service + + const publishGlobal = (event: EventV2.Payload) => + Effect.sync(() => { + GlobalBus.emit("event", { + workspace: event.location?.workspaceID, + payload: { + id: event.id, + type: event.type, + properties: event.data, + }, + }) + }) + + const provideEventLocation = (event: EventV2.Payload, effect: Effect.Effect) => { + return Effect.gen(function* () { + const ctx = yield* InstanceRef + if (ctx) return yield* effect + const store = Option.getOrUndefined(yield* Effect.serviceOption(InstanceStore.Service)) + if (!event.location?.directory || !store) return yield* publishGlobal(event) + return yield* store.load({ directory: event.location.directory }).pipe( + Effect.flatMap((ctx) => { + const withInstance = effect.pipe(Effect.provideService(InstanceRef, ctx)) + if (!event.location?.workspaceID) return withInstance + return withInstance.pipe(Effect.provideService(WorkspaceRef, event.location.workspaceID)) + }), + ) + }) + } + + const unsubscribe = yield* events.sync((event) => { + const definition = EventV2.registry.get(event.type) + if (!definition) return Effect.void + const aggregateID = definition.aggregate + ? (event.data as Record)[definition.aggregate] + : undefined + + if (definition.version !== undefined && typeof aggregateID === "string") { + return provideEventLocation(event, sync.run(toSyncDefinition(definition), event.data)) + } + + return provideEventLocation( + event, + bus.publish({ type: definition.type, properties: definition.data }, event.data, { id: event.id }), + ) + }) + yield* Effect.addFinalizer(() => unsubscribe) + return Service.of(events) + }), +) + +export const defaultLayer = layer.pipe( + Layer.provideMerge(EventV2.defaultLayer), + Layer.provide(SyncEvent.defaultLayer), + Layer.provide(ProjectBus.defaultLayer), +) + +export * as EventV2Bridge from "./event-v2-bridge" diff --git a/packages/opencode/src/file/watcher.ts b/packages/opencode/src/file/watcher.ts index 657a3dcff03..971b5141076 100644 --- a/packages/opencode/src/file/watcher.ts +++ b/packages/opencode/src/file/watcher.ts @@ -2,10 +2,11 @@ import { Cause, Effect, Layer, Context, Schema } from "effect" // @ts-ignore import { createWrapper } from "@parcel/watcher/wrapper" import type ParcelWatcher from "@parcel/watcher" -import { readdir } from "fs/promises" +import { readdir, realpath } from "fs/promises" import path from "path" import { Bus } from "@/bus" import { BusEvent } from "@/bus/bus-event" +import { EffectBridge } from "@/effect/bridge" import { InstanceState } from "@/effect/instance-state" import { Flag } from "@opencode-ai/core/flag/flag" import { Git } from "@/git" @@ -88,18 +89,18 @@ export const layer = Layer.effect( if (!w) return log.info("watcher backend", { directory: ctx.directory, platform: process.platform, backend }) - + const bridge = yield* EffectBridge.make() const subs: ParcelWatcher.AsyncSubscription[] = [] yield* Effect.addFinalizer(() => Effect.promise(() => Promise.allSettled(subs.map((sub) => sub.unsubscribe()))), ) - const cb: ParcelWatcher.SubscribeCallback = InstanceState.bind((err, evts) => { - if (err) return + const cb: ParcelWatcher.SubscribeCallback = bridge.bind((err, evts) => { + // if (err) return for (const evt of evts) { - if (evt.type === "create") void Bus.publish(Event.Updated, { file: evt.path, event: "add" }) - if (evt.type === "update") void Bus.publish(Event.Updated, { file: evt.path, event: "change" }) - if (evt.type === "delete") void Bus.publish(Event.Updated, { file: evt.path, event: "unlink" }) + if (evt.type === "create") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "add" }) + if (evt.type === "update") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "change" }) + if (evt.type === "delete") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "unlink" }) } }) @@ -131,8 +132,14 @@ export const layer = Layer.effect( const result = yield* git.run(["rev-parse", "--git-dir"], { cwd: ctx.worktree, }) - const vcsDir = result.exitCode === 0 ? path.resolve(ctx.worktree, result.text().trim()) : undefined - if (vcsDir && !cfgIgnores.includes(".git") && !cfgIgnores.includes(vcsDir)) { + const resolved = result.exitCode === 0 ? path.resolve(ctx.worktree, result.text().trim()) : undefined + const vcsDir = resolved ? yield* Effect.promise(() => realpath(resolved).catch(() => resolved)) : undefined + if ( + vcsDir && + !cfgIgnores.includes(".git") && + !cfgIgnores.includes(vcsDir) && + (!resolved || !cfgIgnores.includes(resolved)) + ) { const ignore = (yield* Effect.promise(() => readdir(vcsDir).catch(() => []))).filter( (entry) => entry !== "HEAD", ) diff --git a/packages/opencode/src/format/formatter.ts b/packages/opencode/src/format/formatter.ts index 4c559631f29..27b28c37bcf 100644 --- a/packages/opencode/src/format/formatter.ts +++ b/packages/opencode/src/format/formatter.ts @@ -1,5 +1,5 @@ import { Npm } from "@opencode-ai/core/npm" -import type { InstanceContext } from "../project/instance" +import type { InstanceContext } from "../project/instance-context" import { Filesystem } from "@/util/filesystem" import { Process } from "@/util/process" import { which } from "../util/which" diff --git a/packages/opencode/src/kilo-sessions/kilo-sessions.ts b/packages/opencode/src/kilo-sessions/kilo-sessions.ts index 2f562e6f97b..e40e29355ea 100644 --- a/packages/opencode/src/kilo-sessions/kilo-sessions.ts +++ b/packages/opencode/src/kilo-sessions/kilo-sessions.ts @@ -20,7 +20,7 @@ import { KILO_API_BASE } from "@kilocode/kilo-gateway" import { Config } from "@/config/config" import { EffectBridge } from "@/effect/bridge" import { InstanceState } from "@/effect/instance-state" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { Vcs } from "@/project/vcs" import simpleGit from "simple-git" import { RemoteWS } from "@/kilo-sessions/remote-ws" @@ -34,8 +34,8 @@ import { Snapshot } from "@/snapshot" import { cumulativeSessionDiff } from "@/kilocode/session-portability/cumulative-diff" async function provide(input: { directory: string; fn: () => R }): Promise { - const { WithInstance } = await import("@/project/with-instance") - return WithInstance.provide(input) + const { provide } = await import("@/kilocode/instance") + return provide(input) } export namespace KiloSessions { @@ -368,7 +368,7 @@ export namespace KiloSessions { if (ingestDisabled) return if (enabling) return enabling const seq = ++remoteSeq - void Bus.publish(Event.RemoteStatusChanged, { enabled: true, connected: false }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: true, connected: false }) enabling = (async () => { const token = await kilocodeToken() if (!token) { @@ -433,10 +433,10 @@ export namespace KiloSessions { getSessions, log, onOpen: () => { - void Bus.publish(Event.RemoteStatusChanged, { enabled: true, connected: true }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: true, connected: true }) }, onDisconnect: () => { - void Bus.publish(Event.RemoteStatusChanged, { enabled: !!remote, connected: false }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: !!remote, connected: false }) }, onMessage: (msg) => { // Must run inside Instance.provide so Bus.subscribeAll can access @@ -465,11 +465,11 @@ export namespace KiloSessions { remote = { conn, sender, heartbeat } log.info("remote connection enabled", { connected: conn.connected }) Telemetry.trackRemoteConnectionOpened() - void Bus.publish(Event.RemoteStatusChanged, { enabled: true, connected: conn.connected }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: true, connected: conn.connected }) })() .catch((err) => { if (remoteSeq === seq && !remote) - void Bus.publish(Event.RemoteStatusChanged, { enabled: false, connected: false }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: false, connected: false }) throw err }) .finally(() => { @@ -484,14 +484,14 @@ export namespace KiloSessions { const pending = !!enabling enabling = undefined if (!remote) { - if (pending) void Bus.publish(Event.RemoteStatusChanged, { enabled: false, connected: false }) + if (pending) void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: false, connected: false }) return } remote.sender.dispose() remote.conn.close() remote = undefined log.info("remote connection disabled") - void Bus.publish(Event.RemoteStatusChanged, { enabled: false, connected: false }) + void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: false, connected: false }) } export function remoteStatus() { diff --git a/packages/opencode/src/kilo-sessions/remote-sender.ts b/packages/opencode/src/kilo-sessions/remote-sender.ts index 0811826b9ae..f1086044800 100644 --- a/packages/opencode/src/kilo-sessions/remote-sender.ts +++ b/packages/opencode/src/kilo-sessions/remote-sender.ts @@ -15,11 +15,11 @@ import z from "zod" import { zodObject } from "@opencode-ai/core/effect-zod" import { Effect } from "effect" -type Provide = typeof import("@/project/with-instance").provide +type Provide = typeof import("@/kilocode/instance").provide async function provide(input: { directory: string; fn: () => R }): Promise { - const { WithInstance } = await import("@/project/with-instance") - return WithInstance.provide(input) + const { provide } = await import("@/kilocode/instance") + return provide(input) } const QuestionData = z.object({ diff --git a/packages/opencode/src/kilocode/agent/index.ts b/packages/opencode/src/kilocode/agent/index.ts index 941209cd734..ed59ed25eed 100644 --- a/packages/opencode/src/kilocode/agent/index.ts +++ b/packages/opencode/src/kilocode/agent/index.ts @@ -4,8 +4,7 @@ import { NamedError } from "@opencode-ai/core/util/error" import { Glob } from "@opencode-ai/core/util/glob" import * as Truncate from "../../tool/truncate" import { Config } from "../../config/config" -import { Instance } from "../../project/instance" -import { makeRuntime } from "@/effect/run-service" +import type { Info as AgentInfo } from "../../agent/agent" import { Schema } from "effect" import path from "path" import { Global } from "@opencode-ai/core/global" @@ -459,24 +458,22 @@ export const RemoveError = NamedError.create("AgentRemoveError", { * Scans all config directories for agent/mode .md files matching the name, * then also checks the .kilocodemodes files the ModesMigrator reads. */ -export async function remove(name: string) { - const { Agent } = await import("../../agent/agent") - const agents = makeRuntime(Agent.Service, Agent.defaultLayer) - const agent = await agents.runPromise((svc) => svc.get(name)) - if (!agent) throw new RemoveError({ name, message: "agent not found" }) - if (agent.native) throw new RemoveError({ name, message: "cannot remove native agent" }) +export async function remove(input: { name: string; agent?: AgentInfo; dirs: string[]; directory: string }) { + if (!input.agent) throw new RemoveError({ name: input.name, message: "agent not found" }) + if (input.agent.native) throw new RemoveError({ name: input.name, message: "cannot remove native agent" }) // Prevent removal of organization-managed agents - if (agent.options?.source === "organization") - throw new RemoveError({ name, message: "cannot remove organization agent — manage it from the cloud dashboard" }) + if (input.agent.options?.source === "organization") + throw new RemoveError({ + name: input.name, + message: "cannot remove organization agent — manage it from the cloud dashboard", + }) const { unlink, writeFile } = await import("fs/promises") let found = false // 1. Delete .md files from config directories - const { AppRuntime } = await import("@/effect/app-runtime") - const dirs = await AppRuntime.runPromise(Config.Service.use((svc) => svc.directories())) - const patterns = ["{agent,agents}/**/" + name + ".md", "{mode,modes}/" + name + ".md"] - for (const dir of dirs) { + const patterns = ["{agent,agents}/**/" + input.name + ".md", "{mode,modes}/" + input.name + ".md"] + for (const dir of input.dirs) { for (const pattern of patterns) { const matches = await Glob.scan(pattern, { cwd: dir, absolute: true, dot: true }) for (const file of matches) { @@ -498,14 +495,14 @@ export async function remove(name: string) { path.join(KilocodePaths.vscodeGlobalStorage(), "settings", "custom_modes.yaml"), path.join(home, ".kilocode", "cli", "global", "settings", "custom_modes.yaml"), path.join(home, ".kilocodemodes"), - path.join(Instance.directory, ".kilocodemodes"), + path.join(input.directory, ".kilocodemodes"), ] for (const file of modesFiles) { const modes = await ModesMigrator.readModesFile(file) if (!modes.length) continue - const filtered = modes.filter((m: { slug: string }) => m.slug !== name) + const filtered = modes.filter((m: { slug: string }) => m.slug !== input.name) if (filtered.length === modes.length) continue // Rewrite the file without the removed mode @@ -517,8 +514,5 @@ export async function remove(name: string) { found = true } - if (!found) throw new RemoveError({ name, message: "no agent file found on disk" }) - - const runtime = await import("../../project/instance-runtime") - await runtime.InstanceRuntime.disposeInstance(Instance.current) + if (!found) throw new RemoveError({ name: input.name, message: "no agent file found on disk" }) } diff --git a/packages/opencode/src/kilocode/background-process/index.ts b/packages/opencode/src/kilocode/background-process/index.ts index 035e76b15c9..3b248c2b6c1 100644 --- a/packages/opencode/src/kilocode/background-process/index.ts +++ b/packages/opencode/src/kilocode/background-process/index.ts @@ -3,7 +3,7 @@ import { BusEvent } from "@/bus/bus-event" import { InstanceState } from "@/effect/instance-state" import { makeRuntime } from "@/effect/run-service" import { Identifier } from "@/id/id" -import { Instance, type InstanceContext } from "@/project/instance" +import { Instance, type InstanceContext } from "@/kilocode/instance" import { SessionID } from "@/session/schema" import { Shell } from "@/shell/shell" import { NonNegativeInt, PositiveInt, optionalOmitUndefined, withStatics } from "@opencode-ai/core/schema" @@ -194,7 +194,7 @@ export namespace BackgroundProcess { function emit(active: Active) { Instance.restore(active.ctx, () => { - void Bus.publish(Event.Updated, { info: clone(active.info) }).catch((err) => { + void Bus.publish(active.ctx, Event.Updated, { info: clone(active.info) }).catch((err) => { log.warn("failed to publish process update", { err, id: active.info.id }) }) }) @@ -452,9 +452,11 @@ export namespace BackgroundProcess { active.resolve = undefined if (opts.silent) return await Instance.restore(active.ctx, () => - Bus.publish(Event.Deleted, { sessionID: active.info.sessionID, processID: active.info.id }).catch((err) => { - log.warn("failed to publish process deletion", { err, id: active.info.id }) - }), + Bus.publish(active.ctx, Event.Deleted, { sessionID: active.info.sessionID, processID: active.info.id }).catch( + (err) => { + log.warn("failed to publish process deletion", { err, id: active.info.id }) + }, + ), ) } diff --git a/packages/opencode/src/kilocode/bootstrap.ts b/packages/opencode/src/kilocode/bootstrap.ts index 4a72bbf9030..637323abc29 100644 --- a/packages/opencode/src/kilocode/bootstrap.ts +++ b/packages/opencode/src/kilocode/bootstrap.ts @@ -8,7 +8,7 @@ import path from "node:path" import { Bus } from "@/bus" import { SessionExport } from "@/kilocode/session-export" import { createWorkspaceProvider } from "@/kilocode/session-export/workspace-provider" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { Identity } from "@kilocode/kilo-telemetry" const log = Log.create({ service: "kilocode-bootstrap" }) diff --git a/packages/opencode/src/kilocode/cli/cmd/roll-call.ts b/packages/opencode/src/kilocode/cli/cmd/roll-call.ts index cf025fdef6b..9c2b1f4ba71 100644 --- a/packages/opencode/src/kilocode/cli/cmd/roll-call.ts +++ b/packages/opencode/src/kilocode/cli/cmd/roll-call.ts @@ -1,5 +1,5 @@ import type { Argv } from "yargs" -import { WithInstance } from "../../../project/with-instance" +import { provide } from "../../instance" import { Provider } from "../../../provider/provider" import { ProviderTransform } from "../../../provider/transform" import { cmd } from "../../../cli/cmd/cmd" @@ -167,7 +167,7 @@ export async function handle(args: ArgumentsCamelCase) { ) } - await WithInstance.provide({ + await provide({ directory: process.cwd(), async fn() { const providers = await load() diff --git a/packages/opencode/src/kilocode/config-validation.ts b/packages/opencode/src/kilocode/config-validation.ts index 39eddb67180..681c043f04d 100644 --- a/packages/opencode/src/kilocode/config-validation.ts +++ b/packages/opencode/src/kilocode/config-validation.ts @@ -9,7 +9,7 @@ import { Config } from "@/config/config" import { ConfigAgent } from "@/config/agent" import { ConfigCommand } from "@/config/command" import { JsonError } from "@/config/error" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { Filesystem } from "@/util/filesystem" export namespace ConfigValidation { diff --git a/packages/opencode/src/kilocode/config/config.ts b/packages/opencode/src/kilocode/config/config.ts index 660b29ea482..ef56c8f63d2 100644 --- a/packages/opencode/src/kilocode/config/config.ts +++ b/packages/opencode/src/kilocode/config/config.ts @@ -180,8 +180,9 @@ export namespace KilocodeConfig { const err = new ConfigError.InvalidError({ path: item, issues }, { cause }) if (warnings) warnings.push({ path: item, message, detail: text || undefined }) try { - const { Session } = await import("@/session/session") - Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) + const [{ Session }, { capture }] = await Promise.all([import("@/session/session"), import("@/kilocode/instance")]) + const ctx = capture() + if (ctx) Bus.publish(ctx, Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) } catch (e) { log.warn("could not publish session error", { message, err: e }) } diff --git a/packages/opencode/src/kilocode/indexing.ts b/packages/opencode/src/kilocode/indexing.ts index ab0c883de69..b00b5f4a656 100644 --- a/packages/opencode/src/kilocode/indexing.ts +++ b/packages/opencode/src/kilocode/indexing.ts @@ -6,7 +6,7 @@ import { hasIndexingPlugin } from "@kilocode/kilo-indexing/detect" import { IndexingStatus, disabledIndexingStatus } from "@kilocode/kilo-indexing/status" import { Telemetry } from "@kilocode/kilo-telemetry" import { fetchKiloEmbeddingModelCatalog } from "@kilocode/kilo-gateway" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { Bus } from "@/bus" import { Config } from "@/config/config" import { AppRuntime } from "@/effect/app-runtime" @@ -215,7 +215,7 @@ export namespace KiloIndexing { const inert = async (current: () => Status): Promise => { const publish = async () => { - await Bus.publish(Event, { status: current() }) + await Bus.publish(Instance.current, Event, { status: current() }) } return { @@ -258,7 +258,7 @@ export namespace KiloIndexing { let disposed = false const publish = async () => { - await Bus.publish(Event, { status: current() }) + await Bus.publish(Instance.current, Event, { status: current() }) } const report = Instance.bind(async () => { try { diff --git a/packages/opencode/src/kilocode/instance.ts b/packages/opencode/src/kilocode/instance.ts new file mode 100644 index 00000000000..64e2bb8a1f3 --- /dev/null +++ b/packages/opencode/src/kilocode/instance.ts @@ -0,0 +1,58 @@ +import { Context, Fiber } from "effect" +import { InstanceRef } from "@/effect/instance-ref" +import { context, type InstanceContext } from "@/project/instance-context" +import { LocalContext } from "@/util/local-context" + +export type { InstanceContext } from "@/project/instance-context" + +function current() { + const ctx = capture() + if (!ctx) throw new LocalContext.NotFound("instance") + return ctx +} + +export const Instance = { + get current() { + return current() + }, + get directory() { + return current().directory + }, + get worktree() { + return current().worktree + }, + get project() { + return current().project + }, + bind unknown>(fn: F): F { + const ctx = capture() + if (!ctx) return fn + return ((...args: Parameters) => context.provide(ctx, () => fn(...args))) as F + }, + restore(ctx: InstanceContext, fn: () => R): R { + return context.provide(ctx, fn) + }, +} + +export function capture() { + try { + return context.use() + } catch (err) { + if (!(err instanceof LocalContext.NotFound)) throw err + } + const fiber = Fiber.getCurrent() + return fiber ? Context.getReferenceUnsafe(fiber.context, InstanceRef) : undefined +} + +export function bind unknown>(fn: F): F { + return Instance.bind(fn) +} + +export async function provide(input: { directory: string; fn: () => R }): Promise { + const runtime = await import("@/effect/app-runtime") + const project = await import("@/project/instance-store") + const ctx = await runtime.AppRuntime.runPromise( + project.InstanceStore.Service.use((store) => store.load({ directory: input.directory })), + ) + return context.provide(ctx, input.fn) +} diff --git a/packages/opencode/src/kilocode/permission/drain.ts b/packages/opencode/src/kilocode/permission/drain.ts index 005b91dd795..acda27dd885 100644 --- a/packages/opencode/src/kilocode/permission/drain.ts +++ b/packages/opencode/src/kilocode/permission/drain.ts @@ -2,6 +2,7 @@ import { Bus } from "@/bus" import { Deferred, Effect } from "effect" import { Permission } from "@/permission" import { ConfigProtection } from "@/kilocode/permission/config-paths" +import { Instance } from "@/kilocode/instance" interface PendingEntry { info: Permission.Request @@ -39,14 +40,14 @@ export function drainCovered( if (!denied && !allowed) continue pending.delete(id) if (denied) { - void Bus.publish(Permission.Event.Replied, { + void Bus.publish(Instance.current, Permission.Event.Replied, { sessionID: entry.info.sessionID, requestID: entry.info.id, reply: "reject", }) yield* Deferred.fail(entry.deferred, new Permission.RejectedError()) } else { - void Bus.publish(Permission.Event.Replied, { + void Bus.publish(Instance.current, Permission.Event.Replied, { sessionID: entry.info.sessionID, requestID: entry.info.id, reply: "always", diff --git a/packages/opencode/src/kilocode/plan-followup.ts b/packages/opencode/src/kilocode/plan-followup.ts index 73098ccd377..a32466ae199 100644 --- a/packages/opencode/src/kilocode/plan-followup.ts +++ b/packages/opencode/src/kilocode/plan-followup.ts @@ -5,7 +5,7 @@ import { TuiEvent } from "@/cli/cmd/tui/event" import { Flag } from "@opencode-ai/core/flag/flag" import { Global } from "@opencode-ai/core/global" import { Identifier } from "@/id/id" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { Provider } from "@/provider/provider" import { ProviderID, ModelID } from "@/provider/schema" import { Question } from "@/question" @@ -54,9 +54,8 @@ export const PlanFollowupRuntime = { return AppRuntime.runPromise(Session.Service.use(run)) }, async loop(sessionID: SessionID) { - const item = await import("@/session/prompt") - const prompt = makeRuntime(item.SessionPrompt.Service, item.SessionPrompt.defaultLayer) - return prompt.runPromise((svc) => svc.loop({ sessionID })) + const [item, app] = await Promise.all([import("@/session/prompt"), import("@/effect/app-runtime")]) + return app.AppRuntime.runPromise(item.SessionPrompt.Service.use((svc) => svc.loop({ sessionID }))) }, } @@ -181,7 +180,10 @@ export namespace PlanFollowup { model: z .record( z.string(), - z.object({ providerID: z.custom(Schema.is(ProviderID)), modelID: z.custom(Schema.is(ModelID)) }), + z.object({ + providerID: z.custom(Schema.is(ProviderID)), + modelID: z.custom(Schema.is(ModelID)), + }), ) .optional(), variant: z.record(z.string(), z.string().optional()).optional(), @@ -356,9 +358,9 @@ export namespace PlanFollowup { model: input.model, }) const session = await PlanFollowupRuntime.session((svc) => svc.get(input.sessionID)) - const { WithInstance } = await import("@/project/with-instance") + const { provide } = await import("@/kilocode/instance") - await WithInstance.provide({ + await provide({ directory: session.directory, fn: async () => { // Create the session FIRST so session.created fires immediately while the @@ -370,7 +372,7 @@ export namespace PlanFollowup { pending.set(next.id, ctl) const { AppRuntime } = await import("@/effect/app-runtime") await AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.set(next.id, { type: "busy" }))) - await Bus.publish(TuiEvent.SessionSelect, { sessionID: next.id }) + await Bus.publish(Instance.current, TuiEvent.SessionSelect, { sessionID: next.id }) const idle = () => AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.set(next.id, { type: "idle" }))).catch((err) => { @@ -451,7 +453,7 @@ export namespace PlanFollowup { return } - const queue = WithInstance.provide({ + const queue = provide({ directory: next.directory, fn: async () => { if (ctl.signal.aborted) { diff --git a/packages/opencode/src/kilocode/project-id.ts b/packages/opencode/src/kilocode/project-id.ts index 392604a254b..02d016d9fd6 100644 --- a/packages/opencode/src/kilocode/project-id.ts +++ b/packages/opencode/src/kilocode/project-id.ts @@ -1,5 +1,5 @@ import { Context, Effect, Layer } from "effect" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { InstanceState } from "@/effect/instance-state" import { makeRuntime } from "@/effect/run-service" import path from "path" diff --git a/packages/opencode/src/kilocode/review/review.ts b/packages/opencode/src/kilocode/review/review.ts index 26b80bd49cb..1b497a19b00 100644 --- a/packages/opencode/src/kilocode/review/review.ts +++ b/packages/opencode/src/kilocode/review/review.ts @@ -1,6 +1,6 @@ import { $ } from "bun" import * as Log from "@opencode-ai/core/util/log" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" const log = Log.create({ service: "review" }) diff --git a/packages/opencode/src/kilocode/server/httpapi/handlers/kilo-gateway.ts b/packages/opencode/src/kilocode/server/httpapi/handlers/kilo-gateway.ts index a9472bc234a..6e57c9cee7a 100644 --- a/packages/opencode/src/kilocode/server/httpapi/handlers/kilo-gateway.ts +++ b/packages/opencode/src/kilocode/server/httpapi/handlers/kilo-gateway.ts @@ -32,7 +32,7 @@ import { Auth } from "@/auth" import { EffectBridge } from "@/effect/bridge" import { Bus } from "@/bus" import { Identifier } from "@/id/id" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import { InstanceStore } from "@/project/instance-store" import { ModelCache } from "@/provider/model-cache" import { InstanceHttpApi } from "@/server/routes/instance/httpapi/api" @@ -471,7 +471,10 @@ export const kiloGatewayHandlers = HttpApiBuilder.group(InstanceHttpApi, "kilo", MessageTable, PartTable, SessionToRow: Session.toRow, - Bus, + Bus: { + publish: (_event, payload) => + Bus.publish(Instance.current, Session.Event.Created, payload as never), + }, SessionCreatedEvent: Session.Event.Created, Identifier, }), diff --git a/packages/opencode/src/kilocode/server/httpapi/handlers/kilocode.ts b/packages/opencode/src/kilocode/server/httpapi/handlers/kilocode.ts index 3eda47145b7..75faa4c6fb2 100644 --- a/packages/opencode/src/kilocode/server/httpapi/handlers/kilocode.ts +++ b/packages/opencode/src/kilocode/server/httpapi/handlers/kilocode.ts @@ -1,14 +1,22 @@ import { Effect } from "effect" import { HttpApiBuilder } from "effect/unstable/httpapi" import * as KiloAgent from "@/kilocode/agent" +import { Agent } from "@/agent/agent" +import { Config } from "@/config/config" import { EffectBridge } from "@/effect/bridge" +import { InstanceState } from "@/effect/instance-state" import { HeapSnapshot } from "@/kilocode/cli/heap-snapshot" +import { InstanceStore } from "@/project/instance-store" import { InstanceHttpApi } from "@/server/routes/instance/httpapi/api" import { Skill } from "@/skill" import { RemoveAgentPayload, RemoveSkillPayload } from "../groups/kilocode" export const kilocodeHandlers = HttpApiBuilder.group(InstanceHttpApi, "kilocode", (handlers) => Effect.gen(function* () { + const agents = yield* Agent.Service + const config = yield* Config.Service + const store = yield* InstanceStore.Service + const heapSnapshot = Effect.fn("KilocodeHttpApi.heapSnapshot")(function* () { return yield* Effect.sync(() => HeapSnapshot.write()) }) @@ -23,7 +31,13 @@ export const kilocodeHandlers = HttpApiBuilder.group(InstanceHttpApi, "kilocode" const removeAgent = Effect.fn("KilocodeHttpApi.removeAgent")(function* (ctx: { payload: typeof RemoveAgentPayload.Type }) { - yield* EffectBridge.fromPromise(() => KiloAgent.remove(ctx.payload.name)) + const instance = yield* InstanceState.context + const agent = yield* agents.get(ctx.payload.name) + const dirs = yield* config.directories() + yield* EffectBridge.fromPromise(() => + KiloAgent.remove({ name: ctx.payload.name, agent, dirs, directory: instance.directory }), + ) + yield* store.dispose(instance) return true }) diff --git a/packages/opencode/src/kilocode/session/prompt.ts b/packages/opencode/src/kilocode/session/prompt.ts index dc6244d5dfe..90e33619f94 100644 --- a/packages/opencode/src/kilocode/session/prompt.ts +++ b/packages/opencode/src/kilocode/session/prompt.ts @@ -7,7 +7,7 @@ import { SessionID, PartID } from "@/session/schema" import { MessageV2 } from "@/session/message-v2" import { Session } from "@/session/session" import { Agent } from "@/agent/agent" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import type { SessionStatus } from "@/session/status" import { Flag } from "@opencode-ai/core/flag/flag" import { PlanFollowup } from "@/kilocode/plan-followup" @@ -67,18 +67,18 @@ export namespace KiloSessionPrompt { question: Pick }): Promise<"continue" | "break"> { if (!shouldAskPlanFollowup({ messages: input.messages, abort: input.abort })) return "break" - const ask = InstanceState.bind(PlanFollowup.ask) + const ask = Instance.bind(PlanFollowup.ask) const action = await ask({ sessionID: input.sessionID, messages: input.messages, abort: input.abort, // Keep the request in the listener-local Question service so HTTP replies can resolve it. question: { - ask: InstanceState.bind((request: Parameters[0]) => + ask: Instance.bind((request: Parameters[0]) => Effect.runPromise(input.question.ask(request)), ), - list: InstanceState.bind(() => Effect.runPromise(input.question.list())), - reject: InstanceState.bind((requestID: Parameters[0]) => + list: Instance.bind(() => Effect.runPromise(input.question.list())), + reject: Instance.bind((requestID: Parameters[0]) => Effect.runPromise(input.question.reject(requestID)), ), }, @@ -279,7 +279,7 @@ export namespace KiloSessionPrompt { }) // keep bind(): inside Effect.promise the project context is lost, so Instance.current throws without it - const ctx = InstanceState.bind(() => Instance.current)() + const ctx = Instance.bind(() => Instance.current)() const plan = Session.plan(input.session, ctx) if (mode(input.agent.name) === "plan") { diff --git a/packages/opencode/src/kilocode/snapshot/track.ts b/packages/opencode/src/kilocode/snapshot/track.ts index 269b5b94ca2..6daad81d5b2 100644 --- a/packages/opencode/src/kilocode/snapshot/track.ts +++ b/packages/opencode/src/kilocode/snapshot/track.ts @@ -556,7 +556,7 @@ export namespace KiloSnapshotTrack { * tests that bypass the runtime). */ async function currentDirectory(): Promise<{ directory: string; worktree?: string } | undefined> { - const { Instance } = await import("@/project/instance") + const { Instance } = await import("@/kilocode/instance") try { return { directory: Instance.directory, worktree: Instance.worktree } } catch { diff --git a/packages/opencode/src/kilocode/suggestion/index.ts b/packages/opencode/src/kilocode/suggestion/index.ts index 19e82469dc3..28e4a14ae80 100644 --- a/packages/opencode/src/kilocode/suggestion/index.ts +++ b/packages/opencode/src/kilocode/suggestion/index.ts @@ -8,6 +8,7 @@ import { Telemetry } from "@kilocode/kilo-telemetry" import z from "zod" import { Schema } from "effect" import { KiloSessionPromptQueue } from "../session/prompt-queue" +import { Instance } from "../instance" import { parseReviewCommand } from "../review/command" export namespace Suggestion { @@ -167,7 +168,7 @@ export namespace Suggestion { actionCount: info.actions.length, }) }) - Bus.publish(Event.Shown, { ...info, sessionID: SessionID.make(info.sessionID) }) + Bus.publish(Instance.current, Event.Shown, { ...info, sessionID: SessionID.make(info.sessionID) }) }) } @@ -203,7 +204,7 @@ export namespace Suggestion { }) } - Bus.publish(Event.Accepted, { + Bus.publish(Instance.current, Event.Accepted, { sessionID: SessionID.make(existing.info.sessionID), requestID: existing.info.id, index: input.index, @@ -225,7 +226,7 @@ export namespace Suggestion { log.info("dismissed", { requestID }) - Bus.publish(Event.Dismissed, { + Bus.publish(Instance.current, Event.Dismissed, { sessionID: SessionID.make(existing.info.sessionID), requestID: existing.info.id, }) @@ -246,7 +247,7 @@ export namespace Suggestion { if (entry.info.sessionID !== sessionID) continue delete s.pending[id] log.info("dismissed", { requestID: id }) - Bus.publish(Event.Dismissed, { + Bus.publish(Instance.current, Event.Dismissed, { sessionID: SessionID.make(entry.info.sessionID), requestID: entry.info.id, }) diff --git a/packages/opencode/src/kilocode/system-prompt.ts b/packages/opencode/src/kilocode/system-prompt.ts index 02743776743..7c0f22c412c 100644 --- a/packages/opencode/src/kilocode/system-prompt.ts +++ b/packages/opencode/src/kilocode/system-prompt.ts @@ -3,7 +3,7 @@ import { Global } from "@opencode-ai/core/global" import { staticEnvLines, type EditorContext } from "@/kilocode/editor-context" import type { Provider } from "@/provider/provider" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" export namespace KilocodeSystemPrompt { export function environment(input: { ctx: InstanceContext; model: Provider.Model; editor?: EditorContext }) { diff --git a/packages/opencode/src/kilocode/tool/semantic-search.ts b/packages/opencode/src/kilocode/tool/semantic-search.ts index 872f40ed9c0..9bbbc85a3d5 100644 --- a/packages/opencode/src/kilocode/tool/semantic-search.ts +++ b/packages/opencode/src/kilocode/tool/semantic-search.ts @@ -2,7 +2,7 @@ import { Effect, Schema } from "effect" import path from "path" import * as Tool from "@/tool/tool" import { KiloIndexing } from "@/kilocode/indexing" -import { Instance } from "@/project/instance" +import { Instance } from "@/kilocode/instance" import DESCRIPTION from "./semantic-search.txt" diff --git a/packages/opencode/src/kilocode/tool/task.ts b/packages/opencode/src/kilocode/tool/task.ts index 5f2be34b315..b221165002e 100644 --- a/packages/opencode/src/kilocode/tool/task.ts +++ b/packages/opencode/src/kilocode/tool/task.ts @@ -20,7 +20,10 @@ const ModelState = z model: z .record( z.string(), - z.object({ providerID: z.custom(Schema.is(ProviderID)), modelID: z.custom(Schema.is(ModelID)) }), + z.object({ + providerID: z.custom(Schema.is(ProviderID)), + modelID: z.custom(Schema.is(ModelID)), + }), ) .optional(), variant: z.record(z.string(), z.string().optional()).optional(), diff --git a/packages/opencode/src/kilocode/ts-client.ts b/packages/opencode/src/kilocode/ts-client.ts index 8046df0df48..cb2b3570dcb 100644 --- a/packages/opencode/src/kilocode/ts-client.ts +++ b/packages/opencode/src/kilocode/ts-client.ts @@ -9,7 +9,7 @@ import { TsCheck } from "./ts-check" import * as Log from "@opencode-ai/core/util/log" import { withTimeout } from "../util/timeout" import path from "path" -import { Instance } from "../project/instance" +import { Instance } from "./instance" export namespace TsClient { const log = Log.create({ service: "ts-client" }) @@ -30,7 +30,7 @@ export namespace TsClient { diagnostics.set(file, diags) } for (const file of result.keys()) { - Bus.publish(LSPClient.Event.Diagnostics, { + Bus.publish(Instance.current, LSPClient.Event.Diagnostics, { path: file, serverID: client.serverID, }) diff --git a/packages/opencode/src/lsp/client.ts b/packages/opencode/src/lsp/client.ts index 30577a8f116..205cba6f29e 100644 --- a/packages/opencode/src/lsp/client.ts +++ b/packages/opencode/src/lsp/client.ts @@ -7,10 +7,13 @@ import type { Diagnostic as VSCodeDiagnostic } from "vscode-languageserver-types import * as Log from "@opencode-ai/core/util/log" import { Process } from "@/util/process" import { LANGUAGE_EXTENSIONS } from "./language" -import { Schema } from "effect" +import { Effect, Schema } from "effect" import type * as LSPServer from "./server" import { withTimeout } from "../util/timeout" import { Filesystem } from "@/util/filesystem" +import { InstanceRef } from "@/effect/instance-ref" +import { makeRuntime } from "@/effect/run-service" +import type { InstanceContext } from "@/project/instance-context" const DIAGNOSTICS_DEBOUNCE_MS = 150 const DIAGNOSTICS_DOCUMENT_WAIT_TIMEOUT_MS = 5_000 @@ -25,6 +28,7 @@ const FILE_CHANGE_CHANGED = 2 const TEXT_DOCUMENT_SYNC_INCREMENTAL = 2 const log = Log.create({ service: "lsp.client" }) +const busRuntime = makeRuntime(Bus.Service, Bus.layer) export type Info = NonNullable>> @@ -134,9 +138,16 @@ function shouldSeedDiagnosticsOnFirstPush(serverID: string) { return serverID === "typescript" } -export async function create(input: { serverID: string; server: LSPServer.Handle; root: string; directory: string }) { +export async function create(input: { + serverID: string + server: LSPServer.Handle + root: string + directory: string + instance: InstanceContext +}) { const logger = log.clone().tag("serverID", input.serverID) logger.info("starting client") + const instance = input.instance const connection = createMessageConnection( new StreamMessageReader(input.server.process.stdout as any), @@ -162,7 +173,11 @@ export async function create(input: { serverID: string; server: LSPServer.Handle dedupeDiagnostics([...(pushDiagnostics.get(filePath) ?? []), ...(pullDiagnostics.get(filePath) ?? [])]) const updatePushDiagnostics = (filePath: string, next: Diagnostic[]) => { pushDiagnostics.set(filePath, next) - Bus.publish(Event.Diagnostics, { path: filePath, serverID: input.serverID }) + void busRuntime.runPromise((svc) => + svc + .publish(Event.Diagnostics, { path: filePath, serverID: input.serverID }) + .pipe(Effect.provideService(InstanceRef, instance)), + ) } const updatePullDiagnostics = (filePath: string, next: Diagnostic[]) => { pullDiagnostics.set(filePath, next) @@ -510,10 +525,14 @@ export async function create(input: { serverID: string; server: LSPServer.Handle } timeoutTimer = setTimeout(() => finish(false), request.timeout) - unsub = Bus.subscribe(Event.Diagnostics, (event) => { - if (event.properties.path !== request.path || event.properties.serverID !== input.serverID) return - schedule() - }) + unsub = busRuntime.runSync((svc) => + svc + .subscribeCallback(Event.Diagnostics, (event) => { + if (event.properties.path !== request.path || event.properties.serverID !== input.serverID) return + schedule() + }) + .pipe(Effect.provideService(InstanceRef, instance)), + ) schedule() }) } diff --git a/packages/opencode/src/lsp/lsp.ts b/packages/opencode/src/lsp/lsp.ts index 165bb4477ba..ae08ab50d4a 100644 --- a/packages/opencode/src/lsp/lsp.ts +++ b/packages/opencode/src/lsp/lsp.ts @@ -238,6 +238,7 @@ export const layer = Layer.effect( server: handle, root, directory: ctx.directory, + instance: ctx, }).catch(async (err) => { s.broken.add(key) await Process.stop(handle.process) @@ -274,7 +275,7 @@ export const layer = Layer.effect( const client = TsClient.create({ root }) s.clients.push(client) result.push(client) - Bus.publish(Event.Updated, {}) + await Bus.publish(ctx, Event.Updated, {}) continue } // kilocode_change end @@ -306,7 +307,7 @@ export const layer = Layer.effect( if (!client) continue result.push(client) - Bus.publish(Event.Updated, {}) + await Bus.publish(ctx, Event.Updated, {}) } return result diff --git a/packages/opencode/src/lsp/server.ts b/packages/opencode/src/lsp/server.ts index ba4344026ca..f4334afa900 100644 --- a/packages/opencode/src/lsp/server.ts +++ b/packages/opencode/src/lsp/server.ts @@ -6,7 +6,7 @@ import * as Log from "@opencode-ai/core/util/log" import { text } from "node:stream/consumers" import fs from "fs/promises" import { Filesystem } from "@/util/filesystem" -import type { InstanceContext } from "../project/instance" +import type { InstanceContext } from "../project/instance-context" import { Flag } from "@opencode-ai/core/flag/flag" import { Archive } from "@/util/archive" import { Process } from "@/util/process" @@ -124,11 +124,11 @@ export const Vue: Info = { id: "vue", extensions: [".vue"], root: NearestRoot(["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("vue-language-server") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("@vue/language-server") if (!resolved) return binary = resolved @@ -153,13 +153,13 @@ export const ESLint: Info = { id: "eslint", root: NearestRoot(["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock"]), extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue"], - async spawn(root, ctx) { + async spawn(root, ctx, flags) { const eslint = Module.resolve("eslint", ctx.directory) if (!eslint) return log.info("spawning eslint server") const serverPath = path.join(Global.Path.bin, "vscode-eslint", "server", "out", "eslintServer.js") if (!(await Filesystem.exists(serverPath))) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading and building VS Code ESLint server") const response = await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip") if (!response.ok) return @@ -349,11 +349,11 @@ export const Gopls: Info = { return NearestRoot(["go.mod", "go.sum"])(file, ctx) }, extensions: [".go"], - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("gopls") if (!bin) { if (!which("go")) return - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("installing gopls") const proc = Process.spawn(["go", "install", "golang.org/x/tools/gopls@latest"], { @@ -384,7 +384,7 @@ export const Rubocop: Info = { id: "ruby-lsp", root: NearestRoot(["Gemfile"]), extensions: [".rb", ".rake", ".gemspec", ".ru"], - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("rubocop") if (!bin) { const ruby = which("ruby") @@ -393,7 +393,7 @@ export const Rubocop: Info = { log.info("Ruby not found, please install Ruby first") return } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("installing rubocop") const proc = Process.spawn(["gem", "install", "rubocop", "--bindir", Global.Path.bin], { stdout: "pipe", @@ -484,11 +484,11 @@ export const Pyright: Info = { id: "pyright", extensions: [".py", ".pyi"], root: NearestRoot(["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("pyright-langserver") const args = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("pyright", "pyright-langserver") if (!resolved) return binary = resolved @@ -528,7 +528,7 @@ export const ElixirLS: Info = { id: "elixir-ls", extensions: [".ex", ".exs"], root: NearestRoot(["mix.exs", "mix.lock"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("elixir-ls") if (!binary) { const elixirLsPath = path.join(Global.Path.bin, "elixir-ls") @@ -546,7 +546,7 @@ export const ElixirLS: Info = { return } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading elixir-ls from GitHub releases") const response = await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip") @@ -591,7 +591,7 @@ export const Zls: Info = { id: "zls", extensions: [".zig", ".zon"], root: NearestRoot(["build.zig"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("zls") if (!bin) { @@ -601,7 +601,7 @@ export const Zls: Info = { return } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading zls from GitHub releases") const releaseResponse = await fetch("https://api.github.com/repos/zigtools/zls/releases/latest") @@ -703,8 +703,8 @@ export const CSharp: Info = { id: "csharp", root: NearestRoot([".slnx", ".sln", ".csproj", "global.json"]), extensions: [".cs", ".csx"], - async spawn(root) { - const bin = await getRoslynLanguageServer() + async spawn(root, _ctx, flags) { + const bin = await getRoslynLanguageServer(flags.disableLspDownload) if (!bin) return return { @@ -719,8 +719,8 @@ export const Razor: Info = { id: "razor", root: NearestRoot([".slnx", ".sln", ".csproj", "global.json"]), extensions: [".razor", ".cshtml"], - async spawn(root) { - const bin = await getRoslynLanguageServer() + async spawn(root, _ctx, flags) { + const bin = await getRoslynLanguageServer(flags.disableLspDownload) if (!bin) return const razor = await findVscodeRazorExtension() @@ -751,26 +751,26 @@ export const Razor: Info = { let roslynLanguageServerInstall: Promise | undefined -async function getRoslynLanguageServer() { +async function getRoslynLanguageServer(disableLspDownload: boolean) { const existing = which("roslyn-language-server") if (existing) return existing const global = await roslynLanguageServerGlobalPath() if (global) return global - roslynLanguageServerInstall ||= installRoslynLanguageServer().finally(() => { + roslynLanguageServerInstall ||= installRoslynLanguageServer(disableLspDownload).finally(() => { roslynLanguageServerInstall = undefined }) return roslynLanguageServerInstall } -async function installRoslynLanguageServer() { +async function installRoslynLanguageServer(disableLspDownload: boolean) { if (!which("dotnet")) { log.error(".NET SDK is required to install roslyn-language-server") return } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (disableLspDownload) return log.info("installing roslyn-language-server via dotnet tool") const proc = Process.spawn(["dotnet", "tool", "install", "--global", "roslyn-language-server", "--prerelease"], { stdout: "pipe", @@ -848,7 +848,7 @@ export const FSharp: Info = { id: "fsharp", root: NearestRoot([".slnx", ".sln", ".fsproj", "global.json"]), extensions: [".fs", ".fsi", ".fsx", ".fsscript"], - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("fsautocomplete") if (!bin) { if (!which("dotnet")) { @@ -856,7 +856,7 @@ export const FSharp: Info = { return } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("installing fsautocomplete via dotnet tool") const proc = Process.spawn(["dotnet", "tool", "install", "fsautocomplete", "--tool-path", Global.Path.bin], { stdout: "pipe", @@ -965,7 +965,7 @@ export const Clangd: Info = { id: "clangd", root: NearestRoot(["compile_commands.json", "compile_flags.txt", ".clangd"]), extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"], - async spawn(root) { + async spawn(root, _ctx, flags) { const args = ["--background-index", "--clang-tidy"] const fromPath = which("clangd") if (fromPath) { @@ -1000,7 +1000,7 @@ export const Clangd: Info = { } } - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading clangd from GitHub releases") const releaseResponse = await fetch("https://api.github.com/repos/clangd/clangd/releases/latest") @@ -1111,11 +1111,11 @@ export const Svelte: Info = { id: "svelte", extensions: [".svelte"], root: NearestRoot(["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("svelteserver") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("svelte-language-server") if (!resolved) return binary = resolved @@ -1138,7 +1138,7 @@ export const Astro: Info = { id: "astro", extensions: [".astro"], root: NearestRoot(["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock"]), - async spawn(root, ctx) { + async spawn(root, ctx, flags) { const tsserver = Module.resolve("typescript/lib/tsserver.js", ctx.directory) if (!tsserver) { log.info("typescript not found, required for Astro language server") @@ -1149,7 +1149,7 @@ export const Astro: Info = { let binary = which("astro-ls") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("@astrojs/language-server") if (!resolved) return binary = resolved @@ -1199,7 +1199,7 @@ export const JDTLS: Info = { if (settingsRoot) return settingsRoot }, extensions: [".java"], - async spawn(root) { + async spawn(root, _ctx, flags) { const java = which("java") if (!java) { log.error("Java 21 or newer is required to run the JDTLS. Please install it first.") @@ -1217,7 +1217,7 @@ export const JDTLS: Info = { const launcherDir = path.join(distPath, "plugins") const installed = await pathExists(launcherDir) if (!installed) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("Downloading JDTLS LSP server.") await fs.mkdir(distPath, { recursive: true }) const releaseURL = @@ -1310,13 +1310,13 @@ export const KotlinLS: Info = { // 4) Maven fallback return NearestRoot(["pom.xml"])(file, ctx) }, - async spawn(root) { + async spawn(root, _ctx, flags) { const distPath = path.join(Global.Path.bin, "kotlin-ls") const launcherScript = process.platform === "win32" ? path.join(distPath, "kotlin-lsp.cmd") : path.join(distPath, "kotlin-lsp.sh") const installed = await Filesystem.exists(launcherScript) if (!installed) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("Downloading Kotlin Language Server from GitHub.") const releaseResponse = await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest") @@ -1397,11 +1397,11 @@ export const YamlLS: Info = { id: "yaml-ls", extensions: [".yaml", ".yml"], root: NearestRoot(["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("yaml-language-server") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("yaml-language-server") if (!resolved) return binary = resolved @@ -1431,11 +1431,11 @@ export const LuaLS: Info = { "selene.yml", ]), extensions: [".lua"], - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("lua-language-server") if (!bin) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading lua-language-server from GitHub releases") const releaseResponse = await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest") @@ -1564,11 +1564,11 @@ export const PHPIntelephense: Info = { id: "php intelephense", extensions: [".php"], root: NearestRoot(["composer.json", "composer.lock", ".php-version"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("intelephense") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("intelephense") if (!resolved) return binary = resolved @@ -1648,11 +1648,11 @@ export const BashLS: Info = { id: "bash", extensions: [".sh", ".bash", ".zsh", ".ksh"], root: async (_file, ctx) => ctx.directory, - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("bash-language-server") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("bash-language-server") if (!resolved) return binary = resolved @@ -1674,11 +1674,11 @@ export const TerraformLS: Info = { id: "terraform", extensions: [".tf", ".tfvars"], root: NearestRoot([".terraform.lock.hcl", "terraform.tfstate", "*.tf"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("terraform-ls") if (!bin) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading terraform-ls from HashiCorp releases") const releaseResponse = await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest") @@ -1755,11 +1755,11 @@ export const TexLab: Info = { id: "texlab", extensions: [".tex", ".bib"], root: NearestRoot([".latexmkrc", "latexmkrc", ".texlabroot", "texlabroot"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("texlab") if (!bin) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading texlab from GitHub releases") const response = await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest") @@ -1843,11 +1843,11 @@ export const DockerfileLS: Info = { id: "dockerfile", extensions: [".dockerfile", "Dockerfile"], root: async (_file, ctx) => ctx.directory, - async spawn(root) { + async spawn(root, _ctx, flags) { let binary = which("docker-langserver") const args: string[] = [] if (!binary) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return const resolved = await Npm.which("dockerfile-language-server-nodejs") if (!resolved) return binary = resolved @@ -1939,11 +1939,11 @@ export const Tinymist: Info = { id: "tinymist", extensions: [".typ", ".typc"], root: NearestRoot(["typst.toml"]), - async spawn(root) { + async spawn(root, _ctx, flags) { let bin = which("tinymist") if (!bin) { - if (Flag.KILO_DISABLE_LSP_DOWNLOAD) return + if (flags.disableLspDownload) return log.info("downloading tinymist from GitHub releases") const response = await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest") diff --git a/packages/opencode/src/project/instance-store.ts b/packages/opencode/src/project/instance-store.ts index eb65772daef..27766a3a264 100644 --- a/packages/opencode/src/project/instance-store.ts +++ b/packages/opencode/src/project/instance-store.ts @@ -90,7 +90,7 @@ export const layer: Layer.Layer runDisposers(ctx.directory)) + yield* Effect.promise(() => instanceContext.provide(ctx, () => runDisposers(ctx.directory))) // kilocode_change yield* emitDisposed({ directory: ctx.directory, project: ctx.project.id }) }) diff --git a/packages/opencode/src/project/instance.ts b/packages/opencode/src/project/instance.ts deleted file mode 100644 index a54291cf0c7..00000000000 --- a/packages/opencode/src/project/instance.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { context, type InstanceContext } from "./instance-context" - -export type { InstanceContext } from "./instance-context" - -export const Instance = { - get current() { - return context.use() - }, - get directory() { - return context.use().directory - }, - get worktree() { - return context.use().worktree - }, - get project() { - return context.use().project - }, - - /** - * Captures the current instance ALS context and returns a wrapper that - * restores it when called. Use this for callbacks that fire outside the - * instance async context (native addons, event emitters, timers, etc.). - */ - bind any>(fn: F): F { - const ctx = context.use() - return ((...args: any[]) => context.provide(ctx, () => fn(...args))) as F - }, - /** - * Run a synchronous function within the given instance context ALS. - * Use this to bridge from Effect (where InstanceRef carries context) - * back to sync code that reads Instance.directory from ALS. - */ - restore(ctx: InstanceContext, fn: () => R): R { - return context.provide(ctx, fn) - }, -} diff --git a/packages/opencode/src/project/with-instance.ts b/packages/opencode/src/project/with-instance.ts deleted file mode 100644 index b7b5360c753..00000000000 --- a/packages/opencode/src/project/with-instance.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { AppRuntime } from "@/effect/app-runtime" -import { context } from "./instance-context" -import { InstanceStore } from "./instance-store" - -export async function provide(input: { directory: string; fn: () => R }): Promise { - const ctx = await AppRuntime.runPromise( - InstanceStore.Service.use((store) => store.load({ directory: input.directory })), - ) - return context.provide(ctx, () => input.fn()) -} - -export * as WithInstance from "./with-instance" diff --git a/packages/opencode/src/provider/models.ts b/packages/opencode/src/provider/models.ts index b5c0bb1ebf3..930935ea92a 100644 --- a/packages/opencode/src/provider/models.ts +++ b/packages/opencode/src/provider/models.ts @@ -30,74 +30,72 @@ function baseURL(url: string | undefined, org: string | undefined) { return `${base}/api/openrouter` } -export const layer: Layer.Layer< - Service, - never, - Core.Service | Config.Service | Auth.Service | ModelCache.Service -> = Layer.effect( - Service, - Effect.gen(function* () { - const core = yield* Core.Service - const config = yield* Config.Service - const auth = yield* Auth.Service - const cache = yield* ModelCache.Service +export const layer: Layer.Layer = + Layer.effect( + Service, + Effect.gen(function* () { + const core = yield* Core.Service + const config = yield* Config.Service + const auth = yield* Auth.Service + const cache = yield* ModelCache.Service - const get = Effect.fn("ModelsDev.get")(function* () { - const providers = { ...(yield* core.get()) } - delete providers.kilo + const get = Effect.fn("ModelsDev.get")(function* () { + const providers = { ...(yield* core.get()) } + delete providers.kilo - const cfg = yield* config.get() - const disabled = new Set(cfg.disabled_providers ?? []) - const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : undefined - const allowed = (!enabled || enabled.has("kilo")) && !disabled.has("kilo") - const apt = cfg.provider?.apertis?.options - const aptURL = apt?.baseURL ?? "https://api.apertis.ai/v1" - const aptOpts = apt?.baseURL ? { baseURL: apt.baseURL } : {} + const cfg = yield* config.get() + const disabled = new Set(cfg.disabled_providers ?? []) + const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : undefined + const allowed = (!enabled || enabled.has("kilo")) && !disabled.has("kilo") + const apt = cfg.provider?.apertis?.options + const aptURL = apt?.baseURL ?? "https://api.apertis.ai/v1" + const aptOpts = apt?.baseURL ? { baseURL: apt.baseURL } : {} - const addApertis = Effect.fnUntraced(function* () { - if (providers.apertis) return - const models = yield* cache.fetch("apertis", aptOpts).pipe(Effect.catch(() => Effect.succeed({}))) - providers.apertis = { - id: "apertis", - name: "Apertis", - env: ["APERTIS_API_KEY"], - api: aptURL, - npm: "@ai-sdk/openai-compatible", + const addApertis = Effect.fnUntraced(function* () { + if (providers.apertis) return + const models = yield* cache.fetch("apertis", aptOpts).pipe(Effect.catch(() => Effect.succeed({}))) + providers.apertis = { + id: "apertis", + name: "Apertis", + env: ["APERTIS_API_KEY"], + api: aptURL, + npm: "@ai-sdk/openai-compatible", + models, + } + if (Object.keys(models).length === 0) + yield* cache.refresh("apertis", aptOpts).pipe(Effect.ignore, Effect.forkDetach) + }) + + if (!allowed) { + yield* addApertis() + return providers + } + + const opts = cfg.provider?.kilo?.options + const info = yield* auth.get("kilo").pipe(Effect.catch(() => Effect.succeed(undefined))) + const org = opts?.kilocodeOrganizationId ?? (info?.type === "oauth" ? info.accountId : undefined) + const url = baseURL(opts?.baseURL, org) + const fetch = { + ...(url ? { baseURL: url } : {}), + ...(org ? { kilocodeOrganizationId: org } : {}), + } + const models = yield* cache.fetch("kilo", fetch).pipe(Effect.catch(() => Effect.succeed({}))) + providers.kilo = { + id: "kilo", + name: "Kilo Gateway", + env: ["KILO_API_KEY"], + api: KILO_OPENROUTER_BASE.endsWith("/") ? KILO_OPENROUTER_BASE : `${KILO_OPENROUTER_BASE}/`, + npm: "@kilocode/kilo-gateway", models, } - if (Object.keys(models).length === 0) yield* cache.refresh("apertis", aptOpts).pipe(Effect.ignore, Effect.forkDetach) - }) - - if (!allowed) { + if (Object.keys(models).length === 0) yield* cache.refresh("kilo", fetch).pipe(Effect.ignore, Effect.forkDetach) yield* addApertis() return providers - } + }) - const opts = cfg.provider?.kilo?.options - const info = yield* auth.get("kilo").pipe(Effect.catch(() => Effect.succeed(undefined))) - const org = opts?.kilocodeOrganizationId ?? (info?.type === "oauth" ? info.accountId : undefined) - const url = baseURL(opts?.baseURL, org) - const fetch = { - ...(url ? { baseURL: url } : {}), - ...(org ? { kilocodeOrganizationId: org } : {}), - } - const models = yield* cache.fetch("kilo", fetch).pipe(Effect.catch(() => Effect.succeed({}))) - providers.kilo = { - id: "kilo", - name: "Kilo Gateway", - env: ["KILO_API_KEY"], - api: KILO_OPENROUTER_BASE.endsWith("/") ? KILO_OPENROUTER_BASE : `${KILO_OPENROUTER_BASE}/`, - npm: "@kilocode/kilo-gateway", - models, - } - if (Object.keys(models).length === 0) yield* cache.refresh("kilo", fetch).pipe(Effect.ignore, Effect.forkDetach) - yield* addApertis() - return providers - }) - - return Service.of({ get, refresh: core.refresh }) - }), -) + return Service.of({ get, refresh: core.refresh }) + }), + ) export const defaultLayer = layer.pipe( Layer.provide(Core.defaultLayer), diff --git a/packages/opencode/src/provider/transform.ts b/packages/opencode/src/provider/transform.ts index 8249178e4a4..568007f1b49 100644 --- a/packages/opencode/src/provider/transform.ts +++ b/packages/opencode/src/provider/transform.ts @@ -4,7 +4,6 @@ import type { JSONSchema7 } from "@ai-sdk/provider" import type * as Provider from "./provider" import type * as ModelsDev from "@opencode-ai/core/models" import { iife } from "@/util/iife" -import { Flag } from "@opencode-ai/core/flag/flag" import { kiloProviderOptions } from "@/kilocode/provider-options" import { isLing } from "@/kilocode/model-match" // kilocode_change @@ -18,7 +17,7 @@ function mimeToModality(mime: string): Modality | undefined { return undefined } -export const OUTPUT_TOKEN_MAX = Flag.KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX || 32_000 +export const OUTPUT_TOKEN_MAX = 32_000 export function sanitizeSurrogates(content: string) { return content.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { const parameters = operation.parameters if (!Array.isArray(parameters)) return operation return { ...operation, parameters: parameters.map((parameter) => - parameter?.name === "instance" && parameter?.in === "query" + parameter?.name === "location" && parameter?.in === "query" ? { ...parameter, style: "deepObject", explode: true } : parameter, ), @@ -30,30 +30,30 @@ export const instanceQueryOpenApi = OpenApi.annotations({ }, }) -export class V2InstanceMiddleware extends HttpApiMiddleware.Service< - V2InstanceMiddleware, +export class V2LocationMiddleware extends HttpApiMiddleware.Service< + V2LocationMiddleware, { provides: Catalog.Service | PluginBoot.Service } ->()("@opencode/ExperimentalHttpApiV2Instance") {} +>()("@opencode/ExperimentalHttpApiV2Location") {} -function ref(request: HttpServerRequest.HttpServerRequest): Instance.Ref { +function ref(request: HttpServerRequest.HttpServerRequest): Location.Ref { const query = new URL(request.url, "http://localhost").searchParams return { - directory: query.get("instance[directory]") || request.headers["x-kilo-directory"] || process.cwd(), - workspaceID: query.get("instance[workspace]") || request.headers["x-kilo-workspace"], + directory: query.get("location[directory]") || request.headers["x-kilo-directory"] || process.cwd(), + workspaceID: query.get("location[workspace]") || request.headers["x-kilo-workspace"], } } export const layer = Layer.effect( - V2InstanceMiddleware, + V2LocationMiddleware, Effect.gen(function* () { - const instances = yield* InstanceServiceMap - return V2InstanceMiddleware.of((effect) => + const locations = yield* LocationServiceMap + return V2LocationMiddleware.of((effect) => Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest - return yield* effect.pipe(Effect.provide(instances.get(ref(request)))) + return yield* effect.pipe(Effect.provide(locations.get(ref(request)))) }), ) }), -).pipe(Layer.provide(InstanceServiceMap.layer)) +).pipe(Layer.provide(LocationServiceMap.layer)) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts index 060c6c8a83e..131a1425861 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts @@ -1,5 +1,5 @@ import { SessionID } from "@/session/schema" -import { SessionMessage } from "@/v2/session-message" +import { SessionMessage } from "@opencode-ai/core/session-message" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { Authorization } from "../../middleware/authorization" diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/model.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/model.ts index 47b8ec89655..d265ac7fc24 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/model.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/model.ts @@ -2,15 +2,15 @@ import { ModelV2 } from "@opencode-ai/core/model" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { Authorization } from "../../middleware/authorization" -import { InstanceQuery, instanceQueryOpenApi, V2InstanceMiddleware } from "./instance" +import { LocationQuery, locationQueryOpenApi, V2LocationMiddleware } from "./location" export const ModelGroup = HttpApiGroup.make("v2.model") .add( HttpApiEndpoint.get("models", "/api/model", { - query: InstanceQuery, + query: LocationQuery, success: Schema.Array(ModelV2.Info), }) - .annotateMerge(instanceQueryOpenApi) + .annotateMerge(locationQueryOpenApi) .annotateMerge( OpenApi.annotations({ identifier: "v2.model.list", @@ -25,5 +25,5 @@ export const ModelGroup = HttpApiGroup.make("v2.model") description: "Experimental v2 model routes.", }), ) - .middleware(V2InstanceMiddleware) + .middleware(V2LocationMiddleware) .middleware(Authorization) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/provider.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/provider.ts index e62cfc3240d..7a482ce1149 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/provider.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/provider.ts @@ -3,15 +3,15 @@ import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { ApiNotFoundError } from "../../errors" import { Authorization } from "../../middleware/authorization" -import { InstanceQuery, instanceQueryOpenApi, V2InstanceMiddleware } from "./instance" +import { LocationQuery, locationQueryOpenApi, V2LocationMiddleware } from "./location" export const ProviderGroup = HttpApiGroup.make("v2.provider") .add( HttpApiEndpoint.get("providers", "/api/provider", { - query: InstanceQuery, + query: LocationQuery, success: Schema.Array(ProviderV2.Info), }) - .annotateMerge(instanceQueryOpenApi) + .annotateMerge(locationQueryOpenApi) .annotateMerge( OpenApi.annotations({ identifier: "v2.provider.list", @@ -23,11 +23,11 @@ export const ProviderGroup = HttpApiGroup.make("v2.provider") .add( HttpApiEndpoint.get("provider", "/api/provider/:providerID", { params: { providerID: ProviderV2.ID }, - query: InstanceQuery, + query: LocationQuery, success: ProviderV2.Info, error: ApiNotFoundError, }) - .annotateMerge(instanceQueryOpenApi) + .annotateMerge(locationQueryOpenApi) .annotateMerge( OpenApi.annotations({ identifier: "v2.provider.get", @@ -43,5 +43,5 @@ export const ProviderGroup = HttpApiGroup.make("v2.provider") description: "Experimental v2 provider routes.", }), ) - .middleware(V2InstanceMiddleware) + .middleware(V2LocationMiddleware) .middleware(Authorization) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts index 3776f5c72a3..0313b5c0977 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts @@ -1,5 +1,5 @@ import { SessionID } from "@/session/schema" -import { SessionMessage } from "@/v2/session-message" +import { SessionMessage } from "@opencode-ai/core/session-message" import { Prompt } from "@opencode-ai/core/session-prompt" import { SessionV2 } from "@/v2/session" import { Schema } from "effect" diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts index 7739001db7e..daa799b7a8b 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts @@ -1,12 +1,12 @@ import { SessionV2 } from "@/v2/session" import { Layer } from "effect" -import { layer as v2InstanceLayer } from "../groups/v2/instance" +import { layer as v2LocationLayer } from "../groups/v2/location" import { messageHandlers } from "./v2/message" import { modelHandlers } from "./v2/model" import { providerHandlers } from "./v2/provider" import { sessionHandlers } from "./v2/session" export const v2Handlers = Layer.mergeAll(sessionHandlers, messageHandlers, modelHandlers, providerHandlers).pipe( - Layer.provide(v2InstanceLayer), + Layer.provide(v2LocationLayer), Layer.provide(SessionV2.defaultLayer), ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts index 92e37142b40..fd710ba954a 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts @@ -1,4 +1,4 @@ -import { SessionMessage } from "@/v2/session-message" +import { SessionMessage } from "@opencode-ai/core/session-message" import { SessionV2 } from "@/v2/session" import { Effect, Schema } from "effect" import * as DateTime from "effect/DateTime" diff --git a/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts b/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts index 4edfa807873..30347d85ffd 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts @@ -1,5 +1,5 @@ import { EffectBridge } from "@/effect/bridge" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" import { InstanceStore } from "@/project/instance-store" import * as Log from "@opencode-ai/core/util/log" import { Effect } from "effect" diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts index 74c690ad6cd..7b5643fd68b 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts @@ -1,5 +1,6 @@ import { NamedError } from "@opencode-ai/core/util/error" import * as Log from "@opencode-ai/core/util/log" +import { ConfigError } from "@/config/error" import { Cause, Effect } from "effect" import { HttpRouter, HttpServerError, HttpServerRespondable, HttpServerResponse } from "effect/unstable/http" @@ -18,6 +19,13 @@ export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) if (!defect) return Effect.failCause(cause) const error = defect.defect + if ( + error instanceof NamedError && + (ConfigError.InvalidError.isInstance(error) || ConfigError.JsonError.isInstance(error)) + ) { + return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status: 400 })) + } + log.error("failed", { error, cause: Cause.pretty(cause) }) return Effect.succeed( diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts index d4913696d29..90f3ce47738 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts @@ -1,4 +1,4 @@ -import { WorkspaceRef } from "@/effect/instance-ref" +import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" import { InstanceStore } from "@/project/instance-store" import { Effect, Layer } from "effect" import { HttpRouter, HttpServerResponse } from "effect/unstable/http" @@ -26,9 +26,10 @@ function provideInstanceContext( ): Effect.Effect { return Effect.gen(function* () { const route = yield* WorkspaceRouteContext - return yield* store.provide( - { directory: decode(route.directory) }, - effect.pipe(Effect.provideService(WorkspaceRef, route.workspaceID)), + const ctx = yield* store.load({ directory: decode(route.directory) }) + return yield* effect.pipe( + Effect.provideService(InstanceRef, ctx), + Effect.provideService(WorkspaceRef, route.workspaceID), ) }) } diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts index 0343ccfc87f..018e1f261f2 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts @@ -1,8 +1,7 @@ -import { getAdapter } from "@/control-plane/adapters" import { WorkspaceID } from "@/control-plane/schema" import type { Target } from "@/control-plane/types" import { Workspace } from "@/control-plane/workspace" -import { EffectBridge } from "@/effect/bridge" +import { WorkspaceAdapterRuntime } from "@/control-plane/workspace-adapter-runtime" import { Session } from "@/session/session" import { HttpApiProxy } from "./proxy" import * as Fence from "@/server/shared/fence" @@ -93,8 +92,7 @@ function missingWorkspaceResponse(id: WorkspaceID): HttpServerResponse.HttpServe } function resolveTarget(workspace: Workspace.Info): Effect.Effect { - const adapter = getAdapter(workspace.projectID, workspace.type) - return EffectBridge.fromPromise(() => adapter.target(workspace)) + return WorkspaceAdapterRuntime.target(workspace) } function proxyRemote( diff --git a/packages/opencode/src/server/routes/instance/httpapi/server.ts b/packages/opencode/src/server/routes/instance/httpapi/server.ts index e06d7d2a8ac..5f426cf1381 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/server.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/server.ts @@ -47,6 +47,7 @@ import { SessionSummary } from "@/session/summary" import { Todo } from "@/session/todo" import { SessionShare } from "@/share/session" import { ShareNext } from "@/share/share-next" +import { EventV2Bridge } from "@/event-v2-bridge" import { Skill } from "@/skill" import { Snapshot } from "@/snapshot" import { Storage } from "@/storage/storage" // kilocode_change @@ -112,6 +113,7 @@ const authOnlyRouterLayer = authorizationRouterMiddleware.layer.pipe(Layer.provi const httpApiAuthLayer = authorizationLayer.pipe(Layer.provide(ServerAuth.Config.defaultLayer)) const rootApiRoutes = HttpApiBuilder.layer(RootHttpApi).pipe( Layer.provide([controlHandlers, globalHandlers]), + Layer.provide(schemaErrorLayer), Layer.provide(httpApiAuthLayer), ) const instanceRouterLayer = authorizationRouterMiddleware @@ -149,6 +151,7 @@ const instanceRoutes = Layer.mergeAll(rawInstanceRoutes, instanceApiRoutes).pipe httpApiAuthLayer, workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)), instanceContextLayer, + schemaErrorLayer, ]), ) @@ -185,7 +188,6 @@ export function createRoutes( corsOptions?: CorsOptions, ): Layer.Layer { return Layer.mergeAll(rootApiRoutes, eventApiRoutes, instanceRoutes, docRoute, uiRoute).pipe( - Layer.provide(schemaErrorLayer), // kilocode_change Layer.provide([ errorLayer, compressionLayer, @@ -228,6 +230,7 @@ export function createRoutes( Snapshot.defaultLayer, Storage.defaultLayer, // kilocode_change SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, Skill.defaultLayer, Todo.defaultLayer, ToolRegistry.defaultLayer, diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index b7a46918b24..9a448b78d62 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1,3 +1,5 @@ +import "./init-projectors" + import { NodeHttpServer } from "@effect/platform-node" import * as Log from "@opencode-ai/core/util/log" import { ConfigProvider, Context, Effect, Exit, Layer, Scope } from "effect" @@ -5,7 +7,6 @@ import { HttpRouter, HttpServer } from "effect/unstable/http" import { OpenApi } from "effect/unstable/httpapi" import { createServer } from "node:http" import { MDNS } from "./mdns" -import { initProjectors } from "./projectors" import { HttpApiApp } from "./routes/instance/httpapi/server" import { disposeMiddleware } from "./routes/instance/httpapi/lifecycle" import { WebSocketTracker } from "./routes/instance/httpapi/websocket-tracker" @@ -16,8 +17,6 @@ import { lazy } from "@/util/lazy" // @ts-ignore This global is needed to prevent ai-sdk from logging warnings to stdout https://github.com/vercel/ai/blob/2dc67e0ef538307f21368db32d5a12345d98831b/packages/ai/src/logger/log-warnings.ts#L85 globalThis.AI_SDK_LOG_WARNINGS = false -initProjectors() - const log = Log.create({ service: "server" }) export type Listener = { diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index 82ad7aaa814..253b69b59b5 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -16,7 +16,6 @@ import { Effect, Layer, Context, Schema } from "effect" import * as DateTime from "effect/DateTime" import { InstanceState } from "@/effect/instance-state" import { isOverflow as overflow, usable } from "./overflow" -import { makeRuntime } from "@/effect/run-service" import { serviceUse } from "@/effect/service-use" // kilocode_change start import { KiloSessionPromptQueue } from "@/kilocode/session/prompt-queue" @@ -26,8 +25,8 @@ import { SessionExport } from "@/kilocode/session-export" import { KiloSession } from "@/kilocode/session" // kilocode_change end import { RuntimeFlags } from "@/effect/runtime-flags" -import { SyncEvent } from "@/sync" -import { SessionEvent } from "@/v2/session-event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { SessionEvent } from "@opencode-ai/core/session-event" const log = Log.create({ service: "session.compaction" }) @@ -221,19 +220,7 @@ export class Service extends Context.Service()("@opencode/Se export const use = serviceUse(Service) -export const layer: Layer.Layer< - Service, - never, - | Bus.Service - | Config.Service - | Session.Service - | Agent.Service - | Plugin.Service - | SessionProcessor.Service - | Provider.Service - | SyncEvent.Service - | RuntimeFlags.Service -> = Layer.effect( +export const layer = Layer.effect( Service, Effect.gen(function* () { const bus = yield* Bus.Service @@ -243,14 +230,19 @@ export const layer: Layer.Layer< const plugin = yield* Plugin.Service const processors = yield* SessionProcessor.Service const provider = yield* Provider.Service - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service const isOverflow = Effect.fn("SessionCompaction.isOverflow")(function* (input: { tokens: MessageV2.Assistant["tokens"] model: Provider.Model }) { - return overflow({ cfg: yield* config.get(), tokens: input.tokens, model: input.model }) + return overflow({ + cfg: yield* config.get(), + tokens: input.tokens, + model: input.model, + outputTokenMax: flags.outputTokenMax, + }) }) const estimate = Effect.fn("SessionCompaction.estimate")(function* (input: { @@ -641,7 +633,7 @@ export const layer: Layer.Layer< }, ) if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Compaction.Ended.Sync, { + yield* events.publish(SessionEvent.Compaction.Ended, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(Date.now()), text: summary ?? "", @@ -712,7 +704,7 @@ export const layer: Layer.Layer< KiloSessionPromptQueue.retarget(input.sessionID, msg.id) // kilocode_change end if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Compaction.Started.Sync, { + yield* events.publish(SessionEvent.Compaction.Started, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(Date.now()), reason: input.auto ? "auto" : "manual", @@ -738,20 +730,9 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Plugin.defaultLayer), Layer.provide(Bus.layer), Layer.provide(Config.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), ), ) -const { runPromise } = makeRuntime(Service, defaultLayer) - -export async function isOverflow(input: { tokens: MessageV2.Assistant["tokens"]; model: Provider.Model }) { - return runPromise((svc) => svc.isOverflow(input)) -} - -export async function prune(input: { sessionID: SessionID; reason?: PruneReason }) { - // kilocode_change - return runPromise((svc) => svc.prune(input)) -} - export * as SessionCompaction from "./compaction" diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index de3e0e08756..bc67f7dfbd2 100644 --- a/packages/opencode/src/session/instruction.ts +++ b/packages/opencode/src/session/instruction.ts @@ -3,6 +3,7 @@ import { Effect, Layer, Context } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" import { Config } from "@/config/config" import { InstanceState } from "@/effect/instance-state" +import { RuntimeFlags } from "@/effect/runtime-flags" import { Flag } from "@opencode-ai/core/flag/flag" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { withTransientReadRetry } from "@/util/effect-http-client" @@ -11,9 +12,9 @@ import { KilocodeInstruction } from "@/kilocode/session/instruction" // kilocode import type { MessageV2 } from "./message-v2" import type { MessageID } from "./schema" -const FILES = [ +const files = (disableClaudeCodePrompt: boolean) => [ "AGENTS.md", - ...(Flag.KILO_DISABLE_CLAUDE_CODE_PROMPT ? [] : ["CLAUDE.md"]), + ...(disableClaudeCodePrompt ? [] : ["CLAUDE.md"]), "CONTEXT.md", // deprecated ] @@ -51,21 +52,23 @@ export class Service extends Context.Service()("@opencode/In export const layer: Layer.Layer< Service, never, - AppFileSystem.Service | Config.Service | Global.Service | HttpClient.HttpClient + AppFileSystem.Service | Config.Service | Global.Service | HttpClient.HttpClient | RuntimeFlags.Service > = Layer.effect( Service, Effect.gen(function* () { const cfg = yield* Config.Service const fs = yield* AppFileSystem.Service const global = yield* Global.Service + const flags = yield* RuntimeFlags.Service const http = HttpClient.filterStatusOk(withTransientReadRetry(yield* HttpClient.HttpClient)) const globalFiles = [ // kilocode_change start - prefer KILO_CONFIG_DIR profile when set ...(Flag.KILO_CONFIG_DIR ? [path.join(Flag.KILO_CONFIG_DIR, "AGENTS.md")] : []), // kilocode_change end path.join(global.config, "AGENTS.md"), - ...(!Flag.KILO_DISABLE_CLAUDE_CODE_PROMPT ? [path.join(global.home, ".claude", "CLAUDE.md")] : []), + ...(!flags.disableClaudeCodePrompt ? [path.join(global.home, ".claude", "CLAUDE.md")] : []), ] + const instructionFiles = files(flags.disableClaudeCodePrompt) const state = yield* InstanceState.make( Effect.fn("Instruction.state")(() => @@ -122,8 +125,10 @@ export const layer: Layer.Layer< // The first project-level match wins so we don't stack AGENTS.md/CLAUDE.md from every ancestor. if (!Flag.KILO_DISABLE_PROJECT_CONFIG) { - for (const file of FILES) { - const matches = yield* fs.findUp(file, ctx.directory, ctx.worktree) + for (const file of instructionFiles) { + const matches = yield* fs + .findUp(file, ctx.directory, ctx.worktree) + .pipe(Effect.catch(() => Effect.succeed([]))) if (matches.length > 0) { matches.forEach((item) => paths.add(path.resolve(item))) break @@ -168,7 +173,7 @@ export const layer: Layer.Layer< }) const find = Effect.fn("Instruction.find")(function* (dir: string) { - for (const file of FILES) { + for (const file of instructionFiles) { const filepath = path.resolve(path.join(dir, file)) if (yield* fs.existsSafe(filepath)) return filepath } @@ -228,6 +233,7 @@ export const defaultLayer = layer.pipe( Layer.provide(Global.layer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(FetchHttpClient.layer), + Layer.provide(RuntimeFlags.defaultLayer), ) export function loaded(messages: MessageV2.WithParts[]) { diff --git a/packages/opencode/src/session/llm.ts b/packages/opencode/src/session/llm.ts index caac55bea80..8af3291af3d 100644 --- a/packages/opencode/src/session/llm.ts +++ b/packages/opencode/src/session/llm.ts @@ -215,7 +215,7 @@ const live: Layer.Layer< maxOutputTokens: input.model.api.npm === "@ai-sdk/openai-compatible" && input.model.api.id.toLowerCase().includes("gpt-5") ? undefined - : ProviderTransform.maxOutputTokens(input.model), + : ProviderTransform.maxOutputTokens(input.model, flags.outputTokenMax), // kilocode_change end options, }, @@ -346,7 +346,7 @@ const live: Layer.Layer< const bridge = yield* EffectBridge.make() const approvedToolsForSession = new Set() - workflowModel.approvalHandler = InstanceState.bind(async (approvalTools) => { + workflowModel.approvalHandler = bridge.bind(async (approvalTools) => { const uniqueNames = [...new Set(approvalTools.map((t: { name: string }) => t.name))] as string[] // Auto-approve tools that were already approved in this session // (prevents infinite approval loops for server-side MCP tools) diff --git a/packages/opencode/src/session/network.ts b/packages/opencode/src/session/network.ts index cae83ecd3ba..ea37342a55a 100644 --- a/packages/opencode/src/session/network.ts +++ b/packages/opencode/src/session/network.ts @@ -5,6 +5,9 @@ import { BusEvent } from "../bus/bus-event" import { QuestionID } from "../question/schema" import { SessionID } from "../session/schema" import { InstanceState } from "@/effect/instance-state" +import { InstanceRef } from "@/effect/instance-ref" +import { capture } from "@/kilocode/instance" +import type { InstanceContext } from "@/project/instance-context" import { makeRuntime } from "@/effect/run-service" import * as Log from "@opencode-ai/core/util/log" import { fn } from "@/kilocode/fn" @@ -103,6 +106,7 @@ export namespace SessionNetwork { } interface StateShape { + context: InstanceContext pending: Map< QuestionID, { @@ -122,8 +126,8 @@ export namespace SessionNetwork { StateService, Effect.gen(function* () { const is = yield* InstanceState.make( - Effect.fn("SessionNetwork.state")(function* () { - return { pending: new Map() } as StateShape + Effect.fn("SessionNetwork.state")(function* (ctx) { + return { context: ctx, pending: new Map() } as StateShape }), ) return StateService.of({ @@ -133,7 +137,11 @@ export namespace SessionNetwork { ) const stateRuntime = makeRuntime(StateService, stateLayer) - const state = (): Promise => stateRuntime.runPromise((svc) => svc.get()) + const state = (): Promise => { + const ctx = capture() + if (!ctx) return Promise.reject(new Error("Instance context not available")) + return stateRuntime.runPromise((svc) => svc.get().pipe(Effect.provideService(InstanceRef, ctx))) + } export function code(err: unknown) { for (const item of chain(err)) { @@ -272,7 +280,7 @@ export namespace SessionNetwork { if (!s.pending.has(id)) return input.abort.removeEventListener("abort", onAbort) s.pending.delete(id) - Bus.publish(Event.Rejected, { + void Bus.publish(s.context, Event.Rejected, { sessionID: input.sessionID, requestID: id, }) @@ -296,7 +304,7 @@ export namespace SessionNetwork { return } log.warn("waiting for network", { sessionID: input.sessionID, requestID: id, message: input.message }) - Bus.publish(Event.Asked, info) + void Bus.publish(s.context, Event.Asked, info) void watch({ requestID: id, abort: input.abort }).catch((err) => { log.error("restore watch failed", { err, requestID: id }) }) @@ -317,7 +325,7 @@ export namespace SessionNetwork { req.info.restored = true req.info.time = { ...req.info.time, restored: time } log.info("network restored", { sessionID: req.info.sessionID, requestID }) - Bus.publish(Event.Restored, { + await Bus.publish(s.context, Event.Restored, { sessionID: req.info.sessionID, requestID: req.info.id, time, @@ -369,7 +377,7 @@ export namespace SessionNetwork { log.error("failed to get MCP status for reconnect", { err }) }) // kilocode_change end - Bus.publish(Event.Replied, { + await Bus.publish(s.context, Event.Replied, { sessionID: req.info.sessionID, requestID: req.info.id, }) @@ -390,7 +398,7 @@ export namespace SessionNetwork { return } s.pending.delete(requestID) - Bus.publish(Event.Rejected, { + await Bus.publish(s.context, Event.Rejected, { sessionID: req.info.sessionID, requestID: req.info.id, }) diff --git a/packages/opencode/src/session/overflow.ts b/packages/opencode/src/session/overflow.ts index e6eb566ef1c..478878b3e98 100644 --- a/packages/opencode/src/session/overflow.ts +++ b/packages/opencode/src/session/overflow.ts @@ -6,18 +6,24 @@ import { KiloSessionOverflow } from "@/kilocode/session/overflow" // kilocode_ch const COMPACTION_BUFFER = 20_000 -export function usable(input: { cfg: Config.Info; model: Provider.Model }) { +export function usable(input: { cfg: Config.Info; model: Provider.Model; outputTokenMax?: number }) { const context = input.model.limit.context if (context === 0) return 0 const reserved = - input.cfg.compaction?.reserved ?? Math.min(COMPACTION_BUFFER, ProviderTransform.maxOutputTokens(input.model)) + input.cfg.compaction?.reserved ?? + Math.min(COMPACTION_BUFFER, ProviderTransform.maxOutputTokens(input.model, input.outputTokenMax)) return input.model.limit.input ? Math.max(0, input.model.limit.input - reserved) - : Math.max(0, context - ProviderTransform.maxOutputTokens(input.model)) + : Math.max(0, context - ProviderTransform.maxOutputTokens(input.model, input.outputTokenMax)) } -export function isOverflow(input: { cfg: Config.Info; tokens: MessageV2.Assistant["tokens"]; model: Provider.Model }) { +export function isOverflow(input: { + cfg: Config.Info + tokens: MessageV2.Assistant["tokens"] + model: Provider.Model + outputTokenMax?: number +}) { if (input.cfg.compaction?.auto === false) return false if (input.model.limit.context === 0) return false diff --git a/packages/opencode/src/session/processor.ts b/packages/opencode/src/session/processor.ts index c9ed95863bc..c64aed8acd9 100644 --- a/packages/opencode/src/session/processor.ts +++ b/packages/opencode/src/session/processor.ts @@ -26,8 +26,9 @@ import { Suggestion } from "@/kilocode/suggestion" import { errorMessage } from "@/util/error" import * as Log from "@opencode-ai/core/util/log" import { isRecord } from "@/util/record" -import { SyncEvent } from "@/sync" -import { SessionEvent } from "@/v2/session-event" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { SessionEvent } from "@opencode-ai/core/session-event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import * as DateTime from "effect/DateTime" @@ -99,23 +100,7 @@ type StreamEvent = Event export class Service extends Context.Service()("@opencode/SessionProcessor") {} -export const layer: Layer.Layer< - Service, - never, - | Session.Service - | Config.Service - | Bus.Service - | Snapshot.Service - | Agent.Service - | LLM.Service - | Permission.Service - | Plugin.Service - | Image.Service - | SessionSummary.Service - | SessionStatus.Service - | SyncEvent.Service - | RuntimeFlags.Service -> = Layer.effect( +export const layer = Layer.effect( Service, Effect.gen(function* () { const session = yield* Session.Service @@ -130,7 +115,7 @@ export const layer: Layer.Layer< const scope = yield* Scope.Scope const status = yield* SessionStatus.Service const image = yield* Image.Service - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service const create = Effect.fn("SessionProcessor.create")(function* (input: Input) { @@ -289,7 +274,7 @@ export const layer: Layer.Layer< ctx.step.reasoning = true // kilocode_change // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Reasoning.Started.Sync, { + yield* events.publish(SessionEvent.Reasoning.Started, { sessionID: ctx.sessionID, reasoningID: value.id, timestamp: DateTime.makeUnsafe(Date.now()), @@ -324,7 +309,7 @@ export const layer: Layer.Layer< if (!(value.id in ctx.reasoningMap)) return // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Reasoning.Ended.Sync, { + yield* events.publish(SessionEvent.Reasoning.Ended, { sessionID: ctx.sessionID, reasoningID: value.id, text: ctx.reasoningMap[value.id].text, @@ -346,7 +331,7 @@ export const layer: Layer.Layer< ctx.step.tool = true // kilocode_change // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Tool.Input.Started.Sync, { + yield* events.publish(SessionEvent.Tool.Input.Started, { sessionID: ctx.sessionID, callID: value.id, name: value.toolName, @@ -377,7 +362,7 @@ export const layer: Layer.Layer< case "tool-input-end": { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Tool.Input.Ended.Sync, { + yield* events.publish(SessionEvent.Tool.Input.Ended, { sessionID: ctx.sessionID, callID: value.id, text: "", @@ -418,7 +403,7 @@ export const layer: Layer.Layer< const toolCall = yield* readToolCall(value.toolCallId) // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Tool.Called.Sync, { + yield* events.publish(SessionEvent.Tool.Called, { sessionID: ctx.sessionID, callID: value.toolCallId, tool: value.toolName, @@ -506,7 +491,7 @@ export const layer: Layer.Layer< } // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Tool.Success.Sync, { + yield* events.publish(SessionEvent.Tool.Success, { sessionID: ctx.sessionID, callID: value.toolCallId, structured: output.metadata, @@ -541,7 +526,7 @@ export const layer: Layer.Layer< const toolCall = yield* readToolCall(value.toolCallId) // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Tool.Failed.Sync, { + yield* events.publish(SessionEvent.Tool.Failed, { sessionID: ctx.sessionID, callID: value.toolCallId, error: { @@ -575,7 +560,7 @@ export const layer: Layer.Layer< if (!ctx.assistantMessage.summary) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Step.Started.Sync, { + yield* events.publish(SessionEvent.Step.Started, { sessionID: ctx.sessionID, agent: input.assistantMessage.agent, model: { @@ -625,7 +610,7 @@ export const layer: Layer.Layer< if (!ctx.assistantMessage.summary) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Step.Ended.Sync, { + yield* events.publish(SessionEvent.Step.Ended, { sessionID: ctx.sessionID, finish: value.finishReason, cost: usage.cost, @@ -711,7 +696,7 @@ export const layer: Layer.Layer< if (!ctx.assistantMessage.summary) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Text.Started.Sync, { + yield* events.publish(SessionEvent.Text.Started, { sessionID: ctx.sessionID, timestamp: DateTime.makeUnsafe(Date.now()), }) @@ -760,7 +745,7 @@ export const layer: Layer.Layer< if (!ctx.assistantMessage.summary) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Text.Ended.Sync, { + yield* events.publish(SessionEvent.Text.Ended, { sessionID: ctx.sessionID, text: ctx.currentText.text, timestamp: DateTime.makeUnsafe(Date.now()), @@ -869,7 +854,7 @@ export const layer: Layer.Layer< if (!ctx.assistantMessage.summary) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Step.Failed.Sync, { + yield* events.publish(SessionEvent.Step.Failed, { sessionID: ctx.sessionID, error: { type: "unknown", @@ -940,7 +925,7 @@ export const layer: Layer.Layer< set: (info) => { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. const event = flags.experimentalEventSystem - ? sync.run(SessionEvent.Retried.Sync, { + ? events.publish(SessionEvent.Retried, { sessionID: ctx.sessionID, attempt: info.attempt, error: { @@ -1002,8 +987,8 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Image.defaultLayer), Layer.provide(Bus.layer), Layer.provide(Config.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), ), ) diff --git a/packages/opencode/src/session/projectors-next.ts b/packages/opencode/src/session/projectors-next.ts index 8938a9b91d6..c1ab13859e5 100644 --- a/packages/opencode/src/session/projectors-next.ts +++ b/packages/opencode/src/session/projectors-next.ts @@ -1,10 +1,11 @@ import { and, desc, eq } from "@/storage/db" import type { Database } from "@/storage/db" -import { SessionMessage } from "@/v2/session-message" -import { SessionMessageUpdater } from "@/v2/session-message-updater" -import { SessionEvent } from "@/v2/session-event" +import { SessionMessage } from "@opencode-ai/core/session-message" +import { SessionMessageUpdater } from "@opencode-ai/core/session-message-updater" +import { SessionEvent } from "@opencode-ai/core/session-event" import * as DateTime from "effect/DateTime" import { SyncEvent } from "@/sync" +import { EventV2Bridge } from "@/event-v2-bridge" import { SessionMessageTable, SessionTable } from "./session.sql" import type { SessionID } from "./schema" import { Schema } from "effect" @@ -138,7 +139,7 @@ function update(db: Database.TxOrDb, event: SessionEvent.Event) { } export default [ - SyncEvent.project(SessionEvent.AgentSwitched.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.AgentSwitched), (db, data, event) => { db.update(SessionTable) .set({ agent: data.agent, @@ -148,7 +149,7 @@ export default [ .run() update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.agent.switched", data }) }), - SyncEvent.project(SessionEvent.ModelSwitched.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.ModelSwitched), (db, data, event) => { db.update(SessionTable) .set({ model: data.model, @@ -158,65 +159,65 @@ export default [ .run() update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.model.switched", data }) }), - SyncEvent.project(SessionEvent.Prompted.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Prompted), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.prompted", data }) }), - SyncEvent.project(SessionEvent.Synthetic.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Synthetic), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.synthetic", data }) }), - SyncEvent.project(SessionEvent.Shell.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Shell.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.shell.started", data }) }), - SyncEvent.project(SessionEvent.Shell.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Shell.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.shell.ended", data }) }), - SyncEvent.project(SessionEvent.Step.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.started", data }) }), - SyncEvent.project(SessionEvent.Step.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.ended", data }) }), - SyncEvent.project(SessionEvent.Step.Failed.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Failed), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.failed", data }) }), - SyncEvent.project(SessionEvent.Text.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.text.started", data }) }), - SyncEvent.project(SessionEvent.Text.Delta.Sync, () => {}), - SyncEvent.project(SessionEvent.Text.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Delta), () => {}), + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.text.ended", data }) }), - SyncEvent.project(SessionEvent.Tool.Input.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.input.started", data }) }), - SyncEvent.project(SessionEvent.Tool.Input.Delta.Sync, () => {}), - SyncEvent.project(SessionEvent.Tool.Input.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Delta), () => {}), + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.input.ended", data }) }), - SyncEvent.project(SessionEvent.Tool.Called.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Called), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.called", data }) }), - SyncEvent.project(SessionEvent.Tool.Success.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Success), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.success", data }) }), - SyncEvent.project(SessionEvent.Tool.Failed.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Failed), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.failed", data }) }), - SyncEvent.project(SessionEvent.Reasoning.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.reasoning.started", data }) }), - SyncEvent.project(SessionEvent.Reasoning.Delta.Sync, () => {}), - SyncEvent.project(SessionEvent.Reasoning.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Delta), () => {}), + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.reasoning.ended", data }) }), - SyncEvent.project(SessionEvent.Retried.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Retried), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.retried", data }) }), - SyncEvent.project(SessionEvent.Compaction.Started.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Started), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.compaction.started", data }) }), - SyncEvent.project(SessionEvent.Compaction.Delta.Sync, () => {}), - SyncEvent.project(SessionEvent.Compaction.Ended.Sync, (db, data, event) => { + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Delta), () => {}), + SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Ended), (db, data, event) => { update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.compaction.ended", data }) }), ] diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 67e6abc7f05..acf2280673a 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -62,9 +62,10 @@ import { InstanceState } from "@/effect/instance-state" import { TaskTool, type TaskPromptOps } from "@/tool/task" import { SessionRunState } from "./run-state" import { EffectBridge } from "@/effect/bridge" -import { SyncEvent } from "@/sync" // kilocode_change - preserve Kilo v2 event dual-write wiring import { RuntimeFlags } from "@/effect/runtime-flags" -import { SessionEvent } from "@/v2/session-event" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { SessionEvent } from "@opencode-ai/core/session-event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import { AgentAttachment, FileAttachment, ReferenceAttachment, Source } from "@opencode-ai/core/session-prompt" @@ -223,7 +224,7 @@ export const layer = Layer.effect( const sys = yield* SystemPrompt.Service const llm = yield* LLM.Service const references = yield* Reference.Service - const sync = yield* SyncEvent.Service // kilocode_change - preserve Kilo v2 event dual-write wiring + const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service const runner = Effect.fn("SessionPrompt.runner")(function* () { return yield* EffectBridge.make() @@ -1015,10 +1016,10 @@ NOTE: At any point in time through this workflow you should feel free to ask the yield* sessions.updatePart(part) // kilocode_change start - preserve Kilo v2 shell event dual-write if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Shell.Started.Sync, { + yield* events.publish(SessionEvent.Shell.Started, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(started), - callID, + callID: part.callID, command: input.command, }) } @@ -1040,7 +1041,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the const completed = Date.now() // kilocode_change start - preserve Kilo v2 shell event dual-write if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Shell.Ended.Sync, { + yield* events.publish(SessionEvent.Shell.Ended, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(completed), callID: part.callID, @@ -1194,7 +1195,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the } if (current?.agent !== info.agent) { - yield* sync.run(SessionEvent.AgentSwitched.Sync, { + yield* events.publish(SessionEvent.AgentSwitched, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(info.time.created), agent: info.agent, @@ -1205,7 +1206,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the current.model.id !== info.model.modelID || (current.model.variant === "default" ? undefined : current.model.variant) !== info.model.variant ) { - yield* sync.run(SessionEvent.ModelSwitched.Sync, { + yield* events.publish(SessionEvent.ModelSwitched, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(info.time.created), model: { @@ -1673,7 +1674,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the // kilocode_change start - preserve Kilo v2 prompt event dual-write // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Prompted.Sync, { + yield* events.publish(SessionEvent.Prompted, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(info.time.created), prompt: { @@ -1687,7 +1688,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the for (const text of nextPrompt.synthetic) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { - yield* sync.run(SessionEvent.Synthetic.Sync, { + yield* events.publish(SessionEvent.Synthetic, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(info.time.created), text, @@ -1743,7 +1744,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the input.sessionID, message.info.id, bridge.run( - loop({ sessionID: input.sessionID, snapshotInitialization: input.snapshotInitialization }).pipe(Effect.orDie), + loop({ sessionID: input.sessionID, snapshotInitialization: input.snapshotInitialization }).pipe( + Effect.orDie, + ), ), // kilocode_change bridge.run(lastAssistant(input.sessionID)), ) @@ -1771,9 +1774,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the // kilocode_change start - retain request-scoped snapshot initialization policy const runLoop: (input: LoopInput) => Effect.Effect = Effect.fn( "SessionPrompt.run", - )(function* ( - input: LoopInput, - ) { + )(function* (input: LoopInput) { const sessionID = input.sessionID // kilocode_change end // kilocode_change — cache environment details per turn (prompt caching) @@ -2160,9 +2161,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the const loop: (input: LoopInput) => Effect.Effect = Effect.fn( "SessionPrompt.loop", - )(function* ( - input: LoopInput, - ) { + )(function* (input: LoopInput) { // kilocode_change start yield* KiloSessionPrompt.recoverDanglingAssistant({ sessionID: input.sessionID, status, sessions }) yield* KiloSessionPrompt.recoverProviderFinishError({ sessionID: input.sessionID, status, sessions }) @@ -2345,7 +2344,6 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Truncate.defaultLayer), ) .pipe( - Layer.provide(Image.defaultLayer), // kilocode_change - provide user image normalization service Layer.provide(Provider.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(Instruction.defaultLayer), @@ -2354,15 +2352,16 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Session.defaultLayer), Layer.provide(SessionRevert.defaultLayer), Layer.provide(SessionSummary.defaultLayer), + Layer.provide(Image.defaultLayer), // kilocode_change - provide user image normalization service Layer.provide( Layer.mergeAll( + EventV2Bridge.defaultLayer, Agent.defaultLayer, SystemPrompt.defaultLayer, LLM.defaultLayer, Reference.defaultLayer, Bus.layer, CrossSpawnSpawner.defaultLayer, - SyncEvent.defaultLayer, // kilocode_change - provide Kilo v2 event dual-write service RuntimeFlags.defaultLayer, ), ), diff --git a/packages/opencode/src/session/prompt/default.txt b/packages/opencode/src/session/prompt/default.txt index 08216d46904..09a302b6b22 100644 --- a/packages/opencode/src/session/prompt/default.txt +++ b/packages/opencode/src/session/prompt/default.txt @@ -17,11 +17,6 @@ Only use emojis if the user explicitly requests it. Avoid using emojis in all co IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do. IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to. IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is .", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity: - -user: 2 + 2 -assistant: 4 - - user: what is 2+2? assistant: 4 @@ -43,11 +38,6 @@ assistant: [use the ls tool to list the files in the current directory, then rea npm run dev - -user: How many golf balls fit inside a jetta? -assistant: 150000 - - user: what files are in the directory src/? assistant: [runs ls and sees foo.c, bar.c, baz.c] diff --git a/packages/opencode/src/session/schema.ts b/packages/opencode/src/session/schema.ts index caf8f9d7833..f1622b6958c 100644 --- a/packages/opencode/src/session/schema.ts +++ b/packages/opencode/src/session/schema.ts @@ -1,15 +1,10 @@ import { Schema } from "effect" import { Identifier } from "@/id/id" +import { Session as CoreSession } from "@opencode-ai/core/session" import { withStatics } from "@opencode-ai/core/schema" -export const SessionID = Schema.String.check(Schema.isStartsWith("ses")).pipe( - Schema.brand("SessionID"), - withStatics((s) => ({ - descending: (id?: string) => s.make(Identifier.descending("session", id)), - })), -) - +export const SessionID = CoreSession.ID export type SessionID = Schema.Schema.Type export const MessageID = Schema.String.check(Schema.isStartsWith("msg")).pipe( diff --git a/packages/opencode/src/session/session.sql.ts b/packages/opencode/src/session/session.sql.ts index 7fb71ff39ff..6b040f3d790 100644 --- a/packages/opencode/src/session/session.sql.ts +++ b/packages/opencode/src/session/session.sql.ts @@ -1,7 +1,7 @@ import { sqliteTable, text, integer, index, primaryKey, real } from "drizzle-orm/sqlite-core" import { ProjectTable } from "../project/project.sql" import type { MessageV2 } from "./message-v2" -import type { SessionMessage } from "../v2/session-message" +import type { SessionMessage } from "@opencode-ai/core/session-message" import type { Snapshot } from "../snapshot" import type { Permission } from "../permission" import type { ProjectID } from "../project/schema" diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index e564acfd598..250162995e8 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -17,9 +17,9 @@ import { PartTable, SessionTable } from "./session.sql" import { Storage } from "@/storage/storage" import * as Log from "@opencode-ai/core/util/log" import { MessageV2 } from "./message-v2" -import type { InstanceContext } from "../project/instance" +import type { InstanceContext } from "../project/instance-context" import { InstanceState } from "@/effect/instance-state" -import { Instance } from "@/project/instance" // kilocode_change - children() uses Instance.current to scope by project_id +import { capture } from "@/kilocode/instance" // kilocode_change - children() scopes by current project when available import { Snapshot } from "@/snapshot" import { ProjectID } from "../project/schema" import { WorkspaceID } from "../control-plane/schema" @@ -608,9 +608,9 @@ export const layer: Layer.Layer< // kilocode_change start - scope by project_id when instance context is available const children = Effect.fn("Session.children")(function* (parentID: SessionID) { - const ctx = yield* Effect.try({ try: () => Instance.current, catch: () => undefined }).pipe(Effect.option) + const ctx = capture() const conditions = [eq(SessionTable.parent_id, parentID)] - if (Option.isSome(ctx)) conditions.push(eq(SessionTable.project_id, ctx.value.project.id)) + if (ctx) conditions.push(eq(SessionTable.project_id, ctx.project.id)) const rows = yield* db((d) => d .select() @@ -661,10 +661,11 @@ export const layer: Layer.Layer< const updateMessage = (msg: T): Effect.Effect => Effect.gen(function* () { // kilocode_change start - ignore FK errors when session was deleted while processor was still running - yield* KiloSession.runSyncSafe( - sync.run(MessageV2.Event.Updated, { sessionID: msg.sessionID, info: msg }), - { type: "message update", id: msg.id, sessionID: msg.sessionID }, - ) + yield* KiloSession.runSyncSafe(sync.run(MessageV2.Event.Updated, { sessionID: msg.sessionID, info: msg }), { + type: "message update", + id: msg.id, + sessionID: msg.sessionID, + }) // kilocode_change end return msg }).pipe(Effect.withSpan("Session.updateMessage")) diff --git a/packages/opencode/src/skill/index.ts b/packages/opencode/src/skill/index.ts index 62d934b2a46..198aabd5fda 100644 --- a/packages/opencode/src/skill/index.ts +++ b/packages/opencode/src/skill/index.ts @@ -5,7 +5,6 @@ import { NamedError } from "@opencode-ai/core/util/error" import type { Agent } from "@/agent/agent" import { Bus } from "@/bus" import { InstanceState } from "@/effect/instance-state" -import { Flag } from "@opencode-ai/core/flag/flag" import { Global } from "@opencode-ai/core/global" import { Permission } from "@/permission" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -171,6 +170,7 @@ const discoverSkills = Effect.fnUntraced(function* ( discovery: Discovery.Interface, fsys: AppFileSystem.Interface, global: Global.Interface, + disableExternalSkills: boolean, disableClaudeCodeSkills: boolean, directory: string, worktree: string, @@ -178,7 +178,7 @@ const discoverSkills = Effect.fnUntraced(function* ( const state: ScanState = { matches: new Set(), dirs: new Set() } const externalDirs: string[] = [] - if (!Flag.KILO_DISABLE_EXTERNAL_SKILLS) { + if (!disableExternalSkills) { if (!disableClaudeCodeSkills) externalDirs.push(CLAUDE_EXTERNAL_DIR) externalDirs.push(AGENTS_EXTERNAL_DIR) @@ -265,6 +265,7 @@ export const layer = Layer.effect( discovery, fsys, global, + flags.disableExternalSkills, flags.disableClaudeCodeSkills, ctx.directory, ctx.project.worktree, diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index bafa2a8d06c..3cdc16de6e2 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -301,7 +301,8 @@ export const layer: Layer.Layer[0]) { // kilocode_change + const track = Effect.fnUntraced(function* (opts?: Parameters[0]) { + // kilocode_change return yield* locked( Effect.gen(function* () { if (!(yield* enabled())) return diff --git a/packages/opencode/src/storage/db.ts b/packages/opencode/src/storage/db.ts index 67d1eec4fa4..2bd256bc510 100644 --- a/packages/opencode/src/storage/db.ts +++ b/packages/opencode/src/storage/db.ts @@ -11,7 +11,7 @@ import path from "path" import { readFileSync, readdirSync, existsSync } from "fs" import { Flag } from "@opencode-ai/core/flag/flag" import { InstallationChannel } from "@opencode-ai/core/installation/version" -import { InstanceState } from "@/effect/instance-state" +import { EffectBridge } from "@/effect/bridge" import { init } from "#db" import { Effect, Schema } from "effect" @@ -23,19 +23,19 @@ export const NotFoundError = NamedError.create("NotFoundError", { const log = Log.create({ service: "db" }) -type ChannelDbFlags = Pick +type DatabaseFlags = Pick const readRuntimeFlags = () => Effect.runSync(RuntimeFlags.Service.useSync((flags) => flags).pipe(Effect.provide(RuntimeFlags.defaultLayer))) -export function getChannelPath(flags: ChannelDbFlags = readRuntimeFlags()) { +export function getChannelPath(flags: Pick = readRuntimeFlags()) { if (["latest", "beta", "prod"].includes(InstallationChannel) || flags.disableChannelDb) return path.join(Global.Path.data, "kilo.db") const safe = InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-") return path.join(Global.Path.data, `opencode-${safe}.db`) } -export const getPath = (flags?: ChannelDbFlags) => { +export const getPath = (flags?: Pick) => { if (Flag.KILO_DB) { if (Flag.KILO_DB === ":memory:" || path.isAbsolute(Flag.KILO_DB)) return Flag.KILO_DB return path.join(Global.Path.data, Flag.KILO_DB) @@ -93,7 +93,7 @@ let client: Client | undefined let loaded = false export const Client = Object.assign( - (flags?: ChannelDbFlags): Client => { + (flags: DatabaseFlags = readRuntimeFlags()): Client => { if (loaded) return client as Client const dbPath = getPath(flags) @@ -118,7 +118,7 @@ export const Client = Object.assign( count: entries.length, mode: typeof KILO_MIGRATIONS !== "undefined" ? "bundled" : "dev", }) - if (Flag.KILO_SKIP_MIGRATIONS) { + if (flags.skipMigrations) { for (const item of entries) { item.sql = "select 1;" } @@ -167,7 +167,7 @@ export function use(callback: (trx: TxOrDb) => T): T { } export function effect(fn: () => any | Promise) { - const bound = InstanceState.bind(fn) + const bound = EffectBridge.bind(fn) try { ctx.use().effects.push(bound) } catch { @@ -188,7 +188,7 @@ export function transaction( } catch (err) { if (err instanceof LocalContext.NotFound) { const effects: (() => void | Promise)[] = [] - const txCallback = InstanceState.bind((tx: TxOrDb) => ctx.provide({ tx, effects }, () => callback(tx))) + const txCallback = EffectBridge.bind((tx: TxOrDb) => ctx.provide({ tx, effects }, () => callback(tx))) const result = Client().transaction(txCallback, { behavior: options?.behavior }) for (const effect of effects) effect() return result as NotPromise diff --git a/packages/opencode/src/sync/index.ts b/packages/opencode/src/sync/index.ts index 7f9b8eeef16..530c2c4112a 100644 --- a/packages/opencode/src/sync/index.ts +++ b/packages/opencode/src/sync/index.ts @@ -1,17 +1,23 @@ +// Legacy sync event system. It should stay unaware of core EventV2 execution; +// the only temporary V2 coupling here is exposing versioned core event schemas +// in effectPayloads() so existing HTTP/SDK schema generation remains stable. +// Remove that registry read when event schemas are generated from core directly. import { Database } from "@/storage/db" import { eq } from "drizzle-orm" import { GlobalBus } from "@/bus/global" import { Bus as ProjectBus } from "@/bus" import { BusEvent } from "@/bus/bus-event" -import type { InstanceContext } from "@/project/instance" +import type { InstanceContext } from "@/project/instance-context" import { EventSequenceTable, EventTable } from "./event.sql" import type { WorkspaceID } from "@/control-plane/schema" import { EventID } from "./schema" import { Context, Effect, Layer, Schema as EffectSchema } from "effect" import type { DeepMutable } from "@opencode-ai/core/schema" +import { EventV2 } from "@opencode-ai/core/event" import { serviceUse } from "@/effect/service-use" import { InstanceState } from "@/effect/instance-state" import { RuntimeFlags } from "@/effect/runtime-flags" +import { attachWith } from "@/effect/run-service" // Keep `Event["data"]` mutable because projectors mutate the persisted shape // when writing to the database. Bus payloads (`Properties`) stay readonly — @@ -70,6 +76,7 @@ export class Service extends Context.Service()("@opencode/Sy export const layer = Layer.effect(Service)( Effect.gen(function* () { const flags = yield* RuntimeFlags.Service + const bus = yield* ProjectBus.Service const replay: Interface["replay"] = Effect.fn("SyncEvent.replay")(function* (event, options) { const def = registry.get(event.type) @@ -107,6 +114,7 @@ export const layer = Layer.effect(Service)( } : undefined process(def, event, { + bus, publish, context, ownerID: options?.ownerID, @@ -167,7 +175,7 @@ export const layer = Layer.effect(Service)( const seq = row?.seq != null ? row.seq + 1 : 0 const event = { id, seq, aggregateID: agg, data } - process(def, event, { publish, context, experimentalWorkspaces: flags.experimentalWorkspaces }) + process(def, event, { bus, publish, context, experimentalWorkspaces: flags.experimentalWorkspaces }) }, { behavior: "immediate", @@ -204,12 +212,12 @@ export const layer = Layer.effect(Service)( }), ) -export const defaultLayer = layer.pipe(Layer.provide(RuntimeFlags.defaultLayer)) +export const defaultLayer = layer.pipe(Layer.provide([ProjectBus.defaultLayer, RuntimeFlags.defaultLayer])) export const use = serviceUse(Service) export const registry = new Map() -let projectors: Map | undefined +let projectors: Map | undefined const versions = new Map() let frozen = false let convertEvent: ConvertEvent @@ -221,7 +229,17 @@ export function reset() { } export function init(input: { projectors: Array<[Definition, ProjectorFunc]>; convertEvent?: ConvertEvent }) { - projectors = new Map(input.projectors) + projectors = new Map(input.projectors.map(([def, func]) => [versionedType(def.type, def.version), func])) + for (let entry of EventV2.registry.values()) { + if (!entry.version || !entry.aggregate) continue + register({ + type: entry.type, + version: entry.version, + aggregate: entry.aggregate, + properties: entry.data, + schema: entry.data, + }) + } // Install all the latest event defs to the bus. We only ever emit // latest versions from code, and keep around old versions for @@ -229,7 +247,6 @@ export function init(input: { projectors: Array<[Definition, ProjectorFunc]>; co // simplifies the bus to only use unversioned latest events for (let [type, version] of versions.entries()) { let def = registry.get(versionedType(type, version))! - BusEvent.define(def.type, def.properties) } @@ -269,9 +286,7 @@ export function define< properties: (input.busSchema ?? input.schema) as BusSchema, } - versions.set(def.type, Math.max(def.version, versions.get(def.type) || 0)) - - registry.set(versionedType(def.type, def.version), def) + register(def) return def } @@ -283,18 +298,30 @@ export function project( return [def, func as ProjectorFunc] } +function register(def: Definition) { + versions.set(def.type, Math.max(def.version, versions.get(def.type) || 0)) + registry.set(versionedType(def.type, def.version), def) +} + function process( def: Def, event: Event, - options: { publish: boolean; context?: PublishContext; ownerID?: string; experimentalWorkspaces: boolean }, + options: { + bus: ProjectBus.Interface + publish: boolean + context?: PublishContext + ownerID?: string + experimentalWorkspaces: boolean + }, ) { if (projectors == null) { throw new Error("No projectors available. Call `SyncEvent.init` to install projectors") } - const projector = projectors.get(def) + const projector = projectors.get(versionedType(def.type, def.version)) if (!projector) { - throw new Error(`Projector not found for event: ${def.type}`) + if (!def.type.includes("next")) throw new Error(`Projector not found for event: ${def.type}`) + return } Database.transaction((tx) => { @@ -330,7 +357,13 @@ function process( } const result = convertEvent(def.type, event.data) - const publish = (data: unknown) => ProjectBus.publish(def, data as Properties, { id: event.id }) + const publish = (data: unknown) => + Effect.runPromise( + attachWith(options.bus.publish(def, data as Properties, { id: event.id }), { + instance: options.context?.instance, + workspace: options.context?.workspace, + }), + ) if (result instanceof Promise) { void result.then(publish) } else { @@ -355,19 +388,38 @@ function process( } export function effectPayloads() { - return registry - .entries() - .map(([type, def]) => - EffectSchema.Struct({ - type: EffectSchema.Literal("sync"), - name: EffectSchema.Literal(type), - id: EffectSchema.String, - seq: EffectSchema.Finite, - aggregateID: EffectSchema.Literal(def.aggregate), - data: def.schema, - }).annotate({ identifier: `SyncEvent.${type}` }), - ) - .toArray() + return [ + ...registry + .entries() + .map(([type, def]) => + EffectSchema.Struct({ + type: EffectSchema.Literal("sync"), + name: EffectSchema.Literal(type), + id: EffectSchema.String, + seq: EffectSchema.Finite, + aggregateID: EffectSchema.Literal(def.aggregate), + data: def.schema, + }).annotate({ identifier: `SyncEvent.${type}` }), + ) + .toArray(), + ...EventV2.registry + .values() + .filter( + (definition) => + definition.version !== undefined && !registry.has(versionedType(definition.type, definition.version)), + ) + .map((definition) => + EffectSchema.Struct({ + type: EffectSchema.Literal("sync"), + name: EffectSchema.Literal(versionedType(definition.type, definition.version!)), + id: EffectSchema.String, + seq: EffectSchema.Finite, + aggregateID: EffectSchema.Literal(definition.aggregate!), + data: definition.data, + }).annotate({ identifier: `SyncEvent.${definition.type}` }), + ) + .toArray(), + ] } export * as SyncEvent from "." diff --git a/packages/opencode/src/tool/recall.ts b/packages/opencode/src/tool/recall.ts index 264a2ee786c..c821bb615b5 100644 --- a/packages/opencode/src/tool/recall.ts +++ b/packages/opencode/src/tool/recall.ts @@ -3,7 +3,7 @@ import { Effect, Schema } from "effect" import { EffectBridge } from "../effect/bridge" import * as Tool from "./tool" import { Git } from "../git" -import { Instance } from "../project/instance" +import { Instance } from "../kilocode/instance" import { Locale } from "../util/locale" import { Filesystem } from "../util/filesystem" // kilocode_change import { WorktreeFamily } from "../kilocode/worktree-family" // kilocode_change diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 82276296563..692f739355d 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -219,7 +219,8 @@ export const layer: Layer.Layer< // `match` is an absolute filesystem path from `Glob.scanSync(..., { absolute: true })`. // Import it as `file://` so Node on Windows accepts the dynamic import. const mod = yield* Effect.promise(() => import(pathToFileURL(match).href)) - for (const [id, def] of Object.entries(mod)) { + for (const [id, def] of Object.entries(mod)) { + if (!isPluginTool(def)) continue custom.push(fromPlugin(id === "default" ? namespace : `${namespace}_${id}`, def)) } } @@ -432,6 +433,10 @@ function isZodType(value: unknown): value is z.ZodType { return typeof value === "object" && value !== null && "_zod" in value } +function isPluginTool(value: unknown): value is ToolDefinition { + return typeof value === "object" && value !== null && "args" in value && "description" in value && "execute" in value +} + function isJsonSchemaDefinition(value: unknown): value is JSONSchema7Definition { return typeof value === "boolean" || (typeof value === "object" && value !== null && !Array.isArray(value)) } @@ -448,7 +453,7 @@ function legacyJsonSchema(entries: [string, unknown][]): JSONSchema7 { } function zodJsonSchema(schema: z.ZodType): JSONSchema7 { - const result = normalizeZodJsonSchema(z.toJSONSchema(schema, { io: "input" })) + const result = normalizeZodJsonSchema(z.toJSONSchema(schema, { io: "input", metadata: zodMetadataRegistry(schema) })) if (!isJsonSchemaObject(result)) throw new Error("plugin tool Zod schema produced a non-object JSON Schema") const { $defs, ...rest } = result return ( @@ -456,6 +461,32 @@ function zodJsonSchema(schema: z.ZodType): JSONSchema7 { ) as JSONSchema7 } +function zodMetadataRegistry(schema: z.ZodType) { + const registry = z.registry>() + const seen = new WeakSet() + const collect = (value: unknown) => { + if (typeof value !== "object" || value === null) return + if (seen.has(value)) return + seen.add(value) + + if (isZodType(value)) { + const metadata = typeof value.meta === "function" ? value.meta() : undefined + const description = typeof value.description === "string" ? value.description : undefined + const merged = { + ...(metadata && typeof metadata === "object" ? metadata : {}), + ...(description ? { description } : {}), + } + if (Object.keys(merged).length) registry.add(value, merged) + collect(value._zod.def) + return + } + + for (const item of Object.values(value)) collect(item) + } + collect(schema) + return registry +} + function normalizeZodJsonSchema(value: unknown): unknown { if (Array.isArray(value)) return value.map((item) => normalizeZodJsonSchema(item)) if (typeof value !== "object" || value === null) return value diff --git a/packages/opencode/src/tool/repo_overview.ts b/packages/opencode/src/tool/repo_overview.ts index b08516d2c60..e8fd0b81eb5 100644 --- a/packages/opencode/src/tool/repo_overview.ts +++ b/packages/opencode/src/tool/repo_overview.ts @@ -6,7 +6,7 @@ import { assertExternalDirectoryEffect } from "./external-directory" import DESCRIPTION from "./repo_overview.txt" import * as Tool from "./tool" import { parseRepositoryReference, repositoryCachePath } from "@/util/repository" -import { Instance } from "@/project/instance" +import { InstanceState } from "@/effect/instance-state" export const Parameters = Schema.Struct({ repository: Schema.optional(Schema.String).annotate({ @@ -108,7 +108,9 @@ export const RepoOverviewTool = Tool.define, ) { if (params.path) { - const full = path.isAbsolute(params.path) ? params.path : path.resolve(Instance.directory, params.path) + const full = path.isAbsolute(params.path) + ? params.path + : path.resolve(yield* InstanceState.directory, params.path) return { path: full, repository: params.repository } } diff --git a/packages/opencode/src/tool/shell.ts b/packages/opencode/src/tool/shell.ts index 527e1781a1b..a2699ce9ac2 100644 --- a/packages/opencode/src/tool/shell.ts +++ b/packages/opencode/src/tool/shell.ts @@ -644,10 +644,10 @@ export const ShellTool = Tool.define( parameters: prompt.parameters, execute: (params: Parameters, ctx: Tool.Context) => Effect.gen(function* () { - const executeInstance = yield* InstanceState.context + const instanceCtx = yield* InstanceState.context const cwd = params.workdir - ? yield* resolvePath(params.workdir, executeInstance.directory, shell) - : executeInstance.directory + ? yield* resolvePath(params.workdir, instanceCtx.directory, shell) + : instanceCtx.directory if (params.timeout !== undefined && params.timeout < 0) { throw new Error(`Invalid timeout value: ${params.timeout}. Timeout must be a positive number.`) } @@ -658,9 +658,9 @@ export const ShellTool = Tool.define( const tree = yield* Effect.acquireRelease(parse(params.command, ps), (tree) => Effect.sync(() => tree.delete()), ) - const scan = yield* collect(tree.rootNode, cwd, ps, shell, executeInstance) + const scan = yield* collect(tree.rootNode, cwd, ps, shell, instanceCtx) // kilocode_change start - if (!containsPath(cwd, executeInstance)) { + if (!containsPath(cwd, instanceCtx)) { scan.dirs.add(cwd) scan.access = "unknown" } diff --git a/packages/opencode/src/tool/shell/shell.txt b/packages/opencode/src/tool/shell/shell.txt index 5cba07805c1..22bd8f6c1ac 100644 --- a/packages/opencode/src/tool/shell/shell.txt +++ b/packages/opencode/src/tool/shell/shell.txt @@ -10,68 +10,12 @@ IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO N ${commandSection} -# Committing changes with git - -Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully: - -Git Safety Protocol: -- NEVER update the git config -- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them -- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it -- NEVER run force push to main/master, warn the user if they request it -- Avoid git commit --amend. ONLY use --amend when ALL conditions are met: - (1) User explicitly requested amend, OR the commit succeeded and pre-commit hooks auto-modified files that need including — verify by checking `git log` that HEAD is the new commit before amending - (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae') - (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead") -- CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit -- CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push) -- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive. - -1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following ${gitCommands} in parallel, each using the ${toolName} tool: - - Run a git status command to see all untracked files. - - Run a git diff command to see both staged and unstaged changes that will be committed. - - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style. -2. Analyze all staged changes (both previously staged and newly added) and draft a commit message: - - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.). - - Do not commit files that likely contain secrets (.env, credentials.json, etc.). Warn the user if they specifically request to commit those files - - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what" - - Ensure it accurately reflects the changes and their purpose -3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands: - - Add relevant untracked files to the staging area. - - Create the commit with a message - - Run git status after the commit completes to verify success. - Note: git status depends on the commit completing, so run it sequentially after the commit. -4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above) - -Important notes: -- NEVER run additional commands to read or explore code, besides ${gitCommandRestriction} -- NEVER use the TodoWrite or Task tools -- DO NOT push to the remote repository unless the user explicitly asks you to do so -- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported. -- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit - -# Creating pull requests -Use the gh command via the ${toolName} tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a GitHub URL use the gh command to get the information needed. - -IMPORTANT: When the user asks you to create a pull request, follow these steps carefully: - -1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following ${gitCommands} in parallel using the ${toolName} tool, in order to understand the current state of the branch since it diverged from the main branch: - - Run a git status command to see all untracked files - - Run a git diff command to see both staged and unstaged changes that will be committed - - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote - - Run a git log command and `git diff [base-branch]...HEAD` to understand the full commit history for the current branch (from the time it diverged from the base branch) -2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary -3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel: - - Create new branch if needed - - Push to remote with -u flag if needed - - ${createPrInstruction} - -${createPrExample} - - -Important: -- DO NOT use the TodoWrite or Task tools -- Return the PR URL when you're done, so the user can see it - -# Other common operations -- View comments on a GitHub PR: gh api repos/foo/bar/pulls/123/comments +# Git and GitHub +- Only commit, amend, push, or create PRs when explicitly requested. +- Before committing, inspect `git status`, `git diff`, and `git log --oneline -10`; stage only intended files and never commit secrets. +- Write a concise commit message that matches the repo style. +- Do not update git config, skip hooks, use interactive `-i`, force-push, or create empty commits unless explicitly requested. +- If a commit fails or hooks reject it, fix the issue and create a new commit; do not amend the failed commit. +- Before creating a PR, inspect status, diff, remote tracking, recent commits, and the diff from the base branch. +- Review all commits included in the PR, not just the latest commit. +- Use `gh` for GitHub tasks, including PRs, issues, checks, and releases; return the PR URL when done. diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index aa074dea264..a3a9a5dd937 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -30,6 +30,14 @@ export interface TaskPromptOps { } const id = "task" +const BACKGROUND_DESCRIPTION = [ + "", + "", + [ + "Background mode: background=true launches the subagent asynchronously.", + "Use task_status(task_id=..., wait=false) to poll, or wait=true to block until done.", + ].join(" "), +].join("\n") const BaseParameters = Schema.Struct({ description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }), @@ -396,9 +404,12 @@ export const TaskTool = Tool.define( const costAfter = yield* KiloCostPropagation.childCost(sessions, nextSession.id).pipe( Effect.catchTag("NotFoundError", () => Effect.succeed(costBefore)), ) - yield* KiloCostPropagation.propagate(sessions, ctx.sessionID, ctx.messageID, costAfter - costBefore).pipe( - Effect.catchTag("NotFoundError", () => Effect.void), - ) + yield* KiloCostPropagation.propagate( + sessions, + ctx.sessionID, + ctx.messageID, + costAfter - costBefore, + ).pipe(Effect.catchTag("NotFoundError", () => Effect.void)) }), ), ), @@ -407,7 +418,7 @@ export const TaskTool = Tool.define( }) return { - description: DESCRIPTION, + description: flags.experimentalBackgroundSubagents ? DESCRIPTION + BACKGROUND_DESCRIPTION : DESCRIPTION, parameters: Parameters, jsonSchema: flags.experimentalBackgroundSubagents ? undefined : ToolJsonSchema.fromSchema(BaseParameters), execute: (params: Schema.Schema.Type, ctx: Tool.Context) => diff --git a/packages/opencode/src/tool/task.txt b/packages/opencode/src/tool/task.txt index cab2374a3e2..e2ac605005b 100644 --- a/packages/opencode/src/tool/task.txt +++ b/packages/opencode/src/tool/task.txt @@ -2,57 +2,17 @@ Launch a new agent to handle complex, multistep tasks autonomously. When using the Task tool, you must specify a subagent_type parameter to select which agent type to use. -When to use the Task tool: -- When you are instructed to execute custom slash commands. Use the Task tool with the slash command invocation as the entire prompt. The slash command can take arguments. For example: Task(description="Check the file", prompt="/check-file path/to/file.py") - When NOT to use the Task tool: - If you want to read a specific file path, use the Read or Glob tool instead of the Task tool, to find the match more quickly -- If you are searching for a specific class definition like "class Foo", use the Glob tool instead, to find the match more quickly +- If you are searching for a specific class definition like "class Foo", use the Grep tool instead, to find the match more quickly - If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Task tool, to find the match more quickly -- Other tasks that are not related to the agent descriptions above +- If no available agent is a good fit for the task, use other tools directly Usage notes: 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session. -3. If OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS is enabled, background=true launches the subagent asynchronously. Use task_status(task_id=..., wait=false) to poll, or wait=true to block until done. -4. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. -5. The agent's outputs should generally be trusted -6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands). -7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. - -Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above): - - -"code-reviewer": use this agent after you are done writing a significant piece of code -"greeting-responder": use this agent when to respond to user greetings with a friendly joke - - - -user: "Please write a function that checks if a number is prime" -assistant: Sure let me write a function that checks if a number is prime -assistant: First let me use the Write tool to write a function that checks if a number is prime -assistant: I'm going to use the Write tool to write the following code: - -function isPrime(n) { - if (n <= 1) return false - for (let i = 2; i * i <= n; i++) { - if (n % i === 0) return false - } - return true -} - - -Since a significant piece of code was written and the task was completed, now use the code-reviewer agent to review the code - -assistant: Now let me use the code-reviewer agent to review the code -assistant: Uses the Task tool to launch the code-reviewer agent - - - -user: "Hello" - -Since the user is greeting, use the greeting-responder agent to respond with a friendly joke - -assistant: "I'm going to use the Task tool to launch the with the greeting-responder agent" - +3. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. +4. The agent's outputs should generally be trusted +5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands). +6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. diff --git a/packages/opencode/src/tool/todowrite.txt b/packages/opencode/src/tool/todowrite.txt index 2737cd18b62..a21630c1588 100644 --- a/packages/opencode/src/tool/todowrite.txt +++ b/packages/opencode/src/tool/todowrite.txt @@ -1,167 +1,44 @@ -Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. -It also helps the user understand the progress of the task and overall progress of their requests. +Create and maintain a structured task list for the current coding session. Tracks progress, organizes multi-step work, and surfaces status to the user. -## When to Use This Tool -Use this tool proactively in these scenarios: +## When to use +Use proactively when: +- The task requires 3+ distinct steps or actions (not just 3 tool calls for a single conceptual step) +- The work is non-trivial and benefits from planning +- The user provides multiple tasks (numbered or comma-separated) or explicitly asks for a todo list +- New instructions arrive - capture them as todos +- You start a task - mark it `in_progress` (only one at a time) before working +- You finish a task - mark it `completed` and add any follow-ups discovered during the work -1. Complex multistep tasks - When a task requires 3 or more distinct steps or actions -2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations -3. User explicitly requests todo list - When the user directly asks you to use the todo list -4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated) -5. After receiving new instructions - Immediately capture user requirements as todos. Feel free to edit the todo list based on new information. -6. After completing a task - Mark it complete and add any new follow-up tasks -7. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones. +## When NOT to use +Skip when: +- The work is a single, straightforward task (or <3 trivial steps) +- The request is purely informational or conversational +- Tracking adds no organizational value -## When NOT to Use This Tool +## States +- `pending` - not started +- `in_progress` - actively working (exactly ONE at a time) +- `completed` - finished successfully +- `cancelled` - no longer needed -Skip using this tool when: -1. There is only a single, straightforward task -2. The task is trivial and tracking it provides no organizational benefit -3. The task can be completed in less than 3 trivial steps -4. The task is purely conversational or informational +## Rules +- Update status in real time; don't batch completions +- Mark `completed` only after the required work is actually done, including any required verification. Never based on intent. +- Keep exactly one `in_progress` while work remains +- If blocked or partial, keep it `in_progress` and add a follow-up todo describing the blocker +- Preserve user-provided commands verbatim (flags, args, order) +- Items should be specific and actionable; break large work into smaller steps -NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly. +## Examples -## Examples of When to Use the Todo List +Use it: +- "Add a dark mode toggle and run the tests" -> multi-step feature + explicit verification +- "Rename getCwd -> getCurrentWorkingDirectory across the repo" -> grep reveals 15 occurrences in 8 files +- "Implement registration, catalog, cart, checkout" -> multiple complex features - -User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done! -Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation. -*Creates todo list with the following items:* -1. Create dark mode toggle component in Settings page -2. Add dark mode state management (context/store) -3. Implement CSS-in-JS styles for dark theme -4. Update existing components to support theme switching -5. Run tests and build process, addressing any failures or errors that occur -*Begins working on the first task* - - -The assistant used the todo list because: -1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes -2. The user explicitly requested tests and build be run afterward -3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task - - - - -User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project -Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'. -*Uses grep or search tools to locate all instances of getCwd in the codebase* -Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes. -*Creates todo list with specific items for each file that needs updating* - - -The assistant used the todo list because: -1. First, the assistant searched to understand the scope of the task -2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps -3. The todo list helps ensure every instance is tracked and updated systematically -4. This approach prevents missing any occurrences and maintains code consistency - - - - - -User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow. -Assistant: I'll help implement these features. First, let's add all the features to the todo list. -*Creates a todo list breaking down each feature into specific tasks based on the project architecture* -Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system. - - -The assistant used the todo list because: -1. The user provided multiple complex features to implement in a comma separated list -2. The todo list helps organize these large features into manageable tasks -3. This approach allows for tracking progress across the entire implementation - - - - -User: Can you help optimize my React application? It's rendering slowly and has performance issues. -Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks. -*Reviews component structure, render patterns, state management, and data fetching* -Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts. -*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting* -Let's start by implementing memoization for the expensive calculations in your ProductList component. - - -The assistant used the todo list because: -1. First, the assistant examined the codebase to identify specific performance issues -2. Based on this analysis, it identified multiple optimization opportunities -3. Performance optimization is a non-trivial task requiring multiple steps -4. The todo list helps methodically track improvements across different components -5. This systematic approach ensures all performance bottlenecks are addressed - - - -## Examples of When NOT to Use the Todo List - - -User: How do I print 'Hello World' in Python? -Assistant: In Python, you can print "Hello World" with this simple code: - -python -print("Hello World") - -This will output the text "Hello World" to the console when executed. - - -The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request. - - - - -User: What does the git status command do? -Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits. - - -The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks. - - - - -User: Can you add a comment to the calculateTotal function to explain what it does? -Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does. -* Uses the Edit tool to add a comment to the calculateTotal function * - - -The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization. - - - - -User: Run npm install for me and tell me what happens. -Assistant: I'll run the npm install command for you. - -*Executes: npm install* - -The command completed successfully. Here's the output: -[Output of npm install command] - -All dependencies have been installed according to your package.json file. - - -The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task. - - - -## Task States and Management - -1. **Task States**: Use these states to track progress: - - pending: Task not yet started - - in_progress: Currently working on (limit to ONE task at a time) - - completed: Task finished successfully - - cancelled: Task no longer needed - -2. **Task Management**: - - Update task status in real-time as you work - - Mark tasks complete IMMEDIATELY after finishing (don't batch completions) - - Only have ONE task in_progress at any time - - Complete current tasks before starting new ones - - Cancel tasks that become irrelevant - -3. **Task Breakdown**: - - Create specific, actionable items - - Break complex tasks into smaller, manageable steps - - Use clear, descriptive task names - -When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully. +Skip it: +- "How do I print Hello World in Python?" -> informational +- "Add a comment to calculateTotal" -> single edit +- "Run npm install and tell me what happened" -> one command +When in doubt, use it. diff --git a/packages/opencode/src/tool/warpgrep.ts b/packages/opencode/src/tool/warpgrep.ts index 16ffb474157..da29c1e093a 100644 --- a/packages/opencode/src/tool/warpgrep.ts +++ b/packages/opencode/src/tool/warpgrep.ts @@ -2,7 +2,7 @@ import { Effect, Schema } from "effect" import * as Tool from "./tool" import { WarpGrepClient } from "@morphllm/morphsdk/tools/warp-grep/client" // kilocode_change import { Telemetry } from "@kilocode/kilo-telemetry" // kilocode_change -import { Instance } from "../project/instance" +import { Instance } from "../kilocode/instance" import { Bus } from "../bus" import { TuiEvent } from "../cli/cmd/tui/event" import DESCRIPTION from "./warpgrep.txt" @@ -61,7 +61,7 @@ export const CodebaseSearchTool = Tool.define( "Codebase search unavailable: free period ended. Set MORPH_API_KEY to continue. Get your key at https://www.morphllm.com/" if (isAuthOrRateLimit) { yield* Effect.promise(() => - Bus.publish(TuiEvent.ToastShow, { + Bus.publish(Instance.current, TuiEvent.ToastShow, { title: "Codebase Search Unavailable", message: "Free period has ended. Set MORPH_API_KEY to continue. Get your key at morphllm.com", variant: "error", diff --git a/packages/opencode/src/v2/event.ts b/packages/opencode/src/v2/event.ts deleted file mode 100644 index 14ee44dd528..00000000000 --- a/packages/opencode/src/v2/event.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Identifier } from "@/id/id" -import { SyncEvent } from "@/sync" -import { withStatics } from "@opencode-ai/core/schema" -import * as Schema from "effect/Schema" - -export const ID = Schema.String.pipe( - Schema.brand("Event.ID"), - withStatics((s) => ({ - create: () => s.make(Identifier.create("evt", "ascending")), - })), -) -export type ID = Schema.Schema.Type - -export function define(input: { - type: Type - schema: Fields - aggregate: string - version?: number -}) { - const Payload = Schema.Struct({ - id: ID, - metadata: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), - type: Schema.Literal(input.type), - data: Schema.Struct(input.schema), - }).annotate({ - identifier: input.type, - }) - - const Sync = SyncEvent.define({ - type: input.type, - version: input.version ?? 1, - aggregate: input.aggregate, - schema: Payload.fields.data, - }) - - return Object.assign(Payload, { - Sync, - version: input.version, - aggregate: input.aggregate, - }) -} - -export * as EventV2 from "./event" diff --git a/packages/opencode/src/v2/session.ts b/packages/opencode/src/v2/session.ts index 97c31d39b22..a3c386f66d4 100644 --- a/packages/opencode/src/v2/session.ts +++ b/packages/opencode/src/v2/session.ts @@ -4,14 +4,14 @@ import { WorkspaceID } from "@/control-plane/schema" import { and, asc, desc, eq, gt, gte, isNull, like, lt, or, type SQL } from "@/storage/db" import * as Database from "@/storage/db" import { Context, DateTime, Effect, Layer, Option, Schema } from "effect" -import { SessionMessage } from "./session-message" +import { SessionMessage } from "@opencode-ai/core/session-message" import type { Prompt } from "@opencode-ai/core/session-prompt" -import { EventV2 } from "./event" import { ProjectID } from "@/project/schema" -import { SessionEvent } from "./session-event" +import { SessionEvent } from "@opencode-ai/core/session-event" import { V2Schema } from "@opencode-ai/core/v2-schema" import { optionalOmitUndefined } from "@opencode-ai/core/schema" -import { SyncEvent } from "@/sync" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" @@ -125,7 +125,7 @@ export class Service extends Context.Service()("@opencode/v2 export const layer = Layer.effect( Service, Effect.gen(function* () { - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service const decodeMessage = Schema.decodeUnknownSync(SessionMessage.Message) const decode = (row: typeof SessionMessageTable.$inferSelect) => @@ -292,14 +292,14 @@ export const layer = Layer.effect( shell: Effect.fn("V2Session.shell")(function* (_input) {}), skill: Effect.fn("V2Session.skill")(function* (_input) {}), switchAgent: Effect.fn("V2Session.switchAgent")(function* (input) { - yield* sync.run(SessionEvent.AgentSwitched.Sync, { + yield* events.publish(SessionEvent.AgentSwitched, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(Date.now()), agent: input.agent, }) }), switchModel: Effect.fn("V2Session.switchModel")(function* (input) { - yield* sync.run(SessionEvent.ModelSwitched.Sync, { + yield* events.publish(SessionEvent.ModelSwitched, { sessionID: input.sessionID, timestamp: DateTime.makeUnsafe(Date.now()), model: input.model, @@ -334,6 +334,6 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(SyncEvent.defaultLayer)) +export const defaultLayer = layer.pipe(Layer.provide(EventV2Bridge.defaultLayer)) export * as SessionV2 from "./session" diff --git a/packages/opencode/test/AGENTS.md b/packages/opencode/test/AGENTS.md index bff1ff5dde0..464b75cd82f 100644 --- a/packages/opencode/test/AGENTS.md +++ b/packages/opencode/test/AGENTS.md @@ -116,7 +116,7 @@ describe("my service", () => { Prefer the Effect-aware helpers from `fixture/fixture.ts` instead of building a manual runtime in each test. - `tmpdirScoped(options?)` creates a scoped temp directory and cleans it up when the Effect scope closes. -- `provideInstance(dir)(effect)` is the low-level helper. It does not create a directory; it just runs an Effect with `Instance.current` bound to `dir`. +- `provideInstance(dir)(effect)` is the low-level helper. It does not create a directory; it runs an Effect with `InstanceRef` provided for `dir`. - `provideTmpdirInstance((dir) => effect, options?)` is the convenience helper. It creates a temp directory, binds it as the active instance, and disposes the instance on cleanup. - `provideTmpdirServer((input) => effect, options?)` does the same, but also provides the test LLM server. diff --git a/packages/opencode/test/EFFECT_TEST_MIGRATION.md b/packages/opencode/test/EFFECT_TEST_MIGRATION.md index 73acea91489..893aa922b76 100644 --- a/packages/opencode/test/EFFECT_TEST_MIGRATION.md +++ b/packages/opencode/test/EFFECT_TEST_MIGRATION.md @@ -149,7 +149,7 @@ Do not maintain a long file checklist here. It goes stale quickly. When looking for the next target, search for current anti-patterns: ```bash -git grep -n "Effect.runPromise\|ManagedRuntime\|Promise.withResolvers\|Bun.sleep\|WithInstance" -- packages/opencode/test +git grep -n "Effect.runPromise\|ManagedRuntime\|Promise.withResolvers\|Bun.sleep\|withTestInstance" -- packages/opencode/test ``` Then choose one file or one small cluster, keep the PR focused, and mention diff --git a/packages/opencode/test/cli/cmd/tui/aggregate-failures.test.ts b/packages/opencode/test/cli/cmd/tui/aggregate-failures.test.ts index c9b3551d9a2..c30d719252a 100644 --- a/packages/opencode/test/cli/cmd/tui/aggregate-failures.test.ts +++ b/packages/opencode/test/cli/cmd/tui/aggregate-failures.test.ts @@ -5,6 +5,7 @@ */ import { describe, expect, test } from "bun:test" import { aggregateFailures } from "@/cli/cmd/tui/context/aggregate-failures" +import { ConfigError } from "@/config/error" describe("aggregateFailures", () => { test("returns null when every result is fulfilled", () => { @@ -41,11 +42,48 @@ describe("aggregateFailures", () => { expect(err!.message).toContain("agents: boom") }) + test("formats structured config errors hidden inside SDK error causes", () => { + const configError = new ConfigError.InvalidError({ + path: "/tmp/opencode.json", + issues: [{ message: "Expected object", path: ["provider", "anthropic", "options"] }], + }) + const err = aggregateFailures([ + { + name: "config.get", + result: { + status: "rejected", + reason: new Error("ConfigInvalidError", { + cause: { + body: configError.toObject(), + }, + }), + }, + }, + ]) + + expect(err!.message).toContain("config.get: Configuration is invalid at /tmp/opencode.json") + expect(err!.message).toContain("Expected object provider.anthropic.options") + }) + + test("deduplicates identical failure messages across startup requests", () => { + const reason = new Error("same config problem") + const err = aggregateFailures([ + { name: "config.providers", result: { status: "rejected", reason } }, + { name: "provider.list", result: { status: "rejected", reason } }, + { name: "app.agents", result: { status: "rejected", reason } }, + { name: "config.get", result: { status: "rejected", reason } }, + { name: "project.sync", result: { status: "fulfilled", value: undefined } }, + ]) + + expect(err!.message).toContain("4 of 5 requests failed: same config problem") + expect(err!.message).toContain("Affected startup requests: config.providers, provider.list, app.agents, config.get") + expect(err!.message.match(/same config problem/g)?.length).toBe(1) + }) + test("attaches structured failure list under .cause", () => { const reason = new Error("nope") const err = aggregateFailures([{ name: "providers", result: { status: "rejected", reason } }]) - const cause = err!.cause as { failures: Array<{ name: string; reason: unknown }> } - expect(cause.failures).toEqual([{ name: "providers", reason }]) + expect(err!.cause).toEqual({ failures: [{ name: "providers", reason }] }) }) test("falls back to String() for opaque reasons", () => { diff --git a/packages/opencode/test/cli/cmd/tui/prompt-history.test.ts b/packages/opencode/test/cli/cmd/tui/prompt-history.test.ts new file mode 100644 index 00000000000..f92b34d905a --- /dev/null +++ b/packages/opencode/test/cli/cmd/tui/prompt-history.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, test } from "bun:test" +import { isDuplicateEntry, type PromptInfo } from "../../../../src/cli/cmd/tui/component/prompt/history" + +const entry = (input: string, parts: PromptInfo["parts"] = []): PromptInfo => ({ input, parts }) + +describe("prompt history dedupe", () => { + test("returns false when there is no previous entry", () => { + expect(isDuplicateEntry(undefined, entry("hello"))).toBe(false) + }) + + test("dedupes identical consecutive entries", () => { + const a = entry("hello world this is over twenty chars") + const b = entry("hello world this is over twenty chars") + expect(isDuplicateEntry(a, b)).toBe(true) + }) + + test("does not dedupe when input text differs", () => { + expect(isDuplicateEntry(entry("foo"), entry("bar"))).toBe(false) + }) + + test("does not dedupe when parts differ", () => { + const a = entry("describe this", [ + { + type: "file", + mime: "image/png", + filename: "a.png", + url: "data:image/png;base64,AAA", + }, + ]) + const b = entry("describe this", [ + { + type: "file", + mime: "image/png", + filename: "b.png", + url: "data:image/png;base64,BBB", + }, + ]) + expect(isDuplicateEntry(a, b)).toBe(false) + }) + + test("does not dedupe when mode differs", () => { + expect(isDuplicateEntry({ ...entry("ls"), mode: "normal" }, { ...entry("ls"), mode: "shell" })).toBe(false) + }) +}) diff --git a/packages/opencode/test/cli/cmd/tui/sync-undefined-messages.test.tsx b/packages/opencode/test/cli/cmd/tui/sync-undefined-messages.test.tsx index 108afc162fa..2ee43cb03fb 100644 --- a/packages/opencode/test/cli/cmd/tui/sync-undefined-messages.test.tsx +++ b/packages/opencode/test/cli/cmd/tui/sync-undefined-messages.test.tsx @@ -8,8 +8,7 @@ */ import { describe, expect, test } from "bun:test" import { Global } from "@opencode-ai/core/global" -import { WithInstance } from "../../../../src/project/with-instance" // kilocode_change -import { disposeAllInstances, tmpdir } from "../../../fixture/fixture" +import { disposeAllInstances, provideTestInstance, tmpdir } from "../../../fixture/fixture" import { directory, json, mount } from "./sync-fixture" const sessionID = "ses_undef" @@ -29,7 +28,7 @@ describe("tui sync (#26560)", () => { directory, project_id: "proj_test", } - const { app, sync } = await WithInstance.provide({ + const { app, sync } = await provideTestInstance({ directory: tmp.path, fn: () => mount((url) => { diff --git a/packages/opencode/test/cli/cmd/tui/sync.test.tsx b/packages/opencode/test/cli/cmd/tui/sync.test.tsx index 72d11db08f6..1c8b3d36f5e 100644 --- a/packages/opencode/test/cli/cmd/tui/sync.test.tsx +++ b/packages/opencode/test/cli/cmd/tui/sync.test.tsx @@ -1,8 +1,7 @@ /** @jsxImportSource @opentui/solid */ import { describe, expect, test } from "bun:test" import { Global } from "@opencode-ai/core/global" -import { WithInstance } from "../../../../src/project/with-instance" // kilocode_change -import { disposeAllInstances, tmpdir } from "../../../fixture/fixture" +import { disposeAllInstances, provideTestInstance, tmpdir } from "../../../fixture/fixture" import { mount, wait } from "./sync-fixture" import type { GlobalEvent } from "@kilocode/sdk/v2" @@ -25,7 +24,7 @@ describe("tui sync", () => { await using tmp = await tmpdir() Global.Path.state = tmp.path await Bun.write(`${tmp.path}/kv.json`, "{}") - const { app, kv, sync, session } = await WithInstance.provide({ directory: tmp.path, fn: mount }) // kilocode_change + const { app, kv, sync, session } = await provideTestInstance({ directory: tmp.path, fn: () => mount() }) // kilocode_change try { expect(kv.get("session_directory_filter_enabled", true)).toBe(true) diff --git a/packages/opencode/test/cli/effect-cmd-instance-als.test.ts b/packages/opencode/test/cli/effect-cmd-instance-als.test.ts index 122b87f1742..c8ed9722e78 100644 --- a/packages/opencode/test/cli/effect-cmd-instance-als.test.ts +++ b/packages/opencode/test/cli/effect-cmd-instance-als.test.ts @@ -3,7 +3,6 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Effect } from "effect" import { fileURLToPath } from "url" import { InstanceRef } from "../../src/effect/instance-ref" -import { Instance } from "../../src/project/instance" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" @@ -13,46 +12,28 @@ afterEach(async () => { await disposeAllInstances() }) -// Regression for PR #25522: when an effectCmd handler does -// `yield* Effect.promise(async () => { ... await runPromise(svcMethod) ... })`, -// the inner runPromise creates a fresh fiber after `await` whose Effect context -// has lost the outer InstanceRef. Services that read `InstanceState.context` -// then fall back to `Instance.current` ALS, which must be installed at the JS -// callback boundary (Node ALS persists across awaits, Effect's fiber context -// does not). `it.instance` provides the loaded InstanceRef; the explicit -// Instance.restore mirrors effectCmd's load + ALS-restore wrap. -// Pins effect-cmd.ts directly: the pattern test below exercises the load + -// Instance.restore boundary via the shared `it.instance` fixture, -// so a regression that removed `Instance.restore` from effect-cmd.ts wouldn't -// fail it. This grep guards the actual production callsite. -it.live("effect-cmd.ts wraps the handler body in Instance.restore", () => +it.live("effect-cmd.ts does not restore legacy instance ALS", () => Effect.gen(function* () { const fs = yield* AppFileSystem.Service const source = yield* fs.readFileString(fileURLToPath(new URL("../../src/cli/effect-cmd.ts", import.meta.url))) - expect(source).toContain("Instance.restore(ctx") + expect(source).not.toContain("restore(ctx") }), ) it.instance( - "Instance.current reachable after await inside restored Effect.promise(async)", + "InstanceRef remains the handler context across Effect promise awaits", () => Effect.gen(function* () { const test = yield* TestInstance const ctx = yield* InstanceRef if (!ctx) throw new Error("InstanceRef not provided") - const current = yield* Effect.promise(() => - Instance.restore(ctx, async () => { - await Promise.resolve() - try { - return Instance.current - } catch { - return undefined - } - }), - ) + const directory = yield* Effect.promise(async () => { + await Promise.resolve() + return ctx.directory + }) - expect(current?.directory).toBe(test.directory) + expect(directory).toBe(test.directory) }), { git: true }, ) diff --git a/packages/opencode/test/cli/install-artifact.test.ts b/packages/opencode/test/cli/install-artifact.test.ts index c15a1a9e3de..933ce0f7c55 100644 --- a/packages/opencode/test/cli/install-artifact.test.ts +++ b/packages/opencode/test/cli/install-artifact.test.ts @@ -35,18 +35,27 @@ describe("npm install artifact behavior", () => { await fs.mkdir(path.join(bin, "tree-sitter"), { recursive: true }) await fs.mkdir(path.join(bin, "console", "assets"), { recursive: true }) await fs.copyFile(postinstall, path.join(pkg, "postinstall.mjs")) + await Bun.write( + path.join(pkg, "package.json"), + JSON.stringify({ + optionalDependencies: { + [`@kilocode/cli-${process.platform}-${process.arch}`]: "1.0.0", + }, + }), + ) await Bun.write( path.join(native, "package.json"), JSON.stringify({ name: `@kilocode/cli-${process.platform}-${process.arch}` }), ) - await Bun.write(path.join(bin, "kilo"), "binary") + const binary = "#!/bin/sh\n# binary\nexit 0\n" + await Bun.write(path.join(bin, "kilo"), binary) await Bun.write(path.join(bin, "tree-sitter", "tree-sitter.wasm"), "wasm") await Bun.write(path.join(bin, "console", "index.html"), "console") await Bun.write(path.join(bin, "console", "assets", "app.js"), "asset") const proc = Bun.spawn([node, path.join(pkg, "postinstall.mjs")], { cwd: pkg }) expect(await proc.exited).toBe(0) - expect(await Bun.file(path.join(pkg, "bin", ".kilo")).text()).toBe("binary") + expect(await Bun.file(path.join(pkg, "bin", ".kilo")).text()).toBe(binary) expect(await Bun.file(path.join(pkg, "bin", "tree-sitter", "tree-sitter.wasm")).text()).toBe("wasm") expect(await Bun.file(path.join(pkg, "bin", "console", "index.html")).text()).toBe("console") expect(await Bun.file(path.join(pkg, "bin", "console", "assets", "app.js")).text()).toBe("asset") diff --git a/packages/opencode/test/cli/run/prompt.shared.test.ts b/packages/opencode/test/cli/run/prompt.shared.test.ts index 299751eaa34..35b35ec3e7a 100644 --- a/packages/opencode/test/cli/run/prompt.shared.test.ts +++ b/packages/opencode/test/cli/run/prompt.shared.test.ts @@ -126,6 +126,12 @@ describe("run prompt shared", () => { expect(mentionTriggerIndex("👨‍👩‍👧‍👦 @src", Bun.stringWidth("👨‍👩‍👧‍👦 @src"))).toBe(3) expect(displayCharAt("👨‍👩‍👧‍👦 @src", Bun.stringWidth("👨‍👩‍👧‍👦 @"))).toBe("s") expect(displaySlice("👨‍👩‍👧‍👦 @src", 3, Bun.stringWidth("👨‍👩‍👧‍👦 @src"))).toBe("@src") + expect(mentionTriggerIndex("@file1\n@file2", 13)).toBe(7) + expect(displayCharAt("@file1\n@file2", 6)).toBe("\n") + expect(displaySlice("@file1\n@file2", 8, 13)).toBe("file2") + expect(mentionTriggerIndex("@file1\nfoo @file2", 17)).toBe(11) + expect(mentionTriggerIndex("中文 @one\n@two", 14)).toBe(10) + expect(displaySlice("中文 @one\n@two", 11, 14)).toBe("two") expect(mentionTriggerIndex("中文@")).toBeUndefined() expect(mentionTriggerIndex("こんにちは@")).toBeUndefined() expect(mentionTriggerIndex("한국어@")).toBeUndefined() diff --git a/packages/opencode/test/cli/run/stream.transport.test.ts b/packages/opencode/test/cli/run/stream.transport.test.ts index 1934261374d..309222d0f86 100644 --- a/packages/opencode/test/cli/run/stream.transport.test.ts +++ b/packages/opencode/test/cli/run/stream.transport.test.ts @@ -762,9 +762,7 @@ describe("run stream transport", () => { transport.selectSubagent("child-1") - global.push( - globalEvent(assistant("msg-child-1", "child-1")), - ) + global.push(globalEvent(assistant("msg-child-1", "child-1"))) global.push(globalEvent(textUpdated(textPart("txt-child-1", "msg-child-1", "hello", "child-1")))) expect( diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 746423f7bf6..0a6e0713ff7 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -6,14 +6,14 @@ import { ConfigManaged } from "@/config/managed" import { ConfigParse } from "../../src/config/parse" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { InstanceRef } from "../../src/effect/instance-ref" +import type { InstanceContext } from "../../src/project/instance-context" import { Auth } from "../../src/auth" import { Account } from "../../src/account/account" import { AccessToken, AccountID, OrgID } from "../../src/account/schema" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Env } from "../../src/env" -import { provideTestInstance, provideTmpdirInstance } from "../fixture/fixture" +import { provideTestInstance, provideTmpdirInstance, withTestInstance } from "../fixture/fixture" import { tmpdir } from "../fixture/fixture" import { InstanceRuntime } from "@/project/instance-runtime" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" @@ -61,9 +61,20 @@ const layer = Config.layer.pipe( const it = testEffect(layer) -const load = () => Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(layer))) -const save = (config: Config.Info) => - Effect.runPromise(Config.Service.use((svc) => svc.update(config)).pipe(Effect.scoped, Effect.provide(layer))) +const provideCurrentInstance = (effect: Effect.Effect, ctx: InstanceContext) => + effect.pipe(Effect.provideService(InstanceRef, ctx)) + +const load = (ctx: InstanceContext) => + Effect.runPromise( + Config.Service.use((svc) => provideCurrentInstance(svc.get(), ctx)).pipe(Effect.scoped, Effect.provide(layer)), + ) +const save = (config: Config.Info, ctx: InstanceContext) => + Effect.runPromise( + Config.Service.use((svc) => provideCurrentInstance(svc.update(config), ctx)).pipe( + Effect.scoped, + Effect.provide(layer), + ), + ) const saveGlobal = (config: Config.Info) => Effect.runPromise( Config.Service.use((svc) => svc.updateGlobal(config)).pipe( @@ -76,14 +87,26 @@ const clear = async (wait = false) => { await Effect.runPromise(Config.Service.use((svc) => svc.invalidate()).pipe(Effect.scoped, Effect.provide(layer))) if (wait) await InstanceRuntime.disposeAllInstances() } -const listDirs = () => - Effect.runPromise(Config.Service.use((svc) => svc.directories()).pipe(Effect.scoped, Effect.provide(layer))) +const listDirs = (ctx: InstanceContext) => + Effect.runPromise( + Config.Service.use((svc) => provideCurrentInstance(svc.directories(), ctx)).pipe( + Effect.scoped, + Effect.provide(layer), + ), + ) // kilocode_change start -const warnings = () => - Effect.runPromise(Config.Service.use((svc) => svc.warnings()).pipe(Effect.scoped, Effect.provide(layer))) +const warnings = (ctx: InstanceContext) => + Effect.runPromise( + Config.Service.use((svc) => provideCurrentInstance(svc.warnings(), ctx)).pipe(Effect.scoped, Effect.provide(layer)), + ) // kilocode_change end -const ready = () => - Effect.runPromise(Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(layer))) +const ready = (ctx: InstanceContext) => + Effect.runPromise( + Config.Service.use((svc) => provideCurrentInstance(svc.waitForDependencies(), ctx)).pipe( + Effect.scoped, + Effect.provide(layer), + ), + ) // Get managed config directory from environment (set in preload.ts) const managedConfigDir = process.env.KILO_TEST_MANAGED_CONFIG_DIR! @@ -118,13 +141,13 @@ async function check(map: (dir: string) => string) { $schema: "https://opencode.ai/config.json", snapshot: false, }) - await WithInstance.provide({ + await withTestInstance({ directory: map(tmp.path), - fn: async () => { - const cfg = await load() + fn: async (ctx) => { + const cfg = await load(ctx) expect(cfg.snapshot).toBe(true) - expect(Instance.directory).toBe(Filesystem.resolve(tmp.path)) - expect(Instance.project.id).not.toBe(ProjectID.global) + expect(ctx.directory).toBe(Filesystem.resolve(tmp.path)) + expect(ctx.project.id).not.toBe(ProjectID.global) }, }) } finally { @@ -136,10 +159,10 @@ async function check(map: (dir: string) => string) { test("loads config with defaults when no files exist", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBeDefined() }, }) @@ -152,10 +175,10 @@ test("creates global jsonc config with schema when no global configs exist", asy await clear(true) try { - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - await load() + fn: async (ctx) => { + await load(ctx) }, }) @@ -177,10 +200,10 @@ test("does not create global config when KILO_CONFIG_DIR is set", async () => { await clear(true) try { - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - await load() + fn: async (ctx) => { + await load(ctx) }, }) @@ -204,10 +227,10 @@ test("loads JSON config file", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("test/model") expect(config.username).toBe("testuser") }, @@ -236,10 +259,10 @@ test("preserves Kilo provider free model metadata", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const model = config.provider?.kilo?.models?.["free-e2e"] expect(model?.isFree).toBe(true) expect(model?.ai_sdk_provider).toBe("openai-compatible") @@ -257,10 +280,10 @@ test("loads shell config field", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.shell).toBe("bash") }, }) @@ -276,10 +299,10 @@ test("updates config and preserves empty shell sentinel", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - await save({ shell: "" }) + fn: async (ctx) => { + await save({ shell: "" }, ctx) const writtenConfig = await Filesystem.readJson<{ shell?: string }>(path.join(tmp.path, "kilo.json")) expect(writtenConfig.shell).toBe("") @@ -355,10 +378,10 @@ test("loads formatter boolean config", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.formatter).toBe(true) }, }) @@ -373,10 +396,10 @@ test("loads lsp boolean config", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.lsp).toBe(true) }, }) @@ -410,10 +433,10 @@ test("ignores legacy tui keys in opencode config", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("test/model") expect((config as Record).theme).toBeUndefined() expect((config as Record).tui).toBeUndefined() @@ -435,10 +458,10 @@ test("loads JSONC config file", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("test/model") expect(config.username).toBe("testuser") }, @@ -463,10 +486,10 @@ test("jsonc overrides json in the same directory", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("base") expect(config.username).toBe("base") }, @@ -494,10 +517,10 @@ test("prefers .kilo directory config over legacy .kilocode", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("new/model") }, }) @@ -517,10 +540,10 @@ test("handles environment variable substitution", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("test-user") }, }) @@ -549,10 +572,10 @@ test("preserves env variables when adding $schema to config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("secret_value") // Read the file to verify the env variable was preserved @@ -646,10 +669,10 @@ test("handles file inclusion substitution", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("test-user") }, }) @@ -665,10 +688,10 @@ test("handles file inclusion with replacement tokens", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("const out = await Bun.$`echo hi`") }, }) @@ -686,10 +709,10 @@ test("validates config schema and reports warning on invalid fields", async () = }) await provideTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { // invalid schema surfaces as warnings, not a throw - await load() - const issues = await warnings() + await load(ctx) + const issues = await warnings(ctx) expect(issues.length).toBeGreaterThan(0) }, }) @@ -705,10 +728,10 @@ test("reports warning for invalid JSON", async () => { }) await provideTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { // invalid JSON surfaces as a warning, not a throw - await load() - const issues = await warnings() + await load(ctx) + const issues = await warnings(ctx) expect(issues.length).toBeGreaterThan(0) }, }) @@ -730,10 +753,10 @@ test("handles agent configuration", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test_agent"]).toEqual( expect.objectContaining({ model: "test/model", @@ -761,10 +784,10 @@ test("treats agent variant as model-scoped setting (not provider option)", async }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const agent = config.agent?.["test_agent"] expect(agent?.variant).toBe("xhigh") @@ -791,10 +814,10 @@ test("handles command configuration", async () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.command?.["test_command"]).toEqual({ template: "test template", description: "test command", @@ -816,10 +839,10 @@ test("migrates autoshare to share field", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.share).toBe("auto") expect(config.autoshare).toBe(true) }, @@ -843,10 +866,10 @@ test("migrates mode field to agent field", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test_mode"]).toEqual({ model: "test/model", temperature: 0.5, @@ -875,10 +898,10 @@ Test agent prompt`, ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]).toEqual( expect.objectContaining({ name: "test", @@ -908,10 +931,10 @@ Ordered permissions`, ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(Object.keys(config.agent?.ordered?.permission ?? {})).toEqual(["bash", "*", "edit"]) }, }) @@ -946,10 +969,10 @@ Nested agent prompt`, }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["helper"]).toMatchObject({ name: "helper", @@ -995,10 +1018,10 @@ Nested command template`, }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.command?.["hello"]).toEqual({ description: "Test command", @@ -1040,10 +1063,10 @@ Nested command template`, }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.command?.["hello"]).toEqual({ description: "Test command", @@ -1079,10 +1102,10 @@ Hello from new command`, }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.command?.["hello"]).toEqual({ description: "New command", @@ -1095,10 +1118,10 @@ Hello from new command`, test("gets config directories", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const dirs = await listDirs() + fn: async (ctx) => { + const dirs = await listDirs(ctx) expect(dirs.length).toBeGreaterThanOrEqual(1) }, }) @@ -1125,10 +1148,10 @@ test("does not try to install dependencies in read-only KILO_CONFIG_DIR", async process.env.KILO_CONFIG_DIR = tmp.extra try { - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - await load() + fn: async (ctx) => { + await load(ctx) }, }) } finally { @@ -1160,12 +1183,20 @@ test("installs dependencies in writable KILO_CONFIG_DIR", async () => { ) try { - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - await Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(testLayer))) + fn: async (ctx) => { await Effect.runPromise( - Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(testLayer)), + Config.Service.use((svc) => svc.get().pipe(Effect.provideService(InstanceRef, ctx))).pipe( + Effect.scoped, + Effect.provide(testLayer), + ), + ) + await Effect.runPromise( + Config.Service.use((svc) => svc.waitForDependencies().pipe(Effect.provideService(InstanceRef, ctx))).pipe( + Effect.scoped, + Effect.provide(testLayer), + ), ) }, }) @@ -1221,8 +1252,8 @@ test("resolves scoped npm plugins in config", async () => { await provideTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const pluginEntries = config.plugin ?? [] expect(pluginEntries).toContain("@scope/plugin") }, @@ -1259,8 +1290,8 @@ test("merges plugin arrays from global and local configs", async () => { await provideTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const plugins = config.plugin ?? [] // Should contain both global and local plugins @@ -1293,10 +1324,10 @@ Helper subagent prompt`, ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["helper"]).toMatchObject({ name: "helper", model: "test/model", @@ -1332,10 +1363,10 @@ test("merges instructions arrays from global and local configs", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const instructions = config.instructions ?? [] expect(instructions).toContain("global-instructions.md") @@ -1371,10 +1402,10 @@ test("deduplicates duplicate instructions from global and local configs", async }, }) - await WithInstance.provide({ + await withTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const instructions = config.instructions ?? [] expect(instructions).toContain("global-only.md") @@ -1418,8 +1449,8 @@ test("deduplicates duplicate plugins from global and local configs", async () => await provideTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const plugins = config.plugin ?? [] // Should contain all unique plugins @@ -1467,8 +1498,8 @@ test("keeps plugin origins aligned with merged plugin list", async () => { await provideTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const cfg = await load() + fn: async (ctx) => { + const cfg = await load(ctx) const plugins = cfg.plugin ?? [] const origins = cfg.plugin_origins ?? [] const names = plugins.map((item) => ConfigPlugin.pluginSpecifier(item)) @@ -1506,10 +1537,10 @@ test("migrates legacy tools config to permissions - allow", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ bash: "allow", read: "allow", @@ -1537,10 +1568,10 @@ test("migrates legacy tools config to permissions - deny", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ bash: "deny", webfetch: "deny", @@ -1567,10 +1598,10 @@ test("migrates legacy write tool to edit permission", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ edit: "allow", }) @@ -1599,10 +1630,10 @@ test("managed settings override user settings", async () => { share: "disabled", }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("managed/model") expect(config.share).toBe("disabled") expect(config.username).toBe("testuser") @@ -1627,10 +1658,10 @@ test("managed settings override project settings", async () => { disabled_providers: ["openai"], }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.autoupdate).toBe(false) expect(config.disabled_providers).toEqual(["openai"]) }, @@ -1647,10 +1678,10 @@ test("missing managed settings file is not an error", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.model).toBe("user/model") }, }) @@ -1674,10 +1705,10 @@ test("migrates legacy edit tool to edit permission", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ edit: "deny", }) @@ -1703,10 +1734,10 @@ test("migrates legacy patch tool to edit permission", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ edit: "allow", }) @@ -1735,10 +1766,10 @@ test("migrates mixed legacy tools config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ bash: "allow", edit: "allow", @@ -1770,10 +1801,10 @@ test("merges legacy tools with existing permission config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.agent?.["test"]?.permission).toEqual({ glob: "allow", bash: "allow", @@ -1823,10 +1854,10 @@ test("permission config preserves user key order", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(Object.keys(config.permission!)).toEqual([ "*", "edit", @@ -1894,10 +1925,10 @@ test("local mcp accepts `env` as an alias for `environment`", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.mcp?.context7).toEqual({ type: "local", command: ["npx", "-y", "@upstash/context7-mcp"], @@ -1927,10 +1958,10 @@ test("local mcp prefers `environment` over `env` when both are present", async ( ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.mcp?.context7).toEqual({ type: "local", command: ["npx", "-y", "@upstash/context7-mcp"], @@ -1981,10 +2012,10 @@ test("project config can override MCP server enabled status", async () => { // kilocode_change end }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) // jira should be enabled (overridden by project config) expect(config.mcp?.jira).toEqual({ type: "remote", @@ -2039,10 +2070,10 @@ test("MCP config deep merges preserving base config properties", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.mcp?.myserver).toEqual({ type: "remote", url: "https://myserver.example.com/mcp", @@ -2090,10 +2121,10 @@ test("local .kilo config can override MCP from project config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.mcp?.docs?.enabled).toBe(true) }, }) @@ -2426,8 +2457,8 @@ describe("deduplicatePluginOrigins", () => { await provideTestInstance({ directory: path.join(tmp.path, "project"), - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) const plugins = config.plugin ?? [] expect(plugins.some((p) => ConfigPlugin.pluginSpecifier(p) === "my-plugin@1.0.0")).toBe(true) @@ -2456,10 +2487,10 @@ describe("KILO_DISABLE_PROJECT_CONFIG", () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) // Project config should NOT be loaded - model should be default, not "project/model" expect(config.model).not.toBe("project/model") expect(config.username).not.toBe("project-user") @@ -2488,10 +2519,10 @@ describe("KILO_DISABLE_PROJECT_CONFIG", () => { await Filesystem.write(path.join(opencodeDir, "test-cmd.md"), "# Test Command\nThis is a test command.") }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const directories = await listDirs() + fn: async (ctx) => { + const directories = await listDirs(ctx) // Project .kilo should NOT be in directories list // kilocode_change const hasProjectOpencode = directories.some((d) => d.startsWith(tmp.path)) expect(hasProjectOpencode).toBe(false) @@ -2512,11 +2543,11 @@ describe("KILO_DISABLE_PROJECT_CONFIG", () => { try { await using tmp = await tmpdir() - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { // Should still get default config (from global or defaults) - const config = await load() + const config = await load(ctx) expect(config).toBeDefined() expect(config.username).toBeDefined() }, @@ -2554,12 +2585,12 @@ describe("KILO_DISABLE_PROJECT_CONFIG", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { // The relative instruction should be skipped without error // We're mainly verifying this doesn't throw and the config loads - const config = await load() + const config = await load(ctx) expect(config).toBeDefined() // The instruction should have been skipped (warning logged) // We can't easily test the warning was logged, but we verify @@ -2614,10 +2645,10 @@ describe("KILO_DISABLE_PROJECT_CONFIG", () => { process.env["KILO_DISABLE_PROJECT_CONFIG"] = "true" process.env["KILO_CONFIG_DIR"] = configDirTmp.path - await WithInstance.provide({ + await withTestInstance({ directory: projectTmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) // Should load from KILO_CONFIG_DIR, not project expect(config.model).toBe("configdir/model") }, @@ -2649,10 +2680,10 @@ describe("KILO_CONFIG_CONTENT token substitution", () => { try { await using tmp = await tmpdir() - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("test_api_key_12345") }, }) @@ -2683,10 +2714,10 @@ describe("KILO_CONFIG_CONTENT token substitution", () => { }) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const config = await load() + fn: async (ctx) => { + const config = await load(ctx) expect(config.username).toBe("secret_key_from_file") }, }) diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index 8b6f3ce8bc4..bc8225581cf 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -14,8 +14,7 @@ import { GlobalBus, type GlobalEvent } from "@/bus/global" import { Database } from "@/storage/db" import { ProjectID } from "@/project/schema" import { ProjectTable } from "@/project/project.sql" -import { Instance } from "@/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { context, type InstanceContext } from "@/project/instance-context" import { InstanceRef } from "@/effect/instance-ref" import { Session as SessionNs } from "@/session/session" import { SessionID } from "@/session/schema" @@ -122,12 +121,10 @@ afterEach(async () => { await resetDatabase() }) -async function withInstance(fn: (dir: string) => T | Promise) { +async function withInstance(fn: (ctx: InstanceContext) => T | Promise) { await using tmp = await tmpdir({ git: true }) - return await WithInstance.provide({ - directory: tmp.path, - fn: () => fn(tmp.path), - }) + const ctx = await AppRuntime.runPromise(InstanceStore.Service.use((store) => store.load({ directory: tmp.path }))) + return await context.provide(ctx, () => fn(ctx)) } async function initGitRepo(dir: string) { @@ -142,7 +139,18 @@ async function initGitRepo(dir: string) { await $`git commit -m "base"`.cwd(dir).quiet() } -const runWorkspace = (effect: Effect.Effect) => AppRuntime.runPromise(effect) +function currentInstance() { + try { + return context.use() + } catch { + return undefined + } +} + +const runWorkspace = (effect: Effect.Effect) => { + const ctx = currentInstance() + return AppRuntime.runPromise(ctx ? effect.pipe(Effect.provideService(InstanceRef, ctx)) : effect) +} const createWorkspace = (input: Workspace.CreateInput) => runWorkspace(Workspace.Service.use((workspace) => workspace.create(input))) const warpWorkspaceSession = (input: Workspace.SessionWarpInput) => @@ -416,16 +424,16 @@ describe("workspace CRUD", () => { }) test("list maps database rows, filters by project, and sorts by id", async () => { - await withInstance(async () => { + await withInstance(async (instance) => { const otherProjectID = ProjectID.make("project-other") insertProject(otherProjectID, "/tmp/other") - const a = workspaceInfo(Instance.project.id, "manual", { + const a = workspaceInfo(instance.project.id, "manual", { id: WorkspaceID.ascending("wrk_a_list"), branch: "a", directory: "/a", extra: { a: true }, }) - const b = workspaceInfo(Instance.project.id, "manual", { + const b = workspaceInfo(instance.project.id, "manual", { id: WorkspaceID.ascending("wrk_b_list"), branch: "b", directory: "/b", @@ -436,12 +444,12 @@ describe("workspace CRUD", () => { insertWorkspace(other) insertWorkspace(a) - expect(await listWorkspaces(Instance.project)).toEqual([a, b]) + expect(await listWorkspaces(instance.project)).toEqual([a, b]) }) }) test("create configures, persists, creates, starts local sync, and passes environment", async () => { - await withInstance(async (dir) => { + await withInstance(async (instance) => { process.env.KILO_AUTH_CONTENT = JSON.stringify({ test: { type: "api", key: "secret" } }) process.env.OTEL_EXPORTER_OTLP_HEADERS = "authorization=otel" process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://otel.test" @@ -449,7 +457,7 @@ describe("workspace CRUD", () => { const workspaceID = WorkspaceID.ascending("wrk_create_local") const type = unique("create-local") - const targetDir = path.join(dir, "created-local") + const targetDir = path.join(instance.directory, "created-local") const recorded = recordedAdapter({ configure(info) { return { @@ -467,13 +475,13 @@ describe("workspace CRUD", () => { return { type: "local", directory: targetDir } }, }) - registerAdapter(Instance.project.id, type, recorded.adapter) + registerAdapter(instance.project.id, type, recorded.adapter) const info = await createWorkspace({ id: workspaceID, type, branch: null, - projectID: Instance.project.id, + projectID: instance.project.id, extra: null, }) @@ -484,11 +492,11 @@ describe("workspace CRUD", () => { name: "Configured Name", directory: targetDir, extra: { configured: true }, - projectID: Instance.project.id, + projectID: instance.project.id, timeUsed: info.timeUsed, }) expect(await getWorkspace(workspaceID)).toEqual(info) - expect(await listWorkspaces(Instance.project)).toEqual([info]) + expect(await listWorkspaces(instance.project)).toEqual([info]) expect(recorded.calls.configure).toHaveLength(1) expect(recorded.calls.configure[0]).toMatchObject({ id: workspaceID, type, directory: null }) expect(recorded.calls.create).toHaveLength(1) @@ -499,7 +507,7 @@ describe("workspace CRUD", () => { name: "Configured Name", directory: targetDir, extra: { configured: true }, - projectID: Instance.project.id, + projectID: instance.project.id, }) expect(JSON.parse(recorded.calls.create[0].env.KILO_AUTH_CONTENT ?? "{}")).toEqual({ test: { type: "api", key: "secret" }, @@ -517,10 +525,10 @@ describe("workspace CRUD", () => { }) test("create propagates configure failures and does not insert a workspace", async () => { - await withInstance(async () => { + await withInstance(async (instance) => { const type = unique("configure-failure") registerAdapter( - Instance.project.id, + instance.project.id, type, recordedAdapter({ configure() { @@ -533,14 +541,14 @@ describe("workspace CRUD", () => { ) await expect( - createWorkspace({ type, branch: null, projectID: Instance.project.id, extra: null }), + createWorkspace({ type, branch: null, projectID: instance.project.id, extra: null }), ).rejects.toThrow("configure exploded") - expect(await listWorkspaces(Instance.project)).toEqual([]) + expect(await listWorkspaces(instance.project)).toEqual([]) }) }) test("create leaves the inserted row when adapter create fails", async () => { - await withInstance(async () => { + await withInstance(async (instance) => { const type = unique("create-failure") const recorded = recordedAdapter({ async create() { @@ -550,13 +558,13 @@ describe("workspace CRUD", () => { return { type: "local", directory: "/unused" } }, }) - registerAdapter(Instance.project.id, type, recorded.adapter) + registerAdapter(instance.project.id, type, recorded.adapter) await expect( - createWorkspace({ type, branch: "branch", projectID: Instance.project.id, extra: { x: 1 } }), + createWorkspace({ type, branch: "branch", projectID: instance.project.id, extra: { x: 1 } }), ).rejects.toThrow("create exploded") - const rows = await listWorkspaces(Instance.project) + const rows = await listWorkspaces(instance.project) expect(rows).toHaveLength(1) expect(rows[0]).toMatchObject({ type, branch: "branch", extra: { x: 1 } }) expect(recorded.calls.target).toHaveLength(0) @@ -565,13 +573,13 @@ describe("workspace CRUD", () => { }) test("create returns after a local workspace reports error", async () => { - await withInstance(async (dir) => { + await withInstance(async (instance) => { const type = unique("local-error") - const missing = path.join(dir, "missing-local-target") + const missing = path.join(instance.directory, "missing-local-target") const recorded = localAdapter(missing, { createDir: false }) - registerAdapter(Instance.project.id, type, recorded.adapter) + registerAdapter(instance.project.id, type, recorded.adapter) - const info = await createWorkspace({ type, branch: null, projectID: Instance.project.id, extra: null }) + const info = await createWorkspace({ type, branch: null, projectID: instance.project.id, extra: null }) expect(info.directory).toBe(missing) expect((await workspaceStatus()).find((item) => item.workspaceID === info.id)?.status).toBe("error") @@ -580,12 +588,12 @@ describe("workspace CRUD", () => { }) test("syncList registers adapter-listed workspaces that are missing by name", async () => { - await withInstance(async (dir) => { + await withInstance(async (instance) => { const type = unique("list-sync") - const existing = workspaceInfo(Instance.project.id, type, { + const existing = workspaceInfo(instance.project.id, type, { id: WorkspaceID.ascending("wrk_list_sync_existing"), name: "existing", - directory: path.join(dir, "existing"), + directory: path.join(instance.directory, "existing"), }) insertWorkspace(existing) @@ -593,9 +601,9 @@ describe("workspace CRUD", () => { type, name: "discovered", branch: "feature/discovered", - directory: path.join(dir, "discovered"), + directory: path.join(instance.directory, "discovered"), extra: { source: "adapter" }, - projectID: Instance.project.id, + projectID: instance.project.id, } const recorded = recordedAdapter({ list() { @@ -604,26 +612,26 @@ describe("workspace CRUD", () => { type, name: existing.name, branch: "ignored", - directory: path.join(dir, "ignored"), + directory: path.join(instance.directory, "ignored"), extra: null, - projectID: Instance.project.id, + projectID: instance.project.id, }, discovered, ] }, target(info) { - return { type: "local", directory: info.directory ?? dir } + return { type: "local", directory: info.directory ?? instance.directory } }, }) - registerAdapter(Instance.project.id, type, recorded.adapter) + registerAdapter(instance.project.id, type, recorded.adapter) - await syncListWorkspaces(Instance.project) - const synced = (await listWorkspaces(Instance.project)).filter((item) => item.name === discovered.name) + await syncListWorkspaces(instance.project) + const synced = (await listWorkspaces(instance.project)).filter((item) => item.name === discovered.name) expect(synced).toHaveLength(1) expect(synced[0]).toMatchObject(discovered) expect(synced[0]?.id).toStartWith("wrk_") - expect(await listWorkspaces(Instance.project)).toEqual(expect.arrayContaining([existing, synced[0]])) + expect(await listWorkspaces(instance.project)).toEqual(expect.arrayContaining([existing, synced[0]])) expect(recorded.calls.list).toBe(1) expect(recorded.calls.configure).toHaveLength(0) expect(recorded.calls.create).toHaveLength(0) @@ -632,7 +640,7 @@ describe("workspace CRUD", () => { }) test("syncList calls every registered adapter with a list method", async () => { - await withInstance(async (dir) => { + await withInstance(async (instance) => { const typeA = unique("list-sync-a") const typeB = unique("list-sync-b") const adapterA = recordedAdapter({ @@ -642,14 +650,14 @@ describe("workspace CRUD", () => { type: typeA, name: "adapter-a", branch: null, - directory: path.join(dir, "adapter-a"), + directory: path.join(instance.directory, "adapter-a"), extra: null, - projectID: Instance.project.id, + projectID: instance.project.id, }, ] }, target(info) { - return { type: "local", directory: info.directory ?? dir } + return { type: "local", directory: info.directory ?? instance.directory } }, }) const adapterB = recordedAdapter({ @@ -659,27 +667,27 @@ describe("workspace CRUD", () => { type: typeB, name: "adapter-b", branch: null, - directory: path.join(dir, "adapter-b"), + directory: path.join(instance.directory, "adapter-b"), extra: null, - projectID: Instance.project.id, + projectID: instance.project.id, }, ] }, target(info) { - return { type: "local", directory: info.directory ?? dir } + return { type: "local", directory: info.directory ?? instance.directory } }, }) const noList = recordedAdapter({ target() { - return { type: "local", directory: dir } + return { type: "local", directory: instance.directory } }, }) - registerAdapter(Instance.project.id, typeA, adapterA.adapter) - registerAdapter(Instance.project.id, typeB, adapterB.adapter) - registerAdapter(Instance.project.id, unique("list-sync-none"), noList.adapter) + registerAdapter(instance.project.id, typeA, adapterA.adapter) + registerAdapter(instance.project.id, typeB, adapterB.adapter) + registerAdapter(instance.project.id, unique("list-sync-none"), noList.adapter) - await syncListWorkspaces(Instance.project) - const synced = await listWorkspaces(Instance.project) + await syncListWorkspaces(instance.project) + const synced = await listWorkspaces(instance.project) expect( synced @@ -719,11 +727,13 @@ describe("workspace CRUD", () => { (dir) => Effect.gen(function* () { const workspace = yield* Workspace.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const type = unique("remote-create") const recorded = remoteAdapter(`${url}/base/?ignored=1#hash`, { directory: dir }) - registerAdapter(Instance.project.id, type, recorded.adapter) + registerAdapter(instance.project.id, type, recorded.adapter) - const info = yield* workspace.create({ type, branch: null, projectID: Instance.project.id, extra: null }) + const info = yield* workspace.create({ type, branch: null, projectID: instance.project.id, extra: null }) expect( calls.map((call) => `${call.method} ${call.url.pathname}${call.url.search}${call.url.hash}`), @@ -782,11 +792,11 @@ describe("workspace CRUD", () => { ) test("remove still deletes the row when the adapter cannot remove resources", async () => { - await withInstance(async () => { + await withInstance(async (instance) => { const type = unique("remove-throws") - const info = workspaceInfo(Instance.project.id, type, { id: WorkspaceID.ascending("wrk_remove_throws") }) + const info = workspaceInfo(instance.project.id, type, { id: WorkspaceID.ascending("wrk_remove_throws") }) registerAdapter( - Instance.project.id, + instance.project.id, type, recordedAdapter({ async remove() { @@ -911,24 +921,26 @@ describe("workspace CRUD", () => { ) test("sessionWarp detaches to the source project when invoked from a workspace instance", async () => { - await withInstance(async () => { - const projectID = Instance.project.id + await withInstance(async (instance) => { + const projectID = instance.project.id await using workspaceTmp = await tmpdir({ git: true }) const previousType = unique("warp-detach-workspace-instance") const previous = workspaceInfo(projectID, previousType) insertWorkspace(previous) registerAdapter(projectID, previousType, localAdapter(workspaceTmp.path, { createDir: false }).adapter) - const session = await AppRuntime.runPromise(SessionNs.Service.use((svc) => svc.create({}))) + const session = await AppRuntime.runPromise( + SessionNs.Service.use((svc) => svc.create({})).pipe(Effect.provideService(InstanceRef, instance)), + ) attachSessionToWorkspace(session.id, previous.id) - const workspaceProjectID = await WithInstance.provide({ - directory: workspaceTmp.path, - fn: async () => { - const id = Instance.project.id - expect(id).not.toBe(projectID) - await warpWorkspaceSession({ workspaceID: null, sessionID: session.id }) - return id - }, + const workspaceCtx = await AppRuntime.runPromise( + InstanceStore.Service.use((store) => store.load({ directory: workspaceTmp.path })), + ) + const workspaceProjectID = await context.provide(workspaceCtx, async () => { + const id = workspaceCtx.project.id + expect(id).not.toBe(projectID) + await warpWorkspaceSession({ workspaceID: null, sessionID: session.id }) + return id }) expect( @@ -988,14 +1000,16 @@ describe("workspace CRUD", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const previousType = unique("warp-remote-source") const targetType = unique("warp-remote-target") - const previous = workspaceInfo(Instance.project.id, previousType) - const target = workspaceInfo(Instance.project.id, targetType, { directory: "remote-target-dir" }) + const previous = workspaceInfo(instance.project.id, previousType) + const target = workspaceInfo(instance.project.id, targetType, { directory: "remote-target-dir" }) insertWorkspace(previous) insertWorkspace(target) - registerAdapter(Instance.project.id, previousType, remoteAdapter(`${url}/warp-source`).adapter) - registerAdapter(Instance.project.id, targetType, remoteAdapter(`${url}/warp-target`).adapter) + registerAdapter(instance.project.id, previousType, remoteAdapter(`${url}/warp-source`).adapter) + registerAdapter(instance.project.id, targetType, remoteAdapter(`${url}/warp-target`).adapter) const session = yield* sessionSvc.create({}) attachSessionToWorkspace(session.id, previous.id) historySessionID = session.id @@ -1197,15 +1211,17 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const captured = captureGlobalEvents() try { const type = unique("remote-start") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/sync`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sync`).adapter) attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.gen(function* () { expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe( @@ -1213,7 +1229,7 @@ describe("workspace sync state", () => { ) }), ) - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* Effect.sleep("25 millis") expect( @@ -1252,13 +1268,15 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const type = unique("remote-connect-fail") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/failed`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/failed`).adapter) attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.gen(function* () { @@ -1292,13 +1310,15 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const type = unique("remote-history-fail") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/history-failed`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/history-failed`).adapter) attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.gen(function* () { @@ -1347,18 +1367,20 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const captured = captureGlobalEvents() try { const type = unique("history-replay") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/history`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/history`).adapter) const session = yield* sessionSvc.create({ title: "before history" }) attachSessionToWorkspace(session.id, info.id) historySessionID = session.id historyNextSeq = (sessionSequence(session.id) ?? -1) + 1 - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.gen(function* () { @@ -1414,15 +1436,17 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const captured = captureGlobalEvents() try { const type = unique("sse-forward") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/sse-forward`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sse-forward`).adapter) attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.sync(() => @@ -1495,18 +1519,20 @@ describe("workspace sync state", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionSvc = yield* SessionNs.Service + const instance = yield* InstanceRef + if (!instance) return yield* Effect.die(new Error("missing test instance")) const captured = captureGlobalEvents() try { const type = unique("sse-sync") - const info = workspaceInfo(Instance.project.id, type) + const info = workspaceInfo(instance.project.id, type) insertWorkspace(info) - registerAdapter(Instance.project.id, type, remoteAdapter(`${url}/sse-sync`).adapter) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sse-sync`).adapter) const session = yield* sessionSvc.create({ title: "before sse" }) attachSessionToWorkspace(session.id, info.id) sseSessionID = session.id sseNextSeq = (sessionSequence(session.id) ?? -1) + 1 - yield* workspace.startWorkspaceSyncing(Instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( Effect.gen(function* () { diff --git a/packages/opencode/test/effect/instance-state.test.ts b/packages/opencode/test/effect/instance-state.test.ts index b928f16bc6a..d983de89a85 100644 --- a/packages/opencode/test/effect/instance-state.test.ts +++ b/packages/opencode/test/effect/instance-state.test.ts @@ -1,16 +1,21 @@ -import { afterEach, expect } from "bun:test" +import { expect } from "bun:test" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { $ } from "bun" import { Context, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect" import { InstanceState } from "@/effect/instance-state" -import { Instance } from "../../src/project/instance" -import { disposeAllInstances, provideInstance, reloadTestInstance, tmpdirScoped } from "../fixture/fixture" +import { + disposeAllInstancesEffect, + provideInstanceEffect, + reloadInstance, + testInstanceStoreLayer, + tmpdirScoped, +} from "../fixture/fixture" import { testEffect } from "../lib/effect" -const it = testEffect(CrossSpawnSpawner.defaultLayer) +const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, testInstanceStoreLayer)) const access = (state: InstanceState.InstanceState, dir: string) => - InstanceState.get(state).pipe(provideInstance(dir)) + InstanceState.get(state).pipe(provideInstanceEffect(dir)) const tmpdirGitScoped = Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) @@ -18,10 +23,6 @@ const tmpdirGitScoped = Effect.gen(function* () { return dir }) -afterEach(async () => { - await disposeAllInstances() -}) - it.live("InstanceState caches values per directory", () => Effect.gen(function* () { const dir = yield* tmpdirScoped() @@ -69,7 +70,7 @@ it.live("InstanceState invalidates on reload", () => ) const a = yield* access(state, dir) - yield* Effect.promise(() => reloadTestInstance({ directory: dir })) + yield* reloadInstance({ directory: dir }) const b = yield* access(state, dir) expect(a).not.toBe(b) @@ -94,7 +95,7 @@ it.live("InstanceState invalidates on disposeAll", () => yield* access(state, one) yield* access(state, two) - yield* Effect.promise(disposeAllInstances) + yield* disposeAllInstancesEffect expect(seen.sort()).toEqual([one, two].sort()) }), @@ -126,8 +127,8 @@ it.live("InstanceState.get reads the current directory lazily", () => } yield* Effect.gen(function* () { - const a = yield* Test.use((svc) => svc.get()).pipe(provideInstance(one)) - const b = yield* Test.use((svc) => svc.get()).pipe(provideInstance(two)) + const a = yield* Test.use((svc) => svc.get()).pipe(provideInstanceEffect(one)) + const b = yield* Test.use((svc) => svc.get()).pipe(provideInstanceEffect(two)) expect(a).toBe(one) expect(b).toBe(two) @@ -178,7 +179,7 @@ it.live("InstanceState preserves directory across async boundaries", () => yield* Effect.gen(function* () { const [a, b, c] = yield* Effect.all( - [one, two, three].map((dir) => Test.use((svc) => svc.get()).pipe(provideInstance(dir))), + [one, two, three].map((dir) => Test.use((svc) => svc.get()).pipe(provideInstanceEffect(dir))), { concurrency: "unbounded" }, ) @@ -225,7 +226,7 @@ it.live("InstanceState survives high-contention concurrent access", () => yield* Effect.gen(function* () { const results = yield* Effect.all( - dirs.map((dir) => Test.use((svc) => svc.get()).pipe(provideInstance(dir))), + dirs.map((dir) => Test.use((svc) => svc.get()).pipe(provideInstanceEffect(dir))), { concurrency: "unbounded" }, ) @@ -264,19 +265,16 @@ it.live("InstanceState correct after interleaved init and dispose", () => } yield* Effect.gen(function* () { - const a = yield* Test.use((svc) => svc.get()).pipe(provideInstance(one)) + const a = yield* Test.use((svc) => svc.get()).pipe(provideInstanceEffect(one)) expect(a).toBe(one) const [, b] = yield* Effect.all( - [ - Effect.promise(() => reloadTestInstance({ directory: one })), - Test.use((svc) => svc.get()).pipe(provideInstance(two)), - ], + [reloadInstance({ directory: one }), Test.use((svc) => svc.get()).pipe(provideInstanceEffect(two))], { concurrency: "unbounded" }, ) expect(b).toBe(two) - const c = yield* Test.use((svc) => svc.get()).pipe(provideInstance(one)) + const c = yield* Test.use((svc) => svc.get()).pipe(provideInstanceEffect(one)) expect(c).toBe(one) }).pipe(Effect.provide(Test.layer)) }), @@ -344,9 +342,9 @@ it.live("InstanceState survives deferred resume from the same instance context", yield* Effect.gen(function* () { const gate = yield* Deferred.make() - const fiber = yield* Test.use((svc) => svc.get(gate)).pipe(provideInstance(dir), Effect.forkScoped) + const fiber = yield* Test.use((svc) => svc.get(gate)).pipe(provideInstanceEffect(dir), Effect.forkScoped) - yield* Deferred.succeed(gate, undefined).pipe(provideInstance(dir)) + yield* Deferred.succeed(gate, undefined).pipe(provideInstanceEffect(dir)) const exit = yield* Fiber.await(fiber) expect(Exit.isSuccess(exit)).toBe(true) @@ -381,7 +379,7 @@ it.live("InstanceState survives deferred resume outside ALS when InstanceRef is yield* Effect.gen(function* () { const gate = yield* Deferred.make() - const fiber = yield* Test.use((svc) => svc.get(gate)).pipe(provideInstance(dir), Effect.forkScoped) + const fiber = yield* Test.use((svc) => svc.get(gate)).pipe(provideInstanceEffect(dir), Effect.forkScoped) yield* Deferred.succeed(gate, undefined) const exit = yield* Fiber.await(fiber) diff --git a/packages/opencode/test/effect/runtime-flags.test.ts b/packages/opencode/test/effect/runtime-flags.test.ts index 1744ffb3411..712e78752de 100644 --- a/packages/opencode/test/effect/runtime-flags.test.ts +++ b/packages/opencode/test/effect/runtime-flags.test.ts @@ -27,6 +27,9 @@ describe("RuntimeFlags", () => { KILO_DISABLE_CHANNEL_DB: "true", KILO_AUTO_SHARE: "true", KILO_DISABLE_EMBEDDED_WEB_UI: "true", + KILO_DISABLE_EXTERNAL_SKILLS: "true", + KILO_DISABLE_LSP_DOWNLOAD: "true", + KILO_SKIP_MIGRATIONS: "true", KILO_EXPERIMENTAL: "true", KILO_ENABLE_EXA: "true", KILO_ENABLE_PARALLEL: "true", @@ -42,6 +45,10 @@ describe("RuntimeFlags", () => { expect(flags.disableDefaultPlugins).toBe(true) expect(flags.disableChannelDb).toBe(true) expect(flags.disableEmbeddedWebUi).toBe(true) + expect(flags.disableExternalSkills).toBe(true) + expect(flags.disableLspDownload).toBe(true) + expect(flags.skipMigrations).toBe(true) + expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.enableExa).toBe(true) expect(flags.enableParallel).toBe(true) expect(flags.enableExperimentalModels).toBe(true) @@ -84,10 +91,15 @@ describe("RuntimeFlags", () => { expect(flags.disableDefaultPlugins).toBe(true) expect(flags.disableChannelDb).toBe(false) expect(flags.disableEmbeddedWebUi).toBe(false) + expect(flags.disableExternalSkills).toBe(false) + expect(flags.disableLspDownload).toBe(false) + expect(flags.skipMigrations).toBe(false) + expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.disableClaudeCodeSkills).toBe(false) expect(flags.enableExa).toBe(false) expect(flags.experimentalIconDiscovery).toBe(false) expect(flags.experimentalOxfmt).toBe(false) + expect(flags.outputTokenMax).toBeUndefined() expect(flags.bashDefaultTimeoutMs).toBe(1_000) expect(flags.enableExperimentalModels).toBe(false) expect(flags.client).toBe("cli") @@ -102,6 +114,78 @@ describe("RuntimeFlags", () => { }), ) + it.effect("disableExternalSkills defaults to false", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) + + expect(flags.disableExternalSkills).toBe(false) + }), + ) + + it.effect("disableExternalSkills reads KILO_DISABLE_EXTERNAL_SKILLS", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_DISABLE_EXTERNAL_SKILLS: "true" }))) + + expect(flags.disableExternalSkills).toBe(true) + }), + ) + + it.effect("disableLspDownload defaults to false", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) + + expect(flags.disableLspDownload).toBe(false) + }), + ) + + it.effect("disableLspDownload reads KILO_DISABLE_LSP_DOWNLOAD", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_DISABLE_LSP_DOWNLOAD: "true" }))) + + expect(flags.disableLspDownload).toBe(true) + }), + ) + + it.effect("skipMigrations defaults to false", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) + + expect(flags.skipMigrations).toBe(false) + }), + ) + + it.effect("skipMigrations reads KILO_SKIP_MIGRATIONS", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_SKIP_MIGRATIONS: "true" }))) + + expect(flags.skipMigrations).toBe(true) + }), + ) + + it.effect("disableClaudeCodePrompt defaults to false", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) + + expect(flags.disableClaudeCodePrompt).toBe(false) + }), + ) + + it.effect("disableClaudeCodePrompt reads KILO_DISABLE_CLAUDE_CODE_PROMPT", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_DISABLE_CLAUDE_CODE_PROMPT: "true" }))) + + expect(flags.disableClaudeCodePrompt).toBe(true) + }), + ) + + it.effect("disableClaudeCodePrompt inherits KILO_DISABLE_CLAUDE_CODE", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_DISABLE_CLAUDE_CODE: "true" }))) + + expect(flags.disableClaudeCodePrompt).toBe(true) + }), + ) + it.effect("experimentalIconDiscovery reads KILO_EXPERIMENTAL_ICON_DISCOVERY", () => Effect.gen(function* () { const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ KILO_EXPERIMENTAL_ICON_DISCOVERY: "true" }))) @@ -183,6 +267,35 @@ describe("RuntimeFlags", () => { ) } + for (const input of [ + { name: "absent", config: {}, expected: undefined }, + { + name: "valid positive integer", + config: { KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX: "1234" }, + expected: 1234, + }, + { + name: "invalid string", + config: { KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX: "nope" }, + expected: undefined, + }, + { name: "zero", config: { KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX: "0" }, expected: undefined }, + { name: "negative", config: { KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX: "-1" }, expected: undefined }, + { + name: "non-integer", + config: { KILO_EXPERIMENTAL_OUTPUT_TOKEN_MAX: "1.5" }, + expected: undefined, + }, + ]) { + it.effect(`parses outputTokenMax from config: ${input.name}`, () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe(Effect.provide(fromConfig(input.config))) + + expect(flags.outputTokenMax).toBe(input.expected) + }), + ) + } + it.effect("layer ignores the active ConfigProvider for omitted test overrides", () => Effect.gen(function* () { const flags = yield* readFlags.pipe( @@ -192,6 +305,9 @@ describe("RuntimeFlags", () => { ConfigProvider.fromUnknown({ KILO_PURE: "true", KILO_DISABLE_DEFAULT_PLUGINS: "true", + KILO_DISABLE_EXTERNAL_SKILLS: "true", + KILO_DISABLE_LSP_DOWNLOAD: "true", + KILO_SKIP_MIGRATIONS: "true", KILO_EXPERIMENTAL: "true", KILO_ENABLE_EXA: "true", KILO_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS: "1234", @@ -205,10 +321,15 @@ describe("RuntimeFlags", () => { expect(flags.disableDefaultPlugins).toBe(false) expect(flags.disableChannelDb).toBe(false) expect(flags.disableEmbeddedWebUi).toBe(false) + expect(flags.disableExternalSkills).toBe(false) + expect(flags.disableLspDownload).toBe(false) + expect(flags.skipMigrations).toBe(false) + expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.disableClaudeCodeSkills).toBe(false) expect(flags.enableExa).toBe(false) expect(flags.experimentalIconDiscovery).toBe(false) expect(flags.experimentalOxfmt).toBe(false) + expect(flags.outputTokenMax).toBeUndefined() expect(flags.bashDefaultTimeoutMs).toBeUndefined() expect(flags.client).toBe("cli") }), diff --git a/packages/opencode/test/file/watcher.test.ts b/packages/opencode/test/file/watcher.test.ts index f5495218b43..8a812fcd0dd 100644 --- a/packages/opencode/test/file/watcher.test.ts +++ b/packages/opencode/test/file/watcher.test.ts @@ -1,5 +1,6 @@ import { describe, expect } from "bun:test" import path from "path" +import { realpath } from "fs/promises" // kilocode_change - accept canonical paths from symlinked git directories import { AppFileSystem } from "@opencode-ai/core/filesystem" import { ConfigProvider, Deferred, Effect, Layer, Option } from "effect" import { TestInstance, provideInstance } from "../fixture/fixture" @@ -133,11 +134,12 @@ function ready(directory: string) { if (!(yield* fs.existsSafe(head))) return + const realHead = yield* Effect.promise(() => realpath(head).catch(() => head)) // kilocode_change const branch = `watch-${Math.random().toString(36).slice(2)}` const hash = (yield* git.run(["rev-parse", "HEAD"], { cwd: directory })).text() yield* nextUpdate( directory, - (evt) => evt.file === head && evt.event !== "unlink", + (evt) => (evt.file === head || evt.file === realHead) && evt.event !== "unlink", // kilocode_change fs .writeFileString(path.join(directory, ".git", "refs", "heads", branch), hash.trim() + "\n") .pipe(Effect.andThen(fs.writeFileString(head, `ref: refs/heads/${branch}\n`))), @@ -260,4 +262,58 @@ describeWatcher("FileWatcher", () => { }), { git: true }, ) + + // Symlink support varies by platform; skip where unavailable + const describeSymlink = process.platform !== "win32" ? describe : describe.skip + + describeSymlink("symlinked .git", () => { + it.instance( + "publishes .git/HEAD events through a symlinked .git directory", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const fs = yield* AppFileSystem.Service + const git = yield* Git.Service + const dir = test.directory + const actualGit = path.join(dir, "..", "tmp_actual_git_" + Math.random().toString(36).slice(2)) + + // Move .git to a sibling directory and replace with a symlink + yield* Effect.promise(() => import("fs")).pipe( + Effect.flatMap((nodeFs) => + Effect.all([ + Effect.promise(() => nodeFs.promises.rename(path.join(dir, ".git"), actualGit)), + Effect.promise(() => nodeFs.promises.symlink(actualGit, path.join(dir, ".git"))), + ]), + ), + ) + + yield* Effect.acquireRelease(Effect.succeed(actualGit), (p) => + Effect.promise(() => + import("fs").then((f) => f.promises.rm(p, { recursive: true, force: true }).catch(() => undefined)), + ), + ) + + const head = path.join(dir, ".git", "HEAD") + const branch = `watch-${Math.random().toString(36).slice(2)}` + yield* git.run(["branch", branch], { cwd: dir }) + + yield* withWatcher( + dir, + nextUpdate( + dir, + (evt) => evt.file === path.join(actualGit, "HEAD") && evt.event !== "unlink", + fs.writeFileString(head, `ref: refs/heads/${branch}\n`), + ).pipe( + Effect.tap((evt) => + Effect.sync(() => { + expect(evt.file).toBe(path.join(actualGit, "HEAD")) + expect(["add", "change"]).toContain(evt.event) + }), + ), + ), + ) + }), + { git: true }, + ) + }) }) diff --git a/packages/opencode/test/fixture/fixture.ts b/packages/opencode/test/fixture/fixture.ts index 1075061df42..eab11973297 100644 --- a/packages/opencode/test/fixture/fixture.ts +++ b/packages/opencode/test/fixture/fixture.ts @@ -11,30 +11,40 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" import type { Config } from "@/config/config" import { InstanceRef } from "../../src/effect/instance-ref" import { InstanceBootstrap } from "../../src/project/bootstrap-service" +import { context as instanceContext, type InstanceContext } from "../../src/project/instance-context" import { InstanceRuntime } from "../../src/project/instance-runtime" import { InstanceStore } from "../../src/project/instance-store" -import { Instance } from "../../src/project/instance" import { TestLLMServer } from "../lib/llm-server" import { remove as cleanup } from "../kilocode/cleanup" // kilocode_change const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void })) -const testInstanceRuntime = ManagedRuntime.make( - InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap), Layer.provideMerge(Observability.layer)), -) +export const testInstanceStoreLayer = InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap)) +const testInstanceRuntime = ManagedRuntime.make(testInstanceStoreLayer.pipe(Layer.provideMerge(Observability.layer))) const runTestInstanceStore = (fn: (store: InstanceStore.Interface) => Effect.Effect) => testInstanceRuntime.runPromise(InstanceStore.Service.use(fn)) -export async function provideTestInstance(input: { directory: string; init?: Effect.Effect; fn: () => R }) { +export async function provideTestInstance(input: { + directory: string + init?: Effect.Effect + fn: (ctx: InstanceContext) => R +}) { const ctx = await runTestInstanceStore((store) => store.load({ directory: input.directory })) try { if (input.init) await testInstanceRuntime.runPromise(input.init.pipe(Effect.provideService(InstanceRef, ctx))) - return await Instance.restore(ctx, () => input.fn()) + return await instanceContext.provide(ctx, () => input.fn(ctx)) } finally { - await runTestInstanceStore((store) => store.dispose(ctx)) + await instanceContext.provide(ctx, () => + runTestInstanceStore((store) => store.dispose(ctx).pipe(Effect.provideService(InstanceRef, ctx))), + ) } } +export async function withTestInstance(input: { directory: string; fn: (ctx: InstanceContext) => R }) { + const ctx = await runTestInstanceStore((store) => store.load({ directory: input.directory })) + return instanceContext.provide(ctx, () => input.fn(ctx)) +} + export async function reloadTestInstance(input: { directory: string }) { return runTestInstanceStore((store) => store.reload(input)) } @@ -153,12 +163,20 @@ export const provideInstance = Effect.contextWith((services: Context.Context) => Effect.promise(async () => { const ctx = await runTestInstanceStore((store) => store.load({ directory })) - return Instance.restore(ctx, () => - Effect.runPromiseWith(services)(self.pipe(Effect.provideService(InstanceRef, ctx))), - ) + return Effect.runPromiseWith(services)(self.pipe(Effect.provideService(InstanceRef, ctx))) }), ) +export const provideInstanceEffect = + (directory: string) => + (self: Effect.Effect): Effect.Effect => + InstanceStore.Service.use((store) => store.provide({ directory }, self)) + +export const reloadInstance = (input: InstanceStore.LoadInput) => + InstanceStore.Service.use((store) => store.reload(input)) + +export const disposeAllInstancesEffect = InstanceStore.Service.use((store) => store.disposeAll()) + export function provideTmpdirInstance( self: (path: string) => Effect.Effect, options?: { git?: boolean; config?: Partial }, @@ -189,13 +207,8 @@ export const withTmpdirInstance = (self: Effect.Effect) => Effect.gen(function* () { const directory = yield* tmpdirScoped(options) - return yield* InstanceStore.Service.use((store) => - store.provide({ directory }, self.pipe(Effect.provideService(TestInstance, { directory }))), - ) - }).pipe( - Effect.provide(InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap))), - Effect.provide(CrossSpawnSpawner.defaultLayer), - ) + return yield* self.pipe(Effect.provideService(TestInstance, { directory }), provideInstanceEffect(directory)) + }).pipe(Effect.provide(testInstanceStoreLayer), Effect.provide(CrossSpawnSpawner.defaultLayer)) export function provideTmpdirServer( self: (input: { dir: string; llm: TestLLMServer["Service"] }) => Effect.Effect, diff --git a/packages/opencode/test/kilocode/agent-permission-overrides.test.ts b/packages/opencode/test/kilocode/agent-permission-overrides.test.ts index 2cd9345ba6e..fe223252e5d 100644 --- a/packages/opencode/test/kilocode/agent-permission-overrides.test.ts +++ b/packages/opencode/test/kilocode/agent-permission-overrides.test.ts @@ -2,7 +2,7 @@ import { afterEach, expect, test } from "bun:test" import { Effect } from "effect" import { Agent } from "../../src/agent/agent" import { Permission } from "../../src/permission" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { disposeAllInstances, provideInstance, tmpdir } from "../fixture/fixture" function load(dir: string, fn: (svc: Agent.Interface) => Effect.Effect) { @@ -25,7 +25,7 @@ test("ask agent honors user MCP allow over generated ask rule", async () => { }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const ask = await load(tmp.path, (svc) => svc.get("ask")) @@ -44,7 +44,7 @@ test("plan agent honors user bash allow over read-only deny default", async () = }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const plan = await load(tmp.path, (svc) => svc.get("plan")) @@ -63,7 +63,7 @@ test("plan agent still hard-denies non-plan edits after user edit allow", async }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const plan = await load(tmp.path, (svc) => svc.get("plan")) diff --git a/packages/opencode/test/kilocode/bash-permission-metadata.test.ts b/packages/opencode/test/kilocode/bash-permission-metadata.test.ts index dea0138049b..fe2779230db 100644 --- a/packages/opencode/test/kilocode/bash-permission-metadata.test.ts +++ b/packages/opencode/test/kilocode/bash-permission-metadata.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test" import { Effect, Layer, ManagedRuntime } from "effect" import { ShellTool } from "../../src/tool/shell" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { tmpdir } from "../fixture/fixture" import { Shell } from "../../src/shell/shell" import { SessionID, MessageID } from "../../src/session/schema" @@ -51,7 +51,7 @@ const capture = (requests: Array { test("permission prompt shows raw command without tool name prefix", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const bash = await runtime.runPromise(ShellTool.pipe(Effect.flatMap((info) => info.init()))) diff --git a/packages/opencode/test/kilocode/compaction-payload-recovery.test.ts b/packages/opencode/test/kilocode/compaction-payload-recovery.test.ts index dc8e46ee86b..70f0a5fbfb5 100644 --- a/packages/opencode/test/kilocode/compaction-payload-recovery.test.ts +++ b/packages/opencode/test/kilocode/compaction-payload-recovery.test.ts @@ -1,17 +1,18 @@ import { afterEach, describe, expect, mock, test } from "bun:test" import { APICallError } from "ai" -import { Effect, Layer, ManagedRuntime } from "effect" +import { Effect, Layer, ManagedRuntime, Scope } from "effect" import * as Stream from "effect/Stream" import { Agent } from "../../src/agent/agent" import { Bus } from "../../src/bus" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Image } from "../../src/image/image" import { KiloCompactionPayloadRecovery } from "../../src/kilocode/session/compaction-payload-recovery" import { KiloSessionCompaction } from "../../src/kilocode/session/compaction" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { ModelID, ProviderID } from "../../src/provider/schema" import { Snapshot } from "../../src/snapshot" import { LLM } from "../../src/session/llm" @@ -19,6 +20,7 @@ import { MessageV2 } from "../../src/session/message-v2" import * as SessionProcessorModule from "../../src/session/processor" import { Session as SessionNs } from "../../src/session/session" import { MessageID, PartID, SessionID } from "../../src/session/schema" +import { Reference } from "../../src/reference/reference" import { SessionCompaction } from "../../src/session/compaction" import { SessionStatus } from "../../src/session/status" import { SessionSummary } from "../../src/session/summary" @@ -175,6 +177,8 @@ function reply( } } +const scope = Layer.effect(Scope.Scope, Scope.make()) + function runtime(layer: Layer.Layer, config = Config.defaultLayer) { const bus = Bus.layer const status = SessionStatus.layer.pipe(Layer.provide(bus)) @@ -197,7 +201,11 @@ function runtime(layer: Layer.Layer, config = Config.defaultLayer) Layer.provide(bus), Layer.provide(config), Layer.provide(RuntimeFlags.layer()), + Layer.provide(scope), + Layer.provide(Reference.defaultLayer), Layer.provide(SyncEvent.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(Reference.defaultLayer), ), ) } @@ -315,7 +323,7 @@ describe("KiloCompactionPayloadRecovery", () => { }), ) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) diff --git a/packages/opencode/test/kilocode/config-gitignore.test.ts b/packages/opencode/test/kilocode/config-gitignore.test.ts index 59616d45b77..b80e783fccb 100644 --- a/packages/opencode/test/kilocode/config-gitignore.test.ts +++ b/packages/opencode/test/kilocode/config-gitignore.test.ts @@ -18,7 +18,7 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Env } from "../../src/env" import { Auth } from "../../src/auth" import { Account } from "../../src/account/account" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Filesystem } from "../../src/util/filesystem" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { tmpdir } from "../fixture/fixture" @@ -58,7 +58,7 @@ test(".gitignore in .kilo config dir includes pnpm and yarn lockfile patterns", const kilo = path.join(dir, ".kilo") await fs.mkdir(kilo, { recursive: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: dir, fn: async () => { await Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(testLayer))) diff --git a/packages/opencode/test/kilocode/config-resilience.test.ts b/packages/opencode/test/kilocode/config-resilience.test.ts index e49e510bc4a..a93de350999 100644 --- a/packages/opencode/test/kilocode/config-resilience.test.ts +++ b/packages/opencode/test/kilocode/config-resilience.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test" import path from "path" import { Config } from "../../src/config/config" import { AppRuntime } from "../../src/effect/app-runtime" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Filesystem } from "../../src/util/filesystem" import { disposeAllInstances, tmpdir } from "../fixture/fixture" @@ -35,7 +35,7 @@ Valid agent prompt`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const cfg = await load() @@ -63,7 +63,7 @@ Broken agent prompt`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await load() @@ -94,7 +94,7 @@ Valid command template`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const cfg = await load() @@ -121,7 +121,7 @@ Broken command template`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await load() @@ -145,7 +145,7 @@ Broken agent`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await load() @@ -169,7 +169,7 @@ Broken command`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await load() @@ -187,7 +187,7 @@ Broken command`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const cfg = await load() @@ -208,7 +208,7 @@ Broken command`, }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const cfg = await load() @@ -225,7 +225,7 @@ Broken command`, config: { model: "test/model" }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await load() diff --git a/packages/opencode/test/kilocode/config-validation.test.ts b/packages/opencode/test/kilocode/config-validation.test.ts index 8cfce322593..d1c8bb76139 100644 --- a/packages/opencode/test/kilocode/config-validation.test.ts +++ b/packages/opencode/test/kilocode/config-validation.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test" import path from "path" import { ConfigValidation } from "../../src/kilocode/config-validation" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Config } from "../../src/config/config" import { AppRuntime } from "../../src/effect/app-runtime" import { Filesystem } from "../../src/util/filesystem" @@ -20,7 +20,7 @@ describe("ConfigValidation.check", () => { const filepath = path.join(tmp.path, "src", "index.ts") await Filesystem.write(filepath, "export const x = 1") - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -32,7 +32,7 @@ describe("ConfigValidation.check", () => { const filepath = path.join(tmp.path, "kilo.json") await Filesystem.write(filepath, JSON.stringify({ model: "anthropic/claude-sonnet-4-20250514" })) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -45,7 +45,7 @@ describe("ConfigValidation.check", () => { const filepath = path.join(tmp.path, "kilo.json") await Filesystem.write(filepath, '{ "model": "test/model" "extra": true }') - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -60,7 +60,7 @@ describe("ConfigValidation.check", () => { // Config.Info uses .strict() so unknown fields produce errors await Filesystem.write(filepath, JSON.stringify({ notAField: true })) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -80,7 +80,7 @@ description: A test command Do something useful`, ) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -101,7 +101,7 @@ subtask: "not-a-boolean" Do something`, ) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -122,7 +122,7 @@ description: A helper agent You are a helpful agent.`, ) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -135,7 +135,7 @@ You are a helpful agent.`, const filepath = path.join(tmp.path, "AGENTS.md") await Filesystem.write(filepath, "# Project agents") - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -147,7 +147,7 @@ You are a helpful agent.`, const filepath = path.join(tmp.path, ".kilo", "plans", "plan.md") await Filesystem.write(filepath, "# Plan") - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: () => check(filepath), }) @@ -172,7 +172,7 @@ Broken agent`, const filepath = path.join(tmp.path, "kilo.json") await Filesystem.write(filepath, JSON.stringify({ model: "anthropic/claude-sonnet-4-20250514" })) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: tmp.path, fn: async () => { // Force config load to populate warnings diff --git a/packages/opencode/test/kilocode/config/config.test.ts b/packages/opencode/test/kilocode/config/config.test.ts index 55c2039a6bc..6cb862ad5b7 100644 --- a/packages/opencode/test/kilocode/config/config.test.ts +++ b/packages/opencode/test/kilocode/config/config.test.ts @@ -15,7 +15,7 @@ import { ConfigMarkdown } from "../../../src/config/markdown" import { Env } from "../../../src/env" import { KiloIndexing } from "../../../src/kilocode/indexing" import { KilocodeConfig } from "../../../src/kilocode/config/config" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { Filesystem } from "../../../src/util/filesystem" import { disposeAllInstances, tmpdir } from "../../fixture/fixture" @@ -109,7 +109,7 @@ describe("kilocode indexing config", () => { experimental: { semantic_indexing: true, batch_tool: true }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const config = await load() @@ -137,7 +137,7 @@ describe("kilocode indexing config", () => { }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const config = await load() @@ -173,7 +173,7 @@ describe("kilocode indexing config", () => { }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const global = await Effect.runPromise( diff --git a/packages/opencode/test/kilocode/config/indexing-default-plugin.test.ts b/packages/opencode/test/kilocode/config/indexing-default-plugin.test.ts index 7bfdf95a232..3059d6d7340 100644 --- a/packages/opencode/test/kilocode/config/indexing-default-plugin.test.ts +++ b/packages/opencode/test/kilocode/config/indexing-default-plugin.test.ts @@ -15,7 +15,7 @@ import { Env } from "../../../src/env" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" import { Filesystem } from "../../../src/util/filesystem" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { Npm } from "@opencode-ai/core/npm" import { disposeAllInstances, tmpdir } from "../../fixture/fixture" @@ -78,20 +78,20 @@ describe("kilocode default indexing plugin", () => { try { await using tmp = await tmpdir({ - init: async (dir) => { - await Filesystem.write( - path.join(dir, "opencode.json"), - JSON.stringify({ - $schema: "https://app.kilo.ai/config.json", - plugin: ["global-plugin-1"], - }), - ) - }, - }) + init: async (dir) => { + await Filesystem.write( + path.join(dir, "opencode.json"), + JSON.stringify({ + $schema: "https://app.kilo.ai/config.json", + plugin: ["global-plugin-1"], + }), + ) + }, + }) - await WithInstance.provide({ - directory: tmp.path, - fn: async () => { + await provideTestInstance({ + directory: tmp.path, + fn: async () => { const config = await load() expect(hasIndexingPlugin(config.plugin ?? [])).toBe(false) }, diff --git a/packages/opencode/test/kilocode/cost-propagation.test.ts b/packages/opencode/test/kilocode/cost-propagation.test.ts index ad7d0c87821..d68bfca6940 100644 --- a/packages/opencode/test/kilocode/cost-propagation.test.ts +++ b/packages/opencode/test/kilocode/cost-propagation.test.ts @@ -7,7 +7,7 @@ import { Effect, Layer } from "effect" import { Bus } from "../../src/bus" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { KiloCostPropagation } from "../../src/kilocode/session/cost-propagation" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { ProviderID, ModelID } from "../../src/provider/schema" import { Session } from "../../src/session/session" import { MessageV2 } from "../../src/session/message-v2" diff --git a/packages/opencode/test/kilocode/edit-permission-filediff.test.ts b/packages/opencode/test/kilocode/edit-permission-filediff.test.ts index 598365f03da..8785d145d43 100644 --- a/packages/opencode/test/kilocode/edit-permission-filediff.test.ts +++ b/packages/opencode/test/kilocode/edit-permission-filediff.test.ts @@ -7,7 +7,7 @@ import { afterAll, afterEach, describe, test, expect } from "bun:test" import path from "path" import { Effect, Layer, ManagedRuntime } from "effect" import { EditTool } from "../../src/tool/edit" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { disposeAllInstances, tmpdir } from "../fixture/fixture" import { LSP } from "../../src/lsp/lsp" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -68,7 +68,7 @@ describe("edit tool permission filediff metadata", () => { await using tmp = await tmpdir() const filepath = path.join(tmp.path, "new.txt") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const edit = await resolve() @@ -102,7 +102,7 @@ describe("edit tool permission filediff metadata", () => { const filepath = path.join(tmp.path, "existing.txt") await Bun.write(filepath, "line one\nline two\nline three\n") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const edit = await resolve() @@ -136,7 +136,7 @@ describe("edit tool permission filediff metadata", () => { const filepath = path.join(tmp.path, "diff-check.txt") await Bun.write(filepath, "alpha\nbeta\ngamma\n") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const edit = await resolve() @@ -167,7 +167,7 @@ describe("edit tool permission filediff metadata", () => { await using tmp = await tmpdir() const filepath = path.join(tmp.path, "result-new.txt") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const edit = await resolve() @@ -195,7 +195,7 @@ describe("edit tool permission filediff metadata", () => { const filepath = path.join(tmp.path, "result-edit.txt") await Bun.write(filepath, "before\n") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const edit = await resolve() diff --git a/packages/opencode/test/kilocode/external-directory-boundary.test.ts b/packages/opencode/test/kilocode/external-directory-boundary.test.ts index e594e5c3f73..aef72edc37b 100644 --- a/packages/opencode/test/kilocode/external-directory-boundary.test.ts +++ b/packages/opencode/test/kilocode/external-directory-boundary.test.ts @@ -2,9 +2,9 @@ import { describe, expect, test } from "bun:test" import { Effect } from "effect" import path from "path" import type { Permission } from "../../src/permission" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { InstanceRuntime } from "../../src/project/instance-runtime" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { SessionID, MessageID } from "../../src/session/schema" import { assertExternalDirectory } from "../../src/tool/external-directory" import type { Tool } from "../../src/tool/tool" @@ -44,7 +44,7 @@ describe("kilocode external directory boundaries", () => { const file = path.join(outer.path, "outside.txt") const { items, ctx } = asks() - await WithInstance.provide({ + await provideTestInstance({ directory: repo.path, fn: async () => { try { @@ -68,7 +68,7 @@ describe("kilocode external directory boundaries", () => { const file = path.join(outer.path, "outside-root.txt") const { items, ctx } = asks() - await WithInstance.provide({ + await provideTestInstance({ directory: root, fn: async () => { try { diff --git a/packages/opencode/test/kilocode/indexing-startup.test.ts b/packages/opencode/test/kilocode/indexing-startup.test.ts index 63c873a994c..eca44d1d3b6 100644 --- a/packages/opencode/test/kilocode/indexing-startup.test.ts +++ b/packages/opencode/test/kilocode/indexing-startup.test.ts @@ -1,11 +1,12 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" +import { Effect } from "effect" import { CodeIndexManager } from "@kilocode/kilo-indexing/engine" import { normalizeIndexingStatus } from "@kilocode/kilo-indexing/status" import type { Config } from "../../src/config/config" import { GlobalBus } from "../../src/bus/global" import { KiloIndexing } from "../../src/kilocode/indexing" import { IndexingWorker } from "../../src/kilocode/indexing-worker-client" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Server } from "../../src/server/server" import * as Log from "@opencode-ai/core/util/log" import { disposeAllInstances, tmpdir } from "../fixture/fixture" @@ -213,8 +214,9 @@ describe("indexing startup degradation", () => { GlobalBus.on("event", on) try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect((await KiloIndexing.current()).state).toBe("In Progress") @@ -241,8 +243,9 @@ describe("indexing startup degradation", () => { process.env["KILO_CONFIG_DIR"] = tmp.path try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { const status = await wait(() => KiloIndexing.current(), "Error") @@ -267,8 +270,9 @@ describe("indexing startup degradation", () => { const init = spyOn(CodeIndexManager.prototype, "initialize").mockImplementation(() => gate.promise) try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) @@ -289,7 +293,7 @@ describe("indexing startup degradation", () => { process.env["KILO_CONFIG_DIR"] = tmp.path const init = spyOn(CodeIndexManager.prototype, "initialize") - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const status = await wait(() => KiloIndexing.current(), "Disabled") @@ -316,7 +320,7 @@ describe("indexing startup degradation", () => { await using tmp = await tmpdir({ git: true, config: inactive }) process.env["KILO_CONFIG_DIR"] = tmp.path - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const status = await wait(() => KiloIndexing.current(), "Disabled") @@ -356,8 +360,9 @@ describe("indexing startup degradation", () => { process.env.KILO_ORG_ID = "org_123" try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect(init.mock.calls[0]?.[0]).toMatchObject({ @@ -400,8 +405,9 @@ describe("indexing startup degradation", () => { process.env.KILO_API_KEY = "kilo-token" try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect(init.mock.calls[0]?.[0]).toMatchObject({ @@ -454,8 +460,9 @@ describe("indexing startup degradation", () => { process.env.KILO_API_KEY = "kilo-token" try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect(init.mock.calls[0]?.[0]).toMatchObject({ @@ -482,8 +489,9 @@ describe("indexing startup degradation", () => { process.env.KILO_API_KEY = "kilo-token" try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect(init.mock.calls[0]?.[0]).toMatchObject({ embedderProvider: "kilo" }) @@ -507,8 +515,9 @@ describe("indexing startup degradation", () => { process.env.KILO_API_KEY = "kilo-token" try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { await called(init) expect(init.mock.calls[0]?.[0]).toMatchObject({ @@ -531,8 +540,9 @@ describe("indexing startup degradation", () => { const init = spyOn(CodeIndexManager.prototype, "initialize") try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, + init: Effect.promise(() => KiloIndexing.init()), fn: async () => { const status = await KiloIndexing.current() diff --git a/packages/opencode/test/kilocode/indexing-worktree.test.ts b/packages/opencode/test/kilocode/indexing-worktree.test.ts index fa42d92e1be..3042d7c9d56 100644 --- a/packages/opencode/test/kilocode/indexing-worktree.test.ts +++ b/packages/opencode/test/kilocode/indexing-worktree.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test" import { mkdir } from "node:fs/promises" import type { Config } from "../../src/config/config" import { KiloIndexing } from "../../src/kilocode/indexing" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { disposeAllInstances, tmpdir } from "../fixture/fixture" const cfg: Partial = { @@ -32,7 +32,7 @@ describe("indexing worktree disable", () => { const dir = `${tmp.path}/.kilo/worktrees/feature` await mkdir(dir, { recursive: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: dir, fn: async () => { const status = await KiloIndexing.current() @@ -52,7 +52,7 @@ describe("indexing worktree disable", () => { const dir = `${tmp.path}/.kilocode/worktrees/feature` await mkdir(dir, { recursive: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: dir, fn: async () => { const status = await KiloIndexing.current() diff --git a/packages/opencode/test/kilocode/instruction.test.ts b/packages/opencode/test/kilocode/instruction.test.ts index f0e2692e982..0d81087cb63 100644 --- a/packages/opencode/test/kilocode/instruction.test.ts +++ b/packages/opencode/test/kilocode/instruction.test.ts @@ -6,13 +6,24 @@ import { FetchHttpClient } from "effect/unstable/http" import { NodeFileSystem } from "@effect/platform-node" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" +import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { Reference } from "../../src/reference/reference" import { Instruction } from "../../src/session/instruction" import { Global } from "@opencode-ai/core/global" import { TestConfig } from "../fixture/config" import { provideInstance, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" -const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer)) +const reference = Layer.mock(Reference.Service)({ + init: () => Effect.void, + list: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + ensure: () => Effect.void, + contains: () => Effect.succeed(false), +}) +const it = testEffect( + Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer, reference, RuntimeFlags.layer()), +) const configLayer = TestConfig.layer() diff --git a/packages/opencode/test/kilocode/lsp-typescript-lightweight.test.ts b/packages/opencode/test/kilocode/lsp-typescript-lightweight.test.ts index 6baee85611b..4c3af1300b5 100644 --- a/packages/opencode/test/kilocode/lsp-typescript-lightweight.test.ts +++ b/packages/opencode/test/kilocode/lsp-typescript-lightweight.test.ts @@ -8,7 +8,7 @@ import * as LSPServer from "../../src/lsp/server" import { TsClient } from "../../src/kilocode/ts-client" import { TsCheck } from "../../src/kilocode/ts-check" import { Flag } from "@opencode-ai/core/flag/flag" -import { Instance, type InstanceContext } from "../../src/project/instance" +import { Instance, type InstanceContext } from "../../src/kilocode/instance" import { disposeAllInstances } from "../fixture/fixture" import type { RuntimeFlags } from "../../src/effect/runtime-flags" diff --git a/packages/opencode/test/kilocode/permission/external-directory-allow.test.ts b/packages/opencode/test/kilocode/permission/external-directory-allow.test.ts index f1af05cb648..0280f9d3b28 100644 --- a/packages/opencode/test/kilocode/permission/external-directory-allow.test.ts +++ b/packages/opencode/test/kilocode/permission/external-directory-allow.test.ts @@ -10,7 +10,7 @@ import { Config } from "../../../src/config/config" import { RuntimeFlags } from "../../../src/effect/runtime-flags" import { Permission } from "../../../src/permission" import { PermissionID } from "../../../src/permission/schema" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { MessageID, SessionID } from "../../../src/session/schema" import { Shell } from "../../../src/shell/shell" import { Truncate } from "../../../src/tool/truncate" @@ -239,7 +239,7 @@ describe("bash external_directory access metadata", () => { test("emits read access metadata for cat external files", async () => { await using outer = await tmpdir({ init: (dir) => Bun.write(path.join(dir, "hello.txt"), "hello") }) await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const bash = await init() @@ -267,7 +267,7 @@ describe("bash external_directory access metadata", () => { withShell(item, async () => { await using outer = await tmpdir({ init: (dir) => Bun.write(path.join(dir, "hello.txt"), "hello") }) await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const bash = await init() @@ -294,7 +294,7 @@ describe("bash external_directory access metadata", () => { test("does not emit read access metadata for mutating external file commands", async () => { await using outer = await tmpdir({ init: (dir) => Bun.write(path.join(dir, "hello.txt"), "hello") }) await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const bash = await init() @@ -325,7 +325,7 @@ describe("bash external_directory access metadata", () => { test("does not emit read access metadata for mixed read and write external commands", async () => { await using outer = await tmpdir({ init: (dir) => Bun.write(path.join(dir, "hello.txt"), "hello") }) await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const bash = await init() diff --git a/packages/opencode/test/kilocode/permission/next.reply-http.test.ts b/packages/opencode/test/kilocode/permission/next.reply-http.test.ts index 20abcbdfead..7fb355eca4b 100644 --- a/packages/opencode/test/kilocode/permission/next.reply-http.test.ts +++ b/packages/opencode/test/kilocode/permission/next.reply-http.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { tmpdir } from "../../fixture/fixture" async function app() { @@ -11,7 +11,7 @@ describe("POST /permission/:requestID/reply", () => { test("returns 404 when requestID is not pending", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const server = await app() @@ -35,7 +35,7 @@ describe("POST /permission/:requestID/always-rules", () => { test("returns 404 when requestID is not pending", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const server = await app() diff --git a/packages/opencode/test/kilocode/plan-exit-detection.test.ts b/packages/opencode/test/kilocode/plan-exit-detection.test.ts index b2440c1a5de..0ee10c66c67 100644 --- a/packages/opencode/test/kilocode/plan-exit-detection.test.ts +++ b/packages/opencode/test/kilocode/plan-exit-detection.test.ts @@ -6,8 +6,8 @@ import path from "path" import { Identifier } from "../../src/id/id" import { SessionID, MessageID, PartID } from "../../src/session/schema" import { ModelID, ProviderID } from "../../src/provider/schema" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { Instance } from "../../src/kilocode/instance" +import { provideTestInstance } from "../fixture/fixture" import { PlanFollowup } from "../../src/kilocode/plan-followup" import { KiloSessionPrompt } from "../../src/kilocode/session/prompt" import { makeRuntime } from "../../src/effect/run-service" @@ -56,7 +56,7 @@ const model = { async function withInstance(fn: () => Promise) { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ directory: tmp.path, fn }) + await provideTestInstance({ directory: tmp.path, fn }) } async function seed(input: { diff --git a/packages/opencode/test/kilocode/plan-file.test.ts b/packages/opencode/test/kilocode/plan-file.test.ts index 8d3fbf8a676..47124b4bc65 100644 --- a/packages/opencode/test/kilocode/plan-file.test.ts +++ b/packages/opencode/test/kilocode/plan-file.test.ts @@ -3,8 +3,8 @@ import { Effect, Layer, ManagedRuntime } from "effect" import path from "path" import { Agent } from "../../src/agent/agent" import { PlanFile } from "../../src/kilocode/plan-file" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { Instance } from "../../src/kilocode/instance" +import { provideTestInstance } from "../fixture/fixture" import { Session } from "../../src/session/session" import { MessageID } from "../../src/session/schema" import { PlanExitTool } from "../../src/tool/plan" @@ -26,7 +26,7 @@ async function init() { describe("PlanFile", () => { test("plan_exit accepts custom paths from plan agent", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await rt.runPromise(Session.Service.use((svc) => svc.create({}))) @@ -54,7 +54,7 @@ describe("PlanFile", () => { test("rejects custom plan paths outside the worktree", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { expect(PlanFile.resolve("../../etc/shadow", Instance.current)).toBeUndefined() diff --git a/packages/opencode/test/kilocode/plan-followup.test.ts b/packages/opencode/test/kilocode/plan-followup.test.ts index d0835591eb1..06664e7c219 100644 --- a/packages/opencode/test/kilocode/plan-followup.test.ts +++ b/packages/opencode/test/kilocode/plan-followup.test.ts @@ -7,8 +7,8 @@ import { Identifier } from "../../src/id/id" import { SessionID, MessageID, PartID } from "../../src/session/schema" import { ModelID, ProviderID } from "../../src/provider/schema" import { formatTodos, generateHandover, PlanFollowup, PlanFollowupRuntime } from "../../src/kilocode/plan-followup" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { Instance } from "../../src/kilocode/instance" +import { provideTestInstance } from "../fixture/fixture" import { Provider } from "../../src/provider/provider" import { Question } from "../../src/question" import { Session } from "../../src/session/session" @@ -90,7 +90,7 @@ const savedKey = `${saved.providerID}/${saved.modelID}` async function withInstance(fn: () => Promise) { await using tmp = await tmpdir({ git: true }) await fs.rm(statePath, { force: true }).catch(() => {}) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await fs.rm(statePath, { force: true }).catch(() => {}) @@ -724,12 +724,12 @@ describe("plan follow-up", () => { const dir = other.path - const seeded = await WithInstance.provide({ + const seeded = await provideTestInstance({ directory: dir, fn: async () => seed({ text: "1. Add API\n2. Add tests" }), }) - const before = await WithInstance.provide({ + const before = await provideTestInstance({ directory: dir, fn: async () => sessions(), }) @@ -750,7 +750,7 @@ describe("plan follow-up", () => { }) await expect(pending).resolves.toBe("break") - const after = await WithInstance.provide({ + const after = await provideTestInstance({ directory: dir, fn: async () => sessions(), }) @@ -764,7 +764,7 @@ describe("plan follow-up", () => { expect(next?.parentID).toBeUndefined() if (next) { - const planPath = await WithInstance.provide({ + const planPath = await provideTestInstance({ directory: dir, fn: async () => Session.plan(await store.get(seeded.sessionID), Instance.current), }) diff --git a/packages/opencode/test/kilocode/project-config-update.test.ts b/packages/opencode/test/kilocode/project-config-update.test.ts index efd4d08cf9b..9b980d53d98 100644 --- a/packages/opencode/test/kilocode/project-config-update.test.ts +++ b/packages/opencode/test/kilocode/project-config-update.test.ts @@ -12,7 +12,7 @@ import { Auth } from "../../src/auth" import { Account } from "../../src/account/account" import { Env } from "../../src/env" import { Npm } from "@opencode-ai/core/npm" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Filesystem } from "../../src/util/filesystem" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { tmpdir } from "../fixture/fixture" @@ -56,7 +56,7 @@ async function writeConfig(dir: string, config: unknown) { test("project config update creates .kilo/kilo.json and reloads it", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await save({ model: "updated/model" } as any) @@ -72,7 +72,7 @@ test("project config update creates .kilo/kilo.json and reloads it", async () => test("project config update skips empty delete-only writes when no config exists", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await save({ provider: { missing: null } } as any) @@ -86,7 +86,7 @@ test("project config update prefers existing root kilo.json", async () => { await using tmp = await tmpdir() await writeConfig(tmp.path, { username: "alice" }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { await save({ model: "updated/model" } as any) @@ -105,7 +105,7 @@ test("project config update patches ancestor .kilo/kilo.json from nested directo await fs.mkdir(path.join(tmp.path, ".kilo"), { recursive: true }) await writeConfig(path.join(tmp.path, ".kilo"), { username: "alice" }) - await WithInstance.provide({ + await provideTestInstance({ directory: child, fn: async () => { await save({ model: "updated/model" } as any) diff --git a/packages/opencode/test/kilocode/project-id.test.ts b/packages/opencode/test/kilocode/project-id.test.ts index 8f9198c4ff2..d93dc7a85d0 100644 --- a/packages/opencode/test/kilocode/project-id.test.ts +++ b/packages/opencode/test/kilocode/project-id.test.ts @@ -2,7 +2,7 @@ import { test, expect, describe } from "bun:test" import { tmpdir } from "../fixture/fixture" import path from "path" import fs from "fs/promises" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { getKiloProjectId } from "../../src/kilocode/project-id" describe("project-id", () => { @@ -16,7 +16,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -33,7 +33,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -49,7 +49,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -65,7 +65,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -82,7 +82,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -112,7 +112,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -136,7 +136,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -158,7 +158,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -182,7 +182,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -208,7 +208,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -234,7 +234,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -258,7 +258,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -284,7 +284,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -297,7 +297,7 @@ describe("project-id", () => { test("returns undefined when no config and no git origin", async () => { await using tmp = await tmpdir({ git: true }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -308,7 +308,7 @@ describe("project-id", () => { test("returns undefined for non-git directory", async () => { await using tmp = await tmpdir() - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -327,7 +327,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -354,7 +354,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -373,12 +373,12 @@ describe("project-id", () => { }, }) - const id1 = await WithInstance.provide({ + const id1 = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) - const id2 = await WithInstance.provide({ + const id2 = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -397,7 +397,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -420,7 +420,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) @@ -444,7 +444,7 @@ describe("project-id", () => { }, }) - const id = await WithInstance.provide({ + const id = await provideTestInstance({ directory: tmp.path, fn: () => getKiloProjectId(), }) diff --git a/packages/opencode/test/kilocode/pty-self-command.test.ts b/packages/opencode/test/kilocode/pty-self-command.test.ts index 8dce5c515db..d799f42dc92 100644 --- a/packages/opencode/test/kilocode/pty-self-command.test.ts +++ b/packages/opencode/test/kilocode/pty-self-command.test.ts @@ -12,9 +12,11 @@ describe("pty self-command", () => { const cmd = KiloPtySelfCommand.command(proc) expect(cmd).toStrictEqual({ command: "/tmp/kilo", args: [] }) - expect( - KiloPtySelfCommand.resolve({ command: "kilo", cwd: "/tmp/project" }, cmd), - ).toStrictEqual({ command: "/tmp/kilo", args: [], cwd: "/tmp/project" }) + expect(KiloPtySelfCommand.resolve({ command: "kilo", cwd: "/tmp/project" }, cmd)).toStrictEqual({ + command: "/tmp/kilo", + args: [], + cwd: "/tmp/project", + }) expect( KiloPtySelfCommand.command({ ...proc, @@ -41,9 +43,7 @@ describe("pty self-command", () => { args: ["--conditions=browser", "/tmp/kilo/src/index.ts"], cwd: "/tmp/kilo", }) - expect( - KiloPtySelfCommand.resolve({ command: "kilo", cwd: "/tmp/project" }, cmd), - ).toStrictEqual({ + expect(KiloPtySelfCommand.resolve({ command: "kilo", cwd: "/tmp/project" }, cmd)).toStrictEqual({ command: "/tmp/bun", args: ["--conditions=browser", "/tmp/kilo/src/index.ts", "/tmp/project"], cwd: "/tmp/kilo", diff --git a/packages/opencode/test/kilocode/semantic-search.test.ts b/packages/opencode/test/kilocode/semantic-search.test.ts index 2e69a77efae..2b6f6efc795 100644 --- a/packages/opencode/test/kilocode/semantic-search.test.ts +++ b/packages/opencode/test/kilocode/semantic-search.test.ts @@ -4,7 +4,7 @@ import { Effect, Layer, ManagedRuntime } from "effect" import { Agent } from "../../src/agent/agent" import { SemanticSearchTool } from "../../src/kilocode/tool/semantic-search" import { KiloIndexing } from "../../src/kilocode/indexing" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { tmpdir } from "../fixture/fixture" import type { Permission } from "../../src/permission" import { SessionID, MessageID } from "../../src/session/schema" @@ -48,7 +48,7 @@ describe("tool.semantic_search", () => { test("asks permission and forwards normalized relative path to indexing search", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const requests: Array> = [] @@ -89,7 +89,7 @@ describe("tool.semantic_search", () => { test("searches entire workspace when path is omitted", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const search = spyOn(KiloIndexing, "search").mockResolvedValue([]) @@ -110,7 +110,7 @@ describe("tool.semantic_search", () => { test("formats and normalizes search results", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const search = spyOn(KiloIndexing, "search").mockResolvedValue([ @@ -166,7 +166,7 @@ describe("tool.semantic_search", () => { test("rejects paths outside the workspace", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const search = spyOn(KiloIndexing, "search").mockResolvedValue([]) diff --git a/packages/opencode/test/kilocode/server/permission-allow-everything.test.ts b/packages/opencode/test/kilocode/server/permission-allow-everything.test.ts index 2842095b3b7..e00ceb824e4 100644 --- a/packages/opencode/test/kilocode/server/permission-allow-everything.test.ts +++ b/packages/opencode/test/kilocode/server/permission-allow-everything.test.ts @@ -7,7 +7,7 @@ import * as Config from "../../../src/config/config" import { AllowEverythingPermission } from "../../../src/kilocode/permission/allow-everything" import { Permission } from "../../../src/permission" import { PermissionID } from "../../../src/permission/schema" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { Server } from "../../../src/server/server" import { Session } from "../../../src/session/session" import { provideTmpdirInstance, tmpdir } from "../../fixture/fixture" @@ -48,7 +48,7 @@ const wait = () => describe("AllowEverythingPermission", () => { test("handles disable requests through the HTTP endpoint", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const enable = await Server.Default().app.request("/permission/allow-everything", { diff --git a/packages/opencode/test/kilocode/session-compaction-cap.test.ts b/packages/opencode/test/kilocode/session-compaction-cap.test.ts index f38dd97e393..4b16e85778d 100644 --- a/packages/opencode/test/kilocode/session-compaction-cap.test.ts +++ b/packages/opencode/test/kilocode/session-compaction-cap.test.ts @@ -13,6 +13,7 @@ import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { Env } from "../../src/env" import { Ripgrep } from "../../src/file/ripgrep" @@ -46,6 +47,7 @@ import { SessionSummary } from "../../src/session/summary" import { Todo } from "../../src/session/todo" import { Skill } from "../../src/skill" import { Snapshot } from "../../src/snapshot" +import { Storage } from "../../src/storage/storage" import { SyncEvent } from "../../src/sync" import { ToolRegistry } from "../../src/tool/registry" import { Truncate } from "../../src/tool/truncate" @@ -145,6 +147,7 @@ function makeHttp() { mcp, AppFileSystem.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, Reference.defaultLayer, status, ).pipe(Layer.provideMerge(infra)) @@ -184,7 +187,21 @@ function makeHttp() { Layer.provide(SystemPrompt.defaultLayer), Layer.provideMerge(deps), ), - ).pipe(Layer.provide(summary)) + ).pipe( + Layer.provide( + Layer.mergeAll( + summary, + deps, + Config.defaultLayer, + RuntimeFlags.layer(), + BackgroundJob.defaultLayer, + Bus.layer, + infra, + Storage.defaultLayer, + Reference.defaultLayer, + ), + ), + ) } const it = testEffect(makeHttp()) diff --git a/packages/opencode/test/kilocode/session-compaction-chunks.test.ts b/packages/opencode/test/kilocode/session-compaction-chunks.test.ts index 8c5ecf12054..76441e1fd5e 100644 --- a/packages/opencode/test/kilocode/session-compaction-chunks.test.ts +++ b/packages/opencode/test/kilocode/session-compaction-chunks.test.ts @@ -1,20 +1,22 @@ import { afterEach, describe, expect, mock, test } from "bun:test" -import { Effect, Layer, ManagedRuntime } from "effect" +import { Effect, Layer, ManagedRuntime, Scope } from "effect" import * as Stream from "effect/Stream" import { Agent } from "../../src/agent/agent" import { Bus } from "../../src/bus" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Image } from "../../src/image/image" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { ModelID, ProviderID } from "../../src/provider/schema" import { Snapshot } from "../../src/snapshot" import { KiloCompactionChunks } from "../../src/kilocode/session/compaction-chunks" import { KiloSessionCompaction } from "../../src/kilocode/session/compaction" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" +import { Reference } from "../../src/reference/reference" import { SessionCompaction } from "../../src/session/compaction" import * as SessionProcessorModule from "../../src/session/processor" import type { SessionProcessor } from "../../src/session/processor" @@ -220,7 +222,9 @@ function runtime(layer: Layer.Layer, context = 7_000) { Layer.provide(Agent.defaultLayer), Layer.provide(Plugin.defaultLayer), Layer.provide(SyncEvent.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(RuntimeFlags.layer()), + Layer.provide(Reference.defaultLayer), Layer.provide(status), Layer.provide(bus), Layer.provide( @@ -286,7 +290,9 @@ function fakeRuntime() { Layer.provide(Agent.defaultLayer), Layer.provide(Plugin.defaultLayer), Layer.provide(SyncEvent.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(RuntimeFlags.layer()), + Layer.provide(Reference.defaultLayer), Layer.provide(bus), Layer.provide( Layer.mock(Config.Service)({ @@ -317,7 +323,9 @@ function liveRuntime(layer: Layer.Layer, context = 10_000) { Layer.provide(Agent.defaultLayer), Layer.provide(Plugin.defaultLayer), Layer.provide(SyncEvent.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(RuntimeFlags.layer()), + Layer.provide(Reference.defaultLayer), Layer.provide(status), Layer.provide(bus), Layer.provide( @@ -367,7 +375,7 @@ describe("KiloCompactionChunks", () => { test("falls back to chunk workers after the first compaction overflows", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) @@ -421,7 +429,7 @@ describe("KiloCompactionChunks", () => { test("uses chunk fallback before sending oversized normal compaction", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) @@ -467,7 +475,7 @@ describe("KiloCompactionChunks", () => { test("uses a worker even when fallback selection produces one oversized chunk", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) @@ -519,7 +527,7 @@ describe("KiloCompactionChunks", () => { test("serializes oversized fallback chunks before summarizing", async () => { await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) @@ -564,7 +572,7 @@ describe("KiloCompactionChunks", () => { test("caps worker output budget below oversized model output limit", async () => { const { rt, calls, outputs } = fakeRuntime() await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) @@ -612,7 +620,7 @@ describe("KiloCompactionChunks", () => { stub.push(reply("replay summary", (input) => calls.push(JSON.stringify(input.messages)))) await using tmp = await tmpdir() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await svc.create({}) diff --git a/packages/opencode/test/kilocode/session-fork-remap.test.ts b/packages/opencode/test/kilocode/session-fork-remap.test.ts index 342de6a8285..08ca78376c5 100644 --- a/packages/opencode/test/kilocode/session-fork-remap.test.ts +++ b/packages/opencode/test/kilocode/session-fork-remap.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, test } from "bun:test" import { Effect } from "effect" import { createKiloClient } from "@kilocode/sdk/v2/client" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Server } from "../../src/server/server" import { Session } from "../../src/session/session" import { MessageV2 } from "../../src/session/message-v2" @@ -88,7 +88,7 @@ describe("Session.fork cost accounting", () => { "forked sessions start with zero cost", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const original = await sessions.create({ title: "original" }) @@ -130,7 +130,7 @@ describe("Session.fork child session remapping", () => { "forked session gets its own copy of child sessions", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const parent = await sessions.create({ title: "parent" }) @@ -204,7 +204,7 @@ describe("Session.fork child session remapping", () => { "nested child sessions are also remapped", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { // grandchild -> child -> parent @@ -291,7 +291,7 @@ describe("Session.fork child session remapping", () => { "self-referential task metadata remaps to the forked session", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const parent = await sessions.create({ title: "parent" }) @@ -331,7 +331,7 @@ describe("Session.fork child session remapping", () => { "cyclic task metadata remaps each session once", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const parent = await sessions.create({ title: "parent" }) @@ -399,7 +399,7 @@ describe("Session.fork child session remapping", () => { "non-task tool parts are not affected", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const parent = await sessions.create({ title: "parent" }) diff --git a/packages/opencode/test/kilocode/session-list.test.ts b/packages/opencode/test/kilocode/session-list.test.ts index 519baa72636..0dc998fde7c 100644 --- a/packages/opencode/test/kilocode/session-list.test.ts +++ b/packages/opencode/test/kilocode/session-list.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test" import { Effect } from "effect" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { ProjectTable } from "../../src/project/project.sql" import { ProjectID } from "../../src/project/schema" import { Session } from "../../src/session/session" @@ -18,7 +18,7 @@ afterEach(async () => { describe("Kilo Session.list", () => { test("includes directory matches from legacy project ids", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await Effect.runPromise( diff --git a/packages/opencode/test/kilocode/session-processor-empty-tool-calls.test.ts b/packages/opencode/test/kilocode/session-processor-empty-tool-calls.test.ts index b318976bcaf..a7278d48d70 100644 --- a/packages/opencode/test/kilocode/session-processor-empty-tool-calls.test.ts +++ b/packages/opencode/test/kilocode/session-processor-empty-tool-calls.test.ts @@ -7,11 +7,13 @@ import { Agent as AgentSvc } from "../../src/agent/agent" import { Bus } from "../../src/bus" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Image } from "../../src/image/image" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" import type { Provider } from "../../src/provider/provider" import { ModelID, ProviderID } from "../../src/provider/schema" +import { Reference } from "../../src/reference/reference" import { Session } from "../../src/session/session" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" @@ -94,6 +96,13 @@ const llm = Layer.unwrap( }), ) +const reference = Layer.mock(Reference.Service)({ + init: () => Effect.void, + list: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + ensure: () => Effect.void, + contains: () => Effect.succeed(false), +}) const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) const deps = Layer.mergeAll( @@ -104,13 +113,15 @@ const deps = Layer.mergeAll( Plugin.defaultLayer, Config.defaultLayer, RuntimeFlags.layer(), + reference, SessionSummary.defaultLayer, Image.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, status, llm, ).pipe(Layer.provideMerge(infra)) -const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps)) +const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps), Layer.provide(reference)) const it = testEffect(env) diff --git a/packages/opencode/test/kilocode/session-processor-network-offline.test.ts b/packages/opencode/test/kilocode/session-processor-network-offline.test.ts index abdb5fc55d8..b1fa5eba71a 100644 --- a/packages/opencode/test/kilocode/session-processor-network-offline.test.ts +++ b/packages/opencode/test/kilocode/session-processor-network-offline.test.ts @@ -7,11 +7,13 @@ import { Agent as AgentSvc } from "../../src/agent/agent" import { Bus } from "../../src/bus" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Image } from "../../src/image/image" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" import type { Provider } from "../../src/provider/provider" import { ModelID, ProviderID } from "../../src/provider/schema" +import { Reference } from "../../src/reference/reference" import { Session } from "../../src/session/session" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" @@ -93,6 +95,13 @@ const llm = Layer.unwrap( }), ) +const reference = Layer.mock(Reference.Service)({ + init: () => Effect.void, + list: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + ensure: () => Effect.void, + contains: () => Effect.succeed(false), +}) const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) const deps = Layer.mergeAll( @@ -103,13 +112,15 @@ const deps = Layer.mergeAll( Plugin.defaultLayer, Config.defaultLayer, RuntimeFlags.layer(), + reference, SessionSummary.defaultLayer, Image.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, status, llm, ).pipe(Layer.provideMerge(infra)) -const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps)) +const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps), Layer.provide(reference)) const it = testEffect(env) diff --git a/packages/opencode/test/kilocode/session-processor-retry-limit.test.ts b/packages/opencode/test/kilocode/session-processor-retry-limit.test.ts index 827e9c0cf38..79b04943fb6 100644 --- a/packages/opencode/test/kilocode/session-processor-retry-limit.test.ts +++ b/packages/opencode/test/kilocode/session-processor-retry-limit.test.ts @@ -14,11 +14,13 @@ import { Agent as AgentSvc } from "../../src/agent/agent" import { Bus } from "../../src/bus" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Image } from "../../src/image/image" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" import type { Provider } from "../../src/provider/provider" import { ModelID, ProviderID } from "../../src/provider/schema" +import { Reference } from "../../src/reference/reference" import { Session } from "../../src/session/session" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" @@ -106,6 +108,13 @@ const llm = Layer.unwrap( }), ) +const reference = Layer.mock(Reference.Service)({ + init: () => Effect.void, + list: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + ensure: () => Effect.void, + contains: () => Effect.succeed(false), +}) const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) const deps = Layer.mergeAll( @@ -116,13 +125,15 @@ const deps = Layer.mergeAll( Plugin.defaultLayer, Config.defaultLayer, RuntimeFlags.layer(), + reference, SessionSummary.defaultLayer, Image.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, status, llm, ).pipe(Layer.provideMerge(infra)) -const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps)) +const env = SessionProcessor.layer.pipe(Layer.provideMerge(deps), Layer.provide(reference)) const it = testEffect(env) diff --git a/packages/opencode/test/kilocode/session-prompt-compaction-safety.test.ts b/packages/opencode/test/kilocode/session-prompt-compaction-safety.test.ts index 22c1cae000b..b7311dc9ec6 100644 --- a/packages/opencode/test/kilocode/session-prompt-compaction-safety.test.ts +++ b/packages/opencode/test/kilocode/session-prompt-compaction-safety.test.ts @@ -12,6 +12,7 @@ import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { Env } from "../../src/env" import { Ripgrep } from "../../src/file/ripgrep" @@ -43,6 +44,7 @@ import { SessionSummary } from "../../src/session/summary" import { Todo } from "../../src/session/todo" import { Skill } from "../../src/skill" import { Snapshot } from "../../src/snapshot" +import { Storage } from "../../src/storage/storage" import { SyncEvent } from "../../src/sync" import { ToolRegistry } from "../../src/tool/registry" import { Truncate } from "../../src/tool/truncate" @@ -139,6 +141,7 @@ function makeHttp() { AppFileSystem.defaultLayer, Reference.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, status, ).pipe(Layer.provideMerge(infra)) const question = Question.layer.pipe(Layer.provideMerge(deps)) @@ -179,7 +182,19 @@ function makeHttp() { Layer.provideMerge(deps), ), ).pipe( - Layer.provide(Layer.mergeAll(summary, deps, Config.defaultLayer, RuntimeFlags.layer(), BackgroundJob.defaultLayer)), + Layer.provide( + Layer.mergeAll( + summary, + deps, + Config.defaultLayer, + RuntimeFlags.layer(), + BackgroundJob.defaultLayer, + Bus.layer, + infra, + Storage.defaultLayer, + Reference.defaultLayer, + ), + ), ) } diff --git a/packages/opencode/test/kilocode/session-prompt-permission-refresh.test.ts b/packages/opencode/test/kilocode/session-prompt-permission-refresh.test.ts index 168977c9ac1..3f4d74d4e91 100644 --- a/packages/opencode/test/kilocode/session-prompt-permission-refresh.test.ts +++ b/packages/opencode/test/kilocode/session-prompt-permission-refresh.test.ts @@ -12,6 +12,7 @@ import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Env } from "../../src/env" import { Format } from "../../src/format" import { Git } from "../../src/git" @@ -37,6 +38,7 @@ import { SessionSummary } from "../../src/session/summary" import { Todo } from "../../src/session/todo" import { Skill } from "../../src/skill" import { Snapshot } from "../../src/snapshot" +import { Storage } from "../../src/storage/storage" import { SyncEvent } from "../../src/sync" import { Ripgrep } from "../../src/file/ripgrep" import { ToolRegistry } from "../../src/tool/registry" @@ -133,6 +135,7 @@ function makeHttp() { AppFileSystem.defaultLayer, Reference.defaultLayer, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, status, ).pipe(Layer.provideMerge(infra)) const question = Question.layer.pipe(Layer.provideMerge(deps)) @@ -173,7 +176,19 @@ function makeHttp() { Layer.provideMerge(deps), ), ).pipe( - Layer.provide(Layer.mergeAll(summary, deps, Config.defaultLayer, RuntimeFlags.layer(), BackgroundJob.defaultLayer)), + Layer.provide( + Layer.mergeAll( + summary, + deps, + Config.defaultLayer, + RuntimeFlags.layer(), + BackgroundJob.defaultLayer, + Bus.layer, + infra, + Storage.defaultLayer, + Reference.defaultLayer, + ), + ), ) } diff --git a/packages/opencode/test/kilocode/session-prompt-queue.test.ts b/packages/opencode/test/kilocode/session-prompt-queue.test.ts index 4e6c57ebaf9..2194ef5ab37 100644 --- a/packages/opencode/test/kilocode/session-prompt-queue.test.ts +++ b/packages/opencode/test/kilocode/session-prompt-queue.test.ts @@ -9,7 +9,7 @@ import { KiloSessionPromptQueue } from "@/kilocode/session/prompt-queue" import { Suggestion } from "../../src/kilocode/suggestion" import { ModelID, ProviderID } from "../../src/provider/schema" import { InstanceStore } from "../../src/project/instance-store" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Session } from "../../src/session/session" import { MessageV2 } from "../../src/session/message-v2" import { SessionCompaction } from "../../src/session/compaction" @@ -275,7 +275,7 @@ describe("session prompt queue", () => { // scope() hides that marker, runLoop never processes the compaction task and // instead retries the same oversized request until compaction is exhausted. await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const session = await sessions.create({ title: "Queued compaction regression" }) @@ -444,7 +444,7 @@ describe("session prompt queue", () => { }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => scoped(tmp.path, async (prompt) => { @@ -656,7 +656,7 @@ describe("session prompt queue", () => { }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => scoped(tmp.path, async (prompt) => { @@ -722,7 +722,7 @@ describe("session prompt queue", () => { const dismissed = Promise.withResolvers() await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => scoped(tmp.path, async (prompt) => { @@ -771,7 +771,7 @@ describe("session prompt queue", () => { // hasFollowup=true and reject synchronously, before any pending entry or // Shown event is published. await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const sessionID = SessionID.make("ses_auto_suggestion") diff --git a/packages/opencode/test/kilocode/session/instruction-substitution.test.ts b/packages/opencode/test/kilocode/session/instruction-substitution.test.ts index 98cc02243af..d4668089670 100644 --- a/packages/opencode/test/kilocode/session/instruction-substitution.test.ts +++ b/packages/opencode/test/kilocode/session/instruction-substitution.test.ts @@ -5,6 +5,8 @@ import { FetchHttpClient } from "effect/unstable/http" import { NodeFileSystem } from "@effect/platform-node" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" +import { RuntimeFlags } from "../../../src/effect/runtime-flags" +import { Reference } from "../../../src/reference/reference" import { Instruction } from "../../../src/session/instruction" import { MessageID } from "../../../src/session/schema" import { Global } from "@opencode-ai/core/global" @@ -12,7 +14,16 @@ import { provideTmpdirInstance } from "../../fixture/fixture" import { testEffect } from "../../lib/effect" import { TestConfig } from "../../fixture/config" -const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer)) +const reference = Layer.mock(Reference.Service)({ + init: () => Effect.void, + list: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + ensure: () => Effect.void, + contains: () => Effect.succeed(false), +}) +const it = testEffect( + Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer, reference, RuntimeFlags.layer()), +) const configLayer = TestConfig.layer() diff --git a/packages/opencode/test/kilocode/session/platform-attribution.test.ts b/packages/opencode/test/kilocode/session/platform-attribution.test.ts index 51ecd66564a..2009a7d142e 100644 --- a/packages/opencode/test/kilocode/session/platform-attribution.test.ts +++ b/packages/opencode/test/kilocode/session/platform-attribution.test.ts @@ -5,7 +5,7 @@ import { Session as SessionNs } from "@/session/session" import { AppRuntime } from "../../../src/effect/app-runtime" import { Bus } from "../../../src/bus" import { KiloSession } from "../../../src/kilocode/session" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { MessageV2 } from "../../../src/session/message-v2" import { MessageID, PartID, type SessionID } from "../../../src/session/schema" @@ -30,7 +30,7 @@ function updatePart(part: T) { describe("session platform attribution", () => { test("child sessions inherit the root platform override", async () => { - await WithInstance.provide({ + await provideTestInstance({ directory: projectRoot, fn: async () => { const root = await create({ platform: "agent-manager" }) @@ -49,7 +49,7 @@ describe("session platform attribution", () => { }) test("child sessions expose parent and root lineage", async () => { - await WithInstance.provide({ + await provideTestInstance({ directory: projectRoot, fn: async () => { const root = await create({}) @@ -71,7 +71,7 @@ describe("step-finish token propagation via Bus event", () => { test( "non-zero tokens propagate through PartUpdated event", async () => { - await WithInstance.provide({ + await provideTestInstance({ directory: projectRoot, fn: async () => { const info = await create({}) diff --git a/packages/opencode/test/kilocode/session/session.test.ts b/packages/opencode/test/kilocode/session/session.test.ts index 323b7091b98..5d561af608d 100644 --- a/packages/opencode/test/kilocode/session/session.test.ts +++ b/packages/opencode/test/kilocode/session/session.test.ts @@ -3,7 +3,7 @@ import path from "path" import { Session as SessionNs } from "@/session/session" import { Bus } from "../../../src/bus" import * as Log from "@opencode-ai/core/util/log" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { AppRuntime } from "../../../src/effect/app-runtime" import { RuntimeFlags } from "../../../src/effect/runtime-flags" import { Effect } from "effect" @@ -27,7 +27,7 @@ function remove(id: SessionID) { describe("session.created event", () => { test("should emit session.created event when session is created", async () => { - await WithInstance.provide({ + await provideTestInstance({ directory: projectRoot, fn: async () => { let eventReceived = false @@ -62,7 +62,7 @@ describe("session.created event", () => { const previous = process.env.KILO_EXPERIMENTAL_WORKSPACES delete process.env.KILO_EXPERIMENTAL_WORKSPACES try { - await WithInstance.provide({ + await provideTestInstance({ directory: projectRoot, fn: async () => { const flags = AppRuntime.runSync(Effect.service(RuntimeFlags.Service)) @@ -103,7 +103,7 @@ describe("Session", () => { test("remove works without an instance", async () => { await using tmp = await tmpdir({ git: true }) - const info = await WithInstance.provide({ + const info = await provideTestInstance({ directory: tmp.path, fn: () => create({ title: "remove-without-instance" }), }) diff --git a/packages/opencode/test/kilocode/snapshot-cache.test.ts b/packages/opencode/test/kilocode/snapshot-cache.test.ts index 6fb9e86dbb1..e3e7bbba9e5 100644 --- a/packages/opencode/test/kilocode/snapshot-cache.test.ts +++ b/packages/opencode/test/kilocode/snapshot-cache.test.ts @@ -2,7 +2,7 @@ import { test, expect } from "bun:test" import { $ } from "bun" import { Effect } from "effect" import { Snapshot } from "../../src/snapshot" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Filesystem } from "../../src/util/filesystem" import * as Log from "@opencode-ai/core/util/log" import { tmpdir } from "../fixture/fixture" @@ -27,7 +27,7 @@ function run(body: (snapshot: Snapshot.Interface) => Effect.Effect) { test("diffFull returns cached result for same hash pair", async () => { await using tmp = await bootstrap() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: () => run((snapshot) => @@ -53,7 +53,7 @@ test("diffFull returns cached result for same hash pair", async () => { test("diffFull returns empty array when from === to", async () => { await using tmp = await bootstrap() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: () => run((snapshot) => @@ -70,7 +70,7 @@ test("diffFull returns empty array when from === to", async () => { test("diffFull concurrent calls for same pair share one result", async () => { await using tmp = await bootstrap() - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: () => run((snapshot) => diff --git a/packages/opencode/test/kilocode/snapshot-freeze-repro.test.ts b/packages/opencode/test/kilocode/snapshot-freeze-repro.test.ts index 4dc29a388e9..863ba232955 100644 --- a/packages/opencode/test/kilocode/snapshot-freeze-repro.test.ts +++ b/packages/opencode/test/kilocode/snapshot-freeze-repro.test.ts @@ -15,7 +15,7 @@ import { test, expect, afterEach, mock } from "bun:test" import { $ } from "bun" import { Effect, Fiber } from "effect" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance } from "../fixture/fixture" import { Server } from "../../src/server/server" import { Session } from "../../src/session/session" import { Snapshot } from "../../src/snapshot" @@ -52,7 +52,7 @@ test("pathological diffFull workload finishes quickly and does not block abort", }, }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: () => run((snapshot) => diff --git a/packages/opencode/test/kilocode/snapshot-seed.test.ts b/packages/opencode/test/kilocode/snapshot-seed.test.ts index 375324ae63f..84813cbcf7a 100644 --- a/packages/opencode/test/kilocode/snapshot-seed.test.ts +++ b/packages/opencode/test/kilocode/snapshot-seed.test.ts @@ -6,7 +6,7 @@ import { Effect } from "effect" import { Global } from "@opencode-ai/core/global" import { Hash } from "@opencode-ai/core/util/hash" import { Snapshot } from "../../src/snapshot" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { Filesystem } from "../../src/util/filesystem" import { disposeAllInstances, provideInstance, tmpdir } from "../fixture/fixture" diff --git a/packages/opencode/test/kilocode/suggestion/auto-dismiss.test.ts b/packages/opencode/test/kilocode/suggestion/auto-dismiss.test.ts index b5c95ec97ed..5318a2786ae 100644 --- a/packages/opencode/test/kilocode/suggestion/auto-dismiss.test.ts +++ b/packages/opencode/test/kilocode/suggestion/auto-dismiss.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test" import { Effect } from "effect" import { KiloSessionPromptQueue } from "../../../src/kilocode/session/prompt-queue" import { Suggestion } from "../../../src/kilocode/suggestion" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { MessageID, SessionID } from "../../../src/session/schema" import { tmpdir } from "../../fixture/fixture" @@ -13,7 +13,7 @@ describe("Suggestion.show auto-dismiss on queued followup", () => { // hasFollowup check rejects with DismissedError before any pending entry // is registered or a Shown event is published. await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const sessionID = SessionID.make("ses_auto_show") diff --git a/packages/opencode/test/kilocode/suggestion/suggestion.test.ts b/packages/opencode/test/kilocode/suggestion/suggestion.test.ts index 524cd17fa65..aeeb85d3579 100644 --- a/packages/opencode/test/kilocode/suggestion/suggestion.test.ts +++ b/packages/opencode/test/kilocode/suggestion/suggestion.test.ts @@ -3,7 +3,7 @@ import { Effect } from "effect" import { Telemetry } from "@kilocode/kilo-telemetry" import { Command } from "../../../src/command" import { localReviewUncommittedCommand } from "../../../src/kilocode/review/command" -import { WithInstance } from "../../../src/project/with-instance" +import { provideTestInstance } from "../../fixture/fixture" import { Suggestion } from "../../../src/kilocode/suggestion" import { resolvePrompt } from "../../../src/kilocode/suggestion/tool" import { SessionID } from "../../../src/session/schema" @@ -27,7 +27,7 @@ describe("suggestion", () => { test("show adds pending request with blocking flag", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const pending = Suggestion.show({ @@ -50,7 +50,7 @@ describe("suggestion", () => { test("accept resolves selected action and removes pending request", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const ask = Suggestion.show({ @@ -77,7 +77,7 @@ describe("suggestion", () => { test("accept tracks suggestion telemetry with parsed slash command", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const track = spyOn(Telemetry, "trackSuggestionAccepted") @@ -106,7 +106,7 @@ describe("suggestion", () => { test("show tracks review suggestion telemetry with parsed slash command", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const track = spyOn(Telemetry, "trackSuggestionShown") @@ -136,7 +136,7 @@ describe("suggestion", () => { test("show and accept parse local review arguments as local-review", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const shown = spyOn(Telemetry, "trackSuggestionShown") @@ -180,7 +180,7 @@ describe("suggestion", () => { test("non-review commands do not track suggestion telemetry", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const shown = spyOn(Telemetry, "trackSuggestionShown") @@ -203,7 +203,7 @@ describe("suggestion", () => { test("dismiss does not track accepted suggestion telemetry", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const shown = spyOn(Telemetry, "trackSuggestionShown") @@ -226,7 +226,7 @@ describe("suggestion", () => { test("invalid action index does not track accepted suggestion telemetry", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const shown = spyOn(Telemetry, "trackSuggestionShown") @@ -249,7 +249,7 @@ describe("suggestion", () => { test("dismiss rejects pending request and removes it", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const ask = Suggestion.show({ @@ -269,7 +269,7 @@ describe("suggestion", () => { test("dismissAll clears all pending suggestions for the target session", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { // Two suggestions for session A @@ -326,7 +326,7 @@ describe("suggestion", () => { test("dismissAll is a no-op when no suggestions exist", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { // Should not throw diff --git a/packages/opencode/test/kilocode/tool-encoding.test.ts b/packages/opencode/test/kilocode/tool-encoding.test.ts index 5202a6d6264..9ef84aac090 100644 --- a/packages/opencode/test/kilocode/tool-encoding.test.ts +++ b/packages/opencode/test/kilocode/tool-encoding.test.ts @@ -15,7 +15,7 @@ import { Bus } from "../../src/bus" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { EditTool } from "../../src/tool/edit" import { Format } from "../../src/format" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { Instruction } from "../../src/session/instruction" import { LSP } from "../../src/lsp/lsp" import { MessageID, SessionID } from "../../src/session/schema" diff --git a/packages/opencode/test/kilocode/tool-registry-indexing.test.ts b/packages/opencode/test/kilocode/tool-registry-indexing.test.ts index 90a6baf096d..4d638595d5f 100644 --- a/packages/opencode/test/kilocode/tool-registry-indexing.test.ts +++ b/packages/opencode/test/kilocode/tool-registry-indexing.test.ts @@ -9,7 +9,7 @@ import { KiloToolRegistry } from "../../src/kilocode/tool/registry" import { ModelID, ProviderID } from "../../src/provider/schema" import { ToolRegistry } from "../../src/tool/registry" import type * as Tool from "../../src/tool/tool" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" diff --git a/packages/opencode/test/kilocode/tool-task-model.test.ts b/packages/opencode/test/kilocode/tool-task-model.test.ts index 1bf091152d1..9a0ef41a76e 100644 --- a/packages/opencode/test/kilocode/tool-task-model.test.ts +++ b/packages/opencode/test/kilocode/tool-task-model.test.ts @@ -11,7 +11,7 @@ import { Config } from "../../src/config/config" import { RuntimeFlags } from "../../src/effect/runtime-flags" import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner" import { Global } from "@opencode-ai/core/global" -import { Instance } from "../../src/project/instance" +import { Instance } from "../../src/kilocode/instance" import { Session } from "../../src/session/session" import { MessageV2 } from "../../src/session/message-v2" import type { SessionPrompt } from "../../src/session/prompt" diff --git a/packages/opencode/test/lsp/client.test.ts b/packages/opencode/test/lsp/client.test.ts index 7d9f5a71555..93844d942fc 100644 --- a/packages/opencode/test/lsp/client.test.ts +++ b/packages/opencode/test/lsp/client.test.ts @@ -1,11 +1,9 @@ import { beforeEach, describe, expect, test } from "bun:test" import path from "path" import { pathToFileURL } from "url" -import { tmpdir } from "../fixture/fixture" +import { tmpdir, withTestInstance } from "../fixture/fixture" import { LSPClient } from "@/lsp/client" import * as LSPServer from "@/lsp/server" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" import * as Log from "@opencode-ai/core/util/log" function spawnFakeServer() { @@ -26,14 +24,15 @@ describe("LSPClient interop", () => { test("handles workspace/workspaceFolders request", async () => { const handle = spawnFakeServer() as any - const client = await WithInstance.provide({ + const client = await withTestInstance({ directory: process.cwd(), - fn: () => + fn: (ctx) => LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: process.cwd(), directory: process.cwd(), + instance: ctx, }), }) @@ -49,14 +48,15 @@ describe("LSPClient interop", () => { test("handles client/registerCapability request", async () => { const handle = spawnFakeServer() as any - const client = await WithInstance.provide({ + const client = await withTestInstance({ directory: process.cwd(), - fn: () => + fn: (ctx) => LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: process.cwd(), directory: process.cwd(), + instance: ctx, }), }) @@ -72,14 +72,15 @@ describe("LSPClient interop", () => { test("handles client/unregisterCapability request", async () => { const handle = spawnFakeServer() as any - const client = await WithInstance.provide({ + const client = await withTestInstance({ directory: process.cwd(), - fn: () => + fn: (ctx) => LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: process.cwd(), directory: process.cwd(), + instance: ctx, }), }) @@ -95,14 +96,15 @@ describe("LSPClient interop", () => { test("initialize does not overclaim unsupported diagnostics capabilities", async () => { const handle = spawnFakeServer() as any - const client = await WithInstance.provide({ + const client = await withTestInstance({ directory: process.cwd(), - fn: () => + fn: (ctx) => LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: process.cwd(), directory: process.cwd(), + instance: ctx, }), }) @@ -122,9 +124,9 @@ describe("LSPClient interop", () => { gamma: true, } - const client = await WithInstance.provide({ + const client = await withTestInstance({ directory: process.cwd(), - fn: () => + fn: (ctx) => LSPClient.create({ serverID: "fake", server: { @@ -133,6 +135,7 @@ describe("LSPClient interop", () => { }, root: process.cwd(), directory: process.cwd(), + instance: ctx, }), }) @@ -151,14 +154,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.ts") await Bun.write(file, "first\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) await client.notify.open({ path: file }) @@ -194,14 +198,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.ts") await Bun.write(file, "const x = 1\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) const version = await client.notify.open({ path: file }) @@ -240,14 +245,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.ts") await Bun.write(file, "const x = 1\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) const version = await client.notify.open({ path: file }) @@ -287,14 +293,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.cs") await Bun.write(file, "class C {}\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) await client.connection.sendRequest("test/configure-pull-diagnostics", { @@ -335,14 +342,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.cs") await Bun.write(file, "class C {}\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) await client.connection.sendRequest("test/configure-pull-diagnostics", { @@ -388,14 +396,15 @@ describe("LSPClient interop", () => { await Bun.write(file, "class C {}\n") await Bun.write(related, "class D {}\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) await client.connection.sendRequest("test/configure-pull-diagnostics", { @@ -452,14 +461,15 @@ describe("LSPClient interop", () => { const file = path.join(tmp.path, "client.cs") await Bun.write(file, "class C {}\n") - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { const client = await LSPClient.create({ serverID: "fake", server: handle as unknown as LSPServer.Handle, root: tmp.path, directory: tmp.path, + instance: ctx, }) await client.connection.sendRequest("test/configure-pull-diagnostics", { diff --git a/packages/opencode/test/lsp/index.test.ts b/packages/opencode/test/lsp/index.test.ts index 8520afae21e..be76ab43d39 100644 --- a/packages/opencode/test/lsp/index.test.ts +++ b/packages/opencode/test/lsp/index.test.ts @@ -1,17 +1,17 @@ import { describe, expect, spyOn, test } from "bun:test" import path from "path" import fs from "fs/promises" -import { Effect, Layer } from "effect" +import { Deferred, Effect, Layer } from "effect" +import { Bus } from "@/bus" import { Config } from "@/config/config" import { RuntimeFlags } from "@/effect/runtime-flags" import { LSP } from "@/lsp/lsp" import * as LSPServer from "@/lsp/server" import * as launch from "../../src/lsp/launch" // kilocode_change - spy on spawn import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { provideTmpdirInstance, tmpdir } from "../fixture/fixture" -import { testEffect } from "../lib/effect" -import { type InstanceContext } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { provideTestInstance, provideTmpdirInstance, tmpdir } from "../fixture/fixture" +import { awaitWithTimeout, testEffect } from "../lib/effect" +import { type InstanceContext } from "../../src/project/instance-context" import { Flag } from "@opencode-ai/core/flag/flag" // kilocode_change import { TsCheck } from "../../src/kilocode/ts-check" // kilocode_change @@ -26,6 +26,13 @@ const experimentalTyIt = testEffect( CrossSpawnSpawner.defaultLayer, ), ) +const fakeServerPath = path.join(__dirname, "../fixture/lsp/fake-lsp-server.js") +const disabledDownloadIt = testEffect( + Layer.mergeAll( + LSP.layer.pipe(Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.layer({ disableLspDownload: true }))), + CrossSpawnSpawner.defaultLayer, + ), +) describe("lsp.spawn", () => { it.live("does not spawn builtin LSP for files outside instance", () => @@ -107,6 +114,35 @@ describe("lsp.spawn", () => { ), ) + it.live("publishes lsp.updated after custom LSP initialization", () => + provideTmpdirInstance( + (dir) => + Effect.gen(function* () { + const lsp = yield* LSP.Service + const updated = yield* Deferred.make() + const unsubscribe = Bus.subscribe(LSP.Event.Updated, () => + Effect.runSync(Deferred.succeed(updated, undefined)), + ) + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)) + + const file = path.join(dir, "sample.repro") + yield* Effect.promise(() => Bun.write(file, "sample\n")) + yield* lsp.touchFile(file) + yield* awaitWithTimeout(Deferred.await(updated), "lsp.updated event was not published") + }), + { + config: { + lsp: { + fake: { + command: [process.execPath, fakeServerPath], + extensions: [".repro"], + }, + }, + }, + }, + ), + ) + experimentalToolIt.live("would spawn builtin LSP for files inside instance when config object is provided", () => provideTmpdirInstance( (dir) => @@ -149,7 +185,7 @@ describe("lsp.spawn", () => { const tsgoSpy = spyOn(TsCheck, "native_tsgo").mockResolvedValue("/fake/tsgo") try { - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const result = await LSPServer.Typescript.spawn(tmp.path, fakeCtx, fakeFlags) @@ -230,4 +266,28 @@ describe("lsp.spawn", () => { { config: { lsp: true } }, ), ) + + disabledDownloadIt.live("passes disableLspDownload to builtin LSP spawn", () => + provideTmpdirInstance( + (dir) => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.py"), + line: 0, + character: 0, + }) + expect(pyright).toHaveBeenCalledTimes(1) + expect(pyright.mock.calls[0]?.[2]).toMatchObject({ disableLspDownload: true }) + } finally { + pyright.mockRestore() + } + }), + ), + { config: { lsp: true } }, + ), + ) }) diff --git a/packages/opencode/test/plugin/workspace-adapter.test.ts b/packages/opencode/test/plugin/workspace-adapter.test.ts index 41dbf53445d..b4b40fe7677 100644 --- a/packages/opencode/test/plugin/workspace-adapter.test.ts +++ b/packages/opencode/test/plugin/workspace-adapter.test.ts @@ -15,10 +15,10 @@ import { RuntimeFlags } from "../../src/effect/runtime-flags" import { Workspace } from "../../src/control-plane/workspace" import { Plugin } from "../../src/plugin/index" import { InstanceBootstrap } from "../../src/project/bootstrap-service" -import { Instance } from "../../src/project/instance" import { InstanceStore } from "../../src/project/instance-store" import { Project } from "../../src/project/project" import { Vcs } from "../../src/project/vcs" +import { InstanceState } from "../../src/effect/instance-state" import { Session } from "../../src/session/session" import { SessionPrompt } from "../../src/session/prompt" import { SyncEvent } from "../../src/sync" @@ -116,11 +116,12 @@ describe("plugin.workspace", () => { const plugin = yield* Plugin.Service yield* plugin.init() const workspace = yield* Workspace.Service + const ctx = yield* InstanceState.context const info = yield* workspace.create({ type, branch: null, extra: { key: "value" }, - projectID: Instance.project.id, + projectID: ctx.project.id, }) expect(info.type).toBe(type) diff --git a/packages/opencode/test/project/instance-bootstrap.test.ts b/packages/opencode/test/project/instance-bootstrap.test.ts index 4be2a76113d..c5b18cc5b8d 100644 --- a/packages/opencode/test/project/instance-bootstrap.test.ts +++ b/packages/opencode/test/project/instance-bootstrap.test.ts @@ -3,12 +3,13 @@ import { existsSync } from "node:fs" import path from "node:path" import { pathToFileURL } from "node:url" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Effect, Layer } from "effect" +import { Cause, Effect, Exit, Fiber, Layer } from "effect" import { bootstrap as cliBootstrap } from "../../src/cli/bootstrap" import { InstanceLayer } from "../../src/project/instance-layer" import { InstanceStore } from "../../src/project/instance-store" import { disposeAllInstances, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { waitGlobalBusEvent } from "../server/global-bus" const it = testEffect(Layer.mergeAll(InstanceLayer.layer, CrossSpawnSpawner.defaultLayer)) @@ -54,6 +55,13 @@ const bootstrapFixture = Effect.gen(function* () { return { directory: dir, marker } }) +function waitDisposed(directory: string) { + return waitGlobalBusEvent({ + message: "timed out waiting for CLI bootstrap instance disposal", + predicate: (event) => event.payload.type === "server.instance.disposed" && event.directory === directory, + }) +} + it.live("InstanceStore.provide runs InstanceBootstrap before effect", () => Effect.gen(function* () { const tmp = yield* bootstrapFixture @@ -75,6 +83,21 @@ it.live("CLI bootstrap runs InstanceBootstrap before callback", () => }), ) +it.live("CLI bootstrap disposes the instance when the callback rejects", () => + Effect.gen(function* () { + const tmp = yield* bootstrapFixture + const disposed = yield* waitDisposed(tmp.directory).pipe(Effect.forkScoped) + + const exit = yield* Effect.promise(() => + cliBootstrap(tmp.directory, async () => Promise.reject(new Error("boom"))), + ).pipe(Effect.exit) + + expect(Exit.isFailure(exit)).toBe(true) + if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toMatchObject({ message: "boom" }) + yield* Fiber.join(disposed) + }), +) + it.live("InstanceStore.reload runs InstanceBootstrap", () => Effect.gen(function* () { const tmp = yield* bootstrapFixture diff --git a/packages/opencode/test/project/instance.test.ts b/packages/opencode/test/project/instance.test.ts index 5d5337d584c..ae026dc4c95 100644 --- a/packages/opencode/test/project/instance.test.ts +++ b/packages/opencode/test/project/instance.test.ts @@ -4,9 +4,8 @@ import { Deferred, Effect, Fiber, Layer } from "effect" import { InstanceRef } from "../../src/effect/instance-ref" import { registerDisposer } from "../../src/effect/instance-registry" import { InstanceBootstrap } from "../../src/project/bootstrap-service" -import { Instance } from "../../src/project/instance" import { InstanceStore } from "../../src/project/instance-store" -import { TestInstance, tmpdirScoped } from "../fixture/fixture" +import { tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" let bootstrapRun: Effect.Effect = Effect.void @@ -37,7 +36,7 @@ const registerDisposerScoped = (disposer: (directory: string) => Promise) ) describe("InstanceStore", () => { - it.live("loads instance context without installing ALS for the caller", () => + it.live("loads instance context", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const store = yield* InstanceStore.Service @@ -45,7 +44,6 @@ describe("InstanceStore", () => { expect(ctx.directory).toBe(dir) expect(ctx.worktree).toBe(dir) - expect(() => Instance.current).toThrow() }), ) @@ -63,7 +61,6 @@ describe("InstanceStore", () => { yield* store.load({ directory: dir }) expect(initializedDirectory).toBe(dir) - expect(() => Instance.current).toThrow() }), ) @@ -246,34 +243,17 @@ describe("InstanceStore", () => { }), ) - it.instance( - "provides legacy Promise callers with instance ALS", - () => - Effect.gen(function* () { - const test = yield* TestInstance - const ctx = yield* InstanceRef - if (!ctx) throw new Error("InstanceRef not provided") - - const directory = yield* Effect.promise(() => Promise.resolve(Instance.restore(ctx, () => Instance.directory))) - - expect(directory).toBe(test.directory) - expect(() => Instance.current).toThrow() - }), - { git: true }, - ) - - // kilocode_change - InstanceStore.boot wraps bootstrap.run in the Instance ALS so + // kilocode_change - InstanceStore.boot provides InstanceRef to bootstrap.run so // KilocodeBootstrap (and anything it forkDetaches, e.g. KiloIndexing.init) can read - // Instance.directory. Upstream runs bootstrap without the ALS; this regression test - // pins the Kilo contract. - it.live("installs Instance ALS around bootstrap for Kilo bootstrap compatibility", () => + // the current directory. This regression test pins the Kilo contract. + it.live("provides InstanceRef during bootstrap for Kilo bootstrap compatibility", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const store = yield* InstanceStore.Service let directoryDuringBootstrap: string | undefined - bootstrapRun = Effect.sync(() => { - directoryDuringBootstrap = Instance.directory + bootstrapRun = Effect.gen(function* () { + directoryDuringBootstrap = (yield* InstanceRef)?.directory }) yield* store.load({ directory: dir }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 308e2f957b4..688b818beed 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -5,7 +5,7 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect" import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import { Git } from "../../src/git" -import { Instance } from "../../src/project/instance" +import { InstanceRef } from "../../src/effect/instance-ref" import { InstanceRuntime } from "../../src/project/instance-runtime" import { Worktree } from "../../src/worktree" import { disposeAllInstances, provideInstance, TestInstance } from "../fixture/fixture" @@ -41,7 +41,10 @@ const waitReady = Effect.fn("WorktreeTest.waitReady")(function* () { const removeCreatedWorktree = (directory: string) => Effect.gen(function* () { const svc = yield* Worktree.Service - const ctx = yield* Effect.sync(() => Instance.current).pipe(provideInstance(directory)) + const ctx = yield* Effect.gen(function* () { + return yield* InstanceRef + }).pipe(provideInstance(directory)) + if (!ctx) return yield* Effect.die(new Error("missing test instance")) yield* Effect.promise(() => InstanceRuntime.disposeInstance(ctx)) const ok = yield* svc.remove({ directory }) if (!ok) return yield* Effect.fail(new Error(`failed to remove worktree ${directory}`)) diff --git a/packages/opencode/test/provider/amazon-bedrock.test.ts b/packages/opencode/test/provider/amazon-bedrock.test.ts index c75231d44da..82f1a86a99f 100644 --- a/packages/opencode/test/provider/amazon-bedrock.test.ts +++ b/packages/opencode/test/provider/amazon-bedrock.test.ts @@ -1,28 +1,47 @@ -import { test, expect, describe } from "bun:test" +import { afterEach, test, expect, describe } from "bun:test" import path from "path" import { unlink } from "fs/promises" import { ProviderID } from "../../src/provider/schema" -import { tmpdir } from "../fixture/fixture" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import { disposeAllInstances, tmpdir, withTestInstance } from "../fixture/fixture" +import type { InstanceContext } from "../../src/project/instance-context" import { Provider } from "@/provider/provider" import { Env } from "../../src/env" import { Global } from "@opencode-ai/core/global" import { Filesystem } from "@/util/filesystem" import { Effect } from "effect" import { AppRuntime } from "../../src/effect/app-runtime" +import { InstanceRef } from "../../src/effect/instance-ref" import { makeRuntime } from "../../src/effect/run-service" const env = makeRuntime(Env.Service, Env.defaultLayer) -const set = (k: string, v: string) => env.runSync((svc) => svc.set(k, v)) +const originalEnv = new Map() -async function list() { +function rememberEnv(k: string) { + if (!originalEnv.has(k)) originalEnv.set(k, process.env[k]) +} + +const set = (ctx: InstanceContext, k: string, v: string) => { + rememberEnv(k) + process.env[k] = v + return env.runSync((svc) => svc.set(k, v).pipe(Effect.provideService(InstanceRef, ctx))) +} + +afterEach(async () => { + for (const [key, value] of originalEnv) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + originalEnv.clear() + await disposeAllInstances() +}) + +async function list(ctx: InstanceContext) { return AppRuntime.runPromise( Effect.gen(function* () { const provider = yield* Provider.Service return yield* provider.list() - }), + }).pipe(Effect.provideService(InstanceRef, ctx)), ) } @@ -44,12 +63,12 @@ test("Bedrock: config region takes precedence over AWS_REGION env var", async () ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_REGION", "us-east-1") - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_REGION", "us-east-1") + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") }, @@ -67,12 +86,12 @@ test("Bedrock: falls back to AWS_REGION env var when no config region", async () ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_REGION", "eu-west-1") - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_REGION", "eu-west-1") + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") }, @@ -120,13 +139,13 @@ test("Bedrock: loads when bearer token from auth.json is present", async () => { }), ) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "") - set("AWS_ACCESS_KEY_ID", "") - set("AWS_BEARER_TOKEN_BEDROCK", "") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "") + set(ctx, "AWS_ACCESS_KEY_ID", "") + set(ctx, "AWS_BEARER_TOKEN_BEDROCK", "") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") }, @@ -164,12 +183,12 @@ test("Bedrock: config profile takes precedence over AWS_PROFILE env var", async ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - set("AWS_ACCESS_KEY_ID", "test-key-id") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + set(ctx, "AWS_ACCESS_KEY_ID", "test-key-id") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.region).toBe("us-east-1") }, @@ -194,11 +213,11 @@ test("Bedrock: includes custom endpoint in options when specified", async () => ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.endpoint).toBe( "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com", @@ -225,14 +244,14 @@ test("Bedrock: autoloads when AWS_WEB_IDENTITY_TOKEN_FILE is present", async () ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_WEB_IDENTITY_TOKEN_FILE", "/var/run/secrets/eks.amazonaws.com/serviceaccount/token") - set("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/my-eks-role") - set("AWS_PROFILE", "") - set("AWS_ACCESS_KEY_ID", "") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_WEB_IDENTITY_TOKEN_FILE", "/var/run/secrets/eks.amazonaws.com/serviceaccount/token") + set(ctx, "AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/my-eks-role") + set(ctx, "AWS_PROFILE", "") + set(ctx, "AWS_ACCESS_KEY_ID", "") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].options?.region).toBe("us-east-1") }, @@ -266,11 +285,11 @@ test("Bedrock: model with us. prefix should not be double-prefixed", async () => ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() // The model should exist with the us. prefix expect(providers[ProviderID.amazonBedrock].models["us.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() @@ -301,11 +320,11 @@ test("Bedrock: model with global. prefix should not be prefixed", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].models["global.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() }, @@ -335,11 +354,11 @@ test("Bedrock: model with eu. prefix should not be double-prefixed", async () => ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() expect(providers[ProviderID.amazonBedrock].models["eu.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() }, @@ -369,11 +388,11 @@ test("Bedrock: model without prefix in US region should get us. prefix added", a ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("AWS_PROFILE", "default") - const providers = await list() + fn: async (ctx) => { + set(ctx, "AWS_PROFILE", "default") + const providers = await list(ctx) expect(providers[ProviderID.amazonBedrock]).toBeDefined() // Non-prefixed model should still be registered expect(providers[ProviderID.amazonBedrock].models["anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() diff --git a/packages/opencode/test/provider/gitlab-duo.test.ts b/packages/opencode/test/provider/gitlab-duo.test.ts index 8bb3b96347e..4ac62cf69de 100644 --- a/packages/opencode/test/provider/gitlab-duo.test.ts +++ b/packages/opencode/test/provider/gitlab-duo.test.ts @@ -7,9 +7,7 @@ export {} // import path from "path" // import { ProviderID, ModelID } from "../../src/provider/schema" -// import { tmpdir } from "../fixture/fixture" -// import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +// import { tmpdir, withTestInstance } from "../fixture/fixture" // import { Provider } from "@/provider/provider" // import { Env } from "../../src/env" // import { Global } from "@opencode-ai/core/global" @@ -26,7 +24,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-gitlab-token") @@ -57,7 +55,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -96,7 +94,7 @@ import { WithInstance } from "../../src/project/with-instance" // }), // ) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "") @@ -131,7 +129,7 @@ import { WithInstance } from "../../src/project/with-instance" // }), // ) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "") @@ -163,7 +161,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_INSTANCE_URL", "https://gitlab.company.internal") @@ -194,7 +192,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "env-token") @@ -217,7 +215,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -253,7 +251,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -278,7 +276,7 @@ import { WithInstance } from "../../src/project/with-instance" // ) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -302,7 +300,7 @@ import { WithInstance } from "../../src/project/with-instance" // await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://opencode.ai/config.json" })) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -350,7 +348,7 @@ import { WithInstance } from "../../src/project/with-instance" // await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://opencode.ai/config.json" })) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -373,7 +371,7 @@ import { WithInstance } from "../../src/project/with-instance" // await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://opencode.ai/config.json" })) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") @@ -397,7 +395,7 @@ import { WithInstance } from "../../src/project/with-instance" // await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ $schema: "https://opencode.ai/config.json" })) // }, // }) -// await WithInstance.provide({ +// await withTestInstance({ // directory: tmp.path, // init: async () => { // Env.set("GITLAB_TOKEN", "test-token") diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 9cf1af1bb85..656cbb2c259 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -1,12 +1,10 @@ -import { test, expect } from "bun:test" +import { afterEach, test, expect } from "bun:test" import { mkdir, unlink } from "fs/promises" import path from "path" -import { tmpdir } from "../fixture/fixture" +import { disposeAllInstances, tmpdir, withTestInstance } from "../fixture/fixture" import { Global } from "@opencode-ai/core/global" -import { Instance } from "../../src/project/instance" -import { InstanceRuntime } from "../../src/project/instance-runtime" -import { WithInstance } from "../../src/project/with-instance" +import type { InstanceContext } from "../../src/project/instance-context" import { Plugin } from "../../src/plugin/index" import { ModelsDev } from "@opencode-ai/core/models" import { Provider } from "@/provider/provider" @@ -15,6 +13,7 @@ import { Filesystem } from "@/util/filesystem" import { Env } from "../../src/env" import { Effect, Layer } from "effect" import { AppRuntime } from "../../src/effect/app-runtime" +import { InstanceRef } from "../../src/effect/instance-ref" import { makeRuntime } from "../../src/effect/run-service" import { testEffect } from "../lib/effect" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -23,8 +22,31 @@ import { Auth } from "@/auth" import { RuntimeFlags } from "@/effect/runtime-flags" const env = makeRuntime(Env.Service, Env.defaultLayer) -const set = (k: string, v: string) => env.runSync((svc) => svc.set(k, v)) -const remove = (k: string) => env.runSync((svc) => svc.remove(k)) +const originalEnv = new Map() + +function rememberEnv(k: string) { + if (!originalEnv.has(k)) originalEnv.set(k, process.env[k]) +} + +const set = (ctx: InstanceContext, k: string, v: string) => { + rememberEnv(k) + process.env[k] = v + return env.runSync((svc) => svc.set(k, v).pipe(Effect.provideService(InstanceRef, ctx))) +} +const remove = (ctx: InstanceContext, k: string) => { + rememberEnv(k) + delete process.env[k] + return env.runSync((svc) => svc.remove(k).pipe(Effect.provideService(InstanceRef, ctx))) +} + +afterEach(async () => { + for (const [key, value] of originalEnv) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + originalEnv.clear() + await disposeAllInstances() +}) const providerLayer = (flags: Partial = {}) => Provider.layer.pipe( @@ -37,41 +59,41 @@ const providerLayer = (flags: Partial = {}) => Layer.provide(RuntimeFlags.layer(flags)), ) -async function run(fn: (provider: Provider.Interface) => Effect.Effect) { +async function run(ctx: InstanceContext, fn: (provider: Provider.Interface) => Effect.Effect) { return AppRuntime.runPromise( Effect.gen(function* () { const provider = yield* Provider.Service return yield* fn(provider) - }), + }).pipe(Effect.provideService(InstanceRef, ctx)), ) } -async function list() { - return run((provider) => provider.list()) +async function list(ctx: InstanceContext) { + return run(ctx, (provider) => provider.list()) } -async function getProvider(providerID: ProviderID) { - return run((provider) => provider.getProvider(providerID)) +async function getProvider(providerID: ProviderID, ctx: InstanceContext) { + return run(ctx, (provider) => provider.getProvider(providerID)) } -async function getModel(providerID: ProviderID, modelID: ModelID) { - return run((provider) => provider.getModel(providerID, modelID)) +async function getModel(providerID: ProviderID, modelID: ModelID, ctx: InstanceContext) { + return run(ctx, (provider) => provider.getModel(providerID, modelID)) } -async function getLanguage(model: Provider.Model) { - return run((provider) => provider.getLanguage(model)) +async function getLanguage(model: Provider.Model, ctx: InstanceContext) { + return run(ctx, (provider) => provider.getLanguage(model)) } -async function closest(providerID: ProviderID, query: string[]) { - return run((provider) => provider.closest(providerID, query)) +async function closest(providerID: ProviderID, query: string[], ctx: InstanceContext) { + return run(ctx, (provider) => provider.closest(providerID, query)) } -async function getSmallModel(providerID: ProviderID) { - return run((provider) => provider.getSmallModel(providerID)) +async function getSmallModel(providerID: ProviderID, ctx: InstanceContext) { + return run(ctx, (provider) => provider.getSmallModel(providerID)) } -async function defaultModel() { - return run((provider) => provider.defaultModel()) +async function defaultModel(ctx: InstanceContext) { + return run(ctx, (provider) => provider.defaultModel()) } async function markPluginDependenciesReady(dir: string) { @@ -124,11 +146,11 @@ test("provider loaded from env variable", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() // Provider should retain its connection source even if custom loaders // merge additional options. @@ -156,10 +178,10 @@ test("provider loaded from config with apiKey option", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() }, }) @@ -177,11 +199,11 @@ test("disabled_providers excludes provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeUndefined() }, }) @@ -199,12 +221,12 @@ test("enabled_providers restricts to only listed providers", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - set("OPENAI_API_KEY", "test-openai-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + set(ctx, "OPENAI_API_KEY", "test-openai-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() expect(providers[ProviderID.openai]).toBeUndefined() }, @@ -227,11 +249,11 @@ test("model whitelist filters models for provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() const models = Object.keys(providers[ProviderID.anthropic].models) expect(models).toContain("claude-sonnet-4-20250514") @@ -256,11 +278,11 @@ test("model blacklist excludes specific models", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() const models = Object.keys(providers[ProviderID.anthropic].models) expect(models).not.toContain("claude-sonnet-4-20250514") @@ -289,11 +311,11 @@ test("custom model alias via config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() expect(providers[ProviderID.anthropic].models["my-alias"]).toBeDefined() expect(providers[ProviderID.anthropic].models["my-alias"].name).toBe("My Custom Alias") @@ -333,10 +355,10 @@ test("custom provider with npm package", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("custom-provider")]).toBeDefined() expect(providers[ProviderID.make("custom-provider")].name).toBe("Custom Provider") expect(providers[ProviderID.make("custom-provider")].models["custom-model"]).toBeDefined() @@ -410,10 +432,10 @@ test("custom DeepSeek openai-compatible model defaults interleaved reasoning fie ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const provider = providers[ProviderID.make("custom-provider")] expect(provider.models["deepseek-r1"].capabilities.interleaved).toEqual({ field: "reasoning_content" }) expect(provider.models["deepseek-details"].capabilities.interleaved).toEqual({ field: "reasoning_details" }) @@ -444,11 +466,11 @@ test("env variable takes precedence, config merges options", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "env-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "env-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() // Config options should be merged expect(providers[ProviderID.anthropic].options.timeout).toBe(60000) @@ -468,15 +490,15 @@ test("getModel returns model for valid provider/model", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514"), ctx) expect(model).toBeDefined() expect(String(model.providerID)).toBe("anthropic") expect(String(model.id)).toBe("claude-sonnet-4-20250514") - const language = await getLanguage(model) + const language = await getLanguage(model, ctx) expect(language).toBeDefined() }, }) @@ -493,11 +515,11 @@ test("getModel throws ModelNotFoundError for invalid model", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - expect(getModel(ProviderID.anthropic, ModelID.make("nonexistent-model"))).rejects.toThrow() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + expect(getModel(ProviderID.anthropic, ModelID.make("nonexistent-model"), ctx)).rejects.toThrow() }, }) }) @@ -513,10 +535,10 @@ test("getModel throws ModelNotFoundError for invalid provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - expect(getModel(ProviderID.make("nonexistent-provider"), ModelID.make("some-model"))).rejects.toThrow() + fn: async (ctx) => { + expect(getModel(ProviderID.make("nonexistent-provider"), ModelID.make("some-model"), ctx)).rejects.toThrow() }, }) }) @@ -544,11 +566,11 @@ test("defaultModel returns first available model when no config set", async () = ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model = await defaultModel() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model = await defaultModel(ctx) expect(model.providerID).toBeDefined() expect(model.modelID).toBeDefined() }, @@ -567,11 +589,11 @@ test("defaultModel respects config model setting", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model = await defaultModel() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model = await defaultModel(ctx) expect(String(model.providerID)).toBe("anthropic") expect(String(model.modelID)).toBe("claude-sonnet-4-20250514") }, @@ -700,11 +722,11 @@ test("closest finds model by partial match", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const result = await closest(ProviderID.anthropic, ["sonnet-4"]) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const result = await closest(ProviderID.anthropic, ["sonnet-4"], ctx) expect(result).toBeDefined() expect(String(result?.providerID)).toBe("anthropic") expect(String(result?.modelID)).toContain("sonnet-4") @@ -723,10 +745,10 @@ test("closest returns undefined for nonexistent provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const result = await closest(ProviderID.make("nonexistent"), ["model"]) + fn: async (ctx) => { + const result = await closest(ProviderID.make("nonexistent"), ["model"], ctx) expect(result).toBeUndefined() }, }) @@ -753,14 +775,14 @@ test("getModel uses realIdByKey for aliased models", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic].models["my-sonnet"]).toBeDefined() - const model = await getModel(ProviderID.anthropic, ModelID.make("my-sonnet")) + const model = await getModel(ProviderID.anthropic, ModelID.make("my-sonnet"), ctx) expect(model).toBeDefined() expect(String(model.id)).toBe("my-sonnet") expect(model.name).toBe("My Sonnet Alias") @@ -797,10 +819,10 @@ test("provider api field sets model api.url", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) // api field is stored on model.api.url, used by getSDK to set baseURL expect(providers[ProviderID.make("custom-api")].models["model-1"].api.url).toBe("https://api.example.com/v1") }, @@ -837,10 +859,10 @@ test("explicit baseURL overrides api field", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("custom-api")].options.baseURL).toBe("https://custom.override.com/v1") }, }) @@ -866,11 +888,11 @@ test("model inherits properties from existing database model", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.name).toBe("Custom Name for Sonnet") expect(model.capabilities.toolcall).toBe(true) @@ -892,11 +914,11 @@ test("disabled_providers prevents loading even with env var", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("OPENAI_API_KEY", "test-openai-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "OPENAI_API_KEY", "test-openai-key") + const providers = await list(ctx) expect(providers[ProviderID.openai]).toBeUndefined() }, }) @@ -914,12 +936,12 @@ test("enabled_providers with empty array allows no providers", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - set("OPENAI_API_KEY", "test-openai-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + set(ctx, "OPENAI_API_KEY", "test-openai-key") + const providers = await list(ctx) expect(Object.keys(providers).length).toBe(0) }, }) @@ -942,11 +964,11 @@ test("whitelist and blacklist can be combined", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() const models = Object.keys(providers[ProviderID.anthropic].models) expect(models).toContain("claude-sonnet-4-20250514") @@ -982,10 +1004,10 @@ test("model modalities default correctly", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const model = providers[ProviderID.make("test-provider")].models["test-model"] expect(model.capabilities.input.text).toBe(true) expect(model.capabilities.output.text).toBe(true) @@ -1025,10 +1047,10 @@ test("model with custom cost values", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const model = providers[ProviderID.make("test-provider")].models["test-model"] expect(model.cost.input).toBe(5) expect(model.cost.output).toBe(15) @@ -1049,11 +1071,11 @@ test("getSmallModel returns appropriate small model", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model = await getSmallModel(ProviderID.anthropic) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model = await getSmallModel(ProviderID.anthropic, ctx) expect(model).toBeDefined() expect(model?.id).toContain("haiku") }, @@ -1072,11 +1094,11 @@ test("getSmallModel respects config small_model override", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model = await getSmallModel(ProviderID.anthropic) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model = await getSmallModel(ProviderID.anthropic, ctx) expect(model).toBeDefined() expect(String(model?.providerID)).toBe("anthropic") expect(String(model?.id)).toBe("claude-sonnet-4-20250514") @@ -1096,11 +1118,11 @@ test("getSmallModel ignores invalid config small_model", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - expect(await getSmallModel(ProviderID.anthropic)).toBeUndefined() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + expect(await getSmallModel(ProviderID.anthropic, ctx)).toBeUndefined() }, }) }) @@ -1139,12 +1161,12 @@ test("multiple providers can be configured simultaneously", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-anthropic-key") - set("OPENAI_API_KEY", "test-openai-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-anthropic-key") + set(ctx, "OPENAI_API_KEY", "test-openai-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() expect(providers[ProviderID.openai]).toBeDefined() expect(providers[ProviderID.anthropic].options.timeout).toBe(30000) @@ -1182,10 +1204,10 @@ test("provider with custom npm package", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("local-llm")]).toBeDefined() expect(providers[ProviderID.make("local-llm")].models["llama-3"].api.npm).toBe("@ai-sdk/openai-compatible") expect(providers[ProviderID.make("local-llm")].options.baseURL).toBe("http://localhost:11434/v1") @@ -1216,11 +1238,11 @@ test("model alias name defaults to alias key when id differs", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic].models["sonnet"].name).toBe("sonnet") }, }) @@ -1254,11 +1276,11 @@ test("provider with multiple env var options only includes apiKey when single en ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("MULTI_ENV_KEY_1", "test-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "MULTI_ENV_KEY_1", "test-key") + const providers = await list(ctx) expect(providers[ProviderID.make("multi-env")]).toBeDefined() // When multiple env options exist, key should NOT be auto-set expect(providers[ProviderID.make("multi-env")].key).toBeUndefined() @@ -1294,11 +1316,11 @@ test("provider with single env var includes apiKey automatically", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("SINGLE_ENV_KEY", "my-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "SINGLE_ENV_KEY", "my-api-key") + const providers = await list(ctx) expect(providers[ProviderID.make("single-env")]).toBeDefined() // Single env option should auto-set key expect(providers[ProviderID.make("single-env")].key).toBe("my-api-key") @@ -1329,11 +1351,11 @@ test("model cost overrides existing cost values", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.cost.input).toBe(999) expect(model.cost.output).toBe(888) @@ -1377,10 +1399,10 @@ test("completely new provider not in database can be configured", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("brand-new-provider")]).toBeDefined() expect(providers[ProviderID.make("brand-new-provider")].name).toBe("Brand New") const model = providers[ProviderID.make("brand-new-provider")].models["new-model"] @@ -1406,13 +1428,13 @@ test("disabled_providers and enabled_providers interaction", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-anthropic") - set("OPENAI_API_KEY", "test-openai") - set("GOOGLE_GENERATIVE_AI_API_KEY", "test-google") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-anthropic") + set(ctx, "OPENAI_API_KEY", "test-openai") + set(ctx, "GOOGLE_GENERATIVE_AI_API_KEY", "test-google") + const providers = await list(ctx) // anthropic: in enabled, not in disabled = allowed expect(providers[ProviderID.anthropic]).toBeDefined() // openai: in enabled, but also in disabled = NOT allowed @@ -1449,10 +1471,10 @@ test("model with tool_call false", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("no-tools")].models["basic-model"].capabilities.toolcall).toBe(false) }, }) @@ -1484,10 +1506,10 @@ test("model defaults tool_call to true when not specified", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("default-tools")].models["model"].capabilities.toolcall).toBe(true) }, }) @@ -1523,10 +1545,10 @@ test("model headers are preserved", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const model = providers[ProviderID.make("headers-provider")].models["model"] expect(model.headers).toEqual({ "X-Custom-Header": "custom-value", @@ -1562,12 +1584,12 @@ test("provider env fallback - second env var used if first missing", async () => ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { + fn: async (ctx) => { // Only set fallback, not primary - set("FALLBACK_KEY", "fallback-api-key") - const providers = await list() + set(ctx, "FALLBACK_KEY", "fallback-api-key") + const providers = await list(ctx) // Provider should load because fallback env var is set expect(providers[ProviderID.make("fallback-env")]).toBeDefined() }, @@ -1585,12 +1607,12 @@ test("getModel returns consistent results", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const model1 = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) - const model2 = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const model1 = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514"), ctx) + const model2 = await getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514"), ctx) expect(model1.providerID).toEqual(model2.providerID) expect(model1.id).toEqual(model2.id) expect(model1).toEqual(model2) @@ -1624,10 +1646,10 @@ test("provider name defaults to id when not in database", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("my-custom-id")].name).toBe("my-custom-id") }, }) @@ -1644,12 +1666,12 @@ test("ModelNotFoundError includes suggestions for typos", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") try { - await getModel(ProviderID.anthropic, ModelID.make("claude-sonet-4")) // typo: sonet instead of sonnet + await getModel(ProviderID.anthropic, ModelID.make("claude-sonet-4"), ctx) // typo: sonet instead of sonnet expect(true).toBe(false) // Should not reach here } catch (e: any) { expect(e.suggestions).toBeDefined() @@ -1670,12 +1692,12 @@ test("ModelNotFoundError for provider includes suggestions", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") try { - await getModel(ProviderID.make("antropic"), ModelID.make("claude-sonnet-4")) // typo: antropic + await getModel(ProviderID.make("antropic"), ModelID.make("claude-sonnet-4"), ctx) // typo: antropic expect(true).toBe(false) // Should not reach here } catch (e: any) { expect(e.suggestions).toBeDefined() @@ -1696,12 +1718,12 @@ test("ModelNotFoundError suggests catalog models for unloaded providers", async ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - remove("OPENCODE_API_KEY") + fn: async (ctx) => { + remove(ctx, "OPENCODE_API_KEY") try { - await getModel(ProviderID.opencode, ModelID.make("claude-haiku-fake-model")) + await getModel(ProviderID.opencode, ModelID.make("claude-haiku-fake-model"), ctx) throw new Error("expected model lookup to fail") } catch (e) { if (!Provider.ModelNotFoundError.isInstance(e)) throw e @@ -1722,10 +1744,10 @@ test("getProvider returns undefined for nonexistent provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const provider = await getProvider(ProviderID.make("nonexistent")) + fn: async (ctx) => { + const provider = await getProvider(ProviderID.make("nonexistent"), ctx) expect(provider).toBeUndefined() }, }) @@ -1742,11 +1764,11 @@ test("getProvider returns provider info", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const provider = await getProvider(ProviderID.anthropic) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const provider = await getProvider(ProviderID.anthropic, ctx) expect(provider).toBeDefined() expect(String(provider?.id)).toBe("anthropic") }, @@ -1764,11 +1786,11 @@ test("closest returns undefined when no partial match found", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const result = await closest(ProviderID.anthropic, ["nonexistent-xyz-model"]) + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const result = await closest(ProviderID.anthropic, ["nonexistent-xyz-model"], ctx) expect(result).toBeUndefined() }, }) @@ -1785,12 +1807,12 @@ test("closest checks multiple query terms in order", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") // First term won't match, second will - const result = await closest(ProviderID.anthropic, ["nonexistent", "haiku"]) + const result = await closest(ProviderID.anthropic, ["nonexistent", "haiku"], ctx) expect(result).toBeDefined() expect(result?.modelID).toContain("haiku") }, @@ -1823,10 +1845,10 @@ test("model limit defaults to zero when not specified", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const model = providers[ProviderID.make("no-limit")].models["model"] expect(model.limit.context).toBe(0) expect(model.limit.output).toBe(0) @@ -1855,11 +1877,11 @@ test("provider options are deeply merged", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) // Custom options should be merged expect(providers[ProviderID.anthropic].options.timeout).toBe(30000) expect(providers[ProviderID.anthropic].options.headers["X-Custom"]).toBe("custom-value") @@ -1887,10 +1909,10 @@ test("hosted nvidia provider adds billing origin header", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("nvidia")].options.headers).toEqual({ "HTTP-Referer": "https://kilo.ai/", "X-Title": "Kilo Code", @@ -1919,10 +1941,10 @@ test("custom nvidia baseURL adds billing origin header", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("nvidia")].options.headers).toEqual({ "HTTP-Referer": "https://kilo.ai/", "X-Title": "Kilo Code", @@ -1954,10 +1976,10 @@ test("explicit nvidia billing origin header is preserved", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) expect(providers[ProviderID.make("nvidia")].options.headers["X-BILLING-INVOKE-ORIGIN"]).toBe("CustomOrigin") }, }) @@ -1985,11 +2007,11 @@ test("custom model inherits npm package from models.dev provider config", async ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("OPENAI_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "OPENAI_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.openai].models["my-custom-model"] expect(model).toBeDefined() expect(model.api.npm).toBe("@ai-sdk/openai") @@ -2018,11 +2040,11 @@ test("custom model inherits api.url from models.dev provider", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("OPENROUTER_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "OPENROUTER_API_KEY", "test-api-key") + const providers = await list(ctx) expect(providers[ProviderID.openrouter]).toBeDefined() // New model not in database should inherit api.url from provider @@ -2149,11 +2171,11 @@ test("model variants are generated for reasoning models", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) // Claude sonnet 4 has reasoning capability const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.capabilities.reasoning).toBe(true) @@ -2185,11 +2207,11 @@ test("model variants can be disabled via config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants).toBeDefined() expect(model.variants!["high"]).toBeUndefined() @@ -2226,11 +2248,11 @@ test("model variants can be customized via config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["high"]).toBeDefined() expect(model.variants!["high"].thinking.budgetTokens).toBe(20000) @@ -2263,11 +2285,11 @@ test("disabled key is stripped from variant config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["max"]).toBeDefined() expect(model.variants!["max"].disabled).toBeUndefined() @@ -2299,11 +2321,11 @@ test("all variants can be disabled via config", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants).toBeDefined() expect(Object.keys(model.variants!).length).toBe(0) @@ -2335,11 +2357,11 @@ test("variant config merges with generated variants", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["high"]).toBeDefined() // Should have both the generated thinking config and the custom option @@ -2371,11 +2393,11 @@ test("variants filtered in second pass for database models", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("OPENAI_API_KEY", "test-api-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "OPENAI_API_KEY", "test-api-key") + const providers = await list(ctx) const model = providers[ProviderID.openai].models["gpt-5"] expect(model.variants).toBeDefined() expect(model.variants!["high"]).toBeUndefined() @@ -2418,10 +2440,10 @@ test("custom model with variants enabled and disabled", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const providers = await list() + fn: async (ctx) => { + const providers = await list(ctx) const model = providers[ProviderID.make("custom-reasoning")].models["reasoning-model"] expect(model.variants).toBeDefined() // Enabled variants should exist @@ -2473,11 +2495,11 @@ test("Google Vertex: retains baseURL for custom proxy", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("GOOGLE_APPLICATION_CREDENTIALS", "test-creds") - const providers = await list() + fn: async (ctx) => { + set(ctx, "GOOGLE_APPLICATION_CREDENTIALS", "test-creds") + const providers = await list(ctx) expect(providers[ProviderID.make("vertex-proxy")]).toBeDefined() expect(providers[ProviderID.make("vertex-proxy")].options.baseURL).toBe("https://my-proxy.com/v1") }, @@ -2516,11 +2538,11 @@ test("Google Vertex: supports OpenAI compatible models", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("GOOGLE_APPLICATION_CREDENTIALS", "test-creds") - const providers = await list() + fn: async (ctx) => { + set(ctx, "GOOGLE_APPLICATION_CREDENTIALS", "test-creds") + const providers = await list(ctx) const model = providers[ProviderID.make("vertex-openai")].models["gpt-4"] expect(model).toBeDefined() @@ -2540,13 +2562,13 @@ test("cloudflare-ai-gateway loads with env variables", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("CLOUDFLARE_ACCOUNT_ID", "test-account") - set("CLOUDFLARE_GATEWAY_ID", "test-gateway") - set("CLOUDFLARE_API_TOKEN", "test-token") - const providers = await list() + fn: async (ctx) => { + set(ctx, "CLOUDFLARE_ACCOUNT_ID", "test-account") + set(ctx, "CLOUDFLARE_GATEWAY_ID", "test-gateway") + set(ctx, "CLOUDFLARE_API_TOKEN", "test-token") + const providers = await list(ctx) expect(providers[ProviderID.make("cloudflare-ai-gateway")]).toBeDefined() }, }) @@ -2570,13 +2592,13 @@ test("cloudflare-ai-gateway forwards config metadata options", async () => { ) }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("CLOUDFLARE_ACCOUNT_ID", "test-account") - set("CLOUDFLARE_GATEWAY_ID", "test-gateway") - set("CLOUDFLARE_API_TOKEN", "test-token") - const providers = await list() + fn: async (ctx) => { + set(ctx, "CLOUDFLARE_ACCOUNT_ID", "test-account") + set(ctx, "CLOUDFLARE_GATEWAY_ID", "test-gateway") + set(ctx, "CLOUDFLARE_API_TOKEN", "test-token") + const providers = await list(ctx) expect(providers[ProviderID.make("cloudflare-ai-gateway")]).toBeDefined() expect(providers[ProviderID.make("cloudflare-ai-gateway")].options.metadata).toEqual({ invoked_by: "test", @@ -2623,29 +2645,26 @@ test("plugin config providers persist after instance dispose", async () => { }, }) - const first = await WithInstance.provide({ + const first = await withTestInstance({ directory: tmp.path, - fn: async () => + fn: async (ctx) => AppRuntime.runPromise( Effect.gen(function* () { const plugin = yield* Plugin.Service const provider = yield* Provider.Service yield* plugin.init() return yield* provider.list() - }), + }).pipe(Effect.provideService(InstanceRef, ctx)), ), }) expect(first[ProviderID.make("demo")]).toBeDefined() expect(first[ProviderID.make("demo")].models[ModelID.make("chat")]).toBeDefined() - await WithInstance.provide({ - directory: tmp.path, - fn: () => InstanceRuntime.disposeInstance(Instance.current), - }) + await disposeAllInstances() - const second = await WithInstance.provide({ + const second = await withTestInstance({ directory: tmp.path, - fn: async () => list(), + fn: async (ctx) => list(ctx), }) expect(second[ProviderID.make("demo")]).toBeDefined() expect(second[ProviderID.make("demo")].models[ModelID.make("chat")]).toBeDefined() @@ -2674,12 +2693,12 @@ test("plugin config enabled and disabled providers are honored", async () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - set("ANTHROPIC_API_KEY", "test-anthropic-key") - set("OPENAI_API_KEY", "test-openai-key") - const providers = await list() + fn: async (ctx) => { + set(ctx, "ANTHROPIC_API_KEY", "test-anthropic-key") + set(ctx, "OPENAI_API_KEY", "test-openai-key") + const providers = await list(ctx) expect(providers[ProviderID.anthropic]).toBeDefined() expect(providers[ProviderID.openai]).toBeUndefined() }, @@ -2698,9 +2717,9 @@ test("opencode loader keeps paid models when config apiKey is present", async () }, }) - const none = await WithInstance.provide({ + const none = await withTestInstance({ directory: base.path, - fn: async () => paid(await list()), + fn: async (ctx) => paid(await list(ctx)), }) await using keyed = await tmpdir({ @@ -2721,9 +2740,9 @@ test("opencode loader keeps paid models when config apiKey is present", async () }, }) - const keyedCount = await WithInstance.provide({ + const keyedCount = await withTestInstance({ directory: keyed.path, - fn: async () => paid(await list()), + fn: async (ctx) => paid(await list(ctx)), }) expect(none).toBe(0) @@ -2742,9 +2761,9 @@ test("opencode loader keeps paid models when auth exists", async () => { }, }) - const none = await WithInstance.provide({ + const none = await withTestInstance({ directory: base.path, - fn: async () => paid(await list()), + fn: async (ctx) => paid(await list(ctx)), }) await using keyed = await tmpdir({ @@ -2776,9 +2795,9 @@ test("opencode loader keeps paid models when auth exists", async () => { }), ) - const keyedCount = await WithInstance.provide({ + const keyedCount = await withTestInstance({ directory: keyed.path, - fn: async () => paid(await list()), + fn: async (ctx) => paid(await list(ctx)), }) expect(none).toBe(0) diff --git a/packages/opencode/test/question/question.test.ts b/packages/opencode/test/question/question.test.ts index 37a1d534f5c..7e0a7cb57a3 100644 --- a/packages/opencode/test/question/question.test.ts +++ b/packages/opencode/test/question/question.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect } from "bun:test" // kilocode_change - blocking behavior now uses the scoped service test helper import { Cause, Effect, Exit, Fiber, Layer, Queue } from "effect" import { Question } from "../../src/question" -import { Instance } from "../../src/project/instance" +import { InstanceRef } from "../../src/effect/instance-ref" import { InstanceRuntime } from "../../src/project/instance-runtime" import { QuestionID } from "../../src/question/schema" import { disposeAllInstances, provideInstance, reloadTestInstance, tmpdirScoped } from "../fixture/fixture" // kilocode_change - blocking coverage no longer uses the Promise facade fixture @@ -454,7 +454,10 @@ it.live("pending question rejects on instance dispose", () => }).pipe(provideInstance(dir), Effect.forkScoped) expect(yield* waitForPending(1).pipe(provideInstance(dir))).toHaveLength(1) - const ctx = yield* Effect.sync(() => Instance.current).pipe(provideInstance(dir)) + const ctx = yield* Effect.gen(function* () { + return yield* InstanceRef + }).pipe(provideInstance(dir)) + if (!ctx) return yield* Effect.die(new Error("missing test instance")) yield* Effect.promise(() => InstanceRuntime.disposeInstance(ctx)) const exit = yield* Fiber.await(fiber) diff --git a/packages/opencode/test/server/experimental-session-list.test.ts b/packages/opencode/test/server/experimental-session-list.test.ts index 0292057367c..c4f01d8494d 100644 --- a/packages/opencode/test/server/experimental-session-list.test.ts +++ b/packages/opencode/test/server/experimental-session-list.test.ts @@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test" import { $ } from "bun" import path from "path" -import { WithInstance } from "../../src/project/with-instance" +import type { InstanceContext } from "../../src/project/instance-context" +import { InstanceRef } from "../../src/effect/instance-ref" import * as Log from "@opencode-ai/core/util/log" import { resetDatabase } from "../fixture/db" -import { tmpdir } from "../fixture/fixture" +import { tmpdir, withTestInstance } from "../fixture/fixture" import { RemoteSender } from "../../src/kilo-sessions/remote-sender" import { Effect } from "effect" -import { Session } from "../../src/session/session" beforeEach(() => { spyOn(RemoteSender, "create").mockReturnValue({ handle() {}, dispose() {} }) @@ -21,8 +21,15 @@ afterEach(async () => { await resetDatabase() }) -const create = (title: string) => - Effect.runPromise(Session.Service.use((svc) => svc.create({ title })).pipe(Effect.provide(Session.defaultLayer))) +const create = async (title: string, ctx: InstanceContext) => { + const [{ AppRuntime }, { Session }] = await Promise.all([ + import("../../src/effect/app-runtime"), + import("../../src/session/session"), + ]) + return AppRuntime.runPromise( + Session.Service.use((svc) => svc.create({ title })).pipe(Effect.provideService(InstanceRef, ctx)), + ) +} describe("experimental.session.list", () => { test("filters sessions by repo worktree family even when project IDs drift", async () => { @@ -37,29 +44,29 @@ describe("experimental.session.list", () => { const { Server } = await import("../../src/server/server") // Create worktree session first so it computes its own project ID via rev-list - const branch = await WithInstance.provide({ + const branch = await withTestInstance({ directory: worktree, - fn: () => create("worktree-session"), + fn: (ctx) => create("worktree-session", ctx), }) // Now write a stale project ID to .git/kilo — this overrides the root's cached ID await Bun.write(path.join(first.path, ".git", "kilo"), "stale-project-id") - const root = await WithInstance.provide({ + const root = await withTestInstance({ directory: first.path, - fn: async () => ({ + fn: async (ctx) => ({ app: Server.Default().app, project: await Server.Default().app.request("/project/current", { headers: { "x-kilo-directory": first.path }, }), - session: await create("root-session"), + session: await create("root-session", ctx), }), }) await Bun.file(path.join(first.path, ".git", "kilo")).delete() - await WithInstance.provide({ + await withTestInstance({ directory: second.path, - fn: () => create("other-project-session"), + fn: (ctx) => create("other-project-session", ctx), }) const app = root.app @@ -101,25 +108,25 @@ describe("experimental.session.list", () => { try { const { Server } = await import("../../src/server/server") - const branch = await WithInstance.provide({ + const branch = await withTestInstance({ directory: worktree, - fn: () => create("worktree-session"), + fn: (ctx) => create("worktree-session", ctx), }) - const root = await WithInstance.provide({ + const root = await withTestInstance({ directory: first.path, - fn: async () => ({ + fn: async (ctx) => ({ app: Server.Default().app, project: await Server.Default().app.request("/project/current", { headers: { "x-kilo-directory": first.path }, }), - session: await create("root-session"), + session: await create("root-session", ctx), }), }) - await WithInstance.provide({ + await withTestInstance({ directory: second.path, - fn: () => create("other-project-session"), + fn: (ctx) => create("other-project-session", ctx), }) const app = root.app diff --git a/packages/opencode/test/server/httpapi-config.test.ts b/packages/opencode/test/server/httpapi-config.test.ts index 018b4bb773c..e3d0fbbe2bf 100644 --- a/packages/opencode/test/server/httpapi-config.test.ts +++ b/packages/opencode/test/server/httpapi-config.test.ts @@ -59,7 +59,8 @@ describe("config HttpApi", () => { lsp: false, }) yield* Fiber.join(disposed) - expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "opencode.json")).json())).toMatchObject({ // kilocode_change + expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "opencode.json")).json())).toMatchObject({ + // kilocode_change username: "patched-user", formatter: false, lsp: false, diff --git a/packages/opencode/test/server/httpapi-error-middleware.test.ts b/packages/opencode/test/server/httpapi-error-middleware.test.ts index 15f8aa20260..51d4cf9e0c0 100644 --- a/packages/opencode/test/server/httpapi-error-middleware.test.ts +++ b/packages/opencode/test/server/httpapi-error-middleware.test.ts @@ -1,6 +1,7 @@ import { NodeHttpServer, NodeServices } from "@effect/platform-node" import { NamedError } from "@opencode-ai/core/util/error" import { describe, expect } from "bun:test" +import { ConfigError } from "../../src/config/error" import { Effect, Layer } from "effect" import { HttpClient, HttpClientRequest, HttpRouter } from "effect/unstable/http" import { errorLayer } from "../../src/server/routes/instance/httpapi/middleware/error" @@ -50,6 +51,27 @@ describe("HttpApi error middleware", () => { }), ) + it.live("preserves config defects as client-visible bad requests", () => + Effect.gen(function* () { + const configError = new ConfigError.InvalidError({ + path: "/tmp/opencode.json", + issues: [{ message: "Expected object", path: ["provider", "anthropic", "options"] }], + }) + + yield* HttpRouter.add("GET", "/config-error", Effect.die(configError)).pipe( + Layer.provide(errorLayer), + HttpRouter.serve, + Layer.build, + ) + + const response = yield* HttpClientRequest.get("/config-error").pipe(HttpClient.execute) + const body = yield* response.json + + expect(response.status).toBe(400) + expect(JSON.stringify(body)).toBe(JSON.stringify(configError.toObject())) + }), + ) + it.live("does not map storage not-found defects to 404", () => Effect.gen(function* () { yield* HttpRouter.add( diff --git a/packages/opencode/test/server/httpapi-event.test.ts b/packages/opencode/test/server/httpapi-event.test.ts index 5ad2926f274..f1eb512e24c 100644 --- a/packages/opencode/test/server/httpapi-event.test.ts +++ b/packages/opencode/test/server/httpapi-event.test.ts @@ -1,11 +1,12 @@ import { afterEach, describe, expect, test } from "bun:test" import { Bus } from "../../src/bus" -import { Instance } from "../../src/project/instance" +import { AppRuntime } from "../../src/effect/app-runtime" +import { InstanceRef } from "../../src/effect/instance-ref" import { Server } from "../../src/server/server" import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" import { Event as ServerEvent } from "../../src/server/event" import * as Log from "@opencode-ai/core/util/log" -import { Schema } from "effect" +import { Effect, Schema } from "effect" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, reloadTestInstance, tmpdir } from "../fixture/fixture" @@ -133,7 +134,11 @@ describe("event HttpApi", () => { const id = Bus.createID() const next = readUntil(reader, (event) => event.id === id && event.type === "server.connected") const ctx = await reloadTestInstance({ directory: tmp.path }) - await Instance.restore(ctx, () => Bus.publish(ServerEvent.Connected, {}, { id })) + await AppRuntime.runPromise( + Bus.Service.use((svc) => svc.publish(ServerEvent.Connected, {}, { id })).pipe( + Effect.provideService(InstanceRef, ctx), + ), + ) expect(await next).toMatchObject({ id, type: "server.connected", properties: {} }) } finally { diff --git a/packages/opencode/test/server/httpapi-exercise/runtime.ts b/packages/opencode/test/server/httpapi-exercise/runtime.ts index 9d2b6d238e6..2a7c6e080b4 100644 --- a/packages/opencode/test/server/httpapi-exercise/runtime.ts +++ b/packages/opencode/test/server/httpapi-exercise/runtime.ts @@ -3,7 +3,6 @@ export type Runtime = { HttpApiApp: (typeof import("../../../src/server/routes/instance/httpapi/server"))["HttpApiApp"] AppLayer: (typeof import("../../../src/effect/app-runtime"))["AppLayer"] InstanceRef: (typeof import("../../../src/effect/instance-ref"))["InstanceRef"] - Instance: (typeof import("../../../src/project/instance"))["Instance"] InstanceStore: (typeof import("../../../src/project/instance-store"))["InstanceStore"] Session: (typeof import("../../../src/session/session"))["Session"] Todo: (typeof import("../../../src/session/todo"))["Todo"] @@ -22,7 +21,6 @@ export function runtime() { const httpApiServer = await import("../../../src/server/routes/instance/httpapi/server") const appRuntime = await import("../../../src/effect/app-runtime") const instanceRef = await import("../../../src/effect/instance-ref") - const instance = await import("../../../src/project/instance") const instanceStore = await import("../../../src/project/instance-store") const session = await import("../../../src/session/session") const todo = await import("../../../src/session/todo") @@ -35,7 +33,6 @@ export function runtime() { HttpApiApp: httpApiServer.HttpApiApp, AppLayer: appRuntime.AppLayer, InstanceRef: instanceRef.InstanceRef, - Instance: instance.Instance, InstanceStore: instanceStore.InstanceStore, Session: session.Session, Todo: todo.Todo, diff --git a/packages/opencode/test/server/httpapi-file.test.ts b/packages/opencode/test/server/httpapi-file.test.ts index 442a996a291..10a4289e180 100644 --- a/packages/opencode/test/server/httpapi-file.test.ts +++ b/packages/opencode/test/server/httpapi-file.test.ts @@ -3,7 +3,6 @@ import { Context } from "effect" import path from "path" import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" import { FilePaths } from "../../src/server/routes/instance/httpapi/groups/file" -import { Instance } from "../../src/project/instance" import * as Log from "@opencode-ai/core/util/log" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, tmpdir } from "../fixture/fixture" diff --git a/packages/opencode/test/server/httpapi-instance-context.test.ts b/packages/opencode/test/server/httpapi-instance-context.test.ts index 4e2cc9d8ae7..27c91808eab 100644 --- a/packages/opencode/test/server/httpapi-instance-context.test.ts +++ b/packages/opencode/test/server/httpapi-instance-context.test.ts @@ -10,7 +10,6 @@ import { WorkspaceID } from "../../src/control-plane/schema" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" import { InstanceRef, WorkspaceRef } from "../../src/effect/instance-ref" -import { Instance } from "../../src/project/instance" import { InstanceLayer } from "../../src/project/instance-layer" import { Project } from "../../src/project/project" import { disposeMiddleware, markInstanceForDisposal } from "../../src/server/routes/instance/httpapi/lifecycle" diff --git a/packages/opencode/test/server/httpapi-pty.test.ts b/packages/opencode/test/server/httpapi-pty.test.ts index 62758727a5a..bf2ed2a7cbd 100644 --- a/packages/opencode/test/server/httpapi-pty.test.ts +++ b/packages/opencode/test/server/httpapi-pty.test.ts @@ -1,7 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test" import { NodeHttpServer, NodeServices } from "@effect/platform-node" import { PtyID } from "../../src/pty/schema" -import { Instance } from "../../src/project/instance" import { Server } from "../../src/server/server" import { PtyPaths } from "../../src/server/routes/instance/httpapi/groups/pty" import * as Log from "@opencode-ai/core/util/log" diff --git a/packages/opencode/test/server/httpapi-raw-route-auth.test.ts b/packages/opencode/test/server/httpapi-raw-route-auth.test.ts index 102bcc8f50a..f8ee06f19df 100644 --- a/packages/opencode/test/server/httpapi-raw-route-auth.test.ts +++ b/packages/opencode/test/server/httpapi-raw-route-auth.test.ts @@ -1,7 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test" import { ConfigProvider, Layer } from "effect" import { HttpRouter } from "effect/unstable/http" -import { Instance } from "../../src/project/instance" import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" import { PtyPaths } from "../../src/server/routes/instance/httpapi/groups/pty" import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" diff --git a/packages/opencode/test/server/httpapi-session.test.ts b/packages/opencode/test/server/httpapi-session.test.ts index 4b6feb7e1b6..7970c4c0f72 100644 --- a/packages/opencode/test/server/httpapi-session.test.ts +++ b/packages/opencode/test/server/httpapi-session.test.ts @@ -19,7 +19,7 @@ import { MessageID, PartID, SessionID, type SessionID as SessionIDType } from ". import { MessageV2 } from "../../src/session/message-v2" import { Database } from "@/storage/db" import { SessionMessageTable, SessionTable } from "@/session/session.sql" -import { SessionMessage } from "../../src/v2/session-message" +import { SessionMessage } from "@opencode-ai/core/session-message" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import * as DateTime from "effect/DateTime" diff --git a/packages/opencode/test/server/httpapi-ui.test.ts b/packages/opencode/test/server/httpapi-ui.test.ts index e7790895c74..fd2560af017 100644 --- a/packages/opencode/test/server/httpapi-ui.test.ts +++ b/packages/opencode/test/server/httpapi-ui.test.ts @@ -67,13 +67,14 @@ function app(input?: { password?: string; username?: string }) { ).handler return { request(input: string | URL | Request, init?: RequestInit) { - return Effect.promise((): Promise => - Promise.resolve( - handler( - input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), - HttpApiApp.context, + return Effect.promise( + (): Promise => + Promise.resolve( + handler( + input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), + HttpApiApp.context, + ), ), - ), ) }, } @@ -114,13 +115,14 @@ function uiApp(input?: { ).handler return { request(input: string | URL | Request, init?: RequestInit) { - return Effect.promise((): Promise => - Promise.resolve( - handler( - input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), - HttpApiApp.context, + return Effect.promise( + (): Promise => + Promise.resolve( + handler( + input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), + HttpApiApp.context, + ), ), - ), ) }, } @@ -156,13 +158,14 @@ function routeOrderingApp() { return { proxiedUrl: () => proxiedUrl, request(input: string | URL | Request, init?: RequestInit) { - return Effect.promise((): Promise => - Promise.resolve( - handler( - input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), - HttpApiApp.context, + return Effect.promise( + (): Promise => + Promise.resolve( + handler( + input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), + HttpApiApp.context, + ), ), - ), ) }, } diff --git a/packages/opencode/test/server/httpapi-workspace.test.ts b/packages/opencode/test/server/httpapi-workspace.test.ts index 2f72d3bbe58..1862c11bc18 100644 --- a/packages/opencode/test/server/httpapi-workspace.test.ts +++ b/packages/opencode/test/server/httpapi-workspace.test.ts @@ -13,7 +13,6 @@ import * as Log from "@opencode-ai/core/util/log" import { Server } from "../../src/server/server" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, provideInstance, tmpdirScoped } from "../fixture/fixture" -import { Instance } from "../../src/project/instance" import { InstanceBootstrap } from "../../src/project/bootstrap" import { InstanceStore } from "../../src/project/instance-store" import { Project } from "../../src/project/project" @@ -71,7 +70,7 @@ function listedAdapter(directory: string, type: string): WorkspaceAdapter { }, async create() {}, async remove() {}, - list() { + list(context) { return [ { type, @@ -79,7 +78,7 @@ function listedAdapter(directory: string, type: string): WorkspaceAdapter { branch: "listed/main", directory, extra: { listed: true }, - projectID: Instance.project.id, + projectID: context?.instance?.project.id ?? missingAdapterContext(), }, ] }, @@ -92,6 +91,10 @@ function listedAdapter(directory: string, type: string): WorkspaceAdapter { } } +function missingAdapterContext(): never { + throw new Error("missing workspace adapter context") +} + function remoteAdapter(directory: string, url: string, headers?: HeadersInit): WorkspaceAdapter { return { name: "Remote Test", diff --git a/packages/opencode/test/session/compaction.test.ts b/packages/opencode/test/session/compaction.test.ts index f43340e07af..c2990940906 100644 --- a/packages/opencode/test/session/compaction.test.ts +++ b/packages/opencode/test/session/compaction.test.ts @@ -29,6 +29,7 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { TestConfig } from "../fixture/config" import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) @@ -225,6 +226,8 @@ const deps = Layer.mergeAll( Bus.layer, Config.defaultLayer, SyncEvent.defaultLayer, + RuntimeFlags.layer({ experimentalEventSystem: true }), + EventV2Bridge.defaultLayer, ).pipe(Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true }))) const env = Layer.mergeAll( @@ -274,6 +277,8 @@ function compactionProcessLayer(options?: CompactionProcessOptions) { Layer.provide(bus), Layer.provide(options?.config ?? Config.defaultLayer), Layer.provide(SyncEvent.defaultLayer), + Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })), + Layer.provide(EventV2Bridge.defaultLayer), ) } diff --git a/packages/opencode/test/session/instruction.test.ts b/packages/opencode/test/session/instruction.test.ts index 5d40933954e..0f9c340dd4c 100644 --- a/packages/opencode/test/session/instruction.test.ts +++ b/packages/opencode/test/session/instruction.test.ts @@ -10,6 +10,7 @@ import { Instruction } from "../../src/session/instruction" import type { MessageV2 } from "../../src/session/message-v2" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { Global } from "@opencode-ai/core/global" +import { RuntimeFlags } from "../../src/effect/runtime-flags" import { provideInstance, provideTmpdirInstance, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { TestConfig } from "../fixture/config" @@ -18,18 +19,19 @@ const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSys const configLayer = TestConfig.layer() -const instructionLayer = (global: Partial) => +const instructionLayer = (global: Partial, flags: Partial = {}) => Instruction.layer.pipe( Layer.provide(configLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(Global.layerWith(global)), + Layer.provide(RuntimeFlags.layer(flags)), ) const provideInstruction = - (global: Partial) => + (global: Partial, flags?: Partial) => (self: Effect.Effect) => - self.pipe(Effect.provide(instructionLayer(global))) + self.pipe(Effect.provide(instructionLayer(global, flags))) const write = (filepath: string, content: string) => Effect.gen(function* () { @@ -215,6 +217,24 @@ describe("Instruction.system", () => { }).pipe(provideInstance(projectTmp), provideInstruction({ home: globalTmp, config: globalTmp })) }), ) + + it.live("skips project and global CLAUDE.md when Claude Code prompt is disabled", () => + Effect.gen(function* () { + const globalTmp = yield* tmpWithFiles({ ".claude/CLAUDE.md": "# Global Claude" }) + const projectTmp = yield* tmpWithFiles({ "CLAUDE.md": "# Project Claude" }) + + yield* Effect.gen(function* () { + const svc = yield* Instruction.Service + const paths = yield* svc.systemPaths() + expect(paths.has(path.join(globalTmp, ".claude", "CLAUDE.md"))).toBe(false) + expect(paths.has(path.join(projectTmp, "CLAUDE.md"))).toBe(false) + expect(yield* svc.system()).toEqual([]) + }).pipe( + provideInstance(projectTmp), + provideInstruction({ home: globalTmp, config: globalTmp }, { disableClaudeCodePrompt: true }), + ) + }), + ) }) describe("Instruction.systemPaths global config", () => { diff --git a/packages/opencode/test/session/llm.test.ts b/packages/opencode/test/session/llm.test.ts index a6915282c81..04e7da6965c 100644 --- a/packages/opencode/test/session/llm.test.ts +++ b/packages/opencode/test/session/llm.test.ts @@ -4,33 +4,35 @@ import { tool, type ModelMessage } from "ai" import { Cause, Effect, Exit, Stream } from "effect" import z from "zod" import { makeRuntime } from "../../src/effect/run-service" +import { InstanceRef } from "../../src/effect/instance-ref" import { LLM } from "../../src/session/llm" -import { Instance } from "../../src/project/instance" -import { WithInstance } from "../../src/project/with-instance" +import type { InstanceContext } from "../../src/project/instance-context" import { Provider } from "@/provider/provider" import { ProviderTransform } from "@/provider/transform" import { ModelsDev } from "@opencode-ai/core/models" import { ProviderID, ModelID } from "../../src/provider/schema" import { Filesystem } from "@/util/filesystem" -import { tmpdir } from "../fixture/fixture" +import { tmpdir, withTestInstance } from "../fixture/fixture" import type { Agent } from "../../src/agent/agent" import { MessageV2 } from "../../src/session/message-v2" import { SessionID, MessageID } from "../../src/session/schema" import { AppRuntime } from "../../src/effect/app-runtime" -async function getModel(providerID: ProviderID, modelID: ModelID) { - return AppRuntime.runPromise( - Effect.gen(function* () { - const provider = yield* Provider.Service - return yield* provider.getModel(providerID, modelID) - }), - ) +async function getModel(providerID: ProviderID, modelID: ModelID, ctx: InstanceContext) { + const effect = Effect.gen(function* () { + const provider = yield* Provider.Service + return yield* provider.getModel(providerID, modelID) + }) + return AppRuntime.runPromise(effect.pipe(Effect.provideService(InstanceRef, ctx))) } const llm = makeRuntime(LLM.Service, LLM.defaultLayer) -async function drain(input: LLM.StreamInput) { - return llm.runPromise((svc) => svc.stream(input).pipe(Stream.runDrain)) +async function drain(input: LLM.StreamInput, ctx: InstanceContext) { + return llm.runPromise((svc) => { + const effect = svc.stream(input).pipe(Stream.runDrain) + return effect.pipe(Effect.provideService(InstanceRef, ctx)) + }) } describe("session.llm.hasToolCalls", () => { @@ -358,10 +360,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-1") const agent = { name: "test", @@ -381,15 +383,18 @@ describe("session.llm.stream", () => { model: { providerID: ProviderID.make(providerID), modelID: resolved.id, variant: "high" }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - system: ["You are a helpful assistant."], - messages: [{ role: "user", content: "Hello" }], - tools: {}, - }) + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: ["You are a helpful assistant."], + messages: [{ role: "user", content: "Hello" }], + tools: {}, + }, + ctx, + ) const capture = await request const body = capture.body @@ -446,10 +451,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-service-abort") const agent = { name: "test", @@ -479,7 +484,7 @@ describe("session.llm.stream", () => { messages: [{ role: "user", content: "Hello" }], tools: {}, }) - .pipe(Stream.runDrain), + .pipe(Stream.runDrain, Effect.provideService(InstanceRef, ctx)), { signal: ctrl.signal }, ) @@ -536,10 +541,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-tools") const agent = { name: "test", @@ -558,22 +563,25 @@ describe("session.llm.stream", () => { tools: { question: true }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - permission: [{ permission: "question", pattern: "*", action: "allow" }], - system: ["You are a helpful assistant."], - messages: [{ role: "user", content: "Hello" }], - tools: { - question: tool({ - description: "Ask a question", - inputSchema: z.object({}), - execute: async () => ({ output: "" }), - }), + await drain( + { + user, + sessionID, + model: resolved, + agent, + permission: [{ permission: "question", pattern: "*", action: "allow" }], + system: ["You are a helpful assistant."], + messages: [{ role: "user", content: "Hello" }], + tools: { + question: tool({ + description: "Ask a question", + inputSchema: z.object({}), + execute: async () => ({ output: "" }), + }), + }, }, - }) + ctx, + ) const capture = await request const tools = capture.body.tools as Array<{ function?: { name?: string } }> | undefined @@ -650,10 +658,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.openai, ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.openai, ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-2") const agent = { name: "test", @@ -672,15 +680,18 @@ describe("session.llm.stream", () => { model: { providerID: ProviderID.make("openai"), modelID: resolved.id, variant: "high" }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - system: ["You are a helpful assistant."], - messages: [{ role: "user", content: "Hello" }], - tools: {}, - }) + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: ["You are a helpful assistant."], + messages: [{ role: "user", content: "Hello" }], + tools: {}, + }, + ctx, + ) const capture = await request const body = capture.body @@ -766,10 +777,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.openai, ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.openai, ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-data-url") const agent = { name: "test", @@ -787,28 +798,31 @@ describe("session.llm.stream", () => { model: { providerID: ProviderID.make("openai"), modelID: resolved.id }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - system: ["You are a helpful assistant."], - messages: [ - { - role: "user", - content: [ - { type: "text", text: "Describe this image" }, - { - type: "file", - mediaType: "image/png", - filename: "large-image.png", - data: image, - }, - ], - }, - ] as ModelMessage[], - tools: {}, - }) + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: ["You are a helpful assistant."], + messages: [ + { + role: "user", + content: [ + { type: "text", text: "Describe this image" }, + { + type: "file", + mediaType: "image/png", + filename: "large-image.png", + data: image, + }, + ], + }, + ] as ModelMessage[], + tools: {}, + }, + ctx, + ) const capture = await request expect(capture.url.pathname.endsWith("/responses")).toBe(true) @@ -885,10 +899,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-3") const agent = { name: "test", @@ -908,15 +922,18 @@ describe("session.llm.stream", () => { model: { providerID: ProviderID.make("minimax"), modelID: ModelID.make("MiniMax-M2.5") }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - system: ["You are a helpful assistant."], - messages: [{ role: "user", content: "Hello" }], - tools: {}, - }) + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: ["You are a helpful assistant."], + messages: [{ role: "user", content: "Hello" }], + tools: {}, + }, + ctx, + ) const capture = await request const body = capture.body @@ -1003,10 +1020,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make("anthropic"), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make("anthropic"), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-anthropic-tools") const agent = { name: "test", @@ -1111,31 +1128,34 @@ describe("session.llm.stream", () => { }, ] as any[] - await drain({ - user, - sessionID, - model: resolved, - agent, - system: [], - messages: await MessageV2.toModelMessages(input as any, resolved), - tools: { - read: tool({ - description: "Stub read tool", - inputSchema: z.object({ - filePath: z.string(), + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: [], + messages: await MessageV2.toModelMessages(input as any, resolved), + tools: { + read: tool({ + description: "Stub read tool", + inputSchema: z.object({ + filePath: z.string(), + }), + execute: async () => ({ output: "stub" }), }), - execute: async () => ({ output: "stub" }), - }), - glob: tool({ - description: "Stub glob tool", - inputSchema: z.object({ - pattern: z.string(), - path: z.string().optional(), + glob: tool({ + description: "Stub glob tool", + inputSchema: z.object({ + pattern: z.string(), + path: z.string().optional(), + }), + execute: async () => ({ output: "stub" }), }), - execute: async () => ({ output: "stub" }), - }), + }, }, - }) + ctx, + ) const capture = await request const body = capture.body @@ -1244,10 +1264,10 @@ describe("session.llm.stream", () => { }, }) - await WithInstance.provide({ + await withTestInstance({ directory: tmp.path, - fn: async () => { - const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id)) + fn: async (ctx) => { + const resolved = await getModel(ProviderID.make(providerID), ModelID.make(model.id), ctx) const sessionID = SessionID.make("session-test-4") const agent = { name: "test", @@ -1267,15 +1287,18 @@ describe("session.llm.stream", () => { model: { providerID: ProviderID.make(providerID), modelID: resolved.id }, } satisfies MessageV2.User - await drain({ - user, - sessionID, - model: resolved, - agent, - system: ["You are a helpful assistant."], - messages: [{ role: "user", content: "Hello" }], - tools: {}, - }) + await drain( + { + user, + sessionID, + model: resolved, + agent, + system: ["You are a helpful assistant."], + messages: [{ role: "user", content: "Hello" }], + tools: {}, + }, + ctx, + ) const capture = await request const body = capture.body diff --git a/packages/opencode/test/session/network.test.ts b/packages/opencode/test/session/network.test.ts index 2ddf1bb0537..f25d7e97d88 100644 --- a/packages/opencode/test/session/network.test.ts +++ b/packages/opencode/test/session/network.test.ts @@ -1,8 +1,7 @@ // kilocode_change - new file import { afterEach, describe, expect, test } from "bun:test" import { Bus } from "../../src/bus" -import { WithInstance } from "../../src/project/with-instance" -import { tmpdir } from "../fixture/fixture" +import { provideTestInstance, tmpdir } from "../fixture/fixture" import { SessionNetwork } from "../../src/session/network" import { SessionID } from "../../src/session/schema" @@ -88,7 +87,7 @@ describe("session.network", () => { test("reply resolves pending request", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const { promise } = await SessionNetwork.ask({ @@ -107,7 +106,7 @@ describe("session.network", () => { test("restore auto-resumes pending request after cancellation window", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const run = manual() @@ -130,7 +129,7 @@ describe("session.network", () => { test("reject wins before restored auto-resume fires", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const run = manual() @@ -151,7 +150,7 @@ describe("session.network", () => { test("abort cancels restored auto-resume timer", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const run = manual() @@ -173,7 +172,7 @@ describe("session.network", () => { test("reject rejects pending request", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const { promise } = await SessionNetwork.ask({ @@ -192,7 +191,7 @@ describe("session.network", () => { test("aborted signal rejects without publishing asked", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const abort = new AbortController() @@ -223,7 +222,7 @@ describe("session.network", () => { test("abort during pending ask rejects with AbortError and cleans up", async () => { await using tmp = await tmpdir({ git: true }) - await WithInstance.provide({ + await provideTestInstance({ directory: tmp.path, fn: async () => { const abort = new AbortController() diff --git a/packages/opencode/test/session/processor-effect.test.ts b/packages/opencode/test/session/processor-effect.test.ts index 0f057b6d139..5ad7800f9d4 100644 --- a/packages/opencode/test/session/processor-effect.test.ts +++ b/packages/opencode/test/session/processor-effect.test.ts @@ -27,6 +27,7 @@ import { testEffect } from "../lib/effect" import { raw, reply, TestLLMServer } from "../lib/llm-server" import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) @@ -181,6 +182,7 @@ const deps = Layer.mergeAll( Provider.defaultLayer, status, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra)) const env = Layer.mergeAll( TestLLMServer.layer, diff --git a/packages/opencode/test/session/prompt.test.ts b/packages/opencode/test/session/prompt.test.ts index 82836741ce5..f3b7ff44c66 100644 --- a/packages/opencode/test/session/prompt.test.ts +++ b/packages/opencode/test/session/prompt.test.ts @@ -58,6 +58,7 @@ import { reply, TestLLMServer } from "../lib/llm-server" import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" import { BackgroundJob } from "@/background/job" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) const summary = Layer.succeed( @@ -196,6 +197,7 @@ function makeHttp() { AppFileSystem.defaultLayer, status, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra), Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true }))) const question = Question.layer.pipe(Layer.provideMerge(deps)) const todo = Todo.layer.pipe(Layer.provideMerge(deps)) diff --git a/packages/opencode/test/session/shell-v2.test.ts b/packages/opencode/test/session/shell-v2.test.ts index 294b2667b04..b497f3e79f9 100644 --- a/packages/opencode/test/session/shell-v2.test.ts +++ b/packages/opencode/test/session/shell-v2.test.ts @@ -2,9 +2,9 @@ import { describe, expect, test } from "bun:test" import * as DateTime from "effect/DateTime" import { SessionID } from "../../src/session/schema" -import { EventV2 } from "../../src/v2/event" -import { SessionEvent } from "../../src/v2/session-event" -import { SessionMessageUpdater } from "../../src/v2/session-message-updater" +import { EventV2 } from "@opencode-ai/core/event" +import { SessionEvent } from "@opencode-ai/core/session-event" +import { SessionMessageUpdater } from "@opencode-ai/core/session-message-updater" describe("v2 shell event correlation", () => { test("an unmatched end is ignored before a matching start and end complete one record", () => { diff --git a/packages/opencode/test/session/snapshot-tool-race.test.ts b/packages/opencode/test/session/snapshot-tool-race.test.ts index e4476a20e98..b87c6f4e2ec 100644 --- a/packages/opencode/test/session/snapshot-tool-race.test.ts +++ b/packages/opencode/test/session/snapshot-tool-race.test.ts @@ -61,6 +61,7 @@ import { Format } from "../../src/format" import { Reference } from "../../src/reference/reference" import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) @@ -129,6 +130,7 @@ function makeHttp() { BackgroundJob.defaultLayer, status, SyncEvent.defaultLayer, + EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra)) const question = Question.layer.pipe(Layer.provideMerge(deps)) const todo = Todo.layer.pipe(Layer.provideMerge(deps)) diff --git a/packages/opencode/test/skill/skill.test.ts b/packages/opencode/test/skill/skill.test.ts index 4bcf8d54e5a..a219208233a 100644 --- a/packages/opencode/test/skill/skill.test.ts +++ b/packages/opencode/test/skill/skill.test.ts @@ -15,18 +15,19 @@ import fs from "fs/promises" const node = CrossSpawnSpawner.defaultLayer -const skills = (disableClaudeCodeSkills: boolean) => +const skills = (disableExternalSkills: boolean, disableClaudeCodeSkills: boolean) => Skill.layer.pipe( Layer.provide(Discovery.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(Bus.layer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(Global.layer), - Layer.provide(RuntimeFlags.layer({ disableClaudeCodeSkills })), + Layer.provide(RuntimeFlags.layer({ disableExternalSkills, disableClaudeCodeSkills })), ) -const it = testEffect(Layer.mergeAll(skills(false), node)) -const itWithoutClaudeCodeSkills = testEffect(Layer.mergeAll(skills(true), node)) +const it = testEffect(Layer.mergeAll(skills(false, false), node)) +const itWithoutExternalSkills = testEffect(Layer.mergeAll(skills(true, false), node)) +const itWithoutClaudeCodeSkills = testEffect(Layer.mergeAll(skills(false, true), node)) // kilocode_change async function createGlobalSkill(homeDir: string) { const skillDir = path.join(homeDir, ".claude", "skills", "global-test-skill") @@ -425,6 +426,53 @@ description: A skill in the .agents/skills directory. ), ) + itWithoutExternalSkills.live("skips external skill directories when disabled", () => + provideTmpdirInstance( + (dir) => + Effect.gen(function* () { + yield* Effect.promise(() => + Promise.all([ + Bun.write( + path.join(dir, ".claude", "skills", "claude-skill", "SKILL.md"), + `--- +name: claude-skill +description: A skill in the .claude/skills directory. +--- + +# Claude Skill +`, + ), + Bun.write( + path.join(dir, ".agents", "skills", "agent-skill", "SKILL.md"), + `--- +name: agent-skill +description: A skill in the .agents/skills directory. +--- + +# Agent Skill +`, + ), + Bun.write( + path.join(dir, ".opencode", "skill", "opencode-skill", "SKILL.md"), + `--- +name: opencode-skill +description: A skill in the .opencode/skill directory. +--- + +# OpenCode Skill +`, + ), + ]), + ) + + const skill = yield* Skill.Service + const list = discovered(yield* skill.all()) // kilocode_change + expect(list.map((s) => s.name)).toEqual(["opencode-skill"]) + }), + { git: true }, + ), + ) + it.live("properly resolves directories that skills live in", () => provideTmpdirInstance( (dir) => diff --git a/packages/opencode/test/storage/db.test.ts b/packages/opencode/test/storage/db.test.ts index d56c0bd1ec7..0004310aa12 100644 --- a/packages/opencode/test/storage/db.test.ts +++ b/packages/opencode/test/storage/db.test.ts @@ -26,4 +26,13 @@ describe("Database.getChannelPath", () => { expect(Database.getChannelPath(flags)).toBe(path.join(Global.Path.data, "kilo.db")) }).pipe(Effect.provide(RuntimeFlags.layer({ disableChannelDb: true }))), ) + + it.effect("accepts RuntimeFlags with skipMigrations for database callers", () => + Effect.gen(function* () { + const flags = yield* RuntimeFlags.Service + + expect(flags.skipMigrations).toBe(true) + expect(Database.getChannelPath(flags)).toBe(Database.getChannelPath({ disableChannelDb: flags.disableChannelDb })) + }).pipe(Effect.provide(RuntimeFlags.layer({ skipMigrations: true }))), + ) }) diff --git a/packages/opencode/test/sync/index.test.ts b/packages/opencode/test/sync/index.test.ts index c4e5b86062b..2fbfc9b94ca 100644 --- a/packages/opencode/test/sync/index.test.ts +++ b/packages/opencode/test/sync/index.test.ts @@ -13,7 +13,10 @@ import { RuntimeFlags } from "@/effect/runtime-flags" const it = testEffect( Layer.mergeAll( - SyncEvent.layer.pipe(Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: true }))), + SyncEvent.layer.pipe( + Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: true })), + Layer.provideMerge(Bus.layer), + ), CrossSpawnSpawner.defaultLayer, ), ) @@ -114,7 +117,8 @@ describe("SyncEvent", () => { const received = new Promise((done) => { resolve = done }) - const dispose = Bus.subscribeAll((event) => { + const bus = yield* Bus.Service + const dispose = yield* bus.subscribeAllCallback((event) => { events.push(event) resolve() }) diff --git a/packages/opencode/test/tool/external-directory.test.ts b/packages/opencode/test/tool/external-directory.test.ts index 2dcb157c422..b5d96ee50e6 100644 --- a/packages/opencode/test/tool/external-directory.test.ts +++ b/packages/opencode/test/tool/external-directory.test.ts @@ -48,7 +48,7 @@ describe("tool.assertExternalDirectory", () => { }), ) - it.live("no-ops for paths inside Instance.directory", () => + it.live("no-ops for paths inside the instance directory", () => provideInstance("/tmp/project")( Effect.gen(function* () { const { requests, ctx } = makeCtx() diff --git a/packages/opencode/test/tool/lsp.test.ts b/packages/opencode/test/tool/lsp.test.ts index 875af8e010f..875edc1c05f 100644 --- a/packages/opencode/test/tool/lsp.test.ts +++ b/packages/opencode/test/tool/lsp.test.ts @@ -6,7 +6,6 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { LSP } from "@/lsp/lsp" import { Permission } from "../../src/permission" -import { Instance } from "../../src/project/instance" import { MessageID, SessionID } from "../../src/session/schema" import { Tool } from "@/tool/tool" import { Truncate } from "@/tool/truncate" diff --git a/packages/opencode/test/tool/read.test.ts b/packages/opencode/test/tool/read.test.ts index 1d52601874f..3e4c2c39c27 100644 --- a/packages/opencode/test/tool/read.test.ts +++ b/packages/opencode/test/tool/read.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect } from "bun:test" -import { Cause, Effect, Exit, Layer } from "effect" +import { Cause, Effect, Exit, Layer, Stream } from "effect" import path from "path" import { Agent } from "../../src/agent/agent" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" @@ -10,7 +10,6 @@ import { RuntimeFlags } from "@/effect/runtime-flags" import { Git } from "@/git" import { LSP } from "@/lsp/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" @@ -369,6 +368,38 @@ describe("tool.read truncation", () => { }), ) + it.instance("stops streaming after the byte cap", () => + Effect.gen(function* () { + const test = yield* TestInstance + const filepath = path.join(test.directory, "huge.txt") + const content = `${"x".repeat(80)}\n`.repeat(50_000) + yield* put(filepath, content) + + const fs = yield* AppFileSystem.Service + const counter = { bytes: 0 } + const result = yield* run({ filePath: filepath }).pipe( + Effect.provideService( + AppFileSystem.Service, + AppFileSystem.Service.of({ + ...fs, + stream: (file, options) => + fs.stream(file, options).pipe( + Stream.tap((chunk) => + Effect.sync(() => { + counter.bytes += chunk.length + }), + ), + ), + }), + ), + ) + + expect(result.metadata.truncated).toBe(true) + expect(result.output).toContain("Output capped at") + expect(counter.bytes).toBeLessThan(Buffer.byteLength(content, "utf-8") / 2) + }), + ) + it.instance("truncates by line count when limit is specified", () => Effect.gen(function* () { const test = yield* TestInstance diff --git a/packages/opencode/test/tool/recall.test.ts b/packages/opencode/test/tool/recall.test.ts index 50c08882e9b..f338be9f9e7 100644 --- a/packages/opencode/test/tool/recall.test.ts +++ b/packages/opencode/test/tool/recall.test.ts @@ -4,11 +4,10 @@ import { $ } from "bun" import { Effect } from "effect" import { Session } from "../../src/session/session" import path from "path" -import { WithInstance } from "../../src/project/with-instance" import { RecallTool } from "../../src/tool/recall" import { AppRuntime } from "../../src/effect/app-runtime" import { resetDatabase } from "../fixture/db" -import { tmpdir } from "../fixture/fixture" +import { provideTestInstance, tmpdir } from "../fixture/fixture" import type { Tool } from "../../src/tool/tool" import { SessionID, MessageID } from "../../src/session/schema" import { RemoteSender } from "../../src/kilo-sessions/remote-sender" @@ -33,8 +32,7 @@ afterEach(async () => { await resetDatabase() }) -const create = (title: string) => - Effect.runPromise(Session.Service.use((svc) => svc.create({ title })).pipe(Effect.provide(Session.defaultLayer))) +const create = (title: string) => AppRuntime.runPromise(Session.Service.use((svc) => svc.create({ title }))) describe("tool.recall", () => { test("search is limited to the current project worktrees", async () => { @@ -47,20 +45,20 @@ describe("tool.recall", () => { await Bun.write(path.join(first.path, ".git", "opencode"), "stale-project-id") try { - await WithInstance.provide({ + await provideTestInstance({ directory: first.path, fn: () => create("search-target root"), }) - await WithInstance.provide({ + await provideTestInstance({ directory: worktree, fn: () => create("search-target worktree"), }) - await WithInstance.provide({ + await provideTestInstance({ directory: second.path, fn: () => create("search-target other"), }) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: first.path, fn: async () => { const info = await AppRuntime.runPromise(RecallTool) @@ -85,12 +83,12 @@ describe("tool.recall", () => { await using second = await tmpdir({ git: true }) try { - const session = await WithInstance.provide({ + const session = await provideTestInstance({ directory: second.path, fn: () => create("other-project-session"), }) - const err = await WithInstance.provide({ + const err = await provideTestInstance({ directory: first.path, fn: async () => { const info = await AppRuntime.runPromise(RecallTool) @@ -117,12 +115,12 @@ describe("tool.recall", () => { await Bun.write(path.join(first.path, ".git", "opencode"), "stale-project-id") try { - const session = await WithInstance.provide({ + const session = await provideTestInstance({ directory: worktree, fn: () => create("worktree readable"), }) - const result = await WithInstance.provide({ + const result = await provideTestInstance({ directory: first.path, fn: async () => { const info = await AppRuntime.runPromise(RecallTool) diff --git a/packages/opencode/test/tool/registry.test.ts b/packages/opencode/test/tool/registry.test.ts index ec772e1ee79..ba8f6c92454 100644 --- a/packages/opencode/test/tool/registry.test.ts +++ b/packages/opencode/test/tool/registry.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect } from "bun:test" import path from "path" import fs from "fs/promises" -import { pathToFileURL } from "url" +import { fileURLToPath, pathToFileURL } from "url" import { Effect, Layer, Result, Schema } from "effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { ToolRegistry } from "@/tool/registry" @@ -171,6 +171,33 @@ describe("tool.registry", () => { }), ) + it.instance("ignores non-tool exports in .opencode/tool files", () => + Effect.gen(function* () { + const test = yield* TestInstance + const tool = path.join(test.directory, ".opencode", "tool") + yield* Effect.promise(() => fs.mkdir(tool, { recursive: true })) + yield* Effect.promise(() => + Bun.write( + path.join(tool, "mixed.ts"), + [ + "export const helper = 'not a tool'", + "export default {", + " description: 'mixed tool',", + " args: {},", + " execute: async () => 'ok',", + "}", + "", + ].join("\n"), + ), + ) + + const registry = yield* ToolRegistry.Service + const ids = yield* registry.ids() + expect(ids).toContain("mixed") + expect(ids).not.toContain("mixed_helper") + }), + ) + it.instance("loads tools from .opencode/tools (plural)", () => Effect.gen(function* () { const test = yield* TestInstance @@ -249,6 +276,73 @@ describe("tool.registry", () => { }), ) + it.instance( + "preserves Zod arg descriptions from older config-scoped plugin packages", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const opencode = path.join(test.directory, ".opencode") + const customTools = path.join(opencode, "tools") + const plugin = path.join(opencode, "node_modules", "@kilocode", "plugin") // kilocode_change + yield* Effect.promise(() => fs.mkdir(path.join(plugin, "dist"), { recursive: true })) + yield* Effect.promise(() => fs.mkdir(customTools, { recursive: true })) + yield* Effect.promise(() => + fs.cp(path.dirname(fileURLToPath(import.meta.resolve("zod"))), path.join(opencode, "node_modules", "zod"), { + dereference: true, + recursive: true, + }), + ) + yield* Effect.promise(() => + Bun.write( + path.join(plugin, "package.json"), + JSON.stringify({ name: "@kilocode/plugin", type: "module", exports: { ".": "./dist/index.js" } }), + ), + ) + yield* Effect.promise(() => + Bun.write( + path.join(plugin, "dist", "index.js"), + [ + "import { z } from 'zod'", + "export function tool(input) {", + " return input", + "}", + "tool.schema = z", + "", + ].join("\n"), + ), + ) + yield* Effect.promise(() => + Bun.write( + path.join(customTools, "addition.ts"), + [ + 'import { tool } from "@kilocode/plugin"', + "export default tool({", + " description: 'Use this tool to add two numbers and return their sum.',", + " args: {", + " left: tool.schema.number().describe('The first number to add'),", + " right: tool.schema.number().describe('The second number to add'),", + " },", + " execute: async (args) => `${args.left} + ${args.right} = ${args.left + args.right}`,", + "})", + "", + ].join("\n"), + ), + ) + + const registry = yield* ToolRegistry.Service + const loaded = (yield* registry.all()).find((tool) => tool.id === "addition") + if (!loaded) throw new Error("custom addition tool was not loaded") + + expect(ToolJsonSchema.fromTool(loaded)).toMatchObject({ + properties: { + left: { type: "number", description: "The first number to add" }, + right: { type: "number", description: "The second number to add" }, + }, + }) + }), + 20_000, + ) + it.instance("preserves attachments from structured custom tool results", () => Effect.gen(function* () { const test = yield* TestInstance diff --git a/packages/opencode/test/tool/repo_overview.test.ts b/packages/opencode/test/tool/repo_overview.test.ts index 556fa05d1fb..c854e51a3fd 100644 --- a/packages/opencode/test/tool/repo_overview.test.ts +++ b/packages/opencode/test/tool/repo_overview.test.ts @@ -97,6 +97,21 @@ describe("tool.repo_overview", () => { ), ) + it.live("resolves relative paths from the instance directory", () => + provideTmpdirInstance((dir) => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + yield* fs.writeWithDirs(path.join(dir, "nested", "README.md"), "# Nested\n") + + const tool = yield* init() + const result = yield* tool.execute({ path: "nested" }, ctx) + + expect(result.metadata.path).toBe(path.join(dir, "nested")) + expect(result.output).toContain("README.md") + }), + ), + ) + it.live("resolves a cached repository from repository shorthand", () => provideTmpdirInstance((_dir) => Effect.gen(function* () { diff --git a/packages/opencode/test/tool/skill.test.ts b/packages/opencode/test/tool/skill.test.ts index 7518526fdea..de40d7aeff8 100644 --- a/packages/opencode/test/tool/skill.test.ts +++ b/packages/opencode/test/tool/skill.test.ts @@ -5,7 +5,6 @@ import path from "path" import { pathToFileURL } from "url" import type { Permission } from "../../src/permission" import type { Tool } from "@/tool/tool" -import { Instance } from "../../src/project/instance" import { SkillTool } from "../../src/tool/skill" import { ToolRegistry } from "@/tool/registry" import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" diff --git a/packages/opencode/test/tool/write.test.ts b/packages/opencode/test/tool/write.test.ts index f6ac57a8ce1..8a5545e717d 100644 --- a/packages/opencode/test/tool/write.test.ts +++ b/packages/opencode/test/tool/write.test.ts @@ -3,7 +3,6 @@ import { Effect, Layer } from "effect" import path from "path" import fs from "fs/promises" import { WriteTool } from "../../src/tool/write" -import { Instance } from "../../src/project/instance" import { LSP } from "@/lsp/lsp" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Bus } from "../../src/bus" diff --git a/packages/opencode/test/v2/session-message-updater.test.ts b/packages/opencode/test/v2/session-message-updater.test.ts index 180483937c5..588521281ce 100644 --- a/packages/opencode/test/v2/session-message-updater.test.ts +++ b/packages/opencode/test/v2/session-message-updater.test.ts @@ -1,11 +1,11 @@ import { expect, test } from "bun:test" import * as DateTime from "effect/DateTime" import { SessionID } from "../../src/session/schema" -import { EventV2 } from "../../src/v2/event" +import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" -import { SessionEvent } from "../../src/v2/session-event" -import { SessionMessageUpdater } from "../../src/v2/session-message-updater" +import { SessionEvent } from "@opencode-ai/core/session-event" +import { SessionMessageUpdater } from "@opencode-ai/core/session-message-updater" test("step snapshots carry over to assistant messages", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } diff --git a/packages/plugin/package.json b/packages/plugin/package.json index e77a5e0f149..0bfeeaab4dd 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -22,9 +22,9 @@ "zod": "catalog:" }, "peerDependencies": { - "@opentui/core": ">=0.2.10", - "@opentui/solid": ">=0.2.10", - "@opentui/keymap": ">=0.2.10" + "@opentui/core": ">=0.2.11", + "@opentui/solid": ">=0.2.11", + "@opentui/keymap": ">=0.2.11" }, "peerDependenciesMeta": { "@opentui/core": { diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 97ce46a04e3..b459b45f01c 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -5044,14 +5044,14 @@ export class Model extends HeyApiClient { */ public list( parameters?: { - instance?: { + location?: { directory?: string workspace?: string } }, options?: Options, ) { - const params = buildClientParams([parameters], [{ args: [{ in: "query", key: "instance" }] }]) + const params = buildClientParams([parameters], [{ args: [{ in: "query", key: "location" }] }]) return (options?.client ?? this.client).get({ url: "/api/model", ...options, @@ -5068,14 +5068,14 @@ export class Provider2 extends HeyApiClient { */ public list( parameters?: { - instance?: { + location?: { directory?: string workspace?: string } }, options?: Options, ) { - const params = buildClientParams([parameters], [{ args: [{ in: "query", key: "instance" }] }]) + const params = buildClientParams([parameters], [{ args: [{ in: "query", key: "location" }] }]) return (options?.client ?? this.client).get({ url: "/api/provider", ...options, @@ -5091,7 +5091,7 @@ export class Provider2 extends HeyApiClient { public get( parameters: { providerID: string - instance?: { + location?: { directory?: string workspace?: string } @@ -5104,7 +5104,7 @@ export class Provider2 extends HeyApiClient { { args: [ { in: "path", key: "providerID" }, - { in: "query", key: "instance" }, + { in: "query", key: "location" }, ], }, ], diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 5d2a7d48ff4..4700e69b61f 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -43,9 +43,9 @@ export type Event = | EventSuggestionShown | EventSuggestionAccepted | EventSuggestionDismissed - | EventSessionCompacted | EventCommandExecuted | EventProjectUpdated + | EventSessionCompacted | EventVcsBranchUpdated | EventKiloSessionsRemoteStatusChanged | EventWorkspaceReady @@ -59,6 +59,40 @@ export type Event = | EventPtyDeleted | EventInstallationUpdated | EventInstallationUpdateAvailable + | EventMessageUpdated + | EventMessageRemoved + | EventMessagePartUpdated + | EventMessagePartRemoved + | EventSessionCreated + | EventSessionUpdated + | EventSessionDeleted + | EventSessionNextAgentSwitched + | EventSessionNextModelSwitched + | EventSessionNextPrompted + | EventSessionNextSynthetic + | EventSessionNextShellStarted + | EventSessionNextShellEnded + | EventSessionNextStepStarted + | EventSessionNextStepEnded + | EventSessionNextStepFailed + | EventSessionNextTextStarted + | EventSessionNextTextDelta + | EventSessionNextTextEnded + | EventSessionNextReasoningStarted + | EventSessionNextReasoningDelta + | EventSessionNextReasoningEnded + | EventSessionNextToolInputStarted + | EventSessionNextToolInputDelta + | EventSessionNextToolInputEnded + | EventSessionNextToolCalled + | EventSessionNextToolProgress + | EventSessionNextToolSuccess + | EventSessionNextToolFailed + | EventSessionNextRetried + | EventSessionNextCompactionStarted + | EventSessionNextCompactionDelta + | EventSessionNextCompactionEnded + | EventCatalogModelUpdated export type OAuth = { type: "oauth" @@ -897,9 +931,9 @@ export type GlobalEvent = { | EventSuggestionShown | EventSuggestionAccepted | EventSuggestionDismissed - | EventSessionCompacted | EventCommandExecuted | EventProjectUpdated + | EventSessionCompacted | EventVcsBranchUpdated | EventKiloSessionsRemoteStatusChanged | EventWorkspaceReady @@ -913,6 +947,40 @@ export type GlobalEvent = { | EventPtyDeleted | EventInstallationUpdated | EventInstallationUpdateAvailable + | EventMessageUpdated + | EventMessageRemoved + | EventMessagePartUpdated + | EventMessagePartRemoved + | EventSessionCreated + | EventSessionUpdated + | EventSessionDeleted + | EventSessionNextAgentSwitched + | EventSessionNextModelSwitched + | EventSessionNextPrompted + | EventSessionNextSynthetic + | EventSessionNextShellStarted + | EventSessionNextShellEnded + | EventSessionNextStepStarted + | EventSessionNextStepEnded + | EventSessionNextStepFailed + | EventSessionNextTextStarted + | EventSessionNextTextDelta + | EventSessionNextTextEnded + | EventSessionNextReasoningStarted + | EventSessionNextReasoningDelta + | EventSessionNextReasoningEnded + | EventSessionNextToolInputStarted + | EventSessionNextToolInputDelta + | EventSessionNextToolInputEnded + | EventSessionNextToolCalled + | EventSessionNextToolProgress + | EventSessionNextToolSuccess + | EventSessionNextToolFailed + | EventSessionNextRetried + | EventSessionNextCompactionStarted + | EventSessionNextCompactionDelta + | EventSessionNextCompactionEnded + | EventCatalogModelUpdated | SyncEventMessageUpdated | SyncEventMessageRemoved | SyncEventMessagePartUpdated @@ -3030,14 +3098,6 @@ export type EventSuggestionDismissed = { } } -export type EventSessionCompacted = { - id: string - type: "session.compacted" - properties: { - sessionID: string - } -} - export type EventCommandExecuted = { id: string type: "command.executed" @@ -3055,6 +3115,14 @@ export type EventProjectUpdated = { properties: Project } +export type EventSessionCompacted = { + id: string + type: "session.compacted" + properties: { + sessionID: string + } +} + export type EventVcsBranchUpdated = { id: string type: "vcs.branch.updated" @@ -3163,6 +3231,95 @@ export type EventInstallationUpdateAvailable = { } } +export type EventMessageUpdated = { + id: string + type: "message.updated" + properties: { + sessionID: string + info: Message + } +} + +export type EventMessageRemoved = { + id: string + type: "message.removed" + properties: { + sessionID: string + messageID: string + } +} + +export type EventMessagePartUpdated = { + id: string + type: "message.part.updated" + properties: { + sessionID: string + part: Part + time: number + } +} + +export type EventMessagePartRemoved = { + id: string + type: "message.part.removed" + properties: { + sessionID: string + messageID: string + partID: string + } +} + +export type EventSessionCreated = { + id: string + type: "session.created" + properties: { + sessionID: string + info: Session + } +} + +export type EventSessionUpdated = { + id: string + type: "session.updated" + properties: { + sessionID: string + info: Session + } +} + +export type EventSessionDeleted = { + id: string + type: "session.deleted" + properties: { + sessionID: string + info: Session + } +} + +export type EventSessionNextAgentSwitched = { + id: string + type: "session.next.agent.switched" + properties: { + timestamp: number + sessionID: string + agent: string + } +} + +export type EventSessionNextModelSwitched = { + id: string + type: "session.next.model.switched" + properties: { + timestamp: number + sessionID: string + model: { + id: string + providerID: string + variant: string + } + } +} + export type PromptSource = { start: number end: number @@ -3194,11 +3351,214 @@ export type PromptReferenceAttachment = { source?: PromptSource } +export type EventSessionNextPrompted = { + id: string + type: "session.next.prompted" + properties: { + timestamp: number + sessionID: string + prompt: Prompt + } +} + +export type EventSessionNextSynthetic = { + id: string + type: "session.next.synthetic" + properties: { + timestamp: number + sessionID: string + text: string + } +} + +export type EventSessionNextShellStarted = { + id: string + type: "session.next.shell.started" + properties: { + timestamp: number + sessionID: string + callID: string + command: string + } +} + +export type EventSessionNextShellEnded = { + id: string + type: "session.next.shell.ended" + properties: { + timestamp: number + sessionID: string + callID: string + output: string + } +} + +export type EventSessionNextStepStarted = { + id: string + type: "session.next.step.started" + properties: { + timestamp: number + sessionID: string + agent: string + model: { + id: string + providerID: string + variant: string + } + snapshot?: string + } +} + +export type EventSessionNextStepEnded = { + id: string + type: "session.next.step.ended" + properties: { + timestamp: number + sessionID: string + finish: string + cost: number + tokens: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } + } + snapshot?: string + } +} + export type SessionErrorUnknown = { type: "unknown" message: string } +export type EventSessionNextStepFailed = { + id: string + type: "session.next.step.failed" + properties: { + timestamp: number + sessionID: string + error: SessionErrorUnknown + } +} + +export type EventSessionNextTextStarted = { + id: string + type: "session.next.text.started" + properties: { + timestamp: number + sessionID: string + } +} + +export type EventSessionNextTextDelta = { + id: string + type: "session.next.text.delta" + properties: { + timestamp: number + sessionID: string + delta: string + } +} + +export type EventSessionNextTextEnded = { + id: string + type: "session.next.text.ended" + properties: { + timestamp: number + sessionID: string + text: string + } +} + +export type EventSessionNextReasoningStarted = { + id: string + type: "session.next.reasoning.started" + properties: { + timestamp: number + sessionID: string + reasoningID: string + } +} + +export type EventSessionNextReasoningDelta = { + id: string + type: "session.next.reasoning.delta" + properties: { + timestamp: number + sessionID: string + reasoningID: string + delta: string + } +} + +export type EventSessionNextReasoningEnded = { + id: string + type: "session.next.reasoning.ended" + properties: { + timestamp: number + sessionID: string + reasoningID: string + text: string + } +} + +export type EventSessionNextToolInputStarted = { + id: string + type: "session.next.tool.input.started" + properties: { + timestamp: number + sessionID: string + callID: string + name: string + } +} + +export type EventSessionNextToolInputDelta = { + id: string + type: "session.next.tool.input.delta" + properties: { + timestamp: number + sessionID: string + callID: string + delta: string + } +} + +export type EventSessionNextToolInputEnded = { + id: string + type: "session.next.tool.input.ended" + properties: { + timestamp: number + sessionID: string + callID: string + text: string + } +} + +export type EventSessionNextToolCalled = { + id: string + type: "session.next.tool.called" + properties: { + timestamp: number + sessionID: string + callID: string + tool: string + input: { + [key: string]: unknown + } + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } +} + export type ToolTextContent = { type: "text" text: string @@ -3211,6 +3571,57 @@ export type ToolFileContent = { name?: string } +export type EventSessionNextToolProgress = { + id: string + type: "session.next.tool.progress" + properties: { + timestamp: number + sessionID: string + callID: string + structured: { + [key: string]: unknown + } + content: Array + } +} + +export type EventSessionNextToolSuccess = { + id: string + type: "session.next.tool.success" + properties: { + timestamp: number + sessionID: string + callID: string + structured: { + [key: string]: unknown + } + content: Array + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } +} + +export type EventSessionNextToolFailed = { + id: string + type: "session.next.tool.failed" + properties: { + timestamp: number + sessionID: string + callID: string + error: SessionErrorUnknown + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } +} + export type SessionNextRetryError = { message: string statusCode?: number @@ -3224,6 +3635,154 @@ export type SessionNextRetryError = { } } +export type EventSessionNextRetried = { + id: string + type: "session.next.retried" + properties: { + timestamp: number + sessionID: string + attempt: number + error: SessionNextRetryError + } +} + +export type EventSessionNextCompactionStarted = { + id: string + type: "session.next.compaction.started" + properties: { + timestamp: number + sessionID: string + reason: "auto" | "manual" + } +} + +export type EventSessionNextCompactionDelta = { + id: string + type: "session.next.compaction.delta" + properties: { + timestamp: number + sessionID: string + text: string + } +} + +export type EventSessionNextCompactionEnded = { + id: string + type: "session.next.compaction.ended" + properties: { + timestamp: number + sessionID: string + text: string + include?: string + } +} + +export type ModelV2Info = { + id: string + apiID: string + providerID: string + family?: string + name: string + endpoint: + | { + type: "unknown" + } + | { + type: "openai/responses" + url: string + websocket?: boolean + } + | { + type: "openai/completions" + url: string + reasoning?: + | { + type: "reasoning_content" + } + | { + type: "reasoning_details" + } + } + | { + type: "anthropic/messages" + url: string + } + | { + type: "aisdk" + package: string + url?: string + } + capabilities: { + tools: boolean + input: Array + output: Array + } + options: { + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + variant?: string + } + variants: Array<{ + id: string + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + }> + time: { + released: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + } + cost: Array<{ + tier?: { + type: "context" + size: number + } + input: number + output: number + cache: { + read: number + write: number + } + }> + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { + context: number + input?: number + output: number + } +} + +export type EventCatalogModelUpdated = { + id: string + type: "catalog.model.updated" + properties: { + model: ModelV2Info + } +} + export type SessionInfo = { id: string parentID?: string @@ -3459,104 +4018,6 @@ export type SessionMessage = | SessionMessageAssistant | SessionMessageCompaction -export type ModelV2Info = { - id: string - apiID: string - providerID: string - family?: string - name: string - endpoint: - | { - type: "unknown" - } - | { - type: "openai/responses" - url: string - websocket?: boolean - } - | { - type: "openai/completions" - url: string - reasoning?: - | { - type: "reasoning_content" - } - | { - type: "reasoning_details" - } - } - | { - type: "anthropic/messages" - url: string - } - | { - type: "aisdk" - package: string - url?: string - } - capabilities: { - tools: boolean - input: Array - output: Array - } - options: { - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } - variant?: string - } - variants: Array<{ - id: string - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } - }> - time: { - released: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" - } - cost: Array<{ - tier?: { - type: "context" - size: number - } - input: number - output: number - cache: { - read: number - write: number - } - }> - status: "alpha" | "beta" | "deprecated" | "active" - enabled: boolean - limit: { - context: number - input?: number - output: number - } -} - export type ProviderV2Info = { id: string name: string @@ -3635,6 +4096,104 @@ export type EventTuiToastShow1 = { } } +export type ModelV2Info1 = { + id: string + apiID: string + providerID: string + family?: string + name: string + endpoint: + | { + type: "unknown" + } + | { + type: "openai/responses" + url: string + websocket?: boolean + } + | { + type: "openai/completions" + url: string + reasoning?: + | { + type: "reasoning_content" + } + | { + type: "reasoning_details" + } + } + | { + type: "anthropic/messages" + url: string + } + | { + type: "aisdk" + package: string + url?: string + } + capabilities: { + tools: boolean + input: Array + output: Array + } + options: { + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + variant?: string + } + variants: Array<{ + id: string + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + }> + time: { + released: number | "NaN" | "Infinity" | "-Infinity" + } + cost: Array<{ + tier?: { + type: "context" + size: number + } + input: number + output: number + cache: { + read: number + write: number + } + }> + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { + context: number + input?: number + output: number + } +} + export type BadRequestError = { name: "BadRequest" data: { @@ -6979,7 +7538,7 @@ export type V2ModelListData = { body?: never path?: never query?: { - instance?: { + location?: { directory?: string workspace?: string } @@ -7000,7 +7559,7 @@ export type V2ProviderListData = { body?: never path?: never query?: { - instance?: { + location?: { directory?: string workspace?: string } @@ -7023,7 +7582,7 @@ export type V2ProviderGetData = { providerID: string } query?: { - instance?: { + location?: { directory?: string workspace?: string } diff --git a/packages/sdk/openapi.json b/packages/sdk/openapi.json index 186b8a7444d..5fb281817e4 100644 --- a/packages/sdk/openapi.json +++ b/packages/sdk/openapi.json @@ -8215,7 +8215,7 @@ "operationId": "v2.model.list", "parameters": [ { - "name": "instance", + "name": "location", "in": "query", "schema": { "type": "object", @@ -8265,7 +8265,7 @@ "operationId": "v2.provider.list", "parameters": [ { - "name": "instance", + "name": "location", "in": "query", "schema": { "type": "object", @@ -8323,7 +8323,7 @@ "required": true }, { - "name": "instance", + "name": "location", "in": "query", "schema": { "type": "object", @@ -14392,15 +14392,27 @@ { "$ref": "#/components/schemas/EventLspClientDiagnostics" }, - { - "$ref": "#/components/schemas/EventLspUpdated" - }, { "$ref": "#/components/schemas/EventMcpToolsChanged" }, { "$ref": "#/components/schemas/EventMcpBrowserOpenFailed" }, + { + "$ref": "#/components/schemas/EventPermissionAsked" + }, + { + "$ref": "#/components/schemas/EventPermissionReplied" + }, + { + "$ref": "#/components/schemas/EventCommandExecuted" + }, + { + "$ref": "#/components/schemas/EventProjectUpdated" + }, + { + "$ref": "#/components/schemas/EventLspUpdated" + }, { "$ref": "#/components/schemas/EventSessionNetworkAsked" }, @@ -14416,12 +14428,6 @@ { "$ref": "#/components/schemas/EventMessagePartDelta" }, - { - "$ref": "#/components/schemas/EventPermissionAsked" - }, - { - "$ref": "#/components/schemas/EventPermissionReplied" - }, { "$ref": "#/components/schemas/EventBackground_processUpdated" }, @@ -14461,12 +14467,6 @@ { "$ref": "#/components/schemas/EventSessionCompacted" }, - { - "$ref": "#/components/schemas/EventCommandExecuted" - }, - { - "$ref": "#/components/schemas/EventProjectUpdated" - }, { "$ref": "#/components/schemas/EventVcsBranchUpdated" }, @@ -14505,6 +14505,186 @@ }, { "$ref": "#/components/schemas/EventInstallationUpdate-available" + }, + { + "$ref": "#/components/schemas/EventMessageUpdated" + }, + { + "$ref": "#/components/schemas/EventMessageRemoved" + }, + { + "$ref": "#/components/schemas/EventMessagePartUpdated" + }, + { + "$ref": "#/components/schemas/EventMessagePartRemoved" + }, + { + "$ref": "#/components/schemas/EventSessionCreated" + }, + { + "$ref": "#/components/schemas/EventSessionUpdated" + }, + { + "$ref": "#/components/schemas/EventSessionDeleted" + }, + { + "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextModelSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextPrompted" + }, + { + "$ref": "#/components/schemas/EventSessionNextSynthetic" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolCalled" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolProgress" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolSuccess" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextRetried" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + }, + { + "$ref": "#/components/schemas/EventCatalogModelUpdated" + }, + { + "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextModelSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextPrompted" + }, + { + "$ref": "#/components/schemas/EventSessionNextSynthetic" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolCalled" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolProgress" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolSuccess" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextRetried" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionEnded" } ] }, @@ -14891,40 +15071,6 @@ "required": ["sessionID", "requestID"], "additionalProperties": false }, - "SessionNetworkWait": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^que" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "message": { - "type": "string" - }, - "restored": { - "type": "boolean" - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "number" - }, - "restored": { - "type": "number" - } - }, - "required": ["created"], - "additionalProperties": false - } - }, - "required": ["id", "sessionID", "message", "restored", "time"], - "additionalProperties": false - }, "PermissionRequest": { "type": "object", "properties": { @@ -14972,6 +15118,110 @@ "required": ["id", "sessionID", "permission", "patterns", "metadata", "always"], "additionalProperties": false }, + "Project": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "worktree": { + "type": "string" + }, + "vcs": { + "type": "string", + "enum": ["git"] + }, + "name": { + "type": "string" + }, + "icon": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "override": { + "type": "string" + }, + "color": { + "type": "string" + } + }, + "additionalProperties": false + }, + "commands": { + "type": "object", + "properties": { + "start": { + "type": "string", + "description": "Startup script to run when creating a new workspace (worktree)" + } + }, + "additionalProperties": false + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "minimum": 0 + }, + "updated": { + "type": "integer", + "minimum": 0 + }, + "initialized": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["created", "updated"], + "additionalProperties": false + }, + "sandboxes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["id", "worktree", "time", "sandboxes"], + "additionalProperties": false + }, + "SessionNetworkWait": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^que" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "message": { + "type": "string" + }, + "restored": { + "type": "boolean" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "restored": { + "type": "number" + } + }, + "required": ["created"], + "additionalProperties": false + } + }, + "required": ["id", "sessionID", "message", "restored", "time"], + "additionalProperties": false + }, "BackgroundProcessInfo": { "type": "object", "properties": { @@ -15405,76 +15655,6 @@ "required": ["id", "sessionID", "text", "actions"], "additionalProperties": false }, - "Project": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "worktree": { - "type": "string" - }, - "vcs": { - "type": "string", - "enum": ["git"] - }, - "name": { - "type": "string" - }, - "icon": { - "type": "object", - "properties": { - "url": { - "type": "string" - }, - "override": { - "type": "string" - }, - "color": { - "type": "string" - } - }, - "additionalProperties": false - }, - "commands": { - "type": "object", - "properties": { - "start": { - "type": "string", - "description": "Startup script to run when creating a new workspace (worktree)" - } - }, - "additionalProperties": false - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "integer", - "minimum": 0 - }, - "updated": { - "type": "integer", - "minimum": 0 - }, - "initialized": { - "type": "integer", - "minimum": 0 - } - }, - "required": ["created", "updated"], - "additionalProperties": false - }, - "sandboxes": { - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["id", "worktree", "time", "sandboxes"], - "additionalProperties": false - }, "Pty": { "type": "object", "properties": { @@ -16919,15 +17099,27 @@ { "$ref": "#/components/schemas/EventLspClientDiagnostics" }, - { - "$ref": "#/components/schemas/EventLspUpdated" - }, { "$ref": "#/components/schemas/EventMcpToolsChanged" }, { "$ref": "#/components/schemas/EventMcpBrowserOpenFailed" }, + { + "$ref": "#/components/schemas/EventPermissionAsked" + }, + { + "$ref": "#/components/schemas/EventPermissionReplied" + }, + { + "$ref": "#/components/schemas/EventCommandExecuted" + }, + { + "$ref": "#/components/schemas/EventProjectUpdated" + }, + { + "$ref": "#/components/schemas/EventLspUpdated" + }, { "$ref": "#/components/schemas/EventSessionNetworkAsked" }, @@ -16943,12 +17135,6 @@ { "$ref": "#/components/schemas/EventMessagePartDelta" }, - { - "$ref": "#/components/schemas/EventPermissionAsked" - }, - { - "$ref": "#/components/schemas/EventPermissionReplied" - }, { "$ref": "#/components/schemas/EventBackground_processUpdated" }, @@ -16988,12 +17174,6 @@ { "$ref": "#/components/schemas/EventSessionCompacted" }, - { - "$ref": "#/components/schemas/EventCommandExecuted" - }, - { - "$ref": "#/components/schemas/EventProjectUpdated" - }, { "$ref": "#/components/schemas/EventVcsBranchUpdated" }, @@ -17033,6 +17213,186 @@ { "$ref": "#/components/schemas/EventInstallationUpdate-available" }, + { + "$ref": "#/components/schemas/EventMessageUpdated" + }, + { + "$ref": "#/components/schemas/EventMessageRemoved" + }, + { + "$ref": "#/components/schemas/EventMessagePartUpdated" + }, + { + "$ref": "#/components/schemas/EventMessagePartRemoved" + }, + { + "$ref": "#/components/schemas/EventSessionCreated" + }, + { + "$ref": "#/components/schemas/EventSessionUpdated" + }, + { + "$ref": "#/components/schemas/EventSessionDeleted" + }, + { + "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextModelSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextPrompted" + }, + { + "$ref": "#/components/schemas/EventSessionNextSynthetic" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolCalled" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolProgress" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolSuccess" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextRetried" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + }, + { + "$ref": "#/components/schemas/EventCatalogModelUpdated" + }, + { + "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextModelSwitched" + }, + { + "$ref": "#/components/schemas/EventSessionNextPrompted" + }, + { + "$ref": "#/components/schemas/EventSessionNextSynthetic" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextShellEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextStepFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextTextEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolCalled" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolProgress" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolSuccess" + }, + { + "$ref": "#/components/schemas/EventSessionNextToolFailed" + }, + { + "$ref": "#/components/schemas/EventSessionNextRetried" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + }, + { + "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + }, { "$ref": "#/components/schemas/SyncEventMessageUpdated" }, @@ -22920,24 +23280,6 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventLspUpdated": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["lsp.updated"] - }, - "properties": { - "type": "object", - "properties": {} - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, "EventMcpToolsChanged": { "type": "object", "properties": { @@ -22989,6 +23331,126 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, + "EventPermissionAsked": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["permission.asked"] + }, + "properties": { + "$ref": "#/components/schemas/PermissionRequest" + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventPermissionReplied": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["permission.replied"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^per" + }, + "reply": { + "type": "string", + "enum": ["once", "always", "reject"] + } + }, + "required": ["sessionID", "requestID", "reply"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventCommandExecuted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["command.executed"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "arguments": { + "type": "string" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + } + }, + "required": ["name", "sessionID", "arguments", "messageID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventProjectUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["project.updated"] + }, + "properties": { + "$ref": "#/components/schemas/Project" + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventLspUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["lsp.updated"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "EventSessionNetworkAsked": { "type": "object", "properties": { @@ -23135,56 +23597,6 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventPermissionAsked": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["permission.asked"] - }, - "properties": { - "$ref": "#/components/schemas/PermissionRequest" - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventPermissionReplied": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["permission.replied"] - }, - "properties": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "requestID": { - "type": "string", - "pattern": "^per" - }, - "reply": { - "type": "string", - "enum": ["once", "always", "reject"] - } - }, - "required": ["sessionID", "requestID", "reply"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, "EventBackground_processUpdated": { "type": "object", "properties": { @@ -23577,58 +23989,6 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventCommandExecuted": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["command.executed"] - }, - "properties": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "arguments": { - "type": "string" - }, - "messageID": { - "type": "string", - "pattern": "^msg" - } - }, - "required": ["name", "sessionID", "arguments", "messageID"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventProjectUpdated": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["project.updated"] - }, - "properties": { - "$ref": "#/components/schemas/Project" - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, "EventVcsBranchUpdated": { "type": "object", "properties": { @@ -23957,6 +24317,287 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, + "EventMessageUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Message" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventMessageRemoved": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.removed"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + } + }, + "required": ["sessionID", "messageID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventMessagePartUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.part.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "part": { + "$ref": "#/components/schemas/Part" + }, + "time": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["sessionID", "part", "time"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventMessagePartRemoved": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.part.removed"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" + } + }, + "required": ["sessionID", "messageID", "partID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionCreated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.created"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionDeleted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.deleted"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextAgentSwitched": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.agent.switched"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "agent": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "agent"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextModelSwitched": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.model.switched"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["id", "providerID", "variant"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "PromptSource": { "type": "object", "properties": { @@ -24043,6 +24684,252 @@ "required": ["name", "kind"], "additionalProperties": false }, + "EventSessionNextPrompted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.prompted"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + } + }, + "required": ["timestamp", "sessionID", "prompt"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextSynthetic": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.synthetic"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextShellStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.shell.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "command": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "command"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextShellEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.shell.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "output": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "output"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextStepStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "agent": { + "type": "string" + }, + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["id", "providerID", "variant"], + "additionalProperties": false + }, + "snapshot": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "agent", "model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextStepEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "finish": { + "type": "string" + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "reasoning", "cache"], + "additionalProperties": false + }, + "snapshot": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "finish", "cost", "tokens"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "SessionErrorUnknown": { "type": "object", "properties": { @@ -24057,6 +24944,378 @@ "required": ["type", "message"], "additionalProperties": false }, + "EventSessionNextStepFailed": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.failed"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" + } + }, + "required": ["timestamp", "sessionID", "error"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextTextStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + } + }, + "required": ["timestamp", "sessionID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextTextDelta": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextTextEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextReasoningStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextReasoningDelta": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextReasoningEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolInputStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "name"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolInputDelta": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolInputEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolCalled": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.called"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "input": { + "type": "object" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "tool", "input", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "ToolTextContent": { "type": "object", "properties": { @@ -24091,6 +25350,160 @@ "required": ["type", "uri", "mime"], "additionalProperties": false }, + "EventSessionNextToolProgress": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.progress"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + } + }, + "required": ["timestamp", "sessionID", "callID", "structured", "content"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolSuccess": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.success"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "structured", "content", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolFailed": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.failed"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "error", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "SessionNextRetry_error": { "type": "object", "properties": { @@ -24122,6 +25535,485 @@ "required": ["message", "isRetryable"], "additionalProperties": false }, + "EventSessionNextRetried": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.retried"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "attempt": { + "type": "number" + }, + "error": { + "$ref": "#/components/schemas/SessionNextRetry_error" + } + }, + "required": ["timestamp", "sessionID", "attempt", "error"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextCompactionStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reason": { + "type": "string", + "enum": ["auto", "manual"] + } + }, + "required": ["timestamp", "sessionID", "reason"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextCompactionDelta": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextCompactionEnded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + }, + "include": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "ModelV2Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "apiID": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "family": { + "type": "string" + }, + "name": { + "type": "string" + }, + "endpoint": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/responses"] + }, + "url": { + "type": "string" + }, + "websocket": { + "type": "boolean" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/completions"] + }, + "url": { + "type": "string" + }, + "reasoning": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_content"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_details"] + } + }, + "required": ["type"], + "additionalProperties": false + } + ] + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["anthropic/messages"] + }, + "url": { + "type": "string" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["aisdk"] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["type", "package"], + "additionalProperties": false + } + ] + }, + "capabilities": { + "type": "object", + "properties": { + "tools": { + "type": "boolean" + }, + "input": { + "type": "array", + "items": { + "type": "string" + } + }, + "output": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["tools", "input", "output"], + "additionalProperties": false + }, + "options": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + }, + "variant": { + "type": "string" + } + }, + "required": ["headers", "body", "aisdk"], + "additionalProperties": false + }, + "variants": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + } + }, + "required": ["id", "headers", "body", "aisdk"], + "additionalProperties": false + } + }, + "time": { + "type": "object", + "properties": { + "released": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + }, + { + "type": "string", + "enum": ["Infinity", "-Infinity", "NaN"] + } + ] + } + }, + "required": ["released"], + "additionalProperties": false + }, + "cost": { + "type": "array", + "items": { + "type": "object", + "properties": { + "tier": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["context"] + }, + "size": { + "type": "integer" + } + }, + "required": ["type", "size"], + "additionalProperties": false + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "cache"], + "additionalProperties": false + } + }, + "status": { + "type": "string", + "enum": ["alpha", "beta", "deprecated", "active"] + }, + "enabled": { + "type": "boolean" + }, + "limit": { + "type": "object", + "properties": { + "context": { + "type": "integer" + }, + "input": { + "type": "integer" + }, + "output": { + "type": "integer" + } + }, + "required": ["context", "output"], + "additionalProperties": false + } + }, + "required": [ + "id", + "apiID", + "providerID", + "name", + "endpoint", + "capabilities", + "options", + "variants", + "time", + "cost", + "status", + "enabled", + "limit" + ], + "additionalProperties": false + }, + "EventCatalogModelUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["catalog.model.updated"] + }, + "properties": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/ModelV2Info" + } + }, + "required": ["model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, "SessionInfo": { "type": "object", "properties": { @@ -24801,330 +26693,6 @@ } ] }, - "ModelV2Info": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "apiID": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "family": { - "type": "string" - }, - "name": { - "type": "string" - }, - "endpoint": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["unknown"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/responses"] - }, - "url": { - "type": "string" - }, - "websocket": { - "type": "boolean" - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/completions"] - }, - "url": { - "type": "string" - }, - "reasoning": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_content"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_details"] - } - }, - "required": ["type"], - "additionalProperties": false - } - ] - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["anthropic/messages"] - }, - "url": { - "type": "string" - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["aisdk"] - }, - "package": { - "type": "string" - }, - "url": { - "type": "string" - } - }, - "required": ["type", "package"], - "additionalProperties": false - } - ] - }, - "capabilities": { - "type": "object", - "properties": { - "tools": { - "type": "boolean" - }, - "input": { - "type": "array", - "items": { - "type": "string" - } - }, - "output": { - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["tools", "input", "output"], - "additionalProperties": false - }, - "options": { - "type": "object", - "properties": { - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "body": { - "type": "object" - }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false - }, - "variant": { - "type": "string" - } - }, - "required": ["headers", "body", "aisdk"], - "additionalProperties": false - }, - "variants": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "body": { - "type": "object" - }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false - } - }, - "required": ["id", "headers", "body", "aisdk"], - "additionalProperties": false - } - }, - "time": { - "type": "object", - "properties": { - "released": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "string", - "enum": ["NaN"] - }, - { - "type": "string", - "enum": ["Infinity"] - }, - { - "type": "string", - "enum": ["-Infinity"] - }, - { - "type": "string", - "enum": ["Infinity", "-Infinity", "NaN"] - } - ] - } - }, - "required": ["released"], - "additionalProperties": false - }, - "cost": { - "type": "array", - "items": { - "type": "object", - "properties": { - "tier": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["context"] - }, - "size": { - "type": "integer" - } - }, - "required": ["type", "size"], - "additionalProperties": false - }, - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false - } - }, - "required": ["input", "output", "cache"], - "additionalProperties": false - } - }, - "status": { - "type": "string", - "enum": ["alpha", "beta", "deprecated", "active"] - }, - "enabled": { - "type": "boolean" - }, - "limit": { - "type": "object", - "properties": { - "context": { - "type": "integer" - }, - "input": { - "type": "integer" - }, - "output": { - "type": "integer" - } - }, - "required": ["context", "output"], - "additionalProperties": false - } - }, - "required": [ - "id", - "apiID", - "providerID", - "name", - "endpoint", - "capabilities", - "options", - "variants", - "time", - "cost", - "status", - "enabled", - "limit" - ], - "additionalProperties": false - }, "ProviderV2Info": { "type": "object", "properties": { @@ -25361,6 +26929,326 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, + "ModelV2Info1": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "apiID": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "family": { + "type": "string" + }, + "name": { + "type": "string" + }, + "endpoint": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/responses"] + }, + "url": { + "type": "string" + }, + "websocket": { + "type": "boolean" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/completions"] + }, + "url": { + "type": "string" + }, + "reasoning": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_content"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_details"] + } + }, + "required": ["type"], + "additionalProperties": false + } + ] + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["anthropic/messages"] + }, + "url": { + "type": "string" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["aisdk"] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["type", "package"], + "additionalProperties": false + } + ] + }, + "capabilities": { + "type": "object", + "properties": { + "tools": { + "type": "boolean" + }, + "input": { + "type": "array", + "items": { + "type": "string" + } + }, + "output": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["tools", "input", "output"], + "additionalProperties": false + }, + "options": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + }, + "variant": { + "type": "string" + } + }, + "required": ["headers", "body", "aisdk"], + "additionalProperties": false + }, + "variants": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + } + }, + "required": ["id", "headers", "body", "aisdk"], + "additionalProperties": false + } + }, + "time": { + "type": "object", + "properties": { + "released": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + } + ] + } + }, + "required": ["released"], + "additionalProperties": false + }, + "cost": { + "type": "array", + "items": { + "type": "object", + "properties": { + "tier": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["context"] + }, + "size": { + "type": "integer" + } + }, + "required": ["type", "size"], + "additionalProperties": false + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "cache"], + "additionalProperties": false + } + }, + "status": { + "type": "string", + "enum": ["alpha", "beta", "deprecated", "active"] + }, + "enabled": { + "type": "boolean" + }, + "limit": { + "type": "object", + "properties": { + "context": { + "type": "integer" + }, + "input": { + "type": "integer" + }, + "output": { + "type": "integer" + } + }, + "required": ["context", "output"], + "additionalProperties": false + } + }, + "required": [ + "id", + "apiID", + "providerID", + "name", + "endpoint", + "capabilities", + "options", + "variants", + "time", + "cost", + "status", + "enabled", + "limit" + ], + "additionalProperties": false + }, "BadRequestError": { "type": "object", "required": ["name", "data"], diff --git a/packages/ui/src/components/markdown.tsx b/packages/ui/src/components/markdown.tsx index 813bc924108..80df8a35ded 100644 --- a/packages/ui/src/components/markdown.tsx +++ b/packages/ui/src/components/markdown.tsx @@ -263,7 +263,8 @@ export function Markdown( key: local.cacheKey, streaming: local.streaming ?? false, }), - async (src): Promise => { // kilocode_change + async (src): Promise => { + // kilocode_change if (isServer) return { content: fallback(src.text), blocks: [] } // kilocode_change if (!src.text) return { content: "", blocks: [] } // kilocode_change diff --git a/script/check-opencode-promise-facades.ts b/script/check-opencode-promise-facades.ts index 01d5f294602..2974296c675 100644 --- a/script/check-opencode-promise-facades.ts +++ b/script/check-opencode-promise-facades.ts @@ -26,11 +26,10 @@ const allow: Record = { "cli/cmd/run/variant.shared.ts": "direct run variant persistence runtime boundary with test filesystem injection", "cli/cmd/tui/config/tui.ts": "separately tracked TUI config facade", "installation/index.ts": "existing installation facade outside #10655", - "session/compaction.ts": "existing compaction facade outside #10655", } const testAllow: Record = { - "control-plane/workspace.test.ts": { count: 3, reason: "existing runtime integration test" }, + "control-plane/workspace.test.ts": { count: 5, reason: "existing runtime integration test" }, "kilocode/config-resilience.test.ts": { count: 4, reason: "existing runtime integration test" }, "kilocode/config-validation.test.ts": { count: 2, reason: "existing runtime integration test" }, "kilocode/plan-followup.test.ts": { count: 4, reason: "existing runtime integration test" }, @@ -40,8 +39,10 @@ const testAllow: Record = { "kilocode/session/session.test.ts": { count: 5, reason: "existing runtime integration test" }, "provider/amazon-bedrock.test.ts": { count: 2, reason: "existing runtime integration test" }, "provider/provider.test.ts": { count: 3, reason: "existing runtime integration test" }, + "server/experimental-session-list.test.ts": { count: 2, reason: "Kilo session list integration test" }, + "server/httpapi-event.test.ts": { count: 2, reason: "event stream integration test" }, "session/llm.test.ts": { count: 2, reason: "existing runtime integration test" }, - "tool/recall.test.ts": { count: 10, reason: "existing runtime integration test" }, + "tool/recall.test.ts": { count: 11, reason: "existing runtime integration test" }, } const owned = (file: string) => file.startsWith("kilocode/") || file.startsWith("kilo-sessions/") diff --git a/script/upstream/utils/config.ts b/script/upstream/utils/config.ts index d3dd2d3694d..9521bc164f5 100644 --- a/script/upstream/utils/config.ts +++ b/script/upstream/utils/config.ts @@ -122,8 +122,11 @@ export const defaultConfig: MergeConfig = { ".github/workflows/docs-update.yml", ".github/workflows/docs-locale-sync.yml", // Workflows deleted in Kilo (replaced or no longer needed) + ".github/workflows/close-prs.yml", ".github/workflows/opencode.yml", ".github/workflows/publish-vscode.yml", + // Upstream PR cleanup is replaced by .github/workflows/kilo-auto-close.yml + "script/github/close-prs.ts", // VS Code example configs (Kilo ships real .vscode/* files) ".vscode/launch.example.json", ".vscode/settings.example.json",