:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): add an agent-smoke entrypoint that drives one gateway turn (#105730)
Alessandro Pogliaghi7e21cfe269d2
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.jsonindex 265e0a2f8110..307dd345a9e8 100644--- a/products/desktop/packages/agent/package.json+++ b/products/desktop/packages/agent/package.json@@ -130,7 +130,8 @@}},"bin": {- "agent-server": "./dist/server/bin.js"+ "agent-server": "./dist/server/bin.js",+ "agent-smoke": "./dist/smoke/bin.js"},"type": "module","keywords": [diff --git a/products/desktop/packages/agent/src/smoke/bin.ts b/products/desktop/packages/agent/src/smoke/bin.tsnew file mode 100644index 000000000000..dfe5f95d2278--- /dev/null+++ b/products/desktop/packages/agent/src/smoke/bin.ts@@ -0,0 +1,96 @@+#!/usr/bin/env node+import { Command, Option } from "commander";+import { DEFAULT_CODEX_MODEL, DEFAULT_GATEWAY_MODEL } from "../gateway-models";+import { buildGatewayEnv } from "../server/gateway-env";+import { Logger } from "../utils/logger";+import { redactSecrets } from "../utils/redact-secrets";+import { classifyFailure, classifyOutcome, type SmokeResult } from "./classify";+import { runTurn } from "./run-turn";++const EXIT_CODES: Record<SmokeResult, number> = {+ pass: 0,+ broken: 1,+ inconclusive: 2,+ infra: 3,+};++const program = new Command()+ .name("agent-smoke")+ .description(+ "Drive one agent turn through the Go ai-gateway and report the result as one JSON line",+ )+ .addOption(+ new Option("--runtime <runtime>", "runtime adapter to drive")+ .choices(["claude", "codex"])+ .makeOptionMandatory(),+ )+ .option("--timeout <seconds>", "turn timeout in seconds", "300")+ .parse();++const { runtime, timeout } = program.opts<{+ runtime: "claude" | "codex";+ timeout: string;+}>();+delete process.env.CLAUDE_CODE_USE_BEDROCK;+const token = process.env.AI_GATEWAY_TOKEN?.trim() ?? "";+const model =+ process.env.POSTHOG_CODE_MODEL ||+ (runtime === "codex" ? DEFAULT_CODEX_MODEL : DEFAULT_GATEWAY_MODEL);+const logger = new Logger({+ debug: true,+ prefix: "[agent-smoke]",+ onLog: (level, _scope, message, data) =>+ process.stderr.write(+ `[${level}] ${message} ${data === undefined ? "" : JSON.stringify(data)}\n`,+ ),+});+const gatewayEnv = buildGatewayEnv(+ {+ apiKey: "",+ apiUrl: process.env.POSTHOG_API_URL || "https://us.posthog.com",+ projectId: Number(process.env.POSTHOG_PROJECT_ID) || 0,+ },+ { runtimeAdapter: runtime },+ logger,+);++function report(result: SmokeResult, fields: Record<string, unknown>): never {+ const line = JSON.stringify({+ runtime,+ model,+ gateway: gatewayEnv.anthropicBaseUrl,+ result,+ ...fields,+ });+ process.stdout.write(+ `${token ? redactSecrets(line).replaceAll(token, "[REDACTED]") : line}\n`,+ );+ process.exit(EXIT_CODES[result]);+}++if (!token || gatewayEnv.anthropicAuthToken !== token) {+ report("infra", {+ error:+ "the agent did not route to the Go gateway: set AI_GATEWAY_URL, AI_GATEWAY_TOKEN, AI_GATEWAY_PRODUCT and AI_GATEWAY_PRODUCTS",+ });+}++try {+ const outcome = await runTurn({+ runtime,+ model,+ gatewayEnv,+ timeoutSeconds: Number(timeout),+ logger,+ });+ const result = classifyOutcome(outcome);+ report(result, {+ stop_reason: outcome.stopReason,+ tool_calls: outcome.completedToolCalls,+ reply_has_nonce: outcome.replyHasNonce,+ ...(result !== "pass" && { reply: outcome.reply.slice(0, 2000) }),+ });+} catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ report(classifyFailure(message), { error: message.slice(0, 2000) });+}diff --git a/products/desktop/packages/agent/src/smoke/classify.test.ts b/products/desktop/packages/agent/src/smoke/classify.test.tsnew file mode 100644index 000000000000..479752c326a1--- /dev/null+++ b/products/desktop/packages/agent/src/smoke/classify.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import { classifyFailure, classifyOutcome } from "./classify";++describe("smoke classification", () => {+ it.each([+ [+ 'API Error: 400 {"type":"error","error":{"message":"thinking.type: disabled is not supported"}}',+ "broken",+ ],+ ["API Error: 404 model not found", "broken"],+ ["unexpected status 401 Unauthorized", "broken"],+ ["API Error: 529 Overloaded", "inconclusive"],+ ["unexpected status 503 Service Unavailable", "inconclusive"],+ ["API Error: 429 rate limit exceeded", "inconclusive"],+ ["turn timed out after 300s", "inconclusive"],+ ["Internal error: API Error: terminated", "inconclusive"],+ ["Internal error: API Error: Connection error.", "inconclusive"],+ [+ "Internal error: The socket connection was closed unexpectedly",+ "inconclusive",+ ],+ ["Internal error: ACP connection closed", "broken"],+ [+ "The agent stopped before completing this request: fetch failed",+ "inconclusive",+ ],+ ["The file contains 500 lines", "broken"],+ ])("classifies the failure %s as %s", (message, expected) => {+ expect(classifyFailure(message)).toBe(expected);+ });++ it.each([+ ["end_turn", 1, true, "nonce", "pass"],+ ["end_turn", 0, true, "nonce", "broken"],+ ["end_turn", 1, false, "rate limit exceeded", "broken"],+ [+ "refusal",+ 0,+ false,+ "unexpected status 503 Service Unavailable",+ "inconclusive",+ ],+ ["refusal", 0, false, "unexpected status 401 Unauthorized", "broken"],+ ])(+ "classifies a %s turn with %i tool calls and nonce %s as %5$s",+ (stopReason, completedToolCalls, replyHasNonce, reply, expected) => {+ expect(+ classifyOutcome({+ stopReason,+ completedToolCalls,+ replyHasNonce,+ reply,+ }),+ ).toBe(expected);+ },+ );+});diff --git a/products/desktop/packages/agent/src/smoke/classify.ts b/products/desktop/packages/agent/src/smoke/classify.tsnew file mode 100644index 000000000000..a1449250d1a2--- /dev/null+++ b/products/desktop/packages/agent/src/smoke/classify.ts@@ -0,0 +1,34 @@+import {+ classifyAgentError,+ isRetryableUpstreamErrorClassification,+} from "../adapters/error-classification";+import type { TurnOutcome } from "./run-turn";++export type SmokeResult = "pass" | "broken" | "inconclusive" | "infra";++const TRANSIENT_STATUS = /\b(?:error|status|http)\D{0,12}(?:429|5\d\d)\b/i;+const TRANSIENT_TEXT =+ /timed out|overloaded|rate limit|ECONNRESET|ETIMEDOUT|fetch failed|error sending request/i;++const LOCAL_ACP_CLOSED = /^ACP connection closed$/i;++export function classifyFailure(message: string): "broken" | "inconclusive" {+ const cause = message.replace(/^Internal error:\s*/i, "");+ if (LOCAL_ACP_CLOSED.test(cause)) {+ return "broken";+ }+ return TRANSIENT_STATUS.test(cause) ||+ TRANSIENT_TEXT.test(cause) ||+ isRetryableUpstreamErrorClassification(classifyAgentError(cause))+ ? "inconclusive"+ : "broken";+}++export function classifyOutcome(outcome: TurnOutcome): SmokeResult {+ if (outcome.stopReason !== "end_turn") {+ return classifyFailure(outcome.reply);+ }+ return outcome.completedToolCalls > 0 && outcome.replyHasNonce+ ? "pass"+ : "broken";+}diff --git a/products/desktop/packages/agent/src/smoke/run-turn.ts b/products/desktop/packages/agent/src/smoke/run-turn.tsnew file mode 100644index 000000000000..d3807a769a9c--- /dev/null+++ b/products/desktop/packages/agent/src/smoke/run-turn.ts@@ -0,0 +1,155 @@+import { randomUUID } from "node:crypto";+import { promises as fsp, mkdtempSync, realpathSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import {+ type Client,+ ClientSideConnection,+ ndJsonStream,+} from "@agentclientprotocol/sdk";+import type { Adapter } from "@posthog/shared";+import {+ type AcpConnection,+ createAcpConnection,+} from "../adapters/acp-connection";+import type { GatewayEnv } from "../adapters/claude/session/options";+import { codexAuthFromGatewayEnv } from "../server/gateway-env";+import type { Logger } from "../utils/logger";++export interface TurnOutcome {+ stopReason: string | undefined;+ completedToolCalls: number;+ replyHasNonce: boolean;+ reply: string;+}++const PROMPT =+ "Use a tool to read the file nonce.txt, then reply with its contents only.";++export async function runTurn({+ runtime,+ model,+ gatewayEnv,+ timeoutSeconds,+ logger,+}: {+ runtime: Adapter;+ model: string;+ gatewayEnv: GatewayEnv;+ timeoutSeconds: number;+ logger: Logger;+}): Promise<TurnOutcome> {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), "agent-smoke-")));+ let acp: AcpConnection | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const nonce = randomUUID();+ await fsp.writeFile(join(cwd, "nonce.txt"), `${nonce}\n`);++ let reply = "";+ const completedToolCallIds = new Set<string>();+ const client: Client = {+ async sessionUpdate({ update }) {+ if (+ update.sessionUpdate === "agent_message_chunk" &&+ update.content.type === "text"+ ) {+ reply += update.content.text;+ }+ if (+ (update.sessionUpdate === "tool_call" ||+ update.sessionUpdate === "tool_call_update") &&+ update.status === "completed"+ ) {+ completedToolCallIds.add(update.toolCallId);+ }+ },+ async requestPermission({ options }) {+ const allow =+ options.find(+ (o) => o.kind === "allow_once" || o.kind === "allow_always",+ ) ?? options[0];+ return {+ outcome: {+ outcome: "selected",+ optionId: allow?.optionId ?? "allow",+ },+ };+ },+ async readTextFile({ path }) {+ return { content: await fsp.readFile(resolve(cwd, path), "utf8") };+ },+ async writeTextFile({ path, content }) {+ await fsp.writeFile(resolve(cwd, path), content);+ return {};+ },+ async extNotification() {},+ };++ acp = createAcpConnection({+ adapter: runtime,+ deviceType: "cloud",+ logger,+ claudeGatewayEnv: runtime === "claude" ? gatewayEnv : undefined,+ codexOptions:+ runtime === "codex"+ ? {+ cwd,+ ...codexAuthFromGatewayEnv(gatewayEnv),+ binaryPath: process.env.POSTHOG_CODEX_BINARY_PATH,+ model,+ httpHeaders: gatewayEnv.openaiCustomHeaders,+ }+ : undefined,+ });+ const conn = new ClientSideConnection(+ () => client,+ ndJsonStream(acp.clientStreams.writable, acp.clientStreams.readable),+ );+ let sessionId: string | undefined;+ const turn = (async () => {+ await conn.initialize({ protocolVersion: 1, clientCapabilities: {} });+ const session = await conn.newSession({+ cwd,+ mcpServers: [],+ _meta: {+ environment: "cloud",+ model,+ permissionMode: runtime === "codex" ? "auto" : "bypassPermissions",+ },+ });+ sessionId = session.sessionId;+ return conn.prompt({+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: PROMPT }],+ });+ })();+ turn.catch(() => undefined);+ const { stopReason } = await Promise.race([+ turn,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ if (sessionId) {+ conn.cancel({ sessionId }).catch(() => undefined);+ }+ reject(new Error(`turn timed out after ${timeoutSeconds}s`));+ }, timeoutSeconds * 1000);+ }),+ ]);+ return {+ stopReason,+ completedToolCalls: completedToolCallIds.size,+ replyHasNonce: reply.includes(nonce),+ reply,+ };+ } finally {+ clearTimeout(timer);+ if (acp) {+ await Promise.race([+ acp.cleanup().catch(() => undefined),+ new Promise<void>((r) => setTimeout(r, 8000)),+ ]);+ }+ await fsp.rm(cwd, { recursive: true, force: true });+ }+}diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.tsindex dfa34b379b65..1056c9ff947b 100644--- a/products/desktop/packages/agent/tsup.config.ts+++ b/products/desktop/packages/agent/tsup.config.ts@@ -200,6 +200,7 @@ export default defineConfig(["src/server/schemas.ts","src/server/agent-server.ts","src/server/bin.ts",+ "src/smoke/bin.ts",],format: ["esm"],dts: false,