mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(github): silence anonymous sandbox launchers and auto-request GitHub connection on unconfigured git auth failures (#22954)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Sandboxed runs wrap `git` and `gh` with broker launchers so agents do not inherit ambient host credentials, and task feeds use `connection_intent` cards to let users connect services inline. > - When a workspace has no GitHub connection configured, anonymous sandbox launchers logged `Paperclip: GitHub capability_missing; continuing without managed credentials.` on every `git` or `gh` call, and failed local `gh --version`/`--help` commands. > - In addition, when an agent tried to clone a private GitHub repository, push to GitHub, or run `gh` without a GitHub connection configured, the task feed did not prompt the user with a GitHub connection card. > - Both issues hurt first-run clarity: noisy `capability_missing` warnings look like broken infrastructure, while unconfigured git auth failures leave users without an inline path to connect GitHub. > - This pull request marks intentional anonymous sandbox launchers silent, treats local `gh` version/help commands as local, and automatically attaches a `github` `connection_intent` card in the task feed when a run hits an unambiguous unconfigured GitHub auth failure. > - The benefit is clean anonymous git/gh execution and a one-click inline GitHub setup card when a task needs private GitHub access. ## Linked Issues or Issue Description **What happened?** In sandboxes without a GitHub connection configured, running `git` (such as `git --version` or public clones) logged `Paperclip: GitHub capability_missing; continuing without managed credentials.` and `gh --version` / `gh --help` attempted broker resolution. When an agent tried an authenticated GitHub operation (such as cloning a private repository, pushing, or running `gh`), the run failed or reported the auth error without showing a GitHub connection card in the task feed. **Expected behavior** Anonymous unconfigured sandbox launchers should run public/local `git` and local `gh` commands silently without emitting `capability_missing` warnings, while keeping `capability_missing` diagnostics for genuinely missing or failed-bridge broker configs. When an agent hits an unconfigured GitHub authentication failure during a task run or workspace clone, Paperclip should attach a `github` connection card in the task feed and mark run liveness as blocked waiting for the user. **Steps to reproduce** 1. Run an agent in a sandbox with no GitHub connection configured. 2. Execute `git --version`, `gh --version`, and `git clone https://github.com/<org>/<private-repo>.git`. 3. Observe `Paperclip: GitHub capability_missing; continuing without managed credentials.` on stdout/stderr and no GitHub connection card in the task feed after the private clone fails. **Paperclip version or commit** `a0d5f275af` (`master`) **Deployment mode** Other (sandboxed Paperclip Runner and local server) ## What Changed - Added explicit `anonymous` mode to GitHub broker launchers (`packages/adapter-utils/src/github-launcher.ts`, `packages/adapter-utils/src/execution-target.ts`, `server/src/services/heartbeat-github-launchers.ts`) and supported `"anonymous": true` in `broker.json` so intentionally unconfigured sandboxes stay quiet while missing/broken broker bridges still emit `capability_missing`. - Treated local `gh` commands (`--version`, `--help`, `-h`, `version`, `help`) as local in the `gh` launcher without contacting the credential broker. - Added `server/src/services/git-auth-connection-detection.ts` to detect unambiguous `github.com` auth failures in failed command execution events (`tool.execution.completed` and `item.completed`) and structured workspace clone failures while ignoring `exitCode === 0`, assistant prose, non-GitHub remotes, transient 5xx errors, and local non-auth git errors. - Added controller-only `connectionIntentService(db).requestForRunGitHubAuthFailure(runId, resultJsonOverride?)` in `server/src/services/connection-intents.ts` (with `completed_git_auth` run-context mode) to create a `github` `connection_intent` card in the task feed when GitHub is not already configured/usable, skipping `host` auth mode, closed tasks, non-latest runs, existing pending cards, and declined continuations. - Wired `requestForRunGitHubAuthFailure` into `classifyAndPersistRunLiveness` (`server/src/services/heartbeat/run-lifecycle.ts`) and added `githubConnectionRequested` support to `classifyRunLiveness` (`server/src/services/run-liveness.ts`) to classify the run as `blocked` (`Waiting for GitHub connection`). - Added unit and embedded-Postgres integration tests in `packages/adapter-utils/src/github-launcher.test.ts`, `server/src/services/heartbeat-github-launchers.test.ts`, and `server/src/__tests__/github-connection-auto-request.test.ts`. ## Verification - `pnpm vitest run packages/adapter-utils/src/github-launcher.test.ts` (41/41 passed) - `pnpm vitest run packages/adapter-utils/src/github-launcher-environment.test.ts --testTimeout=15000` (40 passed, 1 skipped) - `pnpm vitest run server/src/services/heartbeat-github-launchers.test.ts server/src/services/native-runtime/native-github-access.test.ts` (passed) - `pnpm vitest run server/src/__tests__/github-connection-auto-request.test.ts server/src/__tests__/connection-intents-service.test.ts server/src/__tests__/ai-auth-failure.test.ts server/src/services/heartbeat/run-comment-selection.test.ts` (86/86 passed) - `pnpm vitest run server/src/__tests__/run-liveness.test.ts` (21/21 passed) - `pnpm vitest run server/src/__tests__/heartbeat-process-recovery.test.ts -t "clone|connection|GitHub"` (6/6 passed) - `pnpm --filter @paperclipai/adapter-utils typecheck && pnpm --filter @paperclipai/server typecheck` (0 errors) ## Risks - Low risk. No database migrations or UI schema changes are required; the auto-created card reuses the existing `connection_intent` interaction kind (`serviceSlug: "github"`). - False-positive card creation is guarded by strict `github.com` host matching, non-zero command exit requirements, `githubAuthenticationMode !== "host"`, active-identity checks (`usableConnectionForAgent` and `resolveManagedGitHubIdentitySelection`), idempotent pending-card checks, and decline respect. ## Model Used - Google Gemini (Antigravity agent) with tool use and local code/test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
2538dce415
commit
1fca3a6d8c
10 files changed
+1374
-10
No files matched your search
@@ -1856,6 +1856,7 @@ printf '\0PAPERCLIP_GIT_CONTEXT_END\0'
|
||||
export async function prepareGitHubOperationLaunchers(input: {
|
||||
runId: string; target: AdapterExecutionTarget | null | undefined; cwd: string; env: Record<string, string>;
|
||||
broker?: { url: string; token: string };
|
||||
anonymous?: boolean;
|
||||
}): Promise<Record<string, string>> {
|
||||
const remote = input.target?.kind === "remote" ? input.target : null;
|
||||
const directory = githubOperationLauncherDirectory(input);
|
||||
@@ -1875,7 +1876,7 @@ export async function prepareGitHubOperationLaunchers(input: {
|
||||
// Remote launchers live beneath the checkout. Pin their own package scope
|
||||
// so an enclosing project's "type": "module" cannot reinterpret require().
|
||||
["package.json", '{"type":"commonjs"}\n'],
|
||||
...["git", "gh"].map((name) => [name, githubLauncherSource({ brokerFile: input.broker !== undefined })] as const),
|
||||
...["git", "gh"].map((name) => [name, githubLauncherSource({ brokerFile: input.broker !== undefined, anonymous: input.anonymous })] as const),
|
||||
...[".zshenv", ".zprofile", ".zshrc", ".bash_profile", ".bashrc", ".profile"].map((name) => [name, profile] as const),
|
||||
...(input.broker ? [["broker.json", `${JSON.stringify({ url: input.broker.url, token: input.broker.token })}\n`] as const] : []),
|
||||
]);
|
||||
|
||||
@@ -526,3 +526,67 @@ it.each([401, 403])("does not wait when the task broker denies the capability (%
|
||||
expect(requests).toBe(1);
|
||||
expect(Date.now() - started).toBeLessThan(3000);
|
||||
});
|
||||
|
||||
it("keeps intentionally anonymous launchers silent on git and gh operations while isolating ambient credentials", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-anonymous-silent-"));
|
||||
cleanups.push(() => rm(root, { recursive: true, force: true }));
|
||||
const bin = path.join(root, "managed"), real = path.join(root, "real"), repo = path.join(root, "repo");
|
||||
await mkdir(bin); await mkdir(real);
|
||||
await exec("git", ["init", "-q", repo]);
|
||||
for (const name of ["git", "gh"]) {
|
||||
await writeFile(path.join(bin, name), githubLauncherSource({ anonymous: true }), { mode: 0o700 });
|
||||
}
|
||||
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
|
||||
const env = { ...process.env, ...githubBrokerEnvironment({
|
||||
GH_TOKEN: "ambient-secret", GIT_AUTHOR_NAME: "Ambient", GIT_AUTHOR_EMAIL: "ambient@example.test",
|
||||
}, { url: "", token: "" }), PATH: `${bin}:${real}:${process.env.PATH}` };
|
||||
const ghResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
|
||||
expect(ghResult.stdout).toBe("anonymous");
|
||||
expect(ghResult.stderr).toBe("");
|
||||
const commitResult = await exec(path.join(bin, "git"), ["-C", repo, "commit", "--allow-empty", "-qm", "Anonymous local work"], { env });
|
||||
expect(commitResult.stderr).toBe("");
|
||||
expect((await exec("git", ["-C", repo, "log", "-1", "--format=%an <%ae>"])).stdout.trim()).toBe("Paperclip <noreply@paperclip.ing>");
|
||||
});
|
||||
|
||||
it("keeps broker-file launchers silent only when broker.json explicitly marks anonymous mode", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-anonymous-"));
|
||||
cleanups.push(() => rm(root, { recursive: true, force: true }));
|
||||
const bin = path.join(root, "managed"), real = path.join(root, "real");
|
||||
await mkdir(bin); await mkdir(real);
|
||||
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
|
||||
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
|
||||
const env = { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}`, GH_TOKEN: "ambient-secret" };
|
||||
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ anonymous: true, url: "", token: "" }));
|
||||
const anonymousResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
|
||||
expect(anonymousResult.stdout).toBe("anonymous");
|
||||
expect(anonymousResult.stderr).toBe("");
|
||||
// A failed bridge publishes empty url/token without anonymous:true and still reports capability_missing.
|
||||
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: "", token: "" }));
|
||||
const failedBridgeResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
|
||||
expect(failedBridgeResult.stdout).toBe("anonymous");
|
||||
expect(failedBridgeResult.stderr).toContain("capability_missing");
|
||||
});
|
||||
|
||||
it.each(["--version", "--help", "-h", "version", "help"])(
|
||||
"runs local gh %j without calling the broker or reporting missing capabilities",
|
||||
async (arg) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-gh-local-"));
|
||||
cleanups.push(() => rm(root, { recursive: true, force: true }));
|
||||
const bin = path.join(root, "managed"), real = path.join(root, "real");
|
||||
await mkdir(bin); await mkdir(real);
|
||||
await writeFile(path.join(bin, "gh"), githubLauncherSource(), { mode: 0o700 });
|
||||
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write("gh-local-ok");\n', { mode: 0o700 });
|
||||
let requests = 0;
|
||||
const server = createServer((_req, res) => { requests++; res.writeHead(500); res.end(); });
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
|
||||
const { port } = server.address() as { port: number };
|
||||
for (const broker of [{ url: "", token: "" }, { url: `http://127.0.0.1:${port}`, token: "run-capability" }]) {
|
||||
const env = { ...process.env, ...githubBrokerEnvironment({}, broker), PATH: `${bin}:${real}:${process.env.PATH}` };
|
||||
const result = await exec(path.join(bin, "gh"), [arg], { env });
|
||||
expect(result.stdout).toBe("gh-local-ok");
|
||||
expect(result.stderr).toBe("");
|
||||
}
|
||||
expect(requests).toBe(0);
|
||||
},
|
||||
);
|
||||
@@ -1,7 +1,7 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
/** Standalone source for local, SSH, and sandbox runtimes. No secrets in files. */
|
||||
export function githubLauncherSource(options: { brokerFile?: boolean; interpreterPath?: string } = {}): string {
|
||||
export function githubLauncherSource(options: { brokerFile?: boolean; interpreterPath?: string; anonymous?: boolean } = {}): string {
|
||||
if (options.interpreterPath !== undefined && (typeof options.interpreterPath !== "string"
|
||||
|| !isAbsolute(options.interpreterPath) || /[\s\0]/u.test(options.interpreterPath))) {
|
||||
throw new Error("GitHub launcher interpreter must be an absolute path without whitespace");
|
||||
@@ -10,6 +10,7 @@ export function githubLauncherSource(options: { brokerFile?: boolean; interprete
|
||||
// then publishes a replacement to broker.json. Only that file can change, so
|
||||
// only broker-file launchers wait for it; an inherited URL never recovers.
|
||||
const brokerRecoveryMs = options.brokerFile ? 60_000 : 0;
|
||||
const anonymousLauncher = options.anonymous === true;
|
||||
return String.raw`#!${options.interpreterPath ?? "/usr/bin/env node"}
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
@@ -36,7 +37,9 @@ if (!['git', 'gh'].includes(program) || !executable) {
|
||||
const localGitCommands = new Set(['init', 'status', 'add', 'config', 'rev-parse', 'log', 'diff', 'diff-files', 'write-tree', 'show', 'branch', 'checkout', 'switch', 'restore', 'reset', 'rm', 'mv', 'worktree', 'grep', 'blame', 'describe', 'ls-files', 'ls-tree', 'cat-file', 'rev-list', 'merge-base', 'show-ref', 'for-each-ref', 'symbolic-ref', 'check-ignore', 'version', 'help']);
|
||||
const gitValueOptions = ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--super-prefix', '--attr-source'];
|
||||
const gitFlagOptions = ['-p', '-P', '--paginate', '--no-pager', '--bare', '--no-replace-objects', '--no-lazy-fetch', '--no-optional-locks', '--no-advice', '--literal-pathspecs', '--glob-pathspecs', '--noglob-pathspecs', '--icase-pathspecs'];
|
||||
function isLocalGit(args) {
|
||||
const localGhCommands = new Set(['--version', '--help', '-h', 'version', 'help']);
|
||||
function isLocalCommand(args) {
|
||||
if (program === 'gh') return args.length > 0 && localGhCommands.has(args[0]);
|
||||
if (program !== 'git') return false;
|
||||
for (let index = 0; index < args.length; index++) {
|
||||
const arg = args[index];
|
||||
@@ -56,6 +59,8 @@ function connectorRepositoryTool(args) {
|
||||
}
|
||||
async function main() {
|
||||
let env = { ...process.env };
|
||||
const anonymousLauncher = ${anonymousLauncher ? 'true' : 'false'};
|
||||
let brokerAnonymous = false;
|
||||
${options.brokerFile ? String.raw`
|
||||
delete env.PAPERCLIP_API_URL;
|
||||
delete env.PAPERCLIP_API_KEY;
|
||||
@@ -67,9 +72,16 @@ ${options.brokerFile ? String.raw`
|
||||
const readBroker = () => {
|
||||
let broker;
|
||||
try { broker = JSON.parse(fs.readFileSync(path.join(directory, 'broker.json'), 'utf8')); }
|
||||
catch (error) { return error && error.code === 'ENOENT' ? 'absent' : 'unreadable'; }
|
||||
// A failed replacement bridge publishes empty values, which also means no broker.
|
||||
if (!broker || typeof broker.url !== 'string' || typeof broker.token !== 'string' || !broker.url || !broker.token) return 'absent';
|
||||
catch (error) {
|
||||
if (error && error.code === 'ENOENT') { brokerAnonymous = false; return 'absent'; }
|
||||
return 'unreadable';
|
||||
}
|
||||
// A failed replacement bridge publishes empty values without anonymous: true.
|
||||
if (!broker || typeof broker.url !== 'string' || typeof broker.token !== 'string' || !broker.url || !broker.token) {
|
||||
brokerAnonymous = Boolean(broker && broker.anonymous === true);
|
||||
return 'absent';
|
||||
}
|
||||
brokerAnonymous = false;
|
||||
env.PAPERCLIP_GITHUB_BROKER_URL = broker.url;
|
||||
env.PAPERCLIP_GITHUB_BROKER_TOKEN = broker.token;
|
||||
return 'present';
|
||||
@@ -110,7 +122,7 @@ ${options.brokerFile ? String.raw`
|
||||
GIT_CONFIG_KEY_4: 'user.useConfigOnly', GIT_CONFIG_VALUE_4: 'true',
|
||||
});
|
||||
const base = env.PAPERCLIP_GITHUB_BROKER_URL || env.PAPERCLIP_API_URL;
|
||||
const askBroker = !isLocalGit(process.argv.slice(2));
|
||||
const askBroker = !anonymousLauncher && !brokerAnonymous && !isLocalCommand(process.argv.slice(2));
|
||||
try {
|
||||
let response;
|
||||
if (askBroker && base && env.PAPERCLIP_GITHUB_BROKER_TOKEN) {
|
||||
|
||||
@@ -0,0 +1,687 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
authUsers,
|
||||
companies,
|
||||
companyMemberships,
|
||||
connectionGrants,
|
||||
createDb,
|
||||
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
goals,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
issueThreadInteractions,
|
||||
toolApplications,
|
||||
toolCatalogEntries,
|
||||
toolConnectionInstalls,
|
||||
toolConnections,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
detectUnconfiguredGitHubAuthFailureInEvents,
|
||||
isGitHubWorkspaceCloneAuthFailure,
|
||||
} from "../services/git-auth-connection-detection.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { classifyRunLiveness } from "../services/run-liveness.js";
|
||||
import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "../services/heartbeat/run-lifecycle.js";
|
||||
import { createHeartbeatRunPreparation } from "../services/heartbeat/run-preparation.js";
|
||||
import { createHeartbeatRunState } from "../services/heartbeat/run-state.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
function toolExecutionEvent(options: {
|
||||
output: string;
|
||||
exitCode?: number | null;
|
||||
status?: string;
|
||||
name?: string;
|
||||
subject?: string;
|
||||
}) {
|
||||
return {
|
||||
eventType: "tool.execution.completed",
|
||||
payload: {
|
||||
prpEvent: {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
eventType: "tool.execution.completed",
|
||||
payload: {
|
||||
schema: "paperclip.tool.execution.v1",
|
||||
transport: "process",
|
||||
operation: "shell",
|
||||
name: options.name ?? "git clone https://github.com/acme/private-repo.git",
|
||||
...(options.subject ? { subject: options.subject } : {}),
|
||||
status: options.status ?? "failed",
|
||||
exitCode: options.exitCode === undefined ? 128 : options.exitCode,
|
||||
output: options.output,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function commandItemEvent(options: {
|
||||
command: string;
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
status?: string;
|
||||
}) {
|
||||
return {
|
||||
eventType: "item.completed",
|
||||
payload: {
|
||||
prpEvent: {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
eventType: "item.completed",
|
||||
payload: {
|
||||
item: {
|
||||
type: "command_execution",
|
||||
command: options.command,
|
||||
exit_code: options.exitCode ?? 128,
|
||||
status: options.status ?? "failed",
|
||||
aggregated_output: options.output,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createTestLifecycle(db: ReturnType<typeof createDb>) {
|
||||
const dependencies = {
|
||||
...createHeartbeatRunState(db),
|
||||
...createHeartbeatRunPreparation(db),
|
||||
issuesSvc: { addComment: vi.fn(), listReviewAttention: vi.fn() },
|
||||
recovery: { escalateStrandedAssignedIssue: vi.fn() },
|
||||
companySkills: { completeTestRunForIssue: vi.fn() },
|
||||
budgets: { getInvocationBlock: vi.fn(async () => null) },
|
||||
treeControlSvc: { getActivePauseHoldGate: vi.fn(async () => null) },
|
||||
enqueueWakeup: vi.fn(),
|
||||
getCurrentUserRedactionOptions: vi.fn(async () => ({ enabled: false })),
|
||||
getAgentInvokability: vi.fn<HeartbeatLifecycleDependencies["getAgentInvokability"]>(async () => ({ invokable: true })),
|
||||
emitTerminalAgentTaskRun: vi.fn(),
|
||||
budgetHooks: {},
|
||||
} satisfies HeartbeatLifecycleDependencies;
|
||||
return createHeartbeatLifecycle(db, dependencies);
|
||||
}
|
||||
|
||||
describe("detectUnconfiguredGitHubAuthFailureInEvents", () => {
|
||||
it.each([
|
||||
[
|
||||
"HTTPS private clone with disabled prompts",
|
||||
toolExecutionEvent({
|
||||
output: "Cloning into 'private-repo'...\nfatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
// paperclip:allow-git-push: synthetic command output fixture testing GitHub auth detection
|
||||
"HTTPS git push authentication failed",
|
||||
toolExecutionEvent({
|
||||
// paperclip:allow-git-push: synthetic command fixture testing GitHub auth detection
|
||||
name: "git push origin main",
|
||||
output: "fatal: Authentication failed for 'https://github.com/acme/private-repo.git/'\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"HTTPS git clone 403",
|
||||
toolExecutionEvent({
|
||||
output: "fatal: unable to access 'https://github.com/acme/private-repo.git/': The requested URL returned error: 403\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"HTTPS private repository not found",
|
||||
toolExecutionEvent({
|
||||
output: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private-repo.git/' not found\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"SSH permission denied against github.com",
|
||||
commandItemEvent({
|
||||
command: "git clone git@github.com:acme/private-repo.git",
|
||||
output: "git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"gh CLI not logged in",
|
||||
toolExecutionEvent({
|
||||
name: "gh pr create --fill",
|
||||
exitCode: 4,
|
||||
output: "To get started with GitHub CLI, please run: gh auth login\nAlternatively, populate the GH_TOKEN environment variable with a GitHub API authentication token.\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"gh CLI not logged into any GitHub hosts",
|
||||
commandItemEvent({
|
||||
command: "gh repo view acme/private-repo",
|
||||
exitCode: 1,
|
||||
output: "You are not logged into any GitHub hosts. To log in, run: gh auth login\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"OpenCode generic bash tool without command text",
|
||||
toolExecutionEvent({
|
||||
name: "bash",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"timeout-wrapped git clone",
|
||||
toolExecutionEvent({
|
||||
name: "timeout 60 git clone https://github.com/acme/private-repo.git",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"timeout-wrapped bash -lc compound git clone",
|
||||
toolExecutionEvent({
|
||||
name: "timeout -k 5 60 bash -lc 'cd /workspace && git clone https://github.com/acme/private-repo.git'",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"sudo-wrapped git clone",
|
||||
toolExecutionEvent({
|
||||
name: "sudo -u runner git clone https://github.com/acme/private-repo.git",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
])("detects unambiguous GitHub auth failure: %s", (_label, event) => {
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([event])).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"successful command quoting error text",
|
||||
toolExecutionEvent({
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"assistant prose quoting error text",
|
||||
{
|
||||
eventType: "item.completed",
|
||||
payload: {
|
||||
prpEvent: {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
eventType: "item.completed",
|
||||
payload: {
|
||||
kind: "agentMessage",
|
||||
text: "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"non-GitHub HTTPS remote (GitLab)",
|
||||
toolExecutionEvent({
|
||||
name: "git clone https://gitlab.com/acme/private.git",
|
||||
output: "fatal: could not read Username for 'https://gitlab.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"non-GitHub SSH remote",
|
||||
commandItemEvent({
|
||||
command: "git clone git@gitlab.com:acme/private.git",
|
||||
output: "git@gitlab.com: Permission denied (publickey).\nfatal: Could not read from remote repository.\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"transient GitHub 503 outage",
|
||||
toolExecutionEvent({
|
||||
output: "fatal: unable to access 'https://github.com/acme/repo.git/': The requested URL returned error: 503\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"local non-auth git error",
|
||||
toolExecutionEvent({
|
||||
name: "git status",
|
||||
output: "fatal: not a git repository (or any of the parent directories): .git\n",
|
||||
}),
|
||||
],
|
||||
[
|
||||
"unrelated command printing git auth error text",
|
||||
toolExecutionEvent({
|
||||
name: "vitest run server/src/__tests__/auth.test.ts",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
])("ignores non-matching or non-GitHub failure: %s", (_label, event) => {
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([event])).toBe(false);
|
||||
});
|
||||
|
||||
it("clears detection only on matching authenticated recovery, not unrelated/local/other-repo commands", () => {
|
||||
const authFailure = toolExecutionEvent({
|
||||
name: "git clone https://github.com/acme/private-repo.git",
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
});
|
||||
const localGitStatus = toolExecutionEvent({
|
||||
name: "git status",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "On branch main\n",
|
||||
});
|
||||
const ghSubcommandHelp = toolExecutionEvent({
|
||||
name: "gh pr create --help",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "Create a pull request on GitHub\n",
|
||||
});
|
||||
const echoCommand = toolExecutionEvent({
|
||||
name: "echo gh auth status",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "gh auth status\n",
|
||||
});
|
||||
const gitlabLsRemote = toolExecutionEvent({
|
||||
name: "git ls-remote https://gitlab.com/team/public.git",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "abc123\tHEAD\n",
|
||||
});
|
||||
const differentPublicRepoClone = toolExecutionEvent({
|
||||
name: "git clone https://github.com/acme/public-mirror.git",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "Cloning into 'public-mirror'...\n",
|
||||
});
|
||||
const recoveredSameRepoClone = toolExecutionEvent({
|
||||
name: "git -C /workspace clone https://github.com/acme/private-repo.git",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "Cloning into 'private-repo'...\n",
|
||||
});
|
||||
const recoveredGitPush = toolExecutionEvent({
|
||||
// paperclip:allow-git-push: synthetic command fixture testing recovery detection
|
||||
name: "git -C /workspace push origin main",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "To https://github.com/acme/private-repo.git\n",
|
||||
});
|
||||
|
||||
const recoveredQuietGitPush = toolExecutionEvent({
|
||||
// paperclip:allow-git-push: synthetic command fixture testing recovery detection
|
||||
name: "git -C /workspace push origin main",
|
||||
exitCode: 0,
|
||||
status: "completed",
|
||||
output: "Everything up-to-date\n",
|
||||
});
|
||||
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, localGitStatus])).toBe(true);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, ghSubcommandHelp])).toBe(true);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, echoCommand])).toBe(true);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, gitlabLsRemote])).toBe(true);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, differentPublicRepoClone])).toBe(true);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, recoveredSameRepoClone])).toBe(false);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, recoveredGitPush])).toBe(false);
|
||||
expect(detectUnconfiguredGitHubAuthFailureInEvents([authFailure, recoveredQuietGitPush])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isGitHubWorkspaceCloneAuthFailure", () => {
|
||||
it("detects structured git clone authentication failures targeting github.com", () => {
|
||||
expect(isGitHubWorkspaceCloneAuthFailure({
|
||||
resultJson: {
|
||||
connectionFailure: { schemaVersion: 1, provider: "git", operation: "clone", reason: "authentication_failed" },
|
||||
},
|
||||
contextSnapshot: { workspaceRepoUrl: "https://github.com/acme/private-repo.git" },
|
||||
})).toBe(true);
|
||||
expect(isGitHubWorkspaceCloneAuthFailure({
|
||||
resultJson: {
|
||||
workspaceValidation: {
|
||||
materializationFailures: [{
|
||||
repoUrl: "git@github.com:acme/private-repo.git",
|
||||
connectionFailure: { schemaVersion: 1, provider: "git", operation: "clone", reason: "repository_unavailable" },
|
||||
}],
|
||||
},
|
||||
},
|
||||
})).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores non-GitHub remotes and non-auth transport errors", () => {
|
||||
expect(isGitHubWorkspaceCloneAuthFailure({
|
||||
resultJson: {
|
||||
connectionFailure: { schemaVersion: 1, provider: "git", operation: "clone", reason: "authentication_failed" },
|
||||
},
|
||||
contextSnapshot: { workspaceRepoUrl: "https://example.test/team/repo.git" },
|
||||
})).toBe(false);
|
||||
expect(isGitHubWorkspaceCloneAuthFailure({
|
||||
resultJson: {
|
||||
connectionFailure: { schemaVersion: 1, provider: "git", operation: "clone", reason: "dns_failure" },
|
||||
},
|
||||
contextSnapshot: { workspaceRepoUrl: "https://github.com/acme/private-repo.git" },
|
||||
})).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyRunLiveness with githubConnectionRequested", () => {
|
||||
it("marks runs with an auto-attached GitHub connection card as blocked waiting for user", () => {
|
||||
for (const runStatus of ["failed", "succeeded"] as const) {
|
||||
expect(classifyRunLiveness({
|
||||
runStatus,
|
||||
issue: { status: "in_progress", title: "Clone private repo", description: null },
|
||||
stdoutExcerpt: "I could not clone the private repo without GitHub access.",
|
||||
githubConnectionRequested: true,
|
||||
})).toMatchObject({
|
||||
livenessState: "blocked",
|
||||
livenessReason: "Waiting for GitHub connection",
|
||||
nextAction: "Complete the connection request to continue this task",
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describeEmbeddedPostgres("automatic GitHub connection card on unconfigured git auth failure", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let cleanup: (() => Promise<void>) | undefined;
|
||||
const userId = `git-auto-user-${randomUUID()}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
const tempDb = await startEmbeddedPostgresTestDatabase("paperclip-git-auto-connect-");
|
||||
cleanup = tempDb.cleanup;
|
||||
db = createDb(tempDb.connectionString);
|
||||
await db.insert(authUsers).values({
|
||||
id: userId,
|
||||
name: "Beta Tester",
|
||||
email: "beta@example.test",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await cleanup?.();
|
||||
});
|
||||
|
||||
async function seedTaskAndRun(options: {
|
||||
status: "succeeded" | "failed";
|
||||
contextSnapshot?: Record<string, unknown>;
|
||||
resultJson?: Record<string, unknown>;
|
||||
events?: Array<{ eventType: string; payload: Record<string, unknown> }>;
|
||||
}) {
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const goalId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "GitHub Auto Connect Test",
|
||||
issuePrefix: `G${randomUUID().replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await db.insert(companyMemberships).values({
|
||||
companyId,
|
||||
principalType: "user",
|
||||
principalId: userId,
|
||||
status: "active",
|
||||
membershipRole: "member",
|
||||
});
|
||||
await db.insert(goals).values({
|
||||
id: goalId,
|
||||
companyId,
|
||||
title: "Clone and push code",
|
||||
level: "task",
|
||||
status: "active",
|
||||
});
|
||||
await db.insert(agents).values({
|
||||
id: agentId,
|
||||
companyId,
|
||||
name: "Codex Engineer",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "codex" },
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
});
|
||||
await db.insert(issues).values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
goalId,
|
||||
title: "Clone private repo",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: agentId,
|
||||
});
|
||||
const [run] = await db.insert(heartbeatRuns).values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
invocationSource: "assignment",
|
||||
triggerDetail: "manual",
|
||||
status: options.status,
|
||||
runtimeMode: "native",
|
||||
nativeIssueId: issueId,
|
||||
responsibleUserId: userId,
|
||||
contextSnapshot: {
|
||||
issueId,
|
||||
githubAuthenticationMode: "managed",
|
||||
...(options.contextSnapshot ?? {}),
|
||||
},
|
||||
resultJson: options.resultJson ?? null,
|
||||
stdoutExcerpt: "I tried to clone the repo but GitHub credentials are not configured.",
|
||||
}).returning();
|
||||
|
||||
for (const [idx, ev] of (options.events ?? []).entries()) {
|
||||
await db.insert(heartbeatRunEvents).values({
|
||||
companyId,
|
||||
runId,
|
||||
agentId,
|
||||
seq: idx + 1,
|
||||
eventType: ev.eventType,
|
||||
stream: "system",
|
||||
level: "info",
|
||||
payload: ev.payload,
|
||||
});
|
||||
}
|
||||
return { companyId, agentId, issueId, runId, run: run! };
|
||||
}
|
||||
|
||||
it("creates a pending GitHub connection card in the task feed when an agent fails git clone/push without GitHub configured", async () => {
|
||||
const { companyId, agentId, issueId, runId, run } = await seedTaskAndRun({
|
||||
status: "succeeded",
|
||||
events: [
|
||||
toolExecutionEvent({
|
||||
name: "git clone https://github.com/acme/private-repo.git",
|
||||
output: "Cloning into 'private-repo'...\nfatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const lifecycle = createTestLifecycle(db);
|
||||
const updatedRun = await lifecycle.classifyAndPersistRunLiveness(run);
|
||||
expect(updatedRun?.livenessState).toBe("blocked");
|
||||
expect(updatedRun?.livenessReason).toBe("Waiting for GitHub connection");
|
||||
|
||||
const cards = await db.select().from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, companyId),
|
||||
eq(issueThreadInteractions.issueId, issueId),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
));
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({
|
||||
kind: "connection_intent",
|
||||
status: "pending",
|
||||
sourceRunId: runId,
|
||||
addresseeUserId: userId,
|
||||
payload: expect.objectContaining({
|
||||
serviceSlug: "github",
|
||||
serviceName: "GitHub",
|
||||
requestingAgentId: agentId,
|
||||
phase: "requested",
|
||||
}),
|
||||
});
|
||||
|
||||
// Calling again reuses the pending card without creating a duplicate and keeps liveness blocked.
|
||||
const repeated = await connectionIntentService(db).requestForRunGitHubAuthFailure(runId);
|
||||
expect(repeated?.interactionId).toBe(cards[0]!.id);
|
||||
const recheckedRun = await lifecycle.classifyAndPersistRunLiveness(run);
|
||||
expect(recheckedRun?.livenessState).toBe("blocked");
|
||||
const afterRepeat = await db.select().from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, companyId),
|
||||
eq(issueThreadInteractions.issueId, issueId),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
));
|
||||
expect(afterRepeat).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("creates a GitHub connection card when workspace setup fails to clone a private GitHub repository", async () => {
|
||||
const { companyId, issueId, run } = await seedTaskAndRun({
|
||||
status: "failed",
|
||||
contextSnapshot: { workspaceRepoUrl: "https://github.com/acme/private-repo.git" },
|
||||
resultJson: {
|
||||
connectionFailure: {
|
||||
schemaVersion: 1,
|
||||
provider: "git",
|
||||
operation: "clone",
|
||||
reason: "authentication_failed",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const lifecycle = createTestLifecycle(db);
|
||||
const updatedRun = await lifecycle.classifyAndPersistRunLiveness(run);
|
||||
expect(updatedRun?.livenessState).toBe("blocked");
|
||||
|
||||
const cards = await db.select().from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, companyId),
|
||||
eq(issueThreadInteractions.issueId, issueId),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
));
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.payload).toMatchObject({ serviceSlug: "github", serviceName: "GitHub" });
|
||||
});
|
||||
|
||||
it("does not create a second card after the user declines the GitHub connection request", async () => {
|
||||
const first = await seedTaskAndRun({
|
||||
status: "succeeded",
|
||||
events: [
|
||||
toolExecutionEvent({
|
||||
// paperclip:allow-git-push: synthetic command fixture testing GitHub auth detection
|
||||
name: "git push origin main",
|
||||
output: "fatal: Authentication failed for 'https://github.com/acme/private-repo.git/'\n",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const created = await connectionIntentService(db).requestForRunGitHubAuthFailure(first.runId);
|
||||
expect(created?.interactionId).toBeTruthy();
|
||||
|
||||
await connectionIntentService(db).decline(created!.interactionId!, userId, "Not right now");
|
||||
|
||||
const continuationRunId = randomUUID();
|
||||
const [continuationRun] = await db.insert(heartbeatRuns).values({
|
||||
id: continuationRunId,
|
||||
companyId: first.companyId,
|
||||
agentId: first.agentId,
|
||||
invocationSource: "assignment",
|
||||
triggerDetail: "manual",
|
||||
status: "succeeded",
|
||||
runtimeMode: "native",
|
||||
nativeIssueId: first.issueId,
|
||||
responsibleUserId: userId,
|
||||
contextSnapshot: {
|
||||
issueId: first.issueId,
|
||||
githubAuthenticationMode: "managed",
|
||||
interactionId: created!.interactionId!,
|
||||
},
|
||||
stdoutExcerpt: "Understood, skipping GitHub push.",
|
||||
}).returning();
|
||||
await db.insert(heartbeatRunEvents).values({
|
||||
companyId: first.companyId,
|
||||
runId: continuationRunId,
|
||||
agentId: first.agentId,
|
||||
seq: 1,
|
||||
eventType: "tool.execution.completed",
|
||||
stream: "system",
|
||||
level: "info",
|
||||
payload: toolExecutionEvent({
|
||||
// paperclip:allow-git-push: synthetic command fixture testing GitHub auth detection
|
||||
name: "git push origin main",
|
||||
output: "fatal: Authentication failed for 'https://github.com/acme/private-repo.git/'\n",
|
||||
}).payload,
|
||||
});
|
||||
|
||||
const retried = await connectionIntentService(db).requestForRunGitHubAuthFailure(continuationRun!.id);
|
||||
expect(retried).toBeNull();
|
||||
const cards = await db.select().from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, first.companyId),
|
||||
eq(issueThreadInteractions.issueId, first.issueId),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
));
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.status).toBe("rejected");
|
||||
});
|
||||
|
||||
it("does not create a card when GitHub is already usable for the agent or when using host credentials", async () => {
|
||||
const hostRun = await seedTaskAndRun({
|
||||
status: "succeeded",
|
||||
contextSnapshot: { githubAuthenticationMode: "host" },
|
||||
events: [
|
||||
toolExecutionEvent({
|
||||
output: "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(await connectionIntentService(db).requestForRunGitHubAuthFailure(hostRun.runId)).toBeNull();
|
||||
|
||||
const connected = await seedTaskAndRun({
|
||||
status: "succeeded",
|
||||
events: [
|
||||
toolExecutionEvent({
|
||||
output: "fatal: Authentication failed for 'https://github.com/acme/other-repo.git/'\n",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const [application] = await db.insert(toolApplications).values({
|
||||
companyId: connected.companyId,
|
||||
applicationKey: randomUUID(),
|
||||
name: "GitHub",
|
||||
type: "mcp_http",
|
||||
metadata: { sourceTemplateKey: "github" },
|
||||
}).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({
|
||||
companyId: connected.companyId,
|
||||
applicationId: application!.id,
|
||||
uid: `github-test-${randomUUID()}`,
|
||||
name: "GitHub",
|
||||
transport: "mcp_remote",
|
||||
authKind: "oauth",
|
||||
credentialPolicy: "per_user",
|
||||
enabled: true,
|
||||
status: "active",
|
||||
healthStatus: "ok",
|
||||
config: { sourceTemplateKey: "github" },
|
||||
}).returning();
|
||||
await db.insert(connectionGrants).values({
|
||||
companyId: connected.companyId,
|
||||
connectionId: connection!.id,
|
||||
kind: "user",
|
||||
subjectUserId: userId,
|
||||
status: "active",
|
||||
});
|
||||
await db.insert(toolConnectionInstalls).values({
|
||||
companyId: connected.companyId,
|
||||
connectionId: connection!.id,
|
||||
targetType: "company",
|
||||
targetId: connected.companyId,
|
||||
});
|
||||
await db.insert(toolCatalogEntries).values({
|
||||
companyId: connected.companyId,
|
||||
connectionId: connection!.id,
|
||||
name: "get_me",
|
||||
toolName: "get_me",
|
||||
riskLevel: "read",
|
||||
versionHash: "v1",
|
||||
entryKind: "tool",
|
||||
status: "active",
|
||||
});
|
||||
|
||||
expect(await connectionIntentService(db).requestForRunGitHubAuthFailure(connected.runId)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,11 @@ import { logActivity } from "./activity-log.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { aiConnectionBindingSchema, aiConnectionCatalogSlug, aiConnectionRouterBindingSchema, aiConnectionSourceSlug } from "@paperclipai/shared";
|
||||
import { aiBindingForAuthRecovery, isAiAuthenticationRepairable } from "./ai-auth-failure.js";
|
||||
import { and, eq, desc, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import {
|
||||
detectUnconfiguredGitHubAuthFailureInEvents,
|
||||
isGitHubWorkspaceCloneAuthFailure,
|
||||
} from "./git-auth-connection-detection.js";
|
||||
import { and, eq, desc, inArray, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
@@ -29,6 +33,7 @@ import {
|
||||
toolProfileBindings,
|
||||
toolPolicies,
|
||||
companyMemberships,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
issueComments,
|
||||
@@ -217,7 +222,10 @@ export function connectionIntentService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRunContext(claims: ConnectionRunClaims, mode: "active" | "failed_auth" | "queued_setup" = "active") {
|
||||
async function loadRunContext(
|
||||
claims: ConnectionRunClaims,
|
||||
mode: "active" | "failed_auth" | "queued_setup" | "completed_git_auth" = "active",
|
||||
) {
|
||||
let run = await db
|
||||
.select({
|
||||
id: heartbeatRuns.id,
|
||||
@@ -244,6 +252,7 @@ export function connectionIntentService(db: Db) {
|
||||
) throw forbidden("Runtime tool token does not match its heartbeat run");
|
||||
if (mode === "failed_auth" ? run.status !== "failed" || !isAiAuthenticationRepairable(run)
|
||||
: mode === "queued_setup" ? run.status !== "queued" || run.startedAt !== null || run.runtimeMode !== "legacy" || run.activeIdentityContextId !== null
|
||||
: mode === "completed_git_auth" ? (run.status !== "failed" && run.status !== "succeeded")
|
||||
: run.status !== "running") {
|
||||
throw forbidden("Runtime tool token is no longer active");
|
||||
}
|
||||
@@ -1548,6 +1557,95 @@ export function connectionIntentService(db: Db) {
|
||||
}
|
||||
return requestWithContext(context, binding.provider, { purpose: "ai" });
|
||||
},
|
||||
// Controller-only entry point. Runtime tokens still require a running run.
|
||||
requestForRunGitHubAuthFailure: async (runId: string, resultJsonOverride?: Record<string, unknown> | null) => {
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
if (!run || (run.status !== "failed" && run.status !== "succeeded") || !run.responsibleUserId) return null;
|
||||
if (record(run.contextSnapshot)?.githubAuthenticationMode === "host") return null;
|
||||
let detected = isGitHubWorkspaceCloneAuthFailure({
|
||||
resultJson: resultJsonOverride ?? run.resultJson,
|
||||
contextSnapshot: run.contextSnapshot,
|
||||
});
|
||||
if (!detected) {
|
||||
const recentEvents = await db
|
||||
.select({ eventType: heartbeatRunEvents.eventType, payload: heartbeatRunEvents.payload })
|
||||
.from(heartbeatRunEvents)
|
||||
.where(and(
|
||||
eq(heartbeatRunEvents.companyId, run.companyId),
|
||||
eq(heartbeatRunEvents.runId, run.id),
|
||||
inArray(heartbeatRunEvents.eventType, ["tool.execution.completed", "item.completed"]),
|
||||
))
|
||||
.orderBy(desc(heartbeatRunEvents.seq))
|
||||
.limit(200);
|
||||
// Evaluate chronologically (oldest -> newest) so a later successful remote
|
||||
// git/gh command clears an earlier auth failure.
|
||||
detected = detectUnconfiguredGitHubAuthFailureInEvents(recentEvents.reverse());
|
||||
}
|
||||
if (!detected) return null;
|
||||
let context: Awaited<ReturnType<typeof loadRunContext>>;
|
||||
try {
|
||||
context = await loadRunContext(
|
||||
{ sub: run.agentId, company_id: run.companyId, run_id: run.id, responsible_user_id: run.responsibleUserId },
|
||||
"completed_git_auth",
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && [403, 404, 409, 422].includes(error.status)) return null;
|
||||
throw error;
|
||||
}
|
||||
const [latest] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, run.companyId),
|
||||
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId', ${heartbeatRuns.nativeIssueId}::text) = ${context.issue.id}`,
|
||||
)).orderBy(desc(heartbeatRuns.createdAt)).limit(1);
|
||||
if (latest?.id !== run.id) return null;
|
||||
const [pendingGitHub] = await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, run.companyId),
|
||||
eq(issueThreadInteractions.issueId, context.issue.id),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
sql`${issueThreadInteractions.payload}->>'serviceSlug' = 'github'`,
|
||||
)).limit(1);
|
||||
if (pendingGitHub) {
|
||||
return {
|
||||
version: 1 as const,
|
||||
service: "github",
|
||||
state: "needs_user_action" as const,
|
||||
connectionId: null,
|
||||
interactionId: pendingGitHub.id,
|
||||
instruction: "A GitHub connection card is already pending for the responsible user.",
|
||||
};
|
||||
}
|
||||
const ready = await usableConnectionForAgent({
|
||||
companyId: run.companyId,
|
||||
agentId: run.agentId,
|
||||
responsibleUserId: context.run.responsibleUserId!,
|
||||
serviceSlug: "github",
|
||||
});
|
||||
if (ready) return null;
|
||||
const managedGitHub = await resolveManagedGitHubIdentitySelection(db, run.companyId, {
|
||||
agentId: run.agentId,
|
||||
responsibleUserId: context.run.responsibleUserId!,
|
||||
});
|
||||
if (managedGitHub.configured && managedGitHub.grant?.status === "active") {
|
||||
const [connection] = await db.select({
|
||||
status: toolConnections.status,
|
||||
enabled: toolConnections.enabled,
|
||||
healthStatus: toolConnections.healthStatus,
|
||||
}).from(toolConnections).where(and(
|
||||
eq(toolConnections.companyId, run.companyId),
|
||||
eq(toolConnections.id, managedGitHub.grant.connectionId),
|
||||
)).limit(1);
|
||||
if (connection && connection.status === "active" && connection.enabled && !isToolConnectionAttentionHealth(connection.healthStatus)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const created = await requestWithContext(context, "github");
|
||||
return created.interactionId ? created : null;
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && [403, 404, 409, 422].includes(error.status)) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
loadIntent,
|
||||
setupOptions,
|
||||
complete,
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
export interface GitAuthCommandEvent {
|
||||
eventType: string;
|
||||
payload?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface GitHubWorkspaceFailureRun {
|
||||
resultJson?: Record<string, unknown> | null;
|
||||
contextSnapshot?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
interface CommandExecutionRecord {
|
||||
command: string;
|
||||
output: string;
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
type ParsedGitHubCommand =
|
||||
| { kind: "git"; subcommand: string | null }
|
||||
| { kind: "gh"; authenticated: boolean };
|
||||
|
||||
const GITHUB_HOST_URL_RE =
|
||||
/(?:^|[\s'"`(\[])(?:(?:https?|ssh|git):\/\/(?:[^/\s'"`@]+@)?|git@)github\.com(?::\d+)?(?:[/:]|$|[\s'"`)\]])/i;
|
||||
|
||||
const GITHUB_REPO_RE =
|
||||
/(?:(?:https?|ssh|git):\/\/(?:[^/\s'"`@]+@)?|git@)github\.com(?::\d+)?[/:]([a-z0-9._-]+\/[a-z0-9._-]+?)(?:\.git)?(?=$|[/\s'"`)\],;])/i;
|
||||
|
||||
const GENERIC_SHELL_TOOL_NAMES = new Set([
|
||||
"bash",
|
||||
"sh",
|
||||
"zsh",
|
||||
"shell",
|
||||
"exec",
|
||||
"terminal",
|
||||
"command",
|
||||
"run_command",
|
||||
"execute_command",
|
||||
"shell_command",
|
||||
"process",
|
||||
]);
|
||||
|
||||
const GIT_VALUE_GLOBAL_FLAGS = new Set([
|
||||
"-C",
|
||||
"-c",
|
||||
"--git-dir",
|
||||
"--work-tree",
|
||||
"--namespace",
|
||||
"--super-prefix",
|
||||
"--config-env",
|
||||
"--exec-path",
|
||||
]);
|
||||
|
||||
const GIT_REMOTE_READ_SUBCOMMANDS = new Set(["clone", "fetch", "pull", "ls-remote"]);
|
||||
|
||||
const GH_LOCAL_SUBCOMMANDS = new Set(["help", "version", "completion"]);
|
||||
|
||||
const GH_CLI_UNAUTHENTICATED_PATTERNS = [
|
||||
/\byou are not logged into any github hosts\b/i,
|
||||
/\bto get started with github cli,\s*please run:\s*gh auth login\b/i,
|
||||
/\bto authenticate,\s*please run\s+[`'"]?gh auth login[`'"]?/i,
|
||||
/\bauthentication token not found for host\s+github\.com\b/i,
|
||||
/\bfailed to log in to github\.com\b/i,
|
||||
];
|
||||
|
||||
const GIT_GITHUB_AUTH_FAILURE_PATTERNS = [
|
||||
/fatal:\s*could not read (?:username|password) for ['"]https?:\/\/(?:[^'"/\s@]+@)?github\.com(?:[/:][^'"]*)?['"]/i,
|
||||
/fatal:\s*authentication failed for ['"]https?:\/\/(?:[^'"/\s@]+@)?github\.com(?:[/:][^'"]*)?['"]/i,
|
||||
/fatal:\s*unable to access ['"]https?:\/\/(?:[^'"/\s@]+@)?github\.com(?:[/:][^'"]*)?['"]:\s*the requested url returned error:\s*(?:401|403|404)\b/i,
|
||||
/fatal:\s*repository ['"]https?:\/\/(?:[^'"/\s@]+@)?github\.com(?:[/:][^'"]*)?['"] not found\b/i,
|
||||
/\bgit@github\.com:\s*permission denied\s*\((?:publickey|password|keyboard-interactive)/i,
|
||||
/https?:\/\/(?:[^'"/\s@]+@)?github\.com\b[^\n]*\bterminal prompts disabled\b/i,
|
||||
];
|
||||
|
||||
const GIT_REMOTE_AUTH_FAILURE_RE =
|
||||
/remote:\s*(?:repository not found|permission to [^\n]+ denied|invalid username or (?:password|token)|support for password authentication was removed|write access to repository not granted)/i;
|
||||
|
||||
const NON_GITHUB_REMOTE_URL_RE =
|
||||
/(?:(?:https?|ssh|git):\/\/(?:[^/\s'"`@]+@)?|git@)(?!github\.com(?::\d+)?(?:[/:]|$))[a-z0-9.-]+\.[a-z]{2,}(?::\d+)?[/:]/i;
|
||||
|
||||
const WORKSPACE_CLONE_AUTH_REASONS = new Set(["authentication_failed", "repository_unavailable"]);
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
function asNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function joinTextParts(parts: unknown[]): string {
|
||||
return parts
|
||||
.map(asNonEmptyString)
|
||||
.filter((part): part is string => Boolean(part))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function resolveToolCommand(body: Record<string, unknown>): string {
|
||||
const explicitCommand = joinTextParts([body.command, body.subject]);
|
||||
if (explicitCommand) return explicitCommand;
|
||||
const name = asNonEmptyString(body.name);
|
||||
if (!name) return "";
|
||||
// Generic shell tool names (for example OpenCode's `name: "bash"`) do not
|
||||
// carry the executed command text; treat them as omitted command metadata.
|
||||
if (GENERIC_SHELL_TOOL_NAMES.has(name.toLowerCase())) return "";
|
||||
return name;
|
||||
}
|
||||
|
||||
export function isGitHubRemoteUrl(value: unknown): boolean {
|
||||
const text = asNonEmptyString(value);
|
||||
return text !== null && GITHUB_HOST_URL_RE.test(text);
|
||||
}
|
||||
|
||||
function extractGitHubRepoSlug(text: string): string | null {
|
||||
const match = text.match(GITHUB_REPO_RE);
|
||||
return match?.[1] ? match[1].toLowerCase() : null;
|
||||
}
|
||||
|
||||
function tokenizeSegment(segment: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
const tokenRe = /'([^']*)'|"([^"]*)"|([^\s]+)/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = tokenRe.exec(segment)) !== null) {
|
||||
const token = match[1] ?? match[2] ?? match[3] ?? "";
|
||||
if (token.length > 0) tokens.push(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function splitShellSegments(command: string): string[] {
|
||||
const segments: string[] = [];
|
||||
let current = "";
|
||||
let quote: "'" | '"' | null = null;
|
||||
for (let i = 0; i < command.length; i += 1) {
|
||||
const ch = command[i]!;
|
||||
if (quote) {
|
||||
if (ch === "\\" && quote === '"' && i + 1 < command.length) {
|
||||
current += ch + command[i + 1]!;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === quote) quote = null;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'" || ch === '"') {
|
||||
quote = ch;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\\" && i + 1 < command.length) {
|
||||
current += ch + command[i + 1]!;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ";" || ch === "\n") {
|
||||
if (current.trim()) segments.push(current.trim());
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
if ((ch === "&" && command[i + 1] === "&") || (ch === "|" && command[i + 1] === "|")) {
|
||||
if (current.trim()) segments.push(current.trim());
|
||||
current = "";
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "|") {
|
||||
if (current.trim()) segments.push(current.trim());
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
current += ch;
|
||||
}
|
||||
if (current.trim()) segments.push(current.trim());
|
||||
return segments;
|
||||
}
|
||||
|
||||
function unwrapShellWrapper(command: string): string {
|
||||
const trimmed = command.trim();
|
||||
const wrapper = trimmed.match(/^(?:(?:\/[\w./-]+\/)?(?:bash|sh|zsh))\s+(?:-[a-zA-Z]*c)\s+(['"])([\s\S]*)\1$/);
|
||||
return wrapper?.[2] ? wrapper[2] : trimmed;
|
||||
}
|
||||
|
||||
function basename(executable: string): string {
|
||||
const idx = Math.max(executable.lastIndexOf("/"), executable.lastIndexOf("\\"));
|
||||
return (idx >= 0 ? executable.slice(idx + 1) : executable).toLowerCase();
|
||||
}
|
||||
|
||||
function parseCommandSegment(segment: string): ParsedGitHubCommand[] {
|
||||
const tokens = tokenizeSegment(segment);
|
||||
let i = 0;
|
||||
while (i < tokens.length) {
|
||||
const token = tokens[i]!;
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
const base = basename(token);
|
||||
if (base === "env") {
|
||||
i += 1;
|
||||
while (i < tokens.length) {
|
||||
const arg = tokens[i]!;
|
||||
if (arg === "-u" || arg === "--unset" || arg === "-C" || arg === "--chdir") {
|
||||
i += 2;
|
||||
} else if (arg.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
|
||||
i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (base === "timeout") {
|
||||
i += 1;
|
||||
while (i < tokens.length && tokens[i]!.startsWith("-")) {
|
||||
const arg = tokens[i]!;
|
||||
if (arg === "-k" || arg === "--kill-after" || arg === "-s" || arg === "--signal") {
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
// Skip the duration argument (e.g. "60", "30s", "2m").
|
||||
if (i < tokens.length) i += 1;
|
||||
continue;
|
||||
}
|
||||
if (base === "nice") {
|
||||
i += 1;
|
||||
if (tokens[i] === "-n" || tokens[i] === "--adjustment") {
|
||||
i += 2;
|
||||
} else if (tokens[i]?.startsWith("-")) {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (base === "stdbuf") {
|
||||
i += 1;
|
||||
while (i < tokens.length && tokens[i]!.startsWith("-")) {
|
||||
const arg = tokens[i]!;
|
||||
if (arg === "-i" || arg === "-o" || arg === "-e" || arg === "--input" || arg === "--output" || arg === "--error") {
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (base === "sudo") {
|
||||
i += 1;
|
||||
while (i < tokens.length && tokens[i]!.startsWith("-")) {
|
||||
const arg = tokens[i]!;
|
||||
if (arg === "--") {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if (arg === "-u" || arg === "-g" || arg === "-C" || arg === "-h" || arg === "-p" || arg === "-r" || arg === "-t") {
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (base === "nohup" || base === "time" || base === "command" || base === "exec" || base === "setsid" || base === "unbuffer") {
|
||||
i += 1;
|
||||
while (i < tokens.length && tokens[i]!.startsWith("-")) {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (base === "bash" || base === "sh" || base === "zsh") {
|
||||
let j = i + 1;
|
||||
while (j < tokens.length && tokens[j]!.startsWith("-")) {
|
||||
const flag = tokens[j]!;
|
||||
j += 1;
|
||||
if (/^-[a-zA-Z]*c$/.test(flag) && j < tokens.length) {
|
||||
return parseGitHubCommands(tokens[j]!);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (base === "git") {
|
||||
i += 1;
|
||||
while (i < tokens.length) {
|
||||
const arg = tokens[i]!;
|
||||
if (GIT_VALUE_GLOBAL_FLAGS.has(arg)) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith("-")) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
return [{ kind: "git", subcommand: arg.toLowerCase() }];
|
||||
}
|
||||
return [{ kind: "git", subcommand: null }];
|
||||
}
|
||||
if (base === "gh") {
|
||||
const rest = tokens.slice(i + 1);
|
||||
const hasHelpOrVersionFlag = rest.some((arg) => arg === "-h" || arg === "--help" || arg === "--version");
|
||||
const firstSubcommand = rest.find((arg) => !arg.startsWith("-"))?.toLowerCase() ?? null;
|
||||
const isLocal = hasHelpOrVersionFlag || !firstSubcommand || GH_LOCAL_SUBCOMMANDS.has(firstSubcommand);
|
||||
return [{ kind: "gh", authenticated: !isLocal }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function parseGitHubCommands(command: string): ParsedGitHubCommand[] {
|
||||
if (!command.trim()) return [];
|
||||
const unwrapped = unwrapShellWrapper(command);
|
||||
const segments = splitShellSegments(unwrapped);
|
||||
const parsed: ParsedGitHubCommand[] = [];
|
||||
for (const segment of segments) {
|
||||
parsed.push(...parseCommandSegment(segment));
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function extractCommandExecution(event: GitAuthCommandEvent): CommandExecutionRecord | null {
|
||||
const payload = asRecord(event.payload);
|
||||
if (!payload) return null;
|
||||
const prpEvent = asRecord(payload.prpEvent);
|
||||
const prpPayload = asRecord(prpEvent?.payload);
|
||||
|
||||
if (event.eventType === "tool.execution.completed") {
|
||||
const body = prpPayload ?? payload;
|
||||
const exitCode = typeof body.exitCode === "number" ? body.exitCode : null;
|
||||
const status = asNonEmptyString(body.status)?.toLowerCase() ?? null;
|
||||
const failed = exitCode !== null
|
||||
? exitCode !== 0
|
||||
: (status === "failed" || status === "error");
|
||||
const output = joinTextParts([body.output, body.stderr, body.error]);
|
||||
const command = resolveToolCommand(body);
|
||||
if (!output && !command) return null;
|
||||
return { command, output, failed };
|
||||
}
|
||||
|
||||
if (event.eventType === "item.completed") {
|
||||
const item = asRecord(prpPayload?.item) ?? asRecord(payload.item);
|
||||
if (!item) return null;
|
||||
const itemType = asNonEmptyString(item.type);
|
||||
if (itemType !== "command_execution" && itemType !== "commandExecution") return null;
|
||||
const exitCode = typeof item.exit_code === "number"
|
||||
? item.exit_code
|
||||
: typeof item.exitCode === "number"
|
||||
? item.exitCode
|
||||
: null;
|
||||
const status = asNonEmptyString(item.status)?.toLowerCase() ?? null;
|
||||
const failed = exitCode !== null
|
||||
? exitCode !== 0
|
||||
: (status === "failed" || status === "error");
|
||||
const output = joinTextParts([item.aggregated_output, item.aggregatedOutput, item.output, item.stderr]);
|
||||
const command = asNonEmptyString(item.command) ?? "";
|
||||
if (!output && !command) return null;
|
||||
return { command, output, failed };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function matchesUnconfiguredGitHubAuthFailure(execution: CommandExecutionRecord): boolean {
|
||||
if (!execution.failed || !execution.output) return false;
|
||||
if (execution.command.length > 0 && parseGitHubCommands(execution.command).length === 0) {
|
||||
return false;
|
||||
}
|
||||
const { output } = execution;
|
||||
if (GH_CLI_UNAUTHENTICATED_PATTERNS.some((pattern) => pattern.test(output))) {
|
||||
return true;
|
||||
}
|
||||
if (GIT_GITHUB_AUTH_FAILURE_PATTERNS.some((pattern) => pattern.test(output))) {
|
||||
return true;
|
||||
}
|
||||
if (GIT_REMOTE_AUTH_FAILURE_RE.test(output) && isGitHubRemoteUrl(output)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function didRecoverGitHubAuth(
|
||||
execution: CommandExecutionRecord,
|
||||
failedRepoSlug: string | null,
|
||||
): boolean {
|
||||
if (execution.failed || execution.command.length === 0) return false;
|
||||
const commands = parseGitHubCommands(execution.command);
|
||||
if (commands.length === 0) return false;
|
||||
const combined = `${execution.command}\n${execution.output}`;
|
||||
if (NON_GITHUB_REMOTE_URL_RE.test(combined) && !isGitHubRemoteUrl(combined)) {
|
||||
return false;
|
||||
}
|
||||
const hasGitHubRemote = isGitHubRemoteUrl(combined);
|
||||
const succeededRepoSlug = extractGitHubRepoSlug(combined);
|
||||
for (const cmd of commands) {
|
||||
if (cmd.kind === "gh" && cmd.authenticated) {
|
||||
if (!failedRepoSlug || !succeededRepoSlug || succeededRepoSlug === failedRepoSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (cmd.kind === "git" && cmd.subcommand === "push") {
|
||||
// A successful `git push` already proved remote write auth; quiet or
|
||||
// "Everything up-to-date" output may omit the remote URL, while non-GitHub
|
||||
// remote URLs are already excluded above.
|
||||
if (!failedRepoSlug || !succeededRepoSlug || succeededRepoSlug === failedRepoSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (cmd.kind === "git" && cmd.subcommand && GIT_REMOTE_READ_SUBCOMMANDS.has(cmd.subcommand) && hasGitHubRemote) {
|
||||
// A successful public clone/fetch of a different repository does not prove
|
||||
// access to the private GitHub repository that previously failed.
|
||||
if (failedRepoSlug && succeededRepoSlug === failedRepoSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspects command events in chronological order (oldest -> newest) and returns
|
||||
* true only when an unconfigured GitHub auth failure occurred and was not
|
||||
* followed by a matching successful authenticated GitHub command.
|
||||
*/
|
||||
export function detectUnconfiguredGitHubAuthFailureInEvents(
|
||||
events: Iterable<GitAuthCommandEvent>,
|
||||
): boolean {
|
||||
let detected = false;
|
||||
let failedRepoSlug: string | null = null;
|
||||
for (const event of events) {
|
||||
const execution = extractCommandExecution(event);
|
||||
if (!execution) continue;
|
||||
if (matchesUnconfiguredGitHubAuthFailure(execution)) {
|
||||
detected = true;
|
||||
failedRepoSlug = extractGitHubRepoSlug(`${execution.command}\n${execution.output}`);
|
||||
} else if (detected && didRecoverGitHubAuth(execution, failedRepoSlug)) {
|
||||
detected = false;
|
||||
failedRepoSlug = null;
|
||||
}
|
||||
}
|
||||
return detected;
|
||||
}
|
||||
|
||||
function isGitCloneAuthFailureObject(value: unknown): boolean {
|
||||
const failure = asRecord(value);
|
||||
if (!failure) return false;
|
||||
return failure.provider === "git"
|
||||
&& failure.operation === "clone"
|
||||
&& typeof failure.reason === "string"
|
||||
&& WORKSPACE_CLONE_AUTH_REASONS.has(failure.reason);
|
||||
}
|
||||
|
||||
export function isGitHubWorkspaceCloneAuthFailure(run: GitHubWorkspaceFailureRun): boolean {
|
||||
const resultJson = asRecord(run.resultJson);
|
||||
if (!resultJson) return false;
|
||||
const contextSnapshot = asRecord(run.contextSnapshot);
|
||||
|
||||
if (isGitCloneAuthFailureObject(resultJson.connectionFailure)) {
|
||||
const failure = asRecord(resultJson.connectionFailure);
|
||||
const repoCandidates = [
|
||||
contextSnapshot?.workspaceRepoUrl,
|
||||
contextSnapshot?.repoUrl,
|
||||
resultJson.repoUrl,
|
||||
failure?.repoUrl,
|
||||
];
|
||||
if (repoCandidates.some(isGitHubRemoteUrl)) return true;
|
||||
}
|
||||
|
||||
const validation = asRecord(resultJson.workspaceValidation);
|
||||
const materializationFailures = Array.isArray(validation?.materializationFailures)
|
||||
? validation.materializationFailures
|
||||
: [];
|
||||
for (const entry of materializationFailures) {
|
||||
const record = asRecord(entry);
|
||||
if (!record) continue;
|
||||
if (isGitCloneAuthFailureObject(record.connectionFailure) && isGitHubRemoteUrl(record.repoUrl)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -119,6 +119,7 @@ process.stdout.write(JSON.stringify({token:process.env.GH_TOKEN || '', githubTok
|
||||
expect(await readFile(path.join(first.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, "gh"), "utf8")).not.toContain("ambient-token");
|
||||
// A still-live provider uses its first-turn environment, not the new one.
|
||||
const command = await execute({ command: path.join(first.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, "gh"), env: first.env });
|
||||
expect(command.stderr).toBe("");
|
||||
const result = JSON.parse(command.stdout);
|
||||
expect(result).toEqual({ token: "", githubToken: "", ssh: "", imageConfig: false,
|
||||
global: expect.stringMatching(/\/paperclip-github-operation-[^/]+\/gitconfig$/),
|
||||
@@ -126,6 +127,7 @@ process.stdout.write(JSON.stringify({token:process.env.GH_TOKEN || '', githubTok
|
||||
await expect(readFile(result.global)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const commit = await execute({ command: "bash", args: ["--noprofile", "--norc", "-c",
|
||||
"git init -q && git commit --allow-empty -qm 'Local work' && git log -1 --format='%an <%ae>|%cn <%ce>'"], env: first.env });
|
||||
expect(commit.stderr).toBe("");
|
||||
expect(commit.stdout.trim()).toBe("Paperclip <noreply@paperclip.ing>|Paperclip <noreply@paperclip.ing>");
|
||||
const changedPath = await prepareHeartbeatGitHubLaunchers({ ...base, runId: "run-three", env: { ...imageEnv, PATH: `${imageEnv.PATH}:/extra` } });
|
||||
expect(changedPath.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).not.toBe(first.env.PAPERCLIP_GITHUB_LAUNCHER_DIR);
|
||||
|
||||
@@ -46,7 +46,7 @@ export async function prepareHeartbeatGitHubLaunchers(
|
||||
});
|
||||
try {
|
||||
return {
|
||||
env: await prepareLaunchers({ ...location, cwd: input.cwd, env }),
|
||||
env: await prepareLaunchers({ ...location, cwd: input.cwd, env, ...(anonymous ? { anonymous: true } : {}) }),
|
||||
cleanupLocation: anonymous ? null : location,
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -3174,9 +3174,16 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const githubConnectionRequest = !authRepair?.interactionId && (run.status === "failed" || run.status === "succeeded")
|
||||
? await connectionIntentService(db).requestForRunGitHubAuthFailure(run.id, resultJson).catch(() => {
|
||||
logger.warn({ runId: run.id }, "Could not attach GitHub connection request after unconfigured git auth failure");
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const classification = classifyRunLiveness({
|
||||
...await buildRunLivenessInput(run, resultJson),
|
||||
authenticationRepairRequested: Boolean(authRepair?.interactionId),
|
||||
githubConnectionRequested: Boolean(githubConnectionRequest?.interactionId),
|
||||
});
|
||||
return db
|
||||
.update(heartbeatRuns)
|
||||
|
||||
@@ -40,6 +40,8 @@ export interface RunLivenessClassificationInput {
|
||||
evidence?: Partial<RunLivenessEvidenceInput> | null;
|
||||
/** Set by the controller only after creating a durable connection card. */
|
||||
authenticationRepairRequested?: boolean;
|
||||
/** Set by the controller only after auto-attaching a GitHub connection card. */
|
||||
githubConnectionRequested?: boolean;
|
||||
}
|
||||
|
||||
export interface RunLivenessClassification {
|
||||
@@ -327,6 +329,10 @@ export function classifyRunLiveness(input: RunLivenessClassificationInput): RunL
|
||||
return output("blocked", "Waiting for provider authentication repair", "Complete the connection request to continue this task");
|
||||
}
|
||||
|
||||
if (input.runStatus === "failed" && input.githubConnectionRequested) {
|
||||
return output("blocked", "Waiting for GitHub connection", "Complete the connection request to continue this task");
|
||||
}
|
||||
|
||||
if (input.runStatus !== "succeeded") {
|
||||
if (hasUnmanagedBackgroundTaskEvidence(input.resultJson)) {
|
||||
return output("failed", UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON);
|
||||
@@ -338,6 +344,10 @@ export function classifyRunLiveness(input: RunLivenessClassificationInput): RunL
|
||||
return output("completed", `Issue is ${issueStatus}`);
|
||||
}
|
||||
|
||||
if (input.githubConnectionRequested) {
|
||||
return output("blocked", "Waiting for GitHub connection", "Complete the connection request to continue this task");
|
||||
}
|
||||
|
||||
if (declaredBlocker(input)) {
|
||||
return output("blocked", issueStatus === "blocked" ? "Issue status is blocked" : "Run output declared a concrete blocker", nextAction);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user