paperclip-github-plugin 0.12.0 → 0.14.0

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/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: "Open a GitHub pull request once the implementation branch is pushed. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
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: "Optional Paperclip issue id to link with the created pull request so GitHub Sync can monitor PR status for that issue."
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: "Head branch name or owner:branch."
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"
@@ -3689,8 +3998,8 @@ async function waitForSyncResultWithinGracePeriod(promise, timeoutMs) {
3689
3998
  try {
3690
3999
  return await Promise.race([
3691
4000
  promise,
3692
- new Promise((resolve2) => {
3693
- timer = globalThis.setTimeout(() => resolve2(null), timeoutMs);
4001
+ new Promise((resolve3) => {
4002
+ timer = globalThis.setTimeout(() => resolve3(null), timeoutMs);
3694
4003
  })
3695
4004
  ]);
3696
4005
  } finally {
@@ -3770,16 +4079,16 @@ function normalizeGitHubToken(value) {
3770
4079
  }
3771
4080
  function getExternalConfigFilePath() {
3772
4081
  const paperclipHomeDirectory = getPaperclipHomeDirectory();
3773
- return paperclipHomeDirectory ? join(paperclipHomeDirectory, "plugins", "github-sync", "config.json") : void 0;
4082
+ return paperclipHomeDirectory ? join2(paperclipHomeDirectory, "plugins", "github-sync", "config.json") : void 0;
3774
4083
  }
3775
4084
  function getPaperclipHomeDirectory() {
3776
4085
  const configuredPaperclipHome = process.env.PAPERCLIP_HOME?.trim();
3777
4086
  if (configuredPaperclipHome) {
3778
- return resolve(configuredPaperclipHome);
4087
+ return resolve2(configuredPaperclipHome);
3779
4088
  }
3780
4089
  try {
3781
4090
  const resolvedHomeDirectory = homedir();
3782
- return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ? join(resolvedHomeDirectory, ".paperclip") : void 0;
4091
+ return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ? join2(resolvedHomeDirectory, ".paperclip") : void 0;
3783
4092
  } catch {
3784
4093
  return void 0;
3785
4094
  }
@@ -3866,7 +4175,7 @@ async function writeExternalCompanyGitHubTokenFallback(ctx, companyId, token) {
3866
4175
  [companyId]: token
3867
4176
  }
3868
4177
  };
3869
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4178
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3870
4179
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3871
4180
  `, {
3872
4181
  encoding: "utf8",
@@ -3895,7 +4204,7 @@ async function writeExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
3895
4204
  [companyId]: token
3896
4205
  }
3897
4206
  };
3898
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4207
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3899
4208
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3900
4209
  `, {
3901
4210
  encoding: "utf8",
@@ -3928,7 +4237,7 @@ async function clearExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
3928
4237
  } else {
3929
4238
  delete nextRecord.paperclipBoardApiTokensByCompanyId;
3930
4239
  }
3931
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4240
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3932
4241
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3933
4242
  `, {
3934
4243
  encoding: "utf8",
@@ -4097,10 +4406,6 @@ function normalizeIgnoredIssueAuthorUsernames(value) {
4097
4406
  const entries = Array.isArray(value) ? value.map((entry) => normalizeGitHubUsername(entry)).filter((entry) => Boolean(entry)) : typeof value === "string" ? parseIgnoredIssueAuthorUsernames(value) : [];
4098
4407
  return [...new Set(entries)];
4099
4408
  }
4100
- function normalizeAgentIds(value) {
4101
- const entries = Array.isArray(value) ? value.map((entry) => normalizeOptionalString2(entry)).filter((entry) => Boolean(entry)) : [];
4102
- return [...new Set(entries)].sort((left, right) => left.localeCompare(right));
4103
- }
4104
4409
  function normalizeAdvancedSettingsAssigneeOverride(record, keys) {
4105
4410
  const userId = normalizeOptionalString2(record[keys.userId]);
4106
4411
  if (userId) {
@@ -4123,7 +4428,6 @@ function normalizeAdvancedSettings(value) {
4123
4428
  const record = value;
4124
4429
  const defaultStatus = "defaultStatus" in record ? coercePaperclipIssueStatus(record.defaultStatus) : DEFAULT_ADVANCED_SETTINGS.defaultStatus;
4125
4430
  const ignoredIssueAuthorUsernames = "ignoredIssueAuthorUsernames" in record ? normalizeIgnoredIssueAuthorUsernames(record.ignoredIssueAuthorUsernames) : DEFAULT_ADVANCED_SETTINGS.ignoredIssueAuthorUsernames;
4126
- const githubTokenPropagationAgentIds = "githubTokenPropagationAgentIds" in record ? normalizeAgentIds(record.githubTokenPropagationAgentIds) : [];
4127
4431
  return {
4128
4432
  ...normalizeAdvancedSettingsAssigneeOverride(record, {
4129
4433
  agentId: "defaultAssigneeAgentId",
@@ -4142,8 +4446,7 @@ function normalizeAdvancedSettings(value) {
4142
4446
  userId: "approverAssigneeUserId"
4143
4447
  }),
4144
4448
  defaultStatus,
4145
- ignoredIssueAuthorUsernames,
4146
- ...githubTokenPropagationAgentIds.length > 0 ? { githubTokenPropagationAgentIds } : {}
4449
+ ignoredIssueAuthorUsernames
4147
4450
  };
4148
4451
  }
4149
4452
  function normalizeCompanyAdvancedSettingsByCompanyId(value) {
@@ -10494,7 +10797,7 @@ function decodePullRequestAssetContent(payload) {
10494
10797
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalizedBase64) || normalizedBase64.length % 4 === 1) {
10495
10798
  throw new Error("Asset content must be valid base64.");
10496
10799
  }
10497
- const bytes = Buffer.from(normalizedBase64, "base64");
10800
+ const bytes = Buffer2.from(normalizedBase64, "base64");
10498
10801
  if (bytes.length === 0) {
10499
10802
  throw new Error("Asset content must not be empty.");
10500
10803
  }
@@ -15072,52 +15375,124 @@ function registerGitHubAgentTools(ctx) {
15072
15375
  const input = getToolInputRecord(params);
15073
15376
  const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15074
15377
  const explicitRepository = normalizeOptionalToolString(input.repository);
15075
- const issueLinkScope = paperclipIssueId && !explicitRepository ? await resolveIssueGitHubLinkMapping(ctx, {
15076
- companyId: runCtx.companyId,
15077
- issueId: paperclipIssueId
15078
- }) : null;
15079
- const repository = issueLinkScope?.repository ?? await resolveGitHubToolRepository(ctx, runCtx, input);
15080
15378
  const head = normalizeOptionalToolString(input.head);
15379
+ const headCommitSha = normalizeOptionalToolString(input.headCommitSha);
15081
15380
  const base = normalizeOptionalToolString(input.base);
15082
15381
  const title = normalizeOptionalToolString(input.title);
15083
- if (!head || !base || !title) {
15084
- throw new Error("head, base, and title are required.");
15382
+ if (!paperclipIssueId || !head || !headCommitSha || !base || !title) {
15383
+ throw new Error("paperclipIssueId, head, headCommitSha, base, and title are required.");
15384
+ }
15385
+ const issueLinkScope = await resolveIssueGitHubLinkMapping(ctx, {
15386
+ companyId: runCtx.companyId,
15387
+ issueId: paperclipIssueId,
15388
+ ...explicitRepository ? { repositoryUrl: explicitRepository } : {}
15389
+ });
15390
+ if (issueLinkScope.projectId !== runCtx.projectId) {
15391
+ throw new Error("The selected Paperclip issue does not belong to the current tool run project.");
15392
+ }
15393
+ if (issueLinkScope.issue.assigneeAgentId && issueLinkScope.issue.assigneeAgentId !== runCtx.agentId) {
15394
+ throw new Error("The selected Paperclip issue is assigned to another agent.");
15395
+ }
15396
+ await ctx.issues.assertCheckoutOwner({
15397
+ issueId: paperclipIssueId,
15398
+ companyId: runCtx.companyId,
15399
+ actorAgentId: runCtx.agentId,
15400
+ actorRunId: runCtx.runId
15401
+ });
15402
+ const executionWorkspaceId = normalizeOptionalToolString(issueLinkScope.issue.executionWorkspaceId);
15403
+ if (!executionWorkspaceId) {
15404
+ throw new Error("The selected Paperclip issue does not have an execution workspace for branch publication.");
15085
15405
  }
15406
+ const workspace = await ctx.executionWorkspaces.get(executionWorkspaceId, runCtx.companyId);
15407
+ if (!workspace || workspace.companyId !== runCtx.companyId || workspace.projectId !== runCtx.projectId) {
15408
+ throw new Error("The selected Paperclip issue execution workspace does not belong to the current tool run project.");
15409
+ }
15410
+ const workspacePath = normalizeOptionalToolString(workspace.cwd) ?? normalizeOptionalToolString(workspace.path);
15411
+ if (!workspacePath) {
15412
+ throw new Error("The selected Paperclip issue execution workspace is not locally realized.");
15413
+ }
15414
+ const workspaceRepository = workspace.repoUrl ? parseRepositoryReference(workspace.repoUrl) : null;
15415
+ const repository = issueLinkScope.repository;
15416
+ if (!workspaceRepository || !areRepositoriesEqual(workspaceRepository, repository)) {
15417
+ throw new Error("The execution workspace repository does not match the GitHub repository mapped to this Paperclip issue.");
15418
+ }
15419
+ const githubToken = (await resolveGithubToken(ctx, { companyId: runCtx.companyId })).trim();
15420
+ if (!githubToken) {
15421
+ throw new Error(MISSING_GITHUB_TOKEN_SYNC_MESSAGE);
15422
+ }
15423
+ const publishedBranch = await createPullRequestBranchPublisher({
15424
+ workspacePath,
15425
+ repositoryUrl: repository.url,
15426
+ branchName: head,
15427
+ expectedCommitSha: headCommitSha,
15428
+ baseBranch: base,
15429
+ githubToken
15430
+ });
15086
15431
  const body = typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(
15087
15432
  input.body,
15088
15433
  "pull request description",
15089
15434
  normalizeOptionalToolString(input.llmModel)
15090
15435
  ) : void 0;
15091
- const octokit = await createAgentToolOctokit(runCtx, "create_pull_request", repository);
15092
- const response = await octokit.rest.pulls.create({
15093
- owner: repository.owner,
15094
- repo: repository.repo,
15095
- head,
15096
- base,
15097
- title,
15098
- ...body !== void 0 ? { body } : {},
15099
- ...typeof input.draft === "boolean" ? { draft: input.draft } : {},
15100
- headers: {
15101
- "X-GitHub-Api-Version": GITHUB_API_VERSION
15102
- }
15436
+ const octokit = createGitHubOctokit(ctx, githubToken, {
15437
+ companyId: runCtx.companyId,
15438
+ operation: "github-api",
15439
+ repositoryUrl: repository.url,
15440
+ toolName: "create_pull_request"
15103
15441
  });
15442
+ let pullRequestData;
15443
+ try {
15444
+ pullRequestData = (await octokit.rest.pulls.create({
15445
+ owner: repository.owner,
15446
+ repo: repository.repo,
15447
+ head: publishedBranch.branchName,
15448
+ base,
15449
+ title,
15450
+ ...body !== void 0 ? { body } : {},
15451
+ ...typeof input.draft === "boolean" ? { draft: input.draft } : {},
15452
+ headers: {
15453
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
15454
+ }
15455
+ })).data;
15456
+ } catch (error) {
15457
+ if (getErrorStatus(error) !== 422) {
15458
+ throw error;
15459
+ }
15460
+ const existingResponse = await octokit.rest.pulls.list({
15461
+ owner: repository.owner,
15462
+ repo: repository.repo,
15463
+ state: "open",
15464
+ head: `${repository.owner}:${publishedBranch.branchName}`,
15465
+ base,
15466
+ per_page: 100,
15467
+ headers: {
15468
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
15469
+ }
15470
+ });
15471
+ const existingPullRequest = existingResponse.data.find(
15472
+ (candidate) => candidate.head.ref === publishedBranch.branchName && candidate.base.ref === base && candidate.head.sha.toLowerCase() === publishedBranch.commitSha.toLowerCase()
15473
+ );
15474
+ if (!existingPullRequest) {
15475
+ throw error;
15476
+ }
15477
+ pullRequestData = existingPullRequest;
15478
+ }
15104
15479
  if (paperclipIssueId) {
15105
15480
  const linkScope = issueLinkScope ?? await resolveIssueGitHubLinkMapping(ctx, {
15106
15481
  companyId: runCtx.companyId,
15107
15482
  issueId: paperclipIssueId,
15108
15483
  repositoryUrl: repository.url
15109
15484
  });
15110
- const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(response.data.html_url) ?? `${repository.url}/pull/${response.data.number}`;
15485
+ const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(pullRequestData.html_url) ?? `${repository.url}/pull/${pullRequestData.number}`;
15111
15486
  await upsertGitHubPullRequestLinkRecord(ctx, {
15112
15487
  companyId: runCtx.companyId,
15113
15488
  projectId: linkScope.mapping.paperclipProjectId ?? linkScope.projectId,
15114
15489
  issueId: paperclipIssueId,
15115
15490
  repositoryUrl: repository.url,
15116
- pullRequestNumber: response.data.number,
15491
+ pullRequestNumber: pullRequestData.number,
15117
15492
  pullRequestUrl,
15118
- pullRequestTitle: response.data.title || title,
15493
+ pullRequestTitle: pullRequestData.title || title,
15119
15494
  pullRequestState: getGitHubPullRequestStateForLink({
15120
- state: response.data.state,
15495
+ state: pullRequestData.state,
15121
15496
  merged: false
15122
15497
  })
15123
15498
  });
@@ -15133,26 +15508,31 @@ function registerGitHubAgentTools(ctx) {
15133
15508
  companyId: runCtx.companyId,
15134
15509
  metric: "paperclipPullRequestsCreatedCount",
15135
15510
  repositoryUrl: repository.url,
15136
- pullRequestNumber: response.data.number,
15137
- pullRequestUrl: response.data.html_url ?? void 0
15511
+ pullRequestNumber: pullRequestData.number,
15512
+ pullRequestUrl: pullRequestData.html_url ?? void 0
15138
15513
  },
15139
15514
  {
15140
15515
  throwOnPersistFailure: false
15141
15516
  }
15142
15517
  );
15143
15518
  return buildToolSuccessResult(
15144
- `Created pull request #${response.data.number} in ${formatRepositoryLabel(repository)}.`,
15519
+ `Created pull request #${pullRequestData.number} in ${formatRepositoryLabel(repository)}.`,
15145
15520
  {
15146
15521
  repository: repository.url,
15522
+ publishedBranch: {
15523
+ name: publishedBranch.branchName,
15524
+ commitSha: publishedBranch.commitSha,
15525
+ remoteRef: publishedBranch.remoteRef
15526
+ },
15147
15527
  pullRequest: {
15148
- number: response.data.number,
15149
- title: response.data.title,
15150
- body: response.data.body ?? "",
15151
- url: response.data.html_url,
15152
- state: response.data.state,
15153
- isDraft: response.data.draft,
15154
- headRefName: response.data.head.ref,
15155
- baseRefName: response.data.base.ref
15528
+ number: pullRequestData.number,
15529
+ title: pullRequestData.title,
15530
+ body: pullRequestData.body ?? "",
15531
+ url: pullRequestData.html_url,
15532
+ state: pullRequestData.state,
15533
+ isDraft: pullRequestData.draft,
15534
+ headRefName: pullRequestData.head.ref,
15535
+ baseRefName: pullRequestData.base.ref
15156
15536
  }
15157
15537
  }
15158
15538
  );
@@ -15689,7 +16069,7 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
15689
16069
  try {
15690
16070
  return realpathSync(entry) === realpathSync(modulePath);
15691
16071
  } catch {
15692
- return resolve(entry) === resolve(modulePath);
16072
+ return resolve2(entry) === resolve2(modulePath);
15693
16073
  }
15694
16074
  }
15695
16075
  var __testing = {
@@ -15701,7 +16081,10 @@ var __testing = {
15701
16081
  resolvePaperclipApiAuthTokens,
15702
16082
  resolveGithubToken,
15703
16083
  resolvePaperclipPullRequestIssueStatus,
15704
- resolveSyncTransitionAssignee
16084
+ resolveSyncTransitionAssignee,
16085
+ setCreatePullRequestBranchPublisher(publisher) {
16086
+ createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
16087
+ }
15705
16088
  };
15706
16089
  var plugin = definePlugin({
15707
16090
  async setup(ctx) {