@omercnet/paseo-pr-radar 3.3.0 → 3.4.0-next.541.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.
@@ -1,22 +1,14 @@
1
- import { type ChildProcessByStdio, execFile, spawn } from "node:child_process";
2
- import { constants } from "node:fs";
1
+ import { execFile } from "node:child_process";
3
2
  import { access, mkdir, readdir, realpath, stat } from "node:fs/promises";
4
3
  import { homedir } from "node:os";
5
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
- import type { Readable, Writable } from "node:stream";
7
5
  import { promisify } from "node:util";
8
6
  import type { z } from "zod";
9
7
  import type { PrRadarSettings } from "../shared/settings";
10
- import {
11
- type LocalDirEntry,
12
- type listLocalDirs,
13
- type prepareWorkspaceCwd,
14
- RoutingScriptResultSchema,
15
- type runRoutingScript,
16
- } from "../shared/viewer-scope";
8
+ import type { LocalDirEntry, listLocalDirs, prepareWorkspaceCwd } from "../shared/viewer-scope";
17
9
 
18
10
  const execFileAsync = promisify(execFile);
19
- const COMMAND_TIMEOUT_MS = 30_000;
11
+ export const COMMAND_TIMEOUT_MS = 30_000;
20
12
  const CLONE_TIMEOUT_MS = 120_000;
21
13
  const MAX_BUFFER_BYTES = 8 * 1024 * 1024;
22
14
 
@@ -24,18 +16,6 @@ const MAX_BUFFER_BYTES = 8 * 1024 * 1024;
24
16
  export type WorkspaceOpsSettings = Pick<PrRadarSettings, "sourceCodeDir" | "routingScriptPath">;
25
17
  export type ReadWorkspaceSettings = () => Promise<WorkspaceOpsSettings>;
26
18
 
27
- export interface RoutingScriptLimits {
28
- timeoutMs: number;
29
- outputBytes: number;
30
- killGraceMs: number;
31
- }
32
-
33
- const DEFAULT_ROUTING_LIMITS: RoutingScriptLimits = {
34
- timeoutMs: COMMAND_TIMEOUT_MS,
35
- outputBytes: 1024 * 1024,
36
- killGraceMs: 2_000,
37
- };
38
-
39
19
  // Environment handed to child processes. Everything else in the daemon's environment (API keys,
40
20
  // cloud credentials, tokens for other tools) stays behind. A routing script gets only what a
41
21
  // script needs to find its interpreter and locale. gh additionally needs its own credentials and
@@ -105,7 +85,7 @@ const GIT_ENV_KEYS: ReadonlySet<string> = new Set([
105
85
  "all_proxy",
106
86
  ]);
107
87
 
108
- function allowListedEnv(extraKeys: ReadonlySet<string>): NodeJS.ProcessEnv {
88
+ export function allowListedEnv(extraKeys: ReadonlySet<string>): NodeJS.ProcessEnv {
109
89
  const env: NodeJS.ProcessEnv = {};
110
90
  for (const [key, value] of Object.entries(process.env)) {
111
91
  if (value === undefined) continue;
@@ -121,7 +101,7 @@ export function expandUserPath(rawPath: string): string {
121
101
  return resolve(trimmed);
122
102
  }
123
103
 
124
- async function exists(target: string): Promise<boolean> {
104
+ export async function exists(target: string): Promise<boolean> {
125
105
  try {
126
106
  await access(target);
127
107
  return true;
@@ -241,9 +221,7 @@ async function configuredFilterSafetyArgs(cwd: string): Promise<FilterOverride[]
241
221
  : undefined;
242
222
  if (code !== 1) {
243
223
  throw new Error(
244
- `Could not enumerate repository filter configuration in ${cwd}: ${
245
- err instanceof Error ? err.message : String(err)
246
- }`,
224
+ `Could not enumerate repository filter configuration in ${cwd}: ${errorMessage(err)}`,
247
225
  );
248
226
  }
249
227
  raw = Buffer.alloc(0);
@@ -706,27 +684,67 @@ async function assertNoIgnoredFileOverwrite(
706
684
  }
707
685
  }
708
686
 
709
- /**
710
- * Runs git and returns its stdout as UTF-8, failing closed when the output is not valid UTF-8.
711
- * `runGit` decodes lossily, which would mangle a non-UTF-8 filename and let a comparison miss it.
712
- */
713
- async function runGitLossless(
687
+ const NUL_BYTE = 0x00;
688
+ const TAB_BYTE = 0x09;
689
+ const SPACE_BYTE = 0x20;
690
+ const GITLINK_ENTRY_PREFIX = Buffer.from("160000 ");
691
+
692
+ /** Runs git and returns its stdout undecoded, so a caller can inspect names that are not UTF-8. */
693
+ async function runGitBytes(
714
694
  cwd: string,
715
695
  args: string[],
716
696
  timeout = COMMAND_TIMEOUT_MS,
717
- ): Promise<string> {
697
+ ): Promise<Buffer> {
718
698
  const { stdout } = await execFileAsync("git", [...GIT_SAFETY_ARGS, "-C", cwd, ...args], {
719
699
  timeout,
720
700
  maxBuffer: MAX_BUFFER_BYTES,
721
701
  env: gitEnv(),
722
702
  encoding: "buffer",
723
703
  });
724
- const raw = stdout as Buffer;
725
- const decoded = raw.toString("utf8");
726
- if (!Buffer.from(decoded, "utf8").equals(raw)) {
727
- throw new Error(`Git output in ${cwd} contains invalid UTF-8; refusing to proceed.`);
704
+ return stdout as Buffer;
705
+ }
706
+
707
+ /** Splits `-z` output on NUL into its non-empty records, byte for byte. */
708
+ function nulSeparatedEntries(raw: Buffer): Buffer[] {
709
+ const entries: Buffer[] = [];
710
+ let start = 0;
711
+ for (let end = raw.indexOf(NUL_BYTE); end !== -1; end = raw.indexOf(NUL_BYTE, start)) {
712
+ if (end > start) entries.push(raw.subarray(start, end));
713
+ start = end + 1;
714
+ }
715
+ if (start < raw.length) entries.push(raw.subarray(start));
716
+ return entries;
717
+ }
718
+
719
+ function hasPrefix(bytes: Buffer, prefix: Buffer): boolean {
720
+ return bytes.subarray(0, prefix.length).equals(prefix);
721
+ }
722
+
723
+ /** The path of an `ls-files -s -z` or `ls-tree -z` record: everything after its first tab. */
724
+ function entryPathBytes(entry: Buffer): Buffer {
725
+ return entry.subarray(entry.indexOf(TAB_BYTE) + 1);
726
+ }
727
+
728
+ /**
729
+ * The paths of the submodule (mode 160000) entries in `ls-files -s -z` output. Only these paths are
730
+ * decoded, and strictly: a lossy decode would mangle a non-UTF-8 submodule path and let the
731
+ * comparison against the incoming tree miss it, so that one case fails closed. Every other tracked
732
+ * name, whatever its bytes, is skipped undecoded.
733
+ */
734
+ function submodulePaths(dir: string, lsFilesOutput: Buffer): string[] {
735
+ const paths: string[] = [];
736
+ for (const entry of nulSeparatedEntries(lsFilesOutput)) {
737
+ if (!hasPrefix(entry, GITLINK_ENTRY_PREFIX)) continue;
738
+ const pathBytes = entryPathBytes(entry);
739
+ const path = pathBytes.toString("utf8");
740
+ if (!Buffer.from(path, "utf8").equals(pathBytes)) {
741
+ throw new Error(
742
+ `A submodule path in ${dir} is not valid UTF-8, so it cannot be checked against the incoming tree; refusing to proceed.`,
743
+ );
744
+ }
745
+ paths.push(path);
728
746
  }
729
- return decoded;
747
+ return paths;
730
748
  }
731
749
 
732
750
  /**
@@ -739,30 +757,25 @@ async function assertNoGitlinkToFileOverwrite(
739
757
  target: string,
740
758
  prNumber: number,
741
759
  ): Promise<void> {
742
- const gitlinks = (await runGitLossless(dir, ["ls-files", "-s", "-z"]))
743
- .split("\0")
744
- .filter((entry) => entry.startsWith("160000 "));
745
- if (gitlinks.length === 0) return;
746
- const gitlinkPaths = gitlinks
747
- .map((entry) => entry.slice(entry.indexOf("\t") + 1))
748
- .filter(Boolean);
760
+ const gitlinkPaths = submodulePaths(dir, await runGitBytes(dir, ["ls-files", "-s", "-z"]));
749
761
  if (gitlinkPaths.length === 0) return;
750
762
 
751
763
  // Returns the mode of the exact entry at `path` in the target tree (or null when absent). A leaf
752
764
  // produces exactly the entry at `path`; a directory produces only its children (`path/…`).
765
+ // Compared as bytes, so a sibling with a non-UTF-8 name can neither match nor break it.
753
766
  const targetEntryMode = async (path: string): Promise<string | null> => {
754
- const entries = (
755
- await runGitLossless(dir, ["ls-tree", "-z", target, "--", `:(literal)${path}`])
756
- )
757
- .split("\0")
758
- .filter(Boolean);
767
+ const wanted = Buffer.from(path, "utf8");
768
+ const childPrefix = Buffer.from(`${path}/`, "utf8");
769
+ const entries = nulSeparatedEntries(
770
+ await runGitBytes(dir, ["ls-tree", "-z", target, "--", `:(literal)${path}`]),
771
+ );
772
+ let hasChildren = false;
759
773
  for (const entry of entries) {
760
- if (entry.slice(entry.indexOf("\t") + 1) === path) return entry.slice(0, entry.indexOf(" "));
774
+ const entryPath = entryPathBytes(entry);
775
+ if (entryPath.equals(wanted)) return entry.subarray(0, entry.indexOf(SPACE_BYTE)).toString();
776
+ if (hasPrefix(entryPath, childPrefix)) hasChildren = true;
761
777
  }
762
- if (entries.some((entry) => entry.slice(entry.indexOf("\t") + 1).startsWith(`${path}/`))) {
763
- return "040000";
764
- }
765
- return null;
778
+ return hasChildren ? "040000" : null;
766
779
  };
767
780
 
768
781
  // A gitlink that becomes anything but another gitlink (file, symlink, directory, or removed)
@@ -789,15 +802,21 @@ async function assertNoGitlinkToFileOverwrite(
789
802
  }
790
803
  }
791
804
 
805
+ /** The checked-out branch, or null on a detached HEAD. A git failure is an error, not "detached". */
792
806
  async function currentBranch(repoDir: string): Promise<string | null> {
793
- const name = await runGit(repoDir, ["branch", "--show-current"], 3_000).catch(() => "");
807
+ const name = await runGit(repoDir, ["branch", "--show-current"], 3_000);
794
808
  return name || null;
795
809
  }
796
810
 
811
+ /** Remote branch names that stand in for a default branch the remote has not recorded. */
812
+ const CONVENTIONAL_DEFAULT_BRANCHES = ["main", "master"];
813
+
797
814
  /**
798
815
  * New issue branches start from the remote default branch. Without a recorded remote default the
799
- * current HEAD is used, but only when a remote-tracking branch already contains it: a PR branch, a
800
- * detached PR checkout or a local-only commit would carry unmerged, possibly untrusted code.
816
+ * current HEAD is used, but only when it is already on the conventional default branch (`main` or
817
+ * `master`) of the remote: a PR branch, a detached PR checkout or a local-only commit would carry
818
+ * unmerged, possibly untrusted code. Being on some other remote branch, such as a pushed PR branch,
819
+ * does not count.
801
820
  */
802
821
  async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise<string> {
803
822
  const remoteHead = await runGit(
@@ -813,30 +832,52 @@ async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise
813
832
  ).catch(() => "");
814
833
  if (resolved) return resolved;
815
834
  }
835
+ // One commit is checked and one is returned: another launch can move HEAD in between.
836
+ // `--quiet` makes an unborn HEAD (no commit yet) exit 1 without a message; a timeout or any
837
+ // other failure still surfaces as itself.
838
+ const head = await runGit(
839
+ baseRoot,
840
+ ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
841
+ 3_000,
842
+ ).catch((err: unknown) => {
843
+ if ((err as { code?: unknown } | null)?.code === 1) return "";
844
+ throw err;
845
+ });
846
+ if (!head) {
847
+ throw new Error(
848
+ `Base checkout ${baseRoot} has no recorded default branch for ${remote} and no commit checked out yet; run git remote set-head ${remote} --auto there, or make a first commit on the default branch.`,
849
+ );
850
+ }
816
851
  const branch = await currentBranch(baseRoot);
817
852
  if (branch?.startsWith("pr-radar/")) {
818
853
  throw new Error(
819
854
  `Base checkout ${baseRoot} is on ${branch} and has no recorded default branch for ${remote}; check out the default branch there, or use another directory.`,
820
855
  );
821
856
  }
822
- const published = await runGit(
823
- baseRoot,
824
- [
825
- "for-each-ref",
826
- "--count=1",
827
- "--contains",
828
- "HEAD",
829
- "--format=%(refname)",
830
- `refs/remotes/${remote}`,
831
- ],
832
- 3_000,
833
- ).catch(() => "");
834
- if (!published) {
835
- throw new Error(
836
- `Base checkout ${baseRoot} has no recorded default branch for ${remote} and its HEAD is not on any ${remote} branch, so it may carry unmerged code; run git remote set-head ${remote} --auto there, or check out the default branch.`,
857
+ for (const name of CONVENTIONAL_DEFAULT_BRANCHES) {
858
+ // `show-ref --verify` takes only the exact full ref name. `for-each-ref` would also match a
859
+ // branch named `main/x` by prefix, and `rev-parse` falls back to a tag literally named
860
+ // `refs/remotes/origin/main`; a pushed branch or tag could be named either way.
861
+ const ref = await runGit(
862
+ baseRoot,
863
+ ["show-ref", "--verify", "--hash", `refs/remotes/${remote}/${name}`],
864
+ 3_000,
865
+ ).catch(() => "");
866
+ if (!ref) continue;
867
+ const tip = await runGit(baseRoot, ["rev-parse", "--verify", `${ref}^{commit}`], 3_000);
868
+ const published = await runGit(
869
+ baseRoot,
870
+ ["merge-base", "--is-ancestor", head, tip],
871
+ 3_000,
872
+ ).then(
873
+ () => true,
874
+ () => false,
837
875
  );
876
+ if (published) return head;
838
877
  }
839
- return runGit(baseRoot, ["rev-parse", "HEAD"], 3_000);
878
+ throw new Error(
879
+ `Base checkout ${baseRoot} has no recorded default branch for ${remote} and its HEAD is not on ${remote}/main or ${remote}/master, so it may carry unmerged code; run git remote set-head ${remote} --auto there, or check out the default branch.`,
880
+ );
840
881
  }
841
882
 
842
883
  async function refreshPrWorktree(
@@ -890,7 +931,68 @@ async function refreshIssueWorktree(worktreePath: string, localBranchName: strin
890
931
  await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
891
932
  }
892
933
 
893
- export async function prepareWorkspaceCwdHandler(
934
+ function errorMessage(err: unknown): string {
935
+ return err instanceof Error ? err.message : String(err);
936
+ }
937
+
938
+ /**
939
+ * Materializes a worktree that `worktree add --no-checkout` just registered. When the checkout
940
+ * fails, the half-created worktree is removed, so the next request does not find it by branch and
941
+ * hand back an unpopulated directory. If that removal fails too, both errors are reported: the
942
+ * original cause must not be lost, and the leftover worktree needs to be named.
943
+ */
944
+ async function populateNewWorktree(baseRoot: string, worktreePath: string): Promise<void> {
945
+ try {
946
+ await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
947
+ } catch (checkoutError) {
948
+ try {
949
+ // No short timeout: the cleanup must be allowed to finish.
950
+ await runGit(baseRoot, ["worktree", "remove", "--force", "--", worktreePath]);
951
+ } catch (removalError) {
952
+ throw new AggregateError(
953
+ [checkoutError, removalError],
954
+ `Checking out the new worktree ${worktreePath} failed (${errorMessage(checkoutError)}), and removing the half-created worktree failed too (${errorMessage(removalError)}); remove it with git worktree remove --force.`,
955
+ );
956
+ }
957
+ throw checkoutError;
958
+ }
959
+ }
960
+
961
+ /**
962
+ * Launches whose workspace is being prepared right now, one entry per repository and item. Two
963
+ * launches for the same item would race into the same clone, branch and worktree (a double click,
964
+ * or two devices), so a second identical request gets the running launch's promise and both see one
965
+ * result. A second request that differs (another directory or mode) is refused instead, since the
966
+ * running launch's result would not answer it.
967
+ */
968
+ const launchesInFlight = new Map<
969
+ string,
970
+ { signature: string; result: Promise<z.output<typeof prepareWorkspaceCwd.output>> }
971
+ >();
972
+
973
+ export function prepareWorkspaceCwdHandler(
974
+ input: z.output<typeof prepareWorkspaceCwd.input>,
975
+ readSettings: ReadWorkspaceSettings,
976
+ ): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
977
+ const launchKey = `${input.repository.toLowerCase()}#${input.itemKind}-${input.prNumber}`;
978
+ const signature = JSON.stringify(input);
979
+ const running = launchesInFlight.get(launchKey);
980
+ if (running) {
981
+ if (running.signature === signature) return running.result;
982
+ return Promise.reject(
983
+ new Error(
984
+ `A launch for ${input.itemKind} #${input.prNumber} of ${input.repository} is already preparing its workspace with different settings; wait for it to finish, then try again.`,
985
+ ),
986
+ );
987
+ }
988
+ const result = prepareLockedWorkspaceCwd(input, readSettings).finally(() => {
989
+ launchesInFlight.delete(launchKey);
990
+ });
991
+ launchesInFlight.set(launchKey, { signature, result });
992
+ return result;
993
+ }
994
+
995
+ async function prepareLockedWorkspaceCwd(
894
996
  input: z.output<typeof prepareWorkspaceCwd.input>,
895
997
  readSettings: ReadWorkspaceSettings,
896
998
  ): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
@@ -1025,6 +1127,16 @@ export async function prepareWorkspaceCwdHandler(
1025
1127
  // CWD-WORKTREE: reuse existing worktree for this PR/issue branch if present (never reuse baseRoot).
1026
1128
  const resolvedBaseRoot = resolve(baseRoot);
1027
1129
  const existingWorktrees = await listWorktrees(baseRoot);
1130
+ // A CWD-BASE launch leaves the branch checked out in the base checkout, where `worktree add`
1131
+ // cannot also use it. Refuse, naming it, rather than fail inside git or quietly work in the base.
1132
+ const heldByBase = existingWorktrees.some(
1133
+ (wt) => wt.branch === localBranchName && resolve(wt.path) === resolvedBaseRoot,
1134
+ );
1135
+ if (heldByBase) {
1136
+ throw new Error(
1137
+ `Branch ${localBranchName} is checked out in the base checkout ${baseRoot} (an earlier CWD-BASE launch), so a worktree cannot use it too; switch that checkout to another branch, or launch with CWD-BASE.`,
1138
+ );
1139
+ }
1028
1140
  const existing = existingWorktrees.find(
1029
1141
  (wt) => wt.branch === localBranchName && resolve(wt.path) !== resolvedBaseRoot,
1030
1142
  );
@@ -1114,14 +1226,7 @@ export async function prepareWorkspaceCwdHandler(
1114
1226
  startPoint,
1115
1227
  ]);
1116
1228
  }
1117
- try {
1118
- await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
1119
- } catch (err) {
1120
- // The worktree is already registered; a failed checkout must not leave a half-created one.
1121
- // No short timeout here: cleanup must complete, and a removal failure propagates (not swallowed).
1122
- await runGit(baseRoot, ["worktree", "remove", "--force", worktreePath]);
1123
- throw err;
1124
- }
1229
+ await populateNewWorktree(baseRoot, worktreePath);
1125
1230
  } else {
1126
1231
  const prHead = await fetchPrHead(baseRoot, matchingRemote, input.prNumber);
1127
1232
  await assertBranchFastForwards(
@@ -1140,7 +1245,7 @@ export async function prepareWorkspaceCwdHandler(
1140
1245
  worktreePath,
1141
1246
  prHead,
1142
1247
  ]);
1143
- await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
1248
+ await populateNewWorktree(baseRoot, worktreePath);
1144
1249
  }
1145
1250
 
1146
1251
  return {
@@ -1151,211 +1256,3 @@ export async function prepareWorkspaceCwdHandler(
1151
1256
  worktreeCreated: true,
1152
1257
  };
1153
1258
  }
1154
-
1155
- const STICKY_BIT = 0o1000;
1156
-
1157
- /**
1158
- * Resolves the configured script to a real path and refuses anything but a regular, executable
1159
- * file that only this user (or root) can modify: the file must be owned by the user or root, and so
1160
- * must every directory above it, none of them writable by group or others unless sticky (like
1161
- * /tmp). Otherwise another local user could create the script or swap a path component for their
1162
- * own, and it would run as this user. `uid` is a parameter so tests can stand in for another user.
1163
- */
1164
- export async function resolveRoutingScript(
1165
- rawPath: string,
1166
- uid: number | undefined = process.getuid?.(),
1167
- ): Promise<string> {
1168
- const trimmed = rawPath.trim();
1169
- if (!trimmed) {
1170
- throw new Error("No routing script is configured in the PR Radar settings.");
1171
- }
1172
- if (!isAbsoluteOrHomePath(trimmed)) {
1173
- throw new Error(`Routing script path must be an absolute or ~/ path: ${trimmed}`);
1174
- }
1175
- const expanded = expandUserPath(trimmed);
1176
- if (!(await exists(expanded))) {
1177
- throw new Error(`Routing script not found: ${expanded}`);
1178
- }
1179
- const scriptPath = await realpath(expanded);
1180
- const info = await stat(scriptPath);
1181
- if (!info.isFile()) {
1182
- throw new Error(`Routing script is not a regular file: ${scriptPath}`);
1183
- }
1184
- const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
1185
- if (!trustedOwner(info.uid)) {
1186
- throw new Error(
1187
- `Routing script ${scriptPath} is owned by another user; run chown on it, or use a script you own.`,
1188
- );
1189
- }
1190
- if ((info.mode & 0o022) !== 0) {
1191
- throw new Error(
1192
- `Routing script ${scriptPath} must not be writable by group or others; run chmod go-w on it.`,
1193
- );
1194
- }
1195
- for (let dir = dirname(scriptPath); ; dir = dirname(dir)) {
1196
- const dirInfo = await stat(dir);
1197
- if (!trustedOwner(dirInfo.uid)) {
1198
- throw new Error(
1199
- `Routing script directory ${dir} is owned by another user; move the script somewhere you own, or run chown on it.`,
1200
- );
1201
- }
1202
- if ((dirInfo.mode & 0o022) !== 0 && (dirInfo.mode & STICKY_BIT) === 0) {
1203
- throw new Error(
1204
- `Routing script directory ${dir} must not be writable by group or others; run chmod go-w on it.`,
1205
- );
1206
- }
1207
- if (dirname(dir) === dir) break;
1208
- }
1209
- try {
1210
- await access(scriptPath, constants.X_OK);
1211
- } catch {
1212
- throw new Error(`Routing script is not executable: ${scriptPath}`);
1213
- }
1214
- return scriptPath;
1215
- }
1216
-
1217
- interface ScriptRun {
1218
- /** Settles with the script's stdout, or rejects on failure, timeout or the output cap. */
1219
- result: Promise<string>;
1220
- /** Resolves once the script's process group has exited or has been sent SIGKILL. */
1221
- finished: Promise<void>;
1222
- }
1223
-
1224
- function startScriptCapped(
1225
- scriptPath: string,
1226
- payload: unknown,
1227
- limits: RoutingScriptLimits,
1228
- ): ScriptRun {
1229
- const finishedGate = Promise.withResolvers<void>();
1230
- const result = new Promise<string>((resolvePromise, rejectPromise) => {
1231
- // Its own process group, so a timeout reaches the script's descendants too.
1232
- let child: ChildProcessByStdio<Writable, Readable, Readable>;
1233
- try {
1234
- child = spawn(scriptPath, [], {
1235
- stdio: ["pipe", "pipe", "pipe"],
1236
- env: allowListedEnv(new Set()),
1237
- detached: true,
1238
- });
1239
- } catch (spawnError) {
1240
- finishedGate.resolve();
1241
- rejectPromise(spawnError);
1242
- return;
1243
- }
1244
- const out: Buffer[] = [];
1245
- const err: Buffer[] = [];
1246
- let outBytes = 0;
1247
- let errBytes = 0;
1248
- let settled = false;
1249
- let terminating = false;
1250
- let killTimer: NodeJS.Timeout | undefined;
1251
-
1252
- function signalGroup(signal: NodeJS.Signals): void {
1253
- try {
1254
- if (child.pid !== undefined) process.kill(-child.pid, signal);
1255
- } catch {
1256
- // The group is already gone.
1257
- }
1258
- }
1259
- function settle(finish: () => void): void {
1260
- if (settled) return;
1261
- settled = true;
1262
- clearTimeout(timer);
1263
- // A surviving descendant could otherwise keep feeding buffers nobody reads any more.
1264
- child.stdout.destroy();
1265
- child.stderr.destroy();
1266
- finish();
1267
- }
1268
- function terminate(): void {
1269
- if (terminating) return;
1270
- terminating = true;
1271
- signalGroup("SIGTERM");
1272
- killTimer = setTimeout(() => {
1273
- signalGroup("SIGKILL");
1274
- finishedGate.resolve();
1275
- }, limits.killGraceMs);
1276
- }
1277
- function overCap(): void {
1278
- terminate();
1279
- settle(() =>
1280
- rejectPromise(new Error(`Routing script output exceeded ${limits.outputBytes} bytes.`)),
1281
- );
1282
- }
1283
-
1284
- const timer = setTimeout(() => {
1285
- terminate();
1286
- settle(() =>
1287
- rejectPromise(new Error(`Routing script timed out after ${limits.timeoutMs}ms.`)),
1288
- );
1289
- }, limits.timeoutMs);
1290
-
1291
- child.stdout.on("data", (chunk: Buffer) => {
1292
- if (settled) return;
1293
- outBytes += chunk.length;
1294
- if (outBytes > limits.outputBytes) return overCap();
1295
- out.push(chunk);
1296
- });
1297
- child.stderr.on("data", (chunk: Buffer) => {
1298
- if (settled) return;
1299
- errBytes += chunk.length;
1300
- if (errBytes > limits.outputBytes) return overCap();
1301
- err.push(chunk);
1302
- });
1303
- child.on("error", (spawnError) => {
1304
- settle(() => rejectPromise(spawnError));
1305
- finishedGate.resolve();
1306
- });
1307
- child.on("close", (code) => {
1308
- // Having asked it to stop, make sure no descendant outlives the script.
1309
- if (terminating) signalGroup("SIGKILL");
1310
- clearTimeout(killTimer);
1311
- finishedGate.resolve();
1312
- settle(() => {
1313
- if (code !== 0) {
1314
- const message = Buffer.concat(err).toString("utf8").trim();
1315
- rejectPromise(new Error(message || `Routing script exited with code ${code}.`));
1316
- return;
1317
- }
1318
- resolvePromise(Buffer.concat(out).toString("utf8").trim());
1319
- });
1320
- });
1321
- child.stdin.on("error", () => {});
1322
- child.stdin.end(`${JSON.stringify(payload)}\n`);
1323
- });
1324
- return { result, finished: finishedGate.promise };
1325
- }
1326
-
1327
- let routingScriptRunning = false;
1328
- let routingScriptFinished: Promise<void> | null = null;
1329
-
1330
- export async function waitForRoutingScriptIdleForTests(): Promise<void> {
1331
- await routingScriptFinished;
1332
- }
1333
-
1334
- export async function runRoutingScriptHandler(
1335
- input: z.output<typeof runRoutingScript.input>,
1336
- readSettings: ReadWorkspaceSettings,
1337
- limits: RoutingScriptLimits = DEFAULT_ROUTING_LIMITS,
1338
- ): Promise<z.output<typeof runRoutingScript.output>> {
1339
- if (process.platform === "win32") {
1340
- throw new Error("Routing scripts are not supported on Windows.");
1341
- }
1342
- const settings = await readSettings();
1343
- const scriptPath = await resolveRoutingScript(settings.routingScriptPath);
1344
- if (routingScriptRunning) {
1345
- throw new Error("A routing script is already running; try again when it has finished.");
1346
- }
1347
- routingScriptRunning = true;
1348
- // The guard is held until the script's process group is gone or has been sent SIGKILL, which can
1349
- // be after the call itself has failed on a timeout.
1350
- const run = startScriptCapped(scriptPath, input.payload, limits);
1351
- routingScriptFinished = run.finished.then(() => {
1352
- routingScriptRunning = false;
1353
- routingScriptFinished = null;
1354
- });
1355
- void routingScriptFinished;
1356
- const stdout = await run.result;
1357
-
1358
- if (!stdout) return {};
1359
- const parsed = JSON.parse(stdout) as unknown;
1360
- return RoutingScriptResultSchema.parse(parsed);
1361
- }