@ordewell/core 0.12.4 → 0.12.5

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/index.mjs CHANGED
@@ -4887,10 +4887,139 @@ function allowlistRule(parts, allow, trustedResolves) {
4887
4887
  }
4888
4888
 
4889
4889
  // src/services/researchShell.ts
4890
+ import { execFileSync } from "child_process";
4890
4891
  import * as fsSync from "fs";
4892
+ import * as path2 from "path";
4893
+
4894
+ // src/services/pathScope.ts
4895
+ import * as os from "os";
4891
4896
  import * as path from "path";
4897
+ function expandHome(target) {
4898
+ if (!target.startsWith("~")) return target;
4899
+ const home = os.homedir();
4900
+ if (target === "~" || target.startsWith("~/")) return path.join(home, target.slice(1));
4901
+ return path.join(path.dirname(home), target.slice(1));
4902
+ }
4903
+ function resolveWithin(root, target, from = root, hostPath2) {
4904
+ const spelled = hostPath2 ? hostPath2(target, from) : target;
4905
+ if (spelled === void 0) return { abs: target, inside: false, unfollowable: true };
4906
+ if (hostPath2 && isInertDevice(spelled)) return { abs: spelled, inside: false, device: true };
4907
+ const abs = path.resolve(from, expandHome(spelled));
4908
+ const rel = path.relative(root, abs);
4909
+ return { abs, inside: rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel), ...isInertDevice(abs) ? { device: true } : {} };
4910
+ }
4911
+ function resolveRef(root, ref2, hostPath2) {
4912
+ let from = root;
4913
+ for (const target of ref2.cwd) {
4914
+ const dir = resolveWithin(root, target, from, hostPath2);
4915
+ if (dir.unfollowable) return { abs: ref2.path, inside: false, unfollowable: true };
4916
+ from = dir.abs;
4917
+ }
4918
+ return resolveWithin(root, ref2.path, from, hostPath2);
4919
+ }
4920
+ function grantScopeFor(abs, kind) {
4921
+ if (kind === "directory") return path.join(abs, "*");
4922
+ const parent = path.dirname(abs);
4923
+ if (parent === path.parse(abs).root) return path.join(abs, "*");
4924
+ return path.join(parent, "*");
4925
+ }
4926
+ var INERT_DEVICES = ["/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
4927
+ function isInertDevice(abs) {
4928
+ return INERT_DEVICES.includes(abs);
4929
+ }
4930
+
4931
+ // src/services/researchShell.ts
4892
4932
  var POSIX_SHELL = { file: null, args: [], dialect: "posix", utilsDir: null };
4893
4933
  var CMD_SHELL = { file: null, args: [], dialect: "cmd", utilsDir: null };
4934
+ function defaultReadMounts(root) {
4935
+ const mount = path2.win32.join(root, "usr", "bin", "mount.exe");
4936
+ try {
4937
+ const read2 = (args) => execFileSync(mount, args, { encoding: "utf8", timeout: 5e3, windowsHide: true });
4938
+ return [read2([]), read2(["-p"])];
4939
+ } catch {
4940
+ return void 0;
4941
+ }
4942
+ }
4943
+ function parseMounts(mounts, prefix) {
4944
+ const points = [];
4945
+ for (const line of mounts.split(/\r?\n/)) {
4946
+ const m = /^(.+?) on (\/.*?) type \S+ \(([^)]*)\)/.exec(line);
4947
+ if (!m) continue;
4948
+ const host = m[1].replace(/\//g, "\\");
4949
+ points.push({ point: m[2], host: /^[A-Za-z]:$/.test(host) ? `${host}\\` : host, caseless: m[3].split(",").includes("posix=0") });
4950
+ }
4951
+ if (!points.some((p) => p.point === "/")) return void 0;
4952
+ const cygdrive = /^\s*(\/\S*)\s+\S+\s+\S+/m.exec(prefix.split(/\r?\n/).slice(1).join("\n"))?.[1] ?? "/";
4953
+ return { points, cygdrive };
4954
+ }
4955
+ function defaultMounts(root, env) {
4956
+ const temp = env.TEMP || env.TMP;
4957
+ return {
4958
+ points: [
4959
+ { point: "/", host: root, caseless: false },
4960
+ { point: "/bin", host: path2.win32.join(root, "usr", "bin"), caseless: false },
4961
+ ...temp ? [{ point: "/tmp", host: temp, caseless: true }] : []
4962
+ ],
4963
+ cygdrive: "/"
4964
+ };
4965
+ }
4966
+ function mountedHostPath(table, spelled, from, home) {
4967
+ if (isInertDevice(spelled)) return spelled;
4968
+ if (spelled.startsWith("/")) return mountedAbsolute(table, spelled.replace(/\\/g, "/"));
4969
+ if (home && (spelled === "~" || /^~[\\/]/.test(spelled))) {
4970
+ const base = home.startsWith("/") ? mountedAbsolute(table, home) : home;
4971
+ return base === void 0 ? void 0 : path2.win32.join(base, spelled.slice(1));
4972
+ }
4973
+ if (from === void 0 || /^[A-Za-z]:/.test(spelled) || spelled.startsWith("\\") || spelled.startsWith("~")) return spelled;
4974
+ return staysOnDrive(table, spelled.replace(/\\/g, "/"), from) ? spelled : void 0;
4975
+ }
4976
+ function mountedAbsolute(table, posix17) {
4977
+ if (/^\/\/[^/]/.test(posix17)) return posix17.replace(/\//g, "\\");
4978
+ const segments = posix17.split("/").filter((s) => s !== "" && s !== ".");
4979
+ if (segments.includes("..")) return void 0;
4980
+ const prefix = table.cygdrive.endsWith("/") ? table.cygdrive : `${table.cygdrive}/`;
4981
+ const top = segments[0]?.toLowerCase();
4982
+ if (top === "proc" && segments[1]?.toLowerCase() === "cygdrive") return mountedAbsolute(table, prefix + segments.slice(2).join("/"));
4983
+ if (top === "proc" || top === "dev") return void 0;
4984
+ const normal = `/${segments.join("/")}`;
4985
+ const under = ({ point, caseless }) => {
4986
+ if (point === "/") return true;
4987
+ const [at, here] = caseless ? [point.toLowerCase(), normal.toLowerCase()] : [point, normal];
4988
+ return here === at || here.startsWith(`${at}/`);
4989
+ };
4990
+ let best = table.points.filter(under).sort((a, b) => b.point.length - a.point.length)[0];
4991
+ const drive = normal.toLowerCase().startsWith(prefix.toLowerCase()) ? /^([a-z])(?:\/|$)/i.exec(normal.slice(prefix.length)) : null;
4992
+ if (drive && (!best || prefix.length + 1 > best.point.length)) {
4993
+ best = { point: normal.slice(0, prefix.length + 1), host: `${drive[1].toUpperCase()}:\\` };
4994
+ }
4995
+ if (!best) return void 0;
4996
+ const rest = normal.slice(best.point.length).split("/").filter(Boolean);
4997
+ return rest.length ? path2.win32.join(best.host, ...rest) : best.host;
4998
+ }
4999
+ function staysOnDrive(table, relative20, from) {
5000
+ if (!relative20.split("/").includes("..")) return true;
5001
+ const drive = /^([A-Za-z]):(?:[\\/]|$)/.exec(from);
5002
+ const underMount = table.points.some((p) => {
5003
+ if (/^[A-Za-z]:\\$/.test(p.host)) return false;
5004
+ const rel = path2.win32.relative(p.host, from);
5005
+ return !rel.startsWith("..") && !path2.win32.isAbsolute(rel);
5006
+ });
5007
+ if (!drive || underMount) return false;
5008
+ const top = `/${drive[1].toLowerCase()}`;
5009
+ const climbed = path2.posix.join(`${top}/${from.slice(drive[0].length).replace(/\\/g, "/")}`, relative20);
5010
+ return climbed === top || climbed.startsWith(`${top}/`);
5011
+ }
5012
+ function gitBashHostPath(root, env, readMounts) {
5013
+ let table;
5014
+ return (spelled, from) => {
5015
+ if (!spelled.startsWith("/") && !spelled.startsWith("~") && !/(^|[\\/])\.\.([\\/]|$)/.test(spelled)) return spelled;
5016
+ if (!table) {
5017
+ const read2 = readMounts(root);
5018
+ table = (read2 && parseMounts(...read2)) ?? defaultMounts(root, env);
5019
+ }
5020
+ return mountedHostPath(table, spelled, from, env.HOME);
5021
+ };
5022
+ }
4894
5023
  function defaultExists(candidate) {
4895
5024
  try {
4896
5025
  return fsSync.statSync(candidate).isFile();
@@ -4900,9 +5029,9 @@ function defaultExists(candidate) {
4900
5029
  }
4901
5030
  function gitBashRoots(env) {
4902
5031
  const roots = [
4903
- env.ProgramFiles && path.win32.join(env.ProgramFiles, "Git"),
4904
- env["ProgramFiles(x86)"] && path.win32.join(env["ProgramFiles(x86)"], "Git"),
4905
- env.LOCALAPPDATA && path.win32.join(env.LOCALAPPDATA, "Programs", "Git"),
5032
+ env.ProgramFiles && path2.win32.join(env.ProgramFiles, "Git"),
5033
+ env["ProgramFiles(x86)"] && path2.win32.join(env["ProgramFiles(x86)"], "Git"),
5034
+ env.LOCALAPPDATA && path2.win32.join(env.LOCALAPPDATA, "Programs", "Git"),
4906
5035
  "C:\\Program Files\\Git",
4907
5036
  "C:\\Program Files (x86)\\Git"
4908
5037
  ].filter((r) => !!r);
@@ -4910,32 +5039,34 @@ function gitBashRoots(env) {
4910
5039
  }
4911
5040
  var cached = null;
4912
5041
  function resolveResearchShell(deps = {}) {
4913
- if (cached && !deps.platform && !deps.exists && !deps.env) return cached;
5042
+ const probe = !!(deps.platform || deps.exists || deps.env || deps.readMounts);
5043
+ if (cached && !probe) return cached;
4914
5044
  const platform = deps.platform ?? process.platform;
4915
5045
  if (platform !== "win32") {
4916
- if (!deps.platform && !deps.exists && !deps.env) cached = POSIX_SHELL;
5046
+ if (!probe) cached = POSIX_SHELL;
4917
5047
  return POSIX_SHELL;
4918
5048
  }
4919
5049
  const exists = deps.exists ?? defaultExists;
4920
5050
  const env = deps.env ?? process.env;
4921
5051
  for (const root of gitBashRoots(env)) {
4922
5052
  for (const rel of [["bin", "bash.exe"], ["usr", "bin", "bash.exe"]]) {
4923
- const file = path.win32.join(root, ...rel);
5053
+ const file = path2.win32.join(root, ...rel);
4924
5054
  if (!exists(file)) continue;
4925
- const utilsDir = path.win32.join(root, "usr", "bin");
5055
+ const utilsDir = path2.win32.join(root, "usr", "bin");
4926
5056
  const resolved2 = {
4927
5057
  file,
4928
5058
  // `-c`, not `-lc`: a login shell sources the user's profile, which can
4929
5059
  // change directory out from under a command whose cwd is the workspace.
4930
5060
  args: ["-c"],
4931
5061
  dialect: "posix",
4932
- utilsDir: exists(path.win32.join(utilsDir, "grep.exe")) ? utilsDir : null
5062
+ utilsDir: exists(path2.win32.join(utilsDir, "grep.exe")) ? utilsDir : null,
5063
+ hostPath: gitBashHostPath(root, env, deps.readMounts ?? defaultReadMounts)
4933
5064
  };
4934
- if (!deps.platform && !deps.exists && !deps.env) cached = resolved2;
5065
+ if (!probe) cached = resolved2;
4935
5066
  return resolved2;
4936
5067
  }
4937
5068
  }
4938
- if (!deps.platform && !deps.exists && !deps.env) cached = CMD_SHELL;
5069
+ if (!probe) cached = CMD_SHELL;
4939
5070
  return CMD_SHELL;
4940
5071
  }
4941
5072
  function clearResearchShellCache() {
@@ -4943,8 +5074,8 @@ function clearResearchShellCache() {
4943
5074
  }
4944
5075
  function researchToolsPath(shell, basePath) {
4945
5076
  if (!shell.utilsDir) return basePath ?? "";
4946
- const segments = [shell.utilsDir, ...(basePath ?? "").split(path.win32.delimiter)].filter(Boolean);
4947
- return [...new Set(segments)].join(path.win32.delimiter);
5077
+ const segments = [shell.utilsDir, ...(basePath ?? "").split(path2.win32.delimiter)].filter(Boolean);
5078
+ return [...new Set(segments)].join(path2.win32.delimiter);
4948
5079
  }
4949
5080
  function researchShellWarning(shell) {
4950
5081
  if (shell.dialect !== "cmd") return null;
@@ -4956,16 +5087,16 @@ function researchPolicyOptions(shell) {
4956
5087
 
4957
5088
  // src/services/sandbox/plannerSandbox.ts
4958
5089
  import * as fsSync3 from "fs";
4959
- import * as os from "os";
4960
- import * as path5 from "path";
5090
+ import * as os2 from "os";
5091
+ import * as path6 from "path";
4961
5092
 
4962
5093
  // src/services/sandbox/bubblewrap.ts
4963
5094
  import * as fsSync2 from "fs";
4964
- import * as path3 from "path";
5095
+ import * as path4 from "path";
4965
5096
 
4966
5097
  // src/services/sandbox/SandboxBackend.ts
4967
5098
  import { execFile } from "child_process";
4968
- import * as path2 from "path";
5099
+ import * as path3 from "path";
4969
5100
  var MEMORY_LIMIT_SIGNAL = "SIGUSR2";
4970
5101
  var SandboxUnsupportedError = class extends Error {
4971
5102
  constructor(backend, what) {
@@ -4976,7 +5107,7 @@ var SandboxUnsupportedError = class extends Error {
4976
5107
  function assertProfilePaths(backend, profile) {
4977
5108
  const paths = [...profile.write, ...profile.linkless ?? [], ...profile.gitWorktrees ?? [], ...(profile.gitEntries ?? []).map((entry) => entry.path), ...profile.gitless ?? [], ...profile.read === "host" ? [] : profile.read, ...profile.throwaway ?? [], ...profile.masked ?? []];
4978
5109
  for (const p of paths) {
4979
- if (!path2.posix.isAbsolute(p) || p.includes("\0")) throw new SandboxUnsupportedError(backend, `the path ${JSON.stringify(p)}`);
5110
+ if (!path3.posix.isAbsolute(p) || p.includes("\0")) throw new SandboxUnsupportedError(backend, `the path ${JSON.stringify(p)}`);
4980
5111
  }
4981
5112
  }
4982
5113
  function assertLimits(backend, limits) {
@@ -5012,7 +5143,7 @@ async function probeByRunning(backend, profile, exec5) {
5012
5143
  // src/services/sandbox/bubblewrap.ts
5013
5144
  var SYSTEM_BWRAP = ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap", "/run/current-system/sw/bin/bwrap"];
5014
5145
  function findBubblewrap(env, exists) {
5015
- const onPath = (env.PATH ?? "").split(path3.posix.delimiter).filter((dir) => path3.posix.isAbsolute(dir)).map((dir) => path3.posix.join(dir, "bwrap"));
5146
+ const onPath = (env.PATH ?? "").split(path4.posix.delimiter).filter((dir) => path4.posix.isAbsolute(dir)).map((dir) => path4.posix.join(dir, "bwrap"));
5016
5147
  return [.../* @__PURE__ */ new Set([...SYSTEM_BWRAP, ...onPath])].find(exists) ?? null;
5017
5148
  }
5018
5149
  function defaultIsDirectory(p) {
@@ -5107,7 +5238,7 @@ var BubblewrapBackend = class {
5107
5238
  for (const p of shallowFirst(profile.masked ?? [])) args.push(...this.isDirectory(p) ? ["--tmpfs", p] : ["--ro-bind", "/dev/null", p]);
5108
5239
  for (const p of shallowFirst(profile.write)) args.push("--bind", p, p);
5109
5240
  const readOnlyGit = /* @__PURE__ */ new Set([
5110
- ...(profile.gitWorktrees ?? []).map((worktree) => path3.posix.join(worktree, ".git")),
5241
+ ...(profile.gitWorktrees ?? []).map((worktree) => path4.posix.join(worktree, ".git")),
5111
5242
  ...(profile.gitEntries ?? []).map((entry) => entry.path)
5112
5243
  ]);
5113
5244
  for (const gitPath of readOnlyGit) args.push("--ro-bind", gitPath, gitPath);
@@ -5120,7 +5251,7 @@ var BubblewrapBackend = class {
5120
5251
  };
5121
5252
 
5122
5253
  // src/services/sandbox/seatbelt.ts
5123
- import * as path4 from "path";
5254
+ import * as path5 from "path";
5124
5255
  var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
5125
5256
  var BASE_PROFILE = `(version 1)
5126
5257
  (deny default)
@@ -5279,7 +5410,7 @@ var SeatbeltBackend = class {
5279
5410
  if (profile.write.length) rules.push(`(allow file-read* file-test-existence file-map-executable file-write* ${filters("WRITABLE", "subpath", profile.write)})`);
5280
5411
  if (profile.linkless?.length) rules.push(`(deny file-write-create (require-all (vnode-type SYMLINK) (require-any ${filters("LINKLESS", "subpath", profile.linkless)})))`);
5281
5412
  if (profile.gitWorktrees?.length) {
5282
- const gitDirs = profile.gitWorktrees.map((worktree) => path4.posix.join(worktree, ".git"));
5413
+ const gitDirs = profile.gitWorktrees.map((worktree) => path5.posix.join(worktree, ".git"));
5283
5414
  rules.push(`(deny file-write* ${filters("GIT", "literal", gitDirs)})`);
5284
5415
  rules.push(`(deny file-write* ${filters("WORKTREE", "literal", profile.gitWorktrees)})`);
5285
5416
  }
@@ -5308,7 +5439,7 @@ var SeatbeltBackend = class {
5308
5439
  function directoriesAbove(paths) {
5309
5440
  const above = /* @__PURE__ */ new Set();
5310
5441
  for (const p of paths) {
5311
- for (let dir = path4.posix.dirname(p); dir !== "/" && !above.has(dir); dir = path4.posix.dirname(dir)) above.add(dir);
5442
+ for (let dir = path5.posix.dirname(p); dir !== "/" && !above.has(dir); dir = path5.posix.dirname(dir)) above.add(dir);
5312
5443
  }
5313
5444
  return [...above];
5314
5445
  }
@@ -5537,22 +5668,22 @@ function scratchEnv(scratch, platform) {
5537
5668
  GIT_OPTIONAL_LOCKS: "0",
5538
5669
  // npm writes a debug log under its cache for every command, `npm ls` too,
5539
5670
  // and records its update check there.
5540
- npm_config_cache: path5.join(scratch, "npm"),
5671
+ npm_config_cache: path6.join(scratch, "npm"),
5541
5672
  npm_config_update_notifier: "false",
5542
5673
  // `go list` opens the build cache.
5543
- GOCACHE: path5.join(scratch, "go-build"),
5674
+ GOCACHE: path6.join(scratch, "go-build"),
5544
5675
  // Where Linux tools that follow the XDG layout (pip among them) keep caches.
5545
- XDG_CACHE_HOME: path5.join(scratch, "cache"),
5676
+ XDG_CACHE_HOME: path6.join(scratch, "cache"),
5546
5677
  // Python otherwise writes bytecode beside the sources, in the workspace.
5547
- PYTHONPYCACHEPREFIX: path5.join(scratch, "pycache"),
5678
+ PYTHONPYCACHEPREFIX: path6.join(scratch, "pycache"),
5548
5679
  // The `/usr/bin` shims of Apple's command-line tools (`git` among them)
5549
5680
  // cache lookups in the user's temporary directory, ignoring TMPDIR, and
5550
5681
  // print an error on every call when they cannot.
5551
- ...platform === "darwin" ? { xcrun_db: path5.join(scratch, "xcrun_db") } : {}
5682
+ ...platform === "darwin" ? { xcrun_db: path6.join(scratch, "xcrun_db") } : {}
5552
5683
  };
5553
5684
  }
5554
5685
  function localServices(env, stat, uid) {
5555
- const runtimeDir = env.XDG_RUNTIME_DIR && path5.posix.isAbsolute(env.XDG_RUNTIME_DIR) ? env.XDG_RUNTIME_DIR : void 0;
5686
+ const runtimeDir = env.XDG_RUNTIME_DIR && path6.posix.isAbsolute(env.XDG_RUNTIME_DIR) ? env.XDG_RUNTIME_DIR : void 0;
5556
5687
  const candidates = [runtimeDir, uid === void 0 ? void 0 : `/run/user/${uid}`, "/run/dbus", "/tmp/.X11-unix", "/run/docker.sock"];
5557
5688
  const found = candidates.flatMap((p) => p ? [stat(p)?.canonical] : []).filter((p) => !!p && p !== "/");
5558
5689
  return [...new Set(found)];
@@ -5657,8 +5788,8 @@ function sealedShellProfile(host, opts) {
5657
5788
  };
5658
5789
  }
5659
5790
  function strictlyWithin(child, parent) {
5660
- const rel = path5.relative(parent, child);
5661
- return rel !== "" && !rel.startsWith("..") && !path5.isAbsolute(rel);
5791
+ const rel = path6.relative(parent, child);
5792
+ return rel !== "" && !rel.startsWith("..") && !path6.isAbsolute(rel);
5662
5793
  }
5663
5794
  function canonicalGitEntries(entries) {
5664
5795
  return entries.flatMap((entry) => {
@@ -5711,9 +5842,9 @@ async function detect(deps) {
5711
5842
  }
5712
5843
  return unavailable(`${backend.name} could not start (${detail})`);
5713
5844
  }
5714
- async function detectSealed(backend, platform, stat, probeWorkspace = os.tmpdir()) {
5845
+ async function detectSealed(backend, platform, stat, probeWorkspace = os2.tmpdir()) {
5715
5846
  const existing = (paths) => (paths ?? []).filter((p) => stat(p) !== null);
5716
- const named3 = (paths) => platform === "darwin" ? paths.map((p) => path5.posix.join(stat(path5.posix.dirname(p))?.canonical ?? path5.posix.dirname(p), path5.posix.basename(p))) : paths;
5847
+ const named3 = (paths) => platform === "darwin" ? paths.map((p) => path6.posix.join(stat(path6.posix.dirname(p))?.canonical ?? path6.posix.dirname(p), path6.posix.basename(p))) : paths;
5717
5848
  const developerDir = platform === "darwin" ? stat("/private/var/select/developer_dir")?.canonical : void 0;
5718
5849
  const reads = [.../* @__PURE__ */ new Set([...named3(existing(SEALED_READS[platform])), ...developerDir ? [developerDir] : []])];
5719
5850
  const masked = named3(existing(SEALED_MASKS[platform]));
@@ -5761,7 +5892,7 @@ function sweepOrphanScratch(root) {
5761
5892
  for (const name of names2) {
5762
5893
  const pid = Number(/^ordewell-planner-(\d+)-/.exec(name)?.[1]);
5763
5894
  if (!pid || pid === process.pid || processAlive(pid)) continue;
5764
- const dir = path5.join(root, name);
5895
+ const dir = path6.join(root, name);
5765
5896
  try {
5766
5897
  const stat = fsSync3.lstatSync(dir);
5767
5898
  if (stat.isDirectory() && stat.uid === process.getuid?.()) fsSync3.rmSync(dir, { recursive: true, force: true });
@@ -5775,9 +5906,9 @@ function createScratch() {
5775
5906
  process.once("exit", () => {
5776
5907
  for (const dir2 of [...liveScratch]) removeScratch(dir2);
5777
5908
  });
5778
- sweepOrphanScratch(os.tmpdir());
5909
+ sweepOrphanScratch(os2.tmpdir());
5779
5910
  }
5780
- const dir = fsSync3.realpathSync(fsSync3.mkdtempSync(path5.join(os.tmpdir(), `ordewell-planner-${process.pid}-`)));
5911
+ const dir = fsSync3.realpathSync(fsSync3.mkdtempSync(path6.join(os2.tmpdir(), `ordewell-planner-${process.pid}-`)));
5781
5912
  liveScratch.add(dir);
5782
5913
  return dir;
5783
5914
  }
@@ -5932,35 +6063,6 @@ function sealedMemoryLimitNote(outcome, memoryBytes, forTask) {
5932
6063
  }
5933
6064
  var SEALED_FAILURE_NOTE = "A sealed run cannot reach the network, the user's credentials or their files outside the workspace, and cannot change the workspace, so running it sealed again fails the same way. To read something it could not, run each command on its own, without a loop or inline code, so Ordewell's command rules can judge it; a change belongs in the plan as a task.";
5934
6065
 
5935
- // src/services/pathScope.ts
5936
- import * as os2 from "os";
5937
- import * as path6 from "path";
5938
- function expandHome(target) {
5939
- if (!target.startsWith("~")) return target;
5940
- const home = os2.homedir();
5941
- if (target === "~" || target.startsWith("~/")) return path6.join(home, target.slice(1));
5942
- return path6.join(path6.dirname(home), target.slice(1));
5943
- }
5944
- function resolveWithin(root, target, from = root) {
5945
- const abs = path6.resolve(from, expandHome(target));
5946
- const rel = path6.relative(root, abs);
5947
- return { abs, inside: rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel) };
5948
- }
5949
- function resolveRef(root, ref2) {
5950
- const from = ref2.cwd.reduce((dir, target) => resolveWithin(root, target, dir).abs, root);
5951
- return resolveWithin(root, ref2.path, from);
5952
- }
5953
- function grantScopeFor(abs, kind) {
5954
- if (kind === "directory") return path6.join(abs, "*");
5955
- const parent = path6.dirname(abs);
5956
- if (parent === path6.parse(abs).root) return path6.join(abs, "*");
5957
- return path6.join(parent, "*");
5958
- }
5959
- var INERT_DEVICES = ["/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
5960
- function isInertDevice(abs) {
5961
- return INERT_DEVICES.includes(abs);
5962
- }
5963
-
5964
6066
  // src/services/symbolPatterns.ts
5965
6067
  var SYMBOL_LANGUAGES = [
5966
6068
  {
@@ -6300,6 +6402,9 @@ var CD_HINT = ' A "cd" is followed only on a line joined by "&&" alone, so after
6300
6402
  function refusal(output) {
6301
6403
  return { success: false, output, truncated: false };
6302
6404
  }
6405
+ function unfollowableReason(spelled) {
6406
+ return `Git Bash reads "${spelled}" by rules this check cannot follow, so it cannot tell which folder the command would reach: a ".." past one of its mounts, or its own /proc or /dev. Name the path from its drive (/c/Users/...) or as a Windows path (C:\\Users\\...), with no "..".`;
6407
+ }
6303
6408
  var TASK_UNSEALED = "A read-only task asks nobody, so this command could only run sealed, and this machine has no sandbox to seal it in.";
6304
6409
  var OWN_UNSEALED = "this machine has no sandbox to seal it in, and Ordewell runs nothing in a read-only task's worktree outside one.";
6305
6410
  var TASK_CONTINUE = "Continue without it, and say in your report if what it would have shown matters.";
@@ -6472,12 +6577,13 @@ ${refs.output.trim()}`);
6472
6577
  outsidePaths(command, root) {
6473
6578
  const found = /* @__PURE__ */ new Map();
6474
6579
  for (const ref2 of pathRefs(command, this.policyOptions())) {
6475
- const { abs, inside: inside2 } = resolveRef(root, ref2);
6476
- if (inside2 || isInertDevice(abs)) continue;
6580
+ const { abs, inside: inside2, device, unfollowable } = resolveRef(root, ref2, this.researchShell.hostPath);
6581
+ if (unfollowable) return { outside: [], unfollowable: ref2.path };
6582
+ if (inside2 || device) continue;
6477
6583
  const scope = grantScopeFor(abs, "file");
6478
6584
  if (!found.has(scope)) found.set(scope, abs);
6479
6585
  }
6480
- return [...found].map(([scope, abs]) => ({ abs, scope }));
6586
+ return { outside: [...found].map(([scope, abs]) => ({ abs, scope })) };
6481
6587
  }
6482
6588
  policyOptions() {
6483
6589
  return researchPolicyOptions(this.researchShell);
@@ -6568,7 +6674,7 @@ ${TASK_CONTINUE}`);
6568
6674
  ...approval.commandPolicy?.(),
6569
6675
  ...allow ? { allow } : {}
6570
6676
  });
6571
- const outside = this.outsidePaths(command, root);
6677
+ const { outside, unfollowable } = this.outsidePaths(command, root);
6572
6678
  const asks = tier === "ask";
6573
6679
  const scopes = [...asks ? commandScopes ?? [scope] : [], ...outside.map((o) => o.scope)];
6574
6680
  const touched = outside.map((o) => o.abs).join(", ");
@@ -6587,6 +6693,8 @@ ${TASK_CONTINUE}`);
6587
6693
  }
6588
6694
  if (site.task?.sealed) return this.runSealed(site, command, request, "after", signal);
6589
6695
  if (tier === "refuse") return this.sealedInstead(site, command, request, refusal(`Command refused: ${reason}${site.task ? `
6696
+ ${TASK_UNSEALED} ${TASK_CONTINUE}` : ""}`), signal);
6697
+ if (unfollowable !== void 0) return this.sealedInstead(site, command, request, refusal(`Command refused: ${unfollowableReason(unfollowable)}${site.task ? `
6590
6698
  ${TASK_UNSEALED} ${TASK_CONTINUE}` : ""}`), signal);
6591
6699
  const outbound = [...outboundTexts ?? [], ...(webUrls ?? []).map((url) => url.href)];
6592
6700
  if (outbound.length && carriesSecret(outbound, [...this.outboundSecrets(), ...sensitiveEnvValues(process.env)])) {
@@ -8295,7 +8403,12 @@ function convertForEre(pattern, plainGroups) {
8295
8403
  let closeBracket = false;
8296
8404
  let openBracket = false;
8297
8405
  let dash = false;
8406
+ let caret = false;
8298
8407
  let closed = false;
8408
+ if (pattern[i] === "]") {
8409
+ closeBracket = true;
8410
+ i++;
8411
+ }
8299
8412
  while (i < pattern.length) {
8300
8413
  const ch = pattern[i];
8301
8414
  if (ch === "]") {
@@ -8318,6 +8431,7 @@ function convertForEre(pattern, plainGroups) {
8318
8431
  else if (e === "]") closeBracket = true;
8319
8432
  else if (e === "[") openBracket = true;
8320
8433
  else if (e === "-") dash = true;
8434
+ else if (e === "^") caret = true;
8321
8435
  else body += e;
8322
8436
  continue;
8323
8437
  }
@@ -8328,7 +8442,9 @@ function convertForEre(pattern, plainGroups) {
8328
8442
  out += pattern.slice(start);
8329
8443
  break;
8330
8444
  }
8331
- out += `[${negate ? "^" : ""}${closeBracket ? "]" : ""}${body}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
8445
+ const members = `${closeBracket ? "]" : ""}${body}`;
8446
+ if (caret && !negate && members === "") out += openBracket || dash ? `[${dash ? "-" : ""}${openBracket ? "[" : ""}^]` : "\\^";
8447
+ else out += `[${negate ? "^" : ""}${members}${caret ? "^" : ""}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
8332
8448
  }
8333
8449
  let representable = true;
8334
8450
  const renumbered2 = out.replace(BACKREFERENCE, (_, n) => {
@@ -11039,6 +11155,65 @@ function defaultExists3(candidate) {
11039
11155
  return false;
11040
11156
  }
11041
11157
  }
11158
+ var MAX_SHIM_BYTES = 4096;
11159
+ function defaultReadShim(file) {
11160
+ try {
11161
+ return fsSync4.statSync(file).size > MAX_SHIM_BYTES ? void 0 : fsSync4.readFileSync(file, "utf8");
11162
+ } catch {
11163
+ return void 0;
11164
+ }
11165
+ }
11166
+ var NPM_SHIM_HEAD = "@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT /b\n:start\nSETLOCAL\nCALL :find_dp0\n";
11167
+ var NPM_SHIMS = {
11168
+ node: `${NPM_SHIM_HEAD}
11169
+ IF EXIST "%dp0%\\node.exe" (
11170
+ SET "_prog=%dp0%\\node.exe"
11171
+ ) ELSE (
11172
+ SET "_prog=node"
11173
+ SET PATHEXT=%PATHEXT:;.JS;=;%
11174
+ )
11175
+
11176
+ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\TARGET" %*
11177
+ `,
11178
+ program: `${NPM_SHIM_HEAD}"%dp0%\\TARGET" %*
11179
+ `
11180
+ };
11181
+ function shimPattern(template) {
11182
+ const [before, after] = template.split("TARGET").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
11183
+ return new RegExp(`^${before}([^"%\\n]+)${after}$`);
11184
+ }
11185
+ var NPM_SHIM_PATTERNS = { node: shimPattern(NPM_SHIMS.node), program: shimPattern(NPM_SHIMS.program) };
11186
+ function npmShimTarget(shim, pathDirs, deps) {
11187
+ const raw = (deps.readShim ?? defaultReadShim)(shim);
11188
+ if (raw === void 0) return void 0;
11189
+ const text4 = raw.replace(/\r\n/g, "\n").replace(/\n?$/, "\n");
11190
+ const exists = deps.exists ?? defaultExists3;
11191
+ const folder = path15.win32.dirname(shim);
11192
+ const program = NPM_SHIM_PATTERNS.program.exec(text4)?.[1];
11193
+ if (program !== void 0) {
11194
+ const file2 = path15.win32.join(folder, program);
11195
+ return DIRECT_EXTENSIONS.includes(path15.win32.extname(file2).toLowerCase()) && exists(file2) ? { file: file2, leading: [] } : void 0;
11196
+ }
11197
+ const script = NPM_SHIM_PATTERNS.node.exec(text4)?.[1];
11198
+ if (script === void 0) return void 0;
11199
+ const file = path15.win32.join(folder, script);
11200
+ if (!exists(file)) return void 0;
11201
+ const beside = path15.win32.join(folder, "node.exe");
11202
+ const node = exists(beside) ? beside : shimNode(pathDirs, deps);
11203
+ return node ? { file: node, leading: [file] } : void 0;
11204
+ }
11205
+ function shimNode(pathDirs, deps) {
11206
+ const exists = deps.exists ?? defaultExists3;
11207
+ const declared = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))().split(path15.win32.delimiter).map((e) => e.trim().toLowerCase()).filter(Boolean);
11208
+ const extensions = (declared.length > 0 ? declared : [".com", ".exe", ".bat", ".cmd"]).filter((e) => e !== ".js");
11209
+ for (const dir of pathDirs) {
11210
+ for (const ext of extensions) {
11211
+ const candidate = path15.win32.join(dir, `node${ext}`);
11212
+ if (exists(candidate)) return DIRECT_EXTENSIONS.includes(ext) ? candidate : void 0;
11213
+ }
11214
+ }
11215
+ return void 0;
11216
+ }
11042
11217
  function quoteForCmd(arg) {
11043
11218
  if (arg === "") return '""';
11044
11219
  if (!/[\s"^&|<>()]/.test(arg)) return arg;
@@ -11089,7 +11264,8 @@ async function findWindowsExecutables(command, deps) {
11089
11264
  const exists = deps.exists ?? defaultExists3;
11090
11265
  const pathExt = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))();
11091
11266
  const byRoute = candidateExtensions(command, pathExt);
11092
- const dirs = path15.win32.basename(command) !== command ? [path15.win32.dirname(path15.win32.resolve(command))] : (await (deps.resolvePath ?? augmentedPath)() || "").split(path15.win32.delimiter).map((d) => d.trim().replace(/^"|"$/g, "")).filter(Boolean);
11267
+ const pathDirs = (await (deps.resolvePath ?? augmentedPath)() || "").split(path15.win32.delimiter).map((d) => d.trim().replace(/^"|"$/g, "")).filter(Boolean);
11268
+ const dirs = path15.win32.basename(command) !== command ? [path15.win32.dirname(path15.win32.resolve(command))] : pathDirs;
11093
11269
  const base = path15.win32.basename(command);
11094
11270
  const found = [];
11095
11271
  for (const route of ROUTES) {
@@ -11097,7 +11273,8 @@ async function findWindowsExecutables(command, deps) {
11097
11273
  for (const dir of dirs) {
11098
11274
  const candidate = path15.win32.join(dir, `${base}${ext}`);
11099
11275
  if (exists(candidate)) {
11100
- found.push({ file: candidate, route });
11276
+ const target = route === "cmd" ? npmShimTarget(candidate, pathDirs, deps) : void 0;
11277
+ found.push(target ? { ...target, route: "direct" } : { file: candidate, route });
11101
11278
  break outer;
11102
11279
  }
11103
11280
  }
@@ -11107,8 +11284,9 @@ async function findWindowsExecutables(command, deps) {
11107
11284
  }
11108
11285
  function planFor(found, args, deps) {
11109
11286
  if (found.route === "direct") {
11110
- const length2 = windowsCommandLine(found.file, args).length;
11111
- return length2 > WINDOWS_MAX_COMMAND_LINE ? { tooLong: length2, limit: WINDOWS_MAX_COMMAND_LINE } : { file: found.file, args };
11287
+ const all = [...found.leading ?? [], ...args];
11288
+ const length2 = windowsCommandLine(found.file, all).length;
11289
+ return length2 > WINDOWS_MAX_COMMAND_LINE ? { tooLong: length2, limit: WINDOWS_MAX_COMMAND_LINE } : { file: found.file, args: all };
11112
11290
  }
11113
11291
  if (found.route === "cmd") {
11114
11292
  if (hasLineBreak([found.file, ...args])) return { lineBreak: true };
@@ -12448,8 +12626,8 @@ ${tail}` : ""}`;
12448
12626
  }
12449
12627
  /**
12450
12628
  * Tree-wide, because the direct child may be a CLI whose shells, MCP servers
12451
- * and test runs would outlive it — or, on Windows, the cmd.exe shim rather
12452
- * than the runner. The forced follow-up is scheduled and unref'd, so a
12629
+ * and test runs would outlive it — or, on Windows, the cmd.exe or PowerShell
12630
+ * that runs a shim rather than the runner. The forced follow-up is scheduled and unref'd, so a
12453
12631
  * disposed runner is never the reason the host refuses to exit.
12454
12632
  */
12455
12633
  dispose() {
@@ -14362,6 +14540,17 @@ async function probeCodexSandbox(deps, cwd, env) {
14362
14540
  const landlock = await runProbe(deps, cwd, env, ["--enable", "use_legacy_landlock"]);
14363
14541
  return landlock.code === 0 ? "legacy-landlock" : "unavailable";
14364
14542
  }
14543
+ var CODEX_WINDOWS_DOCS = "https://developers.openai.com/codex/windows";
14544
+ function codexWindowsReadOnlyNote(readiness) {
14545
+ const state = readiness === "updateRequired" ? "needs its setup run again" : "is not set up";
14546
+ return [
14547
+ `Codex's Windows sandbox ${state} on this machine, so Codex runs this task read-only with no sandbox: each edit, and each command it does not judge safe, goes to Codex's reviewer, and what the reviewer approves runs unconfined.`,
14548
+ "",
14549
+ `To give Codex its sandbox, run \`codex\` in a terminal and choose "Set up default sandbox" (it asks for Administrator once), or run /setup-default-sandbox there. Not the non-admin sandbox: under it Codex refuses every command of a task like this one. ${CODEX_WINDOWS_DOCS}`
14550
+ ].join("\n");
14551
+ }
14552
+ var CODEX_WINDOWS_READ_ONLY_ADVICE = "Codex's Windows sandbox is not ready on this machine, so your sandbox may be read-only. That does not stop this task: make edits with apply_patch, and run a command that must write (a build, an install, tests that write files) with escalated permissions. A reviewer decides each such request. Do not end the task because the sandbox is read-only.";
14553
+ var CODEX_WINDOWS_SHELL_ADVICE = "Your shell on this Windows machine is PowerShell. Where its execution policy refuses an npm-installed tool's .ps1 script (npm, npx, pnpm), call the .cmd beside it instead, as in npm.cmd test. Report a test run as passed only when you saw it pass.";
14365
14554
  var NAMESPACE_CAUSE = "Its Linux sandbox needs unprivileged user namespaces, which this kernel restricts (Ubuntu 24.04's AppArmor default), and the legacy Landlock backend did not work either.";
14366
14555
  var SYSCTL_FIX = " sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0";
14367
14556
  function codexSandboxUnavailableMessage(role = "planner") {
@@ -14625,13 +14814,14 @@ ${taskCompletionContract(commits ? { commits } : {})}`;
14625
14814
  */
14626
14815
  plannerInstructions(nativeSearch, hidden, ownShell = true, extra) {
14627
14816
  const tools = ordewellToolNames("planner", hidden, extra);
14817
+ const runCommand = !hidden?.includes("run_command");
14628
14818
  return [
14629
14819
  `You have ${countOf(tools)} tools from the \`${ORDEWELL_MCP_SERVER_NAME}\` MCP server: ${quoted3(tools)}.`,
14630
14820
  `They are not in your tool list up front. Find them with the tool discovery you have (the \`exec\` tool's \`ALL_TOOLS\` list) and call them by their full names, ${quoted3(this.toolNames("planner", hidden, extra))}.`,
14631
- ownShell ? `Run shell commands with \`${this.toolName("run_command")}\`, not your own shell: yours is sandboxed without network, so git remotes, gh and cloud CLIs fail there.` : `You have no shell of your own on this machine: run every command, reads included, with \`${this.toolName("run_command")}\`.`,
14821
+ !runCommand ? "" : ownShell ? `Run shell commands with \`${this.toolName("run_command")}\`, not your own shell: yours is sandboxed without network, so git remotes, gh and cloud CLIs fail there.` : `You have no shell of your own on this machine: run every command, reads included, with \`${this.toolName("run_command")}\`.`,
14632
14822
  `Fetch web pages with \`${this.toolName("fetch")}\`, not curl or your shell.`,
14633
14823
  nativeSearch ? "Search the web with your built-in web search." : `Your built-in web search is off for this session; search with \`${this.toolName("web_search")}\`.`
14634
- ].join(" ");
14824
+ ].filter(Boolean).join(" ");
14635
14825
  },
14636
14826
  plannerWebSearch: (nativeSearch) => nativeSearch ? "cached" : "disabled"
14637
14827
  };
@@ -14975,7 +15165,9 @@ var CodexAdapter = class extends StdioAgentAdapter {
14975
15165
  /** The row each announced file of an in-flight `fileChange` item is shown under, by the file's shown path. */
14976
15166
  fileChangeRows = /* @__PURE__ */ new Map();
14977
15167
  sandbox = "default";
14978
- /** A planner on a host where no sandbox starts: Codex's own shell is off, and `run_command` is its only one (ADR-0033). */
15168
+ /** Whether the user set up Codex's Windows sandbox, asked for a change task on a Windows host; null where nothing asked or Codex did not say. */
15169
+ windowsSandbox = null;
15170
+ /** Codex's own shell is off, and `run_command` is the only one: a read-only task's, and a planner's on a host where no sandbox starts (ADR-0033) or on Windows (ADR-0010). */
14979
15171
  ownShellOff = false;
14980
15172
  /** A read-only task's: every MCP server Codex would start beside Ordewell's, each switched off for its thread (ADR-0046). */
14981
15173
  withheldServers = [];
@@ -15011,9 +15203,11 @@ var CodexAdapter = class extends StdioAgentAdapter {
15011
15203
  const needsSandbox = opts.kind === "planner" || opts.flags.permissionMode !== "danger-full-access";
15012
15204
  const nothingToAsk = readOnly || this.deps.placement !== void 0 && !needsSandbox;
15013
15205
  this.sandbox = nothingToAsk ? "default" : await probeCodexSandbox(this.deps, opts.cwd, this.spawnEnv);
15014
- this.ownShellOff = readOnly || this.sandbox === "unavailable" && opts.kind === "planner" && !!opts.mcp;
15206
+ const unsandboxedPlanner = this.sandbox === "unavailable" && opts.kind === "planner" && !!opts.mcp;
15207
+ const readsThroughOrdewell = !!opts.mcp && !opts.mcp.hidden?.includes("run_command");
15208
+ this.ownShellOff = readOnly || unsandboxedPlanner || opts.kind === "planner" && readsThroughOrdewell && this.onWindowsHost();
15015
15209
  if (this.sandbox === "unavailable" && needsSandbox && !this.ownShellOff) throw new Error(codexSandboxUnavailableMessage(this.deps.placement ? "container" : opts.kind));
15016
- if (this.ownShellOff && !readOnly) this.announce({ type: "thinking", text: codexShellOffNote() });
15210
+ if (unsandboxedPlanner) this.announce({ type: "thinking", text: codexShellOffNote() });
15017
15211
  const incomplete = () => {
15018
15212
  throw this.handshakeIncomplete();
15019
15213
  };
@@ -15039,6 +15233,7 @@ ${this.exitMessage()}`);
15039
15233
  throw initialized.closed ? this.handshakeIncomplete() : new Error(`The Codex app-server rejected initialize: ${initialized.message ?? "unknown error"}`);
15040
15234
  }
15041
15235
  if (readOnlyTask(opts)) this.withheldServers = await this.configuredServers(opts.cwd);
15236
+ if (this.runsWindowsSandbox(opts)) this.windowsSandbox = await this.windowsSandboxReadiness();
15042
15237
  const resumeId = opts.resumeSessionId;
15043
15238
  let opened2 = await this.requestThread(resumeId);
15044
15239
  if ("reason" in opened2 && resumeId) {
@@ -15049,8 +15244,34 @@ ${this.exitMessage()}`);
15049
15244
  this.threadId = opened2.id;
15050
15245
  this.sessionId = opened2.id;
15051
15246
  this.threadModel = opened2.model;
15247
+ if (opts.kind === "task" && this.windowsSandbox !== null && this.windowsSandbox !== "ready" && opened2.sandbox === "readOnly") {
15248
+ this.announce({ type: "thinking", text: codexWindowsReadOnlyNote(this.windowsSandbox) });
15249
+ }
15052
15250
  if (opts.kind === "task") await this.loadCommands(this.runnerCwd(opts));
15053
15251
  }
15252
+ /**
15253
+ * Codex runs on this Windows host, not placed on another machine. Its
15254
+ * sandboxes here cannot keep a planner's command off the network: with none
15255
+ * set up there is none, and under the non-admin one Node reaches the network
15256
+ * (measured, ADR-0010). So a planner's own shell is off here, and every
15257
+ * command goes through Ordewell's `run_command`, as every other planner's
15258
+ * does on Windows (ADR-0026). A one-shot plan, which runs no command, keeps
15259
+ * Codex's shell with its approvals declined: it has no other way to read.
15260
+ */
15261
+ onWindowsHost() {
15262
+ return !this.deps.placement && (this.deps.platform ?? process.platform) === "win32";
15263
+ }
15264
+ /** A change task whose commands Codex runs in its own Windows sandbox, which the user may not have set up. */
15265
+ runsWindowsSandbox(opts) {
15266
+ return opts.kind === "task" && this.onWindowsHost() && !this.ownShellOff && opts.flags.permissionMode === "workspace-write";
15267
+ }
15268
+ /** Codex's answer, or null from a Codex that has no such question: that one is left as it configures itself. */
15269
+ async windowsSandboxReadiness() {
15270
+ const response = await this.rpc.call("windowsSandbox/readiness", {});
15271
+ if (!response.ok && response.closed) throw this.handshakeIncomplete();
15272
+ const status = response.ok ? response.result.status : void 0;
15273
+ return status === "ready" || status === "notConfigured" || status === "updateRequired" ? status : null;
15274
+ }
15054
15275
  commands() {
15055
15276
  return this.nativeCommands.map((command) => ({ ...command }));
15056
15277
  }
@@ -15118,6 +15339,7 @@ ${this.exitMessage()}`);
15118
15339
  }
15119
15340
  return Object.keys(servers).filter((name) => name !== ORDEWELL_MCP_SERVER_NAME);
15120
15341
  }
15342
+ /** The thread, the model it runs, and the sandbox Codex granted it, which need not be the one asked for. */
15121
15343
  async requestThread(resumeSessionId) {
15122
15344
  const response = await this.rpc.call(resumeSessionId ? "thread/resume" : "thread/start", {
15123
15345
  ...resumeSessionId ? { threadId: resumeSessionId } : {},
@@ -15127,7 +15349,8 @@ ${this.exitMessage()}`);
15127
15349
  const thread = response.ok ? response.result.thread : void 0;
15128
15350
  if (!thread?.id) return { reason: !response.ok && response.message || "no thread id returned" };
15129
15351
  const model = response.ok ? response.result.model : void 0;
15130
- return { id: thread.id, model: typeof model === "string" ? model : null };
15352
+ const sandbox = response.ok ? response.result.sandbox?.type : void 0;
15353
+ return { id: thread.id, model: typeof model === "string" ? model : null, sandbox: typeof sandbox === "string" ? sandbox : null };
15131
15354
  }
15132
15355
  threadParams() {
15133
15356
  const opts = this.startOpts;
@@ -15145,14 +15368,20 @@ ${this.exitMessage()}`);
15145
15368
  ...opts?.mcp ? { mcp_servers: CODEX_ORDEWELL.threadServers(opts.mcp) } : {}
15146
15369
  };
15147
15370
  const threadConfig = Object.keys(config).length ? { config } : {};
15371
+ const noWindowsSandbox = this.windowsSandbox !== null && this.windowsSandbox !== "ready";
15148
15372
  if (opts?.kind === "task") {
15149
15373
  const { approvalPolicy, approvalsReviewer } = opts.flags.modeSettings;
15374
+ const developerInstructions = [
15375
+ opts.mcp ? CODEX_ORDEWELL.taskInstructions({ readOnly: readOnlyTask(opts), ...opts.commits ? { commits: true } : {}, ...opts.mcp.extraTools ? { extra: opts.mcp.extraTools } : {} }) : "",
15376
+ this.onWindowsHost() && !this.ownShellOff ? CODEX_WINDOWS_SHELL_ADVICE : "",
15377
+ noWindowsSandbox ? CODEX_WINDOWS_READ_ONLY_ADVICE : ""
15378
+ ].filter(Boolean).join("\n\n");
15150
15379
  return {
15151
15380
  ...common,
15152
15381
  sandbox: opts.flags.permissionMode,
15153
15382
  ...approvalPolicy ? { approvalPolicy } : {},
15154
15383
  ...approvalsReviewer ? { approvalsReviewer } : {},
15155
- ...opts.mcp ? { developerInstructions: CODEX_ORDEWELL.taskInstructions({ readOnly: readOnlyTask(opts), ...opts.commits ? { commits: true } : {}, ...opts.mcp.extraTools ? { extra: opts.mcp.extraTools } : {} }) } : {},
15384
+ ...developerInstructions ? { developerInstructions } : {},
15156
15385
  ...threadConfig,
15157
15386
  ...readOnlyTask(opts) ? { config: { ...config, mcp_servers: { ...withheld(this.withheldServers), ...config.mcp_servers }, projects: untrustedProjects(opts.cwd), web_search: "disabled" } } : {}
15158
15387
  };
@@ -20778,7 +21007,7 @@ function researchTasksGuide(tools) {
20778
21007
  function sealedGuide(tool2) {
20779
21008
  return `${tool2} with "sealed": true runs a command without asking anyone, for local computation over the workspace: a loop over files, a script, a pipe into an interpreter. A sealed run has no network, the workspace read-only, and no home directory or credentials; $TMPDIR is a scratch directory kept for the session's sealed runs, so read what one left there with another sealed run. A command that would be refused for being a loop, a here-document or a pipe into an interpreter runs sealed on its own where this machine has a sandbox, and you can ask for it yourself when you know a command is local computation. Never seal a command that needs the network or the user's accounts: it fails there. An allowlist exclusion and a command the user denied are refused either way, and without a sandbox a command that would run sealed is refused.`;
20780
21009
  }
20781
- function researchPhaseBlock(harnessMode, agents) {
21010
+ function researchPhaseBlock(harnessMode, agents, researchShell) {
20782
21011
  const shared2 = [
20783
21012
  "RESEARCH PHASE:",
20784
21013
  "- Start by reading README.md and any agent config files (AGENTS.md, CLAUDE.md)"
@@ -20787,6 +21016,7 @@ function researchPhaseBlock(harnessMode, agents) {
20787
21016
  "- Explore the repository with your own tools until you understand its architecture",
20788
21017
  "- You are planning, not implementing: do NOT edit, create, or delete any file, and do not run commands that change the workspace",
20789
21018
  "- Run commands \u2014 git, gh, cloud CLIs, the project's own tooling \u2014 with the run_command tool, not a shell of your own. MCP tools the user configured (issue trackers, todo lists) are yours to read from too. Reads run at once; anything else is approved or refused by the user's settings. When something the plan needs to change is refused, add it to the plan instead: a script task when you can state the exact commands, an ops task when it needs judgment",
21019
+ ...researchShellLine(researchShell),
20790
21020
  `- ${sealedGuide("run_command")}`,
20791
21021
  ...agents === null ? [] : ["- When you delegate orientation to your own agents (WHO EXPLORES below), WAIT for their results inside this reply. Do NOT launch them in the background or async and end your turn saying you will report back later: your turn ending is what hands the conversation back to the user, and anything you say after it never reaches them."]
20792
21022
  ] : [
@@ -20834,6 +21064,11 @@ var NATIVE_SHELL_GUIDE = [
20834
21064
  ].join("\n");
20835
21065
  var AUTORUN_ON = "AUTORUN is on: a plan you submit starts when your reply ends, without the user's review. When you are ready to plan, write the outline in your reply as the plan's summary and submit the plan in the same reply; do not wait for the user to confirm it, and do not start its tasks yourself. Still ask clarifying questions first when the goal is vague or a decision would materially change the outcome.";
20836
21066
  var AUTORUN_OFF = "AUTORUN is off now: show the outline and wait for the user to confirm it before you submit a plan.";
21067
+ function researchShellLine(shell) {
21068
+ if (shell === "git-bash") return ["- On this Windows machine run_command runs Git Bash, a POSIX shell: read with cat, ls, grep and find, not PowerShell cmdlets such as Get-Content."];
21069
+ if (shell === "cmd") return ["- On this Windows machine run_command runs cmd.exe: read with type, dir and findstr, not PowerShell cmdlets such as Get-Content."];
21070
+ return [];
21071
+ }
20837
21072
  var EXECUTION_TOOLS_SECTION = [
20838
21073
  "RUNNING THE PLAN:",
20839
21074
  "When the user asks you to start, stop or retry work, do it with these tools rather than telling them which button to press. Ordewell checks every call, may ask the user first, and a refusal says why and what would be accepted.",
@@ -21029,7 +21264,7 @@ function buildConversationBody(goal, context, modelsJson, runners, modeGuide, va
21029
21264
  "4. When the strategy calls for a plan and you have enough context, produce a prose outline \u2014 a short list describing each task in order.",
21030
21265
  autorun ? `5. Write the outline in your reply, then ${submit} in the same reply.` : `5. After the user confirms the outline, ${submit}.`,
21031
21266
  "",
21032
- researchPhaseBlock(tools, agents),
21267
+ researchPhaseBlock(tools, agents, variant.researchShell),
21033
21268
  "",
21034
21269
  ...whoExploresSection(agents),
21035
21270
  "",
@@ -28188,9 +28423,10 @@ function nonPromptingFs(fs29) {
28188
28423
  findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs29.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
28189
28424
  listDir: (p, depth) => withinWorkspace(p) ? fs29.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
28190
28425
  bash: async (command, signal, opts) => {
28191
- const policy = researchPolicyOptions(resolveResearchShell());
28426
+ const shell = resolveResearchShell();
28427
+ const policy = researchPolicyOptions(shell);
28192
28428
  const { tier, reason } = classifyCommand(command, policy);
28193
- const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs29.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
28429
+ const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs29.getWorkspaceRoot(), ref2, shell.hostPath)).find((r) => !r.inside);
28194
28430
  if (tier === "auto" && !escaping && !opts?.sealed) return fs29.bash(command, signal);
28195
28431
  if (opts?.sealed || await fs29.canSeal?.()) return fs29.bash(command, signal, { sealed: true });
28196
28432
  if (tier === "refuse") return refused2(`Command refused: ${reason}`);
@@ -32843,7 +33079,7 @@ import * as path45 from "path";
32843
33079
  // src/services/taskStartConfig.ts
32844
33080
  import * as path41 from "path";
32845
33081
  import { createHash as createHash4 } from "crypto";
32846
- import { existsSync as existsSync16, lstatSync as lstatSync4, readdirSync as readdirSync9, readFileSync as readFileSync15, statSync as statSync12 } from "fs";
33082
+ import { existsSync as existsSync16, lstatSync as lstatSync4, readdirSync as readdirSync9, readFileSync as readFileSync16, statSync as statSync12 } from "fs";
32847
33083
  var MAX_FILES = 2e3;
32848
33084
  var MAX_DEPTH = 8;
32849
33085
  function liveConfig(dir) {
@@ -32854,7 +33090,7 @@ function liveConfig(dir) {
32854
33090
  try {
32855
33091
  const info = statSync12(full);
32856
33092
  if (info.isFile()) {
32857
- found.set(rel, createHash4("sha1").update(readFileSync15(full)).digest("hex"));
33093
+ found.set(rel, createHash4("sha1").update(readFileSync16(full)).digest("hex"));
32858
33094
  } else if (info.isDirectory() && path41.basename(rel) !== "node_modules") {
32859
33095
  for (const name of readdirSync9(full)) visit(path41.posix.join(rel, name), depth + 1);
32860
33096
  }
@@ -39971,7 +40207,7 @@ function nativeShellOffer(input) {
39971
40207
  if (input.runner === "codex") {
39972
40208
  return {
39973
40209
  offered: false,
39974
- reason: "Codex already runs its own shell, read-only and without the network (ADR-0026), so this setting changes nothing for it."
40210
+ reason: platform === "win32" ? "On Windows Codex plans with its own shell off, since its sandbox there cannot keep a command off the network, and runs every command through Ordewell's (ADR-0010)." : "Codex already runs its own shell, read-only and without the network (ADR-0026), so this setting changes nothing for it."
39975
40211
  };
39976
40212
  }
39977
40213
  const checked = CHECKED[input.runner];
@@ -40131,6 +40367,11 @@ var CliAgentAiService = class {
40131
40367
  hasActiveConversation() {
40132
40368
  return this.session?.start != null;
40133
40369
  }
40370
+ /** On Windows, the shell `run_command` runs, which a coding agent there would take for PowerShell (ADR-0010). */
40371
+ researchShell() {
40372
+ if ((this.processDeps.platform ?? process.platform) !== "win32") return void 0;
40373
+ return resolveResearchShell().dialect === "cmd" ? "cmd" : "git-bash";
40374
+ }
40134
40375
  /**
40135
40376
  * False when the running agent process was spawned under a model/effort the
40136
40377
  * user has since changed in the picker. Unlike a vendor backend, the model
@@ -40192,13 +40433,14 @@ var CliAgentAiService = class {
40192
40433
  this.session = session;
40193
40434
  session.notice = req.notice;
40194
40435
  const contextStr = await collectResearchContext(req.fs, req.runners);
40436
+ const researchShell = this.researchShell();
40195
40437
  const systemPrompt = buildConversationSystemPrompt(
40196
40438
  req.goal,
40197
40439
  contextStr,
40198
40440
  req.modelsByRunner,
40199
40441
  req.runners,
40200
40442
  req.runnerModes,
40201
- { harness: true, runner: this.runner, isolatedExecution: req.isolatedExecution, skills: req.skills, execution: req.plannerTools !== void 0, autorun: req.autorun, delegation: req.delegation, subplanner: req.subplanner, ...req.plannerTools.noSubagents ? { subagents: false } : {} }
40443
+ { harness: true, runner: this.runner, isolatedExecution: req.isolatedExecution, skills: req.skills, execution: req.plannerTools !== void 0, autorun: req.autorun, delegation: req.delegation, subplanner: req.subplanner, ...req.plannerTools.noSubagents ? { subagents: false } : {}, ...researchShell ? { researchShell } : {} }
40202
40444
  );
40203
40445
  const fetcher = req.fetcher;
40204
40446
  const cwd = this.workspaceRoot();
@@ -40785,6 +41027,9 @@ ${corrective}`, catalog, onProgress, signal),
40785
41027
  };
40786
41028
  const tools = {
40787
41029
  sessionId: uuidv48(),
41030
+ // No session here runs a command, so the planner is not offered one: it
41031
+ // reads with its harness's own tools, and Codex keeps its shell for it.
41032
+ withheld: ["run_command"],
40788
41033
  handler: {
40789
41034
  listRunners: async () => ({ text: JSON.stringify({ runners: catalog.runners.map((id2) => ({ id: id2, readOnly: readOnlyMode(catalog.runnerModes?.[id2]) !== void 0 })) }) }),
40790
41035
  listModels: async ({ runner }) => ({ text: JSON.stringify({ runner, models: catalog.modelsByRunner?.[runner] ?? [] }) }),
@@ -44217,9 +44462,9 @@ function withTaskRunnerConfig(runner, setting) {
44217
44462
 
44218
44463
  // src/services/container/dockerLease.ts
44219
44464
  import { createHash as createHash11, randomBytes as randomBytes11 } from "crypto";
44220
- import { mkdtempSync as mkdtempSync8, readFileSync as readFileSync17, rmSync as rmSync15 } from "fs";
44465
+ import { mkdtempSync as mkdtempSync8, readFileSync as readFileSync18, rmSync as rmSync15 } from "fs";
44221
44466
  import { tmpdir as tmpdir9 } from "os";
44222
- import { basename as basename7, join as join47, posix as posix15, relative as relative18, sep as sep11 } from "path";
44467
+ import { basename as basename7, join as join47, posix as posix16, relative as relative18, sep as sep11 } from "path";
44223
44468
 
44224
44469
  // src/services/container/modelGateway.ts
44225
44470
  import { createHash as createHash8, randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual2 } from "crypto";
@@ -44392,7 +44637,7 @@ var CredentialBroker = class {
44392
44637
 
44393
44638
  // src/services/container/taskWorkspace.ts
44394
44639
  import { createHash as createHash9 } from "crypto";
44395
- import { posix as posix13 } from "path";
44640
+ import { posix as posix14 } from "path";
44396
44641
  var MIRROR_ROOT = "/mirror";
44397
44642
  var TASK_ROOT = "/task";
44398
44643
  var WORK_ROOT = `${TASK_ROOT}/work`;
@@ -44409,8 +44654,8 @@ printf %s "$kept" > ${mark}
44409
44654
  `;
44410
44655
  var SIGN_IN_COPY = `${TASK_ROOT}/login/claude`;
44411
44656
  var SIGN_IN_MARK = `${TASK_ROOT}/login/handed`;
44412
- var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix13.join(WORK_ROOT, repo.path);
44413
- var mirrorDir2 = (repo) => posix13.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44657
+ var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix14.join(WORK_ROOT, repo.path);
44658
+ var mirrorDir2 = (repo) => posix14.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44414
44659
  var exportRef = (attempt) => `refs/ordewell/export/${attempt}`;
44415
44660
  var receiveScript = (mirror) => `set -e; [ -d ${mirror} ] || git init -q --bare ${mirror}; cd ${mirror}; git config gc.auto 0; git config gc.pruneExpire never; git config receive.autogc false; exec git receive-pack .`;
44416
44661
  var extArgument = (arg) => arg.replace(/%/g, "%%").replace(/ /g, "% ");
@@ -44555,7 +44800,7 @@ function parseContainerSettings(raw) {
44555
44800
  }
44556
44801
 
44557
44802
  // src/services/container/containerRunners.ts
44558
- import { posix as posix14 } from "path";
44803
+ import { posix as posix15 } from "path";
44559
44804
  var LOGIN_VOLUME = "ordewell-login-claude-code";
44560
44805
  var CODEX_LOGIN_VOLUME = "ordewell-login-codex";
44561
44806
  var OPENCODE_LOGIN_VOLUME = "ordewell-login-opencode";
@@ -44608,7 +44853,7 @@ var CONTAINER_RUNNERS = [
44608
44853
  api: ANTHROPIC_API,
44609
44854
  unbrokered: { openai: OPENAI_API },
44610
44855
  // The copy is the runner's data directory, which `XDG_DATA_HOME` names the parent of.
44611
- signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix14.join(TASK_ROOT, "login") } },
44856
+ signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix15.join(TASK_ROOT, "login") } },
44612
44857
  args: (launch) => launch.args
44613
44858
  }
44614
44859
  ];
@@ -45712,7 +45957,7 @@ var DockerExecutionBackend = class {
45712
45957
  }
45713
45958
  async workingDirectory(opened2) {
45714
45959
  const { worktree, writable, cwd } = opened2.workspace;
45715
- return posix15.join(WORK_ROOT, worktree ? relative18(writable ?? cwd, cwd).split(sep11).join("/") : await this.checkoutFolder(cwd));
45960
+ return posix16.join(WORK_ROOT, worktree ? relative18(writable ?? cwd, cwd).split(sep11).join("/") : await this.checkoutFolder(cwd));
45716
45961
  }
45717
45962
  async start({ runner, settings, spec, opened: opened2, repos }, signal) {
45718
45963
  const taskId = spec.task.id;
@@ -45950,7 +46195,7 @@ var DockerExecutionBackend = class {
45950
46195
  const moved = /* @__PURE__ */ new Map();
45951
46196
  for (const file of launch.files) {
45952
46197
  const inside2 = `/tmp/ordewell/${launchNumber}-${basename7(file)}`;
45953
- const wrote = await this.cli.call(["exec", "-i", box.name, "sh", "-c", 'umask 077; mkdir -p /tmp/ordewell; cat > "$0"', inside2], { input: readFileSync17(file) });
46198
+ const wrote = await this.cli.call(["exec", "-i", box.name, "sh", "-c", 'umask 077; mkdir -p /tmp/ordewell; cat > "$0"', inside2], { input: readFileSync18(file) });
45954
46199
  if (wrote.code !== 0) throw new Error(`Could not hand the runner its configuration: ${wrote.stderr.trim()}`);
45955
46200
  moved.set(file, inside2);
45956
46201
  }