paperclip-github-plugin 0.13.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/manifest.js +12 -5
- package/dist/ui/index.js +5 -5
- package/dist/ui/index.js.map +3 -3
- package/dist/worker.js +509 -57
- package/package.json +4 -4
package/dist/worker.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// src/worker.ts
|
|
2
|
-
import { Buffer } from "node:buffer";
|
|
2
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
|
-
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { chmod, mkdir as mkdir2, readFile, writeFile } from "node:fs/promises";
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
|
-
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { dirname, join as join2, resolve as resolve2 } from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { Octokit } from "@octokit/rest";
|
|
9
9
|
import {
|
|
@@ -264,20 +264,25 @@ var GITHUB_AGENT_TOOLS = [
|
|
|
264
264
|
{
|
|
265
265
|
name: "create_pull_request",
|
|
266
266
|
displayName: "Create Pull Request",
|
|
267
|
-
description: "
|
|
267
|
+
description: "Publish the local branch at the exact requested commit, verify the remote branch, then create and link a GitHub pull request in one operation. The GitHub credential remains inside the trusted plugin worker. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
|
|
268
268
|
parametersSchema: {
|
|
269
269
|
type: "object",
|
|
270
270
|
additionalProperties: false,
|
|
271
|
-
required: ["head", "base", "title"],
|
|
271
|
+
required: ["paperclipIssueId", "head", "headCommitSha", "base", "title"],
|
|
272
272
|
properties: {
|
|
273
273
|
repository: repositoryProperty,
|
|
274
274
|
paperclipIssueId: {
|
|
275
275
|
type: "string",
|
|
276
|
-
description: "
|
|
276
|
+
description: "Paperclip issue id used to resolve the trusted project workspace, mapped GitHub repository, and durable pull-request link."
|
|
277
277
|
},
|
|
278
278
|
head: {
|
|
279
279
|
type: "string",
|
|
280
|
-
description: "
|
|
280
|
+
description: "Plain local branch name to publish. Owner-qualified branches and arbitrary refspecs are rejected."
|
|
281
|
+
},
|
|
282
|
+
headCommitSha: {
|
|
283
|
+
type: "string",
|
|
284
|
+
pattern: "^[0-9a-fA-F]{40}$",
|
|
285
|
+
description: "Full 40-character commit SHA that must equal the exact local branch tip and the verified remote branch tip."
|
|
281
286
|
},
|
|
282
287
|
base: {
|
|
283
288
|
type: "string",
|
|
@@ -643,6 +648,309 @@ function getGitHubAgentToolDeclaration(name) {
|
|
|
643
648
|
return declaration;
|
|
644
649
|
}
|
|
645
650
|
|
|
651
|
+
// src/git-branch-publisher.ts
|
|
652
|
+
import { spawn } from "node:child_process";
|
|
653
|
+
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
654
|
+
import { tmpdir } from "node:os";
|
|
655
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
656
|
+
var FULL_GIT_SHA_PATTERN = /^[0-9a-f]{40}$/i;
|
|
657
|
+
var GITHUB_HOST = "github.com";
|
|
658
|
+
var MAX_GIT_OUTPUT_BYTES = 1024 * 1024;
|
|
659
|
+
var GIT_COMMAND_TIMEOUT_MS = 5 * 6e4;
|
|
660
|
+
var GIT_CREDENTIAL_HELPER = '!f() { if [ "$1" = get ]; then IFS= read -r password <&3; printf "%s\\n" username=x-access-token "password=$password"; fi; }; f';
|
|
661
|
+
var defaultRunGit = async (args, options) => {
|
|
662
|
+
return await new Promise((resolvePromise, rejectPromise) => {
|
|
663
|
+
const child = spawn("git", args, {
|
|
664
|
+
env: options.env,
|
|
665
|
+
stdio: ["ignore", "pipe", "pipe", options.credential ? "pipe" : "ignore"]
|
|
666
|
+
});
|
|
667
|
+
let stdout = "";
|
|
668
|
+
let stderr = "";
|
|
669
|
+
let settled = false;
|
|
670
|
+
let timeout;
|
|
671
|
+
const rejectOnce = (error) => {
|
|
672
|
+
if (settled) return;
|
|
673
|
+
settled = true;
|
|
674
|
+
if (timeout) clearTimeout(timeout);
|
|
675
|
+
child.kill("SIGKILL");
|
|
676
|
+
rejectPromise(error);
|
|
677
|
+
};
|
|
678
|
+
const appendOutput = (target, chunk) => {
|
|
679
|
+
if (settled) return;
|
|
680
|
+
if (target === "stdout") stdout += chunk.toString("utf8");
|
|
681
|
+
else stderr += chunk.toString("utf8");
|
|
682
|
+
if (Buffer.byteLength(stdout) + Buffer.byteLength(stderr) > MAX_GIT_OUTPUT_BYTES) {
|
|
683
|
+
rejectOnce(new Error("git output exceeded the 1 MiB safety limit"));
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const stdoutPipe = child.stdout;
|
|
687
|
+
const stderrPipe = child.stderr;
|
|
688
|
+
if (!stdoutPipe || !stderrPipe) {
|
|
689
|
+
rejectOnce(new Error("git output pipes were not available"));
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
stdoutPipe.on("data", (chunk) => appendOutput("stdout", chunk));
|
|
693
|
+
stderrPipe.on("data", (chunk) => appendOutput("stderr", chunk));
|
|
694
|
+
child.on("error", (error) => rejectOnce(error));
|
|
695
|
+
child.on("close", (code, signal) => {
|
|
696
|
+
if (settled) return;
|
|
697
|
+
settled = true;
|
|
698
|
+
if (timeout) clearTimeout(timeout);
|
|
699
|
+
if (code === 0) {
|
|
700
|
+
resolvePromise({ stdout, stderr });
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
const detail = stderr.trim() || stdout.trim() || `exit code ${code ?? "unknown"}${signal ? ` (${signal})` : ""}`;
|
|
704
|
+
rejectPromise(new Error(detail));
|
|
705
|
+
});
|
|
706
|
+
timeout = setTimeout(() => {
|
|
707
|
+
rejectOnce(new Error(`git command timed out after ${GIT_COMMAND_TIMEOUT_MS}ms`));
|
|
708
|
+
}, GIT_COMMAND_TIMEOUT_MS);
|
|
709
|
+
timeout.unref();
|
|
710
|
+
if (options.credential) {
|
|
711
|
+
const credentialPipe = child.stdio[3];
|
|
712
|
+
if (!credentialPipe || typeof credentialPipe.end !== "function") {
|
|
713
|
+
rejectOnce(new Error("git credential pipe was not available"));
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
credentialPipe.on("error", (error) => {
|
|
717
|
+
if (error.code === "EPIPE" || error.code === "ECONNRESET") return;
|
|
718
|
+
rejectOnce(error);
|
|
719
|
+
});
|
|
720
|
+
credentialPipe.end(`${options.credential}
|
|
721
|
+
`);
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
};
|
|
725
|
+
function normalizeRequiredString(value, label) {
|
|
726
|
+
const normalized = value.trim();
|
|
727
|
+
if (!normalized) {
|
|
728
|
+
throw new Error(`${label} is required.`);
|
|
729
|
+
}
|
|
730
|
+
return normalized;
|
|
731
|
+
}
|
|
732
|
+
function normalizePlainBranchName(value, label) {
|
|
733
|
+
const branch = normalizeRequiredString(value, label);
|
|
734
|
+
if (branch.includes(":") || branch.startsWith("-")) {
|
|
735
|
+
throw new Error(`${label} must be a plain local branch name, not an owner-qualified branch or refspec.`);
|
|
736
|
+
}
|
|
737
|
+
return branch;
|
|
738
|
+
}
|
|
739
|
+
function normalizeExpectedCommitSha(value) {
|
|
740
|
+
const sha = normalizeRequiredString(value, "headCommitSha").toLowerCase();
|
|
741
|
+
if (!FULL_GIT_SHA_PATTERN.test(sha)) {
|
|
742
|
+
throw new Error("headCommitSha must be a full 40-character commit SHA.");
|
|
743
|
+
}
|
|
744
|
+
return sha;
|
|
745
|
+
}
|
|
746
|
+
function normalizeGitHubRepositoryRemote(value) {
|
|
747
|
+
const normalized = normalizeRequiredString(value, "repositoryUrl");
|
|
748
|
+
let parsed;
|
|
749
|
+
try {
|
|
750
|
+
parsed = new URL(normalized);
|
|
751
|
+
} catch {
|
|
752
|
+
throw new Error("repositoryUrl must be an HTTPS GitHub repository URL.");
|
|
753
|
+
}
|
|
754
|
+
if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== GITHUB_HOST || parsed.username || parsed.password) {
|
|
755
|
+
throw new Error("repositoryUrl must be a credential-free HTTPS GitHub repository URL.");
|
|
756
|
+
}
|
|
757
|
+
const pathParts = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/").filter(Boolean);
|
|
758
|
+
if (pathParts.length !== 2) {
|
|
759
|
+
throw new Error("repositoryUrl must identify exactly one GitHub owner/repository pair.");
|
|
760
|
+
}
|
|
761
|
+
const [owner, repository] = pathParts;
|
|
762
|
+
if (!owner || !repository) {
|
|
763
|
+
throw new Error("repositoryUrl must identify exactly one GitHub owner/repository pair.");
|
|
764
|
+
}
|
|
765
|
+
return `https://${GITHUB_HOST}/${owner}/${repository}.git`;
|
|
766
|
+
}
|
|
767
|
+
function createBaseGitEnvironment() {
|
|
768
|
+
return {
|
|
769
|
+
PATH: process.env.PATH ?? "",
|
|
770
|
+
LANG: process.env.LANG ?? "C.UTF-8",
|
|
771
|
+
LC_ALL: process.env.LC_ALL ?? "C.UTF-8",
|
|
772
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
773
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
774
|
+
GIT_CONFIG_GLOBAL: "/dev/null"
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
function createAuthenticatedGitEnvironment(params) {
|
|
778
|
+
return {
|
|
779
|
+
...createBaseGitEnvironment(),
|
|
780
|
+
HOME: params.temporaryHome,
|
|
781
|
+
XDG_CONFIG_HOME: params.temporaryHome,
|
|
782
|
+
GIT_ALTERNATE_OBJECT_DIRECTORIES: params.alternateObjectDirectory,
|
|
783
|
+
GIT_CONFIG_COUNT: "3",
|
|
784
|
+
GIT_CONFIG_KEY_0: "credential.helper",
|
|
785
|
+
GIT_CONFIG_VALUE_0: "",
|
|
786
|
+
GIT_CONFIG_KEY_1: "credential.https://github.com.helper",
|
|
787
|
+
GIT_CONFIG_VALUE_1: GIT_CREDENTIAL_HELPER,
|
|
788
|
+
GIT_CONFIG_KEY_2: "core.hooksPath",
|
|
789
|
+
GIT_CONFIG_VALUE_2: "/dev/null"
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
function sanitizeGitError(error, token) {
|
|
793
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
794
|
+
return token ? raw.split(token).join("[REDACTED]") : raw;
|
|
795
|
+
}
|
|
796
|
+
async function runGitStep(runGit, args, env, failureMessage, credential = "") {
|
|
797
|
+
try {
|
|
798
|
+
return await runGit(args, {
|
|
799
|
+
env,
|
|
800
|
+
...credential ? { credential } : {}
|
|
801
|
+
});
|
|
802
|
+
} catch (error) {
|
|
803
|
+
const details = sanitizeGitError(error, credential).trim();
|
|
804
|
+
throw new Error(details ? `${failureMessage}: ${details}` : failureMessage);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
async function publishLocalBranchForPullRequest(input, dependencies = {}) {
|
|
808
|
+
const runGit = dependencies.runGit ?? defaultRunGit;
|
|
809
|
+
const workspacePath = normalizeRequiredString(input.workspacePath, "workspacePath");
|
|
810
|
+
if (!isAbsolute(workspacePath)) {
|
|
811
|
+
throw new Error("workspacePath must be absolute.");
|
|
812
|
+
}
|
|
813
|
+
const branchName = normalizePlainBranchName(input.branchName, "head");
|
|
814
|
+
const baseBranch = normalizePlainBranchName(input.baseBranch, "base");
|
|
815
|
+
if (branchName === baseBranch) {
|
|
816
|
+
throw new Error("The pull request head branch must differ from the base branch.");
|
|
817
|
+
}
|
|
818
|
+
const expectedCommitSha = normalizeExpectedCommitSha(input.expectedCommitSha);
|
|
819
|
+
const githubToken = normalizeRequiredString(input.githubToken, "GitHub token");
|
|
820
|
+
const remoteUrl = normalizeGitHubRepositoryRemote(input.repositoryUrl);
|
|
821
|
+
const remoteRef = `refs/heads/${branchName}`;
|
|
822
|
+
const baseEnvironment = createBaseGitEnvironment();
|
|
823
|
+
await runGitStep(
|
|
824
|
+
runGit,
|
|
825
|
+
["-C", workspacePath, "check-ref-format", "--branch", branchName],
|
|
826
|
+
baseEnvironment,
|
|
827
|
+
"The requested head branch name is invalid"
|
|
828
|
+
);
|
|
829
|
+
await runGitStep(
|
|
830
|
+
runGit,
|
|
831
|
+
["-C", workspacePath, "check-ref-format", "--branch", baseBranch],
|
|
832
|
+
baseEnvironment,
|
|
833
|
+
"The requested base branch name is invalid"
|
|
834
|
+
);
|
|
835
|
+
const expectedHeadRef = `refs/heads/${branchName}`;
|
|
836
|
+
const checkedOutBranchResult = await runGitStep(
|
|
837
|
+
runGit,
|
|
838
|
+
["-C", workspacePath, "symbolic-ref", "--quiet", "HEAD"],
|
|
839
|
+
baseEnvironment,
|
|
840
|
+
"Could not resolve the execution worktree branch"
|
|
841
|
+
);
|
|
842
|
+
const checkedOutBranchRef = checkedOutBranchResult.stdout.trim();
|
|
843
|
+
if (checkedOutBranchRef !== expectedHeadRef) {
|
|
844
|
+
throw new Error(`The requested head branch ${branchName} is not checked out in this execution worktree. Found ${checkedOutBranchRef || "detached HEAD"}.`);
|
|
845
|
+
}
|
|
846
|
+
const checkedOutCommitResult = await runGitStep(
|
|
847
|
+
runGit,
|
|
848
|
+
["-C", workspacePath, "rev-parse", "--verify", "HEAD^{commit}"],
|
|
849
|
+
baseEnvironment,
|
|
850
|
+
"Could not resolve the execution worktree HEAD commit"
|
|
851
|
+
);
|
|
852
|
+
const checkedOutCommitSha = checkedOutCommitResult.stdout.trim().toLowerCase();
|
|
853
|
+
if (checkedOutCommitSha !== expectedCommitSha) {
|
|
854
|
+
throw new Error(`headCommitSha does not match the execution worktree HEAD. Expected ${expectedCommitSha}, found ${checkedOutCommitSha || "no commit"}.`);
|
|
855
|
+
}
|
|
856
|
+
const commonDirResult = await runGitStep(
|
|
857
|
+
runGit,
|
|
858
|
+
["-C", workspacePath, "rev-parse", "--git-common-dir"],
|
|
859
|
+
baseEnvironment,
|
|
860
|
+
"Could not resolve the workspace Git repository"
|
|
861
|
+
);
|
|
862
|
+
const commonGitDirRaw = commonDirResult.stdout.trim();
|
|
863
|
+
if (!commonGitDirRaw) {
|
|
864
|
+
throw new Error("Could not resolve the workspace Git repository: git returned an empty common directory.");
|
|
865
|
+
}
|
|
866
|
+
const commonGitDir = isAbsolute(commonGitDirRaw) ? commonGitDirRaw : resolve(workspacePath, commonGitDirRaw);
|
|
867
|
+
const localTipResult = await runGitStep(
|
|
868
|
+
runGit,
|
|
869
|
+
["-C", workspacePath, "rev-parse", "--verify", `${remoteRef}^{commit}`],
|
|
870
|
+
baseEnvironment,
|
|
871
|
+
`The local branch ${branchName} does not resolve to a commit`
|
|
872
|
+
);
|
|
873
|
+
const localTip = localTipResult.stdout.trim().toLowerCase();
|
|
874
|
+
if (localTip !== expectedCommitSha) {
|
|
875
|
+
throw new Error(`headCommitSha does not match the local branch tip for ${branchName}. Expected ${expectedCommitSha}, found ${localTip || "no commit"}.`);
|
|
876
|
+
}
|
|
877
|
+
const temporaryRoot = await mkdtemp(join(tmpdir(), "paperclip-github-publish-"));
|
|
878
|
+
const temporaryGitDir = join(temporaryRoot, "repository.git");
|
|
879
|
+
const emptyTemplateDir = join(temporaryRoot, "empty-template");
|
|
880
|
+
await mkdir(emptyTemplateDir, { mode: 448 });
|
|
881
|
+
const authenticatedEnvironment = createAuthenticatedGitEnvironment({
|
|
882
|
+
temporaryHome: temporaryRoot,
|
|
883
|
+
alternateObjectDirectory: join(commonGitDir, "objects")
|
|
884
|
+
});
|
|
885
|
+
try {
|
|
886
|
+
await runGitStep(
|
|
887
|
+
runGit,
|
|
888
|
+
["init", "--bare", `--template=${emptyTemplateDir}`, temporaryGitDir],
|
|
889
|
+
authenticatedEnvironment,
|
|
890
|
+
"Could not initialize the temporary Git publisher"
|
|
891
|
+
);
|
|
892
|
+
await runGitStep(
|
|
893
|
+
runGit,
|
|
894
|
+
[
|
|
895
|
+
"--git-dir",
|
|
896
|
+
temporaryGitDir,
|
|
897
|
+
"fetch",
|
|
898
|
+
"--no-tags",
|
|
899
|
+
remoteUrl,
|
|
900
|
+
`refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}`
|
|
901
|
+
],
|
|
902
|
+
authenticatedEnvironment,
|
|
903
|
+
`Could not fetch the pull request base branch ${baseBranch}`,
|
|
904
|
+
githubToken
|
|
905
|
+
);
|
|
906
|
+
await runGitStep(
|
|
907
|
+
runGit,
|
|
908
|
+
["--git-dir", temporaryGitDir, "rev-parse", "--verify", `refs/remotes/origin/${baseBranch}^{commit}`],
|
|
909
|
+
authenticatedEnvironment,
|
|
910
|
+
`The pull request base branch ${baseBranch} was not found on GitHub`
|
|
911
|
+
);
|
|
912
|
+
await runGitStep(
|
|
913
|
+
runGit,
|
|
914
|
+
["--git-dir", temporaryGitDir, "merge-base", "--is-ancestor", `refs/remotes/origin/${baseBranch}`, expectedCommitSha],
|
|
915
|
+
authenticatedEnvironment,
|
|
916
|
+
`The local branch ${branchName} is not based on the requested base branch ${baseBranch}`
|
|
917
|
+
);
|
|
918
|
+
await runGitStep(
|
|
919
|
+
runGit,
|
|
920
|
+
[
|
|
921
|
+
"--git-dir",
|
|
922
|
+
temporaryGitDir,
|
|
923
|
+
"push",
|
|
924
|
+
"--porcelain",
|
|
925
|
+
"--no-verify",
|
|
926
|
+
remoteUrl,
|
|
927
|
+
`${expectedCommitSha}:${remoteRef}`
|
|
928
|
+
],
|
|
929
|
+
authenticatedEnvironment,
|
|
930
|
+
`Could not publish ${branchName}; only a new branch or fast-forward update is allowed`,
|
|
931
|
+
githubToken
|
|
932
|
+
);
|
|
933
|
+
const remoteResult = await runGitStep(
|
|
934
|
+
runGit,
|
|
935
|
+
["--git-dir", temporaryGitDir, "ls-remote", "--heads", remoteUrl, remoteRef],
|
|
936
|
+
authenticatedEnvironment,
|
|
937
|
+
`Could not verify the published branch ${branchName}`,
|
|
938
|
+
githubToken
|
|
939
|
+
);
|
|
940
|
+
const remoteCommitSha = remoteResult.stdout.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
941
|
+
if (remoteCommitSha !== expectedCommitSha) {
|
|
942
|
+
throw new Error(`Remote branch verification failed for ${branchName}. Expected ${expectedCommitSha}, found ${remoteCommitSha || "no remote ref"}.`);
|
|
943
|
+
}
|
|
944
|
+
return {
|
|
945
|
+
branchName,
|
|
946
|
+
commitSha: expectedCommitSha,
|
|
947
|
+
remoteRef
|
|
948
|
+
};
|
|
949
|
+
} finally {
|
|
950
|
+
await rm(temporaryRoot, { recursive: true, force: true });
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
646
954
|
// src/github-repo.ts
|
|
647
955
|
function parseRepositoryReference(repositoryInput) {
|
|
648
956
|
const trimmed = repositoryInput.trim();
|
|
@@ -721,6 +1029,7 @@ function requiresPaperclipBoardAccessForHealth(health) {
|
|
|
721
1029
|
var GITHUB_SYNC_BASE_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}`;
|
|
722
1030
|
var GITHUB_ISSUE_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-issue`;
|
|
723
1031
|
var GITHUB_PULL_REQUEST_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-pull-request`;
|
|
1032
|
+
var createPullRequestBranchPublisher = publishLocalBranchForPullRequest;
|
|
724
1033
|
var SETTINGS_SCOPE = {
|
|
725
1034
|
scopeKind: "instance",
|
|
726
1035
|
stateKey: "paperclip-github-plugin-settings"
|
|
@@ -2669,7 +2978,7 @@ async function resolvePaperclipIssueGitHubLink(ctx, issueId, companyId, options
|
|
|
2669
2978
|
};
|
|
2670
2979
|
return await hydrateRecoveredPaperclipIssueGitHubLink(ctx, issueId, fallbackLink) ?? fallbackLink;
|
|
2671
2980
|
}
|
|
2672
|
-
async function
|
|
2981
|
+
async function listPaperclipIssueGitHubPullRequestLinks(ctx, issueId, companyId) {
|
|
2673
2982
|
const links = await listGitHubPullRequestLinkRecords(ctx, {
|
|
2674
2983
|
paperclipIssueId: issueId
|
|
2675
2984
|
});
|
|
@@ -2679,7 +2988,10 @@ async function resolvePaperclipIssueGitHubPullRequestLink(ctx, issueId, companyI
|
|
|
2679
2988
|
const safeRightTimestamp = Number.isFinite(rightTimestamp) ? rightTimestamp : 0;
|
|
2680
2989
|
const safeLeftTimestamp = Number.isFinite(leftTimestamp) ? leftTimestamp : 0;
|
|
2681
2990
|
return safeRightTimestamp - safeLeftTimestamp;
|
|
2682
|
-
})
|
|
2991
|
+
});
|
|
2992
|
+
}
|
|
2993
|
+
async function resolvePaperclipIssueGitHubPullRequestLink(ctx, issueId, companyId) {
|
|
2994
|
+
return (await listPaperclipIssueGitHubPullRequestLinks(ctx, issueId, companyId))[0] ?? null;
|
|
2683
2995
|
}
|
|
2684
2996
|
async function hydrateRecoveredPaperclipIssueGitHubLink(ctx, issueId, fallbackLink) {
|
|
2685
2997
|
const repository = parseRepositoryReference(fallbackLink.repositoryUrl);
|
|
@@ -3689,8 +4001,8 @@ async function waitForSyncResultWithinGracePeriod(promise, timeoutMs) {
|
|
|
3689
4001
|
try {
|
|
3690
4002
|
return await Promise.race([
|
|
3691
4003
|
promise,
|
|
3692
|
-
new Promise((
|
|
3693
|
-
timer = globalThis.setTimeout(() =>
|
|
4004
|
+
new Promise((resolve3) => {
|
|
4005
|
+
timer = globalThis.setTimeout(() => resolve3(null), timeoutMs);
|
|
3694
4006
|
})
|
|
3695
4007
|
]);
|
|
3696
4008
|
} finally {
|
|
@@ -3770,16 +4082,16 @@ function normalizeGitHubToken(value) {
|
|
|
3770
4082
|
}
|
|
3771
4083
|
function getExternalConfigFilePath() {
|
|
3772
4084
|
const paperclipHomeDirectory = getPaperclipHomeDirectory();
|
|
3773
|
-
return paperclipHomeDirectory ?
|
|
4085
|
+
return paperclipHomeDirectory ? join2(paperclipHomeDirectory, "plugins", "github-sync", "config.json") : void 0;
|
|
3774
4086
|
}
|
|
3775
4087
|
function getPaperclipHomeDirectory() {
|
|
3776
4088
|
const configuredPaperclipHome = process.env.PAPERCLIP_HOME?.trim();
|
|
3777
4089
|
if (configuredPaperclipHome) {
|
|
3778
|
-
return
|
|
4090
|
+
return resolve2(configuredPaperclipHome);
|
|
3779
4091
|
}
|
|
3780
4092
|
try {
|
|
3781
4093
|
const resolvedHomeDirectory = homedir();
|
|
3782
|
-
return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ?
|
|
4094
|
+
return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ? join2(resolvedHomeDirectory, ".paperclip") : void 0;
|
|
3783
4095
|
} catch {
|
|
3784
4096
|
return void 0;
|
|
3785
4097
|
}
|
|
@@ -3866,7 +4178,7 @@ async function writeExternalCompanyGitHubTokenFallback(ctx, companyId, token) {
|
|
|
3866
4178
|
[companyId]: token
|
|
3867
4179
|
}
|
|
3868
4180
|
};
|
|
3869
|
-
await
|
|
4181
|
+
await mkdir2(dirname(externalConfigFilePath), { recursive: true });
|
|
3870
4182
|
await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
|
|
3871
4183
|
`, {
|
|
3872
4184
|
encoding: "utf8",
|
|
@@ -3895,7 +4207,7 @@ async function writeExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
|
|
|
3895
4207
|
[companyId]: token
|
|
3896
4208
|
}
|
|
3897
4209
|
};
|
|
3898
|
-
await
|
|
4210
|
+
await mkdir2(dirname(externalConfigFilePath), { recursive: true });
|
|
3899
4211
|
await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
|
|
3900
4212
|
`, {
|
|
3901
4213
|
encoding: "utf8",
|
|
@@ -3928,7 +4240,7 @@ async function clearExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
|
|
|
3928
4240
|
} else {
|
|
3929
4241
|
delete nextRecord.paperclipBoardApiTokensByCompanyId;
|
|
3930
4242
|
}
|
|
3931
|
-
await
|
|
4243
|
+
await mkdir2(dirname(externalConfigFilePath), { recursive: true });
|
|
3932
4244
|
await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
|
|
3933
4245
|
`, {
|
|
3934
4246
|
encoding: "utf8",
|
|
@@ -10488,7 +10800,7 @@ function decodePullRequestAssetContent(payload) {
|
|
|
10488
10800
|
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalizedBase64) || normalizedBase64.length % 4 === 1) {
|
|
10489
10801
|
throw new Error("Asset content must be valid base64.");
|
|
10490
10802
|
}
|
|
10491
|
-
const bytes =
|
|
10803
|
+
const bytes = Buffer2.from(normalizedBase64, "base64");
|
|
10492
10804
|
if (bytes.length === 0) {
|
|
10493
10805
|
throw new Error("Asset content must not be empty.");
|
|
10494
10806
|
}
|
|
@@ -11092,12 +11404,72 @@ async function resolveGitHubIssueToolTarget(ctx, runCtx, input) {
|
|
|
11092
11404
|
async function resolveGitHubPullRequestToolTarget(ctx, runCtx, input) {
|
|
11093
11405
|
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
11094
11406
|
if (paperclipIssueId) {
|
|
11095
|
-
const link = await
|
|
11096
|
-
|
|
11407
|
+
const [link, directPullRequestLinks] = await Promise.all([
|
|
11408
|
+
resolvePaperclipIssueGitHubLink(ctx, paperclipIssueId, runCtx.companyId),
|
|
11409
|
+
listPaperclipIssueGitHubPullRequestLinks(ctx, paperclipIssueId, runCtx.companyId)
|
|
11410
|
+
]);
|
|
11411
|
+
const directPullRequestReferences = normalizeLinkedPullRequestReferences(
|
|
11412
|
+
directPullRequestLinks.map((record) => ({
|
|
11413
|
+
number: record.data.githubPullRequestNumber,
|
|
11414
|
+
repositoryUrl: record.data.repositoryUrl
|
|
11415
|
+
}))
|
|
11416
|
+
);
|
|
11417
|
+
if (!link && directPullRequestReferences.length === 0) {
|
|
11097
11418
|
throw new Error("This Paperclip issue is not linked to GitHub yet.");
|
|
11098
11419
|
}
|
|
11099
11420
|
const explicitPullRequestNumber = normalizeToolPositiveInteger(input.pullRequestNumber);
|
|
11100
|
-
|
|
11421
|
+
if (!link) {
|
|
11422
|
+
const explicitRepository = normalizeOptionalToolString(input.repository);
|
|
11423
|
+
if (explicitPullRequestNumber !== void 0) {
|
|
11424
|
+
const matchingPullRequests = directPullRequestReferences.filter(
|
|
11425
|
+
(pullRequest) => pullRequest.number === explicitPullRequestNumber
|
|
11426
|
+
);
|
|
11427
|
+
if (explicitRepository) {
|
|
11428
|
+
const requestedRepository = requireRepositoryReference(explicitRepository);
|
|
11429
|
+
const matchingPullRequest = matchingPullRequests.find(
|
|
11430
|
+
(pullRequest) => areRepositoriesEqual(requestedRepository, requireRepositoryReference(pullRequest.repositoryUrl))
|
|
11431
|
+
);
|
|
11432
|
+
if (!matchingPullRequest) {
|
|
11433
|
+
throw new Error("repository and pullRequestNumber must match a pull request directly linked to the provided Paperclip issue.");
|
|
11434
|
+
}
|
|
11435
|
+
return {
|
|
11436
|
+
repository: requestedRepository,
|
|
11437
|
+
pullRequestNumber: explicitPullRequestNumber,
|
|
11438
|
+
paperclipIssueId
|
|
11439
|
+
};
|
|
11440
|
+
}
|
|
11441
|
+
if (matchingPullRequests.length === 1) {
|
|
11442
|
+
return {
|
|
11443
|
+
repository: requireRepositoryReference(matchingPullRequests[0].repositoryUrl),
|
|
11444
|
+
pullRequestNumber: explicitPullRequestNumber,
|
|
11445
|
+
paperclipIssueId
|
|
11446
|
+
};
|
|
11447
|
+
}
|
|
11448
|
+
if (matchingPullRequests.length > 1) {
|
|
11449
|
+
throw new Error("repository is required because the Paperclip issue has matching direct pull request links in multiple repositories.");
|
|
11450
|
+
}
|
|
11451
|
+
throw new Error("pullRequestNumber must match a pull request directly linked to the provided Paperclip issue.");
|
|
11452
|
+
}
|
|
11453
|
+
if (directPullRequestReferences.length === 1) {
|
|
11454
|
+
const inferredPullRequest = directPullRequestReferences[0];
|
|
11455
|
+
if (explicitRepository) {
|
|
11456
|
+
const requestedRepository = requireRepositoryReference(explicitRepository);
|
|
11457
|
+
if (!areRepositoriesEqual(requestedRepository, requireRepositoryReference(inferredPullRequest.repositoryUrl))) {
|
|
11458
|
+
throw new Error("repository must match the GitHub repository for the directly linked pull request.");
|
|
11459
|
+
}
|
|
11460
|
+
}
|
|
11461
|
+
return {
|
|
11462
|
+
repository: requireRepositoryReference(inferredPullRequest.repositoryUrl),
|
|
11463
|
+
pullRequestNumber: inferredPullRequest.number,
|
|
11464
|
+
paperclipIssueId
|
|
11465
|
+
};
|
|
11466
|
+
}
|
|
11467
|
+
throw new Error("pullRequestNumber is required unless the Paperclip issue has exactly one directly linked pull request.");
|
|
11468
|
+
}
|
|
11469
|
+
const linkedPullRequests = normalizeLinkedPullRequestReferences([
|
|
11470
|
+
...link.linkedPullRequests.length > 0 ? link.linkedPullRequests : normalizeLinkedPullRequestReferences(link.linkedPullRequestNumbers, link.repositoryUrl),
|
|
11471
|
+
...directPullRequestReferences
|
|
11472
|
+
]);
|
|
11101
11473
|
if (explicitPullRequestNumber !== void 0) {
|
|
11102
11474
|
const explicitRepository = normalizeOptionalToolString(input.repository);
|
|
11103
11475
|
const matchingLinkedPullRequests = linkedPullRequests.filter(
|
|
@@ -15066,52 +15438,124 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15066
15438
|
const input = getToolInputRecord(params);
|
|
15067
15439
|
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
15068
15440
|
const explicitRepository = normalizeOptionalToolString(input.repository);
|
|
15069
|
-
const issueLinkScope = paperclipIssueId && !explicitRepository ? await resolveIssueGitHubLinkMapping(ctx, {
|
|
15070
|
-
companyId: runCtx.companyId,
|
|
15071
|
-
issueId: paperclipIssueId
|
|
15072
|
-
}) : null;
|
|
15073
|
-
const repository = issueLinkScope?.repository ?? await resolveGitHubToolRepository(ctx, runCtx, input);
|
|
15074
15441
|
const head = normalizeOptionalToolString(input.head);
|
|
15442
|
+
const headCommitSha = normalizeOptionalToolString(input.headCommitSha);
|
|
15075
15443
|
const base = normalizeOptionalToolString(input.base);
|
|
15076
15444
|
const title = normalizeOptionalToolString(input.title);
|
|
15077
|
-
if (!head || !base || !title) {
|
|
15078
|
-
throw new Error("head, base, and title are required.");
|
|
15445
|
+
if (!paperclipIssueId || !head || !headCommitSha || !base || !title) {
|
|
15446
|
+
throw new Error("paperclipIssueId, head, headCommitSha, base, and title are required.");
|
|
15447
|
+
}
|
|
15448
|
+
const issueLinkScope = await resolveIssueGitHubLinkMapping(ctx, {
|
|
15449
|
+
companyId: runCtx.companyId,
|
|
15450
|
+
issueId: paperclipIssueId,
|
|
15451
|
+
...explicitRepository ? { repositoryUrl: explicitRepository } : {}
|
|
15452
|
+
});
|
|
15453
|
+
if (issueLinkScope.projectId !== runCtx.projectId) {
|
|
15454
|
+
throw new Error("The selected Paperclip issue does not belong to the current tool run project.");
|
|
15455
|
+
}
|
|
15456
|
+
if (issueLinkScope.issue.assigneeAgentId && issueLinkScope.issue.assigneeAgentId !== runCtx.agentId) {
|
|
15457
|
+
throw new Error("The selected Paperclip issue is assigned to another agent.");
|
|
15079
15458
|
}
|
|
15459
|
+
await ctx.issues.assertCheckoutOwner({
|
|
15460
|
+
issueId: paperclipIssueId,
|
|
15461
|
+
companyId: runCtx.companyId,
|
|
15462
|
+
actorAgentId: runCtx.agentId,
|
|
15463
|
+
actorRunId: runCtx.runId
|
|
15464
|
+
});
|
|
15465
|
+
const executionWorkspaceId = normalizeOptionalToolString(issueLinkScope.issue.executionWorkspaceId);
|
|
15466
|
+
if (!executionWorkspaceId) {
|
|
15467
|
+
throw new Error("The selected Paperclip issue does not have an execution workspace for branch publication.");
|
|
15468
|
+
}
|
|
15469
|
+
const workspace = await ctx.executionWorkspaces.get(executionWorkspaceId, runCtx.companyId);
|
|
15470
|
+
if (!workspace || workspace.companyId !== runCtx.companyId || workspace.projectId !== runCtx.projectId) {
|
|
15471
|
+
throw new Error("The selected Paperclip issue execution workspace does not belong to the current tool run project.");
|
|
15472
|
+
}
|
|
15473
|
+
const workspacePath = normalizeOptionalToolString(workspace.cwd) ?? normalizeOptionalToolString(workspace.path);
|
|
15474
|
+
if (!workspacePath) {
|
|
15475
|
+
throw new Error("The selected Paperclip issue execution workspace is not locally realized.");
|
|
15476
|
+
}
|
|
15477
|
+
const workspaceRepository = workspace.repoUrl ? parseRepositoryReference(workspace.repoUrl) : null;
|
|
15478
|
+
const repository = issueLinkScope.repository;
|
|
15479
|
+
if (!workspaceRepository || !areRepositoriesEqual(workspaceRepository, repository)) {
|
|
15480
|
+
throw new Error("The execution workspace repository does not match the GitHub repository mapped to this Paperclip issue.");
|
|
15481
|
+
}
|
|
15482
|
+
const githubToken = (await resolveGithubToken(ctx, { companyId: runCtx.companyId })).trim();
|
|
15483
|
+
if (!githubToken) {
|
|
15484
|
+
throw new Error(MISSING_GITHUB_TOKEN_SYNC_MESSAGE);
|
|
15485
|
+
}
|
|
15486
|
+
const publishedBranch = await createPullRequestBranchPublisher({
|
|
15487
|
+
workspacePath,
|
|
15488
|
+
repositoryUrl: repository.url,
|
|
15489
|
+
branchName: head,
|
|
15490
|
+
expectedCommitSha: headCommitSha,
|
|
15491
|
+
baseBranch: base,
|
|
15492
|
+
githubToken
|
|
15493
|
+
});
|
|
15080
15494
|
const body = typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(
|
|
15081
15495
|
input.body,
|
|
15082
15496
|
"pull request description",
|
|
15083
15497
|
normalizeOptionalToolString(input.llmModel)
|
|
15084
15498
|
) : void 0;
|
|
15085
|
-
const octokit =
|
|
15086
|
-
|
|
15087
|
-
|
|
15088
|
-
|
|
15089
|
-
|
|
15090
|
-
base,
|
|
15091
|
-
title,
|
|
15092
|
-
...body !== void 0 ? { body } : {},
|
|
15093
|
-
...typeof input.draft === "boolean" ? { draft: input.draft } : {},
|
|
15094
|
-
headers: {
|
|
15095
|
-
"X-GitHub-Api-Version": GITHUB_API_VERSION
|
|
15096
|
-
}
|
|
15499
|
+
const octokit = createGitHubOctokit(ctx, githubToken, {
|
|
15500
|
+
companyId: runCtx.companyId,
|
|
15501
|
+
operation: "github-api",
|
|
15502
|
+
repositoryUrl: repository.url,
|
|
15503
|
+
toolName: "create_pull_request"
|
|
15097
15504
|
});
|
|
15505
|
+
let pullRequestData;
|
|
15506
|
+
try {
|
|
15507
|
+
pullRequestData = (await octokit.rest.pulls.create({
|
|
15508
|
+
owner: repository.owner,
|
|
15509
|
+
repo: repository.repo,
|
|
15510
|
+
head: publishedBranch.branchName,
|
|
15511
|
+
base,
|
|
15512
|
+
title,
|
|
15513
|
+
...body !== void 0 ? { body } : {},
|
|
15514
|
+
...typeof input.draft === "boolean" ? { draft: input.draft } : {},
|
|
15515
|
+
headers: {
|
|
15516
|
+
"X-GitHub-Api-Version": GITHUB_API_VERSION
|
|
15517
|
+
}
|
|
15518
|
+
})).data;
|
|
15519
|
+
} catch (error) {
|
|
15520
|
+
if (getErrorStatus(error) !== 422) {
|
|
15521
|
+
throw error;
|
|
15522
|
+
}
|
|
15523
|
+
const existingResponse = await octokit.rest.pulls.list({
|
|
15524
|
+
owner: repository.owner,
|
|
15525
|
+
repo: repository.repo,
|
|
15526
|
+
state: "open",
|
|
15527
|
+
head: `${repository.owner}:${publishedBranch.branchName}`,
|
|
15528
|
+
base,
|
|
15529
|
+
per_page: 100,
|
|
15530
|
+
headers: {
|
|
15531
|
+
"X-GitHub-Api-Version": GITHUB_API_VERSION
|
|
15532
|
+
}
|
|
15533
|
+
});
|
|
15534
|
+
const existingPullRequest = existingResponse.data.find(
|
|
15535
|
+
(candidate) => candidate.head.ref === publishedBranch.branchName && candidate.base.ref === base && candidate.head.sha.toLowerCase() === publishedBranch.commitSha.toLowerCase()
|
|
15536
|
+
);
|
|
15537
|
+
if (!existingPullRequest) {
|
|
15538
|
+
throw error;
|
|
15539
|
+
}
|
|
15540
|
+
pullRequestData = existingPullRequest;
|
|
15541
|
+
}
|
|
15098
15542
|
if (paperclipIssueId) {
|
|
15099
15543
|
const linkScope = issueLinkScope ?? await resolveIssueGitHubLinkMapping(ctx, {
|
|
15100
15544
|
companyId: runCtx.companyId,
|
|
15101
15545
|
issueId: paperclipIssueId,
|
|
15102
15546
|
repositoryUrl: repository.url
|
|
15103
15547
|
});
|
|
15104
|
-
const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(
|
|
15548
|
+
const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(pullRequestData.html_url) ?? `${repository.url}/pull/${pullRequestData.number}`;
|
|
15105
15549
|
await upsertGitHubPullRequestLinkRecord(ctx, {
|
|
15106
15550
|
companyId: runCtx.companyId,
|
|
15107
15551
|
projectId: linkScope.mapping.paperclipProjectId ?? linkScope.projectId,
|
|
15108
15552
|
issueId: paperclipIssueId,
|
|
15109
15553
|
repositoryUrl: repository.url,
|
|
15110
|
-
pullRequestNumber:
|
|
15554
|
+
pullRequestNumber: pullRequestData.number,
|
|
15111
15555
|
pullRequestUrl,
|
|
15112
|
-
pullRequestTitle:
|
|
15556
|
+
pullRequestTitle: pullRequestData.title || title,
|
|
15113
15557
|
pullRequestState: getGitHubPullRequestStateForLink({
|
|
15114
|
-
state:
|
|
15558
|
+
state: pullRequestData.state,
|
|
15115
15559
|
merged: false
|
|
15116
15560
|
})
|
|
15117
15561
|
});
|
|
@@ -15127,26 +15571,31 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15127
15571
|
companyId: runCtx.companyId,
|
|
15128
15572
|
metric: "paperclipPullRequestsCreatedCount",
|
|
15129
15573
|
repositoryUrl: repository.url,
|
|
15130
|
-
pullRequestNumber:
|
|
15131
|
-
pullRequestUrl:
|
|
15574
|
+
pullRequestNumber: pullRequestData.number,
|
|
15575
|
+
pullRequestUrl: pullRequestData.html_url ?? void 0
|
|
15132
15576
|
},
|
|
15133
15577
|
{
|
|
15134
15578
|
throwOnPersistFailure: false
|
|
15135
15579
|
}
|
|
15136
15580
|
);
|
|
15137
15581
|
return buildToolSuccessResult(
|
|
15138
|
-
`Created pull request #${
|
|
15582
|
+
`Created pull request #${pullRequestData.number} in ${formatRepositoryLabel(repository)}.`,
|
|
15139
15583
|
{
|
|
15140
15584
|
repository: repository.url,
|
|
15585
|
+
publishedBranch: {
|
|
15586
|
+
name: publishedBranch.branchName,
|
|
15587
|
+
commitSha: publishedBranch.commitSha,
|
|
15588
|
+
remoteRef: publishedBranch.remoteRef
|
|
15589
|
+
},
|
|
15141
15590
|
pullRequest: {
|
|
15142
|
-
number:
|
|
15143
|
-
title:
|
|
15144
|
-
body:
|
|
15145
|
-
url:
|
|
15146
|
-
state:
|
|
15147
|
-
isDraft:
|
|
15148
|
-
headRefName:
|
|
15149
|
-
baseRefName:
|
|
15591
|
+
number: pullRequestData.number,
|
|
15592
|
+
title: pullRequestData.title,
|
|
15593
|
+
body: pullRequestData.body ?? "",
|
|
15594
|
+
url: pullRequestData.html_url,
|
|
15595
|
+
state: pullRequestData.state,
|
|
15596
|
+
isDraft: pullRequestData.draft,
|
|
15597
|
+
headRefName: pullRequestData.head.ref,
|
|
15598
|
+
baseRefName: pullRequestData.base.ref
|
|
15150
15599
|
}
|
|
15151
15600
|
}
|
|
15152
15601
|
);
|
|
@@ -15683,7 +16132,7 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
|
|
|
15683
16132
|
try {
|
|
15684
16133
|
return realpathSync(entry) === realpathSync(modulePath);
|
|
15685
16134
|
} catch {
|
|
15686
|
-
return
|
|
16135
|
+
return resolve2(entry) === resolve2(modulePath);
|
|
15687
16136
|
}
|
|
15688
16137
|
}
|
|
15689
16138
|
var __testing = {
|
|
@@ -15695,7 +16144,10 @@ var __testing = {
|
|
|
15695
16144
|
resolvePaperclipApiAuthTokens,
|
|
15696
16145
|
resolveGithubToken,
|
|
15697
16146
|
resolvePaperclipPullRequestIssueStatus,
|
|
15698
|
-
resolveSyncTransitionAssignee
|
|
16147
|
+
resolveSyncTransitionAssignee,
|
|
16148
|
+
setCreatePullRequestBranchPublisher(publisher) {
|
|
16149
|
+
createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
|
|
16150
|
+
}
|
|
15699
16151
|
};
|
|
15700
16152
|
var plugin = definePlugin({
|
|
15701
16153
|
async setup(ctx) {
|