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.

feat(desktop): add task instructions to pi sessions (#89127)

Jonathan Mielooda2ddb768503
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
index 4a6dc4ef12cc..2b7c42f62254 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
@@ -88,8 +88,13 @@ describe("DesktopPiRpcClientFactory", () => {
await expect(
factory.create({
- taskId: "task-1",
- cwd: "/workspace",
+ taskContext: {
+ taskId: "task-1",
+ cwd: "/workspace",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ },
projectTrusted: true,
}),
).resolves.toBe(client);
@@ -103,7 +108,6 @@ describe("DesktopPiRpcClientFactory", () => {
);
expect(authProxy.start).toHaveBeenCalledWith("https://eu.posthog.com");
expect(createPiRpcClient).toHaveBeenCalledWith({
- cwd: "/workspace",
enrichment: {
apiUrl: "http://127.0.0.1:5678",
publicApiUrl: "https://eu.posthog.com",
@@ -122,6 +126,16 @@ describe("DesktopPiRpcClientFactory", () => {
},
},
projectTrusted: true,
+ taskContext: {
+ projectId: 1,
+ apiHost: "https://eu.posthog.com",
+ taskId: "task-1",
+ cwd: "/workspace",
+ environment: "local",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ },
providerOptions: {
region: "eu",
baseUrl: "http://127.0.0.1:1234",
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
index 1649597c881e..9199774dd7fd 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
@@ -5,6 +5,7 @@ import {
createRuntimeMcpServers,
type PiRpcClient,
} from "@posthog/agent/pi/rpc-client";
+import type { TaskContext } from "@posthog/agent/pi/task-system-prompt";
import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import { type CloudRegion, getCloudUrlFromRegion } from "@posthog/shared";
@@ -52,18 +53,28 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {
// Four independent round-trips: proxy URL, auth proxy, MCP config, wiki mount.
const [baseUrl, enrichmentApiUrl, mcpConfiguration, contextWikiPath] =
await Promise.all([
- this.getProxyUrl(credentials.region, projectId, input.taskId),
+ this.getProxyUrl(
+ credentials.region,
+ projectId,
+ input.taskContext.taskId,
+ ),
this.authProxy.start(access.apiHost),
this.mcpServerSource.getMcpRuntimeConfiguration(),
this.mountContextWiki(projectId),
]);
const runtimeMcpServers = createRuntimeMcpServers(mcpConfiguration.servers);
+ const taskContext: TaskContext = {
+ projectId,
+ apiHost: access.apiHost,
+ environment: "local",
+ ...input.taskContext,
+ };
return createPiRpcClient({
- cwd: input.cwd,
model: input.model,
sessionFile: input.sessionFile,
projectTrusted: input.projectTrusted,
+ taskContext,
enrichment: {
apiUrl: enrichmentApiUrl,
publicApiUrl: access.apiHost,
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts
index 1053c890b78b..51a4c220871c 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts
@@ -12,16 +12,14 @@ describe("DesktopPiRuntimeFactory", () => {
const factory = new DesktopPiRuntimeFactory(clientFactory);
const runtime = await factory.create({
- taskId: "task-1",
- cwd: "/workspace",
+ taskContext: { taskId: "task-1", cwd: "/workspace" },
projectTrusted: true,
});
expect(runtime).toBeInstanceOf(PiRuntime);
expect(runtime.client).toBe(client);
expect(clientFactory.create).toHaveBeenCalledWith({
- taskId: "task-1",
- cwd: "/workspace",
+ taskContext: { taskId: "task-1", cwd: "/workspace" },
projectTrusted: true,
});
});
diff --git a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
index 41d256ece05e..93ea0bd3020c 100644
--- a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
+++ b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
@@ -222,7 +222,13 @@ test.describe("Pi enrichment", () => {
);
client = createPiRpcClient({
cliPath: rpcHostPath,
- cwd: workspace,
+ taskContext: {
+ taskId: "pi-enrichment-e2e",
+ cwd: workspace,
+ projectId: 1,
+ apiHost: "https://us.posthog.com",
+ environment: "local",
+ },
model: "claude-haiku-4-5",
projectTrusted: false,
providerOptions: { apiKey: "gateway-test-key", baseUrl },
diff --git a/products/desktop/apps/code/tests/e2e/tests/pi-extension.spec.ts b/products/desktop/apps/code/tests/e2e/tests/pi-extension.spec.ts
index 183c50607159..f1ac200b89f4 100644
--- a/products/desktop/apps/code/tests/e2e/tests/pi-extension.spec.ts
+++ b/products/desktop/apps/code/tests/e2e/tests/pi-extension.spec.ts
@@ -81,7 +81,13 @@ test.describe("Pi extensions", () => {
);
client = createPiRpcClient({
cliPath: rpcHostPath,
- cwd: e2eHome,
+ taskContext: {
+ taskId: "pi-extension-e2e",
+ cwd: e2eHome,
+ projectId: 1,
+ apiHost: "https://us.posthog.com",
+ environment: "local",
+ },
projectTrusted: false,
providerOptions: { apiKey: "unused-e2e-key" },
});
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.json
index 8d7f52b1ff15..70c4124e6177 100644
--- a/products/desktop/packages/agent/package.json
+++ b/products/desktop/packages/agent/package.json
@@ -36,6 +36,10 @@
"types": "./dist/pi/rpc-client.d.ts",
"import": "./dist/pi/rpc-client.js"
},
+ "./pi/task-system-prompt": {
+ "types": "./dist/pi/task-system-prompt.d.ts",
+ "import": "./dist/pi/task-system-prompt.js"
+ },
"./pi/rpc-transport": {
"types": "./dist/pi/rpc-transport.d.ts",
"import": "./dist/pi/rpc-transport.js"
diff --git a/products/desktop/packages/agent/src/pi/rpc-client.test.ts b/products/desktop/packages/agent/src/pi/rpc-client.test.ts
index 5cb32cbf44db..2bac53419139 100644
--- a/products/desktop/packages/agent/src/pi/rpc-client.test.ts
+++ b/products/desktop/packages/agent/src/pi/rpc-client.test.ts
@@ -8,6 +8,17 @@ import {
createRuntimeMcpServers,
createRuntimeMcpStdioServers,
} from "./rpc-client";
+import type { TaskContext } from "./task-system-prompt";
+
+function taskContext(cwd: string): TaskContext {
+ return {
+ taskId: "task-1",
+ cwd,
+ projectId: 2,
+ apiHost: "https://us.posthog.com",
+ environment: "local",
+ };
+}
describe("createRuntimeMcpServers", () => {
it("maps agent-server HTTP and SSE servers to Harness configuration", () => {
@@ -66,7 +77,7 @@ describe("createRuntimeMcpServers", () => {
describe("createPiRpcClient", () => {
it("does not put provider credentials in the child environment", () => {
const client = createPiRpcClient({
- cwd: "/workspace",
+ taskContext: taskContext("/workspace"),
model: "claude-opus-4-8",
providerOptions: {
region: "us",
@@ -104,7 +115,7 @@ process.stdin.resume();
);
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
projectTrusted: true,
extensions: ["auto-publish"],
providerOptions: { apiKey: "proxy-key" },
@@ -129,6 +140,7 @@ process.stdin.resume();
apiKey: "enrichment-proxy-key",
},
projectTrusted: true,
+ taskContext: taskContext(directory),
extensions: ["auto-publish"],
}),
);
@@ -160,7 +172,7 @@ process.stdin.resume();
);
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
providerOptions: { apiKey: "proxy-key" },
extensions: ["repository-tools"],
});
@@ -206,7 +218,7 @@ createInterface({ input: process.stdin }).on("line", (line) => {
);
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
providerOptions: { apiKey: "proxy-key" },
});
const request = new Promise<unknown>((resolve) => client.onEvent(resolve));
@@ -254,7 +266,7 @@ process.stdin.resume();
);
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
providerOptions: { apiKey: "proxy-key" },
runtimeMcpServers: {
posthog: {
@@ -311,7 +323,7 @@ process.on("message", (response) => {
const requestMcpToolPermission = vi.fn();
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
providerOptions: { apiKey: "proxy-key" },
});
client.onMcpToolPermissionRequest((request) => {
@@ -355,7 +367,7 @@ process.on("message", (request) => {
);
const client = createPiRpcClient({
cliPath: hostPath,
- cwd: directory,
+ taskContext: taskContext(directory),
providerOptions: { apiKey: "proxy-key" },
});
diff --git a/products/desktop/packages/agent/src/pi/rpc-client.ts b/products/desktop/packages/agent/src/pi/rpc-client.ts
index 735ac8c45837..8e28fc8cbabf 100644
--- a/products/desktop/packages/agent/src/pi/rpc-client.ts
+++ b/products/desktop/packages/agent/src/pi/rpc-client.ts
@@ -18,6 +18,7 @@ import type {
} from "@posthog/shared";
import type { PiEnrichmentConfig } from "./enrichment-extension";
import { safePiEnvironment } from "./rpc-environment";
+import type { TaskContext } from "./task-system-prompt";
import type {
PiExtensionEvent,
PiQueueSnapshot,
@@ -59,6 +60,7 @@ export interface PiRpcBootstrap {
runtimeMcpServers?: PiRuntimeMcpServers;
mcpToolPolicies?: McpToolPolicy[];
projectTrusted?: boolean;
+ taskContext: TaskContext;
extensions?: PiRuntimeExtension[];
/** Local checkout of the org's context wiki, when one is mounted. */
contextWikiPath?: string;
@@ -433,16 +435,14 @@ export function getPiRpcClientProcess(
return (client as unknown as RpcClientProcessAccess).process ?? null;
}
-export type PiRpcClientOptions = Pick<
- RpcClientOptions,
- "cliPath" | "cwd" | "model"
-> & {
+export type PiRpcClientOptions = Pick<RpcClientOptions, "cliPath" | "model"> & {
sessionFile?: string;
providerOptions: PiRpcProviderOptions;
enrichment?: PiEnrichmentConfig;
runtimeMcpServers?: PiRuntimeMcpServers;
mcpToolPolicies?: McpToolPolicy[];
projectTrusted?: boolean;
+ taskContext: TaskContext;
extensions?: PiRuntimeExtension[];
contextWikiPath?: string;
};
@@ -455,6 +455,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {
runtimeMcpServers,
mcpToolPolicies,
projectTrusted,
+ taskContext,
extensions,
contextWikiPath,
...rpcOptions
@@ -466,6 +467,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {
return new SecurePiRpcClient(
{
...rpcOptions,
+ cwd: taskContext.cwd,
args,
cliPath,
provider: "posthog",
@@ -476,6 +478,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {
runtimeMcpServers,
mcpToolPolicies,
projectTrusted: projectTrusted ?? false,
+ taskContext,
extensions,
contextWikiPath,
} satisfies PiRpcBootstrap,
diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.ts
index 4fe272f1c21a..9f0c68c53733 100644
--- a/products/desktop/packages/agent/src/pi/rpc-host.ts
+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts
@@ -19,6 +19,10 @@ import {
import { createPiRepositoryToolsExtension } from "./repository-tools-extension";
import type { PiRpcBootstrap, PiRuntimeExtension } from "./rpc-client";
import { sanitizePiHostEnvironment } from "./rpc-environment";
+import {
+ createPiTaskSystemPromptExtension,
+ resolvePiTaskContext,
+} from "./task-system-prompt-extension";
interface PiHostRequest {
type: "posthog_pi_host_request";
@@ -81,6 +85,8 @@ const extensionFactories: Record<PiRuntimeExtension, InlineExtension> = {
const runtimeExtensions = (bootstrap.extensions ?? []).map(
(extension) => extensionFactories[extension],
);
+const taskContext = resolvePiTaskContext(sessionManager, bootstrap.taskContext);
+runtimeExtensions.push(createPiTaskSystemPromptExtension(taskContext));
if (bootstrap.enrichment) {
runtimeExtensions.push(createPiEnrichmentExtension(bootstrap.enrichment));
}
diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.ts b/products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.ts
new file mode 100644
index 000000000000..fecaa416980c
--- /dev/null
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.ts
@@ -0,0 +1,91 @@
+import type {
+ ExtensionAPI,
+ SessionEntry,
+ SessionManager,
+} from "@earendil-works/pi-coding-agent";
+import { describe, expect, it, vi } from "vitest";
+import { buildTaskSystemPrompt, type TaskContext } from "./task-system-prompt";
+import {
+ createPiTaskSystemPromptExtension,
+ POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE,
+ resolvePiTaskContext,
+} from "./task-system-prompt-extension";
+
+const taskContext: TaskContext = {
+ projectId: 42,
+ apiHost: "https://us.posthog.com",
+ taskId: "task-123",
+ cwd: "/tmp/task-123",
+ environment: "local",
+};
+
+describe("Pi task system prompt", () => {
+ it("persists a new context and restores it on resume", () => {
+ const appendCustomEntry = vi.fn();
+ const manager = {
+ getEntries: () => [],
+ appendCustomEntry,
+ } as unknown as SessionManager;
+
+ expect(resolvePiTaskContext(manager, undefined)).toBeNull();
+ expect(resolvePiTaskContext(manager, taskContext)).toEqual(taskContext);
+ expect(appendCustomEntry).toHaveBeenCalledWith(
+ POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE,
+ { context: taskContext },
+ );
+
+ const persistedManager = {
+ getEntries: () =>
+ [
+ {
+ type: "custom",
+ customType: POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE,
+ data: { context: taskContext },
+ },
+ ] as SessionEntry[],
+ } as unknown as SessionManager;
+ expect(resolvePiTaskContext(persistedManager, undefined)).toEqual(
+ taskContext,
+ );
+ });
+
+ it("preserves optional persisted context when resume supplies runtime fields", () => {
+ const persistedContext: TaskContext = {
+ ...taskContext,
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ };
+ const appendCustomEntry = vi.fn();
+ const manager = {
+ getEntries: () =>
+ [
+ {
+ type: "custom",
+ customType: POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE,
+ data: { context: persistedContext },
+ },
+ ] as SessionEntry[],
+ appendCustomEntry,
+ } as unknown as SessionManager;
+
+ expect(resolvePiTaskContext(manager, taskContext)).toEqual(
+ persistedContext,
+ );
+ expect(appendCustomEntry).not.toHaveBeenCalled();
+ });
+
+ it("renders and appends the task prompt before each agent run", () => {
+ const handlers = new Map<string, unknown>();
+ createPiTaskSystemPromptExtension(taskContext).factory({
+ on: (event: string, handler: unknown) => handlers.set(event, handler),
+ } as unknown as ExtensionAPI);
+ const beforeAgentStart = handlers.get("before_agent_start") as (event: {
+ systemPrompt: string;
+ }) => { systemPrompt: string };
+
+ expect(beforeAgentStart({ systemPrompt: "Pi instructions" })).toEqual({
+ systemPrompt: `Pi instructions\n\n${buildTaskSystemPrompt(taskContext)}`,
+ });
+ });
+});
diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts b/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts
new file mode 100644
index 000000000000..03dd5d108fe9
--- /dev/null
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts
@@ -0,0 +1,107 @@
+import type {
+ ExtensionFactory,
+ InlineExtension,
+ SessionEntry,
+ SessionManager,
+} from "@earendil-works/pi-coding-agent";
+import { buildTaskSystemPrompt, type TaskContext } from "./task-system-prompt";
+
+export const POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE = "posthog.pi.task-context";
+
+type NamedInlineExtension = Exclude<InlineExtension, ExtensionFactory>;
+
+function isTaskContext(value: unknown): value is TaskContext {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+
+ const context = value as Partial<TaskContext>;
+ const hasValidDirectories =
+ context.additionalDirectories === undefined ||
+ (Array.isArray(context.additionalDirectories) &&
+ context.additionalDirectories.every(
+ (directory) => typeof directory === "string",
+ ));
+
+ return (
+ typeof context.projectId === "number" &&
+ typeof context.apiHost === "string" &&
+ typeof context.taskId === "string" &&
+ typeof context.cwd === "string" &&
+ (context.environment === "local" || context.environment === "cloud") &&
+ (context.customInstructions === undefined ||
+ typeof context.customInstructions === "string") &&
+ hasValidDirectories &&
+ (context.channelMode === undefined ||
+ typeof context.channelMode === "boolean") &&
+ (context.additionalInstructions === undefined ||
+ typeof context.additionalInstructions === "string")
+ );
+}
+
+export function readPersistedPiTaskContext(
+ entries: SessionEntry[],
+): TaskContext | null {
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
+ const entry = entries[index];
+ if (
+ entry?.type !== "custom" ||
+ entry.customType !== POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE
+ ) {
+ continue;
+ }
+ const data = entry.data as { context?: unknown } | undefined;
+ if (isTaskContext(data?.context)) {
+ return data.context;
+ }
+ }
+
+ return null;
+}
+
+export function resolvePiTaskContext(
+ sessionManager: SessionManager,
+ context: TaskContext | undefined,
+): TaskContext | null {
+ const persistedContext = readPersistedPiTaskContext(
+ sessionManager.getEntries(),
+ );
+ if (!context) {
+ return persistedContext;
+ }
+
+ const resolvedContext = {
+ ...persistedContext,
+ ...context,
+ customInstructions:
+ context.customInstructions ?? persistedContext?.customInstructions,
+ additionalDirectories:
+ context.additionalDirectories ?? persistedContext?.additionalDirectories,
+ channelMode: context.channelMode ?? persistedContext?.channelMode,
+ additionalInstructions:
+ context.additionalInstructions ??
+ persistedContext?.additionalInstructions,
+ };
+ if (JSON.stringify(resolvedContext) !== JSON.stringify(persistedContext)) {
+ sessionManager.appendCustomEntry(POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE, {
+ context: resolvedContext,
+ });
+ }
+ return resolvedContext;
+}
+
+export function createPiTaskSystemPromptExtension(
+ context: TaskContext | null,
+): NamedInlineExtension {
+ return {
+ name: "posthog-task-system-prompt",
+ factory: (pi) => {
+ if (!context) {
+ return;
+ }
+ pi.on("before_agent_start", (event) => ({
+ systemPrompt: `${event.systemPrompt}\n\n${buildTaskSystemPrompt(context)}`,
+ }));
+ },
+ };
+}
diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts b/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts
new file mode 100644
index 000000000000..e0a8826de775
--- /dev/null
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+import { buildTaskSystemPrompt } from "./task-system-prompt";
+
+describe("buildTaskSystemPrompt", () => {
+ it("builds durable local task instructions", () => {
+ const prompt = buildTaskSystemPrompt({
+ projectId: 42,
+ apiHost: "https://us.posthog.com",
+ taskId: "task-123",
+ cwd: "/tmp/task-123",
+ environment: "local",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/a&b", "/tmp/<shared>"],
+ channelMode: true,
+ });
+
+ expect(prompt).toContain("use project 42 on https://us.posthog.com");
+ expect(prompt).toContain("This is task task-123");
+ expect(prompt).toContain("Generated-By: PostHog Desktop");
+ expect(prompt).toContain("Task-Id: task-123");
+ expect(prompt).toContain("Keep the patch small.");
+ expect(prompt).toContain("<directory>/tmp/a&amp;b</directory>");
+ expect(prompt).toContain("<directory>/tmp/&lt;shared&gt;</directory>");
+ expect(prompt).toContain("## Channel task");
+ });
+
+ it("does not give local source-control instructions to cloud tasks", () => {
+ const prompt = buildTaskSystemPrompt({
+ projectId: 42,
+ apiHost: "https://us.posthog.com",
+ taskId: "task-123",
+ cwd: "/tmp/workspace",
+ environment: "cloud",
+ additionalInstructions: "Use the existing pull request.",
+ });
+
+ expect(prompt).not.toContain("Generated-By: PostHog Desktop");
+ expect(prompt).toContain("Use the existing pull request.");
+ });
+});
diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt.ts b/products/desktop/packages/agent/src/pi/task-system-prompt.ts
new file mode 100644
index 000000000000..1fb6992844ef
--- /dev/null
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt.ts
@@ -0,0 +1,166 @@
+export interface TaskContextInput {
+ taskId: string;
+ cwd: string;
+ customInstructions?: string;
+ additionalDirectories?: string[];
+ channelMode?: boolean;
+}
+
+export interface TaskContext extends TaskContextInput {
+ projectId: number;
+ apiHost: string;
+ environment: "local" | "cloud";
+ additionalInstructions?: string;
+}
+
+export interface TaskPromptCapabilities {
+ structuredInput?: boolean;
+ repositoryTools?: boolean;
+}
+
+function escapeXml(value: string): string {
+ return value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+}
+
+export function buildPostHogContextPrompt(
+ context: Pick<TaskContext, "projectId" | "apiHost">,
+): string {
+ return `PostHog context: use project ${context.projectId} on ${context.apiHost}. When using PostHog MCP tools, operate only on this project.`;
+}
+
+export function buildTaskContextPrompt(taskId: string): string {
+ return `## Task context
+This is task ${taskId}. Keep material provided as task context, including customer conversations, support tickets, logs, and internal threads, out of code, tests, comments, commit messages, and pull request text. Rewriting or anonymizing that material does not make it safe to publish.`;
+}
+
+export function buildLocalAttributionPrompt(taskId: string): string {
+ return `## Attribution
+Do NOT use Claude Code's default attribution (no "Co-Authored-By" trailers, no "Generated with [Claude Code]" lines).
+
+Instead, add the following trailers to EVERY commit message (after a blank line at the end):
+ Generated-By: PostHog Desktop
+ Task-Id: ${taskId}
+
+Example:
+\`\`\`
+git commit -m "$(cat <<'EOF'
+fix: resolve login redirect loop
+
+Generated-By: PostHog Desktop
+Task-Id: ${taskId}
+EOF
+)"
+\`\`\`
+
+When creating new branches, prefix them with \`posthog/\` (e.g. \`posthog/fix-login-redirect\`).
+
+When creating pull requests, add the following footer at the end of the PR description:
+\`\`\`
+---
+*Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)*
+\`\`\``;
+}
+
+export function buildQuestionsPrompt(
+ structuredInputAvailable: boolean,
+): string {
+ if (structuredInputAvailable) {
+ return `## Questions
+When you need an answer from the user before you can continue, use the structured user-input tool available in your current mode. Never end a turn with a blocking question in a normal assistant message because plain-text questions mark the task as finished instead of waiting for the user's response.`;
+ }
+
+ return `## Questions
+When you need an answer before you can continue, ask one concise blocking question and stop.`;
+}
+
+export function buildPullRequestLinksPrompt(): string {
+ return `## Pull request links
+When you mention a pull request in any reply or summary, always hyperlink it to its full URL (e.g. a Markdown link like [#123](https://github.com/org/repo/pull/123)) rather than plain text, so readers can open it directly.`;
+}
+
+export function buildShellEfficiencyPrompt(): string {
+ return `## Shell efficiency
+Optimize for the fewest shell round trips.
+- Batch related commands into one Bash invocation using \`&&\` (e.g. \`npm run typecheck && npm run lint && npm test\`).
+- Emit all independent tool calls in the same response.
+- Read multiple files at once.
+- Never rerun a command solely to reproduce output you already have.`;
+}
+
+export function buildChannelPrompt(repositoryToolsAvailable: boolean): string {
+ if (!repositoryToolsAvailable) {
+ return `## Channel task
+This task may not need a repository. Treat the working directory as task-specific scratch space and do not use another checkout.`;
+ }
+
+ return `## Channel task (no repository attached)
+You are running in a PostHog channel as a general-purpose assistant. This task may not need a code repository. It could be data analysis via PostHog tools, drafting a message, or answering a question. Do not assume you need a repo.
+
+- Your working directory is a scratch directory, not a git checkout. Treat it as empty.
+- Decide from the user's request and the channel CONTEXT.md, if present, whether the task requires a code repository. If it doesn't, do the work in the scratch directory.
+- Do not \`cd\` into or edit an existing checkout elsewhere on the machine. Another task may be using it.
+
+If a repository is required, call \`list_repos\` to find it, then use \`clone_repo\` with its \`owner/repo\`. The tool creates a task-specific clone inside the scratch directory and returns the path to use. If you cannot confidently identify the repository, ask the user which repository to clone.`;
+}
+
+export function buildCustomInstructionsPrompt(
+ customInstructions: string,
+): string {
+ return `User custom instructions:\n${customInstructions}`;
+}
+
+export function buildAdditionalDirectoriesPrompt(
+ additionalDirectories: string[],
+): string {
+ const directories = additionalDirectories
+ .map((directory) => ` <directory>${escapeXml(directory)}</directory>`)
+ .join("\n");
+
+ return `The user has granted you access to additional directories outside the working directory. You may read and edit files in these paths just like the working directory:
+<additional_directories>
+${directories}
+</additional_directories>`;
+}
+
+export function buildTaskSystemPrompt(
+ context: TaskContext,
+ capabilities: TaskPromptCapabilities = {},
+): string {
+ const sections = [
+ buildPostHogContextPrompt(context),
+ buildTaskContextPrompt(context.taskId),
+ ];
+
+ if (context.environment === "local") {
+ sections.push(buildLocalAttributionPrompt(context.taskId));
+ }
+
+ sections.push(
+ buildQuestionsPrompt(capabilities.structuredInput === true),
+ buildPullRequestLinksPrompt(),
+ buildShellEfficiencyPrompt(),
+ );
+
+ if (context.channelMode) {
+ sections.push(buildChannelPrompt(capabilities.repositoryTools === true));
+ }
+
+ if (context.customInstructions) {
+ sections.push(buildCustomInstructionsPrompt(context.customInstructions));
+ }
+
+ if (context.additionalDirectories?.length) {
+ sections.push(
+ buildAdditionalDirectoriesPrompt(context.additionalDirectories),
+ );
+ }
+
+ if (context.additionalInstructions) {
+ sections.push(context.additionalInstructions);
+ }
+
+ return sections.join("\n\n");
+}
diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.ts
index 752b8e1b8698..3e88b1288c19 100644
--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts
+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts
@@ -30,6 +30,7 @@ import {
} from "../pi/rpc-client";
import { piRpcCommandSchema, type RpcCommand } from "../pi/rpc-transport";
import { PiRuntime } from "../pi/runtime";
+import type { TaskContext } from "../pi/task-system-prompt";
import { PostHogAPIClient } from "../posthog-api";
import { resolveLlmGatewayUrl } from "../utils/gateway";
import { Logger } from "../utils/logger";
@@ -550,6 +551,18 @@ export class PiAgentServer {
? runState.snapshot_kind
: "absent"
: null;
+ const configuredSystemPrompt =
+ typeof this.config.claudeCode?.systemPrompt === "string"
+ ? this.config.claudeCode.systemPrompt
+ : this.config.claudeCode?.systemPrompt?.append;
+ const taskContext: TaskContext = {
+ projectId: this.config.projectId,
+ apiHost: this.config.apiUrl,
+ taskId: this.config.taskId,
+ cwd,
+ environment: "cloud",
+ additionalInstructions: configuredSystemPrompt,
+ };
const attributionHeaders = buildPosthogPropertyHeaderRecord({
task_id: payload.task_id,
task_run_id: payload.run_id,
@@ -580,7 +593,6 @@ export class PiAgentServer {
}
const client = createPiRpcClient({
cliPath: this.config.piRpcHostPath,
- cwd,
model: this.config.model,
sessionFile: restoredSessionFile,
enrichment: {
@@ -590,6 +602,7 @@ export class PiAgentServer {
},
runtimeMcpServers,
mcpToolPolicies: mcpConfiguration.policies,
+ taskContext,
providerOptions: {
apiKey: this.config.apiKey,
baseUrl: resolveLlmGatewayUrl(
diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.ts
index 60bb6d55d708..b8858e24368a 100644
--- a/products/desktop/packages/agent/tsup.config.ts
+++ b/products/desktop/packages/agent/tsup.config.ts
@@ -158,6 +158,7 @@ export default defineConfig([
"src/pr-url-detector.ts",
"src/pi/rpc-client.ts",
"src/pi/runtime.ts",
+ "src/pi/task-system-prompt.ts",
"src/pi/types.ts",
"src/pi/conversation/translatePiConversation.ts",
"src/resume.ts",
diff --git a/products/desktop/packages/core/src/pi-runtime/piRunner.ts b/products/desktop/packages/core/src/pi-runtime/piRunner.ts
index ffb909e84f05..af1e8ed60c98 100644
--- a/products/desktop/packages/core/src/pi-runtime/piRunner.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piRunner.ts
@@ -1,8 +1,8 @@
+import type { TaskContextInput } from "@posthog/agent/pi/task-system-prompt";
import type { PiThinkingLevel } from "@posthog/agent/pi/types";
export interface PiRunInput {
- taskId: string;
- cwd: string;
+ taskContext: TaskContextInput;
projectTrustPath?: string;
prompt: string;
model?: string;
@@ -10,8 +10,7 @@ export interface PiRunInput {
}
export interface PiResumeInput {
- taskId: string;
- cwd: string;
+ taskContext: Pick<TaskContextInput, "taskId" | "cwd">;
projectTrustPath?: string;
}
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
index ec837f8a89ca..f3e6f52ae4f8 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -391,6 +391,8 @@ describe("TaskCreationSaga", () => {
runtime: "pi",
model: "claude-sonnet",
reasoningLevel: "medium",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
allowNoRepo: true,
});
@@ -399,8 +401,13 @@ describe("TaskCreationSaga", () => {
expect.objectContaining({ runtime: "pi" }),
);
expect(piRunner.create).toHaveBeenCalledWith({
- taskId: "task-123",
- cwd: "/tmp/scratch/task-123",
+ taskContext: {
+ taskId: "task-123",
+ cwd: "/tmp/scratch/task-123",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ },
projectTrustPath: "/tmp/scratch/task-123",
prompt: "Draft a launch email",
model: "claude-sonnet",
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index 37205df2a5c8..e8240efab6d2 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -552,8 +552,13 @@ export class TaskCreationSaga extends Saga<
.join("\n\n");
await this.deps.piRunner.create({
- taskId: task.id,
- cwd: agentCwd ?? "",
+ taskContext: {
+ taskId: task.id,
+ cwd: agentCwd ?? "",
+ customInstructions: input.customInstructions,
+ additionalDirectories: input.additionalDirectories,
+ channelMode: !!scratchCwd && agentCwd === scratchCwd,
+ },
projectTrustPath:
workspace?.folderPath ?? repoPath ?? scratchCwd ?? undefined,
prompt,
diff --git a/products/desktop/packages/core/src/task-detail/taskService.test.ts b/products/desktop/packages/core/src/task-detail/taskService.test.ts
index fc0145f3232c..557315ee27b3 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.test.ts
@@ -97,8 +97,7 @@ describe("TaskService.openTask", () => {
success: true,
});
expect(piRunner.resume).toHaveBeenCalledWith({
- taskId: "task-1",
- cwd: "/worktrees/task-1",
+ taskContext: { taskId: "task-1", cwd: "/worktrees/task-1" },
projectTrustPath: "/repo",
});
});
diff --git a/products/desktop/packages/core/src/task-detail/taskService.ts b/products/desktop/packages/core/src/task-detail/taskService.ts
index ae38b49fc3f1..a4d03ea687cd 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.ts
@@ -259,8 +259,11 @@ export class TaskService {
try {
if (runtime === "pi") {
await this.piRunner.resume({
- taskId,
- cwd: existingWorkspace.worktreePath ?? existingWorkspace.folderPath,
+ taskContext: {
+ taskId,
+ cwd:
+ existingWorkspace.worktreePath ?? existingWorkspace.folderPath,
+ },
projectTrustPath: existingWorkspace.folderPath,
});
}
@@ -282,7 +285,10 @@ export class TaskService {
if (runtime === "pi") {
try {
const cwd = await this.host.ensureScratchDir(taskId);
- await this.piRunner.resume({ taskId, cwd, projectTrustPath: cwd });
+ await this.piRunner.resume({
+ taskContext: { taskId, cwd },
+ projectTrustPath: cwd,
+ });
return {
success: true,
data: { task, workspace: null },
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 509725465543..2f96483a630f 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -1245,6 +1245,7 @@ describe("AgentService", () => {
buildSystemPrompt: (
credentials: { apiHost: string; projectId: number },
taskId: string,
+ cwd: string,
customInstructions?: string,
additionalDirectories?: string[],
systemPromptOverride?: string,
@@ -1254,6 +1255,7 @@ describe("AgentService", () => {
).buildSystemPrompt(
credentials,
"task-1",
+ "/tmp/task-1",
undefined,
undefined,
systemPromptOverride,
@@ -1298,11 +1300,13 @@ describe("AgentService", () => {
buildSystemPrompt: (
credentials: { apiHost: string; projectId: number },
taskId: string,
+ cwd: string,
) => { append: string };
}
).buildSystemPrompt(
{ apiHost: "https://app.posthog.com", projectId: 1 },
"task-1",
+ "/tmp/task-1",
).append;
expect(prompt).toContain(
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index cb564ee0ddbc..d963fa105ad2 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -32,6 +32,7 @@ import {
getAvailableModes,
} from "@posthog/agent/execution-mode";
import { fetchGatewayModels } from "@posthog/agent/gateway-models";
+import { buildTaskSystemPrompt } from "@posthog/agent/pi/task-system-prompt";
import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";
import {
findPrUrls,
@@ -679,6 +680,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
private buildSystemPrompt(
credentials: Credentials,
taskId: string,
+ cwd: string,
customInstructions?: string,
additionalDirectories?: string[],
systemPromptOverride?: string,
@@ -695,75 +697,22 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
};
}
- let prompt = `PostHog context: use project ${credentials.projectId} on ${credentials.apiHost}. When using PostHog MCP tools, operate only on this project.`;
-
- prompt += `
-
-## Attribution
-Do NOT use Claude Code's default attribution (no "Co-Authored-By" trailers, no "Generated with [Claude Code]" lines).
-
-Instead, add the following trailers to EVERY commit message (after a blank line at the end):
- Generated-By: PostHog Desktop
- Task-Id: ${taskId}
-
-Example:
-\`\`\`
-git commit -m "$(cat <<'EOF'
-fix: resolve login redirect loop
-
-Generated-By: PostHog Desktop
-Task-Id: ${taskId}
-EOF
-)"
-\`\`\`
-
-When creating new branches, prefix them with \`posthog/\` (e.g. \`posthog/fix-login-redirect\`).
-
-When creating pull requests, add the following footer at the end of the PR description:
-\`\`\`
----
-*Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)*
-\`\`\`
-
-When you mention a pull request in any reply or summary, always hyperlink it to its full URL (e.g. a Markdown link like [#123](https://github.com/org/repo/pull/123)) rather than plain text, so readers can open it directly.
-
-## Questions
-When you need an answer from the user before you can continue, use the structured user-input tool available in your current mode. Never end a turn with a blocking question in a normal assistant message because plain-text questions mark the task as finished instead of waiting for the user's response.
-
-## Shell efficiency
-Optimize for the fewest shell round trips.
-- Batch related commands into one Bash invocation using \`&&\` (e.g. \`npm run typecheck && npm run lint && npm test\`).
-- Emit all independent tool calls in the same response.
-- Read multiple files at once.
-- Never rerun a command solely to reproduce output you already have.
-
-`;
-
- if (channelMode) {
- prompt += `
-
-## Channel task (no repository attached)
-You are running in a PostHog channel as a general-purpose assistant. This task may not need a code repository. It could be data analysis via PostHog tools, drafting a message, or answering a question. Do not assume you need a repo.
-
-- Your working directory is a scratch directory, not a git checkout. Treat it as empty.
-- Decide from the user's request and the channel CONTEXT.md, if present, whether the task requires a code repository. If it doesn't, do the work in the scratch directory.
-- Do not \`cd\` into or edit an existing checkout elsewhere on the machine. Another task may be using it.
-
-If a repository is required, call \`list_repos\` to find it, then use \`clone_repo\` with its \`owner/repo\`. The tool creates a task-specific clone inside the scratch directory and returns the path to use. If you cannot confidently identify the repository, ask the user which repository to clone.`;
- }
-
- if (customInstructions) {
- prompt += `\n\nUser custom instructions:\n${customInstructions}`;
- }
-
- if (additionalDirectories?.length) {
- const escapeXml = (s: string) =>
- s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
- const dirs = additionalDirectories
- .map((d) => ` <directory>${escapeXml(d)}</directory>`)
- .join("\n");
- prompt += `\n\nThe user has granted you access to additional directories outside the working directory. You may read and edit files in these paths just like the working directory:\n<additional_directories>\n${dirs}\n</additional_directories>`;
- }
+ const prompt = buildTaskSystemPrompt(
+ {
+ projectId: credentials.projectId,
+ apiHost: credentials.apiHost,
+ taskId,
+ cwd,
+ environment: "local",
+ customInstructions,
+ additionalDirectories,
+ channelMode,
+ },
+ {
+ structuredInput: true,
+ repositoryTools: true,
+ },
+ );
return {
append: appendRichOutputPrompt(prependProductEngineerPrompt(prompt)),
@@ -918,6 +867,7 @@ If a repository is required, call \`list_repos\` to find it, then use \`clone_re
const systemPrompt = this.buildSystemPrompt(
credentials,
taskId,
+ repoPath,
customInstructions,
additionalDirectories,
systemPromptOverride,
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts b/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts
index 624b1505186c..9985388420b1 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts
@@ -3,14 +3,15 @@ import type {
PiRpcClientOptions,
} from "@posthog/agent/pi/rpc-client";
import type { PiRuntime } from "@posthog/agent/pi/runtime";
+import type { TaskContextInput } from "@posthog/agent/pi/task-system-prompt";
export interface PiRpcClientFactory {
create(
input: Pick<
PiRpcClientOptions,
- "cwd" | "model" | "sessionFile" | "projectTrusted"
+ "model" | "sessionFile" | "projectTrusted"
> & {
- taskId: string;
+ taskContext: TaskContextInput;
},
): Promise<PiRpcClient>;
}
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
index 9d80f5cb823b..103dba1f3ab2 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
@@ -233,12 +233,28 @@ describe("PiSessionService start", () => {
);
await service.start({
- taskId: "task-1",
- cwd: "/tmp",
+ taskContext: {
+ taskId: "task-1",
+ cwd: "/tmp",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ },
prompt: "hello",
thinkingLevel: "high",
});
+ expect(runtimeFactory.create).toHaveBeenCalledWith({
+ taskContext: {
+ taskId: "task-1",
+ cwd: "/tmp",
+ customInstructions: "Keep the patch small.",
+ additionalDirectories: ["/tmp/shared"],
+ channelMode: true,
+ },
+ model: undefined,
+ projectTrusted: false,
+ });
expect(setThinkingLevel).toHaveBeenCalledWith("high");
expect(setThinkingLevel.mock.invocationCallOrder[0]).toBeLessThan(
prompt.mock.invocationCallOrder[0],
@@ -347,8 +363,7 @@ describe("PiSessionService project trust", () => {
);
await service.start({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
projectTrustPath: repository,
prompt: "hello",
});
@@ -357,8 +372,7 @@ describe("PiSessionService project trust", () => {
hasProjectResources: true,
});
expect(runtimeFactory.create).toHaveBeenLastCalledWith({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
model: undefined,
projectTrusted: false,
});
@@ -372,14 +386,12 @@ describe("PiSessionService project trust", () => {
expect(processTracking.unregister).not.toHaveBeenCalled();
await service.resume({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
projectTrustPath: repository,
});
expect(clients[0].stop).toHaveBeenCalledTimes(2);
expect(runtimeFactory.create).toHaveBeenLastCalledWith({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
sessionFile: "/tmp/session.jsonl",
projectTrusted: false,
});
@@ -392,13 +404,11 @@ describe("PiSessionService project trust", () => {
);
await service.resume({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
projectTrustPath: repository,
});
expect(runtimeFactory.create).toHaveBeenLastCalledWith({
- taskId: "task-1",
- cwd: worktree,
+ taskContext: { taskId: "task-1", cwd: worktree },
sessionFile: "/tmp/session.jsonl",
projectTrusted: true,
});
@@ -424,8 +434,7 @@ describe("PiSessionService project trust", () => {
await expect(
service.start({
- taskId: "task-1",
- cwd: unrelatedRepository,
+ taskContext: { taskId: "task-1", cwd: unrelatedRepository },
projectTrustPath: trustedRepository,
prompt: "hello",
}),
@@ -478,7 +487,10 @@ describe("PiSessionService extension UI", () => {
rootLogger,
);
const abortController = new AbortController();
- await service.start({ taskId: "task-1", cwd: "/tmp", prompt: "hello" });
+ await service.start({
+ taskContext: { taskId: "task-1", cwd: "/tmp" },
+ prompt: "hello",
+ });
extensionHandlers[0]({
type: "extension_ui_request",
id: "startup-notification",
@@ -559,8 +571,7 @@ describe("PiSessionService extension UI", () => {
const oldEvent = oldIterator.next();
extensionHandlers[0]({ ...request, id: "buffered-old-extension" });
await service.start({
- taskId: "task-1",
- cwd: "/tmp/replacement",
+ taskContext: { taskId: "task-1", cwd: "/tmp/replacement" },
prompt: "hello again",
});
await expect(oldEvent).resolves.toEqual({
@@ -678,14 +689,18 @@ describe("PiSessionService RPC request pinning", () => {
rootLogger,
);
- await service.resume({ taskId: "first", cwd: "/tmp" });
+ await service.resume({
+ taskContext: { taskId: "first", cwd: "/tmp" },
+ });
const bashRequest = service.request("first", {
type: "bash",
command: "sleep 1",
});
const queueRequest = service.getQueue("first");
- await service.resume({ taskId: "second", cwd: "/tmp" });
+ await service.resume({
+ taskContext: { taskId: "second", cwd: "/tmp" },
+ });
expect(firstClient.stop).not.toHaveBeenCalled();
requestResolvers[0](successfulResponse("bash"));
@@ -697,7 +712,9 @@ describe("PiSessionService RPC request pinning", () => {
await queueRequest;
expect(firstClient.stop).not.toHaveBeenCalled();
- await service.resume({ taskId: "third", cwd: "/tmp" });
+ await service.resume({
+ taskContext: { taskId: "third", cwd: "/tmp" },
+ });
expect(firstClient.stop).toHaveBeenCalledOnce();
expect(thirdClient.stop).not.toHaveBeenCalled();
});
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
index a75b6e45c422..3c7c7f7d0006 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
@@ -260,32 +260,34 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {
async start(
input: StartPiSessionInput,
): Promise<{ sessionFile: string | null; sessionId: string }> {
- return this.runExclusive(input.taskId, () => this.startLocked(input));
+ return this.runExclusive(input.taskContext.taskId, () =>
+ this.startLocked(input),
+ );
}
private async startLocked(
input: StartPiSessionInput,
): Promise<{ sessionFile: string | null; sessionId: string }> {
- await this.stopLocked(input.taskId);
+ const { taskId, cwd } = input.taskContext;
+ await this.stopLocked(taskId);
- const projectTrustPath = input.projectTrustPath ?? input.cwd;
- await assertProjectTrustAppliesToCwd(projectTrustPath, input.cwd);
- const projectTrust = readPiProjectTrust(projectTrustPath, input.cwd);
+ const projectTrustPath = input.projectTrustPath ?? cwd;
+ await assertProjectTrustAppliesToCwd(projectTrustPath, cwd);
+ const projectTrust = readPiProjectTrust(projectTrustPath, cwd);
const runtime = await this.runtimeFactory.create({
- taskId: input.taskId,
- cwd: input.cwd,
+ taskContext: input.taskContext,
model: input.model,
projectTrusted: projectTrust.trusted,
});
const client = runtime.client;
const session = this.registerSession(
- input.taskId,
+ taskId,
runtime,
- input.cwd,
+ cwd,
projectTrustPath,
);
- return this.startSession(input.taskId, client, session, async () => {
+ return this.startSession(taskId, client, session, async () => {
if (input.thinkingLevel) {
await client.setThinkingLevel(input.thinkingLevel);
}
@@ -297,7 +299,7 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {
);
}
- this.taskMetadataRepository.upsert(input.taskId, {
+ this.taskMetadataRepository.upsert(taskId, {
piSessionFile: state.sessionFile,
});
@@ -311,50 +313,50 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {
}
async resume(input: ResumePiSessionInput): Promise<void> {
- await this.runExclusive(input.taskId, () => this.resumeLocked(input));
+ await this.runExclusive(input.taskContext.taskId, () =>
+ this.resumeLocked(input),
+ );
}
private async resumeLocked(input: ResumePiSessionInput): Promise<void> {
- const existingSession = this.sessions.get(input.taskId);
- const projectTrustPath = input.projectTrustPath ?? input.cwd;
+ const { taskId, cwd } = input.taskContext;
+ const existingSession = this.sessions.get(taskId);
+ const projectTrustPath = input.projectTrustPath ?? cwd;
if (
existingSession &&
!existingSession.stopFailed &&
- existingSession.cwd === input.cwd &&
+ existingSession.cwd === cwd &&
existingSession.projectTrustPath === projectTrustPath
) {
this.touchSession(existingSession);
return;
}
- const metadata = this.taskMetadataRepository.findByTaskId(input.taskId);
+ const metadata = this.taskMetadataRepository.findByTaskId(taskId);
const sessionFile = metadata?.piSessionFile;
if (!sessionFile) {
- throw new Error(
- `Pi session metadata is missing for task ${input.taskId}`,
- );
+ throw new Error(`Pi session metadata is missing for task ${taskId}`);
}
- await this.stopLocked(input.taskId);
+ await this.stopLocked(taskId);
- await assertProjectTrustAppliesToCwd(projectTrustPath, input.cwd);
- const projectTrust = readPiProjectTrust(projectTrustPath, input.cwd);
+ await assertProjectTrustAppliesToCwd(projectTrustPath, cwd);
+ const projectTrust = readPiProjectTrust(projectTrustPath, cwd);
const runtime = await this.runtimeFactory.create({
- taskId: input.taskId,
- cwd: input.cwd,
+ taskContext: input.taskContext,
sessionFile,
projectTrusted: projectTrust.trusted,
});
const client = runtime.client;
const session = this.registerSession(
- input.taskId,
+ taskId,
runtime,
- input.cwd,
+ cwd,
projectTrustPath,
);
- await this.startSession(input.taskId, client, session, async () => {});
+ await this.startSession(taskId, client, session, async () => {});
}
request(taskId: string, command: RpcCommand): Promise<RpcResponse> {
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts b/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts
index 3b8109e07224..8a0e8167a5fd 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts
@@ -12,9 +12,16 @@ import { z } from "zod";
export { piRpcResponseSchema };
-export const startPiSessionInput = z.object({
+const piTaskContextInput = z.object({
taskId: z.string(),
cwd: z.string(),
+ customInstructions: z.string().optional(),
+ additionalDirectories: z.array(z.string()).optional(),
+ channelMode: z.boolean().optional(),
+});
+
+export const startPiSessionInput = z.object({
+ taskContext: piTaskContextInput,
projectTrustPath: z.string().optional(),
prompt: z.string(),
model: z.string().optional(),
@@ -35,8 +42,7 @@ export const piSessionHealthOutput = z.object({
});
export const resumePiSessionInput = z.object({
- taskId: z.string(),
- cwd: z.string(),
+ taskContext: piTaskContextInput.pick({ taskId: true, cwd: true }),
projectTrustPath: z.string().optional(),
});