Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): inject benjamin-plus instruction in cloud agent sessions (#91505)

Alessandro Pogliaghi43a3fa76ef5d
diff --git a/.github/workflows/desktop-sync-benjamin.yml b/.github/workflows/desktop-sync-benjamin.yml
new file mode 100644
index 000000000000..5004b5e233e5
--- /dev/null
+++ b/.github/workflows/desktop-sync-benjamin.yml
@@ -0,0 +1,164 @@
+name: Desktop Sync Benjamin
+
+on:
+ schedule:
+ - cron: '0 6 * * MON'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: desktop-sync-benjamin
+ cancel-in-progress: false
+
+jobs:
+ sync-benjamin:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ env:
+ SYNC_BRANCH: chore/sync-benjamin
+
+ steps:
+ - name: Guard - only run on master
+ env:
+ REF: ${{ github.ref }}
+ run: |
+ if [ "$REF" != "refs/heads/master" ]; then
+ echo "::error::This workflow can only run on master (got $REF). Re-dispatch it from master."
+ exit 1
+ fi
+
+ - name: Get app token
+ id: app-token
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ vars.GH_APP_POSTHOG_SCHEDULED_ACTIONS_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_SCHEDULED_ACTIONS_PRIVATE_KEY }}
+
+ - name: Checkout repository
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ token: ${{ steps.app-token.outputs.token }}
+ sparse-checkout: |
+ .nvmrc
+ products/desktop/scripts/sync-benjamin.mts
+ products/desktop/packages/agent/src/adapters/benjamin
+ sparse-checkout-cone-mode: false
+
+ - name: Set up Node
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version-file: .nvmrc
+
+ - name: Sync the vendored instruction
+ env:
+ GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
+ run: node products/desktop/scripts/sync-benjamin.mts
+
+ - name: Check for changes
+ id: check-changes
+ run: |
+ if git diff --quiet products/desktop/packages/agent/src/adapters/benjamin; then
+ echo "changes=false" >> $GITHUB_OUTPUT
+ echo "Vendored instruction is already at the upstream tip"
+ else
+ echo "changes=true" >> $GITHUB_OUTPUT
+ git diff --stat products/desktop/packages/agent/src/adapters/benjamin
+ fi
+
+ - name: Find the open sync PR
+ id: find-pr
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ run: |
+ pr=$(gh pr list --head "$SYNC_BRANCH" --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number' 2>/dev/null || true)
+ echo "number=$pr" >> "$GITHUB_OUTPUT"
+
+ - name: Clean up stale sync PR
+ if: steps.check-changes.outputs.changes == 'false' && steps.find-pr.outputs.number != ''
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ STALE_PR: ${{ steps.find-pr.outputs.number }}
+ run: |
+ gh pr close "$STALE_PR" --delete-branch || true
+ echo "Closed stale PR #$STALE_PR and deleted branch"
+
+ - name: Read the pinned commit
+ id: lock
+ if: steps.check-changes.outputs.changes == 'true'
+ run: |
+ commit=$(jq -r .commit products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.json)
+ echo "commit=$commit" >> $GITHUB_OUTPUT
+
+ - name: Build PR body
+ if: steps.check-changes.outputs.changes == 'true'
+ env:
+ COMMIT: ${{ steps.lock.outputs.commit }}
+ run: |
+ {
+ echo "Upstream bump of the vendored Benjamin-Plus instruction."
+ echo
+ echo "- Source: [JetBrains/benjamin-plus-skill@\`$COMMIT\`](https://github.com/JetBrains/benjamin-plus-skill/commit/$COMMIT)"
+ echo "- Regenerated by \`products/desktop/scripts/sync-benjamin.mts\`, which verifies the file against upstream \`SHA256SUMS.txt\` before writing."
+ echo
+ echo "**Do not merge unattended.** The instruction ships into every cloud agent session that runs with \`POSTHOG_BENJAMIN=1\`, so a human has to:"
+ echo
+ echo "1. read the instruction diff, and"
+ echo "2. re-run the token-efficiency benchmark before this lands."
+ } > "$RUNNER_TEMP/pr-body.md"
+
+ - name: Reset branch to checked-out SHA
+ if: steps.check-changes.outputs.changes == 'true'
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ TARGET_SHA: ${{ github.sha }}
+ run: |
+ if gh api "repos/${{ github.repository }}/git/ref/heads/$SYNC_BRANCH" >/dev/null 2>&1; then
+ gh api -X PATCH "repos/${{ github.repository }}/git/refs/heads/$SYNC_BRANCH" \
+ -f sha="$TARGET_SHA" -F force=true
+ else
+ gh api repos/${{ github.repository }}/git/refs -f ref="refs/heads/$SYNC_BRANCH" -f sha="$TARGET_SHA"
+ fi
+
+ - name: Commit via GitHub API (signed)
+ if: steps.check-changes.outputs.changes == 'true'
+ uses: planetscale/ghcommit-action@25309d8005ac7c3bcd61d3fe19b69e0fe47dbdde # v0.2.20
+ with:
+ commit_message: 'chore(tasks): bump vendored benjamin-plus instruction'
+ repo: ${{ github.repository }}
+ branch: ${{ env.SYNC_BRANCH }}
+ file_pattern: 'products/desktop/packages/agent/src/adapters/benjamin'
+ env:
+ GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
+
+ - name: Create or update pull request
+ if: steps.check-changes.outputs.changes == 'true'
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ PREVIOUS_PR: ${{ steps.find-pr.outputs.number }}
+ run: |
+ existing_pr=$(gh pr list --head "$SYNC_BRANCH" --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number' 2>/dev/null || true)
+ if [ -n "$existing_pr" ]; then
+ gh pr edit "$existing_pr" --body-file "$RUNNER_TEMP/pr-body.md"
+ is_draft=$(gh pr view "$existing_pr" --json isDraft --jq '.isDraft')
+ if [ "$is_draft" = "false" ]; then
+ gh pr ready --undo "$existing_pr"
+ gh pr comment "$existing_pr" --body "The vendored instruction changed after this PR was marked ready. It is back in draft: re-read the diff and re-run the benchmark before merging." || true
+ fi
+ else
+ if [ -n "$PREVIOUS_PR" ]; then
+ printf '\nSupersedes #%s.\n' "$PREVIOUS_PR" >> "$RUNNER_TEMP/pr-body.md"
+ fi
+ new_pr_url=$(gh pr create \
+ --draft \
+ --title "chore(tasks): bump vendored benjamin-plus instruction" \
+ --body-file "$RUNNER_TEMP/pr-body.md" \
+ --base master \
+ --head "$SYNC_BRANCH" \
+ --label "automated" --label "dependencies")
+ echo "Created $new_pr_url"
+ if [ -n "$PREVIOUS_PR" ]; then
+ gh pr comment "$PREVIOUS_PR" --body "Superseded by $new_pr_url" || true
+ fi
+ fi
diff --git a/products/desktop/knip.json b/products/desktop/knip.json
index a6eabc2df815..e15fe385788a 100644
--- a/products/desktop/knip.json
+++ b/products/desktop/knip.json
@@ -2,7 +2,11 @@
"$schema": "https://unpkg.com/knip@latest/schema.json",
"workspaces": {
".": {
- "entry": ["mprocs.yaml", "postcss.config.mjs", "scripts/*.{mjs,js,ts}"],
+ "entry": [
+ "mprocs.yaml",
+ "postcss.config.mjs",
+ "scripts/*.{mjs,js,ts,mts}"
+ ],
"ignoreBinaries": ["bin/phrocs"]
},
"apps/code": {
diff --git a/products/desktop/package.json b/products/desktop/package.json
index 17632184e717..2cb45bcc9031 100644
--- a/products/desktop/package.json
+++ b/products/desktop/package.json
@@ -35,6 +35,7 @@
"format": "biome format --write",
"clean": "pnpm -r clean",
"knip": "knip",
+ "benjamin:sync": "node scripts/sync-benjamin.mts",
"skills:local": "node scripts/sync-local-skills.mjs",
"skills:pull": "node scripts/pull-skills.mjs",
"hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD=1 pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.md
index 5ae4b50303a5..3a46fb1bae1f 100644
--- a/products/desktop/packages/agent/README.md
+++ b/products/desktop/packages/agent/README.md
@@ -165,6 +165,10 @@ Required environment variables (validated by zod in `src/server/bin.ts`):
- `POSTHOG_PERSONAL_API_KEY` — API key for PostHog requests
- `POSTHOG_PROJECT_ID` — numeric project ID
+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.
+
Optional run telemetry (the logs pair must both be set, otherwise telemetry stays off):
- `POSTHOG_AGENT_OTEL_LOGS_URL` — full OTLP logs URL for run metadata, e.g. `https://us.i.posthog.com/i/v1/logs`
diff --git a/products/desktop/packages/agent/src/adapters/benjamin-guidance.test.ts b/products/desktop/packages/agent/src/adapters/benjamin-guidance.test.ts
new file mode 100644
index 000000000000..9d7ef48d86bd
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/benjamin-guidance.test.ts
@@ -0,0 +1,108 @@
+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";
+
+const MARKER = "BENJAMIN-PLUS MODE ACTIVE";
+
+const lock = JSON.parse(
+ readFileSync(
+ new URL("./benjamin/benjamin.lock.json", import.meta.url),
+ "utf8",
+ ),
+) as { commit: string; sha256: string };
+
+describe("benjamin guidance", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ describe("isBenjaminEnabled", () => {
+ test("is off when POSTHOG_BENJAMIN is unset", () => {
+ expect(isBenjaminEnabled({})).toBe(false);
+ });
+
+ test.each([["1"], ["true"], ["TRUE"], [" 1 "]])("is on for %j", (value) => {
+ expect(isBenjaminEnabled({ POSTHOG_BENJAMIN: value })).toBe(true);
+ });
+
+ test.each([[""], ["0"], ["false"], ["yes"], ["on"]])(
+ "is off for %j",
+ (value) => {
+ expect(isBenjaminEnabled({ POSTHOG_BENJAMIN: value })).toBe(false);
+ },
+ );
+ });
+
+ describe("appendBenjaminGuidance", () => {
+ test("appends the instruction when enabled", () => {
+ const result = appendBenjaminGuidance("base instructions", {
+ POSTHOG_BENJAMIN: "1",
+ });
+ expect(result.startsWith("base instructions\n\n")).toBe(true);
+ expect(result).toContain(MARKER);
+ });
+
+ test("returns instructions unchanged when unset", () => {
+ expect(appendBenjaminGuidance("base instructions", {})).toBe(
+ "base instructions",
+ );
+ });
+
+ test("does not leave a leading separator when instructions are empty", () => {
+ expect(
+ appendBenjaminGuidance("", { POSTHOG_BENJAMIN: "1" }).startsWith(
+ MARKER,
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe("claude session prompt", () => {
+ test("carries the instruction when enabled", () => {
+ vi.stubEnv("POSTHOG_BENJAMIN", "1");
+ expect(buildAppendedInstructions({ spokenNarration: false })).toContain(
+ MARKER,
+ );
+ });
+
+ test("leaves the prompt untouched when unset", () => {
+ expect(
+ buildAppendedInstructions({ spokenNarration: false }),
+ ).not.toContain(MARKER);
+ });
+ });
+
+ describe("vendored instruction", () => {
+ test("matches the sha256 recorded in benjamin.lock.json", () => {
+ const digest = createHash("sha256")
+ .update(Buffer.from(BENJAMIN_INSTRUCTION, "utf8"))
+ .digest("hex");
+ expect(digest).toBe(lock.sha256);
+ });
+
+ test("reports a short prefix of the pinned upstream commit", () => {
+ expect(lock.commit.startsWith(BENJAMIN_UPSTREAM_COMMIT)).toBe(true);
+ });
+ });
+
+ describe("sync license guard", () => {
+ test("rejects a license that would escape the banner comment", () => {
+ const mitLicense = [
+ "MIT License",
+ "Permission is hereby granted, free of charge, to any person obtaining a copy",
+ 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.',
+ ].join("\n");
+ expect(() => assertMitLicense(mitLicense)).not.toThrow();
+ expect(() =>
+ assertMitLicense(`${mitLicense}\n*/ globalThis.pwned = true; /*`),
+ ).toThrow(/block-comment terminator/);
+ });
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/benjamin-guidance.ts b/products/desktop/packages/agent/src/adapters/benjamin-guidance.ts
new file mode 100644
index 000000000000..f2315400e96c
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/benjamin-guidance.ts
@@ -0,0 +1,18 @@
+import { BENJAMIN_INSTRUCTION } from "./benjamin/instruction";
+
+const BENJAMIN_GUIDANCE = BENJAMIN_INSTRUCTION.trim();
+
+export function isBenjaminEnabled(
+ env: NodeJS.ProcessEnv = process.env,
+): boolean {
+ const value = env.POSTHOG_BENJAMIN?.trim().toLowerCase();
+ return value === "1" || value === "true";
+}
+
+export function appendBenjaminGuidance(
+ instructions: string,
+ env: NodeJS.ProcessEnv = process.env,
+): string {
+ if (!isBenjaminEnabled(env)) return instructions;
+ return [instructions, BENJAMIN_GUIDANCE].filter(Boolean).join("\n\n");
+}
diff --git a/products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.json b/products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.json
new file mode 100644
index 000000000000..0ca344138db7
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/benjamin/benjamin.lock.json
@@ -0,0 +1,7 @@
+{
+ "repo": "JetBrains/benjamin-plus-skill",
+ "commit": "0f7b2df6887d18afb73e60b3a696e765e86eea5b",
+ "file": "injected-instruction.md",
+ "sha256": "8d323e74e82ea1ba853cf995ccb5a6b662205ba14e875eaf520157c5def531e8",
+ "fetched_at": "2026-08-31"
+}
diff --git a/products/desktop/packages/agent/src/adapters/benjamin/instruction.ts b/products/desktop/packages/agent/src/adapters/benjamin/instruction.ts
new file mode 100644
index 000000000000..6c2c54d108b4
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/benjamin/instruction.ts
@@ -0,0 +1,93 @@
+/**
+ * @license
+ * Benjamin-Plus injected instruction, vendored from JetBrains/benjamin-plus-skill.
+ * Upstream: https://github.com/JetBrains/benjamin-plus-skill
+ * Commit: 0f7b2df6887d18afb73e60b3a696e765e86eea5b
+ * File: injected-instruction.md (sha256 8d323e74e82ea1ba853cf995ccb5a6b662205ba14e875eaf520157c5def531e8)
+ *
+ * MIT License
+ *
+ * Copyright (c) 2026 benjamin-plus contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * Generated by scripts/sync-benjamin.mts - do not edit by hand.
+ */
+
+export const BENJAMIN_UPSTREAM_COMMIT = "0f7b2df";
+
+export const BENJAMIN_INSTRUCTION = `BENJAMIN-PLUS MODE ACTIVE
+
+# Benjamin-Plus
+
+Every request you send re-reads the whole conversation so far. The bill is
+steps × context, not words. Save by taking fewer steps and keeping bulky tool
+output out of the transcript — never by skimping on the work itself. Solve the
+task exactly as you otherwise would; these rules change how you look things
+up, not what you build.
+
+**1. Recon in one pass.**
+Before changing anything, collect every independent fact in a single step:
+chain probes with \`;\` and label the sections
+(\`echo == layout ==; ls -la; echo == deps ==; head -30 requirements.txt\`),
+or issue several tool calls in one message. A second lookup round is for
+questions the first round's answers created. Copying a convention (a DSL,
+schema, or file format)? Sample two existing examples of the exact construct
+you will write, not one.
+
+**2. Look through a keyhole.**
+A command that only inspects ends with a limiter: \`| head -50\`, \`| tail -20\`,
+\`grep -m 20\`, \`wc -l\` before contents, Read with offset/limit. Size unknown?
+Measure first, then read the slice you need. Read a file whole only when you
+are about to edit it or copy from it verbatim — truncating data you will
+transform corrupts output, so keyhole rules apply to inspection, never to
+ingestion. If a peek was too narrow, take exactly one wider look.
+
+**3. Probe the environment once.**
+Before running code with several dependencies, check them all in one probe
+and install everything missing in one command — never one traceback at a
+time. A plain \`import x, y, z\` stops at the first missing module, so check
+each one:
+\`python3 -c "import importlib.util as u; [print(m) for m in ['x','y','z'] if not u.find_spec(m)]"\`
+and \`command -v tool1 tool2\` for binaries.
+
+**4. Green means the task's own check.**
+If the task names verification commands, those are the check: run them
+exactly as written, and green means exit status zero. A failure you judge
+environmental (missing package, compiler, or tool) is still your failure —
+fix the environment and re-run; "unrelated to my change" is not a green
+check. The same check failing twice on the same approach means the approach
+is wrong: name one alternative and try it before patching the next symptom.
+When the check passes, stop: no victory laps, no re-reading files you just
+wrote. Close with at most two lines.
+
+**5. Polling is a step.**
+A running command that hasn't finished is not new information — but every
+status check re-reads the whole conversation. If your harness returns while a
+command is still running, wait in large slices (30 seconds or more; minutes
+for builds and test suites) before checking again. Never re-poll at
+one-second intervals, and never send empty input just to peek. Where
+execution blocks until completion, this rule costs nothing.
+
+Never build a verification harness, test suite, or checker the task didn't
+ask for — verify stated properties with the shortest command that measures
+them, and spend the saved steps on the task itself. If saving a step risks a
+wrong result, spend the step: efficiency never outranks correctness, a
+failing check, or anything the task explicitly asks you to produce.
+`;
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts b/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts
index 93e611c76c57..7d65643b9baf 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/instructions.ts
@@ -1,4 +1,5 @@
import { buildContextWikiInstructions } from "../../../context-wiki";
+import { appendBenjaminGuidance } from "../../benjamin-guidance";
const BRANCH_NAMING = `
# Branch Naming
@@ -113,5 +114,8 @@ export function buildAppendedInstructions(opts: {
if (opts.contextWikiPath) {
instructions += buildContextWikiInstructions(opts.contextWikiPath);
}
- return opts.spokenNarration ? instructions + SPOKEN_NARRATION : instructions;
+ if (opts.spokenNarration) {
+ instructions += SPOKEN_NARRATION;
+ }
+ return appendBenjaminGuidance(instructions);
}
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 79d8cd7b8bc6..33e204669863 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -4282,6 +4282,10 @@ describe("AgentServer HTTP Mode", () => {
});
describe("runtime adapter selection", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
it("defaults to claude when no runtime adapter is configured", () => {
const s = createServer();
@@ -4321,6 +4325,29 @@ describe("AgentServer HTTP Mode", () => {
(s as unknown as TestableServer).buildCodexInstructions(sessionPrompt),
).toContain("Cloud Task Execution");
});
+
+ it("injects benjamin into codex instructions when POSTHOG_BENJAMIN is set", () => {
+ vi.stubEnv("POSTHOG_BENJAMIN", "1");
+ const s = createServer({ runtimeAdapter: "codex" });
+ const sessionPrompt = (
+ s as unknown as TestableServer
+ ).buildSessionSystemPrompt();
+
+ expect(
+ (s as unknown as TestableServer).buildCodexInstructions(sessionPrompt),
+ ).toContain("BENJAMIN-PLUS MODE ACTIVE");
+ });
+
+ it("omits benjamin from codex instructions when POSTHOG_BENJAMIN is unset", () => {
+ const s = createServer({ runtimeAdapter: "codex" });
+ const sessionPrompt = (
+ s as unknown as TestableServer
+ ).buildSessionSystemPrompt();
+
+ expect(
+ (s as unknown as TestableServer).buildCodexInstructions(sessionPrompt),
+ ).not.toContain("BENJAMIN-PLUS MODE ACTIVE");
+ });
});
describe("buildClaudeCodeSessionMeta", () => {
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index cea032c5cd36..0a88f268c029 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -53,6 +53,11 @@ 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,
@@ -2251,6 +2256,9 @@ export class AgentServer {
this.posthogAPI
.updateTaskRun(payload.task_id, payload.run_id, {
status: "in_progress",
+ ...(isBenjaminEnabled() && {
+ state: { benjamin_version: BENJAMIN_UPSTREAM_COMMIT },
+ }),
})
.catch((err) =>
this.logger.debug("Failed to set task run to in_progress", err),
@@ -3850,7 +3858,7 @@ export class AgentServer {
typeof systemPrompt === "string" ? systemPrompt : systemPrompt.append;
// Codex has no command-rewrite hook (see rtk-guidance.ts), so RTK is
// adopted through the developer instructions instead.
- return appendRtkGuidanceForCodex(instructions);
+ return appendBenjaminGuidance(appendRtkGuidanceForCodex(instructions));
}
/**
diff --git a/products/desktop/packages/core/src/billing/leanSkills.ts b/products/desktop/packages/core/src/billing/leanSkills.ts
index dfaa12f33d58..05656f245f84 100644
--- a/products/desktop/packages/core/src/billing/leanSkills.ts
+++ b/products/desktop/packages/core/src/billing/leanSkills.ts
@@ -9,9 +9,10 @@
*
* Deliberately absent: JetBrains/benjamin-plus-skill. Its ruleset measured
* -17.9% cost, the best of any of these, but it only works injected into the
- * system prompt. Its authors measured the same text as a skill folder at
- * -0.5%, so no one-click install can deliver it. Adopting it means shipping
- * the rules in the prompt every harness appends, which is its own change.
+ * 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.
*/
export interface LeanSkill {
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index be1d0b7dc0e4..8bc6a2757ae6 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -314,6 +314,7 @@ export function readPendingFollowupMessages(
const taskRunStateFields = {
ai_stage: optionalField(z.string()),
auto_publish: optionalField(z.boolean()),
+ benjamin_version: optionalField(z.string()),
initial_permission_mode: optionalField(executionModeSchema),
initial_prompt_override: optionalField(z.string()),
pending_followup_messages: optionalField(
diff --git a/products/desktop/scripts/sync-benjamin.mts b/products/desktop/scripts/sync-benjamin.mts
new file mode 100644
index 000000000000..852dd3243063
--- /dev/null
+++ b/products/desktop/scripts/sync-benjamin.mts
@@ -0,0 +1,204 @@
+#!/usr/bin/env node
+
+import { createHash } from "node:crypto";
+import { readFile, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const REPO = "JetBrains/benjamin-plus-skill";
+const FILE = "injected-instruction.md";
+const CHECKSUMS_FILE = "SHA256SUMS.txt";
+const LICENSE_FILE = "LICENSE";
+const REF = process.env.BENJAMIN_REF ?? "main";
+
+const VENDOR_DIR = resolve(
+ __dirname,
+ "..",
+ "packages",
+ "agent",
+ "src",
+ "adapters",
+ "benjamin",
+);
+const INSTRUCTION_PATH = join(VENDOR_DIR, "instruction.ts");
+const LOCK_PATH = join(VENDOR_DIR, "benjamin.lock.json");
+
+interface BenjaminLock {
+ repo: string;
+ commit: string;
+ file: string;
+ sha256: string;
+ fetched_at: string;
+}
+
+function githubHeaders(accept: string): Record<string, string> {
+ const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
+ return {
+ accept,
+ "user-agent": "posthog-sync-benjamin",
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
+ };
+}
+
+async function fetchText(url: string, accept: string): Promise<string> {
+ const response = await fetch(url, { headers: githubHeaders(accept) });
+ if (!response.ok) {
+ throw new Error(`GET ${url} failed with ${response.status}`);
+ }
+ return response.text();
+}
+
+async function resolveCommit(ref: string): Promise<string> {
+ const sha = (
+ await fetchText(
+ `https://api.github.com/repos/${REPO}/commits/${ref}`,
+ "application/vnd.github.sha",
+ )
+ ).trim();
+ if (!/^[0-9a-f]{40}$/.test(sha)) {
+ throw new Error(`Unexpected commit sha for ${REPO}@${ref}: ${sha}`);
+ }
+ return sha;
+}
+
+function parseExpectedChecksum(checksums: string, file: string): string {
+ for (const line of checksums.split("\n")) {
+ const [digest, name] = line.trim().split(/\s+/);
+ if (name === file && digest) return digest;
+ }
+ throw new Error(`${CHECKSUMS_FILE} has no entry for ${file}`);
+}
+
+function toTemplateLiteral(text: string): string {
+ const escaped = text
+ .replace(/\\/g, "\\\\")
+ .replace(/`/g, "\\`")
+ .replace(/\$\{/g, "\\${");
+ 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,
+ commit: string,
+ sha256: string,
+): string {
+ const licenseLines = license
+ .trim()
+ .split("\n")
+ .map((line) => ` * ${line}`.trimEnd())
+ .join("\n");
+ return `/**
+ * @license
+ * Benjamin-Plus injected instruction, vendored from ${REPO}.
+ * Upstream: https://github.com/${REPO}
+ * Commit: ${commit}
+ * File: ${FILE} (sha256 ${sha256})
+ *
+${licenseLines}
+ *
+ * Generated by scripts/sync-benjamin.mts - do not edit by hand.
+ */
+
+export const BENJAMIN_UPSTREAM_COMMIT = "${commit.slice(0, 7)}";
+
+export const BENJAMIN_INSTRUCTION = ${toTemplateLiteral(instruction)};
+`;
+}
+
+async function readLock(): Promise<BenjaminLock | null> {
+ try {
+ return JSON.parse(await readFile(LOCK_PATH, "utf8")) as BenjaminLock;
+ } catch {
+ return null;
+ }
+}
+
+async function syncBenjamin(ref: string): Promise<{
+ commit: string;
+ sha256: string;
+ changed: boolean;
+}> {
+ const commit = await resolveCommit(ref);
+ const base = `https://raw.githubusercontent.com/${REPO}/${commit}`;
+ const [instruction, checksums, license, existing, current] =
+ await Promise.all([
+ fetchText(`${base}/${FILE}`, "text/plain"),
+ fetchText(`${base}/${CHECKSUMS_FILE}`, "text/plain"),
+ fetchText(`${base}/${LICENSE_FILE}`, "text/plain"),
+ readLock(),
+ readFile(INSTRUCTION_PATH, "utf8").catch(() => ""),
+ ]);
+ assertMitLicense(license);
+
+ const sha256 = createHash("sha256")
+ .update(Buffer.from(instruction, "utf8"))
+ .digest("hex");
+ const expected = parseExpectedChecksum(checksums, FILE);
+ if (sha256 !== expected) {
+ throw new Error(
+ `Checksum mismatch for ${FILE} at ${commit}: got ${sha256}, ${CHECKSUMS_FILE} says ${expected}`,
+ );
+ }
+
+ const rendered = renderInstructionModule(
+ instruction,
+ license,
+ commit,
+ sha256,
+ );
+ if (existing && current === rendered) {
+ return { commit, sha256, changed: false };
+ }
+
+ const lock: BenjaminLock = {
+ repo: REPO,
+ commit,
+ file: FILE,
+ sha256,
+ fetched_at: new Date().toISOString().slice(0, 10),
+ };
+ await Promise.all([
+ writeFile(INSTRUCTION_PATH, rendered, "utf8"),
+ writeFile(LOCK_PATH, `${JSON.stringify(lock, null, 2)}\n`, "utf8"),
+ ]);
+ return { commit, sha256, changed: true };
+}
+
+async function main(): Promise<void> {
+ const result = await syncBenjamin(REF);
+ console.log(
+ result.changed
+ ? `Vendored ${REPO}@${result.commit} (${FILE}, sha256 ${result.sha256})`
+ : `Already at ${REPO}@${result.commit} - nothing to write`,
+ );
+}
+
+if (
+ process.argv[1] &&
+ resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ await main();
+}