: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
chore(desktop): move harness behavior out of @posthog/agent (#102255)
Jonathan Mieloo46a517552ebc
diff --git a/.github/workflows/desktop-test.yml b/.github/workflows/desktop-test.ymlindex 398d40284aef..d93f0e509707 100644--- a/.github/workflows/desktop-test.yml+++ b/.github/workflows/desktop-test.yml@@ -334,10 +334,7 @@ jobs:key: desktop-pnpm-${{ runner.os }}-${{ hashFiles('products/desktop/pnpm-lock.yaml') }}- name: Build agent dependencies- run: |- pnpm --filter @posthog/shared run build- pnpm --filter @posthog/git run build- pnpm --filter @posthog/enricher run build+ run: pnpm exec turbo build --filter=@posthog/agent^...- name: Download native codex binary# Non-fatal at the STEP so a failure surfaces as the fail-loud binary guarddiff --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.tsindex a3807c996834..342542f53a00 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@@ -6,7 +6,6 @@ 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 {@@ -15,6 +14,7 @@ import {type McpServerConnection,} from "@posthog/shared";import { buildPosthogScopedPropertyHeaderRecord } from "@posthog/shared/posthog-property-headers";+import type { TaskContext } from "@posthog/shared/task-context";import { prepareContextWiki } from "@posthog/workspace-server/services/agent/context-wiki";import {AGENT_AUTH,diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.mdindex fb1eea32cb8c..b22ce2fc6be1 100644--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md@@ -78,6 +78,10 @@ When changing Codex versions, update both `packages/agent/package.json` and `appThe downloader skips existing binaries, so remove `apps/code/resources/codex-acp/codex` and `apps/code/resources/codex-acp/codex-code-mode-host` before running it again after a version change (use the `.exe` filenames on Windows).For Claude Code, keep the Claude Agent SDK versions in `packages/agent/package.json` and `packages/workspace-server/package.json` aligned and regenerate the desktop lockfile.+The agent bundles `@posthog/harness` through `noExternal` in `packages/agent/tsup.config.ts` and copies its runtime assets during the build.+Keep it in the agent's `devDependencies`, alongside the other bundled workspace packages.+Adding it to production dependencies makes Electron packaging expand the harness dependency tree repeatedly and fail with `Invalid string length`.+## Run the appAlready working in the posthog/posthog monorepo? Skip the clone: the app lives at `products/desktop`. Note it needs Node 22 (see `.node-version`), not the Node version the monorepo's flox environment provides, so switch with your version manager first.diff --git a/products/desktop/docs/TESTING.md b/products/desktop/docs/TESTING.mdindex 207b0f51312d..20ef06761b59 100644--- a/products/desktop/docs/TESTING.md+++ b/products/desktop/docs/TESTING.md@@ -9,6 +9,13 @@- `pnpm test:e2e`: run Playwright E2E tests.- `pnpm --filter <pkg> test`: run tests for one package.+## Live agent tests++Before running `pnpm --filter @posthog/agent test:e2e`, build its workspace dependencies with `pnpm exec turbo build --filter=@posthog/agent^...` from `products/desktop`.+This includes the harness extensions imported by the agent source.+Desktop CI uses the same dependency graph so new workspace dependencies are built before the live tests start.+The suite requires `POSTHOG_CODE_E2E_GATEWAY_PERSONAL_API_KEY`, a reachable `POSTHOG_CODE_E2E_GATEWAY_URL`, and the bundled Codex binary.+## Test TypesUse unit tests when the code can run without Electron.diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.mdindex c1f8acdff66d..2e2ecb6a54cc 100644--- a/products/desktop/packages/agent/README.md+++ b/products/desktop/packages/agent/README.md@@ -42,8 +42,6 @@ The core runtime for PostHog cloud runs. Provides two things: an **Agent SDK** fquery() stdin/stdout```-## Design decisions-### Why ACP?ACP is a standard protocol for agent ↔ client communication over ndJson streams. Using it gives us two things:@@ -167,7 +165,7 @@ Required environment variables (validated by zod in `src/server/bin.ts`):Optional behavior toggles:-- `POSTHOG_BENJAMIN` — `1` or `true` appends the vendored Benjamin-Plus token-efficiency instruction (`src/adapters/benjamin/instruction.ts`) to the Claude system prompt and the Codex instructions, and stamps the pinned upstream commit into run state as `benjamin_version` at session start. Any other value leaves prompts unchanged.+- `POSTHOG_BENJAMIN` — `1` or `true` appends the vendored Benjamin-Plus token-efficiency instruction (`@posthog/harness/extensions/benjamin`, source at `packages/harness/src/extensions/benjamin/instruction.ts`) to the Claude system prompt and the Codex instructions, and stamps the pinned upstream commit into run state as `benjamin_version` at session start. Any other value leaves prompts unchanged.Optional run telemetry (the logs pair must both be set, otherwise telemetry stays off):diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.jsonindex 8b28d618b47c..88de330ef8dc 100644--- a/products/desktop/packages/agent/package.json+++ b/products/desktop/packages/agent/package.json@@ -28,18 +28,10 @@"types": "./dist/posthog-api.d.ts","import": "./dist/posthog-api.js"},- "./posthog-products": {- "types": "./dist/posthog-products.d.ts",- "import": "./dist/posthog-products.js"- },"./pi/rpc-client": {"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"@@ -168,7 +160,6 @@"devDependencies": {"@posthog/shared": "workspace:*","@posthog/git": "workspace:*",- "@posthog/enricher": "workspace:*","@posthog/harness": "workspace:*","@types/bun": "1.3.14","msw": "^2.12.7",diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.tsindex 2005b4b3068a..4140f8b0afbc 100644--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts@@ -1,12 +1,9 @@import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";+import type { ContextWikiEnv } from "@posthog/harness/extensions/context-wiki";import type { Adapter } from "@posthog/shared";import type { ModelInfo } from "../gateway-models";import type { SessionLogWriter } from "../session-log-writer";-import type {- ContextWikiEnv,- PostHogAPIConfig,- ProcessSpawnedCallback,-} from "../types";+import type { PostHogAPIConfig, ProcessSpawnedCallback } from "../types";import { createEventIdSource, type NextEventId } from "../utils/event-id";import { Logger } from "../utils/logger";import {diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex bd3b175cc803..b44c06a55087 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -45,6 +45,25 @@ import {type SDKUserMessage,type SlashCommand,} from "@anthropic-ai/claude-agent-sdk";+import type { ContextWikiEnv } from "@posthog/harness/extensions/context-wiki";+import {+ createEnrichment,+ type Enrichment,+ type FileEnrichmentDeps,+} from "@posthog/harness/extensions/enrichment";+import {+ isCloudRun,+ LOCAL_TOOLS_MCP_NAME,+ type LocalToolCtx,+ resolveGithubToken,+} from "@posthog/harness/extensions/local-tools";+import {+ classifyPostHogExecCall,+ isUnclassifiedPostHogSubTool,+ POSTHOG_PRODUCTS,+ type PostHogProductId,+ resolvePostHogExecPermissionRegex,+} from "@posthog/harness/extensions/posthog-mcp-policy";import { leadingSlashCommand, serializeError } from "@posthog/shared";import { v7 as uuidv7 } from "uuid";import packageJson from "../../../package.json" with { type: "json" };@@ -55,33 +74,14 @@ import {type SteerDeclineCause,steerDeclined,} from "../../acp-extensions";-import {- createEnrichment,- type Enrichment,- type FileEnrichmentDeps,-} from "../../enrichment/file-enricher";import { PostHogAPIClient } from "../../posthog-api";-import { resolvePostHogExecPermissionRegex } from "../../posthog-exec-permission";-import {- classifyPostHogExecCall,- isUnclassifiedPostHogSubTool,- POSTHOG_PRODUCTS,- type PostHogProductId,-} from "../../posthog-products";-import type { ContextWikiEnv, PostHogAPIConfig } from "../../types";+import type { PostHogAPIConfig } from "../../types";import { text } from "../../utils/acp-content";-import {- isCloudRun,- unreachable,- withAbort,- withTimeout,-} from "../../utils/common";-import { resolveGithubToken } from "../../utils/github-token";+import { unreachable, withAbort, withTimeout } from "../../utils/common";import { Logger } from "../../utils/logger";import { Pushable } from "../../utils/streams";import { BaseAcpAgent } from "../base-acp-agent";import { isLocalSkillCommandChunk } from "../local-skill";-import { LOCAL_TOOLS_MCP_NAME, type LocalToolCtx } from "../local-tools";import { visiblePromptBlocks } from "../prompt-blocks";import {resolveBedrockGatewayVariant,@@ -409,7 +409,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {this.emittedToolCalls = new Set();this.toolUseStreamCache = new Map();this.logger = new Logger({ debug: true, prefix: "[ClaudeAcpAgent]" });- this.enrichment = createEnrichment(options?.posthogApiConfig, this.logger);+ this.enrichment = createEnrichment(options?.posthogApiConfig);}protected getEnrichmentDeps(): FileEnrichmentDeps | undefined {diff --git a/products/desktop/packages/agent/src/adapters/claude/hooks.test.ts b/products/desktop/packages/agent/src/adapters/claude/hooks.test.tsindex b5e0c184f61c..b02e6295975f 100644--- a/products/desktop/packages/agent/src/adapters/claude/hooks.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/hooks.test.ts@@ -1,9 +1,9 @@import type { HookInput } from "@anthropic-ai/claude-agent-sdk";+import type { FileEnrichmentDeps } from "@posthog/harness/extensions/enrichment";import { describe, expect, test, vi } from "vitest";-import type { FileEnrichmentDeps } from "../../enrichment/file-enricher";const enrichFileMock = vi.hoisted(() => vi.fn());-vi.mock("../../enrichment/file-enricher", () => ({+vi.mock("@posthog/harness/extensions/enrichment", () => ({enrichFileForAgent: enrichFileMock,}));diff --git a/products/desktop/packages/agent/src/adapters/claude/hooks.ts b/products/desktop/packages/agent/src/adapters/claude/hooks.tsindex f0afb38bb438..abe41cefe7ac 100644--- a/products/desktop/packages/agent/src/adapters/claude/hooks.ts+++ b/products/desktop/packages/agent/src/adapters/claude/hooks.ts@@ -2,17 +2,17 @@ import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";import {enrichFileForAgent,type FileEnrichmentDeps,-} from "../../enrichment/file-enricher";+} from "@posthog/harness/extensions/enrichment";+import { SIGNED_COMMIT_QUALIFIED_TOOL_NAME } from "@posthog/harness/extensions/local-tools";import {extractPostHogSubTool,isPostHogExecTool,matchesPostHogExecPermission,-} from "../../posthog-exec-permission";+} from "@posthog/harness/extensions/posthog-mcp-policy";+import { gitSubcommand } from "@posthog/harness/extensions/rtk";import type { Logger } from "../../utils/logger";-import { SIGNED_COMMIT_QUALIFIED_TOOL_NAME } from "../signed-commit-shared";import { stripCatLineNumbers } from "./conversion/sdk-to-acp";import type { TaskState } from "./conversion/task-state";-import { gitSubcommand } from "./git-command";import { neutralizeUnprocessableImages } from "./image-sanitization";import type { SettingsManager } from "./session/settings";import type { CodeExecutionMode } from "./tools";diff --git a/products/desktop/packages/agent/src/adapters/claude/mcp/local-tools.ts b/products/desktop/packages/agent/src/adapters/claude/mcp/local-tools.tsindex 9f683847247a..b7b747a111ff 100644--- a/products/desktop/packages/agent/src/adapters/claude/mcp/local-tools.ts+++ b/products/desktop/packages/agent/src/adapters/claude/mcp/local-tools.ts@@ -8,7 +8,7 @@ import {LOCAL_TOOLS_MCP_NAME,type LocalToolCtx,type LocalToolGateMeta,-} from "../../local-tools";+} from "@posthog/harness/extensions/local-tools";/*** In-process SDK MCP server exposing the enabled local tools to the Claudediff --git a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.tsindex fff300c5caf8..1a58b6a24637 100644--- a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts@@ -1,11 +1,11 @@import * as fs from "node:fs/promises";import * as os from "node:os";import * as path from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {compilePostHogExecPermissionRegex,DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,-} from "../../../posthog-exec-permission";+} from "@posthog/harness/extensions/posthog-mcp-policy";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {clearMcpToolMetadataCache,fetchMcpToolMetadata,diff --git a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.tsindex e175d4860f3b..859997063c73 100644--- a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts+++ b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts@@ -8,16 +8,18 @@ import type {PermissionRuleValue,PermissionUpdate,} from "@anthropic-ai/claude-agent-sdk";+import {+ qualifiedLocalToolName,+ SHOW_ACTIONS_TOOL_NAME,+ SPEAK_TOOL_NAME,+} from "@posthog/harness/extensions/local-tools";import {extractPostHogSubTool,isPostHogExecTool,matchesPostHogExecPermission,-} from "../../../posthog-exec-permission";+} from "@posthog/harness/extensions/posthog-mcp-policy";import { text } from "../../../utils/acp-content";import type { Logger } from "../../../utils/logger";-import { qualifiedLocalToolName } from "../../local-tools";-import { SHOW_ACTIONS_TOOL_NAME } from "../../local-tools/tools/show-actions";-import { SPEAK_TOOL_NAME } from "../../local-tools/tools/speak";import { toolInfoFromToolUse } from "../conversion/tool-use-to-acp";import {getMcpToolApprovalState,diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.tsindex fcd7f0e6f731..2f79e80e0367 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts@@ -13,6 +13,14 @@ import type {SpawnedProcess,SpawnOptions,} from "@anthropic-ai/claude-agent-sdk";+import { buildAppendedInstructions } from "@posthog/harness/extensions/agent-instructions";+import {+ applyContextWikiEnv,+ type ContextWikiEnv,+ resolveContextWikiPath,+} from "@posthog/harness/extensions/context-wiki";+import type { FileEnrichmentDeps } from "@posthog/harness/extensions/enrichment";+import { resolveRtkPrefix } from "@posthog/harness/extensions/rtk";import {BEDROCK_LLM_GATEWAY_FLAG,type BedrockGatewayVariant,@@ -21,12 +29,6 @@ import {buildPosthogProjectHeaderLines,buildPosthogPropertyHeaderLines,} from "@posthog/shared/posthog-property-headers";-import {- applyContextWikiEnv,- resolveContextWikiPath,-} from "../../../context-wiki";-import type { FileEnrichmentDeps } from "../../../enrichment/file-enricher";-import type { ContextWikiEnv } from "../../../types";import { IS_ROOT } from "../../../utils/common";import type { Logger } from "../../../utils/logger";import type { TaskState } from "../conversion/task-state";@@ -49,10 +51,9 @@ import {} from "../machine-auth";import { type CodeExecutionMode, toSdkPermissionMode } from "../tools";import type { EffortLevel } from "../types";-import { buildAppendedInstructions } from "./instructions";import { loadUserClaudeJsonMcpServers } from "./mcp-config";import { DEFAULT_MODEL, resolveFallbackModel } from "./models";-import { createRtkRewriteHook, resolveRtkPrefix } from "./rtk";+import { createRtkRewriteHook } from "./rtk-hook";import type { SettingsManager } from "./settings";import { buildTraceparentHookSettingsJson } from "./traceparent-hook";diff --git a/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.test.tsnew file mode 100644index 000000000000..2a825ac06e86--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.test.ts@@ -0,0 +1,61 @@+import type { HookInput } from "@anthropic-ai/claude-agent-sdk";+import { describe, expect, test } from "vitest";+import type { Logger } from "../../../utils/logger";+import { createRtkRewriteHook } from "./rtk-hook";++describe("createRtkRewriteHook", () => {+ const logger = {+ info() {},+ warn() {},+ error() {},+ debug() {},+ } as unknown as Logger;++ const bashInput = (command: string): HookInput =>+ ({+ session_id: "s",+ transcript_path: "/tmp/t",+ cwd: "/tmp",+ hook_event_name: "PreToolUse",+ tool_name: "Bash",+ tool_input: { command },+ }) as unknown as HookInput;++ test("rewrites an eligible Bash command to updatedInput", async () => {+ const hook = createRtkRewriteHook("rtk", logger);+ const result = await hook(bashInput("git status"), "tool-1", {+ signal: new AbortController().signal,+ });+ expect(result).toMatchObject({+ continue: true,+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ updatedInput: { command: "rtk git status" },+ },+ });+ });++ test("passes ineligible commands through untouched", async () => {+ const hook = createRtkRewriteHook("rtk", logger);+ const result = await hook(bashInput("npm test"), "tool-1", {+ signal: new AbortController().signal,+ });+ expect(result).toEqual({ continue: true });+ });++ test("ignores non-Bash tools", async () => {+ const hook = createRtkRewriteHook("rtk", logger);+ const input = {+ session_id: "s",+ transcript_path: "/tmp/t",+ cwd: "/tmp",+ hook_event_name: "PreToolUse",+ tool_name: "Read",+ tool_input: { file_path: "/x" },+ } as unknown as HookInput;+ const result = await hook(input, "tool-1", {+ signal: new AbortController().signal,+ });+ expect(result).toEqual({ continue: true });+ });+});diff --git a/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.ts b/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.tsnew file mode 100644index 000000000000..e4d60cda9b5e--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/claude/session/rtk-hook.ts@@ -0,0 +1,26 @@+import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";+import { rewriteBashForRtk } from "@posthog/harness/extensions/rtk";+import type { Logger } from "../../../utils/logger";++export const createRtkRewriteHook =+ (rtkPrefix: string, logger: Logger): HookCallback =>+ async (input: HookInput, _toolUseID: string | undefined) => {+ if (input.hook_event_name !== "PreToolUse") return { continue: true };+ if (input.tool_name !== "Bash") return { continue: true };++ const toolInput = input.tool_input as { command?: string } | undefined;+ const command = toolInput?.command;+ if (typeof command !== "string") return { continue: true };++ const rewritten = rewriteBashForRtk(command, rtkPrefix);+ if (!rewritten) return { continue: true };++ logger.info(`[RtkRewriteHook] Rewriting: ${command} → ${rewritten}`);+ return {+ continue: true,+ hookSpecificOutput: {+ hookEventName: "PreToolUse" as const,+ updatedInput: { ...toolInput, command: rewritten },+ },+ };+ };diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.tsindex 3693da4d7435..ff818531c593 100644--- a/products/desktop/packages/agent/src/adapters/claude/types.ts+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts@@ -10,10 +10,10 @@ import type {Query,SDKUserMessage,} from "@anthropic-ai/claude-agent-sdk";+import type { PostHogProductId } from "@posthog/harness/extensions/posthog-mcp-policy";import type { BedrockGatewayVariant } from "@posthog/shared";import type { EffortLevel } from "@posthog/shared/domain-types";import type { SteerDeclineCause } from "../../acp-extensions";-import type { PostHogProductId } from "../../posthog-products";import type { AgentMode } from "../../types";import type { Pushable } from "../../utils/streams";import type { BaseSession } from "../base-acp-agent";diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.tsindex 46ec639d41e9..837938e1ce97 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts@@ -22,6 +22,18 @@ import type {StopReason,} from "@agentclientprotocol/sdk";import { RequestError } from "@agentclientprotocol/sdk";+import {+ buildContextWikiInstructions,+ type ContextWikiEnv,+ resolveContextWikiPath,+} from "@posthog/harness/extensions/context-wiki";+import { LOCAL_TOOLS_MCP_NAME } from "@posthog/harness/extensions/local-tools";+import {+ extractPostHogSubTool,+ isPostHogExecDescriptor,+ matchesPostHogExecPermission,+ resolvePostHogExecPermissionRegex,+} from "@posthog/harness/extensions/posthog-mcp-policy";import {classifyGatewayLimitError,mcpToolKey,@@ -35,19 +47,9 @@ import {POSTHOG_NOTIFICATIONS,steerDeclined,} from "../../acp-extensions";-import {- buildContextWikiInstructions,- resolveContextWikiPath,-} from "../../context-wiki";import type { ModelInfo } from "../../gateway-models";import { DEFAULT_CODEX_MODEL } from "../../gateway-models";-import {- extractPostHogSubTool,- isPostHogExecDescriptor,- matchesPostHogExecPermission,- resolvePostHogExecPermissionRegex,-} from "../../posthog-exec-permission";-import type { ContextWikiEnv, ProcessSpawnedCallback } from "../../types";+import type { ProcessSpawnedCallback } from "../../types";import { ALLOW_BYPASS } from "../../utils/common";import { Logger } from "../../utils/logger";import {@@ -66,7 +68,6 @@ import {sanitizeAgentErrorCause,} from "../error-classification";import { isLocalSkillCommandChunk } from "../local-skill";-import { LOCAL_TOOLS_MCP_NAME } from "../local-tools";import { visiblePromptBlocks } from "../prompt-blocks";import { resolveSpokenNarration } from "../session-meta";import {diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.tsindex 92faafd74b80..8c4c581da1b7 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts@@ -19,7 +19,7 @@ import {LOCAL_TOOLS,LOCAL_TOOLS_MCP_NAME,type LocalToolCtx,-} from "../local-tools";+} from "@posthog/harness/extensions/local-tools";function die(message: string): never {process.stderr.write(`[local-tools-mcp-server] ${message}\n`);diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.tsindex 8d6097156b25..cf5c0bbc73f3 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts@@ -1,5 +1,5 @@+import { LOCAL_TOOLS_MCP_NAME } from "@posthog/harness/extensions/local-tools";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { LOCAL_TOOLS_MCP_NAME } from "../local-tools";import { buildLocalToolsServer } from "./local-tools-mcp";// The dist asset isn't on the walk-up path in unit tests, so make existsSyncdiff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.tsindex b46d5102c221..e7fb74046bc2 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts@@ -7,14 +7,14 @@import type { McpServerStdio } from "@agentclientprotocol/sdk";import { ghTokenEnv } from "@posthog/git/signed-commit";-import { resolveGithubToken } from "../../utils/github-token";-import { resolveBundledMcpScript } from "../../utils/resolve-bundled-script";import {enabledLocalTools,LOCAL_TOOLS_MCP_NAME,type LocalToolCtx,type LocalToolGateMeta,-} from "../local-tools";+ resolveGithubToken,+} from "@posthog/harness/extensions/local-tools";+import { resolveBundledMcpScript } from "../../utils/resolve-bundled-script";import { resolveTaskId } from "../session-meta";/**diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.tsindex df3b0e5b7bb1..9fc1c4b9d303 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts@@ -1,5 +1,5 @@import type { McpServer } from "@agentclientprotocol/sdk";-import { isPostHogExecDescriptor } from "../../posthog-exec-permission";+import { isPostHogExecDescriptor } from "@posthog/harness/extensions/posthog-mcp-policy";import { sanitizeMcpServerName } from "../claude/mcp/tool-metadata";interface CodexMcpServerToolConfig {diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.tsindex 282e4e3fec0a..551b62272767 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts@@ -2,8 +2,11 @@ import { type ChildProcess, execFileSync, spawn } from "node:child_process";import { existsSync } from "node:fs";import { delimiter, dirname } from "node:path";import type { Readable, Writable } from "node:stream";-import { applyContextWikiEnv } from "../../context-wiki";-import type { ContextWikiEnv, ProcessSpawnedCallback } from "../../types";+import {+ applyContextWikiEnv,+ type ContextWikiEnv,+} from "@posthog/harness/extensions/context-wiki";+import type { ProcessSpawnedCallback } from "../../types";import { Logger } from "../../utils/logger";/**diff --git a/products/desktop/packages/agent/src/enrichment/file-enricher.ts b/products/desktop/packages/agent/src/enrichment/file-enricher.tsdeleted file mode 100644index b37d3000fbcb..000000000000--- a/products/desktop/packages/agent/src/enrichment/file-enricher.ts+++ /dev/null@@ -1,177 +0,0 @@-import * as path from "node:path";-import {- EXT_TO_LANG_ID,- type ImportEdge,- type LocalWrapper,- type ParseContext,- PostHogEnricher,-} from "@posthog/enricher";-import type { PostHogAPIConfig } from "../types";-import type { Logger } from "../utils/logger";--export interface FileEnrichmentDeps {- enricher: PostHogEnricher;- apiConfig: PostHogAPIConfig;- logger?: Logger;-}--export interface Enrichment {- deps: FileEnrichmentDeps;- dispose(): void;-}--export function createEnrichment(- apiConfig: PostHogAPIConfig | undefined,- logger?: Logger,-): Enrichment | undefined {- if (!apiConfig) return undefined;- const enricher = new PostHogEnricher();- return {- deps: { enricher, apiConfig, logger },- dispose: () => enricher.dispose(),- };-}--const MAX_ENRICHMENT_BYTES = 1_000_000;-const MAX_RELATIVE_IMPORTS = 64;-const RELATIVE_IMPORT_REGEX =- /(?:^|\n)\s*(?:import\b[^\n]*['"]\.{1,2}\/|from\s+\.)/;-const POSTHOG_LITERAL_REGEX = /posthog/i;--export async function enrichFileForAgent(- deps: FileEnrichmentDeps,- filePath: string,- content: string,-): Promise<string | null> {- if (!content || content.length > MAX_ENRICHMENT_BYTES) return null;-- const ext = path.extname(filePath).toLowerCase();- const langId = EXT_TO_LANG_ID[ext];- if (!langId || !deps.enricher.isSupported(langId)) return null;-- const hasPostHogLiteral = POSTHOG_LITERAL_REGEX.test(content);- const hasRelativeImport = RELATIVE_IMPORT_REGEX.test(content);- let parseContext: ParseContext | undefined;-- // Build wrapper context whenever the file has relative imports — direct PostHog- // usage and wrapper usage can coexist in the same file, so we don't skip this- // just because `posthog` already appears literally.- if (hasRelativeImport) {- const absPath = path.resolve(filePath);- const ctx = await buildWrapperContext(deps, content, langId, absPath);- if (ctx) parseContext = ctx;- }-- // Bail only when nothing at all could be enriched: no direct posthog literal- // AND no resolvable wrappers.- if (!hasPostHogLiteral && !parseContext) return null;-- try {- const parsed = await deps.enricher.parse(content, langId, parseContext);- if (parsed.calls.length === 0 && parsed.initCalls.length === 0) {- return null;- }-- const apiKey = await deps.apiConfig.getApiKey();- if (!apiKey) return null;-- const enriched = await parsed.enrichFromApi({- apiKey,- host: deps.apiConfig.apiUrl,- publicHost: deps.apiConfig.publicApiUrl,- projectId: deps.apiConfig.projectId,- timeoutMs: 5_000,- });-- const annotated = enriched.toInlineComments({- includeEventDescriptions: false,- includeExperimentNames: false,- });- if (annotated === content) {- deps.logger?.debug("File enrichment produced no changes", {- filePath,- calls: parsed.calls.length,- });- return null;- }- deps.logger?.debug("File enriched", {- filePath,- calls: parsed.calls.length,- viaWrappers: parsed.calls.filter((c) => c.viaWrapper).length,- });- return annotated;- } catch (err) {- const detail =- err instanceof Error- ? { message: err.message, name: err.name, stack: err.stack }- : { value: String(err) };- deps.logger?.debug("File enrichment failed", { filePath, ...detail });- return null;- }-}--async function buildWrapperContext(- deps: FileEnrichmentDeps,- content: string,- langId: string,- absPath: string,-): Promise<ParseContext | null> {- let edges: ImportEdge[];- try {- edges = await deps.enricher.findImportsInSource(content, langId, absPath);- } catch (err) {- deps.logger?.debug("Import resolution failed", {- absPath,- err: err instanceof Error ? err.message : String(err),- });- return null;- }-- if (!edges.length) return null;- const bounded = edges.slice(0, MAX_RELATIVE_IMPORTS);-- const wrappersByLocalName = new Map<string, LocalWrapper>();- const namespaceWrappers = new Map<string, Map<string, LocalWrapper>>();-- const resolutions = await Promise.all(- bounded.map(async (edge) => {- if (!edge.resolvedAbsPath) return null;- const wrappers = await deps.enricher.getWrappersForFile(- edge.resolvedAbsPath,- );- if (!wrappers.length) return null;- return { edge, wrappers };- }),- );-- for (const entry of resolutions) {- if (!entry) continue;- const { edge, wrappers } = entry;-- if (edge.isNamespace) {- const nsMap = new Map<string, LocalWrapper>();- for (const w of wrappers) {- if (w.isNamedExport || w.isDefaultExport) {- nsMap.set(w.name, w);- }- }- if (nsMap.size) namespaceWrappers.set(edge.localName, nsMap);- continue;- }-- if (edge.isDefault) {- const target = wrappers.find((w) => w.isDefaultExport);- if (target) wrappersByLocalName.set(edge.localName, target);- continue;- }-- const target = wrappers.find(- (w) => w.name === edge.importedName && w.isNamedExport,- );- if (target) wrappersByLocalName.set(edge.localName, target);- }-- if (!wrappersByLocalName.size && !namespaceWrappers.size) return null;-- return { wrappersByLocalName, namespaceWrappers };-}diff --git a/products/desktop/packages/agent/src/index.ts b/products/desktop/packages/agent/src/index.tsindex 4acb307033b7..70ae4fdd1897 100644--- a/products/desktop/packages/agent/src/index.ts+++ b/products/desktop/packages/agent/src/index.ts@@ -1,3 +1,4 @@+export { detectRtkBinary } from "@posthog/harness/extensions/rtk";export {isNotification,POSTHOG_METHODS,@@ -8,5 +9,3 @@ export {isMcpToolReadOnly,type McpToolMetadata,} from "./adapters/claude/mcp/tool-metadata";-export { detectRtkBinary } from "./adapters/claude/session/rtk";-export type { PostHogProductId } from "./posthog-products";diff --git a/products/desktop/packages/agent/src/pi/repository-tools-extension.ts b/products/desktop/packages/agent/src/pi/repository-tools-extension.tsindex ae700fefe075..0b947ecb74a2 100644--- a/products/desktop/packages/agent/src/pi/repository-tools-extension.ts+++ b/products/desktop/packages/agent/src/pi/repository-tools-extension.ts@@ -3,9 +3,12 @@ import type {InlineExtension,} from "@earendil-works/pi-coding-agent";import { defineTool } from "@earendil-works/pi-coding-agent";+import {+ enabledLocalTools,+ type LocalToolCtx,+} from "@posthog/harness/extensions/local-tools";import { convertJsonSchemaToTypebox } from "@posthog/harness/extensions/mcp/schema";import { z } from "zod";-import { enabledLocalTools, type LocalToolCtx } from "../adapters/local-tools";const REPOSITORY_TOOL_NAMES = new Set(["list_repos", "clone_repo"]);type NamedInlineExtension = Exclude<InlineExtension, ExtensionFactory>;diff --git a/products/desktop/packages/agent/src/pi/rpc-client.test.ts b/products/desktop/packages/agent/src/pi/rpc-client.test.tsindex 66d75194e557..bb734804f6d8 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.test.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.test.ts@@ -2,13 +2,13 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { RpcClient } from "@earendil-works/pi-coding-agent";+import type { TaskContext } from "@posthog/shared/task-context";import { describe, expect, it, vi } from "vitest";import {createPiRpcClient,createRuntimeMcpServers,createRuntimeMcpStdioServers,} from "./rpc-client";-import type { TaskContext } from "./task-system-prompt";function taskContext(cwd: string): TaskContext {return {diff --git a/products/desktop/packages/agent/src/pi/rpc-client.ts b/products/desktop/packages/agent/src/pi/rpc-client.tsindex 2c4cda1ceefb..856d7be6e598 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.ts@@ -9,6 +9,7 @@ import {type RpcClientOptions,type RpcEventListener,} from "@earendil-works/pi-coding-agent";+import type { PiEnrichmentConfig } from "@posthog/harness/extensions/enrichment";import type { McpConfig } from "@posthog/harness/extensions/mcp/config";import type {CloudRegion,@@ -17,10 +18,9 @@ import type {McpToolPermissionRequest,McpToolPolicy,} from "@posthog/shared";+import type { TaskContext } from "@posthog/shared/task-context";import { buildLocalToolsServer } from "../adapters/codex-app-server/local-tools-mcp";-import type { PiEnrichmentConfig } from "./enrichment-extension";import { safePiEnvironment } from "./rpc-environment";-import type { TaskContext } from "./task-system-prompt";import type {PiExtensionEvent,PiQueueSnapshot,diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.tsindex 1ca54964037b..59a5c601f582 100644--- a/products/desktop/packages/agent/src/pi/rpc-host.ts+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts@@ -5,12 +5,16 @@ import {} from "@earendil-works/pi-coding-agent";import { createHarnessRuntime, runRpcMode } from "@posthog/harness";import { createAutoPublishExtension } from "@posthog/harness/extensions/auto-publish";+import { createPiContextWikiExtension } from "@posthog/harness/extensions/context-wiki";+import { createPiEnrichmentExtension } from "@posthog/harness/extensions/enrichment";+import {+ createPiTaskSystemPromptExtension,+ resolvePiTaskContext,+} from "@posthog/harness/extensions/task-system-prompt";import type {McpToolPermissionDecision,McpToolPermissionRequest,} from "@posthog/shared";-import { createPiContextWikiExtension } from "./context-wiki-extension";-import { createPiEnrichmentExtension } from "./enrichment-extension";import {POSTHOG_PI_QUEUE_ENTRY_TYPE,readPersistedPiQueue,@@ -18,10 +22,6 @@ 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";diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex 6865e836a368..b42ac99ada4e 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -1,4 +1,5 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { API_DOWNLOAD_TIMEOUT_MS } from "@posthog/shared";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { PostHogAPIClient } from "./posthog-api";const mockFetch = vi.fn();@@ -10,6 +11,10 @@ describe("PostHogAPIClient", () => {vi.clearAllMocks();});+ afterEach(() => {+ vi.restoreAllMocks();+ });+it.each([["keeps known and backend-only fields",@@ -230,6 +235,37 @@ describe("PostHogAPIClient", () => {);});+ it.each([+ [+ "downloadArtifact",+ (client: PostHogAPIClient) =>+ client.downloadArtifact("task-1", "run-1", "tasks/artifacts/file.txt"),+ ],+ [+ "fetchTaskRunLogs",+ (client: PostHogAPIClient) =>+ client.fetchTaskRunLogs({ id: "run-1", task: "task-1" } as never),+ ],+ ])("gives %s the download timeout", async (_method, call) => {+ const timeout = vi.spyOn(AbortSignal, "timeout");+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ mockFetch.mockResolvedValueOnce({+ ok: true,+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(0)),+ text: vi.fn().mockResolvedValue(""),+ });++ await call(client);++ const init = mockFetch.mock.calls[0]?.[1] as RequestInit | undefined;+ expect(timeout.mock.calls).toEqual([[API_DOWNLOAD_TIMEOUT_MS]]);+ expect(init?.signal).toBe(timeout.mock.results[0]?.value);+ });+it.each([["includes message_id, text_parts and trace_id when provided",@@ -400,33 +436,4 @@ describe("PostHogAPIClient", () => {).rejects.toThrow("Failed to sync task session: [504] Gateway Timeout");expect(mockFetch).toHaveBeenCalledOnce();});-- it("returns only the artifacts created by the current upload request", async () => {- const client = new PostHogAPIClient({- apiUrl: "https://app.posthog.com",- getApiKey: vi.fn().mockResolvedValue("token"),- projectId: 1,- });-- mockFetch.mockResolvedValueOnce({- ok: true,- json: vi.fn().mockResolvedValue({- artifacts: [- { storage_path: "gs://bucket/existing.tar.gz", name: "existing" },- { storage_path: "gs://bucket/new-1.pack", name: "new-1" },- { storage_path: "gs://bucket/new-2.index", name: "new-2" },- ],- }),- });-- const artifacts = await client.uploadTaskArtifacts("task-1", "run-1", [- { name: "new-1", type: "artifact", content: "AAA" },- { name: "new-2", type: "artifact", content: "BBB" },- ]);-- expect(artifacts).toEqual([- { storage_path: "gs://bucket/new-1.pack", name: "new-1" },- { storage_path: "gs://bucket/new-2.index", name: "new-2" },- ]);- });});diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex b852dd87ee38..cecd5433816d 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -1,122 +1,29 @@import {+ API_DOWNLOAD_TIMEOUT_MS,+ API_TRANSFER_TIMEOUT_MS,type McpServerConnection,type McpToolApprovalState,type McpToolPolicy,+ PostHogHttpClient,type StoredLogEntry,+ type TaskRunUpdate,taskRunStateSchema,} from "@posthog/shared";import packageJson from "../package.json" with { type: "json" };-import type {- ArtifactSource,- ArtifactType,- PostHogAPIConfig,- StoredEntry,- Task,- TaskRun,- TaskRunArtifact,-} from "./types";+import type { PostHogAPIConfig, StoredEntry, Task, TaskRun } from "./types";import { getGatewayUsageUrl, getLlmGatewayUrl } from "./utils/gateway";export { getGatewayUsageUrl, getLlmGatewayUrl };+export { API_TRANSFER_TIMEOUT_MS, type TaskRunUpdate };const DEFAULT_USER_AGENT = `posthog/agent.hog.dev; version: ${packageJson.version}`;-// Deadlines for artifact transfers. Control-plane JSON gets the client's flat 30s-// convention (downloadTaskSession, syncTaskSession); byte-carrying payloads scale-// with size at a 256 KB/s throughput floor, so a slow-but-working link can finish-// a 30MB upload while a stall still aborts long before undici's ~5-minute-// internal defaults.-export const API_TRANSFER_TIMEOUT_MS = 30_000;-const MIN_TRANSFER_BYTES_PER_MS = 256;--export function transferTimeoutMs(byteLength: number): number {- return Math.max(- API_TRANSFER_TIMEOUT_MS,- Math.ceil(byteLength / MIN_TRANSFER_BYTES_PER_MS),- );-}--export interface TaskArtifactUploadPayload {- name: string;- type: ArtifactType;- source?: ArtifactSource;- content: string;- /** Encoding of `content`. With "base64" the backend stores the decoded bytes. */- content_encoding?: "utf-8" | "base64";- content_type?: string;-}--export interface TaskArtifactPrepareUploadPayload {- name: string;- type: ArtifactType;- source?: ArtifactSource;- size: number;- content_type?: string;-}--export interface PreparedTaskArtifactUpload {- id: string;- name: string;- type: ArtifactType;- source?: ArtifactSource;- size: number;- content_type?: string;- storage_path: string;- expires_in: number;- presigned_post: { url: string; fields: Record<string, string> };-}-export interface TaskSessionStorageAccess {id: string;download_url: string | null;content_sha256: string | null;}-export interface TaskArtifactFinalizeUploadPayload {- id: string;- name: string;- type: ArtifactType;- source?: ArtifactSource;- storage_path: string;- content_type?: string;-}--/** One peer agent run visible to a sender run (agent peer messaging discovery). */-export interface TaskRunPeer {- run_id: string;- task_id: string;- task_title: string;- created_by_email: string | null;- runtime: string;- model: string | null;- repository: string | null;- stage: string | null;- status: string;- /** Whether the peer accepts messages right now; never infer this from `status`. */- sendable: boolean;- updated_at: string | null;-}--export interface PeerMessageSendResult {- /**- * "accepted" (queued for delivery — not a delivery confirmation),- * "target_finished" (the peer's workflow is gone), or "rejected".- */- result: string;- detail: string;- message_id?: string | null;-}--export type TaskRunUpdate = Partial<- Pick<- TaskRun,- "status" | "branch" | "stage" | "error_message" | "output" | "state"- >-> & {- state_remove_keys?: string[];- state_append?: Record<string, unknown>;-};-export class PostHogAPIError extends Error {constructor(message: string,@@ -136,108 +43,41 @@ export class PostHogAPIError extends Error {}export class PostHogAPIClient {- private config: PostHogAPIConfig;+ private readonly http: PostHogHttpClient;private userNode: string | null | undefined;- constructor(config: PostHogAPIConfig) {- this.config = config;+ constructor(readonly config: PostHogAPIConfig) {+ this.http = new PostHogHttpClient(config, {+ defaultUserAgent: DEFAULT_USER_AGENT,+ buildError: (message, status) =>+ new PostHogAPIError(message, status, Boolean(config.refreshApiKey)),+ });}private get baseUrl(): string {- const host = this.config.apiUrl.endsWith("/")- ? this.config.apiUrl.slice(0, -1)- : this.config.apiUrl;- return host;- }-- private isTokenRejection(status: number): boolean {- // 401 means the token is invalid or expired, which a forced refresh- // fixes. 403 means the credential lacks permission; a refresh from the- // same grant cannot gain any, and forcing one on every 403 rotates the- // refresh token and rebuilds the whole desktop session.- return status === 401;- }-- private async resolveApiKey(forceRefresh = false): Promise<string> {- if (forceRefresh && this.config.refreshApiKey) {- return this.config.refreshApiKey();- }-- return this.config.getApiKey();+ return this.http.baseUrl;}- private async buildHeaders(- options: RequestInit,- forceRefresh = false,- ): Promise<Headers> {- const headers = new Headers(options.headers);- headers.set(- "Authorization",- `Bearer ${await this.resolveApiKey(forceRefresh)}`,- );- if (!headers.has("Content-Type")) {- headers.set("Content-Type", "application/json");- }- headers.set("User-Agent", this.config.userAgent ?? DEFAULT_USER_AGENT);- return headers;- }-- private async performRequest(- endpoint: string,- options: RequestInit,- forceRefresh = false,- ): Promise<Response> {- const url = `${this.baseUrl}${endpoint}`;-- return fetch(url, {- ...options,- headers: await this.buildHeaders(options, forceRefresh),- });+ private getTeamId(): number {+ return this.http.getTeamId();}- private async performRequestWithRetry(+ private apiRequest<T>(endpoint: string,options: RequestInit = {},- ): Promise<Response> {- let response = await this.performRequest(endpoint, options);-- if (!response.ok && this.isTokenRejection(response.status)) {- response = await this.performRequest(endpoint, options, true);- }-- return response;+ ): Promise<T> {+ return this.http.request<T>(endpoint, options);}- private async apiRequest<T>(+ private performRequestWithRetry(endpoint: string,options: RequestInit = {},- ): Promise<T> {- const response = await this.performRequestWithRetry(endpoint, options);-- if (!response.ok) {- let errorMessage: string;- try {- const errorResponse = await response.json();- errorMessage = `Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`;- } catch {- errorMessage = `Failed request: [${response.status}] ${response.statusText}`;- }- throw new PostHogAPIError(- errorMessage,- response.status,- Boolean(this.config.refreshApiKey),- );- }-- return response.json();- }-- private getTeamId(): number {- return this.config.projectId;+ ): Promise<Response> {+ return this.http.performRequestWithRetry(endpoint, options);}async getApiKey(forceRefresh = false): Promise<string> {- return this.resolveApiKey(forceRefresh);+ return this.http.resolveApiKey(forceRefresh);}getLlmGatewayUrl(): string {@@ -367,42 +207,13 @@ export class PostHogAPIClient {return { ...taskRun, state: taskRunStateSchema.parse(taskRun.state) };}- /**- * Record one task-analysis activity. The server owns the activities list, validates the- * shape and enforces the per-run cap, so this is the only way to add one.- */- async reportAnalysisActivity(- taskId: string,- runId: string,- activity: Record<string, unknown>,- signal?: AbortSignal,- ): Promise<{ activity_index: number }> {- const teamId = this.getTeamId();- return this.apiRequest<{ activity_index: number }>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/analysis-activity/`,- {- method: "POST",- body: JSON.stringify(activity),- signal,- },- );- }-async updateTaskRun(taskId: string,runId: string,payload: TaskRunUpdate,signal?: AbortSignal,): Promise<TaskRun> {- const teamId = this.getTeamId();- return this.apiRequest<TaskRun>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/`,- {- method: "PATCH",- body: JSON.stringify(payload),- signal,- },- );+ return this.http.updateTaskRun(taskId, runId, payload, signal);}async setTaskRunOutput(@@ -535,165 +346,6 @@ export class PostHogAPIClient {);}- async uploadTaskArtifacts(- taskId: string,- runId: string,- artifacts: TaskArtifactUploadPayload[],- ): Promise<TaskRunArtifact[]> {- if (!artifacts.length) {- return [];- }-- const teamId = this.getTeamId();- const body = JSON.stringify({ artifacts });- const response = await this.apiRequest<{ artifacts: TaskRunArtifact[] }>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/`,- {- method: "POST",- body,- // Carries the (base64-inflated) artifact bytes, so the deadline scales- // with the payload like the direct-to-storage POST does.- signal: AbortSignal.timeout(transferTimeoutMs(body.length)),- },- );-- const manifest = response.artifacts ?? [];-- // The backend returns the full run artifact manifest after each upload.- // Callers want the artifacts corresponding to this upload request only.- return manifest.slice(-artifacts.length);- }-- /**- * Reserve S3 keys and presigned POST forms so artifact bytes can be- * uploaded directly to object storage instead of traveling base64-encoded- * through the API (which enforces much smaller request body limits).- */- async prepareTaskArtifactUploads(- taskId: string,- runId: string,- artifacts: TaskArtifactPrepareUploadPayload[],- ): Promise<PreparedTaskArtifactUpload[]> {- if (!artifacts.length) {- return [];- }-- const teamId = this.getTeamId();- const response = await this.apiRequest<{- artifacts: PreparedTaskArtifactUpload[];- }>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/prepare_upload/`,- {- method: "POST",- body: JSON.stringify({ artifacts }),- signal: AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),- },- );- return response.artifacts ?? [];- }-- /** Attach directly-uploaded artifacts (see prepareTaskArtifactUploads) to the run manifest. */- async finalizeTaskArtifactUploads(- taskId: string,- runId: string,- artifacts: TaskArtifactFinalizeUploadPayload[],- ): Promise<TaskRunArtifact[]> {- if (!artifacts.length) {- return [];- }-- const teamId = this.getTeamId();- const response = await this.apiRequest<{ artifacts: TaskRunArtifact[] }>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/finalize_upload/`,- {- method: "POST",- body: JSON.stringify({ artifacts }),- signal: AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),- },- );-- // The backend returns the full run artifact manifest; pick out the- // entries for this request (retried finalizes can land mid-manifest).- const manifest = response.artifacts ?? [];- const byStoragePath = new Map(- manifest.map((artifact) => [artifact.storage_path, artifact]),- );- return artifacts- .map((artifact) => byStoragePath.get(artifact.storage_path))- .filter((artifact): artifact is TaskRunArtifact => !!artifact);- }-- /** Peer agent runs this run may message (agent peer messaging discovery). */- async listTaskRunPeers(- taskId: string,- runId: string,- ): Promise<TaskRunPeer[]> {- const teamId = this.getTeamId();- const response = await this.apiRequest<{ peers: TaskRunPeer[] }>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/peers/`,- );- return response.peers ?? [];- }-- /**- * Relay a message from this run to a peer agent run. The synchronous result- * means `accepted` (queued), never delivered — the sandbox handoff happens- * later inside the target's workflow.- */- async sendTaskRunPeerMessage(- taskId: string,- runId: string,- targetRunId: string,- payload: { content: string; artifactIds?: string[] },- ): Promise<PeerMessageSendResult> {- const teamId = this.getTeamId();- return this.apiRequest<PeerMessageSendResult>(- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/peers/${encodeURIComponent(targetRunId)}/message/`,- {- method: "POST",- body: JSON.stringify({- content: payload.content,- artifact_ids: payload.artifactIds ?? [],- }),- },- );- }-- /** Signal reports the given task is associated with (via report task associations). */- async getSignalReportIdsForTask(- taskId: string,- signal?: AbortSignal,- ): Promise<string[]> {- const teamId = this.getTeamId();- const response = await this.apiRequest<{ results?: { id: string }[] }>(- `/api/projects/${teamId}/signals/reports/?task_id=${encodeURIComponent(taskId)}&limit=100`,- { signal },- );- return (response.results ?? []).map((r) => r.id);- }-- /**- * Append a log artefact to a signal report, attributed to `taskId` via the- * `X-PostHog-Task-Id` header (the server validates it against the token's team).- */- async createSignalReportArtefact(- reportId: string,- taskId: string,- body: { artefact_type: string; content: Record<string, unknown> },- signal?: AbortSignal,- ): Promise<void> {- const teamId = this.getTeamId();- await this.apiRequest(- `/api/projects/${teamId}/signals/reports/${reportId}/artefacts/`,- {- method: "POST",- body: JSON.stringify(body),- headers: { "X-PostHog-Task-Id": taskId },- signal,- },- );- }-/*** Download artifact content by storage path* Streams the file through the PostHog backend so the sandbox does not need@@ -712,6 +364,7 @@ export class PostHogAPIClient {{method: "POST",body: JSON.stringify({ storage_path: storagePath }),+ signal: AbortSignal.timeout(API_DOWNLOAD_TIMEOUT_MS),},);if (!response.ok) {@@ -733,7 +386,9 @@ export class PostHogAPIClient {const endpoint = `/api/projects/${teamId}/tasks/${taskRun.task}/runs/${taskRun.id}/logs`;try {- const response = await this.performRequestWithRetry(endpoint);+ const response = await this.performRequestWithRetry(endpoint, {+ signal: AbortSignal.timeout(API_DOWNLOAD_TIMEOUT_MS),+ });if (!response.ok) {if (response.status === 404) {diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 7887ac78225c..548732db3506 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -11,6 +11,7 @@ import {import { tmpdir } from "node:os";import { join } from "node:path";import { type ContentBlock, RequestError } from "@agentclientprotocol/sdk";+import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION as STE100_INSTRUCTION } from "@posthog/harness/extensions/benjamin";import { type Adapter, IDLE_RESUME_STOP_REASON } from "@posthog/shared";import { zipSync } from "fflate";import jwt from "jsonwebtoken";@@ -28,7 +29,6 @@ import {} from "vitest";import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";import { getSessionJsonlPath } from "../adapters/claude/session/jsonl-hydration";-import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION as STE100_INSTRUCTION } from "../adapters/ste100-guidance";import type { PermissionMode } from "../execution-mode";import type { PostHogAPIClient } from "../posthog-api";import type { ResumeState } from "../resume";diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex c15f82848fb5..dc6c2e437744 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -18,6 +18,32 @@ import { type ServerType, serve } from "@hono/node-server";import { execGh } from "@posthog/git/gh";import { getCurrentBranch, getRemoteUrl } from "@posthog/git/queries";import { ghTokenEnv } from "@posthog/git/signed-commit";+import {+ appendBenjaminGuidance,+ appendSte100Guidance,+ BENJAMIN_UPSTREAM_COMMIT,+ isBenjaminEnabled,+} from "@posthog/harness/extensions/benjamin";+import { resolveGithubToken } from "@posthog/harness/extensions/local-tools";+import {+ compilePostHogExecPermissionRegex,+ DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,+ extractPostHogSubTool,+ isPostHogExecDescriptor,+ matchesPostHogExecPermission,+} from "@posthog/harness/extensions/posthog-mcp-policy";+import { appendRtkGuidanceForCodex } from "@posthog/harness/extensions/rtk";+import {+ buildStoreSkillsInstructions,+ syncStoreSkills,+} from "@posthog/harness/extensions/skills-store";+import {+ buildAttachedSkillsPrompt,+ buildCompactionContinuationPrompt,+ buildInstalledSkillPrompt,+ CloudTaskPrompt,+ parseLocalSkillInvocation,+} from "@posthog/harness/extensions/task-system-prompt";import {type AcpMcpServer,type Adapter,@@ -55,11 +81,6 @@ import {createAcpConnection,type InProcessAcpConnection,} from "../adapters/acp-connection";-import { BENJAMIN_UPSTREAM_COMMIT } from "../adapters/benjamin/instruction";-import {- appendBenjaminGuidance,- isBenjaminEnabled,-} from "../adapters/benjamin-guidance";import { setAlwaysAskMcpServers } from "../adapters/claude/mcp/tool-metadata";import {getSessionJsonlPath,@@ -76,27 +97,12 @@ import {isRetryableUpstreamErrorClassification,sanitizeAgentErrorCause,} from "../adapters/error-classification";-import { GH_STACK_QUALIFIED_TOOL_NAME } from "../adapters/local-tools/tools/gh-stack";import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";-import { appendRtkGuidanceForCodex } from "../adapters/rtk-guidance";-import {- SIGNED_COMMIT_QUALIFIED_TOOL_NAME,- SIGNED_MERGE_QUALIFIED_TOOL_NAME,- SIGNED_REWRITE_QUALIFIED_TOOL_NAME,-} from "../adapters/signed-commit-shared";-import { appendSte100Guidance } from "../adapters/ste100-guidance";import type { PermissionMode } from "../execution-mode";import { DEFAULT_CODEX_MODEL, fetchGatewayModels } from "../gateway-models";import { OtelRunTelemetry } from "../otel-telemetry";import { configurePersistentAgentState } from "../persistent-agent-state";import { PostHogAPIClient } from "../posthog-api";-import {- compilePostHogExecPermissionRegex,- DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,- extractPostHogSubTool,- isPostHogExecDescriptor,- matchesPostHogExecPermission,-} from "../posthog-exec-permission";import {findPrUrls,type OwnedBranch,@@ -123,7 +129,6 @@ import { resourceLink } from "../utils/acp-content";import { withTimeout } from "../utils/common";import { createEventIdSource } from "../utils/event-id";import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";-import { resolveGithubToken } from "../utils/github-token";import { Logger } from "../utils/logger";import { redactSecrets, SecretEventRedactor } from "../utils/redact-secrets";import { logAgentshRuntimeInfo } from "./agentsh-runtime";@@ -148,7 +153,6 @@ import {jsonRpcRequestSchema,validateCommandParams,} from "./schemas";-import { buildStoreSkillsInstructions, syncStoreSkills } from "./store-skills";import type { AgentServerConfig, ClaudeCodeConfig } from "./types";import { waitForFile } from "./wait-for-file";@@ -1429,9 +1433,7 @@ export class AgentServer {{sessionId: commandSession.acpSessionId,prompt: [- hiddenTextBlock(- "Compaction is complete. Continue working on the task from the compacted context, following the user's instructions from the /compact command.",- ),+ hiddenTextBlock(buildCompactionContinuationPrompt()),],},false,@@ -3714,7 +3716,7 @@ export class AgentServer {textBlockIndex === -1 ? null : contentBlocks[textBlockIndex];const invocation =textBlock?.type === "text"- ? this.parseLocalSkillInvocation(textBlock.text)+ ? parseLocalSkillInvocation(textBlock.text): null;if (invocation) {@@ -3732,7 +3734,7 @@ export class AgentServer {if (installedSkill) {return {skillName: invocation.skillName,- context: this.buildInstalledSkillPrompt(+ context: buildInstalledSkillPrompt(installedSkill,invocation.args,this.getCoInstalledSkillBundles(runId, invocation.skillName),@@ -3748,20 +3750,19 @@ export class AgentServer {).map((block) => block.text).join("\n");- return this.buildAttachedSkillsPromptContext(runId, artifacts, messageText);+ const context = this.buildAttachedSkillsPromptContext(+ runId,+ artifacts,+ messageText,+ );+ return context ? { context } : null;}- /**- * Fallback for messages that install skill bundles without being a bare- * `/skill` invocation: a running session can't discover mid-session- * installs, so skills named in the message get their definition inlined- * and the rest are listed with their paths.- */private buildAttachedSkillsPromptContext(runId: string,artifacts: TaskRunArtifact[],messageText: string,- ): LocalSkillPromptContext | null {+ ): string | null {const installed = artifacts.filter((artifact) =>@@ -3780,48 +3781,10 @@ export class AgentServer {),).filter((skill): skill is InstalledSkillBundle => !!skill);- if (installed.length === 0) {- return null;- }-- const mentioned = installed.filter((skill) => {- // token-boundary match so "/foo" never matches inside "/foobar"- const escaped = skill.skillName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- return new RegExp(- `(^|[\\s(\`"'\\[])/${escaped}(?![A-Za-z0-9_/-])`,- "m",- ).test(messageText);- });- const unmentioned = installed.filter((skill) => !mentioned.includes(skill));- const sections: string[] = [- "The user's message references local skills that are now installed for this run. Apply a skill's instructions when the message calls for it.",- ];- for (const skill of mentioned) {- sections.push(- "",- `--- BEGIN LOCAL SKILL ${skill.skillName} ---`,- skill.skillDefinition.trim(),- `--- END LOCAL SKILL ${skill.skillName} ---`,- `Installed skill path: ${skill.skillRoot}`,- );- }- if (unmentioned.length > 0) {- sections.push(- "",- "Other local skills installed for this run (read a skill's SKILL.md from its path when referenced):",- ...unmentioned.map(- (skill) => `- /${skill.skillName}: ${skill.skillRoot}`,- ),- );- }- return { context: sections.join("\n") };+ return buildAttachedSkillsPrompt(installed, messageText);}- /**- * Other skills already installed for this run (auto-bundled dependencies,- * skills from earlier messages), listed so the model can find them by path.- */private getCoInstalledSkillBundles(runId: string,invokedSkillName: string,@@ -3836,50 +3799,6 @@ export class AgentServer {.sort((a, b) => a.skillName.localeCompare(b.skillName));}- private parseLocalSkillInvocation(- textValue: string,- ): { skillName: string; args?: string } | null {- const trimmed = textValue.trim();- const match = trimmed.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);- if (!match?.[1]) {- return null;- }-- return {- skillName: match[1],- ...(match[2]?.trim() ? { args: match[2].trim() } : {}),- };- }-- private buildInstalledSkillPrompt(- skill: InstalledSkillBundle,- args: string | undefined,- coInstalledSkills: InstalledSkillBundle[] = [],- ): string {- return [- `The user invoked the local skill "/${skill.skillName}". Apply these skill instructions for this turn.`,- "",- `--- BEGIN LOCAL SKILL ${skill.skillName} ---`,- skill.skillDefinition.trim(),- `--- END LOCAL SKILL ${skill.skillName} ---`,- "",- `Installed skill path: ${skill.skillRoot}`,- ...(coInstalledSkills.length > 0- ? [- "",- "Other local skills installed for this run (when the skill above references one of these, read its SKILL.md from the listed path):",- ...coInstalledSkills.map(- (coInstalled) =>- `- /${coInstalled.skillName}: ${coInstalled.skillRoot}`,- ),- ]- : []),- "",- "User request:",- args?.trim() || `Run /${skill.skillName}.`,- ].join("\n");- }-private getInstalledSkillBundleInfoKey(runId: string,skillName: string,@@ -4453,17 +4372,6 @@ export class AgentServer {].join("\n");}- private buildExistingPrCheckoutInstruction(prUrl: string): string {- return `Continue working on the existing PR branch. If it is not already checked out, check it out with \`gh pr checkout ${prUrl}\`. Do not check it out again when it is already active.`;- }-- /**- * Fire-and-overlap: starts the best-effort PR-branch checkout so it runs- * concurrently with the rest of session setup, returning the promise (or- * null when there is nothing to check out). Only runs when auto-publishing,- * matching the system-prompt fallback's gate: a review-first run must not- * silently check out a branch the prompt told the agent to leave alone.- */private buildExistingPrCheckoutPromise(prUrl: string | null,): Promise<ExistingPrCheckoutResult> | null {@@ -4479,11 +4387,6 @@ export class AgentServer {});}- /**- * Consume a pre-checkout result without throwing — a transient `gh` failure- * must fall back to the agent's own checkout (via the system-prompt- * instruction), never abort session start.- */private logExistingPrCheckoutResult(prUrl: string | null,result: ExistingPrCheckoutResult,@@ -4505,107 +4408,27 @@ export class AgentServer {}}- private buildDetectedPrContext(prUrl: string): string {- if (!this.shouldAutoPublishCloudChanges()) {- return (- `An open pull request already exists: ${prUrl}\n` +- `Use that PR as context if it is helpful, but stop with local changes ready for review.\n` +- `Do NOT create commits, push to the PR branch, update the pull request, create a new branch, or create a new pull request unless the user explicitly asks.`- );- }-- return (- `IMPORTANT — OVERRIDE PREVIOUS INSTRUCTIONS ABOUT CREATING BRANCHES/PRs.\n` +- `You already have an open pull request: ${prUrl}\n` +- `Unless the user explicitly asks for a new branch or separate PR, you MUST:\n` +- `1. ${this.buildExistingPrCheckoutInstruction(prUrl)}\n` +- `2. Make changes, commit, and push to that branch\n` +- `By default, do not create a new branch, close the existing PR, or create a new PR — continue on the existing PR. If the user explicitly asks you to create a new branch or a separate PR, follow their instruction instead.`- );+ private getCloudTaskPrompt(): CloudTaskPrompt {+ return new CloudTaskPrompt({+ apiUrl: this.config.apiUrl,+ baseBranch: this.config.baseBranch,+ createPr: this.config.createPr,+ hasGithubToken: Boolean(resolveGithubToken()),+ isAutomatedOrigin: this.isAutomatedOrigin(),+ isSlack: this.isSlackReplyContext(),+ projectId: this.config.projectId,+ repositoryAttached: Boolean(this.config.repositoryPath),+ shouldAutoPublish: this.shouldAutoPublishCloudChanges(),+ slackArtifactDelivery: this.slackArtifactDelivery,+ slackChartDelivery: this.slackChartDelivery,+ storeSkillsInstalledCount: this.storeSkillsInstalledCount,+ taskId: this.config.taskId,+ taskRepositories: this.taskRepositories,+ });}- /**- * How this run may hand a deliverable to the Slack thread it is answering in.- *- * The offer has to match what delivery will actually accept: naming an adapter the- * workspace cannot use gets the request rejected server-side after the agent has already- * promised the user a canvas or a spreadsheet. The backend resolves that capability from- * the workspace's feature flags and Slack scopes when the task starts and hands it to us- * on the run state, so the wording lives here and the gating stays there.- */- private buildSlackDeliveryInstructions(): string {- if (this.slackArtifactDelivery === null) {- return "";- }-- if (this.slackArtifactDelivery === "none") {- return `-## Delivering to Slack-- You do not have artifact delivery in this workspace: you cannot create or share artifacts (files, canvases, documents) from this run, so do not attempt to. Deliver results as plain text in your reply.-- Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths.`;- }-- const endpoint = `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/`;- const preamble = `-## Delivering to Slack-- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.-- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.-- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;-- // Charts attach to both modes: they post as an image block referencing a PostHog-hosted- // url, so they work wherever the workspace can post at all.- const chartBullets = this.slackChartDelivery- ? `-- When an analytics answer is naturally visual (a trend over time, funnel, breakdown comparison, retention curve), deliver a chart image by default alongside the summary. Do not wait for the user to say "chart". Skip the image only when the result is a single number, a short list, or the user asked for raw data.-- To show a chart in Slack (a saved insight or an ad-hoc analytics query result), make a single call: POST to \`${endpoint}chart/\` with \`$POSTHOG_PERSONAL_API_KEY\` and body \`{"name": "<chart title>", "query": <query JSON, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}>}\`, or \`{"name": "<chart title>", "insight_id": <numeric insight id>}\` for a saved insight. It renders the chart server-side and registers it for Slack delivery in one step, blocking until done (typically a few seconds).-- The chart renders directly under your answer text with its name as the title, so do not restate the title or announce the chart ("Here's a chart of…"). Spend your answer text on the takeaway instead: the trend, inflection points, spikes, or drops a reader should notice, with numbers where they matter. Each chart is delivered with an "Open in PostHog" button, so do not paste the response \`url\` into your answer unless the user explicitly asks for a link. Do not download, view, or re-upload the image yourself.-- Report a chart failure rather than retrying blindly: a 400 carries the reason in \`error\`, or in \`detail\` when the request body itself was rejected, and a 429 means the project's chart render limit is saturated, so answer without the chart.-- SQL results cannot be charted yet, because the chart endpoint rejects SQL queries. Chart with an insight query (e.g. TrendsQuery) when the question can be expressed as one; otherwise summarize the SQL result in your answer text.`- : "";-- if (this.slackArtifactDelivery === "message") {- const chartException = this.slackChartDelivery- ? " Chart images are the one exception: deliver them through the dedicated chart endpoint below, never through the generic living-artifacts endpoint."- : "";- const unsupportedDeliverable = this.slackChartDelivery- ? "- If a deliverable cannot be expressed as a Slack message or a chart image (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."- : "- If a deliverable cannot be expressed as a Slack message (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead.";- return `${preamble}-- You do not have canvas or file delivery in this workspace: do not use the \`slack_canvas\` or \`slack_file\` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.${chartException}-- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}-${unsupportedDeliverable}`;- }-- return `${preamble}-- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\`; choose adapter \`slack_canvas\`, \`slack_message\`, \`slack_file\`, or \`document_connector\`. Use \`adapter=slack_file\` with \`content_base64\` for binary deliverables such as .xlsx/.pdf/.docx, or \`source_artifact_id\` / \`source_storage_path\` for a file you already uploaded as a \`type=output\` run artifact.-- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}-- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending file artifacts to your final answer automatically, so mention the artifact by name only if useful.-- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.`;- }-- private buildGithubAccessInstructions(hasGithubToken: boolean): string {- if (hasGithubToken) {- return `-## GitHub access-You have GitHub access in this session.`;- }-- const settingsUrl = `${this.config.apiUrl.replace(/\/$/, "")}/project/${this.config.projectId}/settings/user-personal-integrations`;- return `-## GitHub access-You do not have GitHub access in this session.-- You can read repository content that is already in the workspace.-- You can clone an exact public repository. Do not call \`list_repos\` without GitHub access.-- Codebase analysis and code review require readable repository content.-- Code changes also require publishing access.-- If the required access is unavailable, do not replace the requested code work with generic guidance or PostHog data analysis.-- Tell the user to connect GitHub at ${settingsUrl}.-- The connection applies to a new task, not this task.-- Write the access explanation first.-- Then call \`show_actions\` with one \`compose\` action.-- Use the label \`Try again in a new task\` and prefill the original repository request.-- Include the exact \`owner/repo\` in the action when you know it.-- Do not guess file contents. Do not start a change that you cannot deliver.`;+ private buildDetectedPrContext(prUrl: string): string {+ return this.getCloudTaskPrompt().buildDetectedPrContext(prUrl);}private buildCloudSystemPrompt(@@ -4613,306 +4436,11 @@ You do not have GitHub access in this session.slackThreadUrl?: string | null,inboxReportUrl?: string | null,): string {- const taskId = this.config.taskId;- const shouldAutoCreatePr = this.shouldAutoPublishCloudChanges();- const isSlack = this.isSlackReplyContext();- // Every instruction in this section runs through `gh`, so a sandbox holding no- // GitHub token cannot act on any of it. An empty token is an explicit logout.- const hasGithubToken = Boolean(resolveGithubToken());- const githubIdentityInstructions = hasGithubToken- ? `-# Whose GitHub account you are using-\`gh\` is authenticated as the person you are working for, so let GitHub resolve who that is. To put them on an issue or pull request, self-assign:- \`gh issue create --assignee "@me"\`, \`gh pr create --assignee "@me"\`, \`gh issue edit <number> --add-assignee "@me"\`-To \`@\`-mention them in a body or a comment, read their handle with \`gh api user --jq .login\`. Read it once per reply rather than reusing one from an earlier reply, because a different person can take over between replies and \`gh\` follows that change.-If the command fails, or returns a name ending in \`[bot]\`, you are acting as the PostHog app rather than as a person: ask them for their GitHub login instead of assigning or mentioning anyone.-`- : "";- const slackIdentityInstructions = isSlack- ? `-# Identity-You are the PostHog Slack app, PostHog's agent for helping users with their product data and coding tasks from Slack. When introducing yourself or referring to yourself in messages to the user, identify as "PostHog Slack app". Do NOT refer to yourself as Claude, an Anthropic assistant, or any underlying model name.--# Response Style-You are replying in a Slack thread. Slack readers want short, skimmable answers — be concise by default.-- Answer simple questions in a single sentence. Keep everything else brief — a few sentences at most.-- Lead with the answer or the outcome. Skip preamble, restating the question, and sign-offs.-- Prefer plain prose. Treat bullet lists as the exception, not the norm, and avoid headers and tables unless they genuinely make a complex answer clearer.-- Do not narrate your thinking or list every step you took; report what matters and the result.-- This is a default, not a hard rule. If the user (or their saved memory) asks for more depth or a specific format, follow that instead.--# PostHog products first-PostHog is a product suite, not just analytics — session replay, feature flags, experiments, surveys, error tracking, logs, data warehouse, CDP, messaging, and customer support all ship as PostHog products.-- When someone asks how to set up, enable, configure, or use a capability, assume they mean PostHog's version of it and answer about that.-- Search our docs with the \`docs-search\` tool before you answer, and ground the answer in what it returns rather than in what you remember. The product changes faster than your training data.-- Never send the user to a third-party product for something PostHog does. If you are unsure whether we cover it, search the docs before concluding we don't — and if we genuinely don't, say so plainly instead of recommending a competitor. Pointing at a third party we integrate with, as a source or destination, is fine.-- When a request could mean either a PostHog feature or something in the user's own codebase, ask which they mean instead of guessing.--# Mentioning users-To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appears in the message context — copy it verbatim, including the \`U…\` ID. Do NOT construct a mention token from a name, and do NOT substitute the display name (or any other string) for the \`U…\` ID — \`<@Jane|Jane Doe>\` is not a valid mention; only the form with the real ID like \`<@U01ABCDEF23|Jane Doe>\` is. If the person you want to refer to has no \`<@U…|displayname>\` token anywhere in the thread context, write their name as plain text instead of inventing one. These \`<@U…>\` tokens are Slack-only: never carry one — or a name or handle derived from it — into a GitHub PR, commit message, or review request as an \`@\`-mention. A Slack display name or handle is NOT a GitHub username; see the pull-request instructions below.--# Suggesting code changes-You can also open pull requests directly from this Slack thread. When the user's question describes a problem with a plausible code-side fix — a bug visible in errors or logs, missing or broken instrumentation, a broken funnel step traceable to UI code, a stale config that lives in a repo — end your reply with a one-sentence offer to open a PR for the fix and ask if they want you to proceed. Skip the offer for pure data lookups with no actionable code change (e.g. "what was DAU yesterday?"), and skip it when the fix would clearly live outside any repo you can reach.-`- : "";- const identityInstructions = `${slackIdentityInstructions}${githubIdentityInstructions}`;- const signedCommitInstructions = `-## Committing (signed commits required)-Commits MUST be signed. \`git commit\` and \`git push\` are blocked in this environment.-To commit: stage your changes with \`git add\`, then call the \`git_signed_commit\` tool (full-name \`${SIGNED_COMMIT_QUALIFIED_TOOL_NAME}\`) with a \`message\` (and optional \`body\`/\`paths\`).-It creates a GitHub-signed ("Verified") commit on the branch and keeps your local checkout in-sync. To start a new branch, pass \`branch\` (prefixed with \`posthog/\`) — the tool creates-it on the remote for you.--## Updating from the base branch-To bring the base branch into your PR branch, call the \`git_signed_merge\` tool (full name-\`${SIGNED_MERGE_QUALIFIED_TOOL_NAME}\`) — it creates a Verified two-parent merge commit-server-side (like GitHub's "Update branch" button). NEVER run \`git merge\` followed by-\`git_signed_commit\`: a merge in progress is refused, because the commit API would linearize-the merge and dump every base-branch change into your PR. If \`git_signed_merge\` reports a-conflict, fix it with a rebase instead: \`git rebase origin/<base>\`, resolve, \`git rebase---continue\`, then call \`git_signed_rewrite\`.--## Rewriting / force-pushing (rebases, conflict fixes)-\`git push --force\` is also blocked. To update a branch after a local rebase or conflict-resolution, rebase locally with normal \`git\` (resolve conflicts and finish with-\`git rebase --continue\`, NOT \`git commit\`), then call the \`git_signed_rewrite\` tool (full-name \`${SIGNED_REWRITE_QUALIFIED_TOOL_NAME}\`). It republishes the branch's commits as Verified-and atomically force-updates the remote branch. This is how you fix conflicts on an existing PR.-Histories containing merge commits are refused — rebase (which flattens merges) first.-If a signed-git tool refuses with a "merge in progress" or "leak" error, follow its recovery-instructions instead of retrying the same call.--## Re-committing to a branch with an open PR-Before committing again to a branch that already has an open PR, fetch it first. The remote-branch can advance between your commits — CI automation often auto-commits regenerated-artifacts (codegen, lockfiles, formatting) onto open PR branches, and collaborators can push-too. Committing from a stale local checkout silently reverts those commits, so-\`git_signed_commit\` refuses when the remote branch is ahead of your checkout. If it does, or-before your next commit, update your checkout — stash any uncommitted work across the update so-you don't lose it: \`git stash --include-untracked\`, \`git fetch origin <branch>\`,-\`git reset --hard origin/<branch>\`, \`git stash pop\` (resolve any conflicts), then re-stage-and commit. A soft/mixed reset would keep your stale files and re-commit the revert, so the-hard reset is the safe one here — your work is held in the stash.--## Attribution-Do NOT add "Co-Authored-By" trailers or "Generated with [Claude Code]" lines to your-commit messages. The \`git_signed_commit\` tool automatically appends the only trailers-we want:- Generated-By: PostHog Desktop- Task-Id: ${taskId}`;-- // A stack is several PRs, so this would contradict the review-first modes.- const stackInstructions = shouldAutoCreatePr- ? `-## Stacked pull requests-Stack only when the layers are independently reviewable (schema, then backend, then UI) or the-user asked for a stack. Keep stacks shallow — 2 to 4 layers. One PR remains the default.-Do NOT use the \`gh stack\` CLI: its publishing commands (\`submit\`, \`sync\`, \`push\`, \`link\`)-all run \`git push\`, which is blocked here. Build the stack this way instead:-1. Commit the bottom layer with \`git_signed_commit\`, passing \`branch\`, then open its pull- request based on the base branch.-2. For each layer above, commit with \`git_signed_commit\` and a new \`branch\` — your checkout- already sits on the layer below, so the branch starts there — then open its pull request- based on the branch of the layer below (\`--base <that branch>\`).-3. Link them with the \`gh_stack\` tool (full name \`${GH_STACK_QUALIFIED_TOOL_NAME}\`),- operation "create", passing \`pull_requests\` bottom to top. Every layer must target the- branch of the one below it, or the link is refused.-When a lower layer changes, restack the layers above it bottom-first. For each layer: check-that layer out, \`git rebase <its parent branch>\`, then republish it with-\`git_signed_rewrite\` passing \`onto\` = the parent branch. Check the layer out every time —-\`git_signed_rewrite\` replays whatever your local HEAD points at and uses \`branch\` only to-pick which remote ref moves, so rewriting from the wrong checkout publishes the wrong history-to that layer.`- : "";-- const prLinkInstructions = `-## Referencing pull requests-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.`;-- const shellEfficiencyInstructions = `-## 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.`;-- const artifactInstructions = `-## Delivering non-code files (artifacts)-When you create a non-code file the user should be able to download (such as a report, chart, image, archive, or data file), call the \`upload_artifact\` tool with its path before your final reply. In your final reply, link to the download URL returned by the tool—never link to the file's local workspace path. Files left in the workspace don't reach the user. Don't upload source code or repository changes—those belong in a commit or PR.`;-- // Closes out every branch below, so a new section is added once rather than five times.- const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.storeSkillsInstalledCount)}`;-- const whyContextInstruction = ` - Add a brief **Why** to the body — one or two sentences capturing the reason the user asked for this change (the motivation, not a restatement of the diff). Keep it short.`;- const publicRepoSafetyInstruction = ` - **Public-repo safety.** Treat the target repository as public-readable unless you have verified otherwise. The PR title, description, and commit messages must not contain private operational scale (exact event counts, internal row volumes, customer-usage percentages), customer names / emails / companies, references to internal tickets or incidents, the contents of Slack threads (do not quote or paraphrase what was said), or unreleased roadmap details. Linking to the originating Slack thread is fine and encouraged — Slack links are auth-gated and useful as context — as are channel references like "raised in #team-foo". Describe findings qualitatively ("present on nearly all X events, absent from Y") rather than with quantitative figures pulled from analytics queries — the reasoning that uses those numbers can stay in the thread; the PR copy cannot.`;- const prMentionSafetyInstruction = ` - **Never guess a GitHub identity.** Do NOT \`@\`-mention, tag, assign, request review from, or attribute the PR to a person (in the title, description, commit message, or reviewers) using a name or handle taken from Slack or this thread. A Slack display name or handle is NOT a GitHub username. Finding a similar-looking handle in the repo's git history, CODEOWNERS, or existing PRs/issues does NOT confirm it belongs to this person: repository presence proves the handle exists, not that it is the person you mean, so treating it as a match still \`@\`-tags an unrelated account (e.g. Slack "Ross" is not necessarily GitHub \`@ross\`, even if some \`@ross\` has committed to the repo). Only \`@\`-mention a GitHub \`@handle\` the user gave you explicitly in this thread, or one you read from \`gh api user --jq .login\`, which authenticates as the person you are working for. Otherwise refer to people by plain-text name, or omit the mention entirely.`;- // Slack- and inbox-originated PRs are attributed to PostHog, not the- // PostHog Desktop app — they come from the Slack app / Self-driving- // inbox, which users know as "PostHog".- const createdWith = this.isAutomatedOrigin()- ? "Created with [PostHog](https://posthog.com?ref=pr)"- : "Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)";- const prFooter = slackThreadUrl- ? `*${createdWith} from a [Slack thread](${slackThreadUrl})*`- : inboxReportUrl- ? `*${createdWith} from an [inbox report](${inboxReportUrl})*`- : `*${createdWith}*`;- const repositoryWorkspaceInstructions =- this.taskRepositories.length > 1- ? `The task workspace contains these repositories:-${this.taskRepositories.map((repository) => `- ${repository}: /tmp/workspace/repos/${repository.toLowerCase()}`).join("\n")}--Apply the repository workflow below separately in every repository you change. Keep branches, commits, diffs, and pull requests repository-specific.`- : "";-- if (prUrl) {- if (!shouldAutoCreatePr) {- return `${identityInstructions}-# Cloud Task Execution--This task already has an open pull request: ${prUrl}--Do the requested work, but stop with local changes ready for review.--Important:-- Do NOT create new commits, push to the branch, or update the pull request unless the user explicitly asks.-- Do NOT create a new branch or a new pull request unless the user explicitly asks.-${commonInstructions}-`;- }-- return `${identityInstructions}-# Cloud Task Execution--This task already has an open pull request: ${prUrl}--After completing the requested changes:-1. ${this.buildExistingPrCheckoutInstruction(prUrl)}-2. Stage your changes with \`git add\`, then call the \`git_signed_commit\` tool with a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). This commits to the existing PR branch.- - If the branch is behind its base, call the \`git_signed_merge\` tool first — it merges the base in server-side with a Verified merge commit. Only if it reports a conflict: fetch and rebase locally (\`git fetch origin <base>\`, \`git rebase origin/<base>\`, resolve, \`git rebase --continue\`), then call the \`git_signed_rewrite\` tool to force-update this same PR branch.-3. For every PR review comment or review thread you addressed, treat the thread as done only after BOTH of these:- - Reply on the thread with a short note describing what changed (reference the commit SHA when useful) using \`gh api -X POST /repos/{owner}/{repo}/pulls/{n}/comments/{id}/replies -f body='...'\`.- - Resolve the thread via the \`resolveReviewThread\` GraphQL mutation: \`gh api graphql -f query='mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{isResolved}}}' -f id="<thread-node-id>"\`.- List unresolved threads first with \`gh api graphql -f query='{repository(owner:"<owner>",name:"<repo>"){pullRequest(number:<n>){reviewThreads(first:100){nodes{id isResolved comments(first:1){nodes{body}}}}}}}'\` so you can resolve each one you fixed.--Important:-- Do NOT create a new branch or a new pull request unless the user explicitly asks.-- Do NOT push fixes for review comments without replying to and resolving each related thread.-${commonInstructions}-`;- }-- if (!this.config.repositoryPath && this.taskRepositories.length === 0) {- const repositoryInstructions = `-When the task requires a GitHub repository:-- If the repository is not specified, call \`list_repos\` and use the task context to choose it. If multiple repositories remain plausible, ask the user.-- Call \`clone_repo\` with the chosen \`owner/repo\` and optional branch. It creates a shallow clone under \`/tmp/workspace/repos/<owner>/<repo>\` and returns the path.-- Work from inside the returned path for all code changes.-- The clone starts with one commit. If older history is genuinely needed, fetch it in bounded steps with \`git fetch --deepen=50 origin <branch>\`, then \`git fetch --deepen=200 origin <branch>\`. Use \`git fetch --unshallow\` only when the task explicitly requires full history, such as a long-range blame or bisect.-`;- const publishInstructions =- this.config.createPr === false- ? `-When the user asks for code changes:-- You may make local edits in a repository cloned with \`clone_repo\`-- Do NOT create branches, commits, push changes, or open pull requests in this run`- : shouldAutoCreatePr- ? `-When the user asks for code changes in a GitHub repository:-- After completing code changes in a cloned repository, create a branch, stage your changes with \`git add\` and commit them with the \`git_signed_commit\` tool (do NOT use \`git commit\`/\`git push\` — they are blocked), and open a draft pull request from inside the clone without waiting to be asked. Before opening the PR, check the cloned repo for a PR template at \`.github/pull_request_template.md\` or in \`.github/PULL_REQUEST_TEMPLATE/*.md\` (or other variants; fall back to the org's \`.github\` repo via \`gh api\`). If multiple templates exist, use the one that best matches the change. Use it as the body structure, and search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links.-- Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.-${whyContextInstruction.trimStart()}-${publicRepoSafetyInstruction.trimStart()}-${prMentionSafetyInstruction.trimStart()}-- End the PR description with a horizontal rule followed by this footer line: ${prFooter}-- Always create the PR as a draft. Do not ask for confirmation before publishing completed code changes`- : `-When the user explicitly asks for code changes in a GitHub repository:-- If the user explicitly asks you to open or update a pull request, create a branch, stage your changes with \`git add\` and commit them with the \`git_signed_commit\` tool (do NOT use \`git commit\`/\`git push\` — they are blocked), and open a draft pull request from inside the clone. Before opening the PR, check the cloned repo for a PR template at \`.github/pull_request_template.md\` or in \`.github/PULL_REQUEST_TEMPLATE/*.md\` (or other variants; fall back to the org's \`.github\` repo via \`gh api\`). If multiple templates exist, use the one that best matches the change. Use it as the body structure, and search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links.-- Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.-${whyContextInstruction.trimStart()}-${publicRepoSafetyInstruction.trimStart()}-${prMentionSafetyInstruction.trimStart()}-- End the PR description with a horizontal rule followed by this footer line: ${prFooter}-- Do NOT create branches, commits, push changes, or open pull requests unless the user explicitly asks for that`;-- return `${identityInstructions}-# Cloud Task Execution — No Repository Mode--You are a helpful assistant with access to PostHog via MCP tools. You can help with both code tasks and data/analytics questions.--For a question about company-specific terms, internal policies, or team knowledge, search the project knowledge base before you answer, whatever else the question is about: call \`posthog:exec\` and run its inner \`posthog:business-knowledge-documents-search\` tool. These documents are not in the public docs or the context wiki, so check the knowledge base before you tell the user that you cannot find the answer. If that tool is not available in this project, move on instead of retrying it.--When the user asks about analytics, data, metrics, events, funnels, dashboards, feature flags, experiments, or anything PostHog-related:-- Use the canonical \`posthog:exec\` tool to query data, search insights, and provide real answers-- A count, sum, or amount of X per day/hour/week/month/year, a rate or percentage of X, an average or percentile of X, a cost per X, a conversion between two events, or a derived form of one of those is a governed metric question — whatever X is (sessions, 404s, feedback submissions, scout runs, tool calls, revenue). For those, inspect the complete governed catalog with \`posthog:metric-list\` first, inspect a candidate with \`posthog:metric-describe\`, then run an approved match with \`posthog:data-catalog-metric-run\`. Do this before \`posthog:read-data-schema\`, a typed domain tool, or a raw query-- Follow its built-in instructions to discover and invoke inner tools-- Do NOT tell the user to check an external analytics platform — you ARE the analytics platform-- Inner tools include \`posthog:read-data-schema\`, \`posthog:execute-sql\`, \`posthog:insight-query\`, and the typed query tools--When the user asks for code changes or software engineering tasks:-- Choose and clone a repository only when the task requires one. For questions and analysis, answer without cloning when possible.-${repositoryInstructions}${publishInstructions}--Important:-- Prefer using MCP tools to answer questions with real data over giving generic advice.-${commonInstructions}-`;- }-- if (!shouldAutoCreatePr) {- return `${identityInstructions}-# Cloud Task Execution--${repositoryWorkspaceInstructions}--Do the requested work, but stop with local changes ready for review.--Important:-- Do NOT create a branch, commit, push, or open a pull request unless the user explicitly asks.-- If the user explicitly asks you to open a pull request: pick a new branch name prefixed with \`posthog/\`, stage your changes with \`git add\`, and call the \`git_signed_commit\` tool with \`branch\` set to that name and a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). Before opening the PR, check the repo for a PR template at \`.github/pull_request_template.md\` or in \`.github/PULL_REQUEST_TEMPLATE/*.md\` (or other variants; fall back to the org's \`.github\` repo via \`gh api\`). If multiple templates exist, use the one that best matches the change. Use it as the body structure, and search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links. Keep the description brief overall — summarize only the most important changes.-${whyContextInstruction.trimStart()}-${publicRepoSafetyInstruction.trimStart()}-${prMentionSafetyInstruction.trimStart()}-- End the PR description with a horizontal rule followed by this footer line: ${prFooter}-- Always create the PR as a draft.-${commonInstructions}-`;- }-- return `${identityInstructions}-# Cloud Task Execution--${repositoryWorkspaceInstructions}--If the work you are being asked to do already has an open pull request — for example, the inbox report you fetched links an implementation PR (its \`implementation_pr_url\`), or this same thread already produced a PR that you are now being asked to revise — do NOT open a second PR. Check that PR out with \`gh pr checkout <url>\`, continue on its branch, and commit your changes to it with the \`git_signed_commit\` tool (if the branch is behind its base, call \`git_signed_merge\` first). A PR is only the one to continue if it is for this same request; if the thread merely mentions an unrelated or older PR, ignore it. Only open a new, separate PR when the change is genuinely distinct from the existing one.--Otherwise, after completing the requested changes:-1. Pick a new branch name prefixed with \`posthog/\` (e.g. \`posthog/fix-login-redirect\`)-2. Stage your changes with \`git add\`, then call the \`git_signed_commit\` tool with \`branch\` set to that name and a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). The tool creates the branch on the remote and a signed commit on it.-3. Before opening the PR, prepare the body:- - Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.-${whyContextInstruction}-${publicRepoSafetyInstruction}-${prMentionSafetyInstruction}- - Check the repo for a default PR template at \`.github/pull_request_template.md\` (also try \`.github/PULL_REQUEST_TEMPLATE.md\`, \`docs/pull_request_template.md\`, and root variants). Also check for named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`. If multiple templates exist, use the one that best matches the change. Use its exact section headings as the PR body — do NOT fall back to a generic Summary/Test plan format.- - If no repo-level template exists, check the org's \`.github\` repo via \`gh api\`. Look for both a default template and named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`, and use the best match as a fallback.- - Search for matching open issues with \`gh issue list --state open --search '<keywords>'\` (derive keywords from the branch name, commits, and changed files; \`gh issue view <n>\` to confirm relevance). For every issue this PR would resolve, include a \`Closes #<n>\` line in the body so GitHub auto-links and auto-closes it on merge. For issues that are related but not fully resolved, use \`Refs #<n>\` instead.-4. Create a draft pull request using \`gh pr create --draft${this.config.baseBranch ? ` --base ${this.config.baseBranch}` : ""}\` with a descriptive title and the body prepared above. Add the following footer at the end of the PR description:-\`\`\`-----${prFooter}-\`\`\`--Important:-- Always create the PR as a draft. Do not ask for confirmation.-${commonInstructions}-`;+ return this.getCloudTaskPrompt().buildCloudSystemPrompt(+ prUrl,+ slackThreadUrl,+ inboxReportUrl,+ );}private async getCurrentGitBranch(): Promise<string | null> {diff --git a/products/desktop/packages/agent/src/server/bin.ts b/products/desktop/packages/agent/src/server/bin.tsindex ea3a68b23fd3..79bd9d3dad24 100644--- a/products/desktop/packages/agent/src/server/bin.ts+++ b/products/desktop/packages/agent/src/server/bin.ts@@ -1,10 +1,10 @@#!/usr/bin/env nodeimport { fileURLToPath } from "node:url";+import { DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE } from "@posthog/harness/extensions/posthog-mcp-policy";import { EFFORT_LEVELS, SERVICE_TIERS } from "@posthog/shared/domain-types";import { Command } from "commander";import { z } from "zod/v4";import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";-import { DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE } from "../posthog-exec-permission";import { AgentServer } from "./agent-server";import { launcherToProcessMs } from "./boot-phases";import { CredentialRelayError } from "./credential-relay";diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex 94f170e3394c..0ecd47ec3ba8 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -4,6 +4,11 @@ import { basename, dirname, join } from "node:path";import type { RpcSessionState } from "@earendil-works/pi-coding-agent";import type { ServerType } from "@hono/node-server";import { serve } from "@hono/node-server";+import { resolveContextWikiPath } from "@posthog/harness/extensions/context-wiki";+import {+ buildStoreSkillsInstructions,+ syncStoreSkills,+} from "@posthog/harness/extensions/skills-store";import {type AgentConversationEvent,type AgentTurnUsage,@@ -17,11 +22,11 @@ import {type TaskRunArtifact,} from "@posthog/shared";import { buildPosthogPropertyHeaderRecord } from "@posthog/shared/posthog-property-headers";+import type { TaskContext } from "@posthog/shared/task-context";import { Hono } from "hono";import { z } from "zod/v4";import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";import { buildLocalToolsServer } from "../adapters/codex-app-server/local-tools-mcp";-import { resolveContextWikiPath } from "../context-wiki";import { OtelRunTelemetry } from "../otel-telemetry";import {createPiRpcClient,@@ -32,7 +37,6 @@ 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 {type PiExtensionEvent,piExtensionUIResponseSchema,@@ -47,7 +51,6 @@ import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";import { jsonRpcRequestSchema } from "./schemas";-import { buildStoreSkillsInstructions, syncStoreSkills } from "./store-skills";import type { AgentServerConfig } from "./types";const MODEL_CHANGING_RPC_COMMANDS: ReadonlySet<string> = new Set([diff --git a/products/desktop/packages/agent/src/server/rtk-savings.ts b/products/desktop/packages/agent/src/server/rtk-savings.tsindex 902c502d5a9e..0e35ff8ceff5 100644--- a/products/desktop/packages/agent/src/server/rtk-savings.ts+++ b/products/desktop/packages/agent/src/server/rtk-savings.ts@@ -1,7 +1,7 @@import { execFile } from "node:child_process";import { promisify } from "node:util";+import { resolveRtkPrefix } from "@posthog/harness/extensions/rtk";import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";-import { resolveRtkPrefix } from "../adapters/claude/session/rtk";const execFileAsync = promisify(execFile);diff --git a/products/desktop/packages/agent/src/server/schemas.ts b/products/desktop/packages/agent/src/server/schemas.tsindex 497b10ea08d4..eb24080eb519 100644--- a/products/desktop/packages/agent/src/server/schemas.ts+++ b/products/desktop/packages/agent/src/server/schemas.ts@@ -1,7 +1,7 @@import type { McpServerConnection } from "@posthog/shared";import { z } from "zod/v4";-export { posthogExecPermissionRegexSchema } from "../posthog-exec-permission";+export { posthogExecPermissionRegexSchema } from "@posthog/harness/extensions/posthog-mcp-policy";const httpHeaderSchema = z.object({name: z.string(),diff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.tsindex 17ef9949fc86..5b7b7e26ef86 100644--- a/products/desktop/packages/agent/src/types.ts+++ b/products/desktop/packages/agent/src/types.ts@@ -1,3 +1,4 @@+import type { ContextWikiEnv } from "@posthog/harness/extensions/context-wiki";import type { Adapter, ModelAccess, PostHogAPIConfig } from "@posthog/shared";import type { EffortLevel } from "@posthog/shared/domain-types";@@ -40,20 +41,6 @@ export interface StoredNotification {*/export type StoredEntry = StoredNotification;-/**- * Per-session context wiki mount, threaded explicitly (instead of via global- * `process.env` writes) so concurrent sessions never exchange wiki paths or- * publish tokens.- */-export interface ContextWikiEnv {- /** Local checkout of the org's wiki (POSTHOG_CONTEXT_LAYER_PATH). */- path: string;- /** API path agents land wiki commits through (POSTHOG_CONTEXT_LAYER_COMMITS_PATH). */- commitsPath: string;- /** Publish token (POSTHOG_PERSONAL_API_KEY); absent for impersonated sessions. */- personalApiKey?: string;-}-export interface ProcessSpawnedCallback {onProcessSpawned?: (info: {pid: number;diff --git a/products/desktop/packages/agent/src/utils/common.ts b/products/desktop/packages/agent/src/utils/common.tsindex 36646bc454e8..0ab9540e9acd 100644--- a/products/desktop/packages/agent/src/utils/common.ts+++ b/products/desktop/packages/agent/src/utils/common.ts@@ -67,19 +67,6 @@ export const IS_ROOT =export const ALLOW_BYPASS = !IS_ROOT || !!process.env.IS_SANDBOX;-/**- * A cloud sandbox run, as opposed to a local desktop session. `taskRunId` is- * used by both desktop and cloud for persistence, so it must not imply cloud.- */-export function isCloudRun(- meta: { environment?: "local" | "cloud" } | undefined,-): boolean {- if (meta?.environment) {- return meta.environment === "cloud";- }- return !!process.env.IS_SANDBOX;-}-export function unreachable(value: never, logger: Logger): void {let valueAsString: string;try {diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.tsindex 60eaeb759789..dfa34b379b65 100644--- a/products/desktop/packages/agent/tsup.config.ts+++ b/products/desktop/packages/agent/tsup.config.ts@@ -175,11 +175,9 @@ export default defineConfig(["src/agent.ts","src/gateway-models.ts","src/posthog-api.ts",- "src/posthog-products.ts","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/billing/leanSkills.ts b/products/desktop/packages/core/src/billing/leanSkills.tsindex 05656f245f84..e64e315ec31e 100644--- a/products/desktop/packages/core/src/billing/leanSkills.ts+++ b/products/desktop/packages/core/src/billing/leanSkills.ts@@ -12,7 +12,7 @@* system prompt (its authors measured the same text as a skill folder at* -0.5%), so no one-click install can deliver it. Cloud agent sessions inject* it instead when POSTHOG_BENJAMIN is set - see- * packages/agent/src/adapters/benjamin-guidance.ts.+ * packages/harness/src/extensions/benjamin/guidance.ts.*/export interface LeanSkill {diff --git a/products/desktop/packages/core/src/pi-runtime/piRunner.ts b/products/desktop/packages/core/src/pi-runtime/piRunner.tsindex cdf0e65086b7..d5861ed7fa4a 100644--- a/products/desktop/packages/core/src/pi-runtime/piRunner.ts+++ b/products/desktop/packages/core/src/pi-runtime/piRunner.ts@@ -1,5 +1,5 @@-import type { TaskContextInput } from "@posthog/agent/pi/task-system-prompt";import type { PiThinkingLevel } from "@posthog/agent/pi/types";+import type { TaskContextInput } from "@posthog/shared/task-context";export interface PiRunInput {taskContext: TaskContextInput;diff --git a/products/desktop/packages/enricher/src/enrich-source.ts b/products/desktop/packages/enricher/src/enrich-source.tsindex 00df3ffc2271..16cb6d894b43 100644--- a/products/desktop/packages/enricher/src/enrich-source.ts+++ b/products/desktop/packages/enricher/src/enrich-source.ts@@ -6,6 +6,7 @@ import type { LocalWrapper, ParseContext } from "./types.js";interface EnrichSourceApiConfig {apiKey: string;host: string;+ publicHost?: string;projectId: number;/** Timeout in ms for each PostHog API request (default: 5000). */timeoutMs?: number;@@ -152,6 +153,7 @@ export async function enrichSource({const enriched = await parsed.enrichFromApi({apiKey: apiConfig.apiKey,host: apiConfig.host,+ publicHost: apiConfig.publicHost,projectId: apiConfig.projectId,timeoutMs: apiConfig.timeoutMs ?? DEFAULT_TIMEOUT_MS,});diff --git a/products/desktop/packages/harness/README.md b/products/desktop/packages/harness/README.mdindex ec2252161fcf..57d4963a4e7f 100644--- a/products/desktop/packages/harness/README.md+++ b/products/desktop/packages/harness/README.md@@ -54,5 +54,14 @@ Set `POSTHOG_REGION` to `us`, `eu`, or `dev` when needed.| `@posthog/harness` | Runtime creation and RPC mode || `@posthog/harness/runtime` | Runtime creation only || `@posthog/harness/extensions` | Harness extension registry |+| `@posthog/harness/extensions/context-wiki` | Context-wiki prompt and environment helpers |+| `@posthog/harness/extensions/enrichment` | File enrichment behavior |+| `@posthog/harness/extensions/task-system-prompt` | Task prompt builders and Pi task-prompt extension |+| `@posthog/harness/extensions/posthog-mcp-policy` | PostHog MCP permission policy and product-id classification |+| `@posthog/harness/extensions/local-tools` | Injected local tools (signed git, artifacts, peer messaging) and their PostHog task/run API client |+| `@posthog/harness/extensions/rtk` | RTK command-compression: Pi's native rewrite, the pure matching rules Claude's hook uses, and the Codex guidance text |+| `@posthog/harness/extensions/benjamin` | Vendored Benjamin-Plus and Simplified Technical English (ASD-STE100) system-prompt instructions, gated by `POSTHOG_BENJAMIN` |+| `@posthog/harness/extensions/agent-instructions` | Base appended system-prompt content (branch naming, PR links, plan mode, shell efficiency, spoken narration, …) |+| `@posthog/harness/extensions/skills-store` | PostHog skills-store pointer-file rendering and install/remove across Claude Code, Codex, and Pi skill roots |Individual extensions are also exported under `@posthog/harness/extensions/*`.diff --git a/products/desktop/packages/harness/package.json b/products/desktop/packages/harness/package.jsonindex 3ff697aaee47..0c62b62e0558 100644--- a/products/desktop/packages/harness/package.json+++ b/products/desktop/packages/harness/package.json@@ -32,6 +32,18 @@"types": "./dist/extensions/auto-publish/index.d.ts","import": "./dist/extensions/auto-publish/index.js"},+ "./extensions/context-wiki": {+ "types": "./dist/extensions/context-wiki/index.d.ts",+ "import": "./dist/extensions/context-wiki/index.js"+ },+ "./extensions/enrichment": {+ "types": "./dist/extensions/enrichment/index.d.ts",+ "import": "./dist/extensions/enrichment/index.js"+ },+ "./extensions/task-system-prompt": {+ "types": "./dist/extensions/task-system-prompt/index.d.ts",+ "import": "./dist/extensions/task-system-prompt/index.js"+ },"./extensions/hog-branding": {"types": "./dist/extensions/hog-branding/index.d.ts","import": "./dist/extensions/hog-branding/index.js"@@ -40,6 +52,10 @@"types": "./dist/extensions/posthog-provider/index.d.ts","import": "./dist/extensions/posthog-provider/index.js"},+ "./extensions/posthog-mcp-policy": {+ "types": "./dist/extensions/posthog-mcp-policy/index.d.ts",+ "import": "./dist/extensions/posthog-mcp-policy/index.js"+ },"./extensions/posthog-provider/model-catalog": {"types": "./dist/extensions/posthog-provider/model-catalog.d.ts","import": "./dist/extensions/posthog-provider/model-catalog.js"@@ -79,6 +95,26 @@"./extensions/footer-focus-demo": {"types": "./dist/extensions/footer-focus-demo/index.d.ts","import": "./dist/extensions/footer-focus-demo/index.js"+ },+ "./extensions/local-tools": {+ "types": "./dist/extensions/local-tools/index.d.ts",+ "import": "./dist/extensions/local-tools/index.js"+ },+ "./extensions/rtk": {+ "types": "./dist/extensions/rtk/index.d.ts",+ "import": "./dist/extensions/rtk/index.js"+ },+ "./extensions/benjamin": {+ "types": "./dist/extensions/benjamin/index.d.ts",+ "import": "./dist/extensions/benjamin/index.js"+ },+ "./extensions/agent-instructions": {+ "types": "./dist/extensions/agent-instructions/index.d.ts",+ "import": "./dist/extensions/agent-instructions/index.js"+ },+ "./extensions/skills-store": {+ "types": "./dist/extensions/skills-store/index.d.ts",+ "import": "./dist/extensions/skills-store/index.js"}},"scripts": {@@ -94,6 +130,8 @@"@earendil-works/pi-coding-agent": "catalog:","@earendil-works/pi-tui": "catalog:","@modelcontextprotocol/sdk": "^1.29.0",+ "@posthog/enricher": "workspace:*",+ "@posthog/git": "workspace:*","@posthog/shared": "workspace:*","fflate": "^0.8.2","lru-cache": "^11.1.0",diff --git a/products/desktop/packages/harness/src/extensions/agent-instructions/index.ts b/products/desktop/packages/harness/src/extensions/agent-instructions/index.tsnew file mode 100644index 000000000000..7d101666fe44--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/agent-instructions/index.ts@@ -0,0 +1,4 @@+export {+ buildAppendedInstructions,+ imageToolsInstruction,+} from "./instructions";diff --git a/products/desktop/packages/agent/src/adapters/claude/session/instructions.test.ts b/products/desktop/packages/harness/src/extensions/agent-instructions/instructions.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/claude/session/instructions.test.tsrename to products/desktop/packages/harness/src/extensions/agent-instructions/instructions.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts b/products/desktop/packages/harness/src/extensions/agent-instructions/instructions.tssimilarity index 98%rename from products/desktop/packages/agent/src/adapters/claude/session/instructions.tsrename to products/desktop/packages/harness/src/extensions/agent-instructions/instructions.tsindex b702bbb3fab6..44ff8775f3bc 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts+++ b/products/desktop/packages/harness/src/extensions/agent-instructions/instructions.ts@@ -1,5 +1,5 @@-import { buildContextWikiInstructions } from "../../../context-wiki";-import { appendBenjaminGuidance } from "../../benjamin-guidance";+import { appendBenjaminGuidance } from "../benjamin";+import { buildContextWikiInstructions } from "../context-wiki";const BRANCH_NAMING = `# Branch Namingdiff --git a/products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.json b/products/desktop/packages/harness/src/extensions/benjamin/benjamin.lock.jsonsimilarity index 100%rename from products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.jsonrename to products/desktop/packages/harness/src/extensions/benjamin/benjamin.lock.jsondiff --git a/products/desktop/packages/agent/src/adapters/benjamin-guidance.test.ts b/products/desktop/packages/harness/src/extensions/benjamin/guidance.test.tssimilarity index 87%rename from products/desktop/packages/agent/src/adapters/benjamin-guidance.test.tsrename to products/desktop/packages/harness/src/extensions/benjamin/guidance.test.tsindex 9d7ef48d86bd..bad92e9cc564 100644--- a/products/desktop/packages/agent/src/adapters/benjamin-guidance.test.ts+++ b/products/desktop/packages/harness/src/extensions/benjamin/guidance.test.ts@@ -1,21 +1,15 @@import { createHash } from "node:crypto";import { readFileSync } from "node:fs";import { afterEach, describe, expect, test, vi } from "vitest";-import { assertMitLicense } from "../../../../scripts/sync-benjamin.mts";-import {- BENJAMIN_INSTRUCTION,- BENJAMIN_UPSTREAM_COMMIT,-} from "./benjamin/instruction";-import { appendBenjaminGuidance, isBenjaminEnabled } from "./benjamin-guidance";-import { buildAppendedInstructions } from "./claude/session/instructions";+import { buildAppendedInstructions } from "../agent-instructions/instructions";+import { appendBenjaminGuidance, isBenjaminEnabled } from "./guidance";+import { BENJAMIN_INSTRUCTION, BENJAMIN_UPSTREAM_COMMIT } from "./instruction";+import { assertMitLicense } from "./license-guard";const MARKER = "BENJAMIN-PLUS MODE ACTIVE";const lock = JSON.parse(- readFileSync(- new URL("./benjamin/benjamin.lock.json", import.meta.url),- "utf8",- ),+ readFileSync(new URL("./benjamin.lock.json", import.meta.url), "utf8"),) as { commit: string; sha256: string };describe("benjamin guidance", () => {diff --git a/products/desktop/packages/agent/src/adapters/benjamin-guidance.ts b/products/desktop/packages/harness/src/extensions/benjamin/guidance.tssimilarity index 88%rename from products/desktop/packages/agent/src/adapters/benjamin-guidance.tsrename to products/desktop/packages/harness/src/extensions/benjamin/guidance.tsindex f2315400e96c..37868d4c2905 100644--- a/products/desktop/packages/agent/src/adapters/benjamin-guidance.ts+++ b/products/desktop/packages/harness/src/extensions/benjamin/guidance.ts@@ -1,4 +1,4 @@-import { BENJAMIN_INSTRUCTION } from "./benjamin/instruction";+import { BENJAMIN_INSTRUCTION } from "./instruction";const BENJAMIN_GUIDANCE = BENJAMIN_INSTRUCTION.trim();diff --git a/products/desktop/packages/harness/src/extensions/benjamin/index.ts b/products/desktop/packages/harness/src/extensions/benjamin/index.tsnew file mode 100644index 000000000000..02dc92d24cb1--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/benjamin/index.ts@@ -0,0 +1,7 @@+export { appendBenjaminGuidance, isBenjaminEnabled } from "./guidance";+export { BENJAMIN_INSTRUCTION, BENJAMIN_UPSTREAM_COMMIT } from "./instruction";+export { assertMitLicense } from "./license-guard";+export {+ appendSte100Guidance,+ SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION,+} from "./ste100";diff --git a/products/desktop/packages/agent/src/adapters/benjamin/instruction.ts b/products/desktop/packages/harness/src/extensions/benjamin/instruction.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/benjamin/instruction.tsrename to products/desktop/packages/harness/src/extensions/benjamin/instruction.tsdiff --git a/products/desktop/packages/harness/src/extensions/benjamin/license-guard.ts b/products/desktop/packages/harness/src/extensions/benjamin/license-guard.tsnew file mode 100644index 000000000000..2773886855e2--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/benjamin/license-guard.ts@@ -0,0 +1,19 @@+export function assertMitLicense(license: string): void {+ const required = [+ "MIT License",+ "Permission is hereby granted, free of charge",+ 'THE SOFTWARE IS PROVIDED "AS IS"',+ ];+ for (const marker of required) {+ if (!license.includes(marker)) {+ throw new Error(+ `Upstream LICENSE no longer looks like the expected MIT license (missing "${marker}") - review it before syncing`,+ );+ }+ }+ if (license.includes("*/")) {+ throw new Error(+ 'Upstream LICENSE contains a block-comment terminator ("*/"), which would escape the generated banner and execute as code - review it before syncing',+ );+ }+}diff --git a/products/desktop/packages/agent/src/adapters/ste100-guidance.ts b/products/desktop/packages/harness/src/extensions/benjamin/ste100.tssimilarity index 91%rename from products/desktop/packages/agent/src/adapters/ste100-guidance.tsrename to products/desktop/packages/harness/src/extensions/benjamin/ste100.tsindex a7297c2adf7f..c1d4a8a03bd8 100644--- a/products/desktop/packages/agent/src/adapters/ste100-guidance.ts+++ b/products/desktop/packages/harness/src/extensions/benjamin/ste100.ts@@ -1,5 +1,5 @@import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION } from "@posthog/shared/product-engineer-prompt";-import { isBenjaminEnabled } from "./benjamin-guidance";+import { isBenjaminEnabled } from "./guidance";export { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION };diff --git a/products/desktop/packages/agent/src/context-wiki.ts b/products/desktop/packages/harness/src/extensions/context-wiki/context-wiki.tssimilarity index 97%rename from products/desktop/packages/agent/src/context-wiki.tsrename to products/desktop/packages/harness/src/extensions/context-wiki/context-wiki.tsindex 01dbd3cb5ad7..302441583309 100644--- a/products/desktop/packages/agent/src/context-wiki.ts+++ b/products/desktop/packages/harness/src/extensions/context-wiki/context-wiki.ts@@ -1,5 +1,9 @@import * as fs from "node:fs";-import type { ContextWikiEnv } from "./types";+export interface ContextWikiEnv {+ path: string;+ commitsPath: string;+ personalApiKey?: string;+}/*** The org's context wiki, shared by every harness adapter (Claude, Codex, Pi).diff --git a/products/desktop/packages/agent/src/pi/context-wiki-extension.test.ts b/products/desktop/packages/harness/src/extensions/context-wiki/extension.test.tssimilarity index 96%rename from products/desktop/packages/agent/src/pi/context-wiki-extension.test.tsrename to products/desktop/packages/harness/src/extensions/context-wiki/extension.test.tsindex de1ab7219871..f7c20c1d9002 100644--- a/products/desktop/packages/agent/src/pi/context-wiki-extension.test.ts+++ b/products/desktop/packages/harness/src/extensions/context-wiki/extension.test.ts@@ -3,7 +3,7 @@ import * as os from "node:os";import * as path from "node:path";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import { describe, expect, it } from "vitest";-import { createPiContextWikiExtension } from "./context-wiki-extension";+import { createPiContextWikiExtension } from "./extension";type BeforeAgentStartHandler = (event: {systemPrompt: string;diff --git a/products/desktop/packages/agent/src/pi/context-wiki-extension.ts b/products/desktop/packages/harness/src/extensions/context-wiki/extension.tssimilarity index 93%rename from products/desktop/packages/agent/src/pi/context-wiki-extension.tsrename to products/desktop/packages/harness/src/extensions/context-wiki/extension.tsindex 7578469af3da..a35385c8f20f 100644--- a/products/desktop/packages/agent/src/pi/context-wiki-extension.ts+++ b/products/desktop/packages/harness/src/extensions/context-wiki/extension.ts@@ -3,7 +3,7 @@ import type {ExtensionFactory,InlineExtension,} from "@earendil-works/pi-coding-agent";-import { buildContextWikiInstructions } from "../context-wiki";+import { buildContextWikiInstructions } from "./context-wiki";type NamedInlineExtension = Exclude<InlineExtension, ExtensionFactory>;diff --git a/products/desktop/packages/harness/src/extensions/context-wiki/index.ts b/products/desktop/packages/harness/src/extensions/context-wiki/index.tsnew file mode 100644index 000000000000..4163fa2145a4--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/context-wiki/index.ts@@ -0,0 +1,7 @@+export {+ applyContextWikiEnv,+ buildContextWikiInstructions,+ type ContextWikiEnv,+ resolveContextWikiPath,+} from "./context-wiki";+export { createPiContextWikiExtension } from "./extension";diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts b/products/desktop/packages/harness/src/extensions/enrichment/extension.test.tssimilarity index 97%rename from products/desktop/packages/agent/src/pi/enrichment-extension.test.tsrename to products/desktop/packages/harness/src/extensions/enrichment/extension.test.tsindex 2c9b999ede35..20366fde2894 100644--- a/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts+++ b/products/desktop/packages/harness/src/extensions/enrichment/extension.test.ts@@ -5,7 +5,7 @@ import type {} from "@earendil-works/pi-coding-agent";import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";import { afterEach, describe, expect, it, vi } from "vitest";-import { createPiEnrichmentExtension } from "./enrichment-extension";+import { createPiEnrichmentExtension } from "./extension";type ToolResultPatch = { content?: ToolResultEvent["content"] };type BeforeAgentStartHandler = (event: { systemPrompt: string }) => {diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.ts b/products/desktop/packages/harness/src/extensions/enrichment/extension.tssimilarity index 95%rename from products/desktop/packages/agent/src/pi/enrichment-extension.tsrename to products/desktop/packages/harness/src/extensions/enrichment/extension.tsindex c7c86588e6db..1088208522ae 100644--- a/products/desktop/packages/agent/src/pi/enrichment-extension.ts+++ b/products/desktop/packages/harness/src/extensions/enrichment/extension.ts@@ -5,10 +5,7 @@ import {isReadToolResult,} from "@earendil-works/pi-coding-agent";import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";-import {- createEnrichment,- enrichFileForAgent,-} from "../enrichment/file-enricher";+import { createEnrichment, enrichFileForAgent } from "./file-enricher";export interface PiEnrichmentConfig {apiUrl: string;diff --git a/products/desktop/packages/agent/src/enrichment/file-enricher.test.ts b/products/desktop/packages/harness/src/extensions/enrichment/file-enricher.test.tssimilarity index 96%rename from products/desktop/packages/agent/src/enrichment/file-enricher.test.tsrename to products/desktop/packages/harness/src/extensions/enrichment/file-enricher.test.tsindex dbb480af91be..d359502ab9de 100644--- a/products/desktop/packages/agent/src/enrichment/file-enricher.test.ts+++ b/products/desktop/packages/harness/src/extensions/enrichment/file-enricher.test.ts@@ -8,6 +8,7 @@ function makeDeps(overrides: {parseRejects?: Error;isSupported?: boolean;getApiKey?: () => string | Promise<string>;+ findWrappersInSource?: () => Promise<unknown[]>;findImportsInSource?: () => Promise<unknown[]>;getWrappersForFile?: () => Promise<unknown[]>;}): {@@ -36,6 +37,9 @@ function makeDeps(overrides: {});const getApiKeySpy = vi.fn(overrides.getApiKey ?? (() => "phx_test"));+ const findWrappersSpy = vi.fn(+ overrides.findWrappersInSource ?? (async () => []),+ );const findImportsSpy = vi.fn(overrides.findImportsInSource ?? (async () => []),);@@ -47,11 +51,13 @@ function makeDeps(overrides: {enricher: {isSupported: vi.fn(() => overrides.isSupported ?? true),parse: parseSpy,+ findWrappersInSource: findWrappersSpy,findImportsInSource: findImportsSpy,getWrappersForFile: getWrappersSpy,} as unknown as FileEnrichmentDeps["enricher"],apiConfig: {apiUrl: "https://test.posthog.com",+ publicApiUrl: "https://public.posthog.com",projectId: 1,getApiKey: getApiKeySpy,},@@ -264,20 +270,14 @@ describe("enrichFileForAgent", () => {expect(result).toBeNull();});- test("returns null and logs debug when enricher throws", async () => {- const logger = { debug: vi.fn() };+ test("returns null when enricher throws", async () => {const { deps } = makeDeps({ parseRejects: new Error("boom") });- deps.logger = logger as unknown as FileEnrichmentDeps["logger"];const result = await enrichFileForAgent(deps,"/tmp/code.ts","posthog.capture('x');",);expect(result).toBeNull();- expect(logger.debug).toHaveBeenCalledWith(- "File enrichment failed",- expect.objectContaining({ filePath: "/tmp/code.ts" }),- );});test("returns enriched string when happy path completes", async () => {@@ -298,6 +298,7 @@ describe("enrichFileForAgent", () => {expect.objectContaining({apiKey: "phx_test",host: "https://test.posthog.com",+ publicHost: "https://public.posthog.com",projectId: 1,}),);diff --git a/products/desktop/packages/harness/src/extensions/enrichment/file-enricher.ts b/products/desktop/packages/harness/src/extensions/enrichment/file-enricher.tsnew file mode 100644index 000000000000..81ee1e78d3ad--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/enrichment/file-enricher.ts@@ -0,0 +1,57 @@+import * as path from "node:path";+import { enrichSource, PostHogEnricher } from "@posthog/enricher";+import type { PostHogAPIConfig } from "@posthog/shared";++export interface FileEnrichmentDeps {+ enricher: PostHogEnricher;+ apiConfig: PostHogAPIConfig;+}++export interface Enrichment {+ deps: FileEnrichmentDeps;+ dispose(): void;+}++export function createEnrichment(+ apiConfig: PostHogAPIConfig | undefined,+): Enrichment | undefined {+ if (!apiConfig) return undefined;+ const enricher = new PostHogEnricher();+ return {+ deps: { enricher, apiConfig },+ dispose: () => enricher.dispose(),+ };+}++export async function enrichFileForAgent(+ deps: FileEnrichmentDeps,+ filePath: string,+ content: string,+): Promise<string | null> {+ try {+ const apiKey = await deps.apiConfig.getApiKey();+ if (!apiKey) return null;++ const enriched = await enrichSource({+ enricher: deps.enricher,+ apiConfig: {+ apiKey,+ host: deps.apiConfig.apiUrl,+ publicHost: deps.apiConfig.publicApiUrl,+ projectId: deps.apiConfig.projectId,+ },+ filePath,+ absolutePath: path.resolve(filePath),+ content,+ });+ if (!enriched) return null;++ const annotated = enriched.toInlineComments({+ includeEventDescriptions: false,+ includeExperimentNames: false,+ });+ return annotated === content ? null : annotated;+ } catch {+ return null;+ }+}diff --git a/products/desktop/packages/harness/src/extensions/enrichment/index.ts b/products/desktop/packages/harness/src/extensions/enrichment/index.tsnew file mode 100644index 000000000000..f89754561068--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/enrichment/index.ts@@ -0,0 +1,10 @@+export {+ createPiEnrichmentExtension,+ type PiEnrichmentConfig,+} from "./extension";+export {+ createEnrichment,+ type Enrichment,+ enrichFileForAgent,+ type FileEnrichmentDeps,+} from "./file-enricher";diff --git a/products/desktop/packages/harness/src/extensions/local-tools/cloud-run.ts b/products/desktop/packages/harness/src/extensions/local-tools/cloud-run.tsnew file mode 100644index 000000000000..97800a5809f0--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/local-tools/cloud-run.ts@@ -0,0 +1,8 @@+export function isCloudRun(+ meta: { environment?: "local" | "cloud" } | undefined,+): boolean {+ if (meta?.environment) {+ return meta.environment === "cloud";+ }+ return !!process.env.IS_SANDBOX;+}diff --git a/products/desktop/packages/agent/src/utils/github-token.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/github-token.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/utils/github-token.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/github-token.test.tsdiff --git a/products/desktop/packages/agent/src/utils/github-token.ts b/products/desktop/packages/harness/src/extensions/local-tools/github-token.tssimilarity index 100%rename from products/desktop/packages/agent/src/utils/github-token.tsrename to products/desktop/packages/harness/src/extensions/local-tools/github-token.tsdiff --git a/products/desktop/packages/harness/src/extensions/local-tools/index.ts b/products/desktop/packages/harness/src/extensions/local-tools/index.tsnew file mode 100644index 000000000000..2832c251f377--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/local-tools/index.ts@@ -0,0 +1,49 @@+export { isCloudRun } from "./cloud-run";+export {+ readGithubTokenFromSandboxEnvFile,+ resolveGithubToken,+} from "./github-token";+export {+ enabledLocalTools,+ LOCAL_TOOLS,+} from "./local-tools";+export {+ defineLocalTool,+ LOCAL_TOOLS_MCP_NAME,+ type LocalTool,+ type LocalToolCtx,+ type LocalToolDef,+ type LocalToolGateMeta,+ type LocalToolResult,+ qualifiedLocalToolName,+} from "./registry";+export {+ createSandboxPosthogClient,+ parseSandboxEnv,+ reportCommitArtefacts,+ reportSignedCommitActivity,+ reportTaskRunBranch,+ reportTaskRunCommits,+ resolveSandboxPosthogApi,+ withReportDeadline,+} from "./signed-commit-artefacts";+export {+ SIGNED_COMMIT_QUALIFIED_TOOL_NAME,+ SIGNED_COMMIT_TOOL_NAME,+ SIGNED_MERGE_QUALIFIED_TOOL_NAME,+ SIGNED_MERGE_TOOL_NAME,+ SIGNED_REWRITE_QUALIFIED_TOOL_NAME,+ SIGNED_REWRITE_TOOL_NAME,+ type SignedCommitToolCtx,+ type SignedCommitToolResult,+} from "./signed-commit-shared";+export {+ type PeerMessageSendResult,+ type TaskRunPeer,+ TaskToolsApiClient,+ TaskToolsApiError,+} from "./task-tools-client";+export { FINISH_TOOL_NAME } from "./tools/finish";+export { GH_STACK_QUALIFIED_TOOL_NAME } from "./tools/gh-stack";+export { SHOW_ACTIONS_TOOL_NAME } from "./tools/show-actions";+export { SPEAK_TOOL_NAME } from "./tools/speak";diff --git a/products/desktop/packages/agent/src/adapters/local-tools/index.ts b/products/desktop/packages/harness/src/extensions/local-tools/local-tools.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/index.tsrename to products/desktop/packages/harness/src/extensions/local-tools/local-tools.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/registry.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/registry.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/registry.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/registry.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/registry.ts b/products/desktop/packages/harness/src/extensions/local-tools/registry.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/registry.tsrename to products/desktop/packages/harness/src/extensions/local-tools/registry.tsdiff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/signed-commit-artefacts.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/signed-commit-artefacts.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/signed-commit-artefacts.test.tsdiff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.ts b/products/desktop/packages/harness/src/extensions/local-tools/signed-commit-artefacts.tssimilarity index 98%rename from products/desktop/packages/agent/src/signed-commit-artefacts.tsrename to products/desktop/packages/harness/src/extensions/local-tools/signed-commit-artefacts.tsindex 89886e97aa0a..574221e70af4 100644--- a/products/desktop/packages/agent/src/signed-commit-artefacts.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/signed-commit-artefacts.ts@@ -1,6 +1,6 @@import { readFileSync } from "node:fs";import type { SignedCommitResult } from "@posthog/git/signed-commit";-import { PostHogAPIClient } from "./posthog-api";+import { TaskToolsApiClient } from "./task-tools-client";const SANDBOX_ENV_FILE = "/tmp/agent-env";const SANDBOX_OAUTH_ENV_FILE = "/tmp/agent-oauth-env";@@ -76,12 +76,12 @@ export function createSandboxPosthogClient(env?: Record<string, string | undefined>,envFilePath?: string,oauthEnvFilePath?: string,-): PostHogAPIClient | undefined {+): TaskToolsApiClient | undefined {const api = resolveSandboxPosthogApi(env, envFilePath, oauthEnvFilePath);if (!api) {return undefined;}- return new PostHogAPIClient({+ return new TaskToolsApiClient({apiUrl: api.apiUrl,projectId: api.projectId,getApiKey: () =>diff --git a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts b/products/desktop/packages/harness/src/extensions/local-tools/signed-commit-shared.tssimilarity index 98%rename from products/desktop/packages/agent/src/adapters/signed-commit-shared.tsrename to products/desktop/packages/harness/src/extensions/local-tools/signed-commit-shared.tsindex 8ae30fcde5c5..81159073cc35 100644--- a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/signed-commit-shared.ts@@ -9,8 +9,8 @@ import {type SignedRewriteInput,} from "@posthog/git/signed-commit";import { z } from "zod";-import { reportSignedCommitActivity } from "../signed-commit-artefacts";-import { qualifiedLocalToolName } from "./local-tools/registry";+import { qualifiedLocalToolName } from "./registry";+import { reportSignedCommitActivity } from "./signed-commit-artefacts";/*** Shared definitions for the `git_signed_commit` tool, used by the local-toolsdiff --git a/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.test.tsnew file mode 100644index 000000000000..c08e0f546c0b--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.test.ts@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { TaskToolsApiClient } from "./task-tools-client";++const mockFetch = vi.fn();++vi.stubGlobal("fetch", mockFetch);++describe("TaskToolsApiClient", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns only the artifacts created by the current upload request", async () => {+ const client = new TaskToolsApiClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 1,+ });++ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: vi.fn().mockResolvedValue({+ artifacts: [+ { storage_path: "gs://bucket/existing.tar.gz", name: "existing" },+ { storage_path: "gs://bucket/new-1.pack", name: "new-1" },+ { storage_path: "gs://bucket/new-2.index", name: "new-2" },+ ],+ }),+ });++ const artifacts = await client.uploadTaskArtifacts("task-1", "run-1", [+ { name: "new-1", type: "artifact", content: "AAA" },+ { name: "new-2", type: "artifact", content: "BBB" },+ ]);++ expect(artifacts).toEqual([+ { storage_path: "gs://bucket/new-1.pack", name: "new-1" },+ { storage_path: "gs://bucket/new-2.index", name: "new-2" },+ ]);+ });+});diff --git a/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.ts b/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.tsnew file mode 100644index 000000000000..1a98d81d551d--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/local-tools/task-tools-client.ts@@ -0,0 +1,247 @@+import {+ API_TRANSFER_TIMEOUT_MS,+ type ArtifactSource,+ type ArtifactType,+ type PostHogAPIConfig,+ PostHogHttpClient,+ type TaskRun,+ type TaskRunArtifact,+ type TaskRunUpdate,+ transferTimeoutMs,+} from "@posthog/shared";++export { API_TRANSFER_TIMEOUT_MS, transferTimeoutMs, type TaskRunUpdate };++export class TaskToolsApiError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "TaskToolsApiError";+ }+}++export interface TaskArtifactUploadPayload {+ name: string;+ type: ArtifactType;+ source?: ArtifactSource;+ content: string;+ content_encoding?: "utf-8" | "base64";+ content_type?: string;+}++export interface TaskArtifactPrepareUploadPayload {+ name: string;+ type: ArtifactType;+ source?: ArtifactSource;+ size: number;+ content_type?: string;+}++export interface PreparedTaskArtifactUpload {+ id: string;+ name: string;+ type: ArtifactType;+ source?: ArtifactSource;+ size: number;+ content_type?: string;+ storage_path: string;+ expires_in: number;+ presigned_post: { url: string; fields: Record<string, string> };+}++export interface TaskArtifactFinalizeUploadPayload {+ id: string;+ name: string;+ type: ArtifactType;+ source?: ArtifactSource;+ storage_path: string;+ content_type?: string;+}++export interface TaskRunPeer {+ run_id: string;+ task_id: string;+ task_title: string;+ created_by_email: string | null;+ runtime: string;+ model: string | null;+ repository: string | null;+ stage: string | null;+ status: string;+ sendable: boolean;+ updated_at: string | null;+}++export interface PeerMessageSendResult {+ result: string;+ detail: string;+ message_id?: string | null;+}++export class TaskToolsApiClient {+ private readonly http: PostHogHttpClient;++ constructor(config: PostHogAPIConfig) {+ this.http = new PostHogHttpClient(config, {+ defaultUserAgent: "posthog/harness.local-tools",+ buildError: (message, status) => new TaskToolsApiError(message, status),+ });+ }++ async updateTaskRun(+ taskId: string,+ runId: string,+ payload: TaskRunUpdate,+ signal?: AbortSignal,+ ): Promise<TaskRun> {+ return this.http.updateTaskRun(taskId, runId, payload, signal);+ }++ async reportAnalysisActivity(+ taskId: string,+ runId: string,+ activity: Record<string, unknown>,+ signal?: AbortSignal,+ ): Promise<{ activity_index: number }> {+ const teamId = this.http.getTeamId();+ return this.http.request<{ activity_index: number }>(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/analysis-activity/`,+ { method: "POST", body: JSON.stringify(activity), signal },+ );+ }++ async uploadTaskArtifacts(+ taskId: string,+ runId: string,+ artifacts: TaskArtifactUploadPayload[],+ ): Promise<TaskRunArtifact[]> {+ if (!artifacts.length) {+ return [];+ }+ const teamId = this.http.getTeamId();+ const body = JSON.stringify({ artifacts });+ const response = await this.http.request<{+ artifacts: TaskRunArtifact[];+ }>(`/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/`, {+ method: "POST",+ body,+ signal: AbortSignal.timeout(transferTimeoutMs(body.length)),+ });+ const manifest = response.artifacts ?? [];+ return manifest.slice(-artifacts.length);+ }++ async prepareTaskArtifactUploads(+ taskId: string,+ runId: string,+ artifacts: TaskArtifactPrepareUploadPayload[],+ ): Promise<PreparedTaskArtifactUpload[]> {+ if (!artifacts.length) {+ return [];+ }+ const teamId = this.http.getTeamId();+ const response = await this.http.request<{+ artifacts: PreparedTaskArtifactUpload[];+ }>(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/prepare_upload/`,+ {+ method: "POST",+ body: JSON.stringify({ artifacts }),+ signal: AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),+ },+ );+ return response.artifacts ?? [];+ }++ async finalizeTaskArtifactUploads(+ taskId: string,+ runId: string,+ artifacts: TaskArtifactFinalizeUploadPayload[],+ ): Promise<TaskRunArtifact[]> {+ if (!artifacts.length) {+ return [];+ }+ const teamId = this.http.getTeamId();+ const response = await this.http.request<{+ artifacts: TaskRunArtifact[];+ }>(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/finalize_upload/`,+ {+ method: "POST",+ body: JSON.stringify({ artifacts }),+ signal: AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),+ },+ );+ const manifest = response.artifacts ?? [];+ const byStoragePath = new Map(+ manifest.map((artifact) => [artifact.storage_path, artifact]),+ );+ return artifacts+ .map((artifact) => byStoragePath.get(artifact.storage_path))+ .filter((artifact): artifact is TaskRunArtifact => !!artifact);+ }++ async listTaskRunPeers(+ taskId: string,+ runId: string,+ ): Promise<TaskRunPeer[]> {+ const teamId = this.http.getTeamId();+ const response = await this.http.request<{ peers: TaskRunPeer[] }>(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/peers/`,+ );+ return response.peers ?? [];+ }++ async sendTaskRunPeerMessage(+ taskId: string,+ runId: string,+ targetRunId: string,+ payload: { content: string; artifactIds?: string[] },+ ): Promise<PeerMessageSendResult> {+ const teamId = this.http.getTeamId();+ return this.http.request<PeerMessageSendResult>(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/peers/${encodeURIComponent(targetRunId)}/message/`,+ {+ method: "POST",+ body: JSON.stringify({+ content: payload.content,+ artifact_ids: payload.artifactIds ?? [],+ }),+ },+ );+ }++ async getSignalReportIdsForTask(+ taskId: string,+ signal?: AbortSignal,+ ): Promise<string[]> {+ const teamId = this.http.getTeamId();+ const response = await this.http.request<{+ results?: { id: string }[];+ }>(+ `/api/projects/${teamId}/signals/reports/?task_id=${encodeURIComponent(taskId)}&limit=100`,+ { signal },+ );+ return (response.results ?? []).map((r) => r.id);+ }++ async createSignalReportArtefact(+ reportId: string,+ taskId: string,+ body: { artefact_type: string; content: Record<string, unknown> },+ signal?: AbortSignal,+ ): Promise<void> {+ const teamId = this.http.getTeamId();+ await this.http.request(+ `/api/projects/${teamId}/signals/reports/${reportId}/artefacts/`,+ {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "X-PostHog-Task-Id": taskId },+ signal,+ },+ );+ }+}diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/artifact-upload.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/artifact-upload.tssimilarity index 95%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/artifact-upload.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/artifact-upload.tsindex 3f239615807a..af1376625700 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/artifact-upload.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/artifact-upload.ts@@ -1,9 +1,12 @@-import { type PostHogAPIClient, transferTimeoutMs } from "../../../posthog-api";import type {ArtifactSource,ArtifactType,TaskRunArtifact,-} from "../../../types";+} from "@posthog/shared";+import {+ type TaskToolsApiClient,+ transferTimeoutMs,+} from "../task-tools-client";export const MAX_ARTIFACT_UPLOAD_BYTES = 30 * 1024 * 1024;// The inline fallback base64-encodes the file into a JSON body, so it is held to a lower@@ -30,7 +33,7 @@ export interface ArtifactUpload {* finalized manifest entry.*/export async function uploadRunArtifact(- client: PostHogAPIClient,+ client: TaskToolsApiClient,taskId: string,taskRunId: string,upload: ArtifactUpload,@@ -47,7 +50,7 @@ export async function uploadRunArtifact(/** Reserve a storage key, POST the bytes straight to object storage, then attach them. */async function uploadDirect(- client: PostHogAPIClient,+ client: TaskToolsApiClient,taskId: string,taskRunId: string,{ name, contentType, content, type, source }: ArtifactUpload,@@ -116,7 +119,7 @@ async function uploadDirect(/** Send the bytes through the PostHog API and let the backend write them to storage. */async function uploadInline(- client: PostHogAPIClient,+ client: TaskToolsApiClient,taskId: string,taskRunId: string,{ name, contentType, content, type, source }: ArtifactUpload,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.test.tsindex 17b046a87923..56a80c61dfd5 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.test.ts@@ -6,7 +6,7 @@ import { pathToFileURL } from "node:url";import { execGit } from "@posthog/git/git-exec";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-vi.mock("../../../utils/github-token", () => ({+vi.mock("../github-token", () => ({resolveGithubToken: vi.fn(() => undefined),}));diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.tsindex d2bab3817e47..af5d5a459e17 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/clone-repo.ts@@ -8,7 +8,7 @@ import {} from "@posthog/git/git-exec";import { parseGithubUrl } from "@posthog/git/utils";import { z } from "zod";-import { resolveGithubToken } from "../../../utils/github-token";+import { resolveGithubToken } from "../github-token";import { defineLocalTool, type LocalToolResult } from "../registry";const GIT_TIMEOUT_MS = 10 * 60 * 1000;diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/finish.test.tssimilarity index 96%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/finish.test.tsindex 3d4636178514..8361fe80afc5 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/finish.test.ts@@ -2,10 +2,8 @@ import { describe, expect, it, vi } from "vitest";const updateTaskRun = vi.fn();-vi.mock("../../../signed-commit-artefacts", async (importOriginal) => ({- ...(await importOriginal<- typeof import("../../../signed-commit-artefacts")- >()),+vi.mock("../signed-commit-artefacts", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../signed-commit-artefacts")>()),createSandboxPosthogClient: () => ({ updateTaskRun }),}));diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/finish.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/finish.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/finish.tsindex b695e760607e..d0cffb6f41af 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/finish.ts@@ -1,13 +1,13 @@import { z } from "zod";-import {- createSandboxPosthogClient,- withReportDeadline,-} from "../../../signed-commit-artefacts";import {defineLocalTool,type LocalToolCtx,type LocalToolResult,} from "../registry";+import {+ createSandboxPosthogClient,+ withReportDeadline,+} from "../signed-commit-artefacts";export const FINISH_TOOL_NAME = "finish";diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/gh-stack.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/gh-stack.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/gh-stack.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/gh-stack.tsindex c78dab2f98ab..9b1f5ec2075e 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/gh-stack.ts@@ -13,11 +13,11 @@ import {validateStackChain,} from "@posthog/git/stacks";import { z } from "zod";+import { qualifiedLocalToolName } from "../registry";import type {SignedCommitToolCtx,SignedCommitToolResult,-} from "../../signed-commit-shared";-import { qualifiedLocalToolName } from "../registry";+} from "../signed-commit-shared";import { defineSignedGitTool } from "./signed-git-tool";const GH_STACK_TOOL_NAME = "gh_stack";diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.test.tssimilarity index 98%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.test.tsindex b42f70bb6560..c2e710ce5534 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const listTaskRunPeers = vi.fn();-vi.mock("../../../signed-commit-artefacts", () => ({+vi.mock("../signed-commit-artefacts", () => ({createSandboxPosthogClient: () => ({ listTaskRunPeers }),}));diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.tssimilarity index 96%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.tsindex f0b82513494b..f67d6f72db42 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-agents.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-agents.ts@@ -1,6 +1,6 @@-import type { TaskRunPeer } from "../../../posthog-api";-import { createSandboxPosthogClient } from "../../../signed-commit-artefacts";import { defineLocalTool, type LocalToolResult } from "../registry";+import { createSandboxPosthogClient } from "../signed-commit-artefacts";+import type { TaskRunPeer } from "../task-tools-client";export const listAgentsTool = defineLocalTool({name: "list_agents",diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-repos.tssimilarity index 98%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/list-repos.tsindex 4383a07298d2..35a9f2017fb9 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/list-repos.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/list-repos.ts@@ -1,6 +1,6 @@import { execGh } from "@posthog/git/gh";import { z } from "zod";-import { resolveGithubToken } from "../../../utils/github-token";+import { resolveGithubToken } from "../github-token";import { defineLocalTool, type LocalToolResult } from "../registry";const GH_TIMEOUT_MS = 30_000;diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.test.tsindex aec23d3a3d1b..ca6e4de856f9 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const reportAnalysisActivity = vi.fn();-vi.mock("../../../signed-commit-artefacts", () => ({+vi.mock("../signed-commit-artefacts", () => ({createSandboxPosthogClient: () => ({ reportAnalysisActivity }),withReportDeadline: <T>(work: (signal: AbortSignal) => Promise<T>) =>work(new AbortController().signal),diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.tsindex ee0d13e5bbc2..cb39f5cb154c 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-activity.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/report-activity.ts@@ -1,11 +1,11 @@import { readdir, readFile, stat } from "node:fs/promises";import path from "node:path";import { z } from "zod";+import { defineLocalTool, type LocalToolResult } from "../registry";import {createSandboxPosthogClient,withReportDeadline,-} from "../../../signed-commit-artefacts";-import { defineLocalTool, type LocalToolResult } from "../registry";+} from "../signed-commit-artefacts";const MAX_ACTIVITIES_PER_RUN = 12;const ATTACHMENTS_DIR = ".posthog/attachments";diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.test.tsindex 483d40c5362d..c5ddd10dd3ac 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.test.ts@@ -9,7 +9,7 @@ const uploadTaskArtifacts = vi.fn();const prepareTaskArtifactUploads = vi.fn();const finalizeTaskArtifactUploads = vi.fn();-vi.mock("../../../signed-commit-artefacts", () => ({+vi.mock("../signed-commit-artefacts", () => ({createSandboxPosthogClient: () => ({sendTaskRunPeerMessage,listTaskRunPeers,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.tssimilarity index 97%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.tsindex ba6832f1ea88..960c35ce9723 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/send-agent-message.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/send-agent-message.ts@@ -1,9 +1,9 @@import { readFile, realpath, stat } from "node:fs/promises";import path from "node:path";import { z } from "zod";-import type { PostHogAPIClient } from "../../../posthog-api";-import { createSandboxPosthogClient } from "../../../signed-commit-artefacts";import { defineLocalTool, type LocalToolResult } from "../registry";+import { createSandboxPosthogClient } from "../signed-commit-artefacts";+import type { TaskToolsApiClient } from "../task-tools-client";import {MAX_ARTIFACT_UPLOAD_BYTES,uploadRunArtifact,@@ -123,7 +123,7 @@ export const sendAgentMessageTool = defineLocalTool({* escapes the workspace is an error, never an upload.*/async function resolveAttachments(- client: PostHogAPIClient,+ client: TaskToolsApiClient,cwd: string,taskId: string,taskRunId: string,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/show-actions.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/show-actions.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/show-actions.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/show-actions.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/show-actions.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/show-actions.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/show-actions.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/show-actions.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.test.tsindex 083d78ee76a5..461106efbf01 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.test.ts@@ -12,7 +12,7 @@ vi.mock("@posthog/git/signed-commit", async (importOriginal) => {};});-vi.mock("../../../signed-commit-artefacts", () => ({+vi.mock("../signed-commit-artefacts", () => ({reportSignedCommitActivity: (...args: unknown[]) =>reportSignedCommitActivity(...args),}));diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.tssimilarity index 91%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.tsindex 704a8cce1b03..78b3dd535e77 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-commit.ts@@ -3,7 +3,7 @@ import {SIGNED_COMMIT_TOOL_DESCRIPTION,SIGNED_COMMIT_TOOL_NAME,signedCommitToolSchema,-} from "../../signed-commit-shared";+} from "../signed-commit-shared";import { defineSignedGitTool } from "./signed-git-tool";export const signedCommitTool = defineSignedGitTool({diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-git-tool.tssimilarity index 92%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-git-tool.tsindex bffff228faa2..bdebda781c1e 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-git-tool.ts@@ -1,12 +1,12 @@import * as path from "node:path";import type { z } from "zod";-import { isCloudRun } from "../../../utils/common";-import { resolveGithubToken } from "../../../utils/github-token";+import { isCloudRun } from "../cloud-run";+import { resolveGithubToken } from "../github-token";+import { defineLocalTool, type LocalTool } from "../registry";import type {SignedCommitToolCtx,SignedCommitToolResult,-} from "../../signed-commit-shared";-import { defineLocalTool, type LocalTool } from "../registry";+} from "../signed-commit-shared";/*** Factory for the cloud-only GitHub tools (git_signed_commit / git_signed_rewrite /diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-merge.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-merge.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-merge.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-merge.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-merge.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-merge.tssimilarity index 90%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-merge.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-merge.tsindex 8530ca3f28ff..4b9852337937 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-merge.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-merge.ts@@ -3,7 +3,7 @@ import {SIGNED_MERGE_TOOL_DESCRIPTION,SIGNED_MERGE_TOOL_NAME,signedMergeToolSchema,-} from "../../signed-commit-shared";+} from "../signed-commit-shared";import { defineSignedGitTool } from "./signed-git-tool";export const signedMergeTool = defineSignedGitTool({diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-rewrite.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-rewrite.tssimilarity index 91%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/signed-rewrite.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/signed-rewrite.tsindex bc49fd90b4a1..27313b3bcc2c 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-rewrite.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/signed-rewrite.ts@@ -3,7 +3,7 @@ import {SIGNED_REWRITE_TOOL_DESCRIPTION,SIGNED_REWRITE_TOOL_NAME,signedRewriteToolSchema,-} from "../../signed-commit-shared";+} from "../signed-commit-shared";import { defineSignedGitTool } from "./signed-git-tool";export const signedRewriteTool = defineSignedGitTool({diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/speak.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/speak.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/speak.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/speak.test.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/speak.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/speak.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/speak.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/speak.tsdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.test.tsindex 51a561eda3de..14334b377b7d 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.test.ts@@ -9,7 +9,7 @@ const uploadTaskArtifacts = vi.fn();const STABLE_DOWNLOAD_URL ="https://app.example/api/projects/2/tasks/task-1/runs/run-1/artifacts/artifact-1/download/";-vi.mock("../../../signed-commit-artefacts", () => ({+vi.mock("../signed-commit-artefacts", () => ({createSandboxPosthogClient: () => ({prepareTaskArtifactUploads,finalizeTaskArtifactUploads,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts b/products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.tssimilarity index 97%rename from products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.tsrename to products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.tsindex c37cbb2e7829..295d3fc259c9 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts+++ b/products/desktop/packages/harness/src/extensions/local-tools/tools/upload-artifact.ts@@ -1,9 +1,9 @@import { readFile, realpath, stat } from "node:fs/promises";import path from "node:path";+import type { TaskRunArtifact } from "@posthog/shared";import { z } from "zod";-import { createSandboxPosthogClient } from "../../../signed-commit-artefacts";-import type { TaskRunArtifact } from "../../../types";import { defineLocalTool, type LocalToolResult } from "../registry";+import { createSandboxPosthogClient } from "../signed-commit-artefacts";import {type ArtifactUpload,MAX_ARTIFACT_UPLOAD_BYTES,diff --git a/products/desktop/packages/agent/src/posthog-exec-permission.test.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/exec-permission.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/posthog-exec-permission.test.tsrename to products/desktop/packages/harness/src/extensions/posthog-mcp-policy/exec-permission.test.tsindex 0751515633cb..4f6e0298c04f 100644--- a/products/desktop/packages/agent/src/posthog-exec-permission.test.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/exec-permission.test.ts@@ -7,7 +7,7 @@ import {isPostHogExecTool,matchesPostHogExecPermission,resolvePostHogExecPermissionRegex,-} from "./posthog-exec-permission";+} from "./exec-permission";const permissionRegex = compilePostHogExecPermissionRegex(DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,diff --git a/products/desktop/packages/agent/src/posthog-exec-permission.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/exec-permission.tssimilarity index 100%rename from products/desktop/packages/agent/src/posthog-exec-permission.tsrename to products/desktop/packages/harness/src/extensions/posthog-mcp-policy/exec-permission.tsdiff --git a/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.tsindex 8ab1b728d353..20cad88dde3f 100644--- a/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.ts@@ -1 +1,19 @@+export {+ compilePostHogExecPermissionRegex,+ DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,+ extractPostHogSubTool,+ isPostHogExecDescriptor,+ isPostHogExecTool,+ matchesPostHogExecPermission,+ posthogExecPermissionRegexSchema,+ resolvePostHogExecPermissionRegex,+} from "./exec-permission";export { default } from "./extension";+export {+ classifyPostHogExecCall,+ classifyPostHogSqlQuery,+ classifyPostHogSubTool,+ isUnclassifiedPostHogSubTool,+ POSTHOG_PRODUCTS,+ type PostHogProductId,+} from "./products";diff --git a/products/desktop/packages/agent/src/posthog-products.test.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.test.tssimilarity index 99%rename from products/desktop/packages/agent/src/posthog-products.test.tsrename to products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.test.tsindex 723cefba7118..71b40410fcb4 100644--- a/products/desktop/packages/agent/src/posthog-products.test.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.test.ts@@ -6,7 +6,7 @@ import {isUnclassifiedPostHogSubTool,POSTHOG_PRODUCTS,type PostHogProductId,-} from "./posthog-products";+} from "./products";describe("classifyPostHogSubTool", () => {it.each([diff --git a/products/desktop/packages/agent/src/posthog-products.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.tssimilarity index 96%rename from products/desktop/packages/agent/src/posthog-products.tsrename to products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.tsindex 05a93be6b567..559c9cc96a5c 100644--- a/products/desktop/packages/agent/src/posthog-products.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/products.ts@@ -12,25 +12,9 @@* the single source of truth for the product id → label set; the renderer maps* ids to icons/styling for display.*/+import { POSTHOG_PRODUCTS, type PostHogProductId } from "@posthog/shared";-/** Canonical PostHog products, keyed by stable id with a display label. */-export const POSTHOG_PRODUCTS = {- product_analytics: "Product analytics",- web_analytics: "Web analytics",- feature_flags: "Feature flags",- experiments: "Experiments",- error_tracking: "Error tracking",- session_replay: "Session replay",- surveys: "Surveys",- llm_analytics: "AI observability",- data_warehouse: "Data warehouse",- cdp: "Data pipelines",- logs: "Logs",- apm: "APM",- sql: "SQL",-} as const;--export type PostHogProductId = keyof typeof POSTHOG_PRODUCTS;+export { POSTHOG_PRODUCTS, type PostHogProductId };/*** Domain prefix → product, or `null` for admin/meta/introspection domains wediff --git a/products/desktop/packages/agent/src/adapters/claude/session/rtk.test.ts b/products/desktop/packages/harness/src/extensions/rtk/commands.test.tssimilarity index 75%rename from products/desktop/packages/agent/src/adapters/claude/session/rtk.test.tsrename to products/desktop/packages/harness/src/extensions/rtk/commands.test.tsindex 8c7f89ba464c..f8e709099456 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/rtk.test.ts+++ b/products/desktop/packages/harness/src/extensions/rtk/commands.test.ts@@ -1,15 +1,12 @@import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import type { HookInput } from "@anthropic-ai/claude-agent-sdk";import { afterAll, beforeAll, describe, expect, test } from "vitest";-import type { Logger } from "../../../utils/logger";import {- createRtkRewriteHook,detectRtkBinary,resolveRtkPrefix,rewriteBashForRtk,-} from "./rtk";+} from "./commands";describe("rewriteBashForRtk", () => {test.each([@@ -177,60 +174,3 @@ describe("detectRtkBinary", () => {).toBeUndefined();});});--describe("createRtkRewriteHook", () => {- const logger = {- info() {},- warn() {},- error() {},- debug() {},- } as unknown as Logger;-- const bashInput = (command: string): HookInput =>- ({- session_id: "s",- transcript_path: "/tmp/t",- cwd: "/tmp",- hook_event_name: "PreToolUse",- tool_name: "Bash",- tool_input: { command },- }) as unknown as HookInput;-- test("rewrites an eligible Bash command to updatedInput", async () => {- const hook = createRtkRewriteHook("rtk", logger);- const result = await hook(bashInput("git status"), "tool-1", {- signal: new AbortController().signal,- });- expect(result).toMatchObject({- continue: true,- hookSpecificOutput: {- hookEventName: "PreToolUse",- updatedInput: { command: "rtk git status" },- },- });- });-- test("passes ineligible commands through untouched", async () => {- const hook = createRtkRewriteHook("rtk", logger);- const result = await hook(bashInput("npm test"), "tool-1", {- signal: new AbortController().signal,- });- expect(result).toEqual({ continue: true });- });-- test("ignores non-Bash tools", async () => {- const hook = createRtkRewriteHook("rtk", logger);- const input = {- session_id: "s",- transcript_path: "/tmp/t",- cwd: "/tmp",- hook_event_name: "PreToolUse",- tool_name: "Read",- tool_input: { file_path: "/x" },- } as unknown as HookInput;- const result = await hook(input, "tool-1", {- signal: new AbortController().signal,- });- expect(result).toEqual({ continue: true });- });-});diff --git a/products/desktop/packages/agent/src/adapters/claude/session/rtk.ts b/products/desktop/packages/harness/src/extensions/rtk/commands.tssimilarity index 83%rename from products/desktop/packages/agent/src/adapters/claude/session/rtk.tsrename to products/desktop/packages/harness/src/extensions/rtk/commands.tsindex 0b7d25682642..349c005a6fbb 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/rtk.ts+++ b/products/desktop/packages/harness/src/extensions/rtk/commands.ts@@ -1,8 +1,6 @@import * as fs from "node:fs";import * as path from "node:path";-import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";-import type { Logger } from "../../../utils/logger";-import { gitSubcommand } from "../git-command";+import { gitSubcommand } from "./git-command";/*** RTK (https://github.com/rtk-ai/rtk) is a CLI proxy that compresses the output@@ -154,26 +152,3 @@ export function detectRtkBinary(env: NodeJS.ProcessEnv): string | undefined {}return findOnPath("rtk", env);}--export const createRtkRewriteHook =- (rtkPrefix: string, logger: Logger): HookCallback =>- async (input: HookInput, _toolUseID: string | undefined) => {- if (input.hook_event_name !== "PreToolUse") return { continue: true };- if (input.tool_name !== "Bash") return { continue: true };-- const toolInput = input.tool_input as { command?: string } | undefined;- const command = toolInput?.command;- if (typeof command !== "string") return { continue: true };-- const rewritten = rewriteBashForRtk(command, rtkPrefix);- if (!rewritten) return { continue: true };-- logger.info(`[RtkRewriteHook] Rewriting: ${command} → ${rewritten}`);- return {- continue: true,- hookSpecificOutput: {- hookEventName: "PreToolUse" as const,- updatedInput: { ...toolInput, command: rewritten },- },- };- };diff --git a/products/desktop/packages/agent/src/adapters/claude/git-command.ts b/products/desktop/packages/harness/src/extensions/rtk/git-command.tssimilarity index 100%rename from products/desktop/packages/agent/src/adapters/claude/git-command.tsrename to products/desktop/packages/harness/src/extensions/rtk/git-command.tsdiff --git a/products/desktop/packages/agent/src/adapters/rtk-guidance.test.ts b/products/desktop/packages/harness/src/extensions/rtk/guidance.test.tssimilarity index 95%rename from products/desktop/packages/agent/src/adapters/rtk-guidance.test.tsrename to products/desktop/packages/harness/src/extensions/rtk/guidance.test.tsindex 334f36053f7c..c6e2f1d4ad7b 100644--- a/products/desktop/packages/agent/src/adapters/rtk-guidance.test.ts+++ b/products/desktop/packages/harness/src/extensions/rtk/guidance.test.ts@@ -2,11 +2,8 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";import { afterAll, beforeAll, describe, expect, test } from "vitest";-import {- GIT_COMPRESSIBLE_SUBCOMMANDS,- RTK_PLAIN_COMMANDS,-} from "./claude/session/rtk";-import { appendRtkGuidanceForCodex, buildRtkGuidance } from "./rtk-guidance";+import { GIT_COMPRESSIBLE_SUBCOMMANDS, RTK_PLAIN_COMMANDS } from "./commands";+import { appendRtkGuidanceForCodex, buildRtkGuidance } from "./guidance";describe("rtk guidance for codex", () => {let dir: string;diff --git a/products/desktop/packages/agent/src/adapters/rtk-guidance.ts b/products/desktop/packages/harness/src/extensions/rtk/guidance.tssimilarity index 98%rename from products/desktop/packages/agent/src/adapters/rtk-guidance.tsrename to products/desktop/packages/harness/src/extensions/rtk/guidance.tsindex 962913a32c37..9433ad2156b1 100644--- a/products/desktop/packages/agent/src/adapters/rtk-guidance.ts+++ b/products/desktop/packages/harness/src/extensions/rtk/guidance.ts@@ -3,7 +3,7 @@ import {RTK_PLAIN_COMMANDS,resolveRtkPrefix,shQuote,-} from "./claude/session/rtk";+} from "./commands";/*** Instruction-level RTK integration for Codex sessions.diff --git a/products/desktop/packages/harness/src/extensions/rtk/index.ts b/products/desktop/packages/harness/src/extensions/rtk/index.tsindex 8ab1b728d353..deea071928e0 100644--- a/products/desktop/packages/harness/src/extensions/rtk/index.ts+++ b/products/desktop/packages/harness/src/extensions/rtk/index.ts@@ -1 +1,11 @@-export { default } from "./extension";+export {+ detectRtkBinary,+ GIT_COMPRESSIBLE_SUBCOMMANDS,+ RTK_PLAIN_COMMANDS,+ resolveRtkPrefix,+ rewriteBashForRtk,+ shQuote,+} from "./commands";+export { createRtkExtension, default } from "./extension";+export { gitSubcommand } from "./git-command";+export { appendRtkGuidanceForCodex, buildRtkGuidance } from "./guidance";diff --git a/products/desktop/packages/harness/src/extensions/skills-store/index.ts b/products/desktop/packages/harness/src/extensions/skills-store/index.tsnew file mode 100644index 000000000000..5c2a906ee851--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/skills-store/index.ts@@ -0,0 +1,15 @@+export {+ buildStoreSkillsInstructions,+ getStoreSkillRoots,+ hasStoreMarker,+ installStoreSkillStubs,+ listStoreSkillStubs,+ removeStoreSkillStubs,+ renderStoreSkillStub,+ type StoreSkillRootsOptions,+ type StoreSkillsInstallError,+ type StoreSkillsInstallResult,+ type StoreSkillsLogger,+ type StoreSkillsSyncContext,+ syncStoreSkills,+} from "./store-skills";diff --git a/products/desktop/packages/agent/src/server/store-skills.test.ts b/products/desktop/packages/harness/src/extensions/skills-store/store-skills.test.tssimilarity index 100%rename from products/desktop/packages/agent/src/server/store-skills.test.tsrename to products/desktop/packages/harness/src/extensions/skills-store/store-skills.test.tsdiff --git a/products/desktop/packages/agent/src/server/store-skills.ts b/products/desktop/packages/harness/src/extensions/skills-store/store-skills.tssimilarity index 100%rename from products/desktop/packages/agent/src/server/store-skills.tsrename to products/desktop/packages/harness/src/extensions/skills-store/store-skills.tsdiff --git a/products/desktop/packages/harness/src/extensions/task-system-prompt/cloud.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/cloud.tsnew file mode 100644index 000000000000..fca3f4eb55a6--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/cloud.ts@@ -0,0 +1,447 @@+import {+ GH_STACK_QUALIFIED_TOOL_NAME,+ SIGNED_COMMIT_QUALIFIED_TOOL_NAME,+ SIGNED_MERGE_QUALIFIED_TOOL_NAME,+ SIGNED_REWRITE_QUALIFIED_TOOL_NAME,+} from "../local-tools";+import { buildStoreSkillsInstructions } from "../skills-store";++export type SlackArtifactDelivery = "none" | "message" | "canvas_file";++export interface CloudTaskPromptOptions {+ apiUrl: string;+ baseBranch?: string;+ createPr?: boolean;+ isAutomatedOrigin: boolean;+ isSlack: boolean;+ projectId: number;+ hasGithubToken: boolean;+ repositoryAttached: boolean;+ shouldAutoPublish: boolean;+ slackArtifactDelivery: SlackArtifactDelivery | null;+ slackChartDelivery: boolean;+ storeSkillsInstalledCount: number;+ taskId: string;+ taskRepositories: string[];+}++export class CloudTaskPrompt {+ constructor(private readonly options: CloudTaskPromptOptions) {}++ private buildExistingPrCheckoutInstruction(prUrl: string): string {+ return `Continue working on the existing PR branch. If it is not already checked out, check it out with \`gh pr checkout ${prUrl}\`. Do not check it out again when it is already active.`;+ }++ buildDetectedPrContext(prUrl: string): string {+ if (!this.options.shouldAutoPublish) {+ return (+ `An open pull request already exists: ${prUrl}\n` ++ `Use that PR as context if it is helpful, but stop with local changes ready for review.\n` ++ `Do NOT create commits, push to the PR branch, update the pull request, create a new branch, or create a new pull request unless the user explicitly asks.`+ );+ }++ return (+ `IMPORTANT — OVERRIDE PREVIOUS INSTRUCTIONS ABOUT CREATING BRANCHES/PRs.\n` ++ `You already have an open pull request: ${prUrl}\n` ++ `Unless the user explicitly asks for a new branch or separate PR, you MUST:\n` ++ `1. ${this.buildExistingPrCheckoutInstruction(prUrl)}\n` ++ `2. Make changes, commit, and push to that branch\n` ++ `By default, do not create a new branch, close the existing PR, or create a new PR — continue on the existing PR. If the user explicitly asks you to create a new branch or a separate PR, follow their instruction instead.`+ );+ }++ /**+ * How this run may hand a deliverable to the Slack thread it is answering in.+ *+ * The offer has to match what delivery will actually accept: naming an adapter the+ * workspace cannot use gets the request rejected server-side after the agent has already+ * promised the user a canvas or a spreadsheet. The backend resolves that capability from+ * the workspace's feature flags and Slack scopes when the task starts and hands it to us+ * on the run state, so the wording lives here and the gating stays there.+ */+ private buildSlackDeliveryInstructions(): string {+ if (this.options.slackArtifactDelivery === null) {+ return "";+ }++ if (this.options.slackArtifactDelivery === "none") {+ return `+## Delivering to Slack+- You do not have artifact delivery in this workspace: you cannot create or share artifacts (files, canvases, documents) from this run, so do not attempt to. Deliver results as plain text in your reply.+- Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths.`;+ }++ const endpoint = `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/`;+ const preamble = `+## Delivering to Slack+- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.+- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.+- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;++ // Charts attach to both modes: they post as an image block referencing a PostHog-hosted+ // url, so they work wherever the workspace can post at all.+ const chartBullets = this.options.slackChartDelivery+ ? `+- When an analytics answer is naturally visual (a trend over time, funnel, breakdown comparison, retention curve), deliver a chart image by default alongside the summary. Do not wait for the user to say "chart". Skip the image only when the result is a single number, a short list, or the user asked for raw data.+- To show a chart in Slack (a saved insight or an ad-hoc analytics query result), make a single call: POST to \`${endpoint}chart/\` with \`$POSTHOG_PERSONAL_API_KEY\` and body \`{"name": "<chart title>", "query": <query JSON, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}>}\`, or \`{"name": "<chart title>", "insight_id": <numeric insight id>}\` for a saved insight. It renders the chart server-side and registers it for Slack delivery in one step, blocking until done (typically a few seconds).+- The chart renders directly under your answer text with its name as the title, so do not restate the title or announce the chart ("Here's a chart of…"). Spend your answer text on the takeaway instead: the trend, inflection points, spikes, or drops a reader should notice, with numbers where they matter. Each chart is delivered with an "Open in PostHog" button, so do not paste the response \`url\` into your answer unless the user explicitly asks for a link. Do not download, view, or re-upload the image yourself.+- Report a chart failure rather than retrying blindly: a 400 carries the reason in \`error\`, or in \`detail\` when the request body itself was rejected, and a 429 means the project's chart render limit is saturated, so answer without the chart.+- SQL results cannot be charted yet, because the chart endpoint rejects SQL queries. Chart with an insight query (e.g. TrendsQuery) when the question can be expressed as one; otherwise summarize the SQL result in your answer text.`+ : "";++ if (this.options.slackArtifactDelivery === "message") {+ const chartException = this.options.slackChartDelivery+ ? " Chart images are the one exception: deliver them through the dedicated chart endpoint below, never through the generic living-artifacts endpoint."+ : "";+ const unsupportedDeliverable = this.options.slackChartDelivery+ ? "- If a deliverable cannot be expressed as a Slack message or a chart image (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."+ : "- If a deliverable cannot be expressed as a Slack message (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead.";+ return `${preamble}+- You do not have canvas or file delivery in this workspace: do not use the \`slack_canvas\` or \`slack_file\` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.${chartException}+- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}+${unsupportedDeliverable}`;+ }++ return `${preamble}+- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\`; choose adapter \`slack_canvas\`, \`slack_message\`, \`slack_file\`, or \`document_connector\`. Use \`adapter=slack_file\` with \`content_base64\` for binary deliverables such as .xlsx/.pdf/.docx, or \`source_artifact_id\` / \`source_storage_path\` for a file you already uploaded as a \`type=output\` run artifact.+- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}+- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending file artifacts to your final answer automatically, so mention the artifact by name only if useful.+- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.`;+ }++ private buildGithubAccessInstructions(hasGithubToken: boolean): string {+ if (hasGithubToken) {+ return `+## GitHub access+You have GitHub access in this session.`;+ }++ const settingsUrl = `${this.options.apiUrl.replace(/\/$/, "")}/project/${this.options.projectId}/settings/user-personal-integrations`;+ return `+## GitHub access+You do not have GitHub access in this session.+- You can read repository content that is already in the workspace.+- You can clone an exact public repository. Do not call \`list_repos\` without GitHub access.+- Codebase analysis and code review require readable repository content.+- Code changes also require publishing access.+- If the required access is unavailable, do not replace the requested code work with generic guidance or PostHog data analysis.+- Tell the user to connect GitHub at ${settingsUrl}.+- The connection applies to a new task, not this task.+- Write the access explanation first.+- Then call \`show_actions\` with one \`compose\` action.+- Use the label \`Try again in a new task\` and prefill the original repository request.+- Include the exact \`owner/repo\` in the action when you know it.+- Do not guess file contents. Do not start a change that you cannot deliver.`;+ }++ buildCloudSystemPrompt(+ prUrl?: string | null,+ slackThreadUrl?: string | null,+ inboxReportUrl?: string | null,+ ): string {+ const taskId = this.options.taskId;+ const shouldAutoCreatePr = this.options.shouldAutoPublish;+ const isSlack = this.options.isSlack;+ // Every instruction in this section runs through `gh`, so a sandbox holding no+ // GitHub token cannot act on any of it. An empty token is an explicit logout.+ const hasGithubToken = this.options.hasGithubToken;+ const githubIdentityInstructions = hasGithubToken+ ? `+# Whose GitHub account you are using+\`gh\` is authenticated as the person you are working for, so let GitHub resolve who that is. To put them on an issue or pull request, self-assign:+\`gh issue create --assignee "@me"\`, \`gh pr create --assignee "@me"\`, \`gh issue edit <number> --add-assignee "@me"\`+To \`@\`-mention them in a body or a comment, read their handle with \`gh api user --jq .login\`. Read it once per reply rather than reusing one from an earlier reply, because a different person can take over between replies and \`gh\` follows that change.+If the command fails, or returns a name ending in \`[bot]\`, you are acting as the PostHog app rather than as a person: ask them for their GitHub login instead of assigning or mentioning anyone.+`+ : "";+ const slackIdentityInstructions = isSlack+ ? `+# Identity+You are the PostHog Slack app, PostHog's agent for helping users with their product data and coding tasks from Slack. When introducing yourself or referring to yourself in messages to the user, identify as "PostHog Slack app". Do NOT refer to yourself as Claude, an Anthropic assistant, or any underlying model name.++# Response Style+You are replying in a Slack thread. Slack readers want short, skimmable answers — be concise by default.+- Answer simple questions in a single sentence. Keep everything else brief — a few sentences at most.+- Lead with the answer or the outcome. Skip preamble, restating the question, and sign-offs.+- Prefer plain prose. Treat bullet lists as the exception, not the norm, and avoid headers and tables unless they genuinely make a complex answer clearer.+- Do not narrate your thinking or list every step you took; report what matters and the result.+- This is a default, not a hard rule. If the user (or their saved memory) asks for more depth or a specific format, follow that instead.++# PostHog products first+PostHog is a product suite, not just analytics — session replay, feature flags, experiments, surveys, error tracking, logs, data warehouse, CDP, messaging, and customer support all ship as PostHog products.+- When someone asks how to set up, enable, configure, or use a capability, assume they mean PostHog's version of it and answer about that.+- Search our docs with the \`docs-search\` tool before you answer, and ground the answer in what it returns rather than in what you remember. The product changes faster than your training data.+- Never send the user to a third-party product for something PostHog does. If you are unsure whether we cover it, search the docs before concluding we don't — and if we genuinely don't, say so plainly instead of recommending a competitor. Pointing at a third party we integrate with, as a source or destination, is fine.+- When a request could mean either a PostHog feature or something in the user's own codebase, ask which they mean instead of guessing.++# Mentioning users+To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appears in the message context — copy it verbatim, including the \`U…\` ID. Do NOT construct a mention token from a name, and do NOT substitute the display name (or any other string) for the \`U…\` ID — \`<@Jane|Jane Doe>\` is not a valid mention; only the form with the real ID like \`<@U01ABCDEF23|Jane Doe>\` is. If the person you want to refer to has no \`<@U…|displayname>\` token anywhere in the thread context, write their name as plain text instead of inventing one. These \`<@U…>\` tokens are Slack-only: never carry one — or a name or handle derived from it — into a GitHub PR, commit message, or review request as an \`@\`-mention. A Slack display name or handle is NOT a GitHub username; see the pull-request instructions below.++# Suggesting code changes+You can also open pull requests directly from this Slack thread. When the user's question describes a problem with a plausible code-side fix — a bug visible in errors or logs, missing or broken instrumentation, a broken funnel step traceable to UI code, a stale config that lives in a repo — end your reply with a one-sentence offer to open a PR for the fix and ask if they want you to proceed. Skip the offer for pure data lookups with no actionable code change (e.g. "what was DAU yesterday?"), and skip it when the fix would clearly live outside any repo you can reach.+`+ : "";+ const identityInstructions = `${slackIdentityInstructions}${githubIdentityInstructions}`;+ const signedCommitInstructions = `+## Committing (signed commits required)+Commits MUST be signed. \`git commit\` and \`git push\` are blocked in this environment.+To commit: stage your changes with \`git add\`, then call the \`git_signed_commit\` tool (full+name \`${SIGNED_COMMIT_QUALIFIED_TOOL_NAME}\`) with a \`message\` (and optional \`body\`/\`paths\`).+It creates a GitHub-signed ("Verified") commit on the branch and keeps your local checkout in+sync. To start a new branch, pass \`branch\` (prefixed with \`posthog/\`) — the tool creates+it on the remote for you.++## Updating from the base branch+To bring the base branch into your PR branch, call the \`git_signed_merge\` tool (full name+\`${SIGNED_MERGE_QUALIFIED_TOOL_NAME}\`) — it creates a Verified two-parent merge commit+server-side (like GitHub's "Update branch" button). NEVER run \`git merge\` followed by+\`git_signed_commit\`: a merge in progress is refused, because the commit API would linearize+the merge and dump every base-branch change into your PR. If \`git_signed_merge\` reports a+conflict, fix it with a rebase instead: \`git rebase origin/<base>\`, resolve, \`git rebase+--continue\`, then call \`git_signed_rewrite\`.++## Rewriting / force-pushing (rebases, conflict fixes)+\`git push --force\` is also blocked. To update a branch after a local rebase or conflict+resolution, rebase locally with normal \`git\` (resolve conflicts and finish with+\`git rebase --continue\`, NOT \`git commit\`), then call the \`git_signed_rewrite\` tool (full+name \`${SIGNED_REWRITE_QUALIFIED_TOOL_NAME}\`). It republishes the branch's commits as Verified+and atomically force-updates the remote branch. This is how you fix conflicts on an existing PR.+Histories containing merge commits are refused — rebase (which flattens merges) first.+If a signed-git tool refuses with a "merge in progress" or "leak" error, follow its recovery+instructions instead of retrying the same call.++## Re-committing to a branch with an open PR+Before committing again to a branch that already has an open PR, fetch it first. The remote+branch can advance between your commits — CI automation often auto-commits regenerated+artifacts (codegen, lockfiles, formatting) onto open PR branches, and collaborators can push+too. Committing from a stale local checkout silently reverts those commits, so+\`git_signed_commit\` refuses when the remote branch is ahead of your checkout. If it does, or+before your next commit, update your checkout — stash any uncommitted work across the update so+you don't lose it: \`git stash --include-untracked\`, \`git fetch origin <branch>\`,+\`git reset --hard origin/<branch>\`, \`git stash pop\` (resolve any conflicts), then re-stage+and commit. A soft/mixed reset would keep your stale files and re-commit the revert, so the+hard reset is the safe one here — your work is held in the stash.++## Attribution+Do NOT add "Co-Authored-By" trailers or "Generated with [Claude Code]" lines to your+commit messages. The \`git_signed_commit\` tool automatically appends the only trailers+we want:+Generated-By: PostHog Desktop+Task-Id: ${taskId}`;++ // A stack is several PRs, so this would contradict the review-first modes.+ const stackInstructions = shouldAutoCreatePr+ ? `+## Stacked pull requests+Stack only when the layers are independently reviewable (schema, then backend, then UI) or the+user asked for a stack. Keep stacks shallow — 2 to 4 layers. One PR remains the default.+Do NOT use the \`gh stack\` CLI: its publishing commands (\`submit\`, \`sync\`, \`push\`, \`link\`)+all run \`git push\`, which is blocked here. Build the stack this way instead:+1. Commit the bottom layer with \`git_signed_commit\`, passing \`branch\`, then open its pull+ request based on the base branch.+2. For each layer above, commit with \`git_signed_commit\` and a new \`branch\` — your checkout+ already sits on the layer below, so the branch starts there — then open its pull request+ based on the branch of the layer below (\`--base <that branch>\`).+3. Link them with the \`gh_stack\` tool (full name \`${GH_STACK_QUALIFIED_TOOL_NAME}\`),+ operation "create", passing \`pull_requests\` bottom to top. Every layer must target the+ branch of the one below it, or the link is refused.+When a lower layer changes, restack the layers above it bottom-first. For each layer: check+that layer out, \`git rebase <its parent branch>\`, then republish it with+\`git_signed_rewrite\` passing \`onto\` = the parent branch. Check the layer out every time —+\`git_signed_rewrite\` replays whatever your local HEAD points at and uses \`branch\` only to+pick which remote ref moves, so rewriting from the wrong checkout publishes the wrong history+to that layer.`+ : "";++ const prLinkInstructions = `+## Referencing pull requests+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.`;++ const shellEfficiencyInstructions = `+## 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.`;++ const artifactInstructions = `+## Delivering non-code files (artifacts)+When you create a non-code file the user should be able to download (such as a report, chart, image, archive, or data file), call the \`upload_artifact\` tool with its path before your final reply. In your final reply, link to the download URL returned by the tool—never link to the file's local workspace path. Files left in the workspace don't reach the user. Don't upload source code or repository changes—those belong in a commit or PR.`;++ // Closes out every branch below, so a new section is added once rather than five times.+ const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.options.storeSkillsInstalledCount)}`;++ const whyContextInstruction = ` - Add a brief **Why** to the body — one or two sentences capturing the reason the user asked for this change (the motivation, not a restatement of the diff). Keep it short.`;+ const publicRepoSafetyInstruction = ` - **Public-repo safety.** Treat the target repository as public-readable unless you have verified otherwise. The PR title, description, and commit messages must not contain private operational scale (exact event counts, internal row volumes, customer-usage percentages), customer names / emails / companies, references to internal tickets or incidents, the contents of Slack threads (do not quote or paraphrase what was said), or unreleased roadmap details. Linking to the originating Slack thread is fine and encouraged — Slack links are auth-gated and useful as context — as are channel references like "raised in #team-foo". Describe findings qualitatively ("present on nearly all X events, absent from Y") rather than with quantitative figures pulled from analytics queries — the reasoning that uses those numbers can stay in the thread; the PR copy cannot.`;+ const prMentionSafetyInstruction = ` - **Never guess a GitHub identity.** Do NOT \`@\`-mention, tag, assign, request review from, or attribute the PR to a person (in the title, description, commit message, or reviewers) using a name or handle taken from Slack or this thread. A Slack display name or handle is NOT a GitHub username. Finding a similar-looking handle in the repo's git history, CODEOWNERS, or existing PRs/issues does NOT confirm it belongs to this person: repository presence proves the handle exists, not that it is the person you mean, so treating it as a match still \`@\`-tags an unrelated account (e.g. Slack "Ross" is not necessarily GitHub \`@ross\`, even if some \`@ross\` has committed to the repo). Only \`@\`-mention a GitHub \`@handle\` the user gave you explicitly in this thread, or one you read from \`gh api user --jq .login\`, which authenticates as the person you are working for. Otherwise refer to people by plain-text name, or omit the mention entirely.`;+ // Slack- and inbox-originated PRs are attributed to PostHog, not the+ // PostHog Desktop app — they come from the Slack app / Self-driving+ // inbox, which users know as "PostHog".+ const createdWith = this.options.isAutomatedOrigin+ ? "Created with [PostHog](https://posthog.com?ref=pr)"+ : "Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)";+ const prFooter = slackThreadUrl+ ? `*${createdWith} from a [Slack thread](${slackThreadUrl})*`+ : inboxReportUrl+ ? `*${createdWith} from an [inbox report](${inboxReportUrl})*`+ : `*${createdWith}*`;+ const repositoryWorkspaceInstructions =+ this.options.taskRepositories.length > 1+ ? `The task workspace contains these repositories:+${this.options.taskRepositories.map((repository) => `- ${repository}: /tmp/workspace/repos/${repository.toLowerCase()}`).join("\n")}++Apply the repository workflow below separately in every repository you change. Keep branches, commits, diffs, and pull requests repository-specific.`+ : "";++ if (prUrl) {+ if (!shouldAutoCreatePr) {+ return `${identityInstructions}+# Cloud Task Execution++This task already has an open pull request: ${prUrl}++Do the requested work, but stop with local changes ready for review.++Important:+- Do NOT create new commits, push to the branch, or update the pull request unless the user explicitly asks.+- Do NOT create a new branch or a new pull request unless the user explicitly asks.+${commonInstructions}+`;+ }++ return `${identityInstructions}+# Cloud Task Execution++This task already has an open pull request: ${prUrl}++After completing the requested changes:+1. ${this.buildExistingPrCheckoutInstruction(prUrl)}+2. Stage your changes with \`git add\`, then call the \`git_signed_commit\` tool with a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). This commits to the existing PR branch.+ - If the branch is behind its base, call the \`git_signed_merge\` tool first — it merges the base in server-side with a Verified merge commit. Only if it reports a conflict: fetch and rebase locally (\`git fetch origin <base>\`, \`git rebase origin/<base>\`, resolve, \`git rebase --continue\`), then call the \`git_signed_rewrite\` tool to force-update this same PR branch.+3. For every PR review comment or review thread you addressed, treat the thread as done only after BOTH of these:+ - Reply on the thread with a short note describing what changed (reference the commit SHA when useful) using \`gh api -X POST /repos/{owner}/{repo}/pulls/{n}/comments/{id}/replies -f body='...'\`.+ - Resolve the thread via the \`resolveReviewThread\` GraphQL mutation: \`gh api graphql -f query='mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{isResolved}}}' -f id="<thread-node-id>"\`.+ List unresolved threads first with \`gh api graphql -f query='{repository(owner:"<owner>",name:"<repo>"){pullRequest(number:<n>){reviewThreads(first:100){nodes{id isResolved comments(first:1){nodes{body}}}}}}}'\` so you can resolve each one you fixed.++Important:+- Do NOT create a new branch or a new pull request unless the user explicitly asks.+- Do NOT push fixes for review comments without replying to and resolving each related thread.+${commonInstructions}+`;+ }++ if (+ !this.options.repositoryAttached &&+ this.options.taskRepositories.length === 0+ ) {+ const repositoryInstructions = `+When the task requires a GitHub repository:+- If the repository is not specified, call \`list_repos\` and use the task context to choose it. If multiple repositories remain plausible, ask the user.+- Call \`clone_repo\` with the chosen \`owner/repo\` and optional branch. It creates a shallow clone under \`/tmp/workspace/repos/<owner>/<repo>\` and returns the path.+- Work from inside the returned path for all code changes.+- The clone starts with one commit. If older history is genuinely needed, fetch it in bounded steps with \`git fetch --deepen=50 origin <branch>\`, then \`git fetch --deepen=200 origin <branch>\`. Use \`git fetch --unshallow\` only when the task explicitly requires full history, such as a long-range blame or bisect.+`;+ const publishInstructions =+ this.options.createPr === false+ ? `+When the user asks for code changes:+- You may make local edits in a repository cloned with \`clone_repo\`+- Do NOT create branches, commits, push changes, or open pull requests in this run`+ : shouldAutoCreatePr+ ? `+When the user asks for code changes in a GitHub repository:+- After completing code changes in a cloned repository, create a branch, stage your changes with \`git add\` and commit them with the \`git_signed_commit\` tool (do NOT use \`git commit\`/\`git push\` — they are blocked), and open a draft pull request from inside the clone without waiting to be asked. Before opening the PR, check the cloned repo for a default PR template at \`.github/pull_request_template.md\` (or variants) and named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`. If multiple templates exist, use the one that best matches the change as the body structure. If no repo-level template exists, check the org's \`.github\` repo via \`gh api\` for a default or named template. Search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links.+- Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.+${whyContextInstruction.trimStart()}+${publicRepoSafetyInstruction.trimStart()}+${prMentionSafetyInstruction.trimStart()}+- End the PR description with a horizontal rule followed by this footer line: ${prFooter}+- Always create the PR as a draft. Do not ask for confirmation before publishing completed code changes`+ : `+When the user explicitly asks for code changes in a GitHub repository:+- If the user explicitly asks you to open or update a pull request, create a branch, stage your changes with \`git add\` and commit them with the \`git_signed_commit\` tool (do NOT use \`git commit\`/\`git push\` — they are blocked), and open a draft pull request from inside the clone. Before opening the PR, check the cloned repo for a default PR template at \`.github/pull_request_template.md\` (or variants) and named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`. If multiple templates exist, use the one that best matches the change as the body structure. If no repo-level template exists, check the org's \`.github\` repo via \`gh api\` for a default or named template. Search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links.+- Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.+${whyContextInstruction.trimStart()}+${publicRepoSafetyInstruction.trimStart()}+${prMentionSafetyInstruction.trimStart()}+- End the PR description with a horizontal rule followed by this footer line: ${prFooter}+- Do NOT create branches, commits, push changes, or open pull requests unless the user explicitly asks for that`;++ return `${identityInstructions}+# Cloud Task Execution — No Repository Mode++You are a helpful assistant with access to PostHog via MCP tools. You can help with both code tasks and data/analytics questions.++For a question about company-specific terms, internal policies, or team knowledge, search the project knowledge base before you answer, whatever else the question is about: call \`posthog:exec\` and run its inner \`posthog:business-knowledge-documents-search\` tool. These documents are not in the public docs or the context wiki, so check the knowledge base before you tell the user that you cannot find the answer. If that tool is not available in this project, move on instead of retrying it.++When the user asks about analytics, data, metrics, events, funnels, dashboards, feature flags, experiments, or anything PostHog-related:+- Use the canonical \`posthog:exec\` tool to query data, search insights, and provide real answers+- A count, sum, or amount of X per day/hour/week/month/year, a rate or percentage of X, an average or percentile of X, a cost per X, a conversion between two events, or a derived form of one of those is a governed metric question — whatever X is (sessions, 404s, feedback submissions, scout runs, tool calls, revenue). For those, inspect the complete governed catalog with \`posthog:metric-list\` first, inspect a candidate with \`posthog:metric-describe\`, then run an approved match with \`posthog:data-catalog-metric-run\`. Do this before \`posthog:read-data-schema\`, a typed domain tool, or a raw query+- Follow its built-in instructions to discover and invoke inner tools+- Do NOT tell the user to check an external analytics platform — you ARE the analytics platform+- Inner tools include \`posthog:read-data-schema\`, \`posthog:execute-sql\`, \`posthog:insight-query\`, and the typed query tools++When the user asks for code changes or software engineering tasks:+- Choose and clone a repository only when the task requires one. For questions and analysis, answer without cloning when possible.+${repositoryInstructions}${publishInstructions}++Important:+- Prefer using MCP tools to answer questions with real data over giving generic advice.+${commonInstructions}+`;+ }++ if (!shouldAutoCreatePr) {+ return `${identityInstructions}+# Cloud Task Execution++${repositoryWorkspaceInstructions}++Do the requested work, but stop with local changes ready for review.++Important:+- Do NOT create a branch, commit, push, or open a pull request unless the user explicitly asks.+- If the user explicitly asks you to open a pull request: pick a new branch name prefixed with \`posthog/\`, stage your changes with \`git add\`, and call the \`git_signed_commit\` tool with \`branch\` set to that name and a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). Before opening the PR, check the repo for a default PR template at \`.github/pull_request_template.md\` (or variants) and named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`. If multiple templates exist, use the one that best matches the change as the body structure. If no repo-level template exists, check the org's \`.github\` repo via \`gh api\` for a default or named template. Search for matching open issues with \`gh issue list --search\` to include \`Closes #<n>\` / \`Refs #<n>\` links. Keep the description brief overall — summarize only the most important changes.+${whyContextInstruction.trimStart()}+${publicRepoSafetyInstruction.trimStart()}+${prMentionSafetyInstruction.trimStart()}+- End the PR description with a horizontal rule followed by this footer line: ${prFooter}+- Always create the PR as a draft.+${commonInstructions}+`;+ }++ return `${identityInstructions}+# Cloud Task Execution++${repositoryWorkspaceInstructions}++If the work you are being asked to do already has an open pull request — for example, the inbox report you fetched links an implementation PR (its \`implementation_pr_url\`), or this same thread already produced a PR that you are now being asked to revise — do NOT open a second PR. Check that PR out with \`gh pr checkout <url>\`, continue on its branch, and commit your changes to it with the \`git_signed_commit\` tool (if the branch is behind its base, call \`git_signed_merge\` first). A PR is only the one to continue if it is for this same request; if the thread merely mentions an unrelated or older PR, ignore it. Only open a new, separate PR when the change is genuinely distinct from the existing one.++Otherwise, after completing the requested changes:+1. Pick a new branch name prefixed with \`posthog/\` (e.g. \`posthog/fix-login-redirect\`)+2. Stage your changes with \`git add\`, then call the \`git_signed_commit\` tool with \`branch\` set to that name and a clear \`message\` (do NOT use \`git commit\`/\`git push\` — they are blocked). The tool creates the branch on the remote and a signed commit on it.+3. Before opening the PR, prepare the body:+ - Keep the PR description brief overall. Summarize only the most important changes — do NOT enumerate every change you made. A few sentences or bullets is plenty.+${whyContextInstruction}+${publicRepoSafetyInstruction}+${prMentionSafetyInstruction}+ - Check the repo for a default PR template at \`.github/pull_request_template.md\` (also try \`.github/PULL_REQUEST_TEMPLATE.md\`, \`docs/pull_request_template.md\`, and root variants). Also check for named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`. If multiple templates exist, use the one that best matches the change. Use its exact section headings as the PR body — do NOT fall back to a generic Summary/Test plan format.+ - If no repo-level template exists, check the org's \`.github\` repo via \`gh api\`. Look for both a default template and named templates in \`.github/PULL_REQUEST_TEMPLATE/*.md\`, and use the best match as a fallback.+ - Search for matching open issues with \`gh issue list --state open --search '<keywords>'\` (derive keywords from the branch name, commits, and changed files; \`gh issue view <n>\` to confirm relevance). For every issue this PR would resolve, include a \`Closes #<n>\` line in the body so GitHub auto-links and auto-closes it on merge. For issues that are related but not fully resolved, use \`Refs #<n>\` instead.+4. Create a draft pull request using \`gh pr create --draft${this.options.baseBranch ? ` --base ${this.options.baseBranch}` : ""}\` with a descriptive title and the body prepared above. Add the following footer at the end of the PR description:+\`\`\`+---+${prFooter}+\`\`\`++Important:+- Always create the PR as a draft. Do not ask for confirmation.+${commonInstructions}+`;+ }+}diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/extension.test.tssimilarity index 96%rename from products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.tsrename to products/desktop/packages/harness/src/extensions/task-system-prompt/extension.test.tsindex 6ba0d37f65ee..e5fa36f13c0a 100644--- a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.test.ts+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/extension.test.ts@@ -3,13 +3,14 @@ import type {SessionEntry,SessionManager,} from "@earendil-works/pi-coding-agent";+import type { TaskContext } from "@posthog/shared/task-context";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";+} from "./extension";+import { buildTaskSystemPrompt } from "./prompt";const taskContext: TaskContext = {projectId: 42,diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/extension.tssimilarity index 95%rename from products/desktop/packages/agent/src/pi/task-system-prompt-extension.tsrename to products/desktop/packages/harness/src/extensions/task-system-prompt/extension.tsindex a8a75707e526..139ebf7890e9 100644--- a/products/desktop/packages/agent/src/pi/task-system-prompt-extension.ts+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/extension.ts@@ -4,11 +4,8 @@ import type {SessionEntry,SessionManager,} from "@earendil-works/pi-coding-agent";-import {- buildTaskSystemPrompt,- type TaskContext,- type TaskPromptCapabilities,-} from "./task-system-prompt";+import type { TaskContext } from "@posthog/shared/task-context";+import { buildTaskSystemPrompt, type TaskPromptCapabilities } from "./prompt";export const POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE = "posthog.pi.task-context";diff --git a/products/desktop/packages/harness/src/extensions/task-system-prompt/index.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/index.tsnew file mode 100644index 000000000000..762d59bdd473--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/index.ts@@ -0,0 +1,32 @@+export {+ CloudTaskPrompt,+ type CloudTaskPromptOptions,+ type SlackArtifactDelivery,+} from "./cloud";+export {+ createPiTaskSystemPromptExtension,+ POSTHOG_PI_TASK_CONTEXT_ENTRY_TYPE,+ resolvePiTaskContext,+} from "./extension";+export {+ buildAdditionalDirectoriesPrompt,+ buildAttributionPrompt,+ buildChannelPrompt,+ buildCompactionContinuationPrompt,+ buildCustomInstructionsPrompt,+ buildLocalAttributionPrompt,+ buildPostHogContextPrompt,+ buildPullRequestLinksPrompt,+ buildQuestionsPrompt,+ buildShellEfficiencyPrompt,+ buildTaskContextPrompt,+ buildTaskSystemPrompt,+ type TaskPromptCapabilities,+} from "./prompt";+export {+ buildAttachedSkillsPrompt,+ buildInstalledSkillPrompt,+ type InstalledSkillPromptData,+ type LocalSkillInvocation,+ parseLocalSkillInvocation,+} from "./skills";diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.test.tssimilarity index 97%rename from products/desktop/packages/agent/src/pi/task-system-prompt.test.tsrename to products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.test.tsindex c629ce87f3bd..97946bd51a56 100644--- a/products/desktop/packages/agent/src/pi/task-system-prompt.test.ts+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { buildTaskSystemPrompt } from "./task-system-prompt";+import { buildTaskSystemPrompt } from "./prompt";describe("buildTaskSystemPrompt", () => {it("builds durable local task instructions", () => {diff --git a/products/desktop/packages/agent/src/pi/task-system-prompt.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.tssimilarity index 95%rename from products/desktop/packages/agent/src/pi/task-system-prompt.tsrename to products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.tsindex f1c9d4ab3342..70bd909e569c 100644--- a/products/desktop/packages/agent/src/pi/task-system-prompt.ts+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/prompt.ts@@ -1,17 +1,4 @@-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;-}+import type { TaskContext } from "@posthog/shared/task-context";export interface TaskPromptCapabilities {structuredInput?: boolean;@@ -36,6 +23,10 @@ export function buildTaskContextPrompt(taskId: string): string {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 buildCompactionContinuationPrompt(): string {+ return "Compaction is complete. Continue working on the task from the compacted context, following the user's instructions from the /compact command.";+}+export function buildAttributionPrompt(taskId: string,environment: TaskContext["environment"],diff --git a/products/desktop/packages/harness/src/extensions/task-system-prompt/skills.ts b/products/desktop/packages/harness/src/extensions/task-system-prompt/skills.tsnew file mode 100644index 000000000000..8c033d1133b4--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/task-system-prompt/skills.ts@@ -0,0 +1,97 @@+export interface InstalledSkillPromptData {+ skillName: string;+ skillDefinition: string;+ skillRoot: string;+}++export interface LocalSkillInvocation {+ skillName: string;+ args?: string;+}++export function parseLocalSkillInvocation(+ textValue: string,+): LocalSkillInvocation | null {+ const trimmed = textValue.trim();+ const match = trimmed.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);+ if (!match?.[1]) {+ return null;+ }++ return {+ skillName: match[1],+ ...(match[2]?.trim() ? { args: match[2].trim() } : {}),+ };+}++export function buildInstalledSkillPrompt(+ skill: InstalledSkillPromptData,+ args: string | undefined,+ coInstalledSkills: readonly InstalledSkillPromptData[] = [],+): string {+ return [+ `The user invoked the local skill "/${skill.skillName}". Apply these skill instructions for this turn.`,+ "",+ `--- BEGIN LOCAL SKILL ${skill.skillName} ---`,+ skill.skillDefinition.trim(),+ `--- END LOCAL SKILL ${skill.skillName} ---`,+ "",+ `Installed skill path: ${skill.skillRoot}`,+ ...(coInstalledSkills.length > 0+ ? [+ "",+ "Other local skills installed for this run (when the skill above references one of these, read its SKILL.md from the listed path):",+ ...coInstalledSkills.map(+ (coInstalled) =>+ `- /${coInstalled.skillName}: ${coInstalled.skillRoot}`,+ ),+ ]+ : []),+ "",+ "User request:",+ args?.trim() || `Run /${skill.skillName}.`,+ ].join("\n");+}++export function buildAttachedSkillsPrompt(+ installedSkills: readonly InstalledSkillPromptData[],+ messageText: string,+): string | null {+ if (installedSkills.length === 0) {+ return null;+ }++ const mentioned = installedSkills.filter((skill) => {+ const escaped = skill.skillName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(+ `(^|[\\s(\`"'\\[])/${escaped}(?![A-Za-z0-9_/-])`,+ "m",+ ).test(messageText);+ });+ const unmentioned = installedSkills.filter(+ (skill) => !mentioned.includes(skill),+ );++ const sections: string[] = [+ "The user's message references local skills that are now installed for this run. Apply a skill's instructions when the message calls for it.",+ ];+ for (const skill of mentioned) {+ sections.push(+ "",+ `--- BEGIN LOCAL SKILL ${skill.skillName} ---`,+ skill.skillDefinition.trim(),+ `--- END LOCAL SKILL ${skill.skillName} ---`,+ `Installed skill path: ${skill.skillRoot}`,+ );+ }+ if (unmentioned.length > 0) {+ sections.push(+ "",+ "Other local skills installed for this run (read a skill's SKILL.md from its path when referenced):",+ ...unmentioned.map(+ (skill) => `- /${skill.skillName}: ${skill.skillRoot}`,+ ),+ );+ }+ return sections.join("\n");+}diff --git a/products/desktop/packages/harness/tsup.config.ts b/products/desktop/packages/harness/tsup.config.tsindex 1bb087ddf415..557a5ae66158 100644--- a/products/desktop/packages/harness/tsup.config.ts+++ b/products/desktop/packages/harness/tsup.config.ts@@ -85,6 +85,13 @@ export default defineConfig({(entrypoint) => `src/extensions/${entrypoint}.ts`,),"src/extensions/auto-publish/index.ts",+ "src/extensions/context-wiki/index.ts",+ "src/extensions/enrichment/index.ts",+ "src/extensions/task-system-prompt/index.ts",+ "src/extensions/local-tools/index.ts",+ "src/extensions/benjamin/index.ts",+ "src/extensions/agent-instructions/index.ts",+ "src/extensions/skills-store/index.ts","src/extensions/posthog-provider/model-catalog.ts","src/extensions/mcp/config.ts","src/extensions/mcp/schema.ts",diff --git a/products/desktop/packages/shared/package.json b/products/desktop/packages/shared/package.jsonindex 4b112a1a59da..52719fa8b889 100644--- a/products/desktop/packages/shared/package.json+++ b/products/desktop/packages/shared/package.json@@ -32,6 +32,10 @@"types": "./dist/types.d.ts","import": "./dist/types.js"},+ "./task-context": {+ "types": "./dist/task-context.d.ts",+ "import": "./dist/task-context.js"+ },"./deeplink": {"types": "./dist/deeplink.d.ts","import": "./dist/deeplink.js"diff --git a/products/desktop/packages/shared/src/api-http-client.test.ts b/products/desktop/packages/shared/src/api-http-client.test.tsnew file mode 100644index 000000000000..79fb64e9a9f4--- /dev/null+++ b/products/desktop/packages/shared/src/api-http-client.test.ts@@ -0,0 +1,48 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { API_TRANSFER_TIMEOUT_MS, PostHogHttpClient } from "./api-http-client";++const mockFetch = vi.fn();++vi.stubGlobal("fetch", mockFetch);++describe("PostHogHttpClient", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockFetch.mockResolvedValue(new Response());+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("uses the transfer timeout when the caller provides no signal", async () => {+ const timeout = vi.spyOn(AbortSignal, "timeout");+ const client = new PostHogHttpClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 1,+ });++ await client.performRequest("/api/test", { method: "GET" });++ expect(timeout).toHaveBeenCalledWith(API_TRANSFER_TIMEOUT_MS);+ });++ it("preserves a caller-provided signal", async () => {+ const timeout = vi.spyOn(AbortSignal, "timeout");+ const signal = new AbortController().signal;+ const client = new PostHogHttpClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 1,+ });++ await client.performRequest("/api/test", { method: "GET", signal });++ expect(timeout).not.toHaveBeenCalled();+ expect(mockFetch).toHaveBeenCalledWith(+ "https://app.posthog.com/api/test",+ expect.objectContaining({ signal }),+ );+ });+});diff --git a/products/desktop/packages/shared/src/api-http-client.ts b/products/desktop/packages/shared/src/api-http-client.tsnew file mode 100644index 000000000000..1cab24dec45e--- /dev/null+++ b/products/desktop/packages/shared/src/api-http-client.ts@@ -0,0 +1,138 @@+import type { TaskRun } from "./domain-types";+import type { PostHogAPIConfig } from "./task";++export const API_TRANSFER_TIMEOUT_MS = 30_000;+export const API_DOWNLOAD_TIMEOUT_MS = 300_000;+const MIN_TRANSFER_BYTES_PER_MS = 256;++export function transferTimeoutMs(byteLength: number): number {+ return Math.max(+ API_TRANSFER_TIMEOUT_MS,+ Math.ceil(byteLength / MIN_TRANSFER_BYTES_PER_MS),+ );+}++export class PostHogHttpError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "PostHogHttpError";+ }+}++export type TaskRunUpdate = Partial<+ Pick<+ TaskRun,+ "status" | "branch" | "stage" | "error_message" | "output" | "state"+ >+> & {+ state_remove_keys?: string[];+ state_append?: Record<string, unknown>;+};++export interface PostHogHttpClientOptions {+ defaultUserAgent?: string;+ buildError?: (message: string, status: number) => Error;+}++export class PostHogHttpClient {+ constructor(+ private readonly config: PostHogAPIConfig,+ private readonly options: PostHogHttpClientOptions = {},+ ) {}++ get baseUrl(): string {+ return this.config.apiUrl.endsWith("/")+ ? this.config.apiUrl.slice(0, -1)+ : this.config.apiUrl;+ }++ getTeamId(): number {+ return this.config.projectId;+ }++ async resolveApiKey(forceRefresh = false): Promise<string> {+ if (forceRefresh && this.config.refreshApiKey) {+ return this.config.refreshApiKey();+ }+ return this.config.getApiKey();+ }++ private async buildHeaders(+ options: RequestInit,+ forceRefresh = false,+ ): Promise<Headers> {+ const headers = new Headers(options.headers);+ headers.set(+ "Authorization",+ `Bearer ${await this.resolveApiKey(forceRefresh)}`,+ );+ if (!headers.has("Content-Type")) {+ headers.set("Content-Type", "application/json");+ }+ headers.set(+ "User-Agent",+ this.config.userAgent ??+ this.options.defaultUserAgent ??+ "posthog/api-http-client",+ );+ return headers;+ }++ async performRequest(+ endpoint: string,+ options: RequestInit,+ forceRefresh = false,+ ): Promise<Response> {+ const url = `${this.baseUrl}${endpoint}`;+ return fetch(url, {+ ...options,+ signal: options.signal ?? AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),+ headers: await this.buildHeaders(options, forceRefresh),+ });+ }++ async performRequestWithRetry(+ endpoint: string,+ options: RequestInit = {},+ ): Promise<Response> {+ let response = await this.performRequest(endpoint, options);+ if (!response.ok && response.status === 401) {+ response = await this.performRequest(endpoint, options, true);+ }+ return response;+ }++ async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {+ const response = await this.performRequestWithRetry(endpoint, options);+ if (!response.ok) {+ let errorMessage: string;+ try {+ const errorResponse = await response.json();+ errorMessage = `Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`;+ } catch {+ errorMessage = `Failed request: [${response.status}] ${response.statusText}`;+ }+ const buildError =+ this.options.buildError ??+ ((message: string, status: number) =>+ new PostHogHttpError(message, status));+ throw buildError(errorMessage, response.status);+ }+ return (await response.json()) as T;+ }++ async updateTaskRun(+ taskId: string,+ runId: string,+ payload: TaskRunUpdate,+ signal?: AbortSignal,+ ): Promise<TaskRun> {+ return this.request<TaskRun>(+ `/api/projects/${this.getTeamId()}/tasks/${taskId}/runs/${runId}/`,+ { method: "PATCH", body: JSON.stringify(payload), signal },+ );+ }+}diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 568a710452ed..f6c5f0b3e4f7 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -19,6 +19,14 @@ export type {} from "./agent-conversation";export * from "./agent-runtime";export * from "./analytics-events";+export type { TaskRunUpdate } from "./api-http-client";+export {+ API_DOWNLOAD_TIMEOUT_MS,+ API_TRANSFER_TIMEOUT_MS,+ PostHogHttpClient,+ PostHogHttpError,+ transferTimeoutMs,+} from "./api-http-client";export type { ArchivedTask } from "./archive-domain";export { withTimeout } from "./async";export {@@ -281,6 +289,7 @@ export {type PiToolCallRecord,type PiToolName,} from "./pi-tool-call";+export { POSTHOG_PRODUCTS, type PostHogProductId } from "./posthog-products";export {buildPrOutput,mergePrUrls,diff --git a/products/desktop/packages/shared/src/posthog-products.ts b/products/desktop/packages/shared/src/posthog-products.tsnew file mode 100644index 000000000000..e41ec7bbb5e4--- /dev/null+++ b/products/desktop/packages/shared/src/posthog-products.ts@@ -0,0 +1,17 @@+export const POSTHOG_PRODUCTS = {+ product_analytics: "Product analytics",+ web_analytics: "Web analytics",+ feature_flags: "Feature flags",+ experiments: "Experiments",+ error_tracking: "Error tracking",+ session_replay: "Session replay",+ surveys: "Surveys",+ llm_analytics: "AI observability",+ data_warehouse: "Data warehouse",+ cdp: "Data pipelines",+ logs: "Logs",+ apm: "APM",+ sql: "SQL",+} as const;++export type PostHogProductId = keyof typeof POSTHOG_PRODUCTS;diff --git a/products/desktop/packages/shared/src/task-context.ts b/products/desktop/packages/shared/src/task-context.tsnew file mode 100644index 000000000000..59b3fbbed86c--- /dev/null+++ b/products/desktop/packages/shared/src/task-context.ts@@ -0,0 +1,14 @@+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;+}diff --git a/products/desktop/packages/shared/tsup.config.ts b/products/desktop/packages/shared/tsup.config.tsindex 6de68d283487..4a12ee237b1c 100644--- a/products/desktop/packages/shared/tsup.config.ts+++ b/products/desktop/packages/shared/tsup.config.ts@@ -16,6 +16,7 @@ export default defineConfig({"src/product-engineer-prompt.ts","src/quick-ask-shortcuts.ts","src/rich-output-prompt.ts",+ "src/task-context.ts","src/types.ts",],format: ["esm"],diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.stories.tsxindex be1da4f1e7db..2264ec61e275 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.stories.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.stories.tsx@@ -1,8 +1,8 @@import {+ type AcpMessage,POSTHOG_PRODUCTS,type PostHogProductId,-} from "@posthog/agent/posthog-products";-import type { AcpMessage } from "@posthog/shared";+} from "@posthog/shared";import { SessionResourcesBar } from "@posthog/ui/features/sessions/components/SessionResourcesBar";import type { Meta, StoryObj } from "@storybook/react-vite";diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.tsxindex c8607d979d1b..894031b94aa2 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionResourcesBar.tsx@@ -15,8 +15,7 @@ import {TableIcon,VideoIcon,} from "@phosphor-icons/react";-import type { PostHogProductId } from "@posthog/agent/posthog-products";-import type { AcpMessage } from "@posthog/shared";+import type { AcpMessage, PostHogProductId } from "@posthog/shared";import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";import { openUrlInBrowser } from "@posthog/ui/utils/browser";import { Badge, Box, Flex, Text } from "@radix-ui/themes";diff --git a/products/desktop/packages/ui/src/features/sessions/components/accumulateSessionResources.ts b/products/desktop/packages/ui/src/features/sessions/components/accumulateSessionResources.tsindex 03d4a88cf195..bd782a78f113 100644--- a/products/desktop/packages/ui/src/features/sessions/components/accumulateSessionResources.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/accumulateSessionResources.ts@@ -2,8 +2,8 @@ import {isNotification,POSTHOG_NOTIFICATIONS,} from "@posthog/agent/acp-extensions";-import type { PostHogProductId } from "@posthog/agent/posthog-products";import { createAppendOnlyTracker } from "@posthog/core/sessions/appendOnlyTracker";+import type { PostHogProductId } from "@posthog/shared";import { type AcpMessage, isJsonRpcNotification } from "@posthog/shared";export interface ResourceProduct {diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex c8f41e0792aa..b5ae080b6c94 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -44,7 +44,6 @@ 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,@@ -58,7 +57,9 @@ import {import type * as AgentTypes from "@posthog/agent/types";import { execGh } from "@posthog/git/gh";import { getCurrentBranch } from "@posthog/git/queries";+import type { ContextWikiEnv } from "@posthog/harness/extensions/context-wiki";import { fetchPosthogPiModelCatalog } from "@posthog/harness/extensions/posthog-provider/model-catalog";+import { buildTaskSystemPrompt } from "@posthog/harness/extensions/task-system-prompt";import { APP_META_SERVICE, type IAppMeta } from "@posthog/platform/app-meta";import {BUNDLED_RESOURCES_SERVICE,@@ -778,7 +779,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {*/private async mountContextWiki(credentials: Credentials,- ): Promise<AgentTypes.ContextWikiEnv | null> {+ ): Promise<ContextWikiEnv | null> {const authToken = await this.agentAuthAdapter.gatewayAuthToken();if (!authToken) {return null;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.tsindex 5f0249a53f3e..94db38e182e5 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,7 +3,7 @@ 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";+import type { TaskContextInput } from "@posthog/shared/task-context";export interface PiRpcClientFactory {create(diff --git a/products/desktop/pnpm-lock.yaml b/products/desktop/pnpm-lock.yamlindex 5a72711214a7..43fb0edeabf1 100644--- a/products/desktop/pnpm-lock.yaml+++ b/products/desktop/pnpm-lock.yaml@@ -829,9 +829,6 @@ importers:specifier: 4.4.3version: 4.4.3devDependencies:- '@posthog/enricher':- specifier: workspace:*- version: link:../enricher'@posthog/git':specifier: workspace:*version: link:../git@@ -1050,6 +1047,12 @@ importers:'@modelcontextprotocol/sdk':specifier: ^1.29.0version: 1.29.0([email protected])+ '@posthog/enricher':+ specifier: workspace:*+ version: link:../enricher+ '@posthog/git':+ specifier: workspace:*+ version: link:../git'@posthog/shared':specifier: workspace:*version: link:../shareddiff --git a/products/desktop/scripts/sync-benjamin.mts b/products/desktop/scripts/sync-benjamin.mtsindex 852dd3243063..db3717908343 100644--- a/products/desktop/scripts/sync-benjamin.mts+++ b/products/desktop/scripts/sync-benjamin.mts@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";import { readFile, writeFile } from "node:fs/promises";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { assertMitLicense } from "../packages/harness/src/extensions/benjamin/license-guard.ts";const __dirname = dirname(fileURLToPath(import.meta.url));@@ -17,9 +18,9 @@ const VENDOR_DIR = resolve(__dirname,"..","packages",- "agent",+ "harness","src",- "adapters",+ "extensions","benjamin",);const INSTRUCTION_PATH = join(VENDOR_DIR, "instruction.ts");@@ -79,26 +80,6 @@ function toTemplateLiteral(text: string): string {return `\`${escaped}\``;}-export function assertMitLicense(license: string): void {- const required = [- "MIT License",- "Permission is hereby granted, free of charge",- 'THE SOFTWARE IS PROVIDED "AS IS"',- ];- for (const marker of required) {- if (!license.includes(marker)) {- throw new Error(- `Upstream ${LICENSE_FILE} no longer looks like the expected MIT license (missing "${marker}") - review it before syncing`,- );- }- }- if (license.includes("*/")) {- throw new Error(- `Upstream ${LICENSE_FILE} contains a block-comment terminator ("*/"), which would escape the generated banner and execute as code - review it before syncing`,- );- }-}-function renderInstructionModule(instruction: string,license: string,