diff --git a/bt-daemon/tests/agent_integration.rs b/bt-daemon/tests/agent_integration.rs index 84eadcc8..204962f5 100644 --- a/bt-daemon/tests/agent_integration.rs +++ b/bt-daemon/tests/agent_integration.rs @@ -87,6 +87,93 @@ fn opencode_test_env( ] } +const OPENCODE_TEST_PASSWORD: &str = "integration-test-password"; + +struct OpenCodeV2Server { + child: tokio::process::Child, + binary: std::ffi::OsString, + url: String, +} + +impl OpenCodeV2Server { + async fn start( + world: &AgentTestWorld, + workspace: &std::path::Path, + home: &std::path::Path, + ) -> Self { + let binary = std::env::var_os("OPENCODE_V2_BIN").expect("set OPENCODE_V2_BIN"); + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let url = format!("http://127.0.0.1:{port}"); + let mut command = support::agent_process::command(&binary); + command + .args([ + "serve", + "--hostname", + "127.0.0.1", + "--port", + &port.to_string(), + ]) + .current_dir(workspace) + .envs(opencode_test_env(workspace, home)) + .env("OPENCODE_PASSWORD", OPENCODE_TEST_PASSWORD) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true); + world.configure(&mut command); + let child = command.spawn().unwrap(); + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + for _ in 0..100 { + if client + .get(format!("{url}/api/session")) + .basic_auth("opencode", Some(OPENCODE_TEST_PASSWORD)) + .send() + .await + .is_ok_and(|response| response.status().is_success()) + { + return Self { child, binary, url }; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + panic!("OpenCode 2 server did not start"); + } + + fn run(&self, workspace: &std::path::Path, home: &std::path::Path) -> tokio::process::Command { + let mut command = support::agent_process::command(&self.binary); + command + .args(["run", "--server", &self.url, "--model", "mock/mock-model"]) + .current_dir(workspace) + .envs(opencode_test_env(workspace, home)) + .env("OPENCODE_PASSWORD", OPENCODE_TEST_PASSWORD); + command + } + + async fn stop(mut self) { + #[cfg(unix)] + self.child.kill().await.unwrap(); + #[cfg(windows)] + { + // The npm .cmd launcher owns the native server as a child process. + let pid = self.child.id().expect("running OpenCode 2 server"); + let output = support::agent_process::command("taskkill") + .args(["/pid", &pid.to_string(), "/t", "/f"]) + .output() + .await + .unwrap(); + assert!( + output.status.success(), + "stop OpenCode 2 server: {} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + self.child.wait().await.unwrap(); + } + } +} + #[cfg(unix)] #[tokio::test] async fn agent_output_does_not_wait_for_inherited_descendant_handles() { @@ -922,19 +1009,11 @@ async fn opencode_v2_session_emits_traces() { let plugins = workspace.join(".opencode/plugins"); std::fs::create_dir_all(&plugins).unwrap(); std::fs::write(plugins.join("reject.js"), r#"export default { id: 'test.reject', setup(ctx) { const c = new AbortController(); void (async () => { for await (const event of ctx.event.subscribe({signal:c.signal})) { if (event.type === 'permission.asked') await ctx.permission.reply({sessionID:event.data.sessionID,requestID:event.data.id,decision:'reject',message:'test denied'}); } })().catch(() => {}); return () => c.abort(); } };"#).unwrap(); - let mut rejected = - support::agent_process::command(std::env::var_os("OPENCODE_V2_BIN").unwrap()); - rejected - .args([ - "run", - "--standalone", - "--model", - "mock/mock-model", - "permission marker", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)); - world.configure(&mut rejected); + // Keep plugin subscriptions alive until ingest observes the terminal events. + // The foreground CLI can exit while the standalone host is still forwarding them. + let server = OpenCodeV2Server::start(&world, &workspace, &home).await; + let mut rejected = server.run(&workspace, &home); + rejected.arg("permission marker"); // OpenCode 2.0 exits nonzero after a rejection; later releases continue. let _output = world.output(&mut rejected).await; world @@ -949,6 +1028,7 @@ async fn opencode_v2_session_emits_traces() { }), ) .await; + server.stop().await; std::fs::remove_file(plugins.join("reject.js")).unwrap(); std::fs::write(plugins.join("interrupt.js"), r#"export default { id: 'test.interrupt', setup(ctx) { const c = new AbortController(); void (async () => { for await (const event of ctx.event.subscribe({signal:c.signal})) { if (event.type === 'session.tool.called') await ctx.session.interrupt({sessionID:event.data.sessionID}); } })().catch(() => {}); return () => c.abort(); } };"#).unwrap(); @@ -961,20 +1041,9 @@ async fn opencode_v2_session_emits_traces() { serde_json::to_vec(&persistent_config).unwrap(), ) .unwrap(); - let mut interrupted = - support::agent_process::command(std::env::var_os("OPENCODE_V2_BIN").unwrap()); - interrupted - .args([ - "run", - "--standalone", - "--auto", - "--model", - "mock/mock-model", - "interrupt marker", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)); - world.configure(&mut interrupted); + let server = OpenCodeV2Server::start(&world, &workspace, &home).await; + let mut interrupted = server.run(&workspace, &home); + interrupted.args(["--auto", "interrupt marker"]); let _output = world.output(&mut interrupted).await; world .wait_for_mock_ingest_scenario(&IngestScenario::new().expect("interrupted turn", |row| { @@ -984,21 +1053,12 @@ async fn opencode_v2_session_emits_traces() { ) })) .await; + server.stop().await; std::fs::remove_file(plugins.join("interrupt.js")).unwrap(); - let mut failed = support::agent_process::command(std::env::var_os("OPENCODE_V2_BIN").unwrap()); - failed - .args([ - "run", - "--standalone", - "--auto", - "--model", - "mock/mock-model", - "model failure marker", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)); - world.configure(&mut failed); + let server = OpenCodeV2Server::start(&world, &workspace, &home).await; + let mut failed = server.run(&workspace, &home); + failed.args(["--auto", "model failure marker"]); let _output = world.output(&mut failed).await; let failure_rows = world .wait_for_mock_ingest_scenario( @@ -1026,21 +1086,15 @@ async fn opencode_v2_session_emits_traces() { .expect("failed native session root")["metadata"]["session_id"] .as_str() .unwrap(); - let mut resumed = support::agent_process::command(std::env::var_os("OPENCODE_V2_BIN").unwrap()); - resumed - .args([ - "run", - "--standalone", - "--auto", - "--model", - "mock/mock-model", - "--session", - native_session, - "model recovery marker", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)); - world.configure(&mut resumed); + server.stop().await; + let server = OpenCodeV2Server::start(&world, &workspace, &home).await; + let mut resumed = server.run(&workspace, &home); + resumed.args([ + "--auto", + "--session", + native_session, + "model recovery marker", + ]); let output = world.output(&mut resumed).await; assert!( output.status.success(), @@ -1058,6 +1112,7 @@ async fn opencode_v2_session_emits_traces() { .iter() .any(|row| row["root_span_id"] == failed_root && row_contains(row, &["Turn 2", "model recovery marker"]))); + server.stop().await; std::fs::write(plugins.join("image.js"), r#"export default { id:'test.image', async setup(ctx) { await ctx.tool.transform(editor => editor.add({name:'fixture_image',description:'Return an image',input:{type:'object',properties:{},additionalProperties:false},options:{codemode:false},async execute() { return {content:[{type:'file',mime:'image/png',uri:'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg=='}]}; }})); } };"#).unwrap(); let mut image_run = support::agent_process::daemon_command(); @@ -1287,60 +1342,11 @@ async fn run_v2_compaction_after_idle(native: bool) { "export default {id:'test.compact',async setup(ctx){await ctx.session.hook('compaction',e=>{e.result={summary:'LEGACY_COMPACTION_SUMMARY'}})}};" }; std::fs::write(plugins.join("compact.js"), hook).unwrap(); - let port = std::net::TcpListener::bind("127.0.0.1:0") - .unwrap() - .local_addr() - .unwrap() - .port(); - let url = format!("http://127.0.0.1:{port}"); - let mut server = support::agent_process::command(&binary); - server - .args([ - "serve", - "--hostname", - "127.0.0.1", - "--port", - &port.to_string(), - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)) - .env("OPENCODE_PASSWORD", "integration-test-password") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .kill_on_drop(true); - world.configure(&mut server); - let mut server = server.spawn().unwrap(); + let server = OpenCodeV2Server::start(&world, &workspace, &home).await; + let url = &server.url; let client = reqwest::Client::builder().no_proxy().build().unwrap(); - let mut ready = false; - for _ in 0..100 { - if client - .get(format!("{url}/api/session")) - .basic_auth("opencode", Some("integration-test-password")) - .send() - .await - .is_ok_and(|r| r.status().is_success()) - { - ready = true; - break; - } - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - } - assert!(ready, "OpenCode 2 server did not start"); - let mut run = support::agent_process::command(&binary); - run.args([ - "run", - "--server", - &url, - "--auto", - "--model", - "mock/mock-model", - "--format", - "json", - "legacy compaction", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)) - .env("OPENCODE_PASSWORD", "integration-test-password"); + let mut run = server.run(&workspace, &home); + run.args(["--auto", "--format", "json", "legacy compaction"]); let output = world.output(&mut run).await; assert!( output.status.success(), @@ -1365,7 +1371,7 @@ async fn run_v2_compaction_after_idle(native: bool) { .clone(); let compact_request = client .post(format!("{url}/api/session/{session_id}/compact")) - .basic_auth("opencode", Some("integration-test-password")) + .basic_auth("opencode", Some(OPENCODE_TEST_PASSWORD)) .json(&json!({"delivery":"queue"})) .build() .unwrap(); @@ -1384,22 +1390,13 @@ async fn run_v2_compaction_after_idle(native: bool) { .iter() .any(|row| row_contains(row, &[r#""type":"llm""#, summary]) && row["root_span_id"] == root_id)); - let mut resume = support::agent_process::command(&binary); - resume - .args([ - "run", - "--server", - &url, - "--auto", - "--model", - "mock/mock-model", - "--session", - &session_id, - "legacy after compaction", - ]) - .current_dir(&workspace) - .envs(opencode_test_env(&workspace, &home)) - .env("OPENCODE_PASSWORD", "integration-test-password"); + let mut resume = server.run(&workspace, &home); + resume.args([ + "--auto", + "--session", + &session_id, + "legacy after compaction", + ]); let output = world.output(&mut resume).await; assert!( output.status.success(), @@ -1459,8 +1456,7 @@ async fn run_v2_compaction_after_idle(native: bool) { .contains("NATIVE_COMPACTION_WINDOW")); assert!(!compact["input"].to_string().contains("legacy compaction")); } - server.kill().await.unwrap(); - server.wait().await.unwrap(); + server.stop().await; } #[cfg(unix)] diff --git a/src/plugins/opencode/content/README.md b/src/plugins/opencode/content/README.md index e16bc1a5..f75979be 100644 --- a/src/plugins/opencode/content/README.md +++ b/src/plugins/opencode/content/README.md @@ -41,10 +41,15 @@ Settings load from these files, with project settings overriding global settings - Global: `$XDG_CONFIG_HOME/opencode/braintrust.json`, or `~/.config/opencode/braintrust.json` if `XDG_CONFIG_HOME` is unset -- Project: `.opencode/braintrust.json` - -`bt trace run` overrides tracing settings for one invocation. Files are merged -at the top level: a project `route` replaces the global `route`. +- Project: `.braintrust.json` at the Git root, or in the working directory outside Git + +An explicit `"trace_to_braintrust": false` in the legacy +`.opencode/braintrust.json` still disables tracing, even if +`.braintrust.json` enables it. The plugin checks the working directory and the +Git root for legacy opt-outs and uses only the tracing flag from those files. +To migrate an opt-out, set `"trace_to_braintrust": false` in +`.braintrust.json`. `bt trace run` can override these settings for one +invocation. ```json { diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index 7af6671f..06229060 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -149,6 +149,34 @@ describe("BraintrustPlugin", () => { expect((await BraintrustPlugin(createInput(directory))).event).toBeDefined(); }); + it("honors a legacy project opt-out without applying the legacy tool settings", async () => { + const global = join(directory, ".config", "opencode"); + const legacy = join(directory, ".opencode"); + const nested = join(directory, "src"); + mkdirSync(global, { recursive: true }); + mkdirSync(legacy); + mkdirSync(nested); + mkdirSync(join(directory, ".git")); + delete process.env.BRAINTRUST_OPENCODE_ENABLE_TOOLS; + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync( + join(legacy, "braintrust.json"), + JSON.stringify({ trace_to_braintrust: false, enable_tools: false }), + ); + const { BraintrustPlugin } = await import("./index"); + const paused = await BraintrustPlugin(createInput(directory)); + expect(paused.event).toBeUndefined(); + expect(paused.tool).toBeDefined(); + + const shared = join(directory, ".braintrust.json"); + writeFileSync(shared, JSON.stringify({ trace_to_braintrust: true })); + expect((await BraintrustPlugin(createInput(nested))).event).toBeUndefined(); + + writeFileSync(join(legacy, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync(shared, JSON.stringify({ trace_to_braintrust: false })); + expect((await BraintrustPlugin(createInput(nested))).event).toBeUndefined(); + }); + it("does not bypass a project opt-out when its plugin list is invalid", async () => { const global = join(directory, ".config", "opencode"); mkdirSync(global, { recursive: true }); diff --git a/src/plugins/opencode/content/src/server.pause.test.ts b/src/plugins/opencode/content/src/server.pause.test.ts index 2ead16a7..e3d3cc96 100644 --- a/src/plugins/opencode/content/src/server.pause.test.ts +++ b/src/plugins/opencode/content/src/server.pause.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; vi.mock("./runtime/daemon-client", async (importOriginal) => ({ ...(await importOriginal()), @@ -25,34 +25,37 @@ afterEach(() => { rmSync(directory, { recursive: true, force: true }); }); -it("applies the project opt-out to OpenCode 2 and permits a managed run", async () => { - const global = join(directory, "config", "opencode"); - const project = directory; - mkdirSync(global, { recursive: true }); - mkdirSync(project, { recursive: true }); - writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); - writeFileSync(join(project, ".braintrust.json"), JSON.stringify({ trace_to_braintrust: false })); - const hook = vi.fn(async () => {}); - const subscribe = vi.fn(async function* () {}); - const ctx = { - app: { version: "2.2.5" }, - location: { directory }, - session: { hook, get: async () => ({}) }, - event: { subscribe }, - tool: { transform: async () => {} }, - }; - expect(await plugin.setup(ctx)).toBeUndefined(); - expect(hook).not.toHaveBeenCalled(); - expect(subscribe).not.toHaveBeenCalled(); - vi.stubEnv( - "BT_TRACE_INVOCATION_SETTINGS", - JSON.stringify({ - trace_to_braintrust: true, - route: { destination: { type: "project_logs", project_name: "managed" } }, - }), - ); - const cleanup = await plugin.setup(ctx); - expect(hook).toHaveBeenCalled(); - expect(subscribe).toHaveBeenCalled(); - await cleanup?.(); -}); +it.each([".braintrust.json", join(".opencode", "braintrust.json")])( + "applies the %s opt-out to OpenCode 2 and permits a managed run", + async (configPath) => { + const global = join(directory, "config", "opencode"); + const projectConfig = join(directory, configPath); + mkdirSync(global, { recursive: true }); + mkdirSync(dirname(projectConfig), { recursive: true }); + writeFileSync(join(global, "braintrust.json"), JSON.stringify({ trace_to_braintrust: true })); + writeFileSync(projectConfig, JSON.stringify({ trace_to_braintrust: false })); + const hook = vi.fn(async () => {}); + const subscribe = vi.fn(async function* () {}); + const ctx = { + app: { version: "2.2.5" }, + location: { directory }, + session: { hook, get: async () => ({}) }, + event: { subscribe }, + tool: { transform: async () => {} }, + }; + expect(await plugin.setup(ctx)).toBeUndefined(); + expect(hook).not.toHaveBeenCalled(); + expect(subscribe).not.toHaveBeenCalled(); + vi.stubEnv( + "BT_TRACE_INVOCATION_SETTINGS", + JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "managed" } }, + }), + ); + const cleanup = await plugin.setup(ctx); + expect(hook).toHaveBeenCalled(); + expect(subscribe).toHaveBeenCalled(); + await cleanup?.(); + }, +); diff --git a/src/plugins/opencode/content/src/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index c2a75524..249fedf7 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -17,10 +17,8 @@ export async function readPluginConfig(input: { const path = await import("node:path"); const os = await import("node:os"); const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"); - const configPaths = [ - path.join(configHome, "opencode", "braintrust.json"), - projectSettingsPath(input.directory), - ]; + const projectPath = projectSettingsPath(input.directory); + const configPaths = [path.join(configHome, "opencode", "braintrust.json"), projectPath]; for (const [index, configPath] of configPaths.entries()) { try { if (fs.existsSync(configPath)) { @@ -94,6 +92,25 @@ export async function readPluginConfig(input: { if (index === 1) pluginConfig = { ...pluginConfig, trace_to_braintrust: false }; } } + + if (pluginConfig?.trace_to_braintrust !== true) return pluginConfig; + + const legacyDirectories = new Set([input.directory, path.dirname(projectPath)]); + for (const directory of legacyDirectories) { + const configPath = path.join(directory, ".opencode", "braintrust.json"); + try { + if (!fs.existsSync(configPath)) continue; + const legacy = JSON.parse(fs.readFileSync(configPath, "utf-8")) as Pick< + PluginConfig, + "trace_to_braintrust" + > | null; + if (legacy?.trace_to_braintrust === false) { + return { ...pluginConfig, trace_to_braintrust: false }; + } + } catch { + // Preserve the legacy loader's handling of unreadable project files. + } + } } catch { // Config loading failed; invocation settings can still enable tracing. } diff --git a/src/plugins/pi/content/README.md b/src/plugins/pi/content/README.md index 1c8f50b0..af6a8dca 100644 --- a/src/plugins/pi/content/README.md +++ b/src/plugins/pi/content/README.md @@ -84,8 +84,15 @@ Settings load in this order, with later values taking precedence: 1. Defaults 2. `~/.pi/agent/braintrust.json` -3. `.pi/braintrust.json` in the project (or Pi's configured project config directory) -4. `bt trace run` settings for that invocation +3. `.braintrust.json` at the Git root, or in the working directory outside Git + +An explicit tracing opt-out in the legacy `.pi/braintrust.json` (or the host's +configured project config directory) still disables tracing, even if +`.braintrust.json` enables it. The extension checks the working directory and +the Git root for legacy opt-outs and uses only the tracing flag from those +files. To migrate an opt-out, set `"trace_to_braintrust": false` in +`.braintrust.json`. `bt trace run` can override these settings for one +invocation. Example: diff --git a/src/plugins/pi/content/src/config.test.ts b/src/plugins/pi/content/src/config.test.ts index 5b79ff5d..0b5eba7d 100644 --- a/src/plugins/pi/content/src/config.test.ts +++ b/src/plugins/pi/content/src/config.test.ts @@ -1,8 +1,11 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { loadConfig } from "./config.ts"; +import { runningPiPackage } from "./pi-package.ts"; + +vi.mock("./pi-package.ts", () => ({ runningPiPackage: vi.fn() })); const ENVIRONMENT_KEYS = [ "BRAINTRUST_PROFILE", @@ -28,6 +31,7 @@ function writeJson(path: string, value: unknown): void { } beforeEach(() => { + vi.mocked(runningPiPackage).mockReturnValue({ configDir: ".pi" }); home = mkdtempSync(join(tmpdir(), "pi-config-home-")); cwd = mkdtempSync(join(tmpdir(), "pi-config-project-")); for (const key of HOME_KEYS) { @@ -132,6 +136,46 @@ describe("loadConfig", () => { expect(loadConfig(nested)).toMatchObject({ enabled: true, projectName: "repo" }); }); + it("honors a legacy project opt-out without applying the legacy route", () => { + mkdirSync(join(cwd, ".git")); + writeJson(join(home, ".pi", "agent", "braintrust.json"), { + trace_to_braintrust: true, + project: "global", + }); + writeJson(join(cwd, ".pi", "braintrust.json"), { + trace_to_braintrust: false, + project: "legacy", + }); + expect(loadConfig(cwd)).toMatchObject({ enabled: false, projectName: "global" }); + + const nested = join(cwd, "src"); + mkdirSync(nested); + writeJson(join(cwd, ".braintrust.json"), { trace_to_braintrust: true, project: "shared" }); + expect(loadConfig(nested)).toMatchObject({ enabled: false, projectName: "shared" }); + + writeJson(join(cwd, ".pi", "braintrust.json"), { + trace_to_braintrust: true, + project: "legacy", + }); + writeJson(join(cwd, ".braintrust.json"), { trace_to_braintrust: false, project: "shared" }); + expect(loadConfig(nested)).toMatchObject({ enabled: false, projectName: "shared" }); + }); + + it("honors the host's legacy config directory and permits a managed run", () => { + vi.mocked(runningPiPackage).mockReturnValue({ configDir: ".custom" }); + mkdirSync(join(cwd, ".git")); + const nested = join(cwd, "src"); + writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: true }); + writeJson(join(nested, ".custom", "braintrust.json"), { trace_to_braintrust: "off" }); + expect(loadConfig(nested).enabled).toBe(false); + + process.env.BT_TRACE_INVOCATION_SETTINGS = JSON.stringify({ + trace_to_braintrust: true, + route: { destination: { type: "project_logs", project_name: "run" } }, + }); + expect(loadConfig(nested)).toMatchObject({ enabled: true }); + }); + it("appends repository plugins relative to the shared configuration and can replace user plugins", () => { writeJson(join(home, ".pi", "agent", "braintrust.json"), { trace_to_braintrust: false, diff --git a/src/plugins/pi/content/src/config.ts b/src/plugins/pi/content/src/config.ts index f4a88255..4a13590d 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { type DaemonSessionRoute, projectSettingsPath, @@ -8,6 +8,7 @@ import { mergeProjectRoute, resolveDaemonTraceSettings, } from "./runtime/daemon-client.ts"; +import { runningPiPackage } from "./pi-package.ts"; export interface PiConfig { enabled: boolean; @@ -156,6 +157,18 @@ export function loadConfig(cwd = process.cwd()): PiConfig { config.enabled = false; } + if (config.enabled) { + const { configDir } = runningPiPackage(); + const legacyDirectories = new Set([cwd, dirname(projectPath)]); + for (const directory of legacyDirectories) { + const legacy = readConfig(join(directory, configDir, "braintrust.json")); + if (boolean(legacy?.trace_to_braintrust) === false) { + config.enabled = false; + break; + } + } + } + config.showUi = boolean(process.env.BRAINTRUST_SHOW_UI) ?? config.showUi; config.showTraceLink = boolean(process.env.BRAINTRUST_SHOW_TRACE_LINK) ?? config.showTraceLink;