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.

fix(desktop): give Pi channel tasks their workspace and repo tools (#92776)

posthog[bot]8d3e0d7c7ffc
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts
index 5432a49c8da5..4383a07298d2 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts
@@ -1,10 +1,9 @@
-import { execFile } from "node:child_process";
-import { promisify } from "node:util";
+import { execGh } from "@posthog/git/gh";
import { z } from "zod";
import { resolveGithubToken } from "../../../utils/github-token";
import { defineLocalTool, type LocalToolResult } from "../registry";
-const execFileAsync = promisify(execFile);
+const GH_TIMEOUT_MS = 30_000;
const listReposSchema = {
owner: z
@@ -64,15 +63,23 @@ export const listReposTool = defineLocalTool({
// vars so gh cannot fall back to the previous actor's frozen process-env
// token and enumerate their private repos. Only an undefined token (an
// unmanaged local/desktop sandbox) inherits the process env unchanged.
+ // execGh merges these overrides onto process.env, so the rest of the env
+ // still passes through.
const env =
token === undefined
- ? process.env
- : { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token };
- const { stdout } = await execFileAsync("gh", cmdArgs, {
+ ? undefined
+ : { GH_TOKEN: token, GITHUB_TOKEN: token };
+ // Bound the subprocess. Without a timeout a stalled gh network call keeps
+ // the tool call, and the agent turn awaiting it, pending with no recovery.
+ const res = await execGh(cmdArgs, {
env,
+ timeoutMs: GH_TIMEOUT_MS,
maxBuffer: 1024 * 1024 * 8,
});
- const parsed = ghRepoSchema.safeParse(JSON.parse(stdout));
+ if (res.exitCode !== 0) {
+ throw new Error(res.error || res.stderr.trim() || "gh failed");
+ }
+ const parsed = ghRepoSchema.safeParse(JSON.parse(res.stdout));
if (!parsed.success) {
return {
content: [
diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.ts
index 087d4053267f..1ca54964037b 100644
--- a/products/desktop/packages/agent/src/pi/rpc-host.ts
+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts
@@ -81,11 +81,22 @@ const extensionFactories: Record<PiRuntimeExtension, InlineExtension> = {
},
"context-wiki": createPiContextWikiExtension(bootstrap.contextWikiPath),
};
-const runtimeExtensions = (bootstrap.extensions ?? []).map(
+const taskContext = resolvePiTaskContext(sessionManager, bootstrap.taskContext);
+// A channel task starts in an empty scratch directory, so it needs the tools
+// that find and clone a repository. Resume drops `channelMode` from the
+// bootstrap payload, so read it from the resolved context, not the payload.
+const requestedExtensions = new Set(bootstrap.extensions ?? []);
+if (taskContext?.channelMode) {
+ requestedExtensions.add("repository-tools");
+}
+const runtimeExtensions = [...requestedExtensions].map(
(extension) => extensionFactories[extension],
);
-const taskContext = resolvePiTaskContext(sessionManager, bootstrap.taskContext);
-runtimeExtensions.push(createPiTaskSystemPromptExtension(taskContext));
+runtimeExtensions.push(
+ createPiTaskSystemPromptExtension(taskContext, {
+ repositoryTools: requestedExtensions.has("repository-tools"),
+ }),
+);
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
index fecaa416980c..6ba0d37f65ee 100644
--- 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
@@ -88,4 +88,21 @@ describe("Pi task system prompt", () => {
systemPrompt: `Pi instructions\n\n${buildTaskSystemPrompt(taskContext)}`,
});
});
+
+ it("renders the prompt with the capabilities the harness reports", () => {
+ const channelContext: TaskContext = { ...taskContext, channelMode: true };
+ const handlers = new Map<string, unknown>();
+ createPiTaskSystemPromptExtension(channelContext, {
+ repositoryTools: true,
+ }).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" }).systemPrompt,
+ ).toContain("call `list_repos` to find it");
+ });
});
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
index e43ff8309a0b..a8a75707e526 100644
--- a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts
@@ -4,7 +4,11 @@ import type {
SessionEntry,
SessionManager,
} from "@earendil-works/pi-coding-agent";
-import { buildTaskSystemPrompt, type TaskContext } from "./task-system-prompt";
+import {
+ buildTaskSystemPrompt,
+ type TaskContext,
+ type TaskPromptCapabilities,
+} from "./task-system-prompt";
export const POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE = "posthog.pi.task-context";
@@ -92,6 +96,7 @@ export function resolvePiTaskContext(
export function createPiTaskSystemPromptExtension(
context: TaskContext | null,
+ capabilities: TaskPromptCapabilities = {},
): NamedInlineExtension {
return {
name: "posthog-task-system-prompt",
@@ -100,7 +105,7 @@ export function createPiTaskSystemPromptExtension(
return;
}
pi.on("before_agent_start", (event) => ({
- systemPrompt: `${event.systemPrompt}\n\n${buildTaskSystemPrompt(context)}`,
+ systemPrompt: `${event.systemPrompt}\n\n${buildTaskSystemPrompt(context, capabilities)}`,
}));
},
};
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
index 29abc3fb5fac..c629ce87f3bd 100644
--- a/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts
@@ -22,6 +22,23 @@ describe("buildTaskSystemPrompt", () => {
expect(prompt).toContain("<directory>/tmp/a&amp;b</directory>");
expect(prompt).toContain("<directory>/tmp/&lt;shared&gt;</directory>");
expect(prompt).toContain("## Channel task");
+ expect(prompt).toContain("Your working directory is `/tmp/task-123`");
+ });
+
+ it("describes the repository tools only when the harness registers them", () => {
+ const context = {
+ projectId: 42,
+ apiHost: "https://us.posthog.com",
+ taskId: "task-123",
+ cwd: "/tmp/task-123",
+ environment: "local",
+ channelMode: true,
+ } as const;
+
+ expect(buildTaskSystemPrompt(context)).not.toContain("list_repos");
+ expect(buildTaskSystemPrompt(context, { repositoryTools: true })).toContain(
+ "call `list_repos` to find it",
+ );
});
it("includes signed commit attribution instructions for cloud tasks", () => {
diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt.ts b/products/desktop/packages/agent/src/pi/task-system-prompt.ts
index 1cd54dc42bec..f1c9d4ab3342 100644
--- a/products/desktop/packages/agent/src/pi/task-system-prompt.ts
+++ b/products/desktop/packages/agent/src/pi/task-system-prompt.ts
@@ -104,16 +104,19 @@ Optimize for the fewest shell round trips.
- Never rerun a command solely to reproduce output you already have.`;
}
-export function buildChannelPrompt(repositoryToolsAvailable: boolean): string {
+export function buildChannelPrompt(
+ cwd: string,
+ 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.`;
+This task may not need a repository. Your working directory is \`${cwd}\`, task-specific scratch space. 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.
+- Your working directory is \`${cwd}\`, 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.
@@ -156,7 +159,9 @@ export function buildTaskSystemPrompt(
);
if (context.channelMode) {
- sections.push(buildChannelPrompt(capabilities.repositoryTools === true));
+ sections.push(
+ buildChannelPrompt(context.cwd, capabilities.repositoryTools === true),
+ );
}
if (context.customInstructions) {
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 0a07dc6938b7..cd67447ca139 100644
--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts
+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts
@@ -591,12 +591,17 @@ export class PiAgentServer {
typeof this.config.claudeCode?.systemPrompt === "string"
? this.config.claudeCode.systemPrompt
: this.config.claudeCode?.systemPrompt?.append;
+ // A repo-less run gets the tools to discover and clone a repository, and the
+ // channel prompt that names them. Derive both from one condition so the tools
+ // and the prompt that describes them can never disagree.
+ const channelMode = !this.config.repositoryPath;
const taskContext: TaskContext = {
projectId: this.config.projectId,
apiHost: this.config.apiUrl,
taskId: this.config.taskId,
cwd,
environment: "cloud",
+ channelMode,
additionalInstructions: configuredSystemPrompt,
};
const attributionHeaders = buildPosthogPropertyHeaderRecord({
@@ -621,7 +626,7 @@ export class PiAgentServer {
});
const extensions: PiRuntimeExtension[] = ["context-wiki"];
- if (!this.config.repositoryPath) {
+ if (channelMode) {
extensions.push("repository-tools");
}
if (this.config.autoPublish === true && this.config.createPr !== false) {