Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions packages/agent/src/adapters/claude/claude-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,8 @@ import {
type FileEnrichmentDeps,
} from "../../enrichment/file-enricher";
import type { PostHogAPIConfig } from "../../types";
import {
isCloudRun,
resolveGithubToken,
unreachable,
withTimeout,
} from "../../utils/common";
import { isCloudRun, unreachable, withTimeout } from "../../utils/common";
import { resolveGithubToken } from "../../utils/github-token";
import { Logger } from "../../utils/logger";
import { Pushable } from "../../utils/streams";
import { BaseAcpAgent } from "../base-acp-agent";
Expand Down
3 changes: 2 additions & 1 deletion packages/agent/src/adapters/codex/codex-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ import {
type PermissionMode,
} from "../../execution-mode";
import type { PostHogAPIConfig, ProcessSpawnedCallback } from "../../types";
import { isCloudRun, resolveGithubToken } from "../../utils/common";
import { isCloudRun } from "../../utils/common";
import { resolveGithubToken } from "../../utils/github-token";
import { Logger } from "../../utils/logger";
import {
nodeReadableToWebReadable,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isCloudRun, resolveGithubToken } from "../../../utils/common";
import { isCloudRun } from "../../../utils/common";
import { resolveGithubToken } from "../../../utils/github-token";
import {
runSignedCommitTool,
SIGNED_COMMIT_TOOL_DESCRIPTION,
Expand All @@ -21,7 +22,10 @@ export const signedCommitTool = defineLocalTool({
alwaysLoad: true,
isEnabled: (_ctx, meta) => isCloudRun(meta),
handler: (ctx, args) => {
const token = ctx.token ?? resolveGithubToken();
// Prefer a freshly-resolved token (reads the live agentsh env file) over
// the one captured at session setup, so a mid-session credential refresh
// takes effect without rebuilding the session.
const token = resolveGithubToken() ?? ctx.token;
if (!token) {
return Promise.resolve({
content: [
Expand Down
16 changes: 16 additions & 0 deletions packages/agent/src/server/agent-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,22 @@ export class AgentServer {
const mcpServers = Array.isArray(params.mcpServers)
? params.mcpServers
: [];
const refreshedCredentials = Array.isArray(params.refreshedCredentials)
? (params.refreshedCredentials as string[])
: [];
const authorship =
typeof params.authorship === "string" ? params.authorship : "";

if (refreshedCredentials.length > 0) {
const owner = authorship ? ` (${authorship})` : "";
this.logger.debug(
`Refreshed sandbox credentials${owner}: ${refreshedCredentials.join(", ")}`,
);
}

if (mcpServers.length === 0) {
return { refreshed: true };
}

this.logger.debug("Refresh session requested", {
serverCount: mcpServers.length,
Expand Down
6 changes: 0 additions & 6 deletions packages/agent/src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { readGithubTokenFromEnv } from "@posthog/git/signed-commit";
import type { Logger } from "./logger";

/**
Expand Down Expand Up @@ -39,11 +38,6 @@ export function isCloudRun(
return !!process.env.IS_SANDBOX;
}

/** The GitHub token available to the sandbox, if any. */
export function resolveGithubToken(): string | undefined {
return readGithubTokenFromEnv();
}

export function unreachable(value: never, logger: Logger): void {
let valueAsString: string;
try {
Expand Down
76 changes: 76 additions & 0 deletions packages/agent/src/utils/github-token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
readGithubTokenFromSandboxEnvFile,
resolveGithubToken,
} from "./github-token";

function writeEnvFile(contents: string): string {
const dir = mkdtempSync(join(tmpdir(), "agent-env-"));
const path = join(dir, "agent-env");
writeFileSync(path, contents);
return path;
}

describe("github-token", () => {
describe("readGithubTokenFromSandboxEnvFile", () => {
it.each([
{
name: "GH_TOKEN",
contents: "PATH=/usr/bin\0GH_TOKEN=ghs_fresh123\0HOME=/root\0",
expected: "ghs_fresh123",
},
{
name: "GITHUB_TOKEN when GH_TOKEN is absent",
contents: "GITHUB_TOKEN=ghu_user456\0PATH=/usr/bin\0",
expected: "ghu_user456",
},
])(
"reads $name from the NUL-delimited env file",
({ contents, expected }) => {
expect(readGithubTokenFromSandboxEnvFile(writeEnvFile(contents))).toBe(
expected,
);
},
);

it("reflects an updated file (live read, not cached)", () => {
const path = writeEnvFile("GH_TOKEN=ghs_old\0");
expect(readGithubTokenFromSandboxEnvFile(path)).toBe("ghs_old");
writeFileSync(path, "GH_TOKEN=ghs_new\0");
expect(readGithubTokenFromSandboxEnvFile(path)).toBe("ghs_new");
});

it("returns undefined when the file is missing", () => {
expect(
readGithubTokenFromSandboxEnvFile("/nonexistent/agent-env"),
).toBeUndefined();
});

it("ignores an empty token value", () => {
const path = writeEnvFile("GH_TOKEN=\0GITHUB_TOKEN=ghs_real\0");
expect(readGithubTokenFromSandboxEnvFile(path)).toBe("ghs_real");
});
});

describe("resolveGithubToken", () => {
afterEach(() => {
vi.unstubAllEnvs();
});

it("prefers the sandbox env file over the process env", () => {
vi.stubEnv("GH_TOKEN", "ghs_fromprocess");
const path = writeEnvFile("GH_TOKEN=ghs_fromfile\0");
expect(resolveGithubToken(path)).toBe("ghs_fromfile");
});

it("falls back to the process env when the sandbox file is absent", () => {
vi.stubEnv("GH_TOKEN", "ghs_fromprocess");
expect(resolveGithubToken("/nonexistent/agent-env")).toBe(
"ghs_fromprocess",
);
});
});
});
44 changes: 44 additions & 0 deletions packages/agent/src/utils/github-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { readFileSync } from "node:fs";
import { readGithubTokenFromEnv } from "@posthog/git/signed-commit";

// helpers for resolving the in-sandbox GitHub token
// agentsh env file (NUL-delimited `key=value` pairs) that the PostHog backend
// rewrites in place when it refreshes the sandbox's GitHub credentials
// mid-session. The agent-server process env is frozen at launch, so reading
// this live file is how in-process tools pick up a refreshed token without a
// process restart.
export const SANDBOX_ENV_FILE = "/tmp/agent-env";

export function readGithubTokenFromSandboxEnvFile(
envFilePath: string = SANDBOX_ENV_FILE,
): string | undefined {
try {
const raw = readFileSync(envFilePath, "utf8");
Comment thread
tatoalo marked this conversation as resolved.
const env: Record<string, string> = {};
for (const entry of raw.split("\0")) {
const eq = entry.indexOf("=");
if (eq > 0) {
env[entry.slice(0, eq)] = entry.slice(eq + 1);
}
}
// Reuse the shared token-var allowlist + precedence instead of hardcoding.
return readGithubTokenFromEnv(env);
} catch {
// No env file (local/desktop or test) — fall back to the process env.
}
return undefined;
}

/** The GitHub token available to the sandbox, if any.
*
* Prefers the live agentsh env file (refreshed in place mid-session) over the
* process env (frozen at launch) so long-running in-process tools — e.g. the
* signed-commit tool — pick up a refreshed token without a restart.
*/
export function resolveGithubToken(
envFilePath: string = SANDBOX_ENV_FILE,
): string | undefined {
return (
readGithubTokenFromSandboxEnvFile(envFilePath) ?? readGithubTokenFromEnv()
);
}
Loading