Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion bt-daemon/tests/agent_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@ fn shell_tool_call(request: &OpenAiRequest, call_id: &str, command: &str) -> Ope
.into_iter()
.find(|name| names.contains(name))
.unwrap_or_else(|| {
panic!("agent offered no supported shell tool; offered tools: {names:?}")
// Include the raw request shape: an empty list can mean the agent
// sent no tools or that it changed how tools are encoded.
let keys: Vec<_> = request.body.as_object().into_iter().flatten().map(|(key, _)| key).collect();
let tools = request.body.get("tools").map(Value::to_string).unwrap_or_default();
panic!(
"agent offered no supported shell tool; offered tools: {names:?}; request keys: {keys:?}; tools: {}",
&tools[..tools.len().min(2000)]
)
});
let arguments = match name {
"exec_command" => json!({"cmd": command, "login": false}),
Expand Down Expand Up @@ -386,6 +393,9 @@ async fn pi_session_emits_traces() {
.mock_inference(inference_server.uri()),
)
.await;
// Trace-delivery failures panic without the agent's own output; print it
// so CI shows what Pi reported (shown with --nocapture).
eprintln!("Pi output:\n{}", output.text());
output.assert_success();
if world.uses_mock_inference() {
output.assert_contains("PI_MOCK_OK");
Expand Down
25 changes: 22 additions & 3 deletions src/plugins/pi/content/src/daemon-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ const mockState = vi.hoisted(() => ({
closed: 0,
claim: true,
hyperlinks: true,
// Oh My Pi's pi-tui exports neither getCapabilities() nor hyperlink().
// A pi-tui without getCapabilities() or hyperlink(), like older hosts.
ompTui: false,
hostName: "@earendil-works/pi-coding-agent",
tuiLoads: 0,
legacyContinuation: undefined as Record<string, unknown> | undefined,
legacyContinuationFor: vi.fn(),
logGate: undefined as Promise<void> | undefined,
Expand All @@ -22,6 +24,7 @@ vi.mock("@earendil-works/pi-tui", async (importOriginal) => {
return {
...original,
get getCapabilities() {
mockState.tuiLoads += 1;
return mockState.ompTui ? undefined : () => ({ hyperlinks: mockState.hyperlinks });
},
get hyperlink() {
Expand Down Expand Up @@ -92,7 +95,7 @@ vi.mock("./legacy-session.ts", () => ({

vi.mock("./pi-package.ts", () => ({
runningPiPackage: () => ({
name: "@oh-my-pi/pi-coding-agent",
name: mockState.hostName,
version: "18.12.6",
configDir: ".pi",
}),
Expand Down Expand Up @@ -132,6 +135,8 @@ describe("Pi daemon adapter", () => {
mockState.claim = true;
mockState.hyperlinks = true;
mockState.ompTui = false;
mockState.hostName = "@earendil-works/pi-coding-agent";
mockState.tuiLoads = 0;
mockState.legacyContinuation = undefined;
mockState.legacyContinuationFor.mockClear();
mockState.logGate = undefined;
Expand All @@ -157,7 +162,7 @@ describe("Pi daemon adapter", () => {
source: "pi",
source_version: "18.12.6",
ts_ms: 1_234,
payload: { host_name: "@oh-my-pi/pi-coding-agent" },
payload: { host_name: "@earendil-works/pi-coding-agent" },
});
});

Expand Down Expand Up @@ -354,6 +359,20 @@ describe("Pi daemon adapter", () => {
await handlers.get("session_shutdown")?.({ reason: "quit" }, ctx);
});

it("never loads upstream pi-tui under Oh My Pi", async () => {
// Oh My Pi 19.2+ refuses to load extensions that import upstream pi-tui.
mockState.hostName = "@oh-my-pi/pi-coding-agent";
const setStatus = vi.fn();
const ctx = fakeContext({ setStatus, setWidget: vi.fn() });
const handlers = await loadExtension();
await handlers.get("session_start")?.({ reason: "new" }, ctx);
await vi.waitFor(() =>
expect(setStatus).toHaveBeenCalledWith("braintrust-tracing", "Braintrust: connected"),
);
expect(mockState.tuiLoads).toBe(0);
await handlers.get("session_shutdown")?.({ reason: "quit" }, ctx);
});

it("polls for the trace link until the daemon delivers the first turn", async () => {
vi.useFakeTimers();
try {
Expand Down
49 changes: 37 additions & 12 deletions src/plugins/pi/content/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createHash, randomUUID } from "node:crypto";
import { resolve } from "node:path";
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import * as piTui from "@earendil-works/pi-tui";
import { loadConfig } from "./config.ts";
import { legacyContinuationFor, type LegacyContinuation } from "./legacy-session.ts";
import { runningPiPackage } from "./pi-package.ts";
Expand All @@ -18,15 +17,37 @@ const TRACE_LINK_POLL_TIMEOUT_MS = 40_000;
const PI_VERSION = runningPiPackage().version;
const PI_HOST_NAME = runningPiPackage().name;

/**
* Oh My Pi resolves this package to its own pi-tui, which exports neither
* helper. A named import would fail to link and OMP would silently drop the
* extension, so read them from the namespace and fall back to plain text.
*/
function terminalHyperlink(text: string, url: string): string | undefined {
const { getCapabilities, hyperlink } = piTui as Partial<typeof piTui>;
if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined;
return getCapabilities().hyperlinks ? hyperlink(text, url) : undefined;
// Oh My Pi 19.2+ refuses to load an extension whose source names upstream
// pi-tui, even in a literal dynamic import, and its own pi-tui has no link
// helpers. Other hosts load it through a computed specifier; keep it computed
// (src/plugins/pi/validate.sh rejects a literal in the build).
const PI_TUI_PACKAGE = ["@earendil-works", "pi-tui"].join("/");
const OH_MY_PI_PACKAGE = "@oh-my-pi/pi-coding-agent";

interface HyperlinkHelpers {
getCapabilities(): { hyperlinks?: boolean };
hyperlink(text: string, url: string): string;
}

async function loadHyperlinkHelpers(): Promise<HyperlinkHelpers | undefined> {
if (runningPiPackage().name === OH_MY_PI_PACKAGE) return undefined;
try {
const { getCapabilities, hyperlink } = (await import(
PI_TUI_PACKAGE
)) as Partial<HyperlinkHelpers>;
if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined;
return { getCapabilities, hyperlink };
} catch {
return undefined;
}
}

function terminalHyperlink(
helpers: HyperlinkHelpers | undefined,
text: string,
url: string,
): string | undefined {
return helpers?.getCapabilities().hyperlinks ? helpers.hyperlink(text, url) : undefined;
}

function sessionKeyFor(
Expand Down Expand Up @@ -95,6 +116,7 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void {
let traceLinkShown = false;
let traceLinkPollGeneration: number | undefined;
let traceLinkPollTimer: ReturnType<typeof setTimeout> | undefined;
let hyperlinkHelpers: Promise<HyperlinkHelpers | undefined> | undefined;
const client = new DaemonClient({
source: "pi",
pluginVersion: EXTENSION_VERSION,
Expand Down Expand Up @@ -139,7 +161,10 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void {
if (!ctx.hasUI || !config.showUi || !sessionId) return;
const refreshGeneration = uiGeneration;
const refreshSessionId = sessionId;
const status = await statusClient.status(refreshSessionId);
const [status, links] = await Promise.all([
statusClient.status(refreshSessionId),
config.showTraceLink ? (hyperlinkHelpers ??= loadHyperlinkHelpers()) : undefined,
]);
if (uiGeneration !== refreshGeneration || sessionId !== refreshSessionId) return;
const daemonSession = status?.sessions.find(
(session) => session.session_id === refreshSessionId,
Expand All @@ -151,7 +176,7 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void {
} else {
ctx.ui.setStatus(
STATUS_KEY,
(permalink && terminalHyperlink(traceLabel, permalink)) || "Braintrust: connected",
(permalink && terminalHyperlink(links, traceLabel, permalink)) || "Braintrust: connected",
);
}
traceLinkShown = Boolean(permalink);
Expand Down
5 changes: 5 additions & 0 deletions src/plugins/pi/validate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ TARGET_DIR="$(cd "$TARGET_DIR" && pwd)"
[[ -f "$TARGET_DIR/package.json" ]] || fail "missing package.json"
[[ -f "$TARGET_DIR/dist/index.mjs" ]] || fail "missing production entrypoint"
[[ -f "$TARGET_DIR/dist/index.d.mts" ]] || fail "missing production declarations"
# Oh My Pi 19.2+ refuses to load an extension that names upstream pi-tui, even
# in a literal dynamic import; src/index.ts loads it via a computed specifier.
if grep -nE "[\"'\`]@(earendil-works|mariozechner)/pi-tui" "$TARGET_DIR/dist/index.mjs"; then
fail "production entrypoint names upstream pi-tui; Oh My Pi 19.2+ will not load it"
fi

(cd "$SOURCE_DIR" && pnpm install --frozen-lockfile)
(cd "$SOURCE_DIR" && pnpm run check && pnpm test && pnpm run build && pnpm run smoke)
Expand Down
Loading