Skip to content

: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.

refactor(agent): create launch config (#120118)

Jonathan Mielooea2a7da0d9f5
diff --git a/packages/agent/biome.jsonc b/packages/agent/biome.jsonc
index a7f8f91440a7..85e1b3f62180 100644
--- a/packages/agent/biome.jsonc
+++ b/packages/agent/biome.jsonc
@@ -87,7 +87,8 @@
"packages/agent/src/sdk/**/*.ts",
"packages/agent/src/server/agent-server.ts",
"packages/agent/src/server/pi-agent-server.ts",
- "packages/agent/src/server/product/**/*.ts"
+ "packages/agent/src/server/product/**/*.ts",
+ "packages/agent/src/server/launch/**/*.ts"
],
"linter": {
"rules": {
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 9d9d0386cd74..10cec653112e 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -131,7 +131,6 @@ import type {
TaskRun,
TaskRunArtifact,
TaskRunState,
- TaskRunStateField,
} from "../types";
import { resourceLink } from "../utils/acp-content";
import { attachmentFilePath, safeArtifactFileName } from "../utils/attachments";
@@ -159,6 +158,7 @@ import {
type GatewayEnvInput,
} from "./gateway-env";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
+import { readProductLaunch, readRunLaunch } from "./launch/run-launch";
import { type McpRelayResponse, McpRelayServer } from "./mcp-relay-server";
import {
CliProcessRegistry,
@@ -172,7 +172,6 @@ import {
import {
appendClosingInstructions,
openProductSession,
- readOriginProduct,
readQuestionRequest,
resolvePullRequestFooter,
} from "./product/session";
@@ -180,7 +179,6 @@ import { createRtkSavingsNotification } from "./rtk-savings";
import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";
import {
type CredentialResponseParams,
- claudeCodeConfigSchema,
jsonRpcRequestSchema,
validateCommandParams,
} from "./schemas";
@@ -439,14 +437,6 @@ interface LocalSkillPromptContext {
context: string;
}
-function getTaskRunStateString(
- taskRun: TaskRun | null,
- key: TaskRunStateField,
-): string | null {
- const value = taskRun?.state[key];
- return typeof value === "string" ? value : null;
-}
-
type SteerDeclineReason =
| "startup_turn"
| "no_active_turn"
@@ -2156,17 +2146,23 @@ export class AgentServer {
this.fetchTaskForSessionContext(payload.task_id),
]),
);
- this.taskRepositories =
- preTask?.repositories ??
- (preTask?.repository ? [preTask.repository] : []);
+ const launchSources = {
+ payload,
+ task: preTask,
+ taskRun: preTaskRun,
+ config: this.config,
+ env: process.env,
+ };
+ const launch = readRunLaunch(launchSources);
+ this.taskRepositories = launch.repositories;
this.runUsage = new RunUsageAccumulator();
this.runUsageRunId = payload.run_id;
this.lastBudgetSnapshot = undefined;
this.lastPersistedBudgetKey = undefined;
this.budgetPersistInFlightKey = undefined;
- seedRunUsage(this.runUsage, preTaskRun?.state.token_usage);
- this.prewarmedRun = preTaskRun?.state.prewarmed === true;
+ seedRunUsage(this.runUsage, launch.tokenUsage);
+ this.prewarmedRun = launch.prewarmed === true;
this.prewarmedStartupTurnPending = this.prewarmedRun;
const runtimeAdapter = this.getRuntimeAdapter();
@@ -2180,28 +2176,23 @@ export class AgentServer {
const gatewayEnv = this.configureEnvironment({
runSpanContext: telemetry?.getRunSpanContext(),
- isInternal: preTask?.internal === true,
- originProduct: preTask?.origin_product,
- signalReportId: preTask?.signal_report,
- aiStage: getTaskRunStateString(preTaskRun, "ai_stage"),
- aiAgentName: getTaskRunStateString(preTaskRun, "ai_agent_name"),
+ isInternal: launch.internal,
+ originProduct: launch.originProduct,
+ signalReportId: launch.signalReportId,
+ aiStage: launch.aiStage,
+ aiAgentName: launch.aiAgentName,
taskId: payload.task_id,
taskRunId: payload.run_id,
- taskUserId: payload.user_id || preTask?.created_by?.id || null,
- taskTitle: preTask?.title,
- taskOriginKey: preTask?.origin_key,
- repositories: this.taskRepositories,
+ taskUserId: launch.userId,
+ taskTitle: launch.title,
+ taskOriginKey: launch.originKey,
+ repositories: launch.repositories,
runtimeAdapter,
- sandboxEnvironmentId: getTaskRunStateString(
- preTaskRun,
- "sandbox_environment_id",
- ),
- snapshotKind: preTaskRun
- ? (getTaskRunStateString(preTaskRun, "snapshot_kind") ?? "absent")
- : null,
- prewarmed: preTaskRun ? this.prewarmedRun : null,
+ sandboxEnvironmentId: launch.sandboxEnvironmentId,
+ snapshotKind: launch.snapshotKind,
+ prewarmed: launch.prewarmed,
executionEnvironment: "cloud",
- sharedPromptCache: preTaskRun?.state.codex_shared_prompt_cache === true,
+ sharedPromptCache: launch.sharedPromptCache,
});
// Only that stamped header makes the run id a trace the generations land
@@ -2219,62 +2210,36 @@ export class AgentServer {
}).catch(() => {});
}
- const runState = preTaskRun?.state;
-
- // Web backlink to the inbox report that spawned this task, so the
- // auto-generated PR can point back at it. Built from the same pieces as the
- // report's `_posthogUrl`: <apiUrl>/project/<projectId>/inbox/<reportId>.
- const signalReportId = preTask?.signal_report;
- const inboxReportUrl = signalReportId
- ? `${this.config.apiUrl.replace(/\/$/, "")}/project/${this.config.projectId}/inbox/${signalReportId}`
- : null;
-
// Unconditional so a re-init on the same instance drops the previous run's product
// behavior and PR URL.
- await this.openProductSession({
- taskId: payload.task_id,
- runId: payload.run_id,
- originProduct: readOriginProduct(),
- launchOptions: structuredClone(runState ?? {}),
- source: inboxReportUrl
- ? { label: "inbox report", url: inboxReportUrl }
- : undefined,
- });
+ await this.openProductSession(readProductLaunch(launchSources));
const prUrl = this.detectedPrUrl;
// Before the prompt: its skills-store section counts the stubs on disk.
await this.installStoreSkills(
payload.task_id,
payload.run_id,
- runState ?? null,
+ launch.runState,
);
// Before the adapter starts: Claude and Codex read these files when the session opens.
this.agentInstructions = await new AgentInstructionFiles(this.logger).sync(
- runState ?? null,
+ launch.runState,
{ taskId: payload.task_id, runId: payload.run_id },
);
- const runStateSystemPrompt =
- claudeCodeConfigSchema.shape.systemPrompt.safeParse(
- runState?.systemPrompt,
- );
- const runStateSystemPromptData = runStateSystemPrompt.success
- ? runStateSystemPrompt.data
- : undefined;
-
if (
- preTask?.origin_product === POSTHOG_AI_ORIGIN_PRODUCT &&
- !systemPromptAppendText(runStateSystemPromptData)
+ launch.originProduct === POSTHOG_AI_ORIGIN_PRODUCT &&
+ !systemPromptAppendText(launch.systemPrompt)
) {
this.logger.warn("posthog_ai_run_state_system_prompt_missing", {
runId: payload.run_id,
- parsed: runStateSystemPrompt.success,
+ parsed: launch.systemPromptValid,
});
}
const sessionSystemPrompt = this.buildSessionSystemPrompt(
prUrl,
- runStateSystemPromptData,
+ launch.systemPrompt,
);
const codexInstructions =
runtimeAdapter === "codex"
@@ -2390,10 +2355,10 @@ export class AgentServer {
serviceTier: this.config.serviceTier,
// Codex runs at most 3 sub-agents per session at once by default; the main agent does
// not count. A run that starts more sub-agents at once sets its own limit.
- ...(runState?.codex_max_subagents && {
+ ...(launch.codexMaxSubagents && {
configOverrides: {
"agents.max_concurrent_threads_per_session":
- runState.codex_max_subagents,
+ launch.codexMaxSubagents,
},
}),
developerInstructions: codexInstructions,
@@ -2445,18 +2410,8 @@ export class AgentServer {
// local sessions. Claude keeps the historical auto-approved default when
// PostHog Desktop has not explicitly selected a mode.
const initialPermissionMode: PermissionMode =
- typeof runState?.initial_permission_mode === "string"
- ? (runState.initial_permission_mode as PermissionMode)
- : runtimeAdapter === "codex"
- ? "auto"
- : "bypassPermissions";
- const pendingUserArtifactIds = Array.isArray(
- runState?.pending_user_artifact_ids,
- )
- ? runState.pending_user_artifact_ids.filter(
- (artifactId): artifactId is string => typeof artifactId === "string",
- )
- : [];
+ launch.initialPermissionMode ??
+ (runtimeAdapter === "codex" ? "auto" : "bypassPermissions");
const sessionCwd = this.config.repositoryPath ?? "/tmp/workspace";
// Only a run with no repository at all gets the discover-and-clone tools;
// a multi-repository workspace already has its repos on disk.
@@ -2471,15 +2426,15 @@ export class AgentServer {
systemPrompt: sessionSystemPrompt,
...(this.config.model && { model: this.config.model }),
allowedDomains: this.config.allowedDomains,
- jsonSchema: preTask?.json_schema ?? null,
+ jsonSchema: launch.jsonSchema,
permissionMode: initialPermissionMode,
...(channelMode && { channelMode: true }),
budgetSteer: { mode: this.budgetSteerMode() },
posthogExecPermissionRegex: this.posthogExecPermissionRegexSource,
- ...(preTask?.origin_product && {
- taskOriginProduct: preTask.origin_product,
+ ...(launch.originProduct && {
+ taskOriginProduct: launch.originProduct,
}),
- ...(runState?.end_run_when_done === true && { endRunWhenDone: true }),
+ ...(launch.endRunWhenDone && { endRunWhenDone: true }),
...(this.config.baseBranch && { baseBranch: this.config.baseBranch }),
...(runtimeAdapter === "claude" &&
this.config.contextWindow && {
@@ -2519,7 +2474,7 @@ export class AgentServer {
payload.run_id,
this.getArtifactsById(
preTaskRun?.artifacts,
- pendingUserArtifactIds,
+ launch.pendingUserArtifactIds,
),
);
const preparedNativeResume = await this.prepareNativeResume(
diff --git a/packages/agent/packages/agent/src/server/launch/run-launch.test.ts b/packages/agent/packages/agent/src/server/launch/run-launch.test.ts
new file mode 100644
index 000000000000..74dde1fdb8fe
--- /dev/null
+++ b/packages/agent/packages/agent/src/server/launch/run-launch.test.ts
@@ -0,0 +1,161 @@
+import { taskRunStateSchema } from "@posthog/agent-contracts";
+import { describe, expect, it } from "vitest";
+import { createTask, createTaskRun } from "../../test/fixtures/api";
+import type { Task, TaskRun } from "../../types";
+import {
+ type RunLaunchSources,
+ readProductLaunch,
+ readRunLaunch,
+} from "./run-launch";
+
+interface SourceOverrides
+ extends Partial<Pick<RunLaunchSources, "task" | "taskRun" | "env">> {
+ userId?: number;
+ apiUrl?: string;
+}
+
+function sources({
+ userId = 0,
+ apiUrl = "https://us.posthog.com",
+ ...overrides
+}: SourceOverrides = {}): RunLaunchSources {
+ return {
+ payload: { task_id: "task-1", run_id: "run-1", user_id: userId },
+ task: createTask(),
+ taskRun: createTaskRun(),
+ config: { apiUrl, projectId: 2 },
+ env: {},
+ ...overrides,
+ };
+}
+
+function runWithState(state: Record<string, unknown>): TaskRun {
+ return createTaskRun({ state: taskRunStateSchema.parse(state) });
+}
+
+describe("run launch", () => {
+ describe("readRunLaunch", () => {
+ it.each<[string, TaskRun | null, string | null]>([
+ ["the recorded kind", runWithState({ snapshot_kind: "warm" }), "warm"],
+ ["absent when the run has none", runWithState({}), "absent"],
+ ["unknown when the run was not fetched", null, null],
+ ])("reads the snapshot kind as %s", (_, taskRun, expected) => {
+ expect(readRunLaunch(sources({ taskRun })).snapshotKind).toBe(expected);
+ });
+
+ it.each<[string, TaskRun | null, boolean | null]>([
+ ["prewarmed", runWithState({ prewarmed: true }), true],
+ ["not prewarmed", runWithState({}), false],
+ ["unknown when the run was not fetched", null, null],
+ ])("reads the run as %s", (_, taskRun, expected) => {
+ expect(readRunLaunch(sources({ taskRun })).prewarmed).toBe(expected);
+ });
+
+ it.each<[string, number, Task | null, number | null]>([
+ ["the acting user first", 7, createTask({ created_by: user(3) }), 7],
+ [
+ "the creator for a system run",
+ 0,
+ createTask({ created_by: user(3) }),
+ 3,
+ ],
+ ["nobody without either", 0, null, null],
+ ])("attributes the run to %s", (_, userId, task, expected) => {
+ expect(readRunLaunch(sources({ userId, task })).userId).toBe(expected);
+ });
+
+ it.each<[string, Task | null, string[]]>([
+ [
+ "the repository list",
+ createTask({ repositories: ["org/a", "org/b"], repository: "org/c" }),
+ ["org/a", "org/b"],
+ ],
+ [
+ "the legacy single repository",
+ createTask({ repository: "org/c" }),
+ ["org/c"],
+ ],
+ [
+ "the legacy repository behind an empty list",
+ createTask({ repositories: [], repository: "org/c" }),
+ ["org/c"],
+ ],
+ ["no repositories without a task", null, []],
+ ])("reads %s", (_, task, expected) => {
+ expect(readRunLaunch(sources({ task })).repositories).toEqual(expected);
+ });
+
+ it.each<[string, Record<string, string>, string | undefined]>([
+ [
+ "the current variable first",
+ {
+ POSTHOG_CODE_INTERACTION_ORIGIN: "slack",
+ CODE_INTERACTION_ORIGIN: "code",
+ TWIG_INTERACTION_ORIGIN: "twig",
+ },
+ "slack",
+ ],
+ [
+ "the older variables as fallbacks",
+ { TWIG_INTERACTION_ORIGIN: "twig" },
+ "twig",
+ ],
+ ["nothing when unset", {}, undefined],
+ ])("reads the interaction origin from %s", (_, env, expected) => {
+ expect(readRunLaunch(sources({ env })).interactionOrigin).toBe(expected);
+ });
+
+ it.each<[string, unknown, string | undefined, boolean]>([
+ ["a valid prompt", "Be brief.", "Be brief.", true],
+ ["a missing prompt", undefined, undefined, true],
+ ["an invalid prompt", 42, undefined, false],
+ ])("reads %s from the run state", (_, systemPrompt, expected, valid) => {
+ const launch = readRunLaunch(
+ sources({ taskRun: runWithState({ systemPrompt }) }),
+ );
+
+ expect([launch.systemPrompt, launch.systemPromptValid]).toEqual([
+ expected,
+ valid,
+ ]);
+ });
+ });
+
+ describe("readProductLaunch", () => {
+ it("links the product source to the inbox report", () => {
+ const launch = readProductLaunch(
+ sources({
+ apiUrl: "https://us.posthog.com/",
+ task: createTask({ signal_report: "rep_1" }),
+ }),
+ );
+
+ expect(launch.source).toEqual({
+ label: "inbox report",
+ url: "https://us.posthog.com/project/2/inbox/rep_1",
+ });
+ });
+
+ it("gives products a copy of the run state", () => {
+ const taskRun = runWithState({
+ slack_thread_url: "https://slack/thread",
+ });
+ const launch = readProductLaunch(sources({ taskRun }));
+
+ (launch.launchOptions as Record<string, unknown>).slack_thread_url =
+ "changed";
+
+ expect(taskRun.state.slack_thread_url).toBe("https://slack/thread");
+ });
+ });
+});
+
+function user(id: number): NonNullable<Task["created_by"]> {
+ return {
+ id,
+ uuid: `user-${id}`,
+ distinct_id: `user-${id}`,
+ first_name: "Test",
+ email: `user-${id}@example.com`,
+ };
+}
diff --git a/packages/agent/packages/agent/src/server/launch/run-launch.ts b/packages/agent/packages/agent/src/server/launch/run-launch.ts
new file mode 100644
index 000000000000..609beddefecc
--- /dev/null
+++ b/packages/agent/packages/agent/src/server/launch/run-launch.ts
@@ -0,0 +1,119 @@
+import { getProjectWebUrl } from "@posthog/agent-contracts/rich-output-prompt";
+import type { PermissionMode } from "../../execution-mode";
+import type { ProductLaunchConfiguration, TaskSource } from "../../sdk/product";
+import type { Task, TaskRun, TaskRunState } from "../../types";
+import type { JwtPayload } from "../jwt";
+import { claudeCodeConfigSchema } from "../schemas";
+import type { AgentServerConfig, ClaudeCodeConfig } from "../types";
+
+export interface RunLaunchSources {
+ readonly payload: Pick<JwtPayload, "task_id" | "run_id" | "user_id">;
+ readonly task: Task | null;
+ readonly taskRun: TaskRun | null;
+ readonly config: Pick<AgentServerConfig, "apiUrl" | "projectId">;
+ readonly env: Readonly<Record<string, string | undefined>>;
+}
+
+export interface RunLaunch {
+ readonly userId: number | null;
+ readonly title: string | null;
+ readonly originProduct: string | null;
+ readonly originKey: string | null;
+ readonly interactionOrigin: string | undefined;
+ readonly internal: boolean;
+ readonly signalReportId: string | null;
+ readonly repositories: string[];
+ readonly jsonSchema: Record<string, unknown> | null;
+ readonly aiStage: string | null;
+ readonly aiAgentName: string | null;
+ readonly sandboxEnvironmentId: string | null;
+ readonly snapshotKind: string | null;
+ readonly prewarmed: boolean | null;
+ readonly sharedPromptCache: boolean;
+ readonly codexMaxSubagents: number | null;
+ readonly initialPermissionMode: PermissionMode | null;
+ readonly pendingUserArtifactIds: string[];
+ readonly endRunWhenDone: boolean;
+ readonly systemPrompt: ClaudeCodeConfig["systemPrompt"];
+ readonly systemPromptValid: boolean;
+ readonly tokenUsage: unknown;
+ readonly runState: TaskRunState | null;
+}
+
+export function readRunLaunch(sources: RunLaunchSources): RunLaunch {
+ const { task, taskRun } = sources;
+ const runState = taskRun?.state ?? null;
+ const systemPrompt = claudeCodeConfigSchema.shape.systemPrompt.safeParse(
+ runState?.systemPrompt,
+ );
+
+ return {
+ userId: sources.payload.user_id || task?.created_by?.id || null,
+ title: task?.title ?? null,
+ originProduct: task?.origin_product ?? null,
+ originKey: task?.origin_key ?? null,
+ interactionOrigin: readInteractionOrigin(sources.env),
+ internal: task?.internal === true,
+ signalReportId: task?.signal_report ?? null,
+ repositories: readRepositories(task),
+ jsonSchema: task?.json_schema ?? null,
+ aiStage: runState?.ai_stage ?? null,
+ aiAgentName: runState?.ai_agent_name ?? null,
+ sandboxEnvironmentId: runState?.sandbox_environment_id ?? null,
+ snapshotKind: taskRun ? (runState?.snapshot_kind ?? "absent") : null,
+ prewarmed: taskRun ? runState?.prewarmed === true : null,
+ sharedPromptCache: runState?.codex_shared_prompt_cache === true,
+ codexMaxSubagents: runState?.codex_max_subagents ?? null,
+ initialPermissionMode: runState?.initial_permission_mode ?? null,
+ pendingUserArtifactIds: runState?.pending_user_artifact_ids ?? [],
+ endRunWhenDone: runState?.end_run_when_done === true,
+ systemPrompt: systemPrompt.success ? systemPrompt.data : undefined,
+ systemPromptValid: systemPrompt.success,
+ tokenUsage: runState?.token_usage,
+ runState,
+ };
+}
+
+export function readProductLaunch(
+ sources: RunLaunchSources,
+): ProductLaunchConfiguration {
+ return {
+ taskId: sources.payload.task_id,
+ runId: sources.payload.run_id,
+ originProduct: readInteractionOrigin(sources.env),
+ launchOptions: structuredClone(sources.taskRun?.state ?? {}),
+ source: readTaskSource(sources),
+ };
+}
+
+function readInteractionOrigin(
+ env: RunLaunchSources["env"],
+): string | undefined {
+ return (
+ env.POSTHOG_CODE_INTERACTION_ORIGIN ??
+ env.CODE_INTERACTION_ORIGIN ??
+ env.TWIG_INTERACTION_ORIGIN
+ );
+}
+
+function readRepositories(task: Task | null): string[] {
+ if (task?.repositories?.length) {
+ return task.repositories;
+ }
+ return task?.repository ? [task.repository] : [];
+}
+
+// Web backlink to the inbox report that spawned this task, so the
+// auto-generated PR can point back at it. Built from the same pieces as the
+// report's `_posthogUrl`: <apiUrl>/project/<projectId>/inbox/<reportId>.
+function readTaskSource(sources: RunLaunchSources): TaskSource | undefined {
+ const signalReportId = sources.task?.signal_report;
+ if (!signalReportId) {
+ return undefined;
+ }
+ const { apiUrl, projectId } = sources.config;
+ return {
+ label: "inbox report",
+ url: `${getProjectWebUrl(apiUrl, projectId)}/inbox/${signalReportId}`,
+ };
+}
diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.ts
index 0025476e5e46..c2b7049f104c 100644
--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts
+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts
@@ -66,6 +66,7 @@ import {
piModelIdForRoute,
} from "./gateway-env";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
+import { readRunLaunch } from "./launch/run-launch";
import { createRtkSavingsNotification } from "./rtk-savings";
import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";
import { jsonRpcRequestSchema } from "./schemas";
@@ -663,24 +664,25 @@ export class PiAgentServer {
return null;
}),
]);
- const runState = taskRun?.state;
- seedRunUsage(this.runUsage, runState?.token_usage);
+ const launch = readRunLaunch({
+ payload,
+ task,
+ taskRun,
+ config: this.config,
+ env: process.env,
+ });
+ seedRunUsage(this.runUsage, launch.tokenUsage);
// Before the prompt: its skills-store section counts the stubs on disk.
const storeSkillsInstalledCount = await syncStoreSkills(
- runState,
+ launch.runState,
{ taskId: payload.task_id, runId: payload.run_id },
this.logger,
);
// Before the Pi child starts: it reads ~/.pi/agent/AGENTS.md when it loads its resources.
- await new AgentInstructionFiles(this.logger).sync(runState, {
+ await new AgentInstructionFiles(this.logger).sync(launch.runState, {
taskId: payload.task_id,
runId: payload.run_id,
});
- const taskSnapshotKind = taskRun
- ? typeof runState?.snapshot_kind === "string"
- ? runState.snapshot_kind
- : "absent"
- : null;
const configuredSystemPrompt =
typeof this.config.claudeCode?.systemPrompt === "string"
? this.config.claudeCode.systemPrompt
@@ -703,36 +705,26 @@ export class PiAgentServer {
channelMode,
additionalInstructions,
};
- const aiStage =
- typeof runState?.ai_stage === "string" ? runState.ai_stage : null;
const providerRoute = buildPiProviderRoute(
this.config,
{
- originProduct: task?.origin_product ?? null,
- aiStage,
+ originProduct: launch.originProduct,
+ aiStage: launch.aiStage,
taskId: payload.task_id,
model: this.config.model,
properties: {
task_id: payload.task_id,
task_run_id: payload.run_id,
- task_origin_product: task?.origin_product ?? null,
- task_repositories: task?.repositories?.length
- ? JSON.stringify(task.repositories)
- : task?.repository
- ? JSON.stringify([task.repository])
- : null,
+ task_origin_product: launch.originProduct,
+ task_repositories: launch.repositories.length
+ ? JSON.stringify(launch.repositories)
+ : null,
task_runtime_adapter: "pi",
- task_sandbox_environment_id:
- typeof runState?.sandbox_environment_id === "string"
- ? runState.sandbox_environment_id
- : null,
- task_snapshot_kind: taskSnapshotKind,
- task_prewarmed: taskRun ? runState?.prewarmed === true : null,
- ai_stage: aiStage,
- ai_agent_name:
- typeof runState?.ai_agent_name === "string"
- ? runState.ai_agent_name
- : null,
+ task_sandbox_environment_id: launch.sandboxEnvironmentId,
+ task_snapshot_kind: launch.snapshotKind,
+ task_prewarmed: launch.prewarmed,
+ ai_stage: launch.aiStage,
+ ai_agent_name: launch.aiAgentName,
task_execution_environment: "cloud",
},
},
@@ -754,10 +746,7 @@ export class PiAgentServer {
apiUrl: this.config.apiUrl,
projectId: this.config.projectId,
apiKey: this.config.apiKey,
- interactionOrigin:
- process.env.POSTHOG_CODE_INTERACTION_ORIGIN ??
- process.env.CODE_INTERACTION_ORIGIN ??
- process.env.TWIG_INTERACTION_ORIGIN,
+ interactionOrigin: launch.interactionOrigin,
},
runtimeMcpServers,
mcpToolPolicies: mcpConfiguration.policies,
diff --git a/packages/agent/packages/agent/src/server/product/session.ts b/packages/agent/packages/agent/src/server/product/session.ts
index 69f5ae98e8bb..62df9a1da2bd 100644
--- a/packages/agent/packages/agent/src/server/product/session.ts
+++ b/packages/agent/packages/agent/src/server/product/session.ts
@@ -22,14 +22,6 @@ const questionSchema = z.object({
.optional(),
});
-export function readOriginProduct(): string | undefined {
- return (
- process.env.POSTHOG_CODE_INTERACTION_ORIGIN ??
- process.env.CODE_INTERACTION_ORIGIN ??
- process.env.TWIG_INTERACTION_ORIGIN
- );
-}
-
export async function openProductSession(
selectProduct: ProductSelector | undefined,
launch: ProductLaunchConfiguration,
diff --git a/packages/agent/packages/agent/src/server/question-relay.test.ts b/packages/agent/packages/agent/src/server/question-relay.test.ts
index 419befade0f0..aa6bc071258f 100644
--- a/packages/agent/packages/agent/src/server/question-relay.test.ts
+++ b/packages/agent/packages/agent/src/server/question-relay.test.ts
@@ -14,6 +14,7 @@ import { selectProduct } from "../boot/select-product";
import type { PostHogAPIClient } from "../posthog-api";
import type { ProductLaunchConfiguration } from "../sdk/product";
import {
+ createTask as createBaseTask,
createTaskRun,
createTestRepo,
type TestRepo,
@@ -81,17 +82,14 @@ const TEST_PAYLOAD = {
};
function createTask(overrides: Partial<Task> = {}): Task {
- return {
+ return createBaseTask({
id: "test-task-id",
- task_number: null,
slug: "test-task",
title: "t",
description: "original task description",
- created_at: "2026-01-01T00:00:00.000Z",
- updated_at: "2026-01-01T00:00:00.000Z",
origin_product: "tasks",
...overrides,
- };
+ });
}
const QUESTION_META = {
diff --git a/packages/agent/packages/agent/src/test/fixtures/api.ts b/packages/agent/packages/agent/src/test/fixtures/api.ts
index 63cfb80486cc..e4465dc78fcf 100644
--- a/packages/agent/packages/agent/src/test/fixtures/api.ts
+++ b/packages/agent/packages/agent/src/test/fixtures/api.ts
@@ -6,7 +6,7 @@ import { join } from "node:path";
import { promisify } from "node:util";
import { vi } from "vitest";
import type { PostHogAPIClient } from "../../posthog-api";
-import type { TaskRun } from "../../types";
+import type { Task, TaskRun } from "../../types";
const execFileAsync = promisify(execFile);
@@ -78,6 +78,20 @@ export function createMockApiClient(
} as unknown as PostHogAPIClient;
}
+export function createTask(overrides: Partial<Task> = {}): Task {
+ return {
+ id: "task-1",
+ task_number: null,
+ slug: "task-1",
+ title: "Task title",
+ description: "Task description",
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ origin_product: "user_created",
+ ...overrides,
+ };
+}
+
export function createTaskRun(overrides: Partial<TaskRun> = {}): TaskRun {
return {
id: "run-1",