@ai-hero/sandcastle 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.
Files changed (77) hide show
  1. package/README.md +15 -1368
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
  4. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  5. package/dist/chunk-6NQPCXSG.js.map +1 -0
  6. package/dist/chunk-7N7AMUYA.js +353 -0
  7. package/dist/chunk-7N7AMUYA.js.map +1 -0
  8. package/dist/chunk-ATA2V2TC.js +112 -0
  9. package/dist/chunk-ATA2V2TC.js.map +1 -0
  10. package/dist/chunk-BIF2X6QB.js +94 -0
  11. package/dist/chunk-BIF2X6QB.js.map +1 -0
  12. package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
  13. package/dist/chunk-BVZWLFFT.js.map +1 -0
  14. package/dist/chunk-EXYXBRCX.js +60 -0
  15. package/dist/chunk-EXYXBRCX.js.map +1 -0
  16. package/dist/chunk-G2R53CVZ.js +3172 -0
  17. package/dist/chunk-G2R53CVZ.js.map +1 -0
  18. package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
  19. package/dist/chunk-GCLEXPXG.js.map +1 -0
  20. package/dist/chunk-H2PEFS4W.js +1244 -0
  21. package/dist/chunk-H2PEFS4W.js.map +1 -0
  22. package/dist/chunk-HSXPRZKG.js +150 -0
  23. package/dist/chunk-HSXPRZKG.js.map +1 -0
  24. package/dist/chunk-IBK2XNSS.js +50 -0
  25. package/dist/chunk-IBK2XNSS.js.map +1 -0
  26. package/dist/chunk-RDW7FNN6.js +792 -0
  27. package/dist/chunk-RDW7FNN6.js.map +1 -0
  28. package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
  29. package/dist/chunk-S6UHPTRG.js.map +1 -0
  30. package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
  31. package/dist/chunk-STB2U7BB.js.map +1 -0
  32. package/dist/chunk-VRXR2T3S.js +24 -0
  33. package/dist/chunk-VRXR2T3S.js.map +1 -0
  34. package/dist/index.d.ts +241 -26
  35. package/dist/index.js +1082 -1679
  36. package/dist/index.js.map +1 -1
  37. package/dist/main.js +1248 -854
  38. package/dist/main.js.map +1 -1
  39. package/dist/sandboxes/bwrap.d.ts +58 -0
  40. package/dist/sandboxes/bwrap.js +296 -0
  41. package/dist/sandboxes/bwrap.js.map +1 -0
  42. package/dist/sandboxes/daytona.d.ts +1 -1
  43. package/dist/sandboxes/daytona.js +203 -98
  44. package/dist/sandboxes/daytona.js.map +1 -1
  45. package/dist/sandboxes/docker.d.ts +18 -4
  46. package/dist/sandboxes/docker.js +7 -4
  47. package/dist/sandboxes/e2b.d.ts +41 -0
  48. package/dist/sandboxes/e2b.js +202 -0
  49. package/dist/sandboxes/e2b.js.map +1 -0
  50. package/dist/sandboxes/modal.d.ts +78 -0
  51. package/dist/sandboxes/modal.js +171 -0
  52. package/dist/sandboxes/modal.js.map +1 -0
  53. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  54. package/dist/sandboxes/no-sandbox.js +2 -2
  55. package/dist/sandboxes/podman.d.ts +18 -4
  56. package/dist/sandboxes/podman.js +72 -56
  57. package/dist/sandboxes/podman.js.map +1 -1
  58. package/dist/sandboxes/seatbelt.d.ts +65 -0
  59. package/dist/sandboxes/seatbelt.js +425 -0
  60. package/dist/sandboxes/seatbelt.js.map +1 -0
  61. package/dist/sandboxes/sprites.d.ts +54 -0
  62. package/dist/sandboxes/sprites.js +198 -0
  63. package/dist/sandboxes/sprites.js.map +1 -0
  64. package/dist/sandboxes/vercel.d.ts +12 -5
  65. package/dist/sandboxes/vercel.js +195 -126
  66. package/dist/sandboxes/vercel.js.map +1 -1
  67. package/dist/templates/parallel-planner/main.mts +13 -22
  68. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  69. package/package.json +63 -11
  70. package/dist/chunk-62WN33RK.js +0 -104
  71. package/dist/chunk-62WN33RK.js.map +0 -1
  72. package/dist/chunk-BIWNFKGV.js.map +0 -1
  73. package/dist/chunk-CP3TYXZA.js.map +0 -1
  74. package/dist/chunk-DJRHWPEH.js.map +0 -1
  75. package/dist/chunk-NGBM7T3E.js.map +0 -1
  76. package/dist/chunk-VOG34SRF.js.map +0 -1
  77. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Shared mount utilities for Docker and Podman sandbox providers.
3
+ *
4
+ * Handles host/sandbox path resolution, tilde expansion, user mount
5
+ * validation, image naming, and Windows path normalization.
6
+ */
7
+
8
+ /**
9
+ * SELinux volume label suffix applied to bind mounts.
10
+ *
11
+ * - `"z"` — shared label. No-op on non-SELinux systems.
12
+ * - `"Z"` — private label; only this container can access the mount.
13
+ * - `false` — disable labeling entirely.
14
+ */
15
+ type SelinuxLabel = "z" | "Z" | false;
16
+ /**
17
+ * Derive the default image name from the repo directory.
18
+ * Returns `sandcastle:<dir-name>` where dir-name is the last path segment,
19
+ * lowercased and sanitized for image tag rules.
20
+ *
21
+ * Handles both POSIX (`/`) and Windows (`\`) path separators.
22
+ */
23
+ declare const defaultImageName: (repoDir: string) => string;
24
+
25
+ /**
26
+ * A Linux capability name as `docker run --cap-drop` and `podman run --cap-drop`
27
+ * accept it: without the `CAP_` prefix (see capabilities(7)), or `"ALL"` for
28
+ * every capability.
29
+ */
30
+ type LinuxCapability = "ALL" | "AUDIT_CONTROL" | "AUDIT_READ" | "AUDIT_WRITE" | "BLOCK_SUSPEND" | "BPF" | "CHECKPOINT_RESTORE" | "CHOWN" | "DAC_OVERRIDE" | "DAC_READ_SEARCH" | "FOWNER" | "FSETID" | "IPC_LOCK" | "IPC_OWNER" | "KILL" | "LEASE" | "LINUX_IMMUTABLE" | "MAC_ADMIN" | "MAC_OVERRIDE" | "MKNOD" | "NET_ADMIN" | "NET_BIND_SERVICE" | "NET_BROADCAST" | "NET_RAW" | "PERFMON" | "SETFCAP" | "SETGID" | "SETPCAP" | "SETUID" | "SYS_ADMIN" | "SYS_BOOT" | "SYS_CHROOT" | "SYS_MODULE" | "SYS_NICE" | "SYS_PACCT" | "SYS_PTRACE" | "SYS_RAWIO" | "SYS_RESOURCE" | "SYS_TIME" | "SYS_TTY_CONFIG" | "SYSLOG" | "WAKE_ALARM";
31
+
32
+ export { type LinuxCapability as L, type SelinuxLabel as S, defaultImageName as d };
@@ -21,6 +21,26 @@ interface InteractiveExecOptions {
21
21
  interface BindMountSandboxHandle {
22
22
  /** Absolute path to the worktree inside the sandbox. */
23
23
  readonly worktreePath: string;
24
+ /**
25
+ * The id a supervisor outside this process can use to address the sandbox
26
+ * with the runtime's own tools, e.g. `docker()` and `podman()` set it to the
27
+ * container name (`docker rm -f <sandboxId>`). Surfaced as
28
+ * `Sandbox.sandboxId`. Omit it when there is nothing outside the process to
29
+ * address, as for the native `bwrap()` and `seatbelt()` sandboxes, whose
30
+ * sandbox is a child process of this one.
31
+ */
32
+ readonly sandboxId?: string;
33
+ /**
34
+ * Absolute path to the agent's home directory, as commands running inside
35
+ * the sandbox see it. Sandcastle runs commands there to find and place agent
36
+ * session files. Omit when it is `/home/agent`, as in the Docker image.
37
+ */
38
+ readonly sandboxHomedir?: string;
39
+ /**
40
+ * Absolute path to a writable temp directory, as commands running inside
41
+ * the sandbox see it. Omit when it is `/tmp`.
42
+ */
43
+ readonly sandboxTmpdir?: string;
24
44
  /**
25
45
  * Execute a command in the sandbox.
26
46
  *
@@ -62,11 +82,11 @@ interface BindMountCreateOptions {
62
82
  /** Host-side path to the original repo root. */
63
83
  readonly hostRepoPath: string;
64
84
  /** Volume mounts to apply (host:sandbox pairs). */
65
- readonly mounts: Array<{
85
+ readonly mounts: {
66
86
  hostPath: string;
67
87
  sandboxPath: string;
68
88
  readonly?: boolean;
69
- }>;
89
+ }[];
70
90
  /** Environment variables to inject into the sandbox. */
71
91
  readonly env: Record<string, string>;
72
92
  }
@@ -89,6 +109,14 @@ interface BindMountSandboxProviderConfig {
89
109
  interface IsolatedSandboxHandle {
90
110
  /** Absolute path to the worktree inside the sandbox. */
91
111
  readonly worktreePath: string;
112
+ /**
113
+ * The vendor's id for the sandbox, so a supervisor outside this process can
114
+ * address it with the vendor's own CLI or API, e.g. `vercel()`,
115
+ * `daytona()` and `modal()` set it to the Vercel, Daytona and Modal sandbox
116
+ * ids. Surfaced as
117
+ * `Sandbox.sandboxId`. Omit it when the provider has no such id.
118
+ */
119
+ readonly sandboxId?: string;
92
120
  /**
93
121
  * Execute a command in the sandbox.
94
122
  *
@@ -240,4 +268,4 @@ declare const createBindMountSandboxProvider: (config: BindMountSandboxProviderC
240
268
  */
241
269
  declare const createIsolatedSandboxProvider: (config: IsolatedSandboxProviderConfig) => IsolatedSandboxProvider;
242
270
 
243
- export { type AnySandboxProvider as A, type BindMountSandboxHandle as B, type ExecResult as E, type HeadBranchStrategy as H, type IsolatedSandboxProvider as I, type MergeToHeadBranchStrategy as M, type NoSandboxProvider as N, type SandboxProvider as S, type BranchStrategy as a, type NamedBranchStrategy as b, type BindMountBranchStrategy as c, type BindMountCreateOptions as d, type BindMountSandboxProvider as e, type BindMountSandboxProviderConfig as f, type InteractiveExecOptions as g, type IsolatedBranchStrategy as h, type IsolatedCreateOptions as i, type IsolatedSandboxHandle as j, type IsolatedSandboxProviderConfig as k, type NoSandboxBranchStrategy as l, type NoSandboxHandle as m, createBindMountSandboxProvider as n, createIsolatedSandboxProvider as o };
271
+ export { type AnySandboxProvider as A, type BindMountSandboxProvider as B, type ExecResult as E, type HeadBranchStrategy as H, type IsolatedSandboxProvider as I, type MergeToHeadBranchStrategy as M, type NoSandboxProvider as N, type SandboxProvider as S, type BindMountSandboxHandle as a, type BranchStrategy as b, type NamedBranchStrategy as c, type BindMountBranchStrategy as d, type BindMountCreateOptions as e, type BindMountSandboxProviderConfig as f, type InteractiveExecOptions as g, type IsolatedBranchStrategy as h, type IsolatedCreateOptions as i, type IsolatedSandboxHandle as j, type IsolatedSandboxProviderConfig as k, type NoSandboxBranchStrategy as l, type NoSandboxHandle as m, createBindMountSandboxProvider as n, createIsolatedSandboxProvider as o };
@@ -62,6 +62,9 @@ var BoundedTail = class {
62
62
  this.items.push(bounded);
63
63
  while (this.totalChars > this.maxChars && this.items.length > 1) {
64
64
  const dropped = this.items.shift();
65
+ if (dropped === void 0) {
66
+ break;
67
+ }
65
68
  this.totalChars -= dropped.length + this.separator.length;
66
69
  }
67
70
  }
@@ -72,5 +75,5 @@ var BoundedTail = class {
72
75
  };
73
76
 
74
77
  export { BoundedTail, MAX_TAIL_CHARS, __commonJS, __export, __reExport, __require, __toESM };
75
- //# sourceMappingURL=chunk-NGBM7T3E.js.map
76
- //# sourceMappingURL=chunk-NGBM7T3E.js.map
78
+ //# sourceMappingURL=chunk-6NQPCXSG.js.map
79
+ //# sourceMappingURL=chunk-6NQPCXSG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/boundedTail.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBO,IAAM,iBAAiB,EAAA,GAAK;AAa5B,IAAM,cAAN,MAAkB;AAAA,EACN,QAAkB,EAAC;AAAA,EAC5B,UAAA,GAAa,CAAA;AAAA,EACJ,QAAA;AAAA,EACA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,WAAA,CAAY,QAAA,GAAmB,cAAA,EAAgB,SAAA,GAAY,EAAA,EAAI;AAC7D,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AAAA;AAAA,EAGA,KAAK,IAAA,EAAoB;AACvB,IAAA,MAAM,OAAA,GACJ,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,QAAA,GACf,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,QAAQ,CAAA,GACtC,IAAA;AACN,IAAA,IAAA,CAAK,UAAA,IACH,QAAQ,MAAA,IAAU,IAAA,CAAK,MAAM,MAAA,GAAS,CAAA,GAAI,IAAA,CAAK,SAAA,CAAU,MAAA,GAAS,CAAA,CAAA;AACpE,IAAA,IAAA,CAAK,KAAA,CAAM,KAAK,OAAO,CAAA;AACvB,IAAA,OAAO,KAAK,UAAA,GAAa,IAAA,CAAK,YAAY,IAAA,CAAK,KAAA,CAAM,SAAS,CAAA,EAAG;AAC/D,MAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,KAAA,EAAM;AACjC,MAAA,IAAI,YAAY,MAAA,EAAW;AACzB,QAAA;AAAA,MACF;AACA,MAAA,IAAA,CAAK,UAAA,IAAc,OAAA,CAAQ,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,MAAA;AAAA,IACrD;AAAA,EACF;AAAA;AAAA,EAGA,QAAA,GAAmB;AACjB,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,SAAS,CAAA;AAAA,EACvC;AACF","file":"chunk-6NQPCXSG.js","sourcesContent":["/**\n * A bounded, rolling tail of streamed output — a pure, provider-agnostic\n * utility shared by every sandbox provider that streams `exec` output.\n *\n * When a provider streams output line-by-line, it accumulates the stream only\n * to build the returned `ExecResult.stdout`/`stderr`. Consumers read just the\n * tail of that value (e.g. the last lines of an error, or a fallback for the\n * agent's final result), so retaining the whole stream is unnecessary — and,\n * once the accumulated string passes V8's ~512MB max string length, fatal: a\n * naive `chunks.join()` throws `RangeError: Invalid string length`, which on a\n * long agent run crashes the whole orchestration.\n */\n\n/**\n * Default maximum number of characters retained in a bounded output tail.\n *\n * 64KiB sits comfortably above any agent completion signal or structured-output\n * payload while staying far below V8's max string length.\n */\nexport const MAX_TAIL_CHARS = 64 * 1024;\n\n/**\n * A fixed-size rolling tail of strings, bounded by total character length.\n *\n * `push` appends to the tail; once the joined length would exceed `maxChars`,\n * the oldest items are dropped from the front. A single item longer than\n * `maxChars` is truncated to its own tail, so a newline-free blob can't\n * overflow on one push. `toString` joins the retained items, and its length is\n * always at most `maxChars`.\n *\n * The running length counter is encapsulated so callers can't desync it.\n */\nexport class BoundedTail {\n private readonly items: string[] = [];\n private totalChars = 0;\n private readonly maxChars: number;\n private readonly separator: string;\n\n /**\n * @param maxChars Maximum length of the joined tail. Defaults to {@link MAX_TAIL_CHARS}.\n * @param separator String placed between items by {@link toString}. Must match\n * how the caller would otherwise have joined the accumulated chunks (e.g.\n * `\"\\n\"` for line streams, `\"\"` for raw chunk streams).\n */\n constructor(maxChars: number = MAX_TAIL_CHARS, separator = \"\") {\n this.maxChars = maxChars;\n this.separator = separator;\n }\n\n /** Append one item to the tail, evicting oldest items to stay within budget. */\n push(item: string): void {\n const bounded =\n item.length > this.maxChars\n ? item.slice(item.length - this.maxChars)\n : item;\n this.totalChars +=\n bounded.length + (this.items.length > 0 ? this.separator.length : 0);\n this.items.push(bounded);\n while (this.totalChars > this.maxChars && this.items.length > 1) {\n const dropped = this.items.shift();\n if (dropped === undefined) {\n break;\n }\n this.totalChars -= dropped.length + this.separator.length;\n }\n }\n\n /** Join the retained tail into a single string (length ≤ `maxChars`). */\n toString(): string {\n return this.items.join(this.separator);\n }\n}\n"]}
@@ -0,0 +1,353 @@
1
+ import { createRequire } from 'node:module';
2
+ import { MAX_TAIL_CHARS, BoundedTail } from './chunk-6NQPCXSG.js';
3
+ import { spawn } from 'child_process';
4
+ import { createInterface } from 'readline';
5
+ import { stat } from 'fs/promises';
6
+ import { win32 } from 'path';
7
+
8
+ createRequire(import.meta.url);
9
+
10
+ // src/sandboxes/posixSimpleCommand.ts
11
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
12
+ var UNQUOTED_SPECIAL = "|&<>()$`*?[]{}~#!%^\n\r";
13
+ var SEPARATORS = " ;";
14
+ var DOUBLE_QUOTE_ESCAPABLE = '"\\$`';
15
+ var readSingleQuoted = (s, start) => {
16
+ const end = s.indexOf("'", start + 1);
17
+ return end === -1 ? void 0 : { text: s.slice(start + 1, end), next: end + 1 };
18
+ };
19
+ var readDoubleQuoted = (s, start) => {
20
+ let text = "";
21
+ let i = start + 1;
22
+ while (i < s.length) {
23
+ const c = s.charAt(i);
24
+ const next = s.charAt(i + 1);
25
+ if (c === '"') {
26
+ return { text, next: i + 1 };
27
+ }
28
+ if (c === "$" || c === "`" || c === "\\" && next === "\n") {
29
+ return void 0;
30
+ }
31
+ if (c === "\\" && next !== "" && DOUBLE_QUOTE_ESCAPABLE.includes(next)) {
32
+ text += next;
33
+ i += 2;
34
+ } else {
35
+ text += c;
36
+ i += 1;
37
+ }
38
+ }
39
+ return void 0;
40
+ };
41
+ var readBare = (s, start) => {
42
+ let i = start;
43
+ while (i < s.length && !SEPARATORS.includes(s.charAt(i)) && !UNQUOTED_SPECIAL.includes(s.charAt(i)) && !`'"\\`.includes(s.charAt(i))) {
44
+ i += 1;
45
+ }
46
+ return { text: s.slice(start, i), next: i };
47
+ };
48
+ var readPiece = (s, start) => {
49
+ const c = s.charAt(start);
50
+ if (c === "'") {
51
+ return readSingleQuoted(s, start);
52
+ }
53
+ if (c === '"') {
54
+ return readDoubleQuoted(s, start);
55
+ }
56
+ if (c === "\\") {
57
+ return s.charAt(start + 1) === "'" ? { text: "'", next: start + 2 } : void 0;
58
+ }
59
+ if (UNQUOTED_SPECIAL.includes(c)) {
60
+ return void 0;
61
+ }
62
+ return readBare(s, start);
63
+ };
64
+ var splitStatements = (s) => {
65
+ const statements = [[]];
66
+ let word;
67
+ const endWord = () => {
68
+ if (word !== void 0) {
69
+ statements.at(-1)?.push(word);
70
+ }
71
+ word = void 0;
72
+ };
73
+ let i = 0;
74
+ while (i < s.length) {
75
+ const c = s.charAt(i);
76
+ const piece = SEPARATORS.includes(c) ? void 0 : readPiece(s, i);
77
+ if (piece !== void 0) {
78
+ word = (word ?? "") + piece.text;
79
+ i = piece.next;
80
+ } else if (SEPARATORS.includes(c)) {
81
+ endWord();
82
+ if (c === ";") {
83
+ statements.push([]);
84
+ }
85
+ i += 1;
86
+ } else {
87
+ return void 0;
88
+ }
89
+ }
90
+ endWord();
91
+ return statements;
92
+ };
93
+ var exportedEnv = (statement) => {
94
+ const [keyword, ...assignments] = statement;
95
+ if (keyword !== "export" || assignments.length === 0) {
96
+ return void 0;
97
+ }
98
+ const env = {};
99
+ for (const assignment of assignments) {
100
+ const eq = assignment.indexOf("=");
101
+ const name = assignment.slice(0, eq);
102
+ if (eq === -1 || !ENV_NAME.test(name)) {
103
+ return void 0;
104
+ }
105
+ env[name] = assignment.slice(eq + 1);
106
+ }
107
+ return env;
108
+ };
109
+ var parseSimpleCommand = (command) => {
110
+ const statements = splitStatements(command);
111
+ const argv = statements?.pop();
112
+ const [program] = argv ?? [];
113
+ if (statements === void 0 || argv === void 0 || program === void 0 || program === "" || program.includes("=")) {
114
+ return void 0;
115
+ }
116
+ const env = {};
117
+ for (const statement of statements) {
118
+ const exported = exportedEnv(statement);
119
+ if (exported === void 0) {
120
+ return void 0;
121
+ }
122
+ Object.assign(env, exported);
123
+ }
124
+ return { env, argv };
125
+ };
126
+
127
+ // src/sandboxes/windowsCommand.ts
128
+ var getEnv = (env, name) => {
129
+ const key = Object.keys(env).filter((k) => k.toUpperCase() === name).reduce(
130
+ (first, k) => first === void 0 || k < first ? k : first,
131
+ void 0
132
+ );
133
+ return key === void 0 ? void 0 : env[key];
134
+ };
135
+ var isFile = async (path) => {
136
+ try {
137
+ const stats = await stat(path);
138
+ return stats.isFile();
139
+ } catch {
140
+ return false;
141
+ }
142
+ };
143
+ var candidatePaths = (program, env, cwd) => {
144
+ const pathExt = (getEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((ext) => ext !== "").map((ext) => ext.toLowerCase());
145
+ const hasExt = pathExt.includes(win32.extname(program).toLowerCase());
146
+ const withExts = (base) => hasExt ? [base] : pathExt.map((ext) => `${base}${ext}`);
147
+ if (/[\\/]/u.test(program) || win32.isAbsolute(program)) {
148
+ return withExts(win32.resolve(cwd, program));
149
+ }
150
+ return (getEnv(env, "PATH") ?? "").split(";").map((dir) => dir.replaceAll('"', "").trim()).filter((dir) => dir !== "").flatMap((dir) => withExts(win32.join(dir, program)));
151
+ };
152
+ var resolveWindowsProgram = async (program, env, cwd) => {
153
+ const candidates = candidatePaths(program, env, cwd);
154
+ const found = await Promise.all(candidates.map(async (p) => isFile(p)));
155
+ return candidates[found.indexOf(true)];
156
+ };
157
+ var CMD_META = /(?<meta>[()\][%!^"`<>&|;, *?])/gu;
158
+ var CMD_MAX_COMMAND_LINE = 8191;
159
+ var escapeCmdMeta = (s) => s.replaceAll(CMD_META, "^$<meta>");
160
+ var escapeBatchArgument = (arg) => {
161
+ const quoted = arg.replaceAll(/(?<bs>\\*)"/gu, String.raw`$<bs>$<bs>\"`).replace(/(?<bs>\\*)$/u, "$<bs>$<bs>");
162
+ return escapeCmdMeta(escapeCmdMeta(`"${quoted}"`));
163
+ };
164
+ var planBatch = (program, file, { args, comspec }) => {
165
+ const name = win32.basename(file);
166
+ if (args.some((arg) => /[\r\n]/u.test(arg))) {
167
+ throw new Error(
168
+ `${program} is a batch file (${name}), which runs under cmd.exe, and cmd.exe cannot pass an argument containing a newline. Pass that text on stdin instead.`
169
+ );
170
+ }
171
+ const commandLine = [
172
+ escapeCmdMeta(file),
173
+ ...args.map((arg) => escapeBatchArgument(arg))
174
+ ].join(" ");
175
+ if (commandLine.length > CMD_MAX_COMMAND_LINE) {
176
+ throw new Error(
177
+ `The command line for ${program} (${name}) is too long for cmd.exe: ${commandLine.length} characters once escaped, over the ${CMD_MAX_COMMAND_LINE}-character limit. Pass long text on stdin instead.`
178
+ );
179
+ }
180
+ return {
181
+ file: comspec,
182
+ args: ["/d", "/s", "/c", `"${commandLine}"`],
183
+ windowsVerbatimArguments: true
184
+ };
185
+ };
186
+ var planWindowsSpawn = async (argv, env, cwd) => {
187
+ const [program, ...args] = argv;
188
+ if (program === void 0) {
189
+ return void 0;
190
+ }
191
+ const file = await resolveWindowsProgram(program, env, cwd);
192
+ if (file === void 0) {
193
+ return void 0;
194
+ }
195
+ const ext = win32.extname(file).toLowerCase();
196
+ if (ext === ".cmd" || ext === ".bat") {
197
+ return planBatch(program, file, {
198
+ args,
199
+ comspec: getEnv(env, "COMSPEC") ?? "cmd.exe"
200
+ });
201
+ }
202
+ return { file, args, windowsVerbatimArguments: false };
203
+ };
204
+ var planWindowsExec = async (command, env, cwd) => {
205
+ const simple = parseSimpleCommand(command);
206
+ if (simple !== void 0) {
207
+ const commandEnv = { ...env, ...simple.env };
208
+ const plan = await planWindowsSpawn(simple.argv, commandEnv, cwd);
209
+ if (plan !== void 0) {
210
+ return { ...plan, env: commandEnv };
211
+ }
212
+ }
213
+ return {
214
+ file: "cmd.exe",
215
+ args: ["/d", "/s", "/c", command],
216
+ windowsVerbatimArguments: true,
217
+ env
218
+ };
219
+ };
220
+
221
+ // src/sandboxes/no-sandbox.ts
222
+ var planExec = async (command, env, cwd) => (
223
+ // Windows has no `sh`, and cmd.exe doesn't understand the POSIX
224
+ // quoting in Sandcastle's commands (#940): run simple commands as a
225
+ // direct spawn of their argv, and only the rest through cmd.exe.
226
+ process.platform === "win32" ? planWindowsExec(command, env, cwd) : {
227
+ file: "sh",
228
+ args: ["-c", command],
229
+ windowsVerbatimArguments: false,
230
+ env
231
+ }
232
+ );
233
+ var spawnExec = (plan, cwd, stdin) => {
234
+ const spawnOptions = {
235
+ cwd,
236
+ env: plan.env,
237
+ windowsVerbatimArguments: plan.windowsVerbatimArguments
238
+ };
239
+ if (stdin === void 0) {
240
+ return spawn(plan.file, plan.args, {
241
+ ...spawnOptions,
242
+ stdio: ["ignore", "pipe", "pipe"]
243
+ });
244
+ }
245
+ const proc = spawn(plan.file, plan.args, {
246
+ ...spawnOptions,
247
+ stdio: ["pipe", "pipe", "pipe"]
248
+ });
249
+ proc.stdin.write(stdin);
250
+ proc.stdin.end();
251
+ return proc;
252
+ };
253
+ var streamLines = (onLine, maxTailChars) => (proc) => {
254
+ const stdoutTail = new BoundedTail(maxTailChars, "\n");
255
+ const stderrTail = new BoundedTail(maxTailChars, "");
256
+ const rl = createInterface({ input: proc.stdout });
257
+ rl.on("line", (line) => {
258
+ stdoutTail.push(line);
259
+ onLine(line);
260
+ });
261
+ proc.stderr.on("data", (chunk) => {
262
+ stderrTail.push(chunk.toString());
263
+ });
264
+ return () => ({
265
+ stdout: stdoutTail.toString(),
266
+ stderr: stderrTail.toString()
267
+ });
268
+ };
269
+ var bufferAll = (proc) => {
270
+ const stdoutChunks = [];
271
+ const stderrChunks = [];
272
+ proc.stdout.on("data", (chunk) => {
273
+ stdoutChunks.push(chunk.toString());
274
+ });
275
+ proc.stderr.on("data", (chunk) => {
276
+ stderrChunks.push(chunk.toString());
277
+ });
278
+ return () => ({
279
+ stdout: stdoutChunks.join(""),
280
+ stderr: stderrChunks.join("")
281
+ });
282
+ };
283
+ var waitForExec = async (proc, collect) => new Promise((resolve, reject) => {
284
+ proc.on("error", (error) => {
285
+ reject(new Error(`exec failed: ${error.message}`));
286
+ });
287
+ const output = collect(proc);
288
+ proc.on("close", (code) => {
289
+ resolve({ ...output(), exitCode: code ?? 0 });
290
+ });
291
+ });
292
+ var runExec = async (command, opts, context) => {
293
+ const cwd = opts?.cwd ?? context.worktreePath;
294
+ const plan = await planExec(command, context.processEnv, cwd);
295
+ const proc = spawnExec(plan, cwd, opts?.stdin);
296
+ const collect = opts?.onLine ? streamLines(opts.onLine, context.maxOutputTailChars) : bufferAll;
297
+ return waitForExec(proc, collect);
298
+ };
299
+ var runInteractiveExec = async (args, opts, context) => {
300
+ const { processEnv } = context;
301
+ const cwd = opts.cwd ?? context.worktreePath;
302
+ const stdio = [opts.stdin, opts.stdout, opts.stderr];
303
+ const plan = process.platform === "win32" ? await planWindowsSpawn(args, processEnv, cwd) : void 0;
304
+ return new Promise((resolve, reject) => {
305
+ const [cmd, ...rest] = args;
306
+ if (cmd === void 0) {
307
+ reject(new Error("interactiveExec needs a command to run"));
308
+ return;
309
+ }
310
+ const proc = plan ? spawn(plan.file, plan.args, {
311
+ cwd,
312
+ env: processEnv,
313
+ stdio,
314
+ windowsVerbatimArguments: plan.windowsVerbatimArguments
315
+ }) : spawn(cmd, rest, {
316
+ cwd,
317
+ env: processEnv,
318
+ stdio,
319
+ shell: process.platform === "win32"
320
+ });
321
+ proc.on("error", (error) => {
322
+ reject(new Error(`exec failed: ${error.message}`));
323
+ });
324
+ proc.on("close", (code) => {
325
+ resolve({ exitCode: code ?? 0 });
326
+ });
327
+ });
328
+ };
329
+ var noSandbox = (options) => ({
330
+ tag: "none",
331
+ name: "no-sandbox",
332
+ env: options?.env ?? {},
333
+ create: async (createOptions) => {
334
+ const { worktreePath } = createOptions;
335
+ const context = {
336
+ worktreePath,
337
+ processEnv: { ...process.env, ...createOptions.env },
338
+ maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS
339
+ };
340
+ const handle = {
341
+ worktreePath,
342
+ exec: async (command, opts) => runExec(command, opts, context),
343
+ interactiveExec: async (args, opts) => runInteractiveExec(args, opts, context),
344
+ close: async () => {
345
+ }
346
+ };
347
+ return handle;
348
+ }
349
+ });
350
+
351
+ export { noSandbox };
352
+ //# sourceMappingURL=chunk-7N7AMUYA.js.map
353
+ //# sourceMappingURL=chunk-7N7AMUYA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandboxes/posixSimpleCommand.ts","../src/sandboxes/windowsCommand.ts","../src/sandboxes/no-sandbox.ts"],"names":[],"mappings":";;;;;;;;;;AAaA,IAAM,QAAA,GAAW,2BAAA;AAOjB,IAAM,gBAAA,GAAmB,yBAAA;AAGzB,IAAM,UAAA,GAAa,KAAA;AAGnB,IAAM,sBAAA,GAAyB,OAAA;AAQ/B,IAAM,gBAAA,GAAmB,CAAC,CAAA,EAAW,KAAA,KAAqC;AACxE,EAAA,MAA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AS,GAAA,IAAO,EAAC;AAAA,EACtB,MAAA,EAAQ,OAAO,aAAA,KAA4C;AACzD,IAAA,MAAM,EAAE,cAAa,GAAI,aAAA;AACzB,IAAA,MAAM,OAAA,GAAuB;AAAA,MAC3B,YAAA;AAAA,MACA,YAAY,EAAE,GAAG,QAAQ,GAAA,EAAK,GAAG,cAAc,GAAA,EAAI;AAAA,MACnD,kBAAA,EAAoB,SAAS,kBAAA,IAAsB;AAAA,KACrD;AAEA,IAAA,MAAM,MAAA,GAA0B;AAAA,MAC9B,YAAA;AAAA,MACA,MAAM,OAAO,OAAA,EAAiB,SAC5B,OAAA,CAAQ,OAAA,EAAS,MAAM,OAAO,CAAA;AAAA,MAChC,iBAAiB,OACf,IAAA,EACA,SAEA,kBAAA,CAAmB,IAAA,EAAM,MAAM,OAAO,CAAA;AAAA,MACxC,OAAO,YAA2B;AAAA,MAElC;AAAA,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA","file":"chunk-7N7AMUYA.js","sourcesContent":["/**\n * @internal Splits a POSIX shell command back into the argv it stands for,\n * when it is a simple command. noSandbox uses it on Windows (issue #940),\n * where there is no `sh` to do this, so the program can be spawned directly\n * instead of handing POSIX quoting to cmd.exe. See `windowsCommand.ts`.\n */\n\n/** A POSIX simple command: leading `export NAME=value;` statements, then argv. */\nexport interface SimpleCommand {\n readonly env: Record<string, string>;\n readonly argv: readonly string[];\n}\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;\n\n/**\n * Characters that make an unquoted word mean something to a POSIX shell\n * (operators, expansions, globs) or look like cmd.exe syntax (`%`, `^`).\n * A command containing one is not simple, and keeps the old cmd.exe path.\n */\nconst UNQUOTED_SPECIAL = \"|&<>()$`*?[]{}~#!%^\\n\\r\";\n\n/** Ends the current word without being part of one. */\nconst SEPARATORS = \" \\t;\";\n\n/** Characters a backslash escapes inside POSIX double quotes. */\nconst DOUBLE_QUOTE_ESCAPABLE = '\"\\\\$`';\n\n/** A run of characters read from the command, and where reading stops. */\ninterface Piece {\n readonly text: string;\n readonly next: number;\n}\n\nconst readSingleQuoted = (s: string, start: number): Piece | undefined => {\n const end = s.indexOf(\"'\", start + 1);\n return end === -1\n ? undefined\n : { text: s.slice(start + 1, end), next: end + 1 };\n};\n\nconst readDoubleQuoted = (s: string, start: number): Piece | undefined => {\n let text = \"\";\n let i = start + 1;\n while (i < s.length) {\n const c = s.charAt(i);\n const next = s.charAt(i + 1);\n if (c === '\"') {\n return { text, next: i + 1 };\n }\n if (c === \"$\" || c === \"`\" || (c === \"\\\\\" && next === \"\\n\")) {\n return undefined;\n }\n if (c === \"\\\\\" && next !== \"\" && DOUBLE_QUOTE_ESCAPABLE.includes(next)) {\n text += next;\n i += 2;\n } else {\n text += c;\n i += 1;\n }\n }\n return undefined;\n};\n\nconst readBare = (s: string, start: number): Piece => {\n let i = start;\n while (\n i < s.length &&\n !SEPARATORS.includes(s.charAt(i)) &&\n !UNQUOTED_SPECIAL.includes(s.charAt(i)) &&\n !\"'\\\"\\\\\".includes(s.charAt(i))\n ) {\n i += 1;\n }\n return { text: s.slice(start, i), next: i };\n};\n\n/** Read the next piece of a word, or undefined if the command isn't simple. */\nconst readPiece = (s: string, start: number): Piece | undefined => {\n const c = s.charAt(start);\n if (c === \"'\") {\n return readSingleQuoted(s, start);\n }\n if (c === '\"') {\n return readDoubleQuoted(s, start);\n }\n if (c === \"\\\\\") {\n // Only the `\\'` that shellEscape emits. Any other bare backslash is more\n // likely a Windows path than a POSIX escape: leave it to cmd.exe.\n return s.charAt(start + 1) === \"'\"\n ? { text: \"'\", next: start + 2 }\n : undefined;\n }\n if (UNQUOTED_SPECIAL.includes(c)) {\n return undefined;\n }\n return readBare(s, start);\n};\n\n/** Split into statements (on `;`), each a list of words. */\nconst splitStatements = (s: string): string[][] | undefined => {\n const statements: string[][] = [[]];\n let word: string | undefined;\n const endWord = () => {\n if (word !== undefined) {\n statements.at(-1)?.push(word);\n }\n word = undefined;\n };\n let i = 0;\n while (i < s.length) {\n const c = s.charAt(i);\n const piece = SEPARATORS.includes(c) ? undefined : readPiece(s, i);\n if (piece !== undefined) {\n word = (word ?? \"\") + piece.text;\n i = piece.next;\n } else if (SEPARATORS.includes(c)) {\n endWord();\n if (c === \";\") {\n statements.push([]);\n }\n i += 1;\n } else {\n return undefined;\n }\n }\n endWord();\n return statements;\n};\n\n/** The env an `export NAME=value …` statement sets, or undefined. */\nconst exportedEnv = (\n statement: readonly string[],\n): Record<string, string> | undefined => {\n const [keyword, ...assignments] = statement;\n if (keyword !== \"export\" || assignments.length === 0) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const assignment of assignments) {\n const eq = assignment.indexOf(\"=\");\n const name = assignment.slice(0, eq);\n if (eq === -1 || !ENV_NAME.test(name)) {\n return undefined;\n }\n env[name] = assignment.slice(eq + 1);\n }\n return env;\n};\n\n/**\n * Split a POSIX shell command into argv, when it is a simple command.\n *\n * Understands exactly what Sandcastle produces: bare words, `'single'`\n * quotes, `\"double\"` quotes with POSIX backslash escapes, the `\\'` that\n * `shellEscape` emits between quoted runs, and leading `export NAME=value;`\n * statements (the agent env prefix from `createSandbox`). Returns undefined\n * for anything else.\n */\nexport const parseSimpleCommand = (\n command: string,\n): SimpleCommand | undefined => {\n const statements = splitStatements(command);\n const argv = statements?.pop();\n const [program] = argv ?? [];\n if (\n statements === undefined ||\n argv === undefined ||\n program === undefined ||\n program === \"\" ||\n program.includes(\"=\")\n ) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const statement of statements) {\n const exported = exportedEnv(statement);\n if (exported === undefined) {\n return undefined;\n }\n Object.assign(env, exported);\n }\n return { env, argv };\n};\n","/**\n * @internal How noSandbox runs a command on Windows (issue #940).\n *\n * Sandcastle builds every exec command as a POSIX shell string (agent print\n * commands quote their values with `shellEscape`), because docker, podman,\n * vercel and daytona all run it with `sh -c`. Windows has no `sh`, and cmd.exe\n * does not understand POSIX quoting, so handing that string to cmd.exe\n * delivers `'claude-fable-5'`, quotes and all.\n *\n * Instead of re-quoting the string for cmd.exe, noSandbox splits it back into\n * the argv it stands for and launches the program directly:\n *\n * - an `.exe` gets the argv array with no shell at all; Node's own argv\n * quoting handles spaces, quotes, `%`, `^`, `&`, `|` and newlines;\n * - a `.cmd`/`.bat` (how npm installs agent CLIs on Windows) can only run\n * under cmd.exe, so its command line is escaped with the standard rules\n * for a batch file that forwards `%*` (as cross-spawn does);\n * - anything that is not a simple command (pipes, redirects, `$VAR`, cmd.exe\n * builtins, Windows-style `%VAR%`) goes to cmd.exe unchanged, as before.\n */\nimport { stat } from \"node:fs/promises\";\nimport { win32 } from \"node:path\";\nimport { parseSimpleCommand } from \"./posixSimpleCommand.js\";\n\n/** How to spawn a command: `file` with `args`, no shell. */\nexport interface SpawnPlan {\n readonly file: string;\n readonly args: readonly string[];\n readonly windowsVerbatimArguments: boolean;\n}\n\ntype Env = Record<string, string | undefined>;\n\n/**\n * Read an env var the way Windows does: names are case-insensitive, and when\n * an env object holds two spellings (`Path` and `PATH`), Node's spawn uses\n * the lexicographically first, so this does too.\n */\nconst getEnv = (env: Env, name: string): string | undefined => {\n const key = Object.keys(env)\n .filter((k) => k.toUpperCase() === name)\n .reduce<string | undefined>(\n (first, k) => (first === undefined || k < first ? k : first),\n undefined,\n );\n return key === undefined ? undefined : env[key];\n};\n\nconst isFile = async (path: string): Promise<boolean> => {\n try {\n const stats = await stat(path);\n return stats.isFile();\n } catch {\n return false;\n }\n};\n\n/** The paths Windows would try for `program`, in order. */\nconst candidatePaths = (program: string, env: Env, cwd: string): string[] => {\n const pathExt = (getEnv(env, \"PATHEXT\") ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .filter((ext) => ext !== \"\")\n .map((ext) => ext.toLowerCase());\n const hasExt = pathExt.includes(win32.extname(program).toLowerCase());\n const withExts = (base: string) =>\n hasExt ? [base] : pathExt.map((ext) => `${base}${ext}`);\n\n if (/[\\\\/]/u.test(program) || win32.isAbsolute(program)) {\n return withExts(win32.resolve(cwd, program));\n }\n return (getEnv(env, \"PATH\") ?? \"\")\n .split(\";\")\n .map((dir) => dir.replaceAll('\"', \"\").trim())\n .filter((dir) => dir !== \"\")\n .flatMap((dir) => withExts(win32.join(dir, program)));\n};\n\n/**\n * Find the file Windows would run for `program`: an explicit path (relative\n * to `cwd`), or the first PATH directory holding `program` with a PATHEXT\n * extension. Returns undefined when nothing matches (cmd.exe builtins such\n * as `echo`, or a program that isn't installed).\n */\nexport const resolveWindowsProgram = async (\n program: string,\n env: Env,\n cwd: string,\n): Promise<string | undefined> => {\n const candidates = candidatePaths(program, env, cwd);\n const found = await Promise.all(candidates.map(async (p) => isFile(p)));\n return candidates[found.indexOf(true)];\n};\n\n/** cmd.exe metacharacters, escaped with `^` (the set cross-spawn uses). */\nconst CMD_META = /(?<meta>[()\\][%!^\"`<>&|;, *?])/gu;\n\n/** The longest command line cmd.exe accepts. */\nexport const CMD_MAX_COMMAND_LINE = 8191;\n\nconst escapeCmdMeta = (s: string): string => s.replaceAll(CMD_META, \"^$<meta>\");\n\n/**\n * Quote one argument for a batch file run through `cmd.exe /d /s /c`.\n *\n * First quote it for the program the batch file ends up launching (the\n * Windows argv rules: backslashes double only before a quote or the end),\n * then `^`-escape every cmd.exe metacharacter twice: once for cmd.exe\n * reading the `/c` line, and once for the batch file's own `%*` line, which\n * cmd.exe parses again.\n */\nconst escapeBatchArgument = (arg: string): string => {\n const quoted = arg\n .replaceAll(/(?<bs>\\\\*)\"/gu, String.raw`$<bs>$<bs>\\\"`)\n .replace(/(?<bs>\\\\*)$/u, \"$<bs>$<bs>\");\n return escapeCmdMeta(escapeCmdMeta(`\"${quoted}\"`));\n};\n\n/** Plan a batch file run under cmd.exe, refusing what cmd.exe can't carry. */\nconst planBatch = (\n program: string,\n file: string,\n { args, comspec }: { args: readonly string[]; comspec: string },\n): SpawnPlan => {\n const name = win32.basename(file);\n if (args.some((arg) => /[\\r\\n]/u.test(arg))) {\n throw new Error(\n `${program} is a batch file (${name}), which runs under cmd.exe, and cmd.exe cannot pass an argument containing a newline. Pass that text on stdin instead.`,\n );\n }\n const commandLine = [\n escapeCmdMeta(file),\n ...args.map((arg) => escapeBatchArgument(arg)),\n ].join(\" \");\n if (commandLine.length > CMD_MAX_COMMAND_LINE) {\n throw new Error(\n `The command line for ${program} (${name}) is too long for cmd.exe: ${commandLine.length} characters once escaped, over the ${CMD_MAX_COMMAND_LINE}-character limit. Pass long text on stdin instead.`,\n );\n }\n return {\n file: comspec,\n args: [\"/d\", \"/s\", \"/c\", `\"${commandLine}\"`],\n windowsVerbatimArguments: true,\n };\n};\n\n/**\n * Plan how to spawn `argv` on Windows without re-quoting it by hand where\n * that can be avoided. Resolves undefined when the program can't be found\n * on PATH, so the caller keeps its old cmd.exe behaviour.\n *\n * Rejects when a batch file would be handed an argument cmd.exe cannot carry\n * (a newline, or a command line over 8191 characters), rather than letting\n * cmd.exe silently cut the command short.\n */\nexport const planWindowsSpawn = async (\n argv: readonly string[],\n env: Env,\n cwd: string,\n): Promise<SpawnPlan | undefined> => {\n const [program, ...args] = argv;\n if (program === undefined) {\n return undefined;\n }\n const file = await resolveWindowsProgram(program, env, cwd);\n if (file === undefined) {\n return undefined;\n }\n const ext = win32.extname(file).toLowerCase();\n if (ext === \".cmd\" || ext === \".bat\") {\n return planBatch(program, file, {\n args,\n comspec: getEnv(env, \"COMSPEC\") ?? \"cmd.exe\",\n });\n }\n return { file, args, windowsVerbatimArguments: false };\n};\n\n/**\n * Plan how noSandbox's `exec` runs a command string on Windows: as a direct\n * spawn when it is a simple command whose program is on PATH, otherwise\n * through `cmd.exe /d /s /c` unchanged (the behaviour before #940).\n */\nexport const planWindowsExec = async (\n command: string,\n env: Env,\n cwd: string,\n): Promise<SpawnPlan & { readonly env: Env }> => {\n const simple = parseSimpleCommand(command);\n if (simple !== undefined) {\n const commandEnv = { ...env, ...simple.env };\n const plan = await planWindowsSpawn(simple.argv, commandEnv, cwd);\n if (plan !== undefined) {\n return { ...plan, env: commandEnv };\n }\n }\n return {\n file: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", command],\n windowsVerbatimArguments: true,\n env,\n };\n};\n","/**\n * No-sandbox provider — runs the agent directly on the host with no container isolation.\n *\n * Usage:\n * import { noSandbox } from \"sandcastle/sandboxes/no-sandbox\";\n * await interactive({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: noSandbox() });\n *\n * Accepted by `run()`, `interactive()`, and `createSandbox()`. Skips\n * container isolation entirely — the agent executes on the host. Does not\n * pass `--dangerously-skip-permissions` to the agent — the user manages\n * permissions themselves.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcessByStdio, StdioOptions } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport type {\n NoSandboxProvider,\n NoSandboxHandle,\n ExecResult,\n InteractiveExecOptions,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { planWindowsExec, planWindowsSpawn } from \"./windowsCommand.js\";\nimport type { SpawnPlan } from \"./windowsCommand.js\";\n\nexport interface NoSandboxOptions {\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\ntype ProcessEnv = Record<string, string | undefined>;\n\n/** A spawn plan for `exec`, with the env the command runs under. */\ntype ExecPlan = SpawnPlan & { readonly env: ProcessEnv };\n\ninterface ExecOptions {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n}\n\n/** What a handle's `exec` and `interactiveExec` share. */\ninterface HostContext {\n readonly worktreePath: string;\n readonly processEnv: ProcessEnv;\n readonly maxOutputTailChars: number;\n}\n\n/** A spawned `exec` process: stdout and stderr are always piped. */\ntype ExecProcess = ChildProcessByStdio<Writable | null, Readable, Readable>;\n\n/** Attaches output listeners; call the result on close for the output. */\ntype OutputCollector = (proc: ExecProcess) => () => {\n stdout: string;\n stderr: string;\n};\n\nconst planExec = async (\n command: string,\n env: ProcessEnv,\n cwd: string,\n): Promise<ExecPlan> =>\n // Windows has no `sh`, and cmd.exe doesn't understand the POSIX\n // quoting in Sandcastle's commands (#940): run simple commands as a\n // direct spawn of their argv, and only the rest through cmd.exe.\n process.platform === \"win32\"\n ? planWindowsExec(command, env, cwd)\n : {\n file: \"sh\",\n args: [\"-c\", command],\n windowsVerbatimArguments: false,\n env,\n };\n\nconst spawnExec = (\n plan: ExecPlan,\n cwd: string,\n stdin: string | undefined,\n): ExecProcess => {\n const spawnOptions = {\n cwd,\n env: plan.env,\n windowsVerbatimArguments: plan.windowsVerbatimArguments,\n };\n // Two literal `stdio` tuples, so the types know stdout and stderr\n // are always piped.\n if (stdin === undefined) {\n return spawn(plan.file, plan.args, {\n ...spawnOptions,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n }\n const proc = spawn(plan.file, plan.args, {\n ...spawnOptions,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n proc.stdin.write(stdin);\n proc.stdin.end();\n return proc;\n};\n\n/** Streams stdout to `onLine` line by line, keeping only a bounded tail. */\nconst streamLines =\n (onLine: (line: string) => void, maxTailChars: number): OutputCollector =>\n (proc) => {\n const stdoutTail = new BoundedTail(maxTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxTailChars, \"\");\n const rl = createInterface({ input: proc.stdout });\n rl.on(\"line\", (line) => {\n stdoutTail.push(line);\n onLine(line);\n });\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderrTail.push(chunk.toString());\n });\n return () => ({\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n });\n };\n\n/** Buffers all of stdout and stderr. */\nconst bufferAll: OutputCollector = (proc) => {\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n proc.stdout.on(\"data\", (chunk: Buffer) => {\n stdoutChunks.push(chunk.toString());\n });\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk.toString());\n });\n return () => ({\n stdout: stdoutChunks.join(\"\"),\n stderr: stderrChunks.join(\"\"),\n });\n};\n\nconst waitForExec = async (\n proc: ExecProcess,\n collect: OutputCollector,\n): Promise<ExecResult> =>\n new Promise((resolve, reject) => {\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`exec failed: ${error.message}`));\n });\n const output = collect(proc);\n proc.on(\"close\", (code: number | null) => {\n resolve({ ...output(), exitCode: code ?? 0 });\n });\n });\n\nconst runExec = async (\n command: string,\n opts: ExecOptions | undefined,\n context: HostContext,\n): Promise<ExecResult> => {\n // sudo is a no-op for no-sandbox — the user is already on the host\n const cwd = opts?.cwd ?? context.worktreePath;\n const plan = await planExec(command, context.processEnv, cwd);\n const proc = spawnExec(plan, cwd, opts?.stdin);\n const collect = opts?.onLine\n ? streamLines(opts.onLine, context.maxOutputTailChars)\n : bufferAll;\n return waitForExec(proc, collect);\n};\n\nconst runInteractiveExec = async (\n args: string[],\n opts: InteractiveExecOptions,\n context: HostContext,\n): Promise<{ exitCode: number }> => {\n const { processEnv } = context;\n const cwd = opts.cwd ?? context.worktreePath;\n const stdio = [opts.stdin, opts.stdout, opts.stderr] as StdioOptions;\n // On Windows, spawn the resolved program with its argv (escaped for\n // cmd.exe only when it is a `.cmd`/`.bat` npm shim, #940). If it\n // isn't on PATH, fall back to `shell: true` so cmd.exe can try.\n const plan =\n process.platform === \"win32\"\n ? await planWindowsSpawn(args, processEnv, cwd)\n : undefined;\n return new Promise((resolve, reject) => {\n const [cmd, ...rest] = args;\n if (cmd === undefined) {\n reject(new Error(\"interactiveExec needs a command to run\"));\n return;\n }\n const proc = plan\n ? spawn(plan.file, plan.args, {\n cwd,\n env: processEnv,\n stdio,\n windowsVerbatimArguments: plan.windowsVerbatimArguments,\n })\n : spawn(cmd, rest, {\n cwd,\n env: processEnv,\n stdio,\n shell: process.platform === \"win32\",\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`exec failed: ${error.message}`));\n });\n\n proc.on(\"close\", (code: number | null) => {\n resolve({ exitCode: code ?? 0 });\n });\n });\n};\n\n/**\n * Create a no-sandbox provider.\n *\n * The returned provider runs the agent directly on the host. All three\n * branch strategies are supported (head, merge-to-head, branch),\n * defaulting to head.\n */\nexport const noSandbox = (options?: NoSandboxOptions): NoSandboxProvider => ({\n tag: \"none\",\n name: \"no-sandbox\",\n env: options?.env ?? {},\n create: async (createOptions): Promise<NoSandboxHandle> => {\n const { worktreePath } = createOptions;\n const context: HostContext = {\n worktreePath,\n processEnv: { ...process.env, ...createOptions.env },\n maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,\n };\n\n const handle: NoSandboxHandle = {\n worktreePath,\n exec: async (command: string, opts?: ExecOptions): Promise<ExecResult> =>\n runExec(command, opts, context),\n interactiveExec: async (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> =>\n runInteractiveExec(args, opts, context),\n close: async (): Promise<void> => {\n // No-op — no container to tear down\n },\n };\n\n return handle;\n },\n});\n"]}