@linxin666/dsh-win-bash 0.4.21 → 0.4.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # node scripts/verify-docs.mjs --write <dir>
5
- README.md: f8261135a77cc61dc2c7e52da1d145f7305a7b80
6
- README.zh.md: 2a7b757d799c70be4e9da034d4215412d6097435
5
+ README.md: cb3501d8a1d791e0c8105fd875165001529b082e
6
+ README.zh.md: 3d202f8d2560174b7fe1d98585393fe41356162d
package/README.md CHANGED
@@ -212,6 +212,23 @@ which ARE confined, so a restricted session keeps a route rather than losing one
212
212
 
213
213
  This tool offers no per-call escalation argument.
214
214
 
215
+ ### Remote execution environments (`0.2.3-alpha.4+`)
216
+
217
+ `win_bash` declares `environment: 'bound'`. When a session targets a remote execution
218
+ environment (`exec.environment !== undefined`), the tool does **not** touch the local
219
+ MSYS2 shell: it resolves the session's sandbox policy, converts it via
220
+ `remoteSandboxPolicy`, and forwards the command through the optional `ctx.environments`
221
+ registry as a self-contained `/usr/bin/env bash -c` invocation (foreground or
222
+ `run_in_background` via `ctx.jobs`). Because the Windows MSYS2 restricted-token
223
+ limitation does not apply on remote POSIX hosts, `read-only`, `workspace-write`, and
224
+ `danger-full-access` modes are forwarded to and enforced by the remote daemon
225
+ (fail-closed when the daemon cannot confine the command). Remote calls are ephemeral
226
+ (no persistent shell state across calls, matching `@deepseek-ai/dsh-tool-bash`). Missing
227
+ `ctx.environments` throws `EnvironmentUnavailableError`; remote `win32` targets are
228
+ refused with `REMOTE_SHELL_UNSUPPORTED`; invalid remote `workdir` values throw
229
+ `ToolArgsError`. Local calls (`exec.environment === undefined`) keep the exact
230
+ `danger-full-access`-only persistent MSYS2 contract above.
231
+
215
232
  ## Payload
216
233
 
217
234
  The vendored runtime comes from Git for Windows `v2.56.0.windows.2` (the
package/README.zh.md CHANGED
@@ -180,6 +180,20 @@ shell 工具:受限会话里的 pwsh 会被保留在工具面上(见 `src/pw
180
180
 
181
181
  本工具不提供单次调用提权参数。
182
182
 
183
+ ### 远端执行环境(`0.2.3-alpha.4+`)
184
+
185
+ `win_bash` 声明 `environment: 'bound'`。当调用指向远端执行环境(`exec.environment !== undefined`)
186
+ 时,工具**不会**触碰本地 MSYS2 进程:它会解析调用会话的有效沙箱策略,经
187
+ `remoteSandboxPolicy` 转换后,通过可选的 `ctx.environments` 服务将命令作为自包含的
188
+ `/usr/bin/env bash -c` 调用转发至远端 daemon(同时支持前台与经 `ctx.jobs` 管理的
189
+ `run_in_background` 后台作业)。由于 Windows MSYS2 受限令牌限制不适用于远端 POSIX 主机,
190
+ `read-only`、`workspace-write` 与 `danger-full-access` 三种模式都会透传并由远端 daemon
191
+ 强制执行(远端无法沙箱隔离时 fail-closed 拒绝)。远端调用采用一次性 `bash -c` 语义(不跨调用
192
+ 保持 `cd`/环境变量,与 `@deepseek-ai/dsh-tool-bash` 一致)。未挂载 `ctx.environments` 时抛
193
+ `EnvironmentUnavailableError`;远端 `win32` 目标以 `REMOTE_SHELL_UNSUPPORTED` 拒绝;无效远端
194
+ `workdir` 抛 `ToolArgsError`。本地调用(`exec.environment === undefined`)保持上文仅限
195
+ `danger-full-access` 的私有持久 MSYS2 契约不变。
196
+
183
197
  ## 载荷
184
198
 
185
199
  随包载荷来自 Git for Windows `v2.56.0.windows.2`(官方上游 release),裁剪为
package/lib/index.js CHANGED
@@ -6,8 +6,9 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
8
  import { spawnSync } from "node:child_process";
9
- import { defineTool } from "@deepseek-ai/dsh-tools";
10
- //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
9
+ import { EnvironmentUnavailableError, ToolArgsError, defineTool } from "@deepseek-ai/dsh-tools";
10
+ import { remoteSandboxPolicy } from "@deepseek-ai/dsh-sandbox";
11
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.10.0-alpha.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
11
12
  /** Return true when a value is `null` or `undefined`. */
12
13
  function isNullable(value) {
13
14
  return value === null || value === void 0;
@@ -261,7 +262,7 @@ var Time;
261
262
  Time.template = template;
262
263
  })(Time || (Time = {}));
263
264
  //#endregion
264
- //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.19.0/node_modules/@deepseek-ai/schemastery/lib/index.mjs
265
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.20.0-alpha.3/node_modules/@deepseek-ai/schemastery/lib/index.mjs
265
266
  const kSchema = Symbol.for("schemastery");
266
267
  const kValidationError = Symbol.for("ValidationError");
267
268
  globalThis.__schemastery_index__ ??= 0;
@@ -1723,7 +1724,7 @@ const HOST_PWSH_TOOL = "pwsh";
1723
1724
  /** The one session mode win_bash can actually serve; every other mode refuses. */
1724
1725
  const SERVING_MODE = "danger-full-access";
1725
1726
  /** Every mode the policy service may answer with. */
1726
- const SANDBOX_MODES$1 = /* @__PURE__ */ new Set([
1727
+ const SANDBOX_MODES$2 = /* @__PURE__ */ new Set([
1727
1728
  "read-only",
1728
1729
  "workspace-write",
1729
1730
  "danger-full-access"
@@ -1785,21 +1786,40 @@ function servingVerdict(read, session) {
1785
1786
  if (typeof cwd !== "string" || cwd === "") return "refuses";
1786
1787
  try {
1787
1788
  const mode = read.resolve({ session })?.mode;
1788
- if (!SANDBOX_MODES$1.has(mode)) return "unknown";
1789
+ if (!SANDBOX_MODES$2.has(mode)) return "unknown";
1789
1790
  return mode === "danger-full-access" ? "serves" : "refuses";
1790
1791
  } catch {
1791
1792
  return "unknown";
1792
1793
  }
1793
1794
  }
1794
1795
  /**
1795
- * The tool names one agent scope currently sees.
1796
+ * The tool names one agent scope currently sees (or `denied` directly under a
1797
+ * PTC root where `tools.get('run_code', agent)` hides program bindings from
1798
+ * `getAll()`).
1796
1799
  * @param ctx - the plugin context.
1797
1800
  * @param agent - the scope to read for.
1801
+ * @param denied - the tool names this replacement intends to withdraw.
1798
1802
  * @returns the names, or undefined when no usable projection is readable.
1799
1803
  */
1800
- function visibleNames(ctx, agent) {
1804
+ function visibleNames(ctx, agent, denied) {
1801
1805
  const service = readService(ctx, "tools");
1802
- if (service === null || typeof service !== "object" || typeof service.schemas !== "function") return void 0;
1806
+ if (service === null || typeof service !== "object") return void 0;
1807
+ if (typeof service.get === "function") try {
1808
+ if (service.get("run_code", agent) !== void 0) return [...denied];
1809
+ } catch {}
1810
+ if (typeof service.getAll === "function") try {
1811
+ const entries = service.getAll(agent);
1812
+ if (!Array.isArray(entries)) return void 0;
1813
+ return entries.map((entry) => entry?.name).filter((name) => typeof name === "string" && name !== "");
1814
+ } catch {
1815
+ return;
1816
+ }
1817
+ if (typeof service.get === "function") try {
1818
+ return denied.filter((name) => service.get(name, agent) !== void 0);
1819
+ } catch {
1820
+ return;
1821
+ }
1822
+ if (typeof service.schemas !== "function") return void 0;
1803
1823
  try {
1804
1824
  const schemas = service.schemas(agent);
1805
1825
  if (!Array.isArray(schemas)) return void 0;
@@ -1820,7 +1840,7 @@ function visibleNames(ctx, agent) {
1820
1840
  function installPwshReplacement(ctx, options = {}) {
1821
1841
  if ((options.platform ?? process.platform) !== "win32") return;
1822
1842
  const denied = [...options.denied ?? ["pwsh"]];
1823
- const read = policyReader(ctx, options.policy);
1843
+ const read = () => policyReader(ctx, options.policy);
1824
1844
  /** Agent scope -> the session it owns and the live restriction, if any. */
1825
1845
  const watched = /* @__PURE__ */ new Map();
1826
1846
  let warned = false;
@@ -1832,6 +1852,9 @@ function installPwshReplacement(ctx, options = {}) {
1832
1852
  return;
1833
1853
  }
1834
1854
  ctx.logger?.warn?.(message);
1855
+ try {
1856
+ process.stderr.write(message + "\n");
1857
+ } catch {}
1835
1858
  };
1836
1859
  const warnOnce = (message) => {
1837
1860
  if (warned) return;
@@ -1892,14 +1915,15 @@ function installPwshReplacement(ctx, options = {}) {
1892
1915
  const evaluate = (scope) => {
1893
1916
  if (scope === null || typeof scope !== "object") return;
1894
1917
  const record = watch(scope);
1895
- const verdict = servingVerdict(read, record.session);
1918
+ const verdict = servingVerdict(read(), record.session);
1896
1919
  if (verdict === "unknown") warnOnce("dsh-win-bash: the sandbox policy of a session could not be resolved, so the host pwsh tool stays visible beside win_bash there (win_bash refuses every call in a session whose mode is unknown).");
1897
1920
  if (verdict !== "serves") {
1898
1921
  release(scope);
1899
1922
  return;
1900
1923
  }
1901
1924
  if (record.dispose !== void 0) return;
1902
- const names = denied.filter((name) => (visibleNames(ctx, scope) ?? []).includes(name));
1925
+ const visible = visibleNames(ctx, scope, denied) ?? [];
1926
+ const names = denied.filter((name) => visible.includes(name));
1903
1927
  if (names.length === 0) return;
1904
1928
  const restrict = scope.ctx?.tools?.restrict;
1905
1929
  if (typeof restrict !== "function") {
@@ -1941,12 +1965,18 @@ function installPwshReplacement(ctx, options = {}) {
1941
1965
  ctx.on("tools/change", () => {
1942
1966
  for (const scope of [...watched.keys()]) evaluate(scope);
1943
1967
  });
1968
+ ctx.on("internal/service", (name) => {
1969
+ if (options.policy !== void 0 || name !== "sandboxPolicy") return;
1970
+ for (const scope of [...watched.keys()]) evaluate(scope);
1971
+ });
1944
1972
  ctx.on("internal/dispatch", (_mode, eventName, args) => {
1945
1973
  if (eventName !== "session/event") return;
1946
1974
  if (!Array.isArray(args)) return;
1947
1975
  const [session, event] = args;
1948
1976
  if (event?.type !== "sandbox/mode") return;
1949
- reevaluate(session);
1977
+ queueMicrotask(() => {
1978
+ reevaluate(session);
1979
+ });
1950
1980
  }, { global: true });
1951
1981
  const registry = readService(ctx, "agents");
1952
1982
  if (registry !== void 0 && typeof registry.list === "function") try {
@@ -1961,9 +1991,9 @@ function installPwshReplacement(ctx, options = {}) {
1961
1991
  //#endregion
1962
1992
  //#region src/dsh-home.ts
1963
1993
  /**
1964
- * DSH_HOME resolution shared by the plugin family's Host halves: the
1965
- * environment override wins, the platform home fallback follows. Mirrors
1966
- * what dsh-pet and dsh-liangshen each used to implement locally.
1994
+ * DSH_HOME and DSH_AGENTS_HOME resolution shared by the plugin family's Host
1995
+ * halves: environment overrides win (blank values treated as unset), then the
1996
+ * platform home fallbacks follow — mirroring `@deepseek-ai/dsh-home-paths`.
1967
1997
  */
1968
1998
  /** Expand a leading ~ (or ~user) in a path, platform-style. */
1969
1999
  function expandHome(path, home = homedir()) {
@@ -1972,6 +2002,16 @@ function expandHome(path, home = homedir()) {
1972
2002
  if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
1973
2003
  return path;
1974
2004
  }
2005
+ function resolveUserRoot(envValue, defaultDirName, home) {
2006
+ const isPosix = home.startsWith("/");
2007
+ const j = isPosix ? join$1 : join;
2008
+ const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
2009
+ if (envValue !== void 0 && envValue.trim() !== "") {
2010
+ const expanded = expandHome(envValue.trim(), home);
2011
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
2012
+ }
2013
+ return j(home, defaultDirName);
2014
+ }
1975
2015
  /**
1976
2016
  * Resolve the DSH home directory.
1977
2017
  * @param env - process environment to read DSH_HOME from.
@@ -1979,15 +2019,7 @@ function expandHome(path, home = homedir()) {
1979
2019
  * @returns the absolute DSH home path.
1980
2020
  */
1981
2021
  function resolveDshHome(env = process.env, home = homedir()) {
1982
- const isPosix = home.startsWith("/");
1983
- const j = isPosix ? join$1 : join;
1984
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
1985
- const raw = env.DSH_HOME;
1986
- if (raw !== void 0 && raw.trim() !== "") {
1987
- const expanded = expandHome(raw.trim(), home);
1988
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
1989
- }
1990
- return j(home, ".dsh");
2022
+ return resolveUserRoot(env.DSH_HOME, ".dsh", home);
1991
2023
  }
1992
2024
  /** Wall-clock bound on one icacls query for a security descriptor. */
1993
2025
  const READ_LABEL_TIMEOUT_MS = 5e3;
@@ -2702,6 +2734,366 @@ const BACKGROUND_STDOUT_BYTES = 4 * 1024 * 1024;
2702
2734
  /** In-memory stderr ceiling for one background job. */
2703
2735
  const BACKGROUND_STDERR_BYTES = SHELL_STDERR_CAPTURE_BYTES;
2704
2736
  //#endregion
2737
+ //#region src/environment.ts
2738
+ /** Environment error code emitted when cancellation confirmed every remote process stopped. */
2739
+ const ENVIRONMENT_RUN_STOPPED = "ENVIRONMENT_RUN_STOPPED";
2740
+ /** Environment error code emitted when the connection dropped before the daemon answered. */
2741
+ const ENVIRONMENT_OUTCOME_UNKNOWN = "ENVIRONMENT_OUTCOME_UNKNOWN";
2742
+ /** Exit code used when a remote process ended by signal without a numeric exit code. */
2743
+ const SIGNAL_EXIT_CODE = 128;
2744
+ const SANDBOX_MODES$1 = /* @__PURE__ */ new Set([
2745
+ "read-only",
2746
+ "workspace-write",
2747
+ "danger-full-access"
2748
+ ]);
2749
+ function isRecord(value) {
2750
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2751
+ }
2752
+ function parseStream(value, label) {
2753
+ if (!isRecord(value)) return `${label} must be an object`;
2754
+ if (typeof value.text !== "string") return `${label}.text must be a string`;
2755
+ if (typeof value.truncated !== "boolean") return `${label}.truncated must be a boolean`;
2756
+ return {
2757
+ text: value.text,
2758
+ truncated: value.truncated
2759
+ };
2760
+ }
2761
+ function parseSandbox(value) {
2762
+ if (value === void 0) return void 0;
2763
+ if (!isRecord(value)) return "sandbox must be an object";
2764
+ if (typeof value.mode !== "string" || !SANDBOX_MODES$1.has(value.mode)) return "sandbox.mode is invalid";
2765
+ if (typeof value.denied !== "boolean") return "sandbox.denied must be a boolean";
2766
+ if (value.enforcement !== void 0 && value.enforcement !== "full" && value.enforcement !== "none") return "sandbox.enforcement is invalid";
2767
+ return {
2768
+ mode: value.mode,
2769
+ denied: value.denied,
2770
+ ...value.enforcement === void 0 ? {} : { enforcement: value.enforcement }
2771
+ };
2772
+ }
2773
+ /** Validate a raw structured-cloned reply returned from a remote environment daemon. */
2774
+ const remoteBashOutcomeValidator = { safeParse(value) {
2775
+ if (!isRecord(value) || typeof value.kind !== "string") return {
2776
+ success: false,
2777
+ error: { message: "outcome must be a tagged object" }
2778
+ };
2779
+ if (value.kind === "workdir") {
2780
+ if (typeof value.cwd !== "string") return {
2781
+ success: false,
2782
+ error: { message: "workdir.cwd must be a string" }
2783
+ };
2784
+ return {
2785
+ success: true,
2786
+ data: {
2787
+ kind: "workdir",
2788
+ cwd: value.cwd
2789
+ }
2790
+ };
2791
+ }
2792
+ if (value.kind === "platform") {
2793
+ if (typeof value.platform !== "string") return {
2794
+ success: false,
2795
+ error: { message: "platform.platform must be a string" }
2796
+ };
2797
+ return {
2798
+ success: true,
2799
+ data: {
2800
+ kind: "platform",
2801
+ platform: value.platform
2802
+ }
2803
+ };
2804
+ }
2805
+ if (value.kind === "exited") {
2806
+ if (typeof value.cwd !== "string") return {
2807
+ success: false,
2808
+ error: { message: "exited.cwd must be a string" }
2809
+ };
2810
+ if (value.exitCode !== null && (typeof value.exitCode !== "number" || !Number.isInteger(value.exitCode))) return {
2811
+ success: false,
2812
+ error: { message: "exited.exitCode must be an integer or null" }
2813
+ };
2814
+ if (value.signal !== null && typeof value.signal !== "string") return {
2815
+ success: false,
2816
+ error: { message: "exited.signal must be a string or null" }
2817
+ };
2818
+ const stdout = parseStream(value.stdout, "stdout");
2819
+ if (typeof stdout === "string") return {
2820
+ success: false,
2821
+ error: { message: stdout }
2822
+ };
2823
+ const stderr = parseStream(value.stderr, "stderr");
2824
+ if (typeof stderr === "string") return {
2825
+ success: false,
2826
+ error: { message: stderr }
2827
+ };
2828
+ const sandbox = parseSandbox(value.sandbox);
2829
+ if (typeof sandbox === "string") return {
2830
+ success: false,
2831
+ error: { message: sandbox }
2832
+ };
2833
+ return {
2834
+ success: true,
2835
+ data: {
2836
+ kind: "exited",
2837
+ cwd: value.cwd,
2838
+ exitCode: value.exitCode,
2839
+ signal: value.signal,
2840
+ stdout,
2841
+ stderr,
2842
+ ...sandbox === void 0 ? {} : { sandbox }
2843
+ }
2844
+ };
2845
+ }
2846
+ return {
2847
+ success: false,
2848
+ error: { message: `unknown outcome kind: ${value.kind}` }
2849
+ };
2850
+ } };
2851
+ /**
2852
+ * Daemon-side command function sent via `fn.toString()`.
2853
+ * Must remain strictly self-contained: no module-scope closures or helper imports.
2854
+ */
2855
+ async function remoteEnvironmentBash(request, env) {
2856
+ if (env.platform === "win32") return {
2857
+ kind: "platform",
2858
+ platform: env.platform
2859
+ };
2860
+ const base = request.cwd === void 0 ? env.cwd : request.cwd;
2861
+ const cwd = request.workdir === void 0 || request.workdir === "" ? base : env.path.resolve(base, request.workdir);
2862
+ let directory = false;
2863
+ try {
2864
+ directory = (await env.fs.stat(cwd)).isDirectory();
2865
+ } catch {}
2866
+ if (!directory) return {
2867
+ kind: "workdir",
2868
+ cwd
2869
+ };
2870
+ const maxPerStream = Math.max(0, Math.floor((env.limits.maxMessageBytes - 4096 - 2 * cwd.length) / 4));
2871
+ const stdoutBudget = Math.max(0, Math.min(request.maxStdoutBytes, maxPerStream));
2872
+ const stderrBudget = Math.max(0, Math.min(request.maxStderrBytes, maxPerStream));
2873
+ const tail = (text, discarded, budget) => {
2874
+ const bytes = Buffer.from(text, "utf8");
2875
+ if (bytes.length <= budget) return {
2876
+ text,
2877
+ truncated: discarded
2878
+ };
2879
+ let start = bytes.length - budget;
2880
+ while (start < bytes.length && (bytes[start] & 192) === 128) start += 1;
2881
+ return {
2882
+ text: bytes.subarray(start).toString("utf8"),
2883
+ truncated: true
2884
+ };
2885
+ };
2886
+ const result = await env.exec([
2887
+ "/usr/bin/env",
2888
+ "bash",
2889
+ "-c",
2890
+ request.command
2891
+ ], { cwd });
2892
+ const out = {
2893
+ kind: "exited",
2894
+ cwd,
2895
+ exitCode: result.exitCode,
2896
+ signal: result.signal,
2897
+ stdout: tail(result.stdout, result.stdoutTruncated, stdoutBudget),
2898
+ stderr: tail(result.stderr, result.stderrTruncated, stderrBudget)
2899
+ };
2900
+ if (result.sandbox !== void 0) out.sandbox = result.sandbox;
2901
+ return out;
2902
+ }
2903
+ function readEnvironmentRegistry(ctx) {
2904
+ let candidate;
2905
+ try {
2906
+ candidate = ctx.get("environments");
2907
+ } catch {
2908
+ return;
2909
+ }
2910
+ if (typeof candidate !== "object" || candidate === null) return void 0;
2911
+ const reg = candidate;
2912
+ if (typeof reg.handle !== "function" || typeof reg.capabilities !== "function" || typeof reg.define !== "function") return;
2913
+ return reg;
2914
+ }
2915
+ function errorCodeOf(error) {
2916
+ if (typeof error !== "object" || error === null) return void 0;
2917
+ const code = error.code;
2918
+ return typeof code === "string" ? code : void 0;
2919
+ }
2920
+ function errorMessageOf(error) {
2921
+ return error instanceof Error ? error.message : String(error);
2922
+ }
2923
+ function refusalError(outcome, environmentId) {
2924
+ if (outcome.kind === "workdir") return new ToolArgsError([`workdir "${outcome.cwd}" is not a directory in environment "${environmentId}"`]);
2925
+ const err = /* @__PURE__ */ new Error(`REMOTE_SHELL_UNSUPPORTED: win_bash forwards remote calls only to POSIX environments; environment "${environmentId}" runs on ${outcome.platform}.`);
2926
+ err.code = "REMOTE_SHELL_UNSUPPORTED";
2927
+ return err;
2928
+ }
2929
+ function formatExitedStderr(stderr, exitCode, signal) {
2930
+ if (exitCode !== null || signal === null) return stderr;
2931
+ const note = `[terminated by signal ${signal}]`;
2932
+ return stderr === "" ? note : `${stderr}\n${note}`;
2933
+ }
2934
+ /**
2935
+ * Create the optional `ctx.environments` forwarding runner for `win_bash`.
2936
+ * Tracks registry load/unload through `ctx.inject(['environments'], ...)` when
2937
+ * available, and falls back to lazy `ctx.get('environments')` lookup keyed per
2938
+ * registry instance so synchronous host stubs work without waiting a microtask.
2939
+ */
2940
+ function createRemoteWinBashRunner(ctx) {
2941
+ const runners = /* @__PURE__ */ new WeakMap();
2942
+ let activeRegistry;
2943
+ const defineFor = (registry) => {
2944
+ let run = runners.get(registry);
2945
+ if (run === void 0) {
2946
+ run = registry.define(remoteEnvironmentBash, { result: remoteBashOutcomeValidator });
2947
+ runners.set(registry, run);
2948
+ }
2949
+ return {
2950
+ registry,
2951
+ run
2952
+ };
2953
+ };
2954
+ const injectFn = ctx.inject;
2955
+ if (typeof injectFn === "function") injectFn.call(ctx, ["environments"], (scoped) => {
2956
+ const reg = readEnvironmentRegistry(scoped);
2957
+ if (reg === void 0) return;
2958
+ defineFor(reg);
2959
+ activeRegistry = reg;
2960
+ scoped.effect(() => () => {
2961
+ if (activeRegistry === reg) activeRegistry = void 0;
2962
+ }, "dsh-win-bash: remote environment runner");
2963
+ });
2964
+ const resolve = (target) => {
2965
+ const registry = activeRegistry ?? readEnvironmentRegistry(ctx);
2966
+ if (registry === void 0) throw new EnvironmentUnavailableError(target.id);
2967
+ return defineFor(registry);
2968
+ };
2969
+ const invoke = async (target, signal, request, policy, awaitStop) => {
2970
+ const { registry, run } = resolve(target);
2971
+ const handle = registry.handle(target.id);
2972
+ const sandbox = await remoteSandboxPolicy(policy, target.cwd, async () => (await registry.capabilities(handle, { signal })).cwd);
2973
+ return run(handle, request, {
2974
+ signal,
2975
+ awaitStop,
2976
+ ...sandbox === void 0 ? {} : { sandbox }
2977
+ });
2978
+ };
2979
+ return {
2980
+ async runForeground(input) {
2981
+ const timeout = new AbortController();
2982
+ const timer = setTimeout(() => {
2983
+ timeout.abort(/* @__PURE__ */ new Error(`timed out after ${input.timeoutMs}ms`));
2984
+ }, input.timeoutMs);
2985
+ let outcome;
2986
+ try {
2987
+ outcome = await invoke(input.target, AbortSignal.any([input.signal, timeout.signal]), {
2988
+ command: input.command,
2989
+ cwd: input.target.cwd,
2990
+ workdir: input.workdir,
2991
+ maxStdoutBytes: input.maxStdoutBytes,
2992
+ maxStderrBytes: input.maxStderrBytes
2993
+ }, input.policy, false);
2994
+ } catch (error) {
2995
+ if (input.signal.aborted || !timeout.signal.aborted) throw error;
2996
+ return {
2997
+ stdout: "",
2998
+ stderr: `[timed out after ${input.timeoutMs}ms in remote environment "${input.target.id}"]`,
2999
+ exitCode: 124,
3000
+ stdoutTruncated: true,
3001
+ stderrTruncated: false,
3002
+ stdoutLostHead: true,
3003
+ stderrLostHead: false,
3004
+ frameOverflow: false
3005
+ };
3006
+ } finally {
3007
+ clearTimeout(timer);
3008
+ }
3009
+ if (outcome.kind !== "exited") throw refusalError(outcome, input.target.id);
3010
+ const exitCode = outcome.exitCode ?? SIGNAL_EXIT_CODE;
3011
+ return {
3012
+ stdout: outcome.stdout.text,
3013
+ stderr: formatExitedStderr(outcome.stderr.text, outcome.exitCode, outcome.signal),
3014
+ exitCode,
3015
+ stdoutTruncated: outcome.stdout.truncated,
3016
+ stderrTruncated: outcome.stderr.truncated,
3017
+ stdoutLostHead: outcome.stdout.truncated,
3018
+ stderrLostHead: outcome.stderr.truncated,
3019
+ frameOverflow: false
3020
+ };
3021
+ },
3022
+ startBackground(input) {
3023
+ return input.jobs.start({
3024
+ kind: BACKGROUND_JOB_KIND,
3025
+ label: input.command,
3026
+ ...input.owner === void 0 ? {} : { owner: input.owner },
3027
+ run: (job) => {
3028
+ const { registry, run } = resolve(input.target);
3029
+ const controller = new AbortController();
3030
+ return {
3031
+ cancel: () => {
3032
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("the background job was stopped"));
3033
+ },
3034
+ done: (async () => {
3035
+ let outcome;
3036
+ try {
3037
+ const handle = registry.handle(input.target.id);
3038
+ const sandbox = await remoteSandboxPolicy(input.policy, input.target.cwd, async () => (await registry.capabilities(handle, { signal: controller.signal })).cwd);
3039
+ outcome = await run(handle, {
3040
+ command: input.command,
3041
+ cwd: input.target.cwd,
3042
+ workdir: input.workdir,
3043
+ maxStdoutBytes: input.maxStdoutBytes,
3044
+ maxStderrBytes: input.maxStderrBytes
3045
+ }, {
3046
+ signal: controller.signal,
3047
+ awaitStop: true,
3048
+ ...sandbox === void 0 ? {} : { sandbox }
3049
+ });
3050
+ } catch (error) {
3051
+ const code = errorCodeOf(error);
3052
+ if (code === ENVIRONMENT_RUN_STOPPED || controller.signal.aborted && error === controller.signal.reason) return {
3053
+ status: "killed",
3054
+ detail: `stopped in environment "${input.target.id}"`
3055
+ };
3056
+ const message = errorMessageOf(error);
3057
+ if (code === ENVIRONMENT_OUTCOME_UNKNOWN) {
3058
+ const when = controller.signal.aborted ? "before it confirmed that the command stopped" : "before the command finished";
3059
+ return {
3060
+ status: "failed",
3061
+ detail: `the connection to environment "${input.target.id}" ended ${when}, so whether the command still runs there is unknown: ${message}`
3062
+ };
3063
+ }
3064
+ return {
3065
+ status: "failed",
3066
+ detail: message
3067
+ };
3068
+ }
3069
+ if (outcome.kind !== "exited") return {
3070
+ status: "failed",
3071
+ detail: refusalError(outcome, input.target.id).message
3072
+ };
3073
+ if (outcome.stdout.text !== "" || outcome.stdout.truncated) job.append(outcome.stdout.text, {
3074
+ channel: "stdout",
3075
+ ...outcome.stdout.truncated ? { gapBefore: true } : {}
3076
+ });
3077
+ if (outcome.stderr.text !== "" || outcome.stderr.truncated) job.append(outcome.stderr.text, {
3078
+ channel: "stderr",
3079
+ ...outcome.stderr.truncated ? { gapBefore: true } : {}
3080
+ });
3081
+ if (outcome.exitCode === null) return {
3082
+ status: "killed",
3083
+ detail: outcome.signal === null ? `stopped in environment "${input.target.id}"` : `terminated by signal ${outcome.signal}`
3084
+ };
3085
+ return outcome.exitCode === 0 ? { status: "completed" } : {
3086
+ status: "completed",
3087
+ detail: `exit code ${outcome.exitCode}`
3088
+ };
3089
+ })()
3090
+ };
3091
+ }
3092
+ });
3093
+ }
3094
+ };
3095
+ }
3096
+ //#endregion
2705
3097
  //#region src/tool.ts
2706
3098
  /** The registered tool name. Deliberately not bash. */
2707
3099
  const WIN_BASH_TOOL = "win_bash";
@@ -2931,8 +3323,10 @@ function resolvePolicy(ctx, agent) {
2931
3323
  */
2932
3324
  function buildWinBashTool(ctx, config, runtime, shells) {
2933
3325
  const jobs = config.enableRunInBackground ? readJobRegistry(ctx) : void 0;
3326
+ const remote = createRemoteWinBashRunner(ctx);
2934
3327
  return defineTool({
2935
3328
  name: WIN_BASH_TOOL,
3329
+ environment: "bound",
2936
3330
  description: config.description,
2937
3331
  parameters: {
2938
3332
  command: {
@@ -2988,12 +3382,45 @@ function buildWinBashTool(ctx, config, runtime, shells) {
2988
3382
  async execute(args, exec) {
2989
3383
  const agent = exec.agent;
2990
3384
  if (agent === void 0) throw new Error("win_bash needs an owning agent session: the persistent shell belongs to the session that calls it.");
2991
- const cwd = sessionCwd(agent);
2992
- if (cwd === void 0) throw new Error("win_bash needs a calling session with a working directory.");
2993
3385
  const policy = resolvePolicy(ctx, agent);
2994
3386
  if (policy === void 0) throw new Error("win_bash: the deployment serves no sandbox policy service, so this command has no authoritative permission mode and will not run. Use the host pwsh tool instead: it is the native shell for this platform and remains available whenever win_bash cannot serve a call.");
2995
- assertUnconfined(policy);
2996
3387
  const timeoutMs = clampTimeout(args.timeoutMs, config.timeoutMs);
3388
+ if (exec.environment !== void 0) {
3389
+ const workdir = args.workdir === void 0 || args.workdir === "" ? void 0 : args.workdir;
3390
+ if (args.run_in_background === true) {
3391
+ if (!config.enableRunInBackground) throw new Error("win_bash: run_in_background is disabled for this deployment (enableRunInBackground: false), so this call was not started.");
3392
+ const registry = readJobRegistry(ctx);
3393
+ if (registry === void 0) throw new Error("BACKGROUND_UNAVAILABLE: this deployment composes no background job registry (ctx.jobs), so win_bash cannot register a background command. This call was not run in the foreground instead. Run it without run_in_background, or start it in the background with the host pwsh tool, which is the native shell for this platform and stays available whenever win_bash cannot serve a call.");
3394
+ return {
3395
+ stdout: "",
3396
+ stderr: "",
3397
+ exitCode: 0,
3398
+ jobId: remote.startBackground({
3399
+ jobs: registry,
3400
+ owner: agent.id,
3401
+ target: exec.environment,
3402
+ command: args.command,
3403
+ workdir,
3404
+ maxStdoutBytes: BACKGROUND_STDOUT_BYTES,
3405
+ maxStderrBytes: BACKGROUND_STDERR_BYTES,
3406
+ policy
3407
+ })
3408
+ };
3409
+ }
3410
+ return await remote.runForeground({
3411
+ target: exec.environment,
3412
+ signal: exec.signal,
3413
+ command: args.command,
3414
+ workdir,
3415
+ timeoutMs,
3416
+ maxStdoutBytes: config.maxStdoutBytes,
3417
+ maxStderrBytes: config.maxStderrBytes,
3418
+ policy
3419
+ });
3420
+ }
3421
+ const cwd = sessionCwd(agent);
3422
+ if (cwd === void 0) throw new Error("win_bash needs a calling session with a working directory.");
3423
+ assertUnconfined(policy);
2997
3424
  const command = args.workdir === void 0 || args.workdir === "" ? args.command : "cd " + shellQuote(normalizeWorkdir(args.workdir)) + " && " + args.command;
2998
3425
  if (args.run_in_background === true) {
2999
3426
  if (!config.enableRunInBackground) throw new Error("win_bash: run_in_background is disabled for this deployment (enableRunInBackground: false), so this call was not started.");
@@ -3127,4 +3554,4 @@ function apply(ctx, config) {
3127
3554
  }
3128
3555
  }
3129
3556
  //#endregion
3130
- export { BACKGROUND_JOB_KIND, CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, HOST_PWSH_TOOL, ISOLATED_CACHE_DIR_PARTS, RUNTIME_ROOT_ENV, SERVING_MODE, SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashIn, bashPath, binIn, buildFrame, cacheRoot, inject, installPwshReplacement, isolatedCacheRoot, markerFor, name, parseChecksums, parseFrame, payloadKey, prepareRuntime, readJobRegistry, registerWinBash, removeShellTempDir, renderResult, resolveRuntime, runtimeRoot, shIn, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, stripTerminalEscapes, sweepOrphanShellTempDirs, truncationNotice, validateConfig, verifyPayload, verifyPayloadRoot };
3557
+ export { BACKGROUND_JOB_KIND, CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, HOST_PWSH_TOOL, ISOLATED_CACHE_DIR_PARTS, RUNTIME_ROOT_ENV, SERVING_MODE, SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashIn, bashPath, binIn, buildFrame, cacheRoot, createRemoteWinBashRunner, inject, installPwshReplacement, isolatedCacheRoot, markerFor, name, parseChecksums, parseFrame, payloadKey, prepareRuntime, readJobRegistry, registerWinBash, remoteBashOutcomeValidator, remoteEnvironmentBash, removeShellTempDir, renderResult, resolveRuntime, runtimeRoot, shIn, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, stripTerminalEscapes, sweepOrphanShellTempDirs, truncationNotice, validateConfig, verifyPayload, verifyPayloadRoot };