@linxin666/dsh-win-bash 0.0.0-stage → 0.4.7

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 (118) hide show
  1. package/LICENSE +202 -0
  2. package/PROVENANCE.md +215 -0
  3. package/README.i18n.yaml +6 -0
  4. package/README.md +257 -2
  5. package/README.zh.md +217 -0
  6. package/cordis.patch.yml +13 -0
  7. package/lib/index.js +2697 -0
  8. package/lib/types/background.d.ts +169 -0
  9. package/lib/types/config.d.ts +130 -0
  10. package/lib/types/gate.d.ts +179 -0
  11. package/lib/types/index.d.ts +104 -0
  12. package/lib/types/protocol.d.ts +90 -0
  13. package/lib/types/pwsh-replacement.d.ts +140 -0
  14. package/lib/types/runtime.d.ts +115 -0
  15. package/lib/types/shell.d.ts +184 -0
  16. package/lib/types/tool.d.ts +108 -0
  17. package/package.json +58 -3
  18. package/runtime/win32-x64/checksums.sha256 +91 -0
  19. package/runtime/win32-x64/etc/bash.bashrc +69 -0
  20. package/runtime/win32-x64/etc/fstab +6 -0
  21. package/runtime/win32-x64/etc/msystem +27 -0
  22. package/runtime/win32-x64/etc/msystem.d/CLANG64 +7 -0
  23. package/runtime/win32-x64/etc/msystem.d/CLANGARM64 +7 -0
  24. package/runtime/win32-x64/etc/msystem.d/MINGW32 +7 -0
  25. package/runtime/win32-x64/etc/msystem.d/MINGW64 +7 -0
  26. package/runtime/win32-x64/etc/msystem.d/MSYS +4 -0
  27. package/runtime/win32-x64/etc/msystem.d/UCRT64 +7 -0
  28. package/runtime/win32-x64/etc/nsswitch.conf +12 -0
  29. package/runtime/win32-x64/etc/package-versions.txt +67 -0
  30. package/runtime/win32-x64/etc/profile +146 -0
  31. package/runtime/win32-x64/etc/profile.d/bash_profile.sh +11 -0
  32. package/runtime/win32-x64/etc/profile.d/lang.sh +19 -0
  33. package/runtime/win32-x64/licenses/GPL-2.0.txt +338 -0
  34. package/runtime/win32-x64/licenses/GPL-3.0.txt +674 -0
  35. package/runtime/win32-x64/licenses/LGPL-2.1.txt +501 -0
  36. package/runtime/win32-x64/licenses/LGPL-3.0.txt +165 -0
  37. package/runtime/win32-x64/licenses/expat-COPYING.txt +21 -0
  38. package/runtime/win32-x64/licenses/gcc-libs-RUNTIME.LIBRARY.EXCEPTION.txt +73 -0
  39. package/runtime/win32-x64/licenses/gettext-runtime-COPYING.LIB.txt +501 -0
  40. package/runtime/win32-x64/licenses/gettext-runtime-COPYING.txt +13 -0
  41. package/runtime/win32-x64/licenses/git-for-windows-LICENSE.txt +360 -0
  42. package/runtime/win32-x64/licenses/heimdal-LICENSE.txt +33 -0
  43. package/runtime/win32-x64/licenses/libcbor-LICENSE.md +21 -0
  44. package/runtime/win32-x64/licenses/libffi-LICENSE.txt +21 -0
  45. package/runtime/win32-x64/licenses/libfido2-LICENSE.txt +26 -0
  46. package/runtime/win32-x64/licenses/libiconv-COPYING.LIB.txt +501 -0
  47. package/runtime/win32-x64/licenses/libiconv-COPYING.txt +674 -0
  48. package/runtime/win32-x64/licenses/libopenssl-LICENSE.txt +177 -0
  49. package/runtime/win32-x64/licenses/libpcre-LICENCE.txt +93 -0
  50. package/runtime/win32-x64/licenses/libsqlite-LICENSE +25 -0
  51. package/runtime/win32-x64/licenses/ncurses-LICENSE +29 -0
  52. package/runtime/win32-x64/licenses/openssh-LICENCE.txt +412 -0
  53. package/runtime/win32-x64/licenses/zlib-LICENSE +22 -0
  54. package/runtime/win32-x64/usr/bin/awk.exe +0 -0
  55. package/runtime/win32-x64/usr/bin/b2sum.exe +0 -0
  56. package/runtime/win32-x64/usr/bin/basename.exe +0 -0
  57. package/runtime/win32-x64/usr/bin/basenc.exe +0 -0
  58. package/runtime/win32-x64/usr/bin/bash.exe +0 -0
  59. package/runtime/win32-x64/usr/bin/cat.exe +0 -0
  60. package/runtime/win32-x64/usr/bin/cmp.exe +0 -0
  61. package/runtime/win32-x64/usr/bin/comm.exe +0 -0
  62. package/runtime/win32-x64/usr/bin/cp.exe +0 -0
  63. package/runtime/win32-x64/usr/bin/cut.exe +0 -0
  64. package/runtime/win32-x64/usr/bin/dash.exe +0 -0
  65. package/runtime/win32-x64/usr/bin/date.exe +0 -0
  66. package/runtime/win32-x64/usr/bin/diff.exe +0 -0
  67. package/runtime/win32-x64/usr/bin/diff3.exe +0 -0
  68. package/runtime/win32-x64/usr/bin/dirname.exe +0 -0
  69. package/runtime/win32-x64/usr/bin/echo.exe +0 -0
  70. package/runtime/win32-x64/usr/bin/env.exe +0 -0
  71. package/runtime/win32-x64/usr/bin/expr.exe +0 -0
  72. package/runtime/win32-x64/usr/bin/false.exe +0 -0
  73. package/runtime/win32-x64/usr/bin/find.exe +0 -0
  74. package/runtime/win32-x64/usr/bin/grep.exe +0 -0
  75. package/runtime/win32-x64/usr/bin/head.exe +0 -0
  76. package/runtime/win32-x64/usr/bin/ls.exe +0 -0
  77. package/runtime/win32-x64/usr/bin/mkdir.exe +0 -0
  78. package/runtime/win32-x64/usr/bin/mktemp.exe +0 -0
  79. package/runtime/win32-x64/usr/bin/msys-2.0.dll +0 -0
  80. package/runtime/win32-x64/usr/bin/msys-gcc_s-seh-1.dll +0 -0
  81. package/runtime/win32-x64/usr/bin/msys-gmp-10.dll +0 -0
  82. package/runtime/win32-x64/usr/bin/msys-iconv-2.dll +0 -0
  83. package/runtime/win32-x64/usr/bin/msys-intl-8.dll +0 -0
  84. package/runtime/win32-x64/usr/bin/msys-mpfr-6.dll +0 -0
  85. package/runtime/win32-x64/usr/bin/msys-ncursesw6.dll +0 -0
  86. package/runtime/win32-x64/usr/bin/msys-pcre-1.dll +0 -0
  87. package/runtime/win32-x64/usr/bin/msys-readline8.dll +0 -0
  88. package/runtime/win32-x64/usr/bin/mv.exe +0 -0
  89. package/runtime/win32-x64/usr/bin/pathchk.exe +0 -0
  90. package/runtime/win32-x64/usr/bin/printf.exe +0 -0
  91. package/runtime/win32-x64/usr/bin/pwd.exe +0 -0
  92. package/runtime/win32-x64/usr/bin/readlink.exe +0 -0
  93. package/runtime/win32-x64/usr/bin/rm.exe +0 -0
  94. package/runtime/win32-x64/usr/bin/rmdir.exe +0 -0
  95. package/runtime/win32-x64/usr/bin/sdiff.exe +0 -0
  96. package/runtime/win32-x64/usr/bin/sed.exe +0 -0
  97. package/runtime/win32-x64/usr/bin/seq.exe +0 -0
  98. package/runtime/win32-x64/usr/bin/sh.exe +0 -0
  99. package/runtime/win32-x64/usr/bin/sleep.exe +0 -0
  100. package/runtime/win32-x64/usr/bin/sort.exe +0 -0
  101. package/runtime/win32-x64/usr/bin/tail.exe +0 -0
  102. package/runtime/win32-x64/usr/bin/test.exe +0 -0
  103. package/runtime/win32-x64/usr/bin/touch.exe +0 -0
  104. package/runtime/win32-x64/usr/bin/tr.exe +0 -0
  105. package/runtime/win32-x64/usr/bin/true.exe +0 -0
  106. package/runtime/win32-x64/usr/bin/uname.exe +0 -0
  107. package/runtime/win32-x64/usr/bin/uniq.exe +0 -0
  108. package/runtime/win32-x64/usr/bin/wc.exe +0 -0
  109. package/runtime/win32-x64/usr/bin/xargs.exe +0 -0
  110. package/src/background.ts +270 -0
  111. package/src/config.ts +209 -0
  112. package/src/gate.ts +308 -0
  113. package/src/index.ts +277 -0
  114. package/src/protocol.ts +130 -0
  115. package/src/pwsh-replacement.ts +435 -0
  116. package/src/runtime.ts +240 -0
  117. package/src/shell.ts +630 -0
  118. package/src/tool.ts +417 -0
package/lib/index.js ADDED
@@ -0,0 +1,2697 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, statSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { defineTool } from "@deepseek-ai/dsh-tools";
7
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
8
+ /** Return true when a value is `null` or `undefined`. */
9
+ function isNullable(value) {
10
+ return value === null || value === void 0;
11
+ }
12
+ /** Return true for non-array object values. */
13
+ function isPlainObject(data) {
14
+ return data && typeof data === "object" && !Array.isArray(data);
15
+ }
16
+ /** Filter object entries and return a new object. */
17
+ function filterKeys(object, filter) {
18
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
19
+ }
20
+ /** Map object values while preserving the original key set. */
21
+ function mapValues(object, transform) {
22
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
23
+ }
24
+ /** Pick selected keys from an object, optionally including `undefined` values. */
25
+ function pick(source, keys, forced) {
26
+ if (!keys) return { ...source };
27
+ const result = {};
28
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
29
+ return result;
30
+ }
31
+ /** Shared config references used by schema validators and plugin runtimes. */
32
+ const write = Symbol.for("cosmokit.volatile.write");
33
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
34
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
35
+ if (value === null || typeof value !== "object") return value;
36
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
37
+ ancestors.add(value);
38
+ try {
39
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
40
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
41
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
42
+ } finally {
43
+ ancestors.delete(value);
44
+ }
45
+ }
46
+ /**
47
+ * Create a detached reference containing an immutable copy of the supplied data.
48
+ * @param value - validated config data; class instances and functions are unsupported.
49
+ * @returns a reference whose value is updated only by its owning runtime.
50
+ */
51
+ function createVolatile(value) {
52
+ let current = snapshot(value);
53
+ return Object.freeze({
54
+ get: () => current,
55
+ [write]: (value) => {
56
+ current = value;
57
+ }
58
+ });
59
+ }
60
+ /**
61
+ * Identify references across ESM/CJS copies of the shared library.
62
+ * @param value - a parsed config value.
63
+ * @returns whether the value implements the shared reference protocol.
64
+ */
65
+ function isVolatile(value) {
66
+ return typeof value === "object" && value !== null && write in value;
67
+ }
68
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
69
+ function is(type, value) {
70
+ if (arguments.length === 1) return (value) => is(type, value);
71
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
72
+ }
73
+ function isArrayBufferLike(value) {
74
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
75
+ }
76
+ function isArrayBufferSource(value) {
77
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
78
+ }
79
+ /** Binary source detection and base64/hex conversion helpers. */
80
+ var Binary;
81
+ (function(Binary) {
82
+ Binary.is = isArrayBufferLike;
83
+ Binary.isSource = isArrayBufferSource;
84
+ function fromSource(source) {
85
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
86
+ else return source;
87
+ }
88
+ Binary.fromSource = fromSource;
89
+ function toBase64(source) {
90
+ source = fromSource(source);
91
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
92
+ let binary = "";
93
+ const bytes = new Uint8Array(source);
94
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
95
+ return btoa(binary);
96
+ }
97
+ Binary.toBase64 = toBase64;
98
+ function fromBase64(source) {
99
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
100
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
101
+ }
102
+ Binary.fromBase64 = fromBase64;
103
+ function toHex(source) {
104
+ source = fromSource(source);
105
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
106
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
107
+ }
108
+ Binary.toHex = toHex;
109
+ function fromHex(source) {
110
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
111
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
112
+ const buffer = [];
113
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
114
+ return Uint8Array.from(buffer).buffer;
115
+ }
116
+ Binary.fromHex = fromHex;
117
+ })(Binary || (Binary = {}));
118
+ Binary.fromBase64;
119
+ Binary.toBase64;
120
+ Binary.fromHex;
121
+ Binary.toHex;
122
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
123
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
124
+ if (!source || typeof source !== "object") return source;
125
+ if (is("Date", source)) return new Date(source.valueOf());
126
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
127
+ if (isArrayBufferLike(source)) return source.slice(0);
128
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
129
+ const cached = refs.get(source);
130
+ if (cached) return cached;
131
+ if (Array.isArray(source)) {
132
+ const result = [];
133
+ refs.set(source, result);
134
+ source.forEach((value, index) => {
135
+ result[index] = Reflect.apply(clone, null, [value, refs]);
136
+ });
137
+ return result;
138
+ }
139
+ const result = Object.create(Object.getPrototypeOf(source));
140
+ refs.set(source, result);
141
+ for (const key of Reflect.ownKeys(source)) {
142
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
143
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
144
+ Reflect.defineProperty(result, key, descriptor);
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * Compare values recursively, treating two volatile references as equal regardless of value.
150
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
151
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
152
+ * @param a - first value.
153
+ * @param b - second value.
154
+ * @param strict - whether to require strict data equality outside volatile references.
155
+ * @returns whether the values compare equal.
156
+ */
157
+ function deepEqual(a, b, strict) {
158
+ const ancestors = /* @__PURE__ */ new Set();
159
+ function compare(a, b) {
160
+ if (a === b) return true;
161
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
162
+ if (!strict && isNullable(a) && isNullable(b)) return true;
163
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
164
+ if (ancestors.has(a)) return false;
165
+ function check(test, then) {
166
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
167
+ }
168
+ ancestors.add(a);
169
+ try {
170
+ return check(Array.isArray, (a, b) => {
171
+ if (a.length !== b.length) return false;
172
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
173
+ return true;
174
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
175
+ if (a.byteLength !== b.byteLength) return false;
176
+ const viewA = new Uint8Array(a);
177
+ const viewB = new Uint8Array(b);
178
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
179
+ return true;
180
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
181
+ ...a,
182
+ ...b
183
+ }).every((key) => compare(a[key], b[key])));
184
+ } finally {
185
+ ancestors.delete(a);
186
+ }
187
+ }
188
+ return compare(a, b);
189
+ }
190
+ /** Time constants plus parsing and formatting helpers. */
191
+ var Time;
192
+ (function(Time) {
193
+ Time.millisecond = 1;
194
+ Time.second = 1e3;
195
+ Time.minute = Time.second * 60;
196
+ Time.hour = Time.minute * 60;
197
+ Time.day = Time.hour * 24;
198
+ Time.week = Time.day * 7;
199
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
200
+ function setTimezoneOffset(offset) {
201
+ timezoneOffset = offset;
202
+ }
203
+ Time.setTimezoneOffset = setTimezoneOffset;
204
+ function getTimezoneOffset() {
205
+ return timezoneOffset;
206
+ }
207
+ Time.getTimezoneOffset = getTimezoneOffset;
208
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
209
+ if (typeof date === "number") date = new Date(date);
210
+ if (offset === void 0) offset = timezoneOffset;
211
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
212
+ }
213
+ Time.getDateNumber = getDateNumber;
214
+ function fromDateNumber(value, offset) {
215
+ const date = new Date(value * Time.day);
216
+ if (offset === void 0) offset = timezoneOffset;
217
+ return new Date(+date + offset * Time.minute);
218
+ }
219
+ Time.fromDateNumber = fromDateNumber;
220
+ const numeric = /\d+(?:\.\d+)?/.source;
221
+ const timeRegExp = new RegExp(`^${[
222
+ "w(?:eek(?:s)?)?",
223
+ "d(?:ay(?:s)?)?",
224
+ "h(?:our(?:s)?)?",
225
+ "m(?:in(?:ute)?(?:s)?)?",
226
+ "s(?:ec(?:ond)?(?:s)?)?"
227
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
228
+ function parseTime(source) {
229
+ const capture = timeRegExp.exec(source);
230
+ if (!capture) return 0;
231
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
232
+ }
233
+ Time.parseTime = parseTime;
234
+ function parseDate(date) {
235
+ const parsed = parseTime(date);
236
+ if (parsed) date = Date.now() + parsed;
237
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
238
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
239
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
240
+ }
241
+ Time.parseDate = parseDate;
242
+ function format(ms) {
243
+ const abs = Math.abs(ms);
244
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
245
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
246
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
247
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
248
+ return ms + "ms";
249
+ }
250
+ Time.format = format;
251
+ function toDigits(source, length = 2) {
252
+ return source.toString().padStart(length, "0");
253
+ }
254
+ Time.toDigits = toDigits;
255
+ function template(template, time = /* @__PURE__ */ new Date()) {
256
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
257
+ }
258
+ Time.template = template;
259
+ })(Time || (Time = {}));
260
+ //#endregion
261
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.5/node_modules/@deepseek-ai/schemastery/lib/index.mjs
262
+ const kSchema = Symbol.for("schemastery");
263
+ const kValidationError = Symbol.for("ValidationError");
264
+ globalThis.__schemastery_index__ ??= 0;
265
+ globalThis.__schemastery_refs__ = void 0;
266
+ var ValidationError = class extends TypeError {
267
+ options;
268
+ name = "ValidationError";
269
+ constructor(message, options) {
270
+ let prefix = "$";
271
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
272
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
273
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
274
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
275
+ super((prefix === "$" ? "" : `${prefix} `) + message);
276
+ this.options = options;
277
+ }
278
+ static is(error) {
279
+ return !!error?.[kValidationError];
280
+ }
281
+ };
282
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
283
+ const Schema = function(options) {
284
+ const schema = function(data, options = {}) {
285
+ return Schema.resolve(data, schema, options)[0];
286
+ };
287
+ if (options.refs) {
288
+ const refs = mapValues(options.refs, (options) => new Schema(options));
289
+ const getRef = (uid) => refs[uid];
290
+ for (const key in refs) {
291
+ const options = refs[key];
292
+ options.sKey = getRef(options.sKey);
293
+ options.inner = getRef(options.inner);
294
+ options.list = options.list && options.list.map(getRef);
295
+ options.dict = options.dict && mapValues(options.dict, getRef);
296
+ }
297
+ return refs[options.uid];
298
+ }
299
+ Object.assign(schema, options);
300
+ if (typeof schema.callback === "string") try {
301
+ schema.callback = new Function("return " + schema.callback)();
302
+ } catch {}
303
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
304
+ Object.setPrototypeOf(schema, Schema.prototype);
305
+ schema.meta ||= {};
306
+ schema.toString = schema.toString.bind(schema);
307
+ return schema;
308
+ };
309
+ Schema.prototype = Object.create(Function.prototype);
310
+ Schema.prototype[kSchema] = true;
311
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
312
+ return {
313
+ version: 1,
314
+ vendor: "schemastery",
315
+ validate: (value) => {
316
+ try {
317
+ return { value: Schema.resolve(value, this, {})[0] };
318
+ } catch (error) {
319
+ if (ValidationError.is(error)) return { issues: [{
320
+ message: error.message,
321
+ path: error.options.path
322
+ }] };
323
+ throw error;
324
+ }
325
+ }
326
+ };
327
+ } });
328
+ Schema.ValidationError = ValidationError;
329
+ Schema.prototype.toJSON = function toJSON() {
330
+ if (globalThis.__schemastery_refs__) {
331
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
332
+ return this.uid;
333
+ }
334
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
335
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
336
+ const result = {
337
+ uid: this.uid,
338
+ refs: globalThis.__schemastery_refs__
339
+ };
340
+ globalThis.__schemastery_refs__ = void 0;
341
+ return result;
342
+ };
343
+ Schema.prototype.set = function set(key, value) {
344
+ this.dict[key] = value;
345
+ return this;
346
+ };
347
+ Schema.prototype.push = function push(value) {
348
+ this.list.push(value);
349
+ return this;
350
+ };
351
+ function mergeDesc(original, messages) {
352
+ const result = typeof original === "string" ? { "": original } : { ...original };
353
+ for (const locale in messages) {
354
+ const value = messages[locale];
355
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
356
+ else if (typeof value === "string") result[locale] = value;
357
+ }
358
+ return result;
359
+ }
360
+ function getInner(value) {
361
+ return value?.$value ?? value?.$inner;
362
+ }
363
+ function extractKeys(data) {
364
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
365
+ }
366
+ Schema.prototype.i18n = function i18n(messages) {
367
+ const schema = Schema(this);
368
+ const desc = mergeDesc(schema.meta.description, messages);
369
+ if (Object.keys(desc).length) schema.meta.description = desc;
370
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
371
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
372
+ });
373
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
374
+ return inner.i18n(mapValues(messages, (data = {}) => {
375
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
376
+ if (Array.isArray(data)) return data[index];
377
+ return extractKeys(data);
378
+ }));
379
+ });
380
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
381
+ if (getInner(data)) return getInner(data);
382
+ return extractKeys(data);
383
+ }));
384
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
385
+ return schema;
386
+ };
387
+ Schema.prototype.extra = function extra(key, value) {
388
+ const schema = Schema(this);
389
+ schema.meta = {
390
+ ...schema.meta,
391
+ [key]: value
392
+ };
393
+ return schema;
394
+ };
395
+ for (const key of [
396
+ "required",
397
+ "disabled",
398
+ "collapse",
399
+ "hidden",
400
+ "loose"
401
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
402
+ const schema = Schema(this);
403
+ schema.meta = {
404
+ ...schema.meta,
405
+ [key]: value
406
+ };
407
+ return schema;
408
+ } });
409
+ Schema.prototype.deprecated = function deprecated() {
410
+ const schema = Schema(this);
411
+ schema.meta.badges ||= [];
412
+ schema.meta.badges.push({
413
+ text: "deprecated",
414
+ type: "danger"
415
+ });
416
+ return schema;
417
+ };
418
+ Schema.prototype.experimental = function experimental() {
419
+ const schema = Schema(this);
420
+ schema.meta.badges ||= [];
421
+ schema.meta.badges.push({
422
+ text: "experimental",
423
+ type: "warning"
424
+ });
425
+ return schema;
426
+ };
427
+ Schema.prototype.pattern = function pattern(regexp) {
428
+ const schema = Schema(this);
429
+ const pattern = pick(regexp, ["source", "flags"]);
430
+ schema.meta = {
431
+ ...schema.meta,
432
+ pattern
433
+ };
434
+ return schema;
435
+ };
436
+ Schema.prototype.simplify = function simplify(value) {
437
+ if (isVolatile(value)) value = value.get();
438
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
439
+ if (isNullable(value)) return value;
440
+ if (this.type === "object" || this.type === "dict") {
441
+ const result = {};
442
+ for (const key in value) {
443
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
444
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
445
+ }
446
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
447
+ return result;
448
+ } else if (this.type === "array" || this.type === "tuple") {
449
+ const result = [];
450
+ value.forEach((value, index) => {
451
+ const schema = this.type === "array" ? this.inner : this.list[index];
452
+ const item = schema ? schema.simplify(value) : value;
453
+ result.push(item);
454
+ });
455
+ return result;
456
+ } else if (this.type === "intersect") {
457
+ const result = {};
458
+ for (const item of this.list) Object.assign(result, item.simplify(value));
459
+ return result;
460
+ } else if (this.type === "union") for (const schema of this.list) try {
461
+ Schema.resolve(value, schema, {});
462
+ return schema.simplify(value);
463
+ } catch {}
464
+ return value;
465
+ };
466
+ Schema.prototype.toString = function toString(inline) {
467
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
468
+ };
469
+ Schema.prototype.role = function role(role, extra) {
470
+ const schema = Schema(this);
471
+ schema.meta = {
472
+ ...schema.meta,
473
+ role,
474
+ extra
475
+ };
476
+ return schema;
477
+ };
478
+ for (const key of [
479
+ "default",
480
+ "link",
481
+ "comment",
482
+ "description",
483
+ "max",
484
+ "min",
485
+ "step"
486
+ ]) Object.assign(Schema.prototype, { [key](value) {
487
+ const schema = Schema(this);
488
+ schema.meta = {
489
+ ...schema.meta,
490
+ [key]: value
491
+ };
492
+ return schema;
493
+ } });
494
+ Schema.prototype.volatile = function volatile() {
495
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
496
+ return this.extra("volatile", true);
497
+ };
498
+ const resolvers = {};
499
+ const checkedVolatile = Symbol("checked-volatile-schema");
500
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
501
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
502
+ if (states.has(blocked)) return;
503
+ states.add(blocked);
504
+ seen.set(schema, states);
505
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
506
+ const nested = blocked || !!schema.meta?.volatile;
507
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
508
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
509
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
510
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
511
+ }
512
+ Schema.extend = function extend(type, resolve) {
513
+ resolvers[type] = resolve;
514
+ };
515
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
516
+ if (!schema) return [data];
517
+ if (!options[checkedVolatile]) {
518
+ validateVolatileSchema(schema, options.path);
519
+ options = {
520
+ ...options,
521
+ [checkedVolatile]: true
522
+ };
523
+ }
524
+ if (schema.meta?.volatile) {
525
+ const inner = Schema(schema);
526
+ inner.meta = {
527
+ ...schema.meta,
528
+ volatile: false
529
+ };
530
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
531
+ try {
532
+ return [createVolatile(value), adapted];
533
+ } catch (error) {
534
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
535
+ }
536
+ }
537
+ if (options.ignore?.(data, schema)) return [data];
538
+ if (isNullable(data) && schema.type !== "lazy") {
539
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
540
+ let current = schema;
541
+ let fallback = schema.meta.default;
542
+ while (current?.type === "intersect" && isNullable(fallback)) {
543
+ current = current.list[0];
544
+ fallback = current?.meta.default;
545
+ }
546
+ if (isNullable(fallback)) return [data];
547
+ data = clone(fallback);
548
+ }
549
+ const callback = resolvers[schema.type];
550
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
551
+ try {
552
+ return callback(data, schema, options, strict);
553
+ } catch (error) {
554
+ if (!schema.meta.loose) throw error;
555
+ return [schema.meta.default];
556
+ }
557
+ };
558
+ Schema.from = function from(source) {
559
+ if (isNullable(source)) return Schema.any();
560
+ else if ([
561
+ "string",
562
+ "number",
563
+ "boolean"
564
+ ].includes(typeof source)) return Schema.const(source).required();
565
+ else if (source[kSchema]) return source;
566
+ else if (typeof source === "function") switch (source) {
567
+ case String: return Schema.string().required();
568
+ case Number: return Schema.number().required();
569
+ case Boolean: return Schema.boolean().required();
570
+ case Function: return Schema.function().required();
571
+ default: return Schema.is(source).required();
572
+ }
573
+ else throw new TypeError(`cannot infer schema from ${source}`);
574
+ };
575
+ Schema.lazy = function lazy(builder) {
576
+ const toJSON = () => {
577
+ if (!schema.inner[kSchema]) {
578
+ schema.inner = schema.builder();
579
+ schema.inner.meta = {
580
+ ...schema.meta,
581
+ ...schema.inner.meta
582
+ };
583
+ }
584
+ return schema.inner.toJSON();
585
+ };
586
+ const schema = new Schema({
587
+ type: "lazy",
588
+ builder,
589
+ inner: { toJSON }
590
+ });
591
+ return schema;
592
+ };
593
+ Schema.natural = function natural() {
594
+ return Schema.number().step(1).min(0);
595
+ };
596
+ Schema.percent = function percent() {
597
+ return Schema.number().step(.01).min(0).max(1).role("slider");
598
+ };
599
+ Schema.date = function date() {
600
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
601
+ const date = new Date(value);
602
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
603
+ return date;
604
+ }, true)]);
605
+ };
606
+ Schema.regExp = function regExp(flag = "") {
607
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
608
+ try {
609
+ return new RegExp(value, flag);
610
+ } catch (e) {
611
+ throw new ValidationError(e.message, options);
612
+ }
613
+ }, true)]);
614
+ };
615
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
616
+ return Schema.union([
617
+ Schema.is(ArrayBuffer),
618
+ Schema.is(SharedArrayBuffer),
619
+ Schema.transform(Schema.any(), (value, options) => {
620
+ if (Binary.isSource(value)) return Binary.fromSource(value);
621
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
622
+ }, true),
623
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
624
+ try {
625
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
626
+ } catch (e) {
627
+ throw new ValidationError(e.message, options);
628
+ }
629
+ }, true)] : []
630
+ ]);
631
+ };
632
+ Schema.extend("lazy", (data, schema, options, strict) => {
633
+ if (!schema.inner[kSchema]) {
634
+ schema.inner = schema.builder();
635
+ schema.inner.meta = {
636
+ ...schema.meta,
637
+ ...schema.inner.meta
638
+ };
639
+ validateVolatileSchema(schema.inner, options.path, true);
640
+ }
641
+ return Schema.resolve(data, schema.inner, options, strict);
642
+ });
643
+ Schema.extend("any", (data) => {
644
+ return [data];
645
+ });
646
+ Schema.extend("never", (data, _, options) => {
647
+ throw new ValidationError(`expected nullable but got ${data}`, options);
648
+ });
649
+ Schema.extend("const", (data, { value }, options) => {
650
+ if (deepEqual(data, value)) return [value];
651
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
652
+ });
653
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
654
+ const { max = Infinity, min = -Infinity } = meta;
655
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
656
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
657
+ }
658
+ Schema.extend("string", (data, { meta }, options) => {
659
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
660
+ if (meta.pattern) {
661
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
662
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
663
+ }
664
+ checkWithinRange(data.length, meta, "string length", options);
665
+ return [data];
666
+ });
667
+ function decimalShift(data, digits) {
668
+ const str = data.toString();
669
+ if (str.includes("e")) return data * Math.pow(10, digits);
670
+ const index = str.indexOf(".");
671
+ if (index === -1) return data * Math.pow(10, digits);
672
+ const frac = str.slice(index + 1);
673
+ const integer = str.slice(0, index);
674
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
675
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
676
+ }
677
+ function isMultipleOf(data, min, step) {
678
+ step = Math.abs(step);
679
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
680
+ const index = step.toString().indexOf(".");
681
+ const digits = step.toString().slice(index + 1).length;
682
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
683
+ }
684
+ Schema.extend("number", (data, { meta }, options) => {
685
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
686
+ checkWithinRange(data, meta, "number", options);
687
+ const { step } = meta;
688
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
689
+ return [data];
690
+ });
691
+ Schema.extend("boolean", (data, _, options) => {
692
+ if (typeof data === "boolean") return [data];
693
+ throw new ValidationError(`expected boolean but got ${data}`, options);
694
+ });
695
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
696
+ let value = 0, keys = [];
697
+ if (typeof data === "number") {
698
+ value = data;
699
+ for (const key in bits) if (data & bits[key]) keys.push(key);
700
+ } else if (Array.isArray(data)) {
701
+ keys = data;
702
+ for (const key of keys) {
703
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
704
+ if (key in bits) value |= bits[key];
705
+ }
706
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
707
+ if (value === meta.default) return [value];
708
+ return [value, keys];
709
+ });
710
+ Schema.extend("function", (data, _, options) => {
711
+ if (typeof data === "function") return [data];
712
+ throw new ValidationError(`expected function but got ${data}`, options);
713
+ });
714
+ Schema.extend("is", (data, { constructor }, options) => {
715
+ if (typeof constructor === "function") {
716
+ if (data instanceof constructor) return [data];
717
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
718
+ } else {
719
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
720
+ let prototype = Object.getPrototypeOf(data);
721
+ while (prototype) {
722
+ if (prototype.constructor?.name === constructor) return [data];
723
+ prototype = Object.getPrototypeOf(prototype);
724
+ }
725
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
726
+ }
727
+ });
728
+ function property(data, key, schema, options) {
729
+ try {
730
+ const [value, adapted] = Schema.resolve(data[key], schema, {
731
+ ...options,
732
+ path: [...options.path || [], key]
733
+ });
734
+ if (adapted !== void 0) data[key] = adapted;
735
+ return value;
736
+ } catch (e) {
737
+ if (!options?.autofix) throw e;
738
+ delete data[key];
739
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
740
+ }
741
+ }
742
+ Schema.extend("array", (data, { inner, meta }, options) => {
743
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
744
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
745
+ return [data.map((_, index) => property(data, index, inner, options))];
746
+ });
747
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
748
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
749
+ const result = {};
750
+ for (const key in data) {
751
+ let rKey;
752
+ try {
753
+ rKey = Schema.resolve(key, sKey, options)[0];
754
+ } catch (error) {
755
+ if (strict) continue;
756
+ throw error;
757
+ }
758
+ result[rKey] = property(data, key, inner, options);
759
+ data[rKey] = data[key];
760
+ if (key !== rKey) delete data[key];
761
+ }
762
+ return [result];
763
+ });
764
+ Schema.extend("tuple", (data, { list }, options, strict) => {
765
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
766
+ const result = list.map((inner, index) => property(data, index, inner, options));
767
+ if (strict) return [result];
768
+ result.push(...data.slice(list.length));
769
+ return [result];
770
+ });
771
+ function merge(result, data) {
772
+ for (const key in data) {
773
+ if (key in result) continue;
774
+ result[key] = data[key];
775
+ }
776
+ }
777
+ Schema.extend("object", (data, { dict }, options, strict) => {
778
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
779
+ const result = {};
780
+ for (const key in dict) {
781
+ const value = property(data, key, dict[key], options);
782
+ if (!isNullable(value) || key in data) result[key] = value;
783
+ }
784
+ if (!strict) merge(result, data);
785
+ return [result];
786
+ });
787
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
788
+ const messages = [];
789
+ for (const inner of list) try {
790
+ return Schema.resolve(data, inner, options, strict);
791
+ } catch (error) {
792
+ messages.push(error);
793
+ }
794
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
795
+ });
796
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
797
+ if (!list.length) return [data];
798
+ let result;
799
+ for (const inner of list) {
800
+ const value = Schema.resolve(data, inner, options, true)[0];
801
+ if (isNullable(value)) continue;
802
+ if (isNullable(result)) result = value;
803
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
804
+ else if (typeof value === "object") merge(result ??= {}, value);
805
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
806
+ }
807
+ if (!strict && isPlainObject(data)) merge(result, data);
808
+ return [result];
809
+ });
810
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
811
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
812
+ if (preserve) return [callback(result)];
813
+ else return [callback(result), callback(adapted)];
814
+ });
815
+ const formatters = {};
816
+ function defineMethod(name, keys, format) {
817
+ formatters[name] = format;
818
+ Object.assign(Schema, { [name](...args) {
819
+ const schema = new Schema({ type: name });
820
+ keys.forEach((key, index) => {
821
+ switch (key) {
822
+ case "sKey":
823
+ schema.sKey = args[index] ?? Schema.string();
824
+ break;
825
+ case "inner":
826
+ schema.inner = Schema.from(args[index]);
827
+ break;
828
+ case "list":
829
+ schema.list = args[index].map(Schema.from);
830
+ break;
831
+ case "dict":
832
+ schema.dict = mapValues(args[index], Schema.from);
833
+ break;
834
+ case "bits":
835
+ schema.bits = {};
836
+ for (const key in args[index]) {
837
+ if (typeof args[index][key] !== "number") continue;
838
+ schema.bits[key] = args[index][key];
839
+ }
840
+ break;
841
+ case "callback": {
842
+ const callback = schema.callback = args[index];
843
+ callback["toJSON"] ||= () => callback.toString();
844
+ break;
845
+ }
846
+ case "constructor": {
847
+ const constructor = schema.constructor = args[index];
848
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
849
+ break;
850
+ }
851
+ default: schema[key] = args[index];
852
+ }
853
+ });
854
+ if (name === "object" || name === "dict") schema.meta.default = {};
855
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
856
+ else if (name === "bitset") schema.meta.default = 0;
857
+ return schema;
858
+ } });
859
+ }
860
+ defineMethod("is", ["constructor"], ({ constructor }) => {
861
+ if (typeof constructor === "function") return constructor.name;
862
+ else return constructor;
863
+ });
864
+ defineMethod("any", [], () => "any");
865
+ defineMethod("never", [], () => "never");
866
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
867
+ defineMethod("string", [], () => "string");
868
+ defineMethod("number", [], () => "number");
869
+ defineMethod("boolean", [], () => "boolean");
870
+ defineMethod("bitset", ["bits"], () => "bitset");
871
+ defineMethod("function", [], () => "function");
872
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
873
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
874
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
875
+ defineMethod("object", ["dict"], ({ dict }) => {
876
+ if (Object.keys(dict).length === 0) return "{}";
877
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
878
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
879
+ }).join(", ")} }`;
880
+ });
881
+ defineMethod("union", ["list"], ({ list }, inline) => {
882
+ const result = list.map(({ toString: format }) => format()).join(" | ");
883
+ return inline ? `(${result})` : result;
884
+ });
885
+ defineMethod("intersect", ["list"], ({ list }) => {
886
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
887
+ });
888
+ defineMethod("transform", [
889
+ "inner",
890
+ "callback",
891
+ "preserve"
892
+ ], ({ inner }, isInner) => inner.toString(isInner));
893
+ //#endregion
894
+ //#region src/protocol.ts
895
+ /**
896
+ * Wire protocol for the session's persistent bash shell.
897
+ *
898
+ * The shell is one long-lived 'bash -s' process per session, so every tool
899
+ * call must (a) inject its command without racing the previous one and (b)
900
+ * find the exact end of that command's output and its exit status inside one
901
+ * continuous byte stream. Both jobs ride this module and nothing else, so the
902
+ * framing is unit-testable without a process.
903
+ *
904
+ * Frame shape, written on stdin for each call:
905
+ *
906
+ * printf '\n%s\n' '<M>BEGIN'
907
+ * . /dev/stdin <<'<M>END'
908
+ * <the model's command, verbatim, any number of lines>
909
+ * <M>END
910
+ * __dsh_win_bash_status=$?
911
+ * printf '\n%s%d\n' '<M>END' "$__dsh_win_bash_status"
912
+ *
913
+ * Why a heredoc and not a plain brace-group: the shell parses a brace group
914
+ * one command at a time, so a syntactic error inside it aborts the REST of the
915
+ * group — a model line with an unterminated quote would swallow the end marker
916
+ * and leave the call (and the shell) wedged forever. The command is therefore
917
+ * read through a heredoc into the source builtin, which the shell parses as
918
+ * ONE unit: a syntax error is reported and the shell moves on to the next
919
+ * line, where the status capture and the end marker still run. Measured on the
920
+ * vendored bash: an unterminated quote produces 'unexpected EOF while looking
921
+ * for matching' on stderr, and the very next call succeeds on the same
922
+ * process.
923
+ *
924
+ * The begin/end markers carry a per-call nonce, so a command cannot forge the
925
+ * end of its own frame even if it echoes marker-shaped text.
926
+ * @module @linxin666/dsh-win-bash/protocol
927
+ */
928
+ /** Literal prefix of every frame marker; the nonce follows it. */
929
+ const MARKER_PREFIX = "__DSH_WIN_BASH_";
930
+ /**
931
+ * Build the marker pair for one call. The nonce is stripped to alphanumerics
932
+ * so the markers stay valid heredoc delimiters and single shell words.
933
+ * @param nonce - caller-supplied uniqueness source (a UUID).
934
+ * @returns the begin/end markers, both printable and both nonce-bearing.
935
+ */
936
+ function markerFor(nonce) {
937
+ const safe = nonce.replace(/[^A-Za-z0-9]/g, "");
938
+ const base = MARKER_PREFIX + safe + "__";
939
+ return {
940
+ begin: base + "BEGIN",
941
+ end: base + "END"
942
+ };
943
+ }
944
+ /**
945
+ * Render the stdin frame for one command. The command is inserted verbatim:
946
+ * the heredoc is quoted, so the shell performs no expansion on it while
947
+ * reading, and the sourced text is executed exactly as the model wrote it.
948
+ * @param command - the model's command, any number of lines.
949
+ * @param marker - the markers for this call.
950
+ * @returns the text to write to the shell's stdin, newline-terminated.
951
+ */
952
+ function buildFrame(command, marker) {
953
+ return [
954
+ "printf '\\n%s\\n' '" + marker.begin + "'",
955
+ ". /dev/stdin <<'" + marker.end + "'",
956
+ command,
957
+ marker.end,
958
+ "__dsh_win_bash_status=$?",
959
+ "printf '\\n%s%d\\n' '" + marker.end + "' \"$__dsh_win_bash_status\"",
960
+ ""
961
+ ].join("\n");
962
+ }
963
+ /**
964
+ * Recover one command's stdout and exit status from accumulated output.
965
+ * Unframed or still-running text returns undefined, so the caller keeps
966
+ * waiting instead of reporting a truncated result.
967
+ * @param text - accumulated stdout for the current call.
968
+ * @param marker - the markers for this call.
969
+ * @param sawBegin - whether the begin marker was observed before the window slid.
970
+ * @returns the outcome once the end marker and its digits arrived.
971
+ */
972
+ function parseFrame(text, marker, sawBegin) {
973
+ const beginIndex = text.indexOf(marker.begin);
974
+ const endIndex = text.indexOf(marker.end, beginIndex < 0 ? 0 : beginIndex + marker.begin.length);
975
+ if (endIndex < 0) return void 0;
976
+ const status = /^(\d+)\r?\n/.exec(text.slice(endIndex + marker.end.length));
977
+ if (status === null) return void 0;
978
+ if (beginIndex < 0 && !sawBegin) return void 0;
979
+ let bodyStart = beginIndex < 0 ? 0 : beginIndex + marker.begin.length;
980
+ if (text[bodyStart] === "\n") bodyStart += 1;
981
+ let stdout = text.slice(bodyStart, endIndex);
982
+ if (stdout.endsWith("\n")) stdout = stdout.slice(0, -1);
983
+ return {
984
+ stdout,
985
+ exitCode: Number(status[1]),
986
+ lostPrefix: beginIndex < 0
987
+ };
988
+ }
989
+ //#endregion
990
+ //#region src/shell.ts
991
+ /**
992
+ * One persistent bash process per calling agent, driven over piped stdio.
993
+ *
994
+ * Why pipes and not the host's terminal seam: this tool needs a persistent
995
+ * SHELL, not a terminal emulator. What must survive across calls is the shell
996
+ * process state (its current directory, exported variables, functions and
997
+ * aliases) plus exact stdout/stderr bytes and an exact exit code — all of
998
+ * which the subprocess seam's collected streams give directly. A PTY would add
999
+ * echoing and escape sequences this tool would then have to strip again, and
1000
+ * would not change the state model.
1001
+ *
1002
+ * Recovery policy: a shell that exits, wedges or fails its handshake is torn
1003
+ * down and the CURRENT call fails with a specific message; the NEXT call
1004
+ * starts a fresh shell. State loss is reported rather than hidden, because a
1005
+ * silent fresh shell would run the model's next command in the wrong directory
1006
+ * with no signal that the previous call's cd/export vanished.
1007
+ * @module @linxin666/dsh-win-bash/shell
1008
+ */
1009
+ /** Command stdout budget, in bytes, for one call. */
1010
+ const DEFAULT_MAX_STDOUT_BYTES = 128 * 1024;
1011
+ /** Command stderr budget, in bytes, for one call. */
1012
+ const DEFAULT_MAX_STDERR_BYTES = 32 * 1024;
1013
+ /** Spill-file byte cap per stream, so a runaway command cannot fill the disk. */
1014
+ const DEFAULT_SPILL_BYTES = 8 * 1024 * 1024;
1015
+ /** Grace period handed to the subprocess seam for range teardown. */
1016
+ const GRACE_MS = 5e3;
1017
+ /** Ceiling on the bytes buffered while looking for a frame's end marker. */
1018
+ const FRAME_WATCH_BYTES = 4 * 1024 * 1024;
1019
+ /** In-memory capture ceiling for one shell's stderr, in bytes. */
1020
+ const SHELL_STDERR_CAPTURE_BYTES = 256 * 1024;
1021
+ /** Poll cadence while waiting for a frame to complete. */
1022
+ const POLL_INTERVAL_MS = 15;
1023
+ /** How long a freshly spawned shell gets to answer its startup handshake. */
1024
+ const HANDSHAKE_TIMEOUT_MS = 15e3;
1025
+ /**
1026
+ * The argv of one pinned shell: the payload's own bash by absolute path, no rc
1027
+ * file and no profile, reading its commands from stdin. This tool never
1028
+ * consults PATH, and every shell it starts — the session's persistent one and
1029
+ * every background job — is built from this one function so the two can never
1030
+ * drift into different shells.
1031
+ * @param runtime - the verified payload paths.
1032
+ * @returns the argv to spawn.
1033
+ */
1034
+ function shellArgv(runtime) {
1035
+ return [
1036
+ runtime.bash,
1037
+ "--norc",
1038
+ "--noprofile",
1039
+ "-s"
1040
+ ];
1041
+ }
1042
+ /**
1043
+ * The environment contract every pinned shell starts with.
1044
+ * @param runtime - the verified payload paths.
1045
+ * @param temp - the private temp directory that shell owns.
1046
+ * @param base - the ambient environment the PATH is appended to.
1047
+ * @returns the entries this tool sets explicitly.
1048
+ */
1049
+ function shellEnvironment(runtime, temp, base = process.env) {
1050
+ return {
1051
+ PATH: runtime.bin + (process.platform === "win32" ? ";" : ":") + (base.PATH ?? ""),
1052
+ TMPDIR: temp,
1053
+ TMP: temp,
1054
+ TEMP: temp,
1055
+ MSYSTEM: "MSYS",
1056
+ TERM: "dumb"
1057
+ };
1058
+ }
1059
+ /**
1060
+ * Create one shell process's private temp directory.
1061
+ * @returns the absolute directory, created if absent.
1062
+ */
1063
+ function shellTempDir() {
1064
+ const temp = join(tmpdir(), "dsh-win-bash-" + process.pid.toString() + "-" + randomUUID().slice(0, 8));
1065
+ mkdirSync(temp, { recursive: true });
1066
+ return temp;
1067
+ }
1068
+ /** Failure raised when the shell cannot serve a call. */
1069
+ var ShellUnavailableError = class extends Error {
1070
+ /** Stable machine-readable reason. */
1071
+ code;
1072
+ /**
1073
+ * @param code - stable reason code.
1074
+ * @param message - explanation safe to show the model.
1075
+ */
1076
+ constructor(code, message) {
1077
+ super(message);
1078
+ this.name = "ShellUnavailableError";
1079
+ this.code = code;
1080
+ }
1081
+ };
1082
+ /** One bounded accumulator fed by an offset-based collected reader. */
1083
+ var StreamTail = class {
1084
+ label;
1085
+ buffer = "";
1086
+ /** Whole-stream offset already consumed from the provider's reader. */
1087
+ offset = 0;
1088
+ overflowed = false;
1089
+ spilled = false;
1090
+ spill;
1091
+ /**
1092
+ * @param label - which collected reader this accumulator drains.
1093
+ * @param from - whole-stream offset already consumed by earlier calls on
1094
+ * the same process. Collected readers are whole-stream and non-consuming,
1095
+ * so without this a call would re-read every previous frame.
1096
+ */
1097
+ constructor(label, from = 0) {
1098
+ this.label = label;
1099
+ this.offset = from;
1100
+ }
1101
+ /** Everything retained so far. */
1102
+ text() {
1103
+ return this.buffer;
1104
+ }
1105
+ /** Whether the retained window dropped bytes (a lossy read or a trim). */
1106
+ lost() {
1107
+ return this.overflowed;
1108
+ }
1109
+ /** Whether anything visible was cut, which is what a spill file is for. */
1110
+ wasCut() {
1111
+ return this.spilled;
1112
+ }
1113
+ /** Spill file holding the complete stream, once the provider made one. */
1114
+ spillPath() {
1115
+ return this.spill;
1116
+ }
1117
+ /**
1118
+ * Cut the visible text down to its last budget bytes, recording that the
1119
+ * stream was cut so the caller can point at the spill file for the rest.
1120
+ * @param budget - the visible byte budget.
1121
+ * @returns the visible text and whether it was cut.
1122
+ */
1123
+ visible(budget) {
1124
+ const result = tailBytes(this.buffer, budget);
1125
+ if (result.truncated) this.spilled = true;
1126
+ return result;
1127
+ }
1128
+ /** Record that this stream's visible text was cut somewhere upstream. */
1129
+ markCut() {
1130
+ this.spilled = true;
1131
+ }
1132
+ /** Whole-stream byte offset already consumed. */
1133
+ consumed() {
1134
+ return this.offset;
1135
+ }
1136
+ /**
1137
+ * Drain new bytes from one handle's collected readers.
1138
+ * @param handle - the live shell's handle.
1139
+ * @param watchBytes - how many bytes may be buffered before the head drops.
1140
+ */
1141
+ drain(handle, watchBytes) {
1142
+ const reader = this.label === "stdout" ? handle.collected.stdout : handle.collected.stderr;
1143
+ if (reader === void 0) return;
1144
+ const read = reader.readFrom(this.offset);
1145
+ this.offset = read.nextOffset;
1146
+ if (read.lossy) this.overflowed = true;
1147
+ if (read.spillPath !== void 0) this.spill = read.spillPath;
1148
+ if (read.text === "") return;
1149
+ this.buffer += read.text;
1150
+ while (byteLength$1(this.buffer) > watchBytes) {
1151
+ this.overflowed = true;
1152
+ this.buffer = this.buffer.slice(Math.ceil(this.buffer.length / 4));
1153
+ }
1154
+ }
1155
+ };
1156
+ /** UTF-8 byte length of a string. */
1157
+ function byteLength$1(text) {
1158
+ return Buffer.byteLength(text, "utf8");
1159
+ }
1160
+ /**
1161
+ * Keep the LAST budget bytes of a string, reporting whether it dropped any.
1162
+ * @param text - the full text.
1163
+ * @param budget - the visible byte budget.
1164
+ * @returns the visible text and whether it was cut.
1165
+ */
1166
+ function tailBytes(text, budget) {
1167
+ if (byteLength$1(text) <= budget) return {
1168
+ text,
1169
+ truncated: false
1170
+ };
1171
+ const bytes = Buffer.from(text, "utf8");
1172
+ const tail = bytes.subarray(bytes.length - budget).toString("utf8");
1173
+ return {
1174
+ text: tail.startsWith("�") ? tail.slice(1) : tail,
1175
+ truncated: true
1176
+ };
1177
+ }
1178
+ /**
1179
+ * The persistent shells of one plugin instance, keyed by calling agent.
1180
+ *
1181
+ * The keys are the live agent objects and the map is plain, so an agent's
1182
+ * shell is dropped by that agent's own disposal hook rather than by a weak
1183
+ * reference that decides for itself when to act.
1184
+ */
1185
+ var ShellRegistry = class {
1186
+ subprocess;
1187
+ now;
1188
+ shells = /* @__PURE__ */ new Map();
1189
+ /**
1190
+ * @param subprocess - the host's managed subprocess seam.
1191
+ * @param now - clock, injected so tests run without real waiting.
1192
+ */
1193
+ constructor(subprocess, now = () => Date.now()) {
1194
+ this.subprocess = subprocess;
1195
+ this.now = now;
1196
+ }
1197
+ /** Live shell count, for teardown assertions. */
1198
+ get size() {
1199
+ return this.shells.size;
1200
+ }
1201
+ /** Whether the given owner currently holds a live shell. */
1202
+ has(owner) {
1203
+ const shell = this.shells.get(owner);
1204
+ return shell !== void 0 && !shell.exited;
1205
+ }
1206
+ /**
1207
+ * Run one command in the owner's persistent shell, starting it on first use.
1208
+ * @param owner - the calling agent (the shell lifetime key).
1209
+ * @param runtime - absolute shell and payload paths.
1210
+ * @param cwd - the session workspace a newly started shell begins in.
1211
+ * @param command - the command to run.
1212
+ * @param budget - output budgets and the call deadline.
1213
+ * @returns the command's complete result.
1214
+ */
1215
+ async run(owner, runtime, cwd, command, budget) {
1216
+ const shell = await this.ensure(owner, runtime, cwd, budget.signal);
1217
+ const marker = markerFor(randomUUID());
1218
+ const stdout = new StreamTail("stdout", shell.cursor.stdout);
1219
+ const stderr = new StreamTail("stderr", shell.cursor.stderr);
1220
+ shell.handle.stdin?.write(buildFrame(command, marker));
1221
+ const deadline = this.now() + budget.timeoutMs;
1222
+ let sawBegin = false;
1223
+ const resume = () => {
1224
+ shell.cursor.stdout = stdout.consumed();
1225
+ shell.cursor.stderr = stderr.consumed();
1226
+ };
1227
+ for (;;) {
1228
+ if (budget.signal?.aborted === true) {
1229
+ resume();
1230
+ await this.dispose(owner, "the tool call was aborted");
1231
+ throw new ShellUnavailableError("aborted", "The win_bash call was aborted and its persistent shell was stopped. The next call starts a fresh shell, so shell state changed before this call was aborted is gone.");
1232
+ }
1233
+ const frame = readFrame(shell, stdout, stderr, marker, sawBegin);
1234
+ sawBegin ||= frame.text.includes(marker.begin);
1235
+ if (frame.outcome !== void 0) {
1236
+ const result = complete(frame.outcome, stdout, stderr, budget);
1237
+ resume();
1238
+ return result;
1239
+ }
1240
+ if (shell.exited) {
1241
+ resume();
1242
+ this.shells.delete(owner);
1243
+ const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes);
1244
+ if (shell.exitCode === null) throw new ShellUnavailableError("shell-exited", "The persistent bash shell exited without reporting a status, so this command did not complete. The next win_bash call starts a fresh shell in the session workspace with a new current directory and environment.");
1245
+ const visibleErr = stderr.visible(budget.stderrBytes);
1246
+ return {
1247
+ stdout: partial.text,
1248
+ stderr: visibleErr.text === "" ? "[the command ended the persistent bash process; the next win_bash call starts a fresh shell]" : visibleErr.text + "\n[the command ended the persistent bash process; the next win_bash call starts a fresh shell]",
1249
+ exitCode: shell.exitCode,
1250
+ stdoutTruncated: partial.truncated,
1251
+ stderrTruncated: visibleErr.truncated,
1252
+ stdoutLostHead: stdout.lost() || partial.truncated,
1253
+ stderrLostHead: stderr.lost() || visibleErr.truncated,
1254
+ frameOverflow: stdout.lost(),
1255
+ ...stdout.wasCut() && stdout.spillPath() !== void 0 ? { stdoutSpillPath: stdout.spillPath() } : {},
1256
+ ...stderr.wasCut() && stderr.spillPath() !== void 0 ? { stderrSpillPath: stderr.spillPath() } : {}
1257
+ };
1258
+ }
1259
+ if (this.now() > deadline) {
1260
+ await this.dispose(owner, "the command exceeded its time budget");
1261
+ const visibleErr = stderr.visible(budget.stderrBytes);
1262
+ const note = "[timed out after " + budget.timeoutMs.toString() + "ms; the persistent shell was stopped, so the next win_bash call starts a fresh shell]";
1263
+ const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes);
1264
+ if (partial.truncated) stdout.markCut();
1265
+ resume();
1266
+ return {
1267
+ stdout: partial.text,
1268
+ stderr: visibleErr.text === "" ? note : visibleErr.text + "\n" + note,
1269
+ exitCode: 124,
1270
+ stdoutTruncated: partial.truncated,
1271
+ stderrTruncated: visibleErr.truncated,
1272
+ stdoutLostHead: stdout.lost() || partial.truncated,
1273
+ stderrLostHead: stderr.lost() || visibleErr.truncated,
1274
+ frameOverflow: stdout.lost(),
1275
+ ...stdout.wasCut() && stdout.spillPath() !== void 0 ? { stdoutSpillPath: stdout.spillPath() } : {},
1276
+ ...stderr.wasCut() && stderr.spillPath() !== void 0 ? { stderrSpillPath: stderr.spillPath() } : {}
1277
+ };
1278
+ }
1279
+ await new Promise((resolve) => {
1280
+ setTimeout(resolve, POLL_INTERVAL_MS);
1281
+ });
1282
+ }
1283
+ }
1284
+ /**
1285
+ * Get the owner's live shell, starting one when absent.
1286
+ * @param owner - calling agent identity.
1287
+ * @param runtime - absolute shell and payload paths.
1288
+ * @param cwd - the session workspace a new shell starts in.
1289
+ * @param signal - cancellation while the shell starts.
1290
+ * @returns the live shell record.
1291
+ */
1292
+ async ensure(owner, runtime, cwd, signal) {
1293
+ const existing = this.shells.get(owner);
1294
+ if (existing !== void 0 && !existing.exited) return existing;
1295
+ if (existing !== void 0) this.shells.delete(owner);
1296
+ const handle = this.subprocess.spawn({
1297
+ argv: shellArgv(runtime),
1298
+ cwd,
1299
+ stdio: {
1300
+ stdin: "pipe",
1301
+ stdout: {
1302
+ maxBytes: FRAME_WATCH_BYTES,
1303
+ spill: { maxBytes: DEFAULT_SPILL_BYTES }
1304
+ },
1305
+ stderr: {
1306
+ maxBytes: SHELL_STDERR_CAPTURE_BYTES,
1307
+ spill: { maxBytes: DEFAULT_SPILL_BYTES }
1308
+ }
1309
+ },
1310
+ graceMs: GRACE_MS,
1311
+ env: shellEnvironment(runtime, shellTempDir())
1312
+ });
1313
+ const shell = {
1314
+ handle,
1315
+ exited: false,
1316
+ cursor: {
1317
+ stdout: 0,
1318
+ stderr: 0
1319
+ },
1320
+ exitCode: null
1321
+ };
1322
+ const markExited = (outcome) => {
1323
+ shell.exitCode = outcome.exitCode;
1324
+ shell.exited = true;
1325
+ };
1326
+ handle.done.then(markExited, () => {
1327
+ shell.exited = true;
1328
+ });
1329
+ this.shells.set(owner, shell);
1330
+ await this.handshake(shell, signal);
1331
+ return shell;
1332
+ }
1333
+ /**
1334
+ * Confirm a fresh shell answers before the first real command runs, so a
1335
+ * payload that cannot start surfaces as one clear failure instead of as a
1336
+ * mysterious empty result on the model's command.
1337
+ */
1338
+ async handshake(shell, signal) {
1339
+ const marker = markerFor(randomUUID());
1340
+ const stdout = new StreamTail("stdout", shell.cursor.stdout);
1341
+ shell.handle.stdin?.write(buildFrame("printf %s \"$BASH_VERSION\"", marker));
1342
+ const deadline = this.now() + HANDSHAKE_TIMEOUT_MS;
1343
+ for (;;) {
1344
+ if (shell.exited) throw new ShellUnavailableError("shell-exited", "The vendored bash exited during startup, so win_bash cannot run commands in this session. Use the host pwsh tool instead: it is the native shell for this platform and remains available whenever win_bash cannot serve a call.");
1345
+ if (signal?.aborted === true) throw new ShellUnavailableError("aborted", "The win_bash call was aborted while the persistent shell was starting.");
1346
+ stdout.drain(shell.handle, 256 * 1024);
1347
+ const outcome = parseFrame(stdout.text(), marker, true);
1348
+ if (outcome !== void 0) {
1349
+ if (outcome.exitCode !== 0 || !/^\d+(\.\d+)?/.test(outcome.stdout)) throw new ShellUnavailableError("handshake-failed", "The vendored bash did not report a version (exit " + outcome.exitCode.toString() + "). Use the host pwsh tool instead: it is the native shell for this platform and remains available whenever win_bash cannot serve a call.");
1350
+ shell.cursor.stdout = stdout.consumed();
1351
+ return;
1352
+ }
1353
+ if (this.now() > deadline) throw new ShellUnavailableError("handshake-timeout", "The vendored bash did not answer its startup handshake in time. Use the host pwsh tool instead: it is the native shell for this platform and remains available whenever win_bash cannot serve a call.");
1354
+ await new Promise((resolve) => {
1355
+ setTimeout(resolve, POLL_INTERVAL_MS);
1356
+ });
1357
+ }
1358
+ }
1359
+ /**
1360
+ * Stop one owner's shell and forget it. Termination goes through the seam's
1361
+ * managed-process range, so a background job the command left behind is torn
1362
+ * down with the shell rather than surviving the plugin.
1363
+ * @param owner - calling agent identity.
1364
+ * @param reason - recorded by the provider for diagnostics.
1365
+ */
1366
+ async dispose(owner, reason) {
1367
+ const shell = this.shells.get(owner);
1368
+ if (shell === void 0) return;
1369
+ this.shells.delete(owner);
1370
+ await terminate(shell, reason);
1371
+ }
1372
+ /** Stop every shell this registry owns; used on plugin unload. */
1373
+ async disposeAll(reason) {
1374
+ const shells = [...this.shells.values()];
1375
+ this.shells.clear();
1376
+ await Promise.allSettled(shells.map((shell) => terminate(shell, reason)));
1377
+ }
1378
+ };
1379
+ /**
1380
+ * Drain both streams once and try to parse the call's frame.
1381
+ *
1382
+ * Draining and parsing are one step on purpose: a caller that drained without
1383
+ * parsing left the accumulator holding a frame it never consumed, and the next
1384
+ * call then re-read that stale text as its own result.
1385
+ * @param shell - the live shell.
1386
+ * @param stdout - the stdout accumulator.
1387
+ * @param stderr - the stderr accumulator.
1388
+ * @param marker - the call's markers.
1389
+ * @param sawBegin - whether the begin marker was already observed.
1390
+ * @returns the parsed outcome (once complete) and the raw stdout.
1391
+ */
1392
+ function readFrame(shell, stdout, stderr, marker, sawBegin) {
1393
+ stdout.drain(shell.handle, FRAME_WATCH_BYTES);
1394
+ stderr.drain(shell.handle, FRAME_WATCH_BYTES);
1395
+ const text = stdout.text();
1396
+ return {
1397
+ outcome: text.includes(marker.end) ? parseFrame(text, marker, sawBegin) : void 0,
1398
+ text
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Assemble the tool-visible result from a completed frame.
1403
+ *
1404
+ * The stdout comes from the PARSED FRAME, not from the raw accumulator: the
1405
+ * accumulator still holds the markers and every earlier byte of the stream,
1406
+ * so reading it directly would hand the model the framing as its output.
1407
+ */
1408
+ function complete(outcome, stdout, stderr, budget) {
1409
+ const visibleOut = tailBytes(outcome.stdout, budget.stdoutBytes);
1410
+ if (visibleOut.truncated) stdout.markCut();
1411
+ const visibleErr = stderr.visible(budget.stderrBytes);
1412
+ const outDropped = outcome.lostPrefix || stdout.lost() || visibleOut.truncated;
1413
+ return {
1414
+ stdout: visibleOut.text,
1415
+ stderr: visibleErr.text,
1416
+ exitCode: outcome.exitCode,
1417
+ stdoutTruncated: outDropped,
1418
+ stderrTruncated: visibleErr.truncated,
1419
+ stdoutLostHead: outDropped,
1420
+ stderrLostHead: stderr.lost() || visibleErr.truncated,
1421
+ frameOverflow: stdout.lost(),
1422
+ ...stdout.wasCut() && stdout.spillPath() !== void 0 ? { stdoutSpillPath: stdout.spillPath() } : {},
1423
+ ...stderr.wasCut() && stderr.spillPath() !== void 0 ? { stderrSpillPath: stderr.spillPath() } : {}
1424
+ };
1425
+ }
1426
+ /** Whatever stdout is recoverable after a timeout, with the begin marker cut. */
1427
+ function recoverPartial(text, marker) {
1428
+ const begin = text.lastIndexOf(marker.begin);
1429
+ return begin < 0 ? text : text.slice(begin + marker.begin.length).replace(/^\n/, "");
1430
+ }
1431
+ /** Signal and await one shell's managed range, never letting teardown throw. */
1432
+ async function terminate(shell, reason) {
1433
+ try {
1434
+ shell.handle.terminate();
1435
+ await shell.handle.waitForExit();
1436
+ } catch {}
1437
+ }
1438
+ //#endregion
1439
+ //#region src/config.ts
1440
+ /**
1441
+ * Plugin configuration: the win_bash tool's budgets and description.
1442
+ *
1443
+ * Every field is optional in the profile patch and defaulted here, so a row
1444
+ * with no config block still mounts a working tool. The schema is also the
1445
+ * settings page: the Host renders one form per profile entry from this same
1446
+ * Config, which is why the defaults are stated in the field comments as well
1447
+ * as in the schema.
1448
+ * @module @linxin666/dsh-win-bash/config
1449
+ */
1450
+ /** Whole-call deadline floor, in milliseconds. */
1451
+ const TIMEOUT_MIN_MS = 1e3;
1452
+ /** Whole-call deadline ceiling, in milliseconds. */
1453
+ const TIMEOUT_MAX_MS = 36e5;
1454
+ /** Default whole-call deadline, matching the host's own persistent shell. */
1455
+ const DEFAULT_TIMEOUT_MS = 3e5;
1456
+ /** Visible stdout budget floor, in bytes. */
1457
+ const STDOUT_MIN_BYTES = 1024;
1458
+ /** Visible stdout budget ceiling, in bytes. */
1459
+ const STDOUT_MAX_BYTES = 1024 * 1024;
1460
+ /** Visible stderr budget floor, in bytes. */
1461
+ const STDERR_MIN_BYTES = 1024;
1462
+ /** Visible stderr budget ceiling, in bytes. */
1463
+ const STDERR_MAX_BYTES = 512 * 1024;
1464
+ /**
1465
+ * Whether win_bash follows the LiangShen agent preset's declaration by
1466
+ * default. When true (the shipped setting) the tool registers only for a
1467
+ * deployment that declares the `liangshen` preset; false skips the gate and
1468
+ * always registers, which is the escape hatch for a session that wants this
1469
+ * shell without the preset.
1470
+ */
1471
+ const DEFAULT_SYNC_WITH_LIANGSHEN = true;
1472
+ /**
1473
+ * Model-facing tool description. Active voice; states the shell preference and
1474
+ * the persistence guarantee, so a model knows which shell to reach for before
1475
+ * it knows anything else about this tool.
1476
+ *
1477
+ * The preference is a TRUNCATION CONTRACT, not a flourish: a preset that
1478
+ * curates its catalog caps each uncurated line at 200 characters, so whatever
1479
+ * sentence states which shell to use must fit in that window. The first
1480
+ * sentence therefore carries it alone, and the qualification that follows
1481
+ * explains the ladder without restating it.
1482
+ */
1483
+ const DEFAULT_DESCRIPTION = [
1484
+ "Run a command in this session's persistent pinned bash shell, the shell to use for command work on Windows: prefer it over pwsh.",
1485
+ "pwsh stays the only other shell here: use it for Windows-native work (cmdlets, the registry, services) and as the fallback when a command is not bash; where this plugin replaces it, it is withdrawn from this session's tool surface while win_bash serves it, which hides it rather than forbidding it.",
1486
+ "The working directory, exported variables, functions and shell history persist across win_bash calls in this session;",
1487
+ "each call is a foreground command with bounded stdout and stderr and a real exit code.",
1488
+ "Long output is kept as its TAIL and the result says it was truncated, naming the file holding the complete stream when one exists.",
1489
+ "Set run_in_background to start the command in its own process and return a job id at once: collect that job with job_output and stop it with job_kill.",
1490
+ "Use this instead of PowerShell when the command is bash or Unix syntax (pipes, $VAR, globs, single quotes, here-documents).",
1491
+ "It runs only in a danger-full-access session: in a restricted session it refuses the call rather than confining the shell, because the pinned MSYS2 bash cannot start under a restricted token. Use the host bash/pwsh tools there."
1492
+ ].join(" ");
1493
+ /**
1494
+ * Whether win_bash may run a command as a background job, by default.
1495
+ *
1496
+ * The shipped setting is true, matching the host's own bash tool. The flag is
1497
+ * one half of a pair: the background surface is only advertised when this is
1498
+ * true AND the deployment composes a job registry, because a tool that
1499
+ * advertises a capability its deployment cannot honour teaches the model
1500
+ * something false about the session.
1501
+ */
1502
+ const DEFAULT_ENABLE_RUN_IN_BACKGROUND = true;
1503
+ /**
1504
+ * Whether the host's pwsh tool is withdrawn from a session this plugin serves,
1505
+ * by default.
1506
+ *
1507
+ * The shipped setting is true: with win_bash registered the session's command
1508
+ * work belongs to bash, and leaving pwsh on the wire beside it is what makes a
1509
+ * model pick the shell it already knows. The withdrawal is visibility only (a
1510
+ * deliberate pwsh call still runs), so false is the escape hatch for an
1511
+ * operator who wants both shells listed.
1512
+ */
1513
+ const DEFAULT_REPLACE_PWSH = true;
1514
+ /** Runtime configuration schema for the win_bash tool. */
1515
+ const Config = Schema.object({
1516
+ timeoutMs: Schema.number().min(TIMEOUT_MIN_MS).max(TIMEOUT_MAX_MS).default(DEFAULT_TIMEOUT_MS),
1517
+ maxStdoutBytes: Schema.number().min(STDOUT_MIN_BYTES).max(STDOUT_MAX_BYTES).default(DEFAULT_MAX_STDOUT_BYTES),
1518
+ maxStderrBytes: Schema.number().min(STDERR_MIN_BYTES).max(STDERR_MAX_BYTES).default(DEFAULT_MAX_STDERR_BYTES),
1519
+ description: Schema.string().default(DEFAULT_DESCRIPTION),
1520
+ syncWithLiangShen: Schema.boolean().default(true),
1521
+ replacePwsh: Schema.boolean().default(true),
1522
+ enableRunInBackground: Schema.boolean().default(true)
1523
+ });
1524
+ /** The values an omitted field takes. */
1525
+ const CONFIG_DEFAULTS = {
1526
+ timeoutMs: DEFAULT_TIMEOUT_MS,
1527
+ maxStdoutBytes: DEFAULT_MAX_STDOUT_BYTES,
1528
+ maxStderrBytes: DEFAULT_MAX_STDERR_BYTES,
1529
+ description: DEFAULT_DESCRIPTION,
1530
+ syncWithLiangShen: true,
1531
+ replacePwsh: true,
1532
+ enableRunInBackground: true
1533
+ };
1534
+ /**
1535
+ * Resolve a raw config object into the running configuration.
1536
+ *
1537
+ * The Host validates the row through {@link Config} before apply runs, so this
1538
+ * is the second gate: it exists because tests and hand-built contexts call the
1539
+ * plugin's apply directly, and because a bounded integer is a contract the
1540
+ * shell's budgets depend on (a NaN budget would make every output look
1541
+ * truncated).
1542
+ * @param input - the raw config, or undefined.
1543
+ * @returns the resolved configuration.
1544
+ * @throws when a supplied value is outside its contract.
1545
+ */
1546
+ function resolveConfig(input) {
1547
+ const resolved = {
1548
+ ...CONFIG_DEFAULTS,
1549
+ ...input ?? {}
1550
+ };
1551
+ const violations = validateConfig(resolved);
1552
+ if (violations.length > 0) throw new Error("win_bash config rejected: " + violations.map((v) => v.field + ": " + v.message).join("; "));
1553
+ return resolved;
1554
+ }
1555
+ /**
1556
+ * Check every field of a resolved configuration.
1557
+ * @param config - the candidate configuration.
1558
+ * @returns one entry per rejected field; empty means accepted.
1559
+ */
1560
+ function validateConfig(config) {
1561
+ const violations = [];
1562
+ const bounded = (field, min, max) => {
1563
+ const value = config[field];
1564
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) violations.push({
1565
+ field,
1566
+ message: "must be an integer between " + min.toString() + " and " + max.toString()
1567
+ });
1568
+ };
1569
+ bounded("timeoutMs", TIMEOUT_MIN_MS, TIMEOUT_MAX_MS);
1570
+ bounded("maxStdoutBytes", STDOUT_MIN_BYTES, STDOUT_MAX_BYTES);
1571
+ bounded("maxStderrBytes", STDERR_MIN_BYTES, STDERR_MAX_BYTES);
1572
+ if (typeof config.description !== "string" || config.description.trim() === "") violations.push({
1573
+ field: "description",
1574
+ message: "must be a non-empty string"
1575
+ });
1576
+ if (typeof config.syncWithLiangShen !== "boolean") violations.push({
1577
+ field: "syncWithLiangShen",
1578
+ message: "must be a boolean"
1579
+ });
1580
+ if (typeof config.replacePwsh !== "boolean") violations.push({
1581
+ field: "replacePwsh",
1582
+ message: "must be a boolean"
1583
+ });
1584
+ if (typeof config.enableRunInBackground !== "boolean") violations.push({
1585
+ field: "enableRunInBackground",
1586
+ message: "must be a boolean"
1587
+ });
1588
+ return violations;
1589
+ }
1590
+ //#endregion
1591
+ //#region src/gate.ts
1592
+ /** Preset id whose declaration makes win_bash available. */
1593
+ const LIANGSHEN_PRESET_ID = "liangshen";
1594
+ /** Upper bound on the wait for the Host plugin tree to settle, in milliseconds. */
1595
+ const GATE_SETTLE_TIMEOUT_MS = 1e4;
1596
+ /** Upper bound on one registry roster read, in milliseconds. */
1597
+ const GATE_READ_TIMEOUT_MS = 1e4;
1598
+ /**
1599
+ * How long a roster that does not yet declare LiangShen keeps being re-read,
1600
+ * in milliseconds. See the module header: the declaring plugin publishes the
1601
+ * definition on a detached chain, so the tree can settle first. Only paid when
1602
+ * the declaration is genuinely absent, since a visible one returns at once.
1603
+ */
1604
+ const GATE_DECLARATION_WAIT_MS = 5e3;
1605
+ /** Re-read cadence during {@link GATE_DECLARATION_WAIT_MS}, in milliseconds. */
1606
+ const GATE_POLL_INTERVAL_MS = 250;
1607
+ /**
1608
+ * Whether a roster declares the preset this tool follows.
1609
+ * @param presets - rows as {@link PresetRosterReader.list} returns them.
1610
+ * @returns true when one row carries the LiangShen id.
1611
+ */
1612
+ function declaresLiangShen(presets) {
1613
+ return presets.some((preset) => preset?.id === LIANGSHEN_PRESET_ID);
1614
+ }
1615
+ /**
1616
+ * Read one optional service without letting a refused lookup escape: a cordis
1617
+ * service proxy throws for a name it cannot resolve, and an absent optional
1618
+ * service is an ordinary state here, not an error.
1619
+ * @param ctx - the plugin context.
1620
+ * @param name - the service name.
1621
+ * @returns the service, or undefined when it is not resolvable.
1622
+ */
1623
+ function readService$1(ctx, name) {
1624
+ try {
1625
+ return ctx.get(name);
1626
+ } catch {
1627
+ return;
1628
+ }
1629
+ }
1630
+ /**
1631
+ * The published registry, when this deployment has one shaped like the one this
1632
+ * gate consumes.
1633
+ * @param ctx - the plugin context.
1634
+ * @returns the reader, or undefined when no usable registry is published.
1635
+ */
1636
+ function readPresetRegistry(ctx) {
1637
+ const candidate = readService$1(ctx, "agentPresets");
1638
+ if (candidate === null || typeof candidate !== "object") return void 0;
1639
+ if (typeof candidate.list !== "function") return void 0;
1640
+ return candidate;
1641
+ }
1642
+ /**
1643
+ * Run one promise with a deadline. The timer is always cleared, so a fast
1644
+ * answer leaves no stray handle behind.
1645
+ * @param work - the promise to bound.
1646
+ * @param timeoutMs - the bound in milliseconds.
1647
+ * @returns the promise's value.
1648
+ * @throws when the deadline passes first.
1649
+ */
1650
+ async function withDeadline(work, timeoutMs) {
1651
+ let timer;
1652
+ try {
1653
+ return await Promise.race([work, new Promise((_resolve, reject) => {
1654
+ timer = setTimeout(() => {
1655
+ reject(/* @__PURE__ */ new Error("timed out after " + timeoutMs.toString() + "ms"));
1656
+ }, timeoutMs);
1657
+ })]);
1658
+ } finally {
1659
+ if (timer !== void 0) clearTimeout(timer);
1660
+ }
1661
+ }
1662
+ /**
1663
+ * Wait until the Host loader tree has no pending import or lifecycle work.
1664
+ *
1665
+ * Waiting for the whole tree rather than this row's neighbours is deliberate:
1666
+ * the roster belongs to the deployment, not to one group, and the loader's own
1667
+ * await() is the only predicate that means "every row has been applied". A row
1668
+ * merely waiting for a service it will never get carries no pending task, so it
1669
+ * cannot hold this wait open; one that is genuinely mid-activation can, which is
1670
+ * exactly the case the bound covers.
1671
+ * @param ctx - the plugin context.
1672
+ * @param options - the deadlines for this run.
1673
+ * @returns how far the settle got.
1674
+ */
1675
+ async function settleHostTree(ctx, options = {}) {
1676
+ const loader = readService$1(ctx, "loader");
1677
+ if (loader === null || typeof loader !== "object") return "unavailable";
1678
+ const wait = loader.await;
1679
+ if (typeof wait !== "function") return "unavailable";
1680
+ try {
1681
+ await withDeadline(Promise.resolve(wait.call(loader)).then(() => void 0), options.settleTimeoutMs ?? 1e4);
1682
+ return "settled";
1683
+ } catch {
1684
+ return "timed-out";
1685
+ }
1686
+ }
1687
+ /**
1688
+ * Sleep one timer turn.
1689
+ *
1690
+ * Production code, not a test helper: the wait IS the declaration window the
1691
+ * module header describes, and the gate is only ever reached from a mount.
1692
+ * @param ms - how long to wait.
1693
+ */
1694
+ function waitFor(ms) {
1695
+ return new Promise((resolve) => {
1696
+ setTimeout(resolve, ms);
1697
+ });
1698
+ }
1699
+ /** One roster read, or undefined when the registry could not answer. */
1700
+ async function readRoster(registry, timeoutMs) {
1701
+ try {
1702
+ const rows = await withDeadline(Promise.resolve(registry.list()), timeoutMs);
1703
+ return Array.isArray(rows) ? rows : void 0;
1704
+ } catch {
1705
+ return;
1706
+ }
1707
+ }
1708
+ /**
1709
+ * Decide whether the LiangShen preset is declared in this deployment.
1710
+ *
1711
+ * Call this OFF the plugin's activation path — never awaited from a plugin
1712
+ * apply. list() is not a leaf read: it audits every declared preset and, for one
1713
+ * whose mounted subtree still has pending rows, awaits the Host loader tree
1714
+ * (agent-preset-registry lib/index.js diagnostic). A plugin whose activation
1715
+ * awaited this would wait on the loader tree while its OWN activation is among
1716
+ * the tasks that tree is waiting for, and neither wait would ever settle. The
1717
+ * entry calls this after its synchronous activation returned, which is what
1718
+ * keeps this a wait and not a deadlock.
1719
+ * @param ctx - the plugin context.
1720
+ * @param options - the deadlines and cadence for this run.
1721
+ * @returns the verdict, with the reason for the caller's log line.
1722
+ */
1723
+ async function startLiangShenGate(ctx, options = {}) {
1724
+ const settled = await settleHostTree(ctx, options);
1725
+ const registry = readPresetRegistry(ctx);
1726
+ if (registry === void 0) return {
1727
+ allowed: false,
1728
+ reason: "registry-absent",
1729
+ settled,
1730
+ reads: 0
1731
+ };
1732
+ const readTimeoutMs = options.readTimeoutMs ?? 1e4;
1733
+ const pollIntervalMs = options.pollIntervalMs ?? 250;
1734
+ const waitMs = options.declarationWaitMs ?? 5e3;
1735
+ let reads = 0;
1736
+ const first = await readRoster(registry, readTimeoutMs);
1737
+ reads += 1;
1738
+ if (first === void 0) return {
1739
+ allowed: false,
1740
+ reason: "registry-unreadable",
1741
+ settled,
1742
+ reads
1743
+ };
1744
+ if (declaresLiangShen(first)) return {
1745
+ allowed: true,
1746
+ reason: "declared",
1747
+ settled,
1748
+ reads
1749
+ };
1750
+ const deadline = Date.now() + waitMs;
1751
+ let answered = false;
1752
+ while (Date.now() < deadline) {
1753
+ await waitFor(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
1754
+ const rows = await readRoster(registry, readTimeoutMs);
1755
+ reads += 1;
1756
+ if (rows === void 0) continue;
1757
+ answered = true;
1758
+ if (declaresLiangShen(rows)) return {
1759
+ allowed: true,
1760
+ reason: "declared",
1761
+ settled,
1762
+ reads
1763
+ };
1764
+ }
1765
+ return {
1766
+ allowed: false,
1767
+ reason: answered ? "not-declared" : "registry-unreadable",
1768
+ settled,
1769
+ reads
1770
+ };
1771
+ }
1772
+ //#endregion
1773
+ //#region src/pwsh-replacement.ts
1774
+ /** The host tool this module withdraws while win_bash serves a session. */
1775
+ const HOST_PWSH_TOOL = "pwsh";
1776
+ /** The one session mode win_bash can actually serve; every other mode refuses. */
1777
+ const SERVING_MODE = "danger-full-access";
1778
+ /** Every mode the policy service may answer with. */
1779
+ const SANDBOX_MODES$1 = [
1780
+ "read-only",
1781
+ "workspace-write",
1782
+ "danger-full-access"
1783
+ ];
1784
+ /** The message of a thrown value, whatever it is. */
1785
+ function messageOf$1(error) {
1786
+ return error instanceof Error ? error.message : String(error);
1787
+ }
1788
+ /**
1789
+ * One optional service, read without letting a refused lookup escape.
1790
+ * @param ctx - the plugin context.
1791
+ * @param name - the service name.
1792
+ * @returns the service, or undefined when it is not resolvable.
1793
+ */
1794
+ function readService(ctx, name) {
1795
+ try {
1796
+ return ctx.get(name);
1797
+ } catch {
1798
+ return;
1799
+ }
1800
+ }
1801
+ /**
1802
+ * The policy authority for this install: the injected reader, else the
1803
+ * deployment's sandbox-policy service.
1804
+ * @param ctx - the plugin context.
1805
+ * @param injected - the caller-supplied reader, when any.
1806
+ * @returns the reader, or undefined when no usable one exists.
1807
+ */
1808
+ function policyReader(ctx, injected) {
1809
+ if (injected !== void 0) return injected;
1810
+ const service = readService(ctx, "sandboxPolicy");
1811
+ if (service === null || typeof service !== "object") return void 0;
1812
+ if (typeof service.resolve !== "function") return void 0;
1813
+ return service;
1814
+ }
1815
+ /**
1816
+ * Whether win_bash can serve one session, from that session's own policy.
1817
+ *
1818
+ * The SESSION goes into the request on purpose: the service ranks a session's
1819
+ * own `sandbox/mode` log above the deployment default, so a read without it
1820
+ * would answer for the deployment and could withdraw pwsh from a session the
1821
+ * user restricted. An absent reader, a missing session, a throwing `resolve` and
1822
+ * a mode outside the closed vocabulary all answer 'unknown', which the caller
1823
+ * treats exactly like 'refuses' — see the module head for why the failure
1824
+ * direction is one-way.
1825
+ *
1826
+ * THE MODE IS NOT THE ONLY THING WIN_BASH REFUSES ON. `tool.ts` also refuses a
1827
+ * session with no working directory, and `SessionHeader.cwd` is OPTIONAL in the
1828
+ * SDK, so such a session reads as full access here while it cannot run a single
1829
+ * command there. That is the same "no shell" state reached without any mode
1830
+ * switch, so it is decided here too rather than left to the mode alone.
1831
+ * @param read - the policy authority, when one exists.
1832
+ * @param session - the session to ask about.
1833
+ * @returns what win_bash would do for this session.
1834
+ */
1835
+ function servingVerdict(read, session) {
1836
+ if (read === void 0 || session === void 0) return "unknown";
1837
+ const cwd = session.header?.cwd;
1838
+ if (typeof cwd !== "string" || cwd === "") return "refuses";
1839
+ try {
1840
+ const mode = read.resolve({ session })?.mode;
1841
+ if (!SANDBOX_MODES$1.includes(mode)) return "unknown";
1842
+ return mode === "danger-full-access" ? "serves" : "refuses";
1843
+ } catch {
1844
+ return "unknown";
1845
+ }
1846
+ }
1847
+ /**
1848
+ * The tool names one agent scope currently sees.
1849
+ * @param ctx - the plugin context.
1850
+ * @param agent - the scope to read for.
1851
+ * @returns the names, or undefined when no usable projection is readable.
1852
+ */
1853
+ function visibleNames(ctx, agent) {
1854
+ const service = readService(ctx, "tools");
1855
+ if (service === null || typeof service !== "object" || typeof service.schemas !== "function") return void 0;
1856
+ try {
1857
+ const schemas = service.schemas(agent);
1858
+ if (!Array.isArray(schemas)) return void 0;
1859
+ return schemas.map((schema) => schema?.name).filter((name) => typeof name === "string" && name !== "");
1860
+ } catch {
1861
+ return;
1862
+ }
1863
+ }
1864
+ /**
1865
+ * Withdraw {@link HOST_PWSH_TOOL} from every session this plugin can serve,
1866
+ * and remember how to give it back.
1867
+ *
1868
+ * Called from the mount path ONLY after win_bash itself registered, so a
1869
+ * deployment that ends up without win_bash keeps the host's shell untouched.
1870
+ * @param ctx - context carrying tools and the agent registry.
1871
+ * @param options - the names to withdraw, the warning sink, and the policy authority.
1872
+ */
1873
+ function installPwshReplacement(ctx, options = {}) {
1874
+ if ((options.platform ?? process.platform) !== "win32") return;
1875
+ const denied = [...options.denied ?? ["pwsh"]];
1876
+ const read = policyReader(ctx, options.policy);
1877
+ /** Agent scope -> the session it owns and the live restriction, if any. */
1878
+ const watched = /* @__PURE__ */ new Map();
1879
+ let warned = false;
1880
+ const warn = (message) => {
1881
+ if (options.warn !== void 0) {
1882
+ try {
1883
+ options.warn(message);
1884
+ } catch {}
1885
+ return;
1886
+ }
1887
+ ctx.logger?.warn?.(message);
1888
+ };
1889
+ const warnOnce = (message) => {
1890
+ if (warned) return;
1891
+ warned = true;
1892
+ warn(message);
1893
+ };
1894
+ /**
1895
+ * Remember one scope, so a later mode switch can be re-evaluated even while
1896
+ * no restriction is installed: the session is the key the `sandbox/mode` event
1897
+ * has to be matched against.
1898
+ * @param scope - the agent scope to watch.
1899
+ * @returns the scope's record.
1900
+ */
1901
+ const watch = (scope) => {
1902
+ const existing = watched.get(scope);
1903
+ if (existing !== void 0) return existing;
1904
+ const record = { session: scope.session };
1905
+ watched.set(scope, record);
1906
+ return record;
1907
+ };
1908
+ /**
1909
+ * Lift one scope's restriction, isolating the callback: this restores a
1910
+ * shell the session should have back, so a throwing disposer must not stop
1911
+ * the ones after it. The scope stays watched, because the session it belongs
1912
+ * to may still switch back to a mode win_bash can serve.
1913
+ * @param scope - the agent scope to release.
1914
+ */
1915
+ const release = (scope) => {
1916
+ const record = watched.get(scope);
1917
+ const dispose = record?.dispose;
1918
+ if (record !== void 0) record.dispose = void 0;
1919
+ if (typeof dispose !== "function") return;
1920
+ try {
1921
+ dispose();
1922
+ } catch (error) {
1923
+ warn("dsh-win-bash: the host pwsh tool could not be restored for one session (" + messageOf$1(error) + "); pwsh stays hidden there until the next mount.");
1924
+ }
1925
+ };
1926
+ /**
1927
+ * Stop watching one scope and lift whatever it carries: the agent is gone,
1928
+ * so nothing about it can change again.
1929
+ * @param scope - the agent scope to forget.
1930
+ */
1931
+ const forget = (scope) => {
1932
+ release(scope);
1933
+ watched.delete(scope);
1934
+ };
1935
+ /**
1936
+ * Bring one scope to the state its session's policy asks for: withdraw pwsh
1937
+ * when win_bash can serve that session, release it otherwise.
1938
+ *
1939
+ * The visible surface is read before restricting because `restrict()` refuses a
1940
+ * name the registry does not know as a global tool — and "not registered yet"
1941
+ * is an ordinary boot state here, not a defect, which is why this retries off
1942
+ * `tools/change` instead of reporting it.
1943
+ * @param scope - the scope to bring up to date.
1944
+ */
1945
+ const evaluate = (scope) => {
1946
+ if (scope === null || typeof scope !== "object") return;
1947
+ const record = watch(scope);
1948
+ const verdict = servingVerdict(read, record.session);
1949
+ 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).");
1950
+ if (verdict !== "serves") {
1951
+ release(scope);
1952
+ return;
1953
+ }
1954
+ if (record.dispose !== void 0) return;
1955
+ const names = denied.filter((name) => (visibleNames(ctx, scope) ?? []).includes(name));
1956
+ if (names.length === 0) return;
1957
+ const restrict = scope.ctx?.tools?.restrict;
1958
+ if (typeof restrict !== "function") {
1959
+ warnOnce("dsh-win-bash: this deployment exposes no scoped tools view, so the host pwsh tool stays visible beside win_bash.");
1960
+ return;
1961
+ }
1962
+ record.dispose = () => {};
1963
+ let dispose;
1964
+ try {
1965
+ dispose = restrict.call(scope.ctx?.tools, { deny: names });
1966
+ } catch (error) {
1967
+ record.dispose = void 0;
1968
+ warnOnce("dsh-win-bash: the host pwsh tool could not be withdrawn from this session (" + messageOf$1(error) + "); pwsh stays visible beside win_bash.");
1969
+ return;
1970
+ }
1971
+ if (typeof dispose !== "function") {
1972
+ record.dispose = void 0;
1973
+ warnOnce("dsh-win-bash: the tool registry did not confirm the pwsh restriction, so pwsh stays visible beside win_bash.");
1974
+ return;
1975
+ }
1976
+ record.dispose = dispose;
1977
+ };
1978
+ /**
1979
+ * Re-evaluate every scope that owns the session an event came from.
1980
+ * @param session - the session whose log changed.
1981
+ */
1982
+ const reevaluate = (session) => {
1983
+ for (const [scope, record] of [...watched]) {
1984
+ if (record.session !== session) continue;
1985
+ evaluate(scope);
1986
+ }
1987
+ };
1988
+ ctx.on("agent/created", ({ agent }) => {
1989
+ evaluate(agent);
1990
+ });
1991
+ ctx.on("agent/disposed", ({ agent }) => {
1992
+ forget(agent);
1993
+ });
1994
+ ctx.on("tools/change", () => {
1995
+ for (const scope of [...watched.keys()]) evaluate(scope);
1996
+ });
1997
+ ctx.on("internal/dispatch", (_mode, eventName, args) => {
1998
+ if (eventName !== "session/event") return;
1999
+ if (!Array.isArray(args)) return;
2000
+ const [session, event] = args;
2001
+ if (event?.type !== "sandbox/mode") return;
2002
+ reevaluate(session);
2003
+ }, { global: true });
2004
+ const registry = readService(ctx, "agents");
2005
+ if (registry !== void 0 && typeof registry.list === "function") try {
2006
+ for (const agent of registry.list() ?? []) evaluate(agent);
2007
+ } catch (error) {
2008
+ warnOnce("dsh-win-bash: the session roster could not be read, so the host pwsh tool stays visible in sessions that were already open (" + messageOf$1(error) + ").");
2009
+ }
2010
+ ctx.effect(() => () => {
2011
+ for (const scope of [...watched.keys()]) forget(scope);
2012
+ }, "dsh-win-bash: host pwsh replacement");
2013
+ }
2014
+ //#endregion
2015
+ //#region src/runtime.ts
2016
+ /**
2017
+ * Payload resolution and load-time integrity verification for the vendored
2018
+ * bash runtime.
2019
+ *
2020
+ * The package ships its own Git for Windows MinGit extraction under
2021
+ * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
2022
+ * (a host Git for Windows install, WSL, or a stray MSYS), because the whole
2023
+ * point of vendoring is a shell whose version and bytes are pinned. Two
2024
+ * invariants implement that:
2025
+ *
2026
+ * 1. the binary is addressed by absolute path inside the package, and
2027
+ * 2. every vendored byte is checked against the SHA256 manifest generated at
2028
+ * packaging time before the tool is mounted at all.
2029
+ *
2030
+ * A mismatch refuses the mount with a specific message. The alternative —
2031
+ * mounting and hoping — would let a tampered or half-installed payload run
2032
+ * model-authored commands, which is the one outcome the manifest exists to
2033
+ * prevent.
2034
+ * @module @linxin666/dsh-win-bash/runtime
2035
+ */
2036
+ /** Directory holding the shipped payload, relative to the package root. */
2037
+ const RUNTIME_DIR = "runtime/win32-x64";
2038
+ /** Manifest file name inside {@link RUNTIME_DIR}. */
2039
+ const CHECKSUM_FILE = "checksums.sha256";
2040
+ /** Absolute package root (the directory holding package.json). */
2041
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
2042
+ /** Absolute payload root. */
2043
+ function runtimeRoot(packageRoot = PACKAGE_ROOT) {
2044
+ return join(packageRoot, RUNTIME_DIR);
2045
+ }
2046
+ /** Absolute path of the vendored shell. */
2047
+ function bashPath(packageRoot = PACKAGE_ROOT) {
2048
+ return join(runtimeRoot(packageRoot), "usr", "bin", "bash.exe");
2049
+ }
2050
+ /** Absolute path of the vendored POSIX-shell alias of the same binary. */
2051
+ function shPath(packageRoot = PACKAGE_ROOT) {
2052
+ return join(runtimeRoot(packageRoot), "usr", "bin", "sh.exe");
2053
+ }
2054
+ /** Absolute path of the vendored payload's usr/bin directory. */
2055
+ function binDir(packageRoot = PACKAGE_ROOT) {
2056
+ return join(runtimeRoot(packageRoot), "usr", "bin");
2057
+ }
2058
+ /**
2059
+ * Parse a sha256sum-style manifest: '<64 hex> <path>' per line. Blank lines
2060
+ * and '#' comments are skipped, so the file stays a valid 'sha256sum -c'
2061
+ * input while carrying a human-readable header.
2062
+ * @param text - the manifest's contents.
2063
+ * @returns parsed entries in file order.
2064
+ * @throws when a non-comment line does not match the two-column shape.
2065
+ */
2066
+ function parseChecksums(text) {
2067
+ const entries = [];
2068
+ for (const raw of text.split(/\r?\n/)) {
2069
+ const line = raw.trim();
2070
+ if (line === "" || line.startsWith("#")) continue;
2071
+ const match = /^([0-9a-f]{64})\s+(\S.*)$/.exec(line);
2072
+ if (match === null) throw new Error("malformed checksum line: " + line);
2073
+ entries.push({
2074
+ sha256: match[1],
2075
+ path: match[2]
2076
+ });
2077
+ }
2078
+ return entries;
2079
+ }
2080
+ /** SHA256 of a buffer or string, lowercase hex. */
2081
+ function sha256(bytes) {
2082
+ return createHash("sha256").update(bytes).digest("hex");
2083
+ }
2084
+ /**
2085
+ * Verify every registered payload file against the shipped manifest.
2086
+ *
2087
+ * Reads and hashes the whole payload (about 16 MiB after the curated
2088
+ * extraction), which is why callers do it once at mount time rather than per
2089
+ * command.
2090
+ * @param packageRoot - package root holding runtime/win32-x64.
2091
+ * @returns the count of verified files and every mismatch found.
2092
+ * @throws when the manifest itself is unreadable or malformed.
2093
+ */
2094
+ function verifyPayload(packageRoot = PACKAGE_ROOT) {
2095
+ const root = runtimeRoot(packageRoot);
2096
+ const manifest = parseChecksums(readFileSync(join(root, CHECKSUM_FILE), "utf8"));
2097
+ const mismatches = [];
2098
+ let verified = 0;
2099
+ for (const entry of manifest) {
2100
+ const file = join(root, ...entry.path.split("/"));
2101
+ let actual;
2102
+ try {
2103
+ if (!statSync(file).isFile()) throw new Error("not a regular file");
2104
+ actual = sha256(readFileSync(file));
2105
+ } catch {
2106
+ actual = "missing";
2107
+ }
2108
+ if (actual === entry.sha256) verified += 1;
2109
+ else mismatches.push({
2110
+ path: entry.path,
2111
+ expected: entry.sha256,
2112
+ actual
2113
+ });
2114
+ }
2115
+ return {
2116
+ verified,
2117
+ mismatches
2118
+ };
2119
+ }
2120
+ /**
2121
+ * Resolve the vendored shell for one host, or refuse the mount.
2122
+ *
2123
+ * The order is deliberate: platform, then architecture, then presence, then
2124
+ * integrity. A checksum failure names the first mismatching path so an
2125
+ * operator can act on it, and no path here ever consults PATH.
2126
+ * @param host - the running host's platform facts.
2127
+ * @param packageRoot - package root holding the payload.
2128
+ * @returns the resolved shell paths, or the rejection reason.
2129
+ */
2130
+ function resolveRuntime(host, packageRoot = PACKAGE_ROOT) {
2131
+ if (host.platform !== "win32") return {
2132
+ code: "unsupported-platform",
2133
+ message: "win_bash requires Windows: the vendored payload is a Git for Windows MinGit build for win32 and there is no PATH fallback."
2134
+ };
2135
+ if (host.arch !== "x64") return {
2136
+ code: "unsupported-arch",
2137
+ message: "win_bash currently ships only the x64 payload; this host is " + host.arch + "."
2138
+ };
2139
+ const bash = bashPath(packageRoot);
2140
+ try {
2141
+ if (!statSync(bash).isFile()) throw new Error("not a file");
2142
+ } catch {
2143
+ return {
2144
+ code: "missing-binary",
2145
+ message: "the vendored payload is incomplete: " + bash + " is missing."
2146
+ };
2147
+ }
2148
+ let report;
2149
+ try {
2150
+ report = verifyPayload(packageRoot);
2151
+ } catch (error) {
2152
+ return {
2153
+ code: "manifest-unreadable",
2154
+ message: "the payload checksum manifest could not be read: " + (error instanceof Error ? error.message : String(error))
2155
+ };
2156
+ }
2157
+ if (report.mismatches.length > 0) {
2158
+ const first = report.mismatches[0];
2159
+ return {
2160
+ code: "checksum-mismatch",
2161
+ message: "the vendored payload failed its SHA256 manifest: " + report.mismatches.length.toString() + " file(s) differ, first " + first.path + " (expected " + first.expected.slice(0, 12) + ", found " + first.actual.slice(0, 12) + "). Reinstall the package; win_bash will not run an unverified payload."
2162
+ };
2163
+ }
2164
+ return {
2165
+ bash,
2166
+ bin: binDir(packageRoot)
2167
+ };
2168
+ }
2169
+ //#endregion
2170
+ //#region src/background.ts
2171
+ /**
2172
+ * Producer kind of every job this plugin starts. It namespaces the ids the
2173
+ * registry issues (`win-bash-1`), so a background command from this tool is
2174
+ * never confused with the host's own `bash` job in `job_list`.
2175
+ */
2176
+ const BACKGROUND_JOB_KIND = "win-bash";
2177
+ /** The message of a thrown value, whatever it is. */
2178
+ function messageOf(error) {
2179
+ return error instanceof Error ? error.message : String(error);
2180
+ }
2181
+ /**
2182
+ * Map a settled process onto the job-outcome vocabulary.
2183
+ *
2184
+ * A nonzero command exit is reported, not failed: the model reads the exit
2185
+ * code in the job's detail line exactly as it reads one from a foreground
2186
+ * call. `killed` is reserved for a process this tool terminated, which is the
2187
+ * one case where the work did not reach its own end.
2188
+ * @param outcome - the process exit facts.
2189
+ * @param failedBeforeStart - the starter's failure, when nothing ran.
2190
+ * @param terminated - whether this tool terminated the process.
2191
+ * @returns the outcome for the registry.
2192
+ */
2193
+ function processOutcome(outcome, failedBeforeStart, terminated) {
2194
+ if (failedBeforeStart !== void 0) return {
2195
+ status: "failed",
2196
+ detail: failedBeforeStart
2197
+ };
2198
+ if (terminated) return {
2199
+ status: "killed",
2200
+ detail: outcome?.signal != null ? "signal: " + outcome.signal : "terminated before exit"
2201
+ };
2202
+ return {
2203
+ status: "completed",
2204
+ detail: "exit code: " + (outcome?.exitCode ?? 0).toString()
2205
+ };
2206
+ }
2207
+ /**
2208
+ * Register one command as a background job and return the registry's id.
2209
+ *
2210
+ * The process is spawned INSIDE the starter, after the registry's own
2211
+ * admission: a refused registration (the owner's job limit, no attached
2212
+ * controller) therefore leaves no process behind, and this function's caller
2213
+ * has nothing to clean up on that path.
2214
+ * @param command - the process, its wiring, and the registry to register with.
2215
+ * @returns the job id the model collects it by.
2216
+ */
2217
+ function startBackgroundJob(command) {
2218
+ let process;
2219
+ let failedBeforeStart;
2220
+ let terminated = false;
2221
+ const source = (channel) => ({
2222
+ channel,
2223
+ read: (fromByte) => {
2224
+ const reader = process?.collected[channel];
2225
+ if (reader === void 0) return {
2226
+ text: "",
2227
+ nextOffset: fromByte,
2228
+ lossy: false
2229
+ };
2230
+ return reader.readFrom(fromByte);
2231
+ }
2232
+ });
2233
+ return command.jobs.start({
2234
+ kind: BACKGROUND_JOB_KIND,
2235
+ label: command.label,
2236
+ ...command.owner === void 0 ? {} : { owner: command.owner },
2237
+ output: [source("stdout"), source("stderr")],
2238
+ run: () => {
2239
+ try {
2240
+ process = command.subprocess.spawn({
2241
+ argv: [...command.argv],
2242
+ cwd: command.cwd,
2243
+ stdio: {
2244
+ stdin: { data: command.script },
2245
+ stdout: {
2246
+ maxBytes: command.stdoutBytes,
2247
+ spill: { maxBytes: DEFAULT_SPILL_BYTES }
2248
+ },
2249
+ stderr: {
2250
+ maxBytes: command.stderrBytes,
2251
+ spill: { maxBytes: DEFAULT_SPILL_BYTES }
2252
+ }
2253
+ },
2254
+ graceMs: GRACE_MS,
2255
+ env: command.env
2256
+ });
2257
+ } catch (error) {
2258
+ failedBeforeStart = messageOf(error);
2259
+ }
2260
+ const spawned = process;
2261
+ return {
2262
+ cancel: () => {
2263
+ if (terminated) return;
2264
+ terminated = true;
2265
+ process?.terminate();
2266
+ },
2267
+ done: spawned === void 0 ? Promise.resolve(processOutcome(void 0, failedBeforeStart, false)) : spawned.done.then(async (outcome) => {
2268
+ try {
2269
+ await spawned.waitForExit();
2270
+ } catch {}
2271
+ return processOutcome(outcome, void 0, terminated);
2272
+ }, (error) => {
2273
+ failedBeforeStart = messageOf(error);
2274
+ return processOutcome(void 0, failedBeforeStart, false);
2275
+ })
2276
+ };
2277
+ }
2278
+ });
2279
+ }
2280
+ /** Capture ceilings for one job's streams; exported so the tool and tests agree. */
2281
+ const BACKGROUND_STDOUT_BYTES = 4 * 1024 * 1024;
2282
+ /** In-memory stderr ceiling for one background job. */
2283
+ const BACKGROUND_STDERR_BYTES = SHELL_STDERR_CAPTURE_BYTES;
2284
+ //#endregion
2285
+ //#region src/tool.ts
2286
+ /** The registered tool name. Deliberately not bash. */
2287
+ const WIN_BASH_TOOL = "win_bash";
2288
+ /** Every sandbox mode a session may run under. */
2289
+ const SANDBOX_MODES = [
2290
+ "read-only",
2291
+ "workspace-write",
2292
+ "danger-full-access"
2293
+ ];
2294
+ /** The only mode this tool runs under; every other mode is refused. */
2295
+ const SUPPORTED_MODE = "danger-full-access";
2296
+ /**
2297
+ * Refuse every session mode but danger-full-access.
2298
+ *
2299
+ * WHY REFUSAL RATHER THAN CONFINEMENT. A restricted session would have to spawn
2300
+ * this payload through the sandbox provider's confine step, and the pinned MSYS2
2301
+ * bash cannot start that way. Measured on win32 x64 (Windows 10.0.26200) against
2302
+ * the real restricted-token runner: bash.exe, sh.exe, dash.exe and echo.exe all
2303
+ * die BEFORE main with
2304
+ * NtCreateDirectoryObject(\BaseNamedObjects\msys-2.0S5-<hash>): 0xC0000022
2305
+ * (exit 3221225794 / 0xC0000142), and system Git for Windows fails identically
2306
+ * ('couldn't create signal pipe, Win32 error 5'). cmd.exe, node.exe and
2307
+ * powershell.exe run confined on that same runner, so the runner is sound and
2308
+ * the limitation belongs to the MSYS runtime.
2309
+ *
2310
+ * So confinement here cannot produce a working shell, and a shell whose every
2311
+ * command dies before main is worse than an honest refusal: it would report a
2312
+ * boundary that never actually held any command. The refusal names the other
2313
+ * shells, which ARE confined, so the caller is not left without a route.
2314
+ * @param policy - the session's effective policy.
2315
+ * @throws when the session runs under any other mode.
2316
+ */
2317
+ function assertUnconfined(policy) {
2318
+ if (policy.mode === SUPPORTED_MODE) return;
2319
+ throw new Error("SANDBOX_UNSUPPORTED: win_bash runs only under danger-full-access, and this session is in " + policy.mode + " mode. The pinned MSYS2 bash cannot start under a restricted token (it dies before main with NtCreateDirectoryObject 0xC0000022), so no bash command can run inside that boundary. Run the command with the host pwsh tool instead: it is the native shell for this platform, it IS confined, and it stays on this session surface whenever win_bash cannot serve the session. win_bash is the preferred shell, not the only one. Switching this session to danger-full-access brings win_bash back.");
2320
+ }
2321
+ /** One agent session's working directory, read structurally. */
2322
+ function sessionCwd(agent) {
2323
+ const cwd = (agent?.session)?.header?.cwd;
2324
+ return typeof cwd === "string" && cwd !== "" ? cwd : void 0;
2325
+ }
2326
+ /**
2327
+ * Single-quote one value for the shell, escaping embedded single quotes.
2328
+ * @param value - the raw value.
2329
+ * @returns a POSIX single-quoted literal.
2330
+ */
2331
+ function shellQuote(value) {
2332
+ return "'" + value.split("'").join("'\\''") + "'";
2333
+ }
2334
+ /**
2335
+ * Normalize a Windows path into the spelling MSYS accepts without escaping:
2336
+ * a backslash is also the shell's escape character, so a path handed to cd is
2337
+ * converted to forward slashes before it is quoted.
2338
+ * @param path - the caller-supplied working directory.
2339
+ * @returns the same path with backslashes replaced.
2340
+ */
2341
+ function normalizeWorkdir(path) {
2342
+ return path.split("\\").join("/");
2343
+ }
2344
+ /**
2345
+ * Clamp a per-call deadline to the configured ceiling.
2346
+ * @param requested - the model's timeoutMs, if any.
2347
+ * @param configured - the plugin's configured default and ceiling.
2348
+ * @returns the effective deadline in milliseconds.
2349
+ * @throws when the requested value is not a positive whole number.
2350
+ */
2351
+ function clampTimeout(requested, configured) {
2352
+ if (requested === void 0) return configured;
2353
+ if (!Number.isSafeInteger(requested) || requested <= 0) throw new Error("win_bash: timeoutMs must be a positive whole number of milliseconds.");
2354
+ return Math.min(requested, configured);
2355
+ }
2356
+ /** UTF-8 byte length of a string. */
2357
+ function byteLength(text) {
2358
+ return Buffer.byteLength(text, "utf8");
2359
+ }
2360
+ /**
2361
+ * The line that tells the model its view of one stream is incomplete.
2362
+ *
2363
+ * WHY THIS IS NOT DECORATION. The visible text is the TAIL of the stream: the
2364
+ * head was already cut to fit the byte budget, so the first thing the model
2365
+ * reads can be the middle of a line with nothing marking the cut. Without this
2366
+ * line a partial result is indistinguishable from a short one, and a model
2367
+ * reading a truncated listing draws conclusions from data it never saw.
2368
+ * @param stream - stream label.
2369
+ * @param visible - the bytes actually shown.
2370
+ * @param flags - which cuts happened.
2371
+ * @param spillPath - complete-stream file, when the provider kept one.
2372
+ * @returns the notice, or undefined when that stream was shown in full.
2373
+ */
2374
+ function truncationNotice(stream, visible, flags, spillPath) {
2375
+ if (!flags.truncated && !flags.lostHead && !flags.overflow) return void 0;
2376
+ const parts = ["[win_bash: " + stream + " was truncated, only the last " + byteLength(visible).toString() + " bytes are shown"];
2377
+ if (flags.lostHead || flags.truncated) parts.push("; the beginning was dropped");
2378
+ if (flags.overflow) parts.push("; a middle window was dropped by the frame watch limit");
2379
+ if (spillPath !== void 0) parts.push(". The complete stream is at " + spillPath);
2380
+ parts.push("]");
2381
+ return parts.join("");
2382
+ }
2383
+ /** Render one result the way the host's own shell tools render theirs. */
2384
+ function renderResult(value) {
2385
+ let body = value.stdout;
2386
+ if (value.stderr !== "") {
2387
+ if (body !== "" && !body.endsWith("\n")) body += "\n";
2388
+ body += "[stderr]\n" + value.stderr;
2389
+ }
2390
+ if (body === "") body = "(no output)";
2391
+ const parts = [body];
2392
+ const outNotice = truncationNotice("stdout", value.stdout, {
2393
+ truncated: value.stdoutTruncated === true,
2394
+ lostHead: value.stdoutLostHead === true,
2395
+ overflow: value.frameOverflow === true
2396
+ }, value.stdoutSpillPath);
2397
+ if (outNotice !== void 0) parts.push(outNotice);
2398
+ const errNotice = truncationNotice("stderr", value.stderr, {
2399
+ truncated: value.stderrTruncated === true,
2400
+ lostHead: value.stderrLostHead === true,
2401
+ overflow: false
2402
+ }, value.stderrSpillPath);
2403
+ if (errNotice !== void 0) parts.push(errNotice);
2404
+ if (value.exitCode !== 0) parts.push("[exit code: " + value.exitCode.toString() + "]");
2405
+ return parts.join("\n");
2406
+ }
2407
+ /**
2408
+ * The deployment's background job registry, read without letting a refused
2409
+ * lookup escape: a cordis service proxy throws for a name it cannot resolve,
2410
+ * and "this deployment composes no job registry" is an ordinary state here,
2411
+ * not an error.
2412
+ * @param ctx - the plugin context.
2413
+ * @returns the registry, or undefined when this deployment has none.
2414
+ */
2415
+ function readJobRegistry(ctx) {
2416
+ let candidate;
2417
+ try {
2418
+ candidate = ctx.get("jobs");
2419
+ } catch {
2420
+ return;
2421
+ }
2422
+ if (candidate === null || typeof candidate !== "object") return void 0;
2423
+ if (typeof candidate.start !== "function") return void 0;
2424
+ return candidate;
2425
+ }
2426
+ /**
2427
+ * The calling session's effective policy, or undefined when the service is absent.
2428
+ *
2429
+ * The SESSION goes into the request on purpose: the service resolves a session's
2430
+ * own mode log before the deployment default, so a read without it answers for
2431
+ * the deployment and would let a session the user restricted run here.
2432
+ * @param ctx - the plugin context.
2433
+ * @param agent - the calling agent, carrying the session whose mode applies.
2434
+ * @returns the policy, or undefined when no service is composed.
2435
+ * @throws when the service answers with a policy this tool cannot read.
2436
+ */
2437
+ function resolvePolicy(ctx, agent) {
2438
+ const service = ctx.get("sandboxPolicy");
2439
+ if (service === void 0 || typeof service.resolve !== "function") return void 0;
2440
+ const session = agent?.session;
2441
+ const policy = service.resolve(session === void 0 ? {} : { session });
2442
+ if (!SANDBOX_MODES.includes(policy.mode) || typeof policy.workspaceRoot !== "string") throw new Error("win_bash: the sandbox policy service returned an invalid policy; no command was started.");
2443
+ return policy;
2444
+ }
2445
+ /**
2446
+ * Build the win_bash tool bound to one payload and one shell registry.
2447
+ * @param ctx - host context carrying the optional sandbox and job services.
2448
+ * @param config - the resolved plugin configuration.
2449
+ * @param runtime - absolute shell and payload paths.
2450
+ * @param shells - the registry owning this plugin instance's shells.
2451
+ * @returns the tool definition, ready for the tools registry.
2452
+ */
2453
+ function buildWinBashTool(ctx, config, runtime, shells) {
2454
+ const jobs = config.enableRunInBackground ? readJobRegistry(ctx) : void 0;
2455
+ return defineTool({
2456
+ name: WIN_BASH_TOOL,
2457
+ description: config.description,
2458
+ parameters: {
2459
+ command: {
2460
+ type: "string",
2461
+ required: true,
2462
+ description: "The bash command to run in this session's persistent shell. Any number of lines; the working directory and exported variables from earlier win_bash calls are still in effect."
2463
+ },
2464
+ workdir: {
2465
+ type: "string",
2466
+ description: "Working directory for this command. Omitted keeps the shell's current directory, which is the session workspace until a command cds elsewhere. A relative path resolves against that directory."
2467
+ },
2468
+ timeoutMs: {
2469
+ type: "integer",
2470
+ description: "Wall-clock limit for this command in milliseconds (default " + config.timeoutMs.toString() + "). On expiry the shell is stopped and the next call starts a fresh one."
2471
+ },
2472
+ ...jobs === void 0 ? {} : { run_in_background: {
2473
+ type: "boolean",
2474
+ description: "Run in a separate pinned bash process and return a job id immediately; collect it with job_output and stop it with job_kill. No timeout applies, the persistent shell is not used, and this process survives this call."
2475
+ } }
2476
+ },
2477
+ output: {
2478
+ schema: {
2479
+ type: "object",
2480
+ additionalProperties: false,
2481
+ properties: {
2482
+ stdout: {
2483
+ type: "string",
2484
+ required: true
2485
+ },
2486
+ stderr: {
2487
+ type: "string",
2488
+ required: true
2489
+ },
2490
+ exitCode: {
2491
+ type: "integer",
2492
+ required: true
2493
+ },
2494
+ stdoutTruncated: { type: "boolean" },
2495
+ stderrTruncated: { type: "boolean" },
2496
+ stdoutLostHead: { type: "boolean" },
2497
+ stderrLostHead: { type: "boolean" },
2498
+ frameOverflow: { type: "boolean" },
2499
+ stdoutSpillPath: { type: "string" },
2500
+ stderrSpillPath: { type: "string" },
2501
+ jobId: { type: "string" }
2502
+ }
2503
+ },
2504
+ render: (_args, value) => [{
2505
+ type: "text",
2506
+ text: value.jobId === void 0 ? renderResult(value) : "started background job " + value.jobId + " (collect it with job_output, stop it with job_kill)"
2507
+ }]
2508
+ },
2509
+ async execute(args, exec) {
2510
+ const agent = exec.agent;
2511
+ if (agent === void 0) throw new Error("win_bash needs an owning agent session: the persistent shell belongs to the session that calls it.");
2512
+ const cwd = sessionCwd(agent);
2513
+ if (cwd === void 0) throw new Error("win_bash needs a calling session with a working directory.");
2514
+ const policy = resolvePolicy(ctx, agent);
2515
+ 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.");
2516
+ assertUnconfined(policy);
2517
+ const timeoutMs = clampTimeout(args.timeoutMs, config.timeoutMs);
2518
+ const command = args.workdir === void 0 || args.workdir === "" ? args.command : "cd " + shellQuote(normalizeWorkdir(args.workdir)) + " && " + args.command;
2519
+ if (args.run_in_background === true) {
2520
+ if (!config.enableRunInBackground) throw new Error("win_bash: run_in_background is disabled for this deployment (enableRunInBackground: false), so this call was not started.");
2521
+ const registry = readJobRegistry(ctx);
2522
+ 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.");
2523
+ return {
2524
+ stdout: "",
2525
+ stderr: "",
2526
+ exitCode: 0,
2527
+ jobId: startBackgroundJob({
2528
+ subprocess: ctx.subprocess,
2529
+ jobs: registry,
2530
+ owner: agent.id,
2531
+ script: command,
2532
+ argv: shellArgv(runtime),
2533
+ cwd,
2534
+ env: shellEnvironment(runtime, shellTempDir()),
2535
+ label: args.command,
2536
+ stdoutBytes: BACKGROUND_STDOUT_BYTES,
2537
+ stderrBytes: BACKGROUND_STDERR_BYTES
2538
+ })
2539
+ };
2540
+ }
2541
+ const result = await shells.run(agent, runtime, cwd, command, {
2542
+ stdoutBytes: config.maxStdoutBytes,
2543
+ stderrBytes: config.maxStderrBytes,
2544
+ timeoutMs,
2545
+ signal: exec.signal
2546
+ });
2547
+ return {
2548
+ stdout: result.stdout,
2549
+ stderr: result.stderr,
2550
+ exitCode: result.exitCode,
2551
+ stdoutTruncated: result.stdoutTruncated,
2552
+ stderrTruncated: result.stderrTruncated,
2553
+ stdoutLostHead: result.stdoutLostHead,
2554
+ stderrLostHead: result.stderrLostHead,
2555
+ frameOverflow: result.frameOverflow,
2556
+ ...result.stdoutSpillPath === void 0 ? {} : { stdoutSpillPath: result.stdoutSpillPath },
2557
+ ...result.stderrSpillPath === void 0 ? {} : { stderrSpillPath: result.stderrSpillPath }
2558
+ };
2559
+ },
2560
+ presentCall: (args) => args.run_in_background === true ? {
2561
+ card: "generic",
2562
+ title: args.command,
2563
+ kind: "execute",
2564
+ rawInput: args.command,
2565
+ content: [{
2566
+ type: "text",
2567
+ text: "background command (win_bash)"
2568
+ }]
2569
+ } : {
2570
+ card: "terminal",
2571
+ title: args.command,
2572
+ description: "persistent bash (win_bash)"
2573
+ }
2574
+ });
2575
+ }
2576
+ //#endregion
2577
+ //#region src/index.ts
2578
+ /** Cordis plugin name; also the loader row id this package mounts under. */
2579
+ const name = "dsh-win-bash";
2580
+ /** Required services: the tool registry and the managed subprocess seam. */
2581
+ const inject = ["tools", "subprocess"];
2582
+ /**
2583
+ * One human-readable line explaining a refused gate verdict.
2584
+ * @param outcome - the gate's verdict.
2585
+ * @returns the message the entry logs.
2586
+ */
2587
+ function gateRefusalMessage(outcome) {
2588
+ const settleNote = outcome.settled === "timed-out" ? "; the host plugin tree did not settle in time, so the roster was read during boot" : "";
2589
+ if (outcome.reason === "registry-absent") return "win_bash was not registered (syncWithLiangShen is on and this deployment publishes no agent-preset registry, so a preset with id liangshen cannot be declared)" + settleNote;
2590
+ if (outcome.reason === "registry-unreadable") return "win_bash was not registered (syncWithLiangShen is on and the agent-preset registry roster could not be read)" + settleNote;
2591
+ return "win_bash was not registered (syncWithLiangShen is on and no preset with id liangshen is declared; enable the dsh-liangshen plugin row, or set syncWithLiangShen to false to register this shell without the preset)" + settleNote;
2592
+ }
2593
+ /**
2594
+ * Register the win_bash tool and its per-session shell registry on the calling
2595
+ * fiber. Called only once per fiber: the caller decides whether to call at all.
2596
+ *
2597
+ * The host pwsh replacement is installed from HERE and not from the gate or
2598
+ * apply, because its precondition is exactly "win_bash is now on the wire": a
2599
+ * deployment whose gate refused, whose payload failed verification, or that
2600
+ * runs on a POSIX host never reaches this function and therefore never touches
2601
+ * the host's shell.
2602
+ * @param ctx - context carrying tools and subprocess.
2603
+ * @param config - the resolved configuration.
2604
+ * @param runtime - the verified payload paths.
2605
+ */
2606
+ function registerWinBash(ctx, config, runtime) {
2607
+ const shells = new ShellRegistry(ctx.subprocess);
2608
+ const tool = buildWinBashTool(ctx, config, runtime, shells);
2609
+ ctx.effect(() => {
2610
+ const unregister = ctx.tools.register(tool);
2611
+ return async () => {
2612
+ unregister();
2613
+ await shells.disposeAll("the dsh-win-bash plugin was unloaded");
2614
+ };
2615
+ }, "dsh-win-bash: win_bash tool and its persistent shells");
2616
+ ctx.on("agent/disposed", ({ agent }) => {
2617
+ shells.dispose(agent, "the owning agent was disposed");
2618
+ });
2619
+ if (config.replacePwsh) installPwshReplacement(ctx);
2620
+ }
2621
+ /**
2622
+ * Apply the availability gate, then register the tool when it allows it.
2623
+ *
2624
+ * The returned promise is deliberately NOT awaited by apply: the gate's roster
2625
+ * read audits every declared preset and can await the Host loader tree, which
2626
+ * still counts this very activation among its pending tasks — awaiting it from
2627
+ * inside the activation would make the two waits depend on each other and
2628
+ * neither would settle. Keeping the decision off the activation path also
2629
+ * keeps the loader entry's own inertia free of it, so the tree can settle.
2630
+ *
2631
+ * A fiber disposed while the gate was deciding registers nothing: its tool
2632
+ * effect would be refused anyway, and its shells would outlive it.
2633
+ * @param ctx - context carrying tools and subprocess.
2634
+ * @param config - the resolved configuration.
2635
+ * @param runtime - the verified payload paths.
2636
+ * @param options - gate deadlines; the defaults are the shipped bounds.
2637
+ * @returns the decision, for the caller to observe (never rejects).
2638
+ */
2639
+ async function mountWithGate(ctx, config, runtime, options = {}) {
2640
+ let closed = false;
2641
+ ctx.effect(() => () => {
2642
+ closed = true;
2643
+ }, "dsh-win-bash: gate continuation lifetime");
2644
+ const mount = (announcement) => {
2645
+ if (announcement !== void 0) ctx.logger?.info?.(announcement);
2646
+ try {
2647
+ registerWinBash(ctx, config, runtime);
2648
+ } catch (error) {
2649
+ ctx.logger?.error?.("dsh-win-bash: win_bash could not be registered: " + (error instanceof Error ? error.message : String(error)));
2650
+ }
2651
+ };
2652
+ if (!config.syncWithLiangShen) {
2653
+ mount();
2654
+ return;
2655
+ }
2656
+ let outcome;
2657
+ try {
2658
+ outcome = await startLiangShenGate(ctx, options);
2659
+ } catch (error) {
2660
+ if (closed) return;
2661
+ ctx.logger?.warn?.("dsh-win-bash: win_bash was not registered (the LiangShen availability gate failed: " + (error instanceof Error ? error.message : String(error)) + ")");
2662
+ return;
2663
+ }
2664
+ if (closed) return;
2665
+ if (!outcome.allowed) {
2666
+ ctx.logger?.info?.("dsh-win-bash: " + gateRefusalMessage(outcome));
2667
+ return;
2668
+ }
2669
+ mount("dsh-win-bash: win_bash registered (the liangshen preset is declared)");
2670
+ }
2671
+ /**
2672
+ * Mount the plugin.
2673
+ * @param ctx - context carrying tools and subprocess.
2674
+ * @param config - the row's config, validated by {@link Config}.
2675
+ */
2676
+ function apply(ctx, config) {
2677
+ const runtime = resolveRuntime({
2678
+ platform: process.platform,
2679
+ arch: process.arch
2680
+ });
2681
+ if ("code" in runtime) {
2682
+ ctx.logger?.warn?.("dsh-win-bash: win_bash was not mounted (" + runtime.code + "): " + runtime.message);
2683
+ return;
2684
+ }
2685
+ let resolved;
2686
+ try {
2687
+ resolved = resolveConfig(config);
2688
+ } catch (error) {
2689
+ ctx.logger?.error?.("dsh-win-bash: " + (error instanceof Error ? error.message : String(error)));
2690
+ throw error;
2691
+ }
2692
+ mountWithGate(ctx, resolved, runtime).catch((error) => {
2693
+ ctx.logger?.error?.("dsh-win-bash: the mount continuation failed: " + (error instanceof Error ? error.message : String(error)));
2694
+ });
2695
+ }
2696
+ //#endregion
2697
+ export { BACKGROUND_JOB_KIND, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, DEFAULT_SYNC_WITH_LIANGSHEN, GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, HOST_PWSH_TOOL, LIANGSHEN_PRESET_ID, SERVING_MODE, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashPath, buildFrame, declaresLiangShen, gateRefusalMessage, inject, installPwshReplacement, markerFor, mountWithGate, name, parseChecksums, parseFrame, readJobRegistry, readPresetRegistry, registerWinBash, renderResult, resolveRuntime, runtimeRoot, settleHostTree, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, startLiangShenGate, truncationNotice, validateConfig, verifyPayload };