@lynn123411/dsh-chat-translate 1.3.2 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -9
- package/docs//351/205/215/347/275/256.md +11 -1
- package/lib/client.js +1527 -489
- package/lib/client.js.map +4 -4
- package/lib/index.js +565 -173
- package/lib/index.js.map +4 -4
- package/lib/types/client/index.d.ts +7 -5
- package/lib/types/client/locales.d.ts +51 -4
- package/lib/types/client/reading-settings-page.d.ts +1 -1
- package/lib/types/client/settings/store.d.ts +17 -4
- package/lib/types/client/settings/ui.d.ts +5 -3
- package/lib/types/client/translate/api.d.ts +13 -0
- package/lib/types/client/translate/client-cache.d.ts +6 -1
- package/lib/types/client/translate/hold.d.ts +135 -0
- package/lib/types/client/translate/lazy.d.ts +8 -0
- package/lib/types/client/translate/mount.d.ts +22 -0
- package/lib/types/client/translate/observer.d.ts +57 -0
- package/lib/types/client/translate/think-button.d.ts +19 -0
- package/lib/types/client/translate/think.d.ts +55 -0
- package/lib/types/client/translate/viewport-observer.d.ts +14 -2
- package/lib/types/index.d.ts +11 -18
- package/lib/types/server/adapters/base.d.ts +1 -1
- package/lib/types/server/adapters/openai.d.ts +2 -2
- package/lib/types/server/cache.d.ts +5 -1
- package/lib/types/server/config.d.ts +35 -7
- package/lib/types/server/dispatcher.d.ts +30 -3
- package/lib/types/server/pipeline/mask-tokens.d.ts +54 -48
- package/lib/types/server/pipeline/masking.d.ts +35 -12
- package/lib/types/server/pipeline/think.d.ts +49 -0
- package/lib/types/server/router.d.ts +24 -3
- package/lib/types/server/types.d.ts +18 -1
- package/package.json +23 -10
package/lib/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.3/node_modules/@deepseek-ai/cosmokit/lib/index.js", "../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.2/node_modules/@deepseek-ai/schemastery/lib/index.mjs", "../node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.1.
|
|
4
|
-
"sourcesContent": ["//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */\nfunction deepEqual(a, b, strict) {\n\tif (a === b) return true;\n\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\tif (typeof a !== typeof b) return false;\n\tif (typeof a !== \"object\") return false;\n\tif (!a || !b) return false;\n\tfunction check(test, then) {\n\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t}\n\treturn check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is(\"Date\"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is(\"RegExp\"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {\n\t\tif (a.byteLength !== b.byteLength) return false;\n\t\tconst viewA = new Uint8Array(a);\n\t\tconst viewB = new Uint8Array(b);\n\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\treturn true;\n\t}) ?? Object.keys({\n\t\t...a,\n\t\t...b\n\t}).every((key) => deepEqual(a[key], b[key], strict));\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (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);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn 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));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union };\n", "import { Binary, clone, deepEqual, filterKeys, isNullable, isPlainObject, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nconst resolvers = {};\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n", "import { opendir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n//#region lib/types/index.js\n/**\n* Shared filesystem path helpers for DeepSeek Harness user data.\n*\n* @module @deepseek-ai/dsh-home-paths\n*/\n/** Directory name for the default DeepSeek Harness home under the OS home. */\nconst DSH_HOME_DIR_NAME = \".dsh\";\n/** Stable user-facing display form for the default DeepSeek Harness home. */\nconst DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default DeepSeek Harness home. */\nconst DSH_HOME_ENV = \"DSH_HOME\";\n/**\n* Give a native filesystem watcher one canonical spelling of a path, even\n* when its final components do not exist yet. The deepest existing ancestor\n* is resolved through {@link realpath}; when a suffix is missing, that\n* ancestor is also proved to be an enumerable directory before the suffix is\n* restored. This prevents Windows from treating a regular-file ancestor as\n* ordinary absence, and prevents short-name aliases from being mixed with\n* long paths emitted by the native watcher backend.\n* @param path - Watch target or root, resolved against the current directory.\n* @returns the target with its existing ancestor canonicalized.\n* @throws when ancestor traversal encounters an error other than absence, or\n* the existing ancestor of a missing suffix is not an enumerable directory.\n*/\nasync function canonicalizeWatchPath(path) {\n\tlet current = resolve(path);\n\tconst missing = [];\n\twhile (true) try {\n\t\tconst canonical = await realpath(current);\n\t\tif (missing.length > 0) await (await opendir(canonical)).close();\n\t\treturn join(canonical, ...missing.reverse());\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tconst parent = dirname(current);\n\t\t/* v8 ignore next -- a filesystem root exists, so traversal resolves before this guard */\n\t\tif (parent === current) throw error;\n\t\tmissing.push(basename(current));\n\t\tcurrent = parent;\n\t}\n}\n/**\n* Resolve the default DeepSeek Harness home using Node's platform path rules.\n* @returns the absolute default harness home path.\n*/\nfunction defaultDshHome() {\n\treturn join(homedir(), DSH_HOME_DIR_NAME);\n}\n/**\n* Expand supported tilde prefixes against the operating-system home.\n* @param path - configured path that may begin with `~`, `~/`, or `~\\`.\n* @returns the expanded path, or the original value when no supported prefix is present.\n*/\nfunction expandHomePath(path) {\n\tif (path === \"~\") return homedir();\n\tif (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(homedir(), path.slice(2));\n\treturn path;\n}\n/**\n* Resolve the single-root DeepSeek Harness home.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_HOME`, then\n* `~/.dsh`. The harness keeps all user data under one root. An empty or\n* whitespace-only `$DSH_HOME` is treated as unset, so a blank override never\n* resolves the home to the current working directory.\n* @param configured - explicit harness-home override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_HOME`.\n* @returns the normalized absolute harness home path.\n*/\nfunction resolveDshHome(configured, env = process.env) {\n\tconst fromEnv = env[DSH_HOME_ENV];\n\treturn resolve(expandHomePath(configured ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : defaultDshHome())));\n}\n/**\n* Join path segments onto the resolved DeepSeek Harness home.\n* @param segments - path segments appended to the Harness home; an empty list returns the home itself.\n* @returns the normalized absolute joined path.\n*/\nfunction dshHomePath(...segments) {\n\treturn join(resolveDshHome(), ...segments);\n}\n/**\n* Describe a resolved harness home symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default home is labelled\n* `~/.dsh`, and any configured home is labelled `$DSH_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveDshHome}.\n* @returns `~/.dsh` for the default home, otherwise `$DSH_HOME`.\n*/\nfunction dshHomeDisplay(resolvedHome) {\n\treturn resolvedHome === resolve(defaultDshHome()) ? DEFAULT_DSH_HOME_DISPLAY : `$${DSH_HOME_ENV}`;\n}\n//#endregion\nexport { DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_DIR_NAME, DSH_HOME_ENV, canonicalizeWatchPath, defaultDshHome, dshHomeDisplay, dshHomePath, expandHomePath, resolveDshHome };\n", "import * as fs from 'node:fs/promises';\nimport type { PluginConfig } from './types.ts';\nimport type { CredentialsReader } from './credentials.ts';\n\n/** Hard cap for the translation concurrency pool. */\nexport const MAX_CONCURRENCY = 100;\n\n/** Bounds for the AI channel request timeout. */\nexport const AI_TIMEOUT_MIN = 500;\nexport const AI_TIMEOUT_MAX = 120000;\n\n/**\n * The settings namespace this plugin owns. The user-editable layer lives in\n * the DSH-managed document (~/.dsh/settings.yaml) under this key; the\n * standalone ~/.dsh/dsh-chat-translate-config.json file is legacy (<=1.1).\n */\nexport const SETTINGS_NAMESPACE = 'dsh-chat-translate';\n\nexport const DEFAULT_CONFIG: PluginConfig = {\n enabled: true,\n concurrency: 3,\n timeoutMs: 2000,\n aiTimeoutMs: 30000,\n aiEnabled: true,\n bingEnabled: true,\n baseUrl: '',\n model: '',\n targetLang: 'zh-Hans',\n};\n\n/**\n * Minimal shape of the owner scope returned by `ctx.settings.register()`.\n * Keeping this structural (instead of importing the DSH package) lets tests\n * inject an in-memory fake and keeps the bundle free of host-service code.\n */\nexport interface SettingsScopeLike {\n /** Resolved value: schema defaults, then composition base, then user layer. */\n get(): PluginConfig;\n /** Observe resolved-value changes; returns the disposer. */\n watch(listener: (config: PluginConfig) => void): () => void;\n /** Merge a patch into the user layer and persist through the provider. */\n update(patch: Partial<PluginConfig>): Promise<unknown>;\n}\n\n/**\n * Config facade over the DSH `ctx.settings` service. No file I/O lives here\n * anymore: persistence, atomic writes, external-edit hot reload and the\n * browser-facing describe/mutate API are all owned by DSH itself.\n */\nexport class ConfigManager {\n private scope: SettingsScopeLike;\n private credentials: CredentialsReader;\n\n constructor(scope: SettingsScopeLike, credentials: CredentialsReader) {\n this.scope = scope;\n this.credentials = credentials;\n }\n\n getConfig(): PluginConfig {\n return this.scope.get();\n }\n\n /** Whether the AI channel has every required piece: baseUrl, model and key. */\n isAiConfigured(): boolean {\n const config = this.getConfig();\n return Boolean(\n config.baseUrl.trim() &&\n config.model.trim() &&\n this.credentials.getApiKey()\n );\n }\n\n onConfigChange(listener: (config: PluginConfig) => void): () => void {\n return this.scope.watch(listener);\n }\n\n /**\n * Merge a partial update into the settings namespace. Values are sanitized\n * here (bounds, trimming) so the schema's own constraints act as a second\n * line of defence rather than the only one.\n *\n * @internal Test-only. No production path calls this: the host writes the\n * settings namespace from the browser through the DSH settings service, and\n * this facade is only driven by `scripts/test-*.mjs` (regression suite).\n * Kept (with this marker) so those tests keep exercising the sanitizer.\n */\n async updateConfig(partial: Partial<PluginConfig>): Promise<PluginConfig> {\n await this.scope.update(sanitizePatch({ ...partial }));\n return this.getConfig();\n }\n}\n\n/**\n * Coerce a raw record (legacy config file, HTTP-era partials) into a\n * validated partial config patch. Unknown fields are dropped, type-mismatched\n * values are skipped (the schema default wins), and numerics are clamped \u2014\n * so one bad field never takes down a whole migration.\n */\nexport function sanitizePatch(input: Record<string, unknown>): Partial<PluginConfig> {\n const next: Partial<PluginConfig> = {};\n if (typeof input.enabled === 'boolean') next.enabled = input.enabled;\n if (typeof input.aiEnabled === 'boolean') next.aiEnabled = input.aiEnabled;\n if (typeof input.bingEnabled === 'boolean') next.bingEnabled = input.bingEnabled;\n\n if (typeof input.concurrency === 'number' && Number.isFinite(input.concurrency)) {\n next.concurrency = Math.min(Math.max(Math.round(input.concurrency), 1), MAX_CONCURRENCY);\n }\n if (typeof input.timeoutMs === 'number' && Number.isFinite(input.timeoutMs)) {\n next.timeoutMs = Math.min(Math.max(Math.round(input.timeoutMs), 500), 10000);\n }\n if (typeof input.aiTimeoutMs === 'number' && Number.isFinite(input.aiTimeoutMs)) {\n next.aiTimeoutMs = Math.min(\n Math.max(Math.round(input.aiTimeoutMs), AI_TIMEOUT_MIN),\n AI_TIMEOUT_MAX\n );\n }\n if (typeof input.baseUrl === 'string') next.baseUrl = input.baseUrl.trim();\n if (typeof input.model === 'string') next.model = input.model.trim();\n if (typeof input.targetLang === 'string' && input.targetLang.trim()) {\n next.targetLang = input.targetLang.trim();\n }\n return next;\n}\n\n/**\n * One-shot migration from the pre-1.2 standalone config file. Runs only while\n * the settings namespace has no user layer yet, so values the user edited\n * after upgrading are never overwritten. The legacy file is removed whether\n * or not a migration happened.\n * @returns whether any legacy values were migrated.\n */\nexport async function migrateLegacyConfigFile(\n settings: {\n describe(): Array<{ ns: string; user?: unknown }>;\n update(ns: string, patch: Record<string, unknown>): Promise<unknown>;\n },\n legacyPath: string\n): Promise<boolean> {\n let raw: string;\n try {\n raw = await fs.readFile(legacyPath, 'utf-8');\n } catch {\n return false; // no legacy file \u2014 nothing to do\n }\n\n let legacy: unknown;\n try {\n legacy = JSON.parse(raw);\n } catch {\n // Corrupt legacy file \u2014 drop it and keep schema defaults.\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n if (typeof legacy !== 'object' || legacy === null || Array.isArray(legacy)) {\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n const record = legacy as Record<string, unknown>;\n\n // Never overwrite a user layer the user already has (e.g. edited through\n // the settings UI after upgrading). The legacy file is still retired.\n const descriptor = settings.describe().find((d) => d.ns === SETTINGS_NAMESPACE);\n if (descriptor?.user !== undefined) {\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n\n // Per-field sanitize: known fields only (retired keys like pre-1.1\n // `channels` drop by construction), type-mismatched values skipped, numeric\n // bounds clamped \u2014 one bad field never blocks the rest of the migration.\n const patch = sanitizePatch(record);\n if (Object.keys(patch).length === 0) {\n // Nothing migratable \u2014 retire the file and keep schema defaults.\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n\n try {\n await settings.update(SETTINGS_NAMESPACE, patch);\n } catch (err) {\n // The patch is already sanitized, so a rejection here is a provider-level\n // failure (read-only document, disk trouble). Keep the file so the next\n // boot retries \u2014 destroying the only copy would lose the user's values.\n console.warn('[dsh-chat-translate] Legacy config migration failed; will retry on next boot:', err);\n return false;\n }\n\n await fs.unlink(legacyPath).catch((err) => {\n console.warn('[dsh-chat-translate] Failed to remove legacy config file:', err);\n });\n return true;\n}\n", "/**\n * API-key access through the DSH `ctx.credentials` service.\n *\n * The service owns ~/.dsh/.credentials.yaml (refs section, 0600 perms, env\n * shadowing, cross-process locking). The pre-1.2 hand-rolled YAML parser is\n * gone: reads go through `resolve`, writes through `set`/`unset`, and the\n * host's `credentials/reference-updated` event keeps the sync cache warm.\n */\n\n/** Refs key that holds the translation API key. */\nexport const TRANSLATE_API_KEY_REF = 'TRANSLATE_API_KEY';\n\n/** The sync read face the hot translation path needs. */\nexport interface KeyReader {\n getApiKey(): string;\n}\n\n/** Minimal structural shape of the DSH `ctx.credentials` service. */\nexport interface CredentialsServiceLike {\n /** Resolve a ref to its stored/inherited value; undefined when absent. */\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n /** Status-only view \u2014 never returns the plaintext value. */\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n /** Store a non-empty value under the ref. */\n set(ref: string, value: string): Promise<void>;\n /** Remove the ref from the document. */\n unset(ref: string): Promise<void>;\n}\n\nexport class CredentialsReader implements KeyReader {\n private service: CredentialsServiceLike;\n private cachedKey = '';\n private refreshing: Promise<void> | null = null;\n\n constructor(service: CredentialsServiceLike) {\n this.service = service;\n }\n\n /** Load the API key once; safe to call multiple times. */\n async init(): Promise<void> {\n await this.refresh();\n }\n\n /**\n * Re-read the key from the credentials service. Used at startup and on\n * `credentials/reference-updated` events so an external edit or a write\n * from another surface takes effect immediately.\n */\n async refresh(): Promise<void> {\n if (this.refreshing) return this.refreshing;\n this.refreshing = (async () => {\n try {\n const resolved = await this.service.resolve(TRANSLATE_API_KEY_REF);\n this.cachedKey = (resolved?.value ?? '').trim();\n } catch (err) {\n console.warn('[dsh-chat-translate] Failed to resolve TRANSLATE_API_KEY:', err);\n } finally {\n this.refreshing = null;\n }\n })();\n return this.refreshing;\n }\n\n /** Synchronous cached read \u2014 the hot translation path stays sync. */\n getApiKey(): string {\n return this.cachedKey;\n }\n\n /**\n * Status-only view of the ref (plaintext never crosses the wire).\n *\n * @internal Test-only. The settings UI reads key status through the\n * `credentials` Remote API with its own client-side shape, so nothing in\n * `src/` calls this host-side method; only `scripts/test-*.mjs` do.\n */\n async describe(): Promise<{ configured: boolean; writable: boolean }> {\n try {\n const info = await this.service.describe(TRANSLATE_API_KEY_REF);\n return { configured: info.configured, writable: info.writable };\n } catch {\n return { configured: false, writable: false };\n }\n }\n\n /** Write (or clear) the ref through the DSH credentials service. */\n async setApiKey(apiKey: string): Promise<void> {\n const normalized = apiKey.trim();\n if (normalized) {\n await this.service.set(TRANSLATE_API_KEY_REF, normalized);\n } else {\n await this.service.unset(TRANSLATE_API_KEY_REF);\n }\n // The write committed: set the cache synchronously so the hot path never\n // reads a stale key even if a concurrent refresh() is still in flight,\n // then confirm from the service (which also fans reference-updated).\n this.cachedKey = normalized;\n await this.refresh();\n }\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport { isMaskLeak } from './pipeline/masking.ts';\n\n/** Entries older than this are treated as expired. */\nconst TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\ninterface CacheEntry {\n t: number; // epoch ms; 0 = legacy entry without timestamp (never expires on its own)\n v: string;\n}\n\nexport class LruDiskCache {\n private cache = new Map<string, CacheEntry>();\n private maxEntries: number;\n private filePath: string;\n private saveTimer: NodeJS.Timeout | null = null;\n private dirty = false;\n\n /** Legacy root-level cache file (<=1.1); moved under the plugin subdir. */\n private legacyPath: string;\n\n constructor(maxEntries = 1000) {\n this.maxEntries = maxEntries;\n // Follow the DSH convention of component-owned home subdirectories\n // (sessions/, storages/, attachments/) instead of polluting ~/.dsh.\n // dshHomePath mirrors resolveDshHome exactly: explicit configured home,\n // then $DSH_HOME (tilde-expanded), then ~/.dsh.\n this.filePath = dshHomePath('dsh-chat-translate', 'cache.json');\n this.legacyPath = dshHomePath('dsh-chat-translate-cache.json');\n }\n\n async init(): Promise<void> {\n // One-shot relocation of the pre-1.2 cache file, keeping its value. When\n // the new file already exists (newer cache), the legacy file is retired.\n let readPath = this.filePath;\n try {\n await fs.access(this.filePath);\n // New cache already in place \u2014 the legacy file is just garbage now.\n await fs.unlink(this.legacyPath).catch(() => {});\n } catch {\n // The plugin subdirectory may not exist on first boot; rename fails\n // with ENOENT otherwise, which would silently lose the old cache.\n try {\n await fs.mkdir(path.dirname(this.filePath), { recursive: true });\n await fs.rename(this.legacyPath, this.filePath);\n readPath = this.filePath;\n } catch {\n readPath = this.legacyPath; // rename failed \u2014 read the legacy file directly\n }\n }\n\n try {\n const content = await fs.readFile(readPath, 'utf-8');\n const obj = JSON.parse(content);\n if (obj && typeof obj === 'object') {\n for (const [k, raw] of Object.entries(obj)) {\n if (typeof raw === 'string') {\n // Legacy entry from an older release \u2014 keep it, no known timestamp.\n if (!isMaskLeak(raw)) this.cache.set(k, { t: 0, v: raw });\n } else if (raw && typeof raw === 'object' && typeof (raw as CacheEntry).v === 'string') {\n const entry = raw as CacheEntry;\n // Poisoned translations written before the mask-leak guard existed\n // must not survive a restart: drop them so the text is re-translated.\n if (typeof entry.t === 'number' && Number.isFinite(entry.t) && !isMaskLeak(entry.v)) {\n this.cache.set(k, entry);\n }\n }\n }\n }\n } catch {\n // Ignore missing or corrupt cache file\n }\n\n // Relocation fallback: the legacy file was the read source \u2014 retire it\n // now that its entries are loaded (or proved unreadable).\n if (readPath !== this.filePath) {\n await fs.unlink(this.legacyPath).catch(() => {});\n }\n }\n\n get(key: string): string | undefined {\n const entry = this.cache.get(key);\n if (entry === undefined) return undefined;\n if (entry.t > 0 && Date.now() - entry.t > TTL_MS) {\n this.cache.delete(key);\n return undefined;\n }\n // Safety net for entries that entered the in-memory map before the\n // mask-leak guard (e.g. a warm cache written this session).\n if (isMaskLeak(entry.v)) {\n this.cache.delete(key);\n return undefined;\n }\n // Refresh key in LRU order (re-insert at the end)\n this.cache.delete(key);\n this.cache.set(key, entry);\n return entry.v;\n }\n\n set(key: string, value: string): void {\n if (isMaskLeak(value)) {\n console.warn('[dsh-chat-translate] refusing to cache a translation with a leaked mask placeholder');\n return;\n }\n if (this.cache.has(key)) {\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxEntries) {\n // Remove least recently used entry (first in Map iterator)\n const oldestKey = this.cache.keys().next().value;\n if (oldestKey !== undefined) {\n this.cache.delete(oldestKey);\n }\n }\n this.cache.set(key, { t: Date.now(), v: value });\n this.dirty = true;\n this.scheduleSave();\n }\n\n private scheduleSave(): void {\n if (this.saveTimer) return;\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n if (this.dirty) {\n // flush() owns the dirty flag: cleared only on a committed write, so\n // a failure keeps it set and schedules its own retry.\n this.flush().catch((err) => {\n console.warn('[dsh-chat-translate] Failed to flush cache to disk:', err);\n });\n }\n }, 5000);\n }\n\n async flush(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n\n const tmpPath = `${this.filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;\n try {\n const obj: Record<string, CacheEntry> = {};\n for (const [k, v] of this.cache.entries()) {\n obj[k] = v;\n }\n await fs.mkdir(path.dirname(this.filePath), { recursive: true });\n await fs.writeFile(tmpPath, JSON.stringify(obj, null, 2), 'utf-8');\n await fs.rename(tmpPath, this.filePath);\n // Only clear the dirty flag once the write actually committed; a failed\n // flush must not silently drop pending entries.\n this.dirty = false;\n } catch (err) {\n console.warn('[dsh-chat-translate] Failed to write cache file atomically:', err);\n try {\n await fs.unlink(tmpPath);\n } catch {}\n // Schedule one retry so a transient disk failure does not lose the\n // pending entries; dispose() is the only caller that must not reschedule.\n if (this.dirty) {\n this.scheduleSave();\n }\n }\n }\n\n async dispose(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n if (this.dirty) {\n await this.flush();\n }\n }\n}\n", "/**\n * Mask placeholder tokens \u2014 single source of truth for the wire format, the\n * tolerant matcher and the leftover detector.\n *\n * Wire format: `__DSHMASKx<letters>_<index>__` (e.g. `__DSHMASKxkbdt_3__`).\n *\n * Design constraints, each one a measured failure of the previous\n * `__DSH_MASK_<index>__` format against real MT engines:\n *\n * - No underscore between `DSH` and `MASK`. Small models routinely drop that\n * one separator (`__DSH_MASK_1__` -> `__DSHMASK_1__`), which defeated the\n * old strict unmask regex and leaked the raw token into the UI.\n * - A random letter run (`x<letters>`) makes the token collision-free against\n * the source text and unambiguous to parse: the index is the digit run after\n * the last `_`, so no lookbehind is needed.\n * - The leading/trailing `__` stay: they survive MT and mark the token as\n * emphasis to the model.\n *\n * `matchMaskToken` stays tolerant of the *legacy* format and of the spacing /\n * casing / separator damage observed in the wild, because poisoned translations\n * already sit in the on-disk and browser caches.\n */\n\n/** Random part of the token. Letters only: never confuses the index scan. */\nconst RANDOM_LETTERS = 'abcdefghijklmnopqrstuvwxyz';\n\nexport function randomTokenId(): string {\n let out = '';\n for (let i = 0; i < 4; i++) {\n out += RANDOM_LETTERS[Math.floor(Math.random() * RANDOM_LETTERS.length)];\n }\n return out;\n}\n\nexport interface MaskTokenFormat {\n /** Unique per `mask()` call; embedded in every token of that call. */\n id: string;\n /** Build the placeholder written into the text sent to the translator. */\n token: (index: number) => string;\n}\n\nexport function createMaskTokenFormat(): MaskTokenFormat {\n const id = randomTokenId();\n return {\n id,\n token: (index: number) => `__DSHMASKx${id}_${index}__`,\n };\n}\n\n/**\n * Loose matcher covering every observed engine rewrite:\n *\n * __DSHMASKxkbdt_3__ exact\n * __DSHMASKXKBDT_3__ case folded\n * __DSH MASK xkbdt _ 3__ spaces inserted around the structural underscores\n * __DSHMASKkbdt_3__ the `x` id separator eaten\n * _DSHMASKxkbdt_3_ one boundary underscore dropped\n * __DSH_MASK_3__ / __dsh_mask_3__ legacy format (no random id)\n *\n * Both boundaries and the internal separators are optional, and the `x` id\n * separator may be replaced by whitespace/dot/hyphen. The two index branches\n * stay unambiguous: an id is always a letter run, the index always digits.\n * Capture groups: `[1] = legacy index` (undefined for the current format),\n * `[2] = token id` (undefined for the legacy format), `[3] = current index`.\n */\nexport const MASK_TOKEN_PATTERN_SOURCE =\n '_*\\\\s*DSH\\\\s*_*\\\\s*MASK\\\\s*(?:_?\\\\s*(\\\\d+)|_*[xX]?[\\\\s._-]*([a-z]{2,8})\\\\s*_+\\\\s*(\\\\d+))(?:_{0,2}(?=[^\\\\w]|$))?';\n\nexport interface MaskTokenMatch {\n index: number;\n /** false when the token carried an id from a different `mask()` call. */\n acceptsId: boolean;\n /** Length of the matched token in characters. */\n length: number;\n}\n\n/**\n * Match a single mask token at `start` in `text`.\n *\n * `acceptsId` is false when the token's random id belongs to another masking\n * pass \u2014 the caller must then leave the token untouched, because its index\n * would resolve to unrelated content.\n */\nexport function matchMaskToken(text: string, start: number, id: string): MaskTokenMatch | null {\n const anchored = new RegExp(`^(?:${MASK_TOKEN_PATTERN_SOURCE})`, 'i').exec(text.slice(start));\n if (!anchored) return null;\n\n // Group 1 is the legacy index, group 2 the random id, group 3 the current\n // index. Whichever index group matched, `parseInt` reads it as a plain\n // number: \"0\" and \"xabcd_0\" both resolve to 0.\n const index = Number.parseInt(anchored[1] ?? anchored[3] ?? '', 10);\n if (Number.isNaN(index)) return null;\n\n const tokenId = anchored[2];\n const acceptsId = tokenId === undefined || tokenId.toLowerCase() === id.toLowerCase();\n return { index, acceptsId, length: anchored[0].length };\n}\n\n/** True when translated text still carries a mask token of any format. */\nexport function hasMaskResidue(text: string): boolean {\n if (!text) return false;\n return new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'i').test(text);\n}\n\n/** Every mask-token-looking fragment in `text`, verbatim. */\nexport function maskResidues(text: string): string[] {\n if (!text) return [];\n return text.match(new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'gi')) ?? [];\n}\n\n/**\n * True when `translatedText` exposes a mask token that was NOT already part of\n * `originalText`.\n *\n * A placeholder surviving the round trip is a leak; but a source text that\n * legitimately talks *about* placeholders (this plugin's own documentation,\n * say) must survive translation, so tokens the source already carried are not\n * treated as residue.\n */\nexport function hasNewMaskResidue(originalText: string, translatedText: string): boolean {\n const residues = maskResidues(translatedText);\n if (residues.length === 0) return false;\n\n const presentInSource = new Map<string, number>();\n for (const fragment of maskResidues(originalText)) {\n const key = fragment.toLowerCase();\n presentInSource.set(key, (presentInSource.get(key) ?? 0) + 1);\n }\n for (const fragment of residues) {\n const key = fragment.toLowerCase();\n const remaining = presentInSource.get(key) ?? 0;\n if (remaining === 0) return true;\n presentInSource.set(key, remaining - 1);\n }\n return false;\n}\n", "import {\n createMaskTokenFormat,\n hasMaskResidue,\n hasNewMaskResidue,\n matchMaskToken,\n MASK_TOKEN_PATTERN_SOURCE,\n} from './mask-tokens.ts';\n\nexport interface MaskResult {\n maskedText: string;\n unmask: (translatedText: string) => string;\n}\n\n/** A match that ate an already-inserted mask token. Dropped, never re-masked. */\nconst MASK_MARKER = /DSH\\s*_?\\s*MASK/i;\n\n/** Bound the unmask scanner so a poisoned translation cannot spin forever. */\nconst MAX_UNMASK_PASSES = 10_000;\n\nexport class ContentMaskingPipeline {\n mask(text: string): MaskResult {\n if (!text || typeof text !== 'string') {\n return {\n maskedText: text,\n unmask: (t: string) => t,\n };\n }\n\n const masks: string[] = [];\n const format = createMaskTokenFormat();\n // Rules may only match the original, never-masked text: a match that\n // swallows an inserted token would hide a whole region from unmasking.\n const addMask = (match: string): string => {\n if (MASK_MARKER.test(match)) return match;\n const idx = masks.length;\n masks.push(match);\n return format.token(idx);\n };\n\n let processed = text;\n\n // 1. Multi-line code blocks (```...``` or ~~~...~~~)\n processed = processed.replace(/(?:```|~~~)[\\s\\S]*?(?:```|~~~)/g, (m) => addMask(m));\n\n // 2. Inline code (`...`)\n processed = processed.replace(/`[^`\\n]+`/g, (m) => addMask(m));\n\n // 3. URLs\n processed = processed.replace(/https?:\\/\\/[^\\s)\\];,;\"'<>]+/g, (m) => addMask(m));\n\n // 4. File paths and filenames with known extensions.\n // Every alternative is anchored on a left boundary (`.`/`/` accepted\n // only when preceded by a word char or start) so a match can never start\n // mid-path: `src/server` inside `src/server/dispatcher.ts` used to split\n // the path into `src__DSH_MASK_1__`, masking the slash away.\n processed = processed.replace(\n /(?:\\/[\\w.\\-\\\\\\/]+|(?<=[\\w.\\-])\\.\\.?[\\\\\\/][\\w.\\-\\\\\\/]+|(?<=^|[\\s([{\"'`])[a-zA-Z]:[\\\\\\/][\\w.\\-\\\\\\/]+|(?<![^\\s([{\"'`])\\b(?:[\\w.\\-]+\\/)+[\\w.\\-]+\\.[a-zA-Z0-9]+\\b|(?<![^\\s([{\"'`])\\b[\\w.\\-]+\\.(?:ts|tsx|js|jsx|json|ya?ml|md|py|go|rs|c|cpp|h|hpp|css|scss|html|sh|bash|mjs|cjs|toml|lock|log|env|svg|png|jpe?g|gif|tar|gz|zip|xml|sql)\\b)/g,\n (m) => addMask(m)\n );\n\n // 5. CLI flags / options (--flag, --flag=value, -f)\n processed = processed.replace(\n /(?<=^|[\\s(\\[{\"'])((?:--[a-zA-Z0-9_\\-]+(?:=[^\\s\"'<>]+)?)|(?:-[a-zA-Z0-9]+))(?=[\\s)\\]}\",:;!?]|$)/g,\n (m) => addMask(m)\n );\n\n const unmask = (translatedText: string): string => {\n if (!translatedText || masks.length === 0) {\n return translatedText;\n }\n return replaceMaskTokens(translatedText, format.id, (index) =>\n index >= 0 && index < masks.length ? masks[index] : undefined\n );\n };\n\n return {\n maskedText: processed,\n unmask,\n };\n }\n}\n\n/**\n * Resolve every in-range mask token in `text` through `resolve`.\n *\n * A token whose random id belongs to another masking pass, an out-of-range\n * index and any unmatched text are all kept verbatim; `hasMaskResidue()` on the\n * result is what flags a leaked token.\n */\nexport function replaceMaskTokens(\n text: string,\n id: string,\n resolve: (index: number) => string | undefined\n): string {\n const pattern = new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'i');\n let out = '';\n let cursor = 0;\n let passes = 0;\n\n while (cursor < text.length && passes++ < MAX_UNMASK_PASSES) {\n const candidate = pattern.exec(text.slice(cursor));\n if (!candidate) break;\n\n const start = cursor + candidate.index;\n const match = matchMaskToken(text, start, id);\n // `matchMaskToken` owns the authoritative token length: the scanning and\n // anchored patterns must never disagree on where a token ends.\n const length = match?.length ?? candidate[0].length;\n if (length <= 0) {\n cursor = start + 1;\n continue;\n }\n\n const replacement = match?.acceptsId ? resolve(match.index) : undefined;\n // Not ours (foreign id / out of range): keep the token verbatim.\n out += text.slice(cursor, start) + (replacement ?? text.slice(start, start + length));\n cursor = start + length;\n }\n\n return out + text.slice(cursor);\n}\n\n/**\n * True when a translated string would still show a mask token to the user.\n * Callers use it to discard a poisoned translation (and to evict poisoned\n * cache entries written by earlier releases).\n */\nexport function isMaskLeak(translatedText: string): boolean {\n return hasMaskResidue(translatedText);\n}\n\n/**\n * Same as `isMaskLeak`, but a token the source text already contained is not a\n * leak: text that talks about placeholders (this plugin's docs, a bug report)\n * must round-trip untouched.\n */\nexport function isMaskLeakAgainst(originalText: string, translatedText: string): boolean {\n return hasNewMaskResidue(originalText, translatedText);\n}\n", "/**\n * \u628A fetch / \u7F51\u7EDC\u5931\u8D25\u7684\u53EF\u8BFB\u539F\u56E0\u5C55\u5F00\u6210\u5355\u884C\u6587\u672C\uFF08\u5BBF\u4E3B\u4E0E\u5BA2\u6237\u7AEF\u5171\u7528\uFF09\u3002\n *\n * \u80CC\u666F\uFF1ANode 18+ \u4E0E\u6D4F\u89C8\u5668\u7684 fetch \u5728\u7F51\u7EDC\u5C42\u5931\u8D25\u65F6\u53EA\u7ED9\u4E00\u53E5 `TypeError: fetch failed`\n * \uFF08\u6D4F\u89C8\u5668\u662F `Failed to fetch`\uFF09\uFF0C\u771F\u5B9E\u539F\u56E0\u85CF\u5728 `err.cause` \u91CC\u2014\u2014\u4F8B\u5982\n * `connect ENETUNREACH 172.24.52.126:8081`\u3001`other side closed [UND_ERR_SOCKET]`\u3001\n * `getaddrinfo ENOTFOUND`\u3002\u53EA\u4E0A\u62A5 `err.message` \u4F1A\u8BA9\u300C\u7AEF\u70B9\u4E0D\u53EF\u8FBE / \u88AB\u4EE3\u7406\u65AD\u5F00\u300D\u548C\n * \u300C\u63D2\u4EF6\u81EA\u8EAB\u51FA\u9519\u300D\u957F\u5F97\u4E00\u6A21\u4E00\u6837\uFF1A\u7528\u6237\u53EA\u770B\u5230\u65E0\u4FE1\u606F\u91CF\u7684 fetch failed\uFF0C\u65E0\u4ECE\u5224\u65AD\u8BE5\u6539\u4EC0\u4E48\u3002\n *\n * \u8FD9\u91CC\u628A message \u4E0E cause \u94FE\uFF08\u542B AggregateError \u7684\u591A\u5730\u5740\u5931\u8D25\uFF09\u62FC\u6210 `A \u2190 B \u2190 C`\u3002\n */\nexport function describeError(err: unknown): string {\n if (err === null || err === undefined) return String(err);\n const parts: string[] = [];\n const push = (s: string): void => {\n const t = String(s || '').trim();\n if (t && !parts.includes(t)) parts.push(t);\n };\n const head = (err as { message?: string }).message || String(err);\n push(head);\n const headCode = (err as { code?: string }).code;\n if (headCode && !head.includes(headCode)) push('[' + headCode + ']');\n let cause = (err as { cause?: unknown }).cause as\n | { message?: string; code?: string; cause?: unknown; errors?: unknown }\n | undefined;\n for (let depth = 0; cause && depth < 4; depth++) {\n const label = cause.message || String(cause);\n push(cause.code && !label.includes(cause.code) ? label + ' [' + cause.code + ']' : label);\n // AggregateError\uFF1A\u591A\u5730\u5740\u5168\u90E8\u5931\u8D25\uFF08happy-eyeballs \u53CC\u6808\u5E38\u89C1\uFF09\uFF0C\u5C55\u5F00\u524D\u51E0\u6761\n if (Array.isArray(cause.errors)) {\n for (const sub of (cause.errors as { message?: string; code?: string }[]).slice(0, 3)) {\n if (sub) push(sub.code || sub.message || String(sub));\n }\n }\n cause = cause.cause as typeof cause;\n }\n return parts.join(' \u2190 ');\n}", "import type { ITranslationAdapter, PluginConfig } from './base.ts';\n\n/**\n * Built-in Bing Web translator channel \u2014 no key, no gateway jar, mainland\n * networks reach cn.bing.com directly. This is the same flow DeepLX and\n * Translate_Api_Free use: fetch the translator page for the IG token and the\n * abuse-prevention key/token, then POST to ttranslatev3.\n */\n\nconst TRANSLATOR_URL = 'https://cn.bing.com/translator';\nconst TRANSLATE_URL = 'https://cn.bing.com/ttranslatev3?isVertical=1&&IG={IG}&IID=translator.5025.1';\nconst UA =\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';\n\nconst IG_RES = [\n /_IG=\"([a-zA-Z0-9]+)\"/,\n /,IG:\"([a-zA-Z0-9]+)\"/,\n /IG:\"([a-zA-Z0-9]+)\"/,\n /\"IG\":\"([a-zA-Z0-9]+)\"/,\n];\nconst ABUSE_RES = [\n /params_AbusePreventionHelper\\s*=\\s*\\[\\s*(\\d+)\\s*,\\s*\"([^\"]+)\"/,\n /var\\s+params_AbusePreventionHelper\\s*=\\s*\\[\\s*(\\d+)\\s*,\\s*\"([^\"]+)\"/,\n];\n\ninterface BingTokens {\n ig: string;\n key: string;\n token: string;\n}\n\nlet cachedTokens: BingTokens | null = null;\nlet tokensFetchedAt = 0;\nconst TOKEN_TTL_MS = 15 * 60 * 1000; // 15 minutes\nlet inFlightTokenPromise: Promise<BingTokens> | null = null;\n\nfunction parseTokens(html: string): BingTokens {\n let ig: string | undefined;\n for (const re of IG_RES) {\n const m = re.exec(html);\n if (m && m[1]) {\n ig = m[1];\n break;\n }\n }\n\n let key: string | undefined;\n let token: string | undefined;\n for (const re of ABUSE_RES) {\n const m = re.exec(html);\n if (m && m[1] && m[2]) {\n key = m[1];\n token = m[2];\n break;\n }\n }\n\n if (!ig || !key || !token) {\n throw new Error(`Bing translator page: missing tokens (ig: ${!!ig}, key: ${!!key}, token: ${!!token})`);\n }\n\n return { ig, key, token };\n}\n\nexport async function fetchTokens(signal: AbortSignal, forceRefresh = false): Promise<BingTokens> {\n if (!forceRefresh && cachedTokens && Date.now() - tokensFetchedAt < TOKEN_TTL_MS) {\n return cachedTokens;\n }\n\n if (inFlightTokenPromise) {\n return inFlightTokenPromise;\n }\n\n inFlightTokenPromise = (async () => {\n try {\n const response = await fetch(TRANSLATOR_URL, {\n headers: {\n 'User-Agent': UA,\n Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n },\n signal,\n });\n if (!response.ok) {\n throw new Error(`Bing translator page responded with status ${response.status}`);\n }\n const html = await response.text();\n const tokens = parseTokens(html);\n cachedTokens = tokens;\n tokensFetchedAt = Date.now();\n return tokens;\n } finally {\n inFlightTokenPromise = null;\n }\n })();\n\n return inFlightTokenPromise;\n}\n\nexport class BingWebAdapter implements ITranslationAdapter {\n readonly id = 'bing';\n readonly name = '\u5FAE\u8F6F Bing \u7F51\u9875\u7FFB\u8BD1 (\u514DKey\u76F4\u8FDE)';\n\n isAvailable(_config: PluginConfig): boolean {\n return true; // No key, no gateway URL required\n }\n\n async translate(text: string, signal: AbortSignal, config: PluginConfig): Promise<string> {\n const targetLang = config.targetLang || 'zh-Hans';\n return this.executeTranslate(text, signal, targetLang, false);\n }\n\n private async executeTranslate(\n text: string,\n signal: AbortSignal,\n targetLang: string,\n isRetry: boolean\n ): Promise<string> {\n const tokens = await fetchTokens(signal, isRetry);\n\n const body = new URLSearchParams({\n fromLang: 'auto-detect',\n text,\n to: targetLang,\n key: tokens.key,\n token: tokens.token,\n tryFetchingGenderDebiasedTranslations: 'true',\n });\n\n const response = await fetch(TRANSLATE_URL.replace('{IG}', tokens.ig), {\n method: 'POST',\n headers: {\n 'User-Agent': UA,\n Referer: 'https://cn.bing.com/translator/',\n Origin: 'https://cn.bing.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body,\n signal,\n });\n\n if (!response.ok) {\n cachedTokens = null;\n // Auto retry once with fresh tokens if not already retrying\n if (!isRetry && (response.status === 400 || response.status === 401 || response.status === 403)) {\n return this.executeTranslate(text, signal, targetLang, true);\n }\n throw new Error(`Bing translate responded with status ${response.status}`);\n }\n\n const json = (await response.json()) as Array<{ translations?: Array<{ text?: string }> }>;\n const translated = json?.[0]?.translations?.[0]?.text?.trim();\n if (!translated) {\n cachedTokens = null;\n if (!isRetry) {\n return this.executeTranslate(text, signal, targetLang, true);\n }\n throw new Error('Bing translate returned an empty result');\n }\n return translated;\n }\n}\n", "import type { ITranslationAdapter, PluginConfig } from './base.ts';\nimport type { KeyReader } from '../credentials.ts';\n\n/**\n * OpenAI-compatible Chat Completions translation channel.\n *\n * Talks to `POST {baseUrl}/chat/completions` with a Bearer token read from\n * ~/.dsh/.credentials.yaml (refs.TRANSLATE_API_KEY). Works with OpenAI,\n * DeepSeek, Qwen, Ollama and any other service exposing the standard endpoint.\n */\n\n/** Map Bing-style targetLang codes to a natural language name for the prompt. */\nconst LANG_HINTS: Record<string, string> = {\n 'zh-hans': 'Simplified Chinese',\n 'zh-cn': 'Simplified Chinese',\n 'zh': 'Simplified Chinese',\n 'zh-tw': 'Traditional Chinese',\n 'zh-hant': 'Traditional Chinese',\n en: 'English',\n ja: 'Japanese',\n ko: 'Korean',\n fr: 'French',\n de: 'German',\n es: 'Spanish',\n ru: 'Russian',\n pt: 'Portuguese',\n it: 'Italian',\n};\n\nexport class OpenAiCompatibleAdapter implements ITranslationAdapter {\n readonly id = 'openai';\n readonly name = 'OpenAI \u517C\u5BB9 (Chat Completions)';\n\n private credentials: KeyReader;\n\n constructor(credentials: KeyReader) {\n this.credentials = credentials;\n }\n\n isAvailable(config: PluginConfig): boolean {\n return Boolean(\n config.aiEnabled && config.baseUrl?.trim() && config.model?.trim() && this.credentials.getApiKey()\n );\n }\n\n async translate(text: string, signal: AbortSignal, config: PluginConfig): Promise<string> {\n const apiKey = this.credentials.getApiKey();\n if (!apiKey) {\n throw new Error(`TRANSLATE_API_KEY is not configured in ~/.dsh/.credentials.yaml`);\n }\n const baseUrl = (config.baseUrl || '').trim().replace(/\\/+$/, '');\n const model = (config.model || '').trim();\n if (!baseUrl || !model) {\n throw new Error('OpenAI channel: baseUrl or model is not configured');\n }\n\n const langName = LANG_HINTS[(config.targetLang || 'zh-Hans').toLowerCase()] || config.targetLang || 'Simplified Chinese';\n\n const response = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0,\n messages: [\n {\n role: 'system',\n content:\n `You are a professional translator. Translate the user's message into ${langName}. ` +\n `Output ONLY the translated text \u2014 no explanations, no quotation marks, no extra words. ` +\n // Placeholders are described, never shown: a literal sample in the\n // prompt makes small models hallucinate a placeholder next to any\n // similar-looking word and ship it into the translation.\n `Some parts of the message are replaced by opaque placeholder markers ` +\n `(an uppercase token starting with \"DSH\" surrounded by double underscores). ` +\n `Copy every such marker into your output character-for-character, unchanged and in place. ` +\n `Never invent a marker that is not present in the message and never remove one.`,\n },\n { role: 'user', content: text },\n ],\n }),\n signal,\n });\n\n if (!response.ok) {\n let detail = '';\n try {\n const errBody = (await response.json()) as { error?: { message?: string }; message?: string };\n detail = errBody?.error?.message || errBody?.message || '';\n } catch {\n // ignore body parse errors\n }\n throw new Error(`OpenAI-compatible API responded with ${response.status}${detail ? `: ${detail}` : ''}`);\n }\n\n const data = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> };\n const content = data?.choices?.[0]?.message?.content;\n const translated = typeof content === 'string' ? content.trim() : '';\n if (!translated) {\n throw new Error('OpenAI-compatible API returned empty content');\n }\n return translated;\n }\n}\n", "import { describeError } from '../describe-error.ts';\nimport type { ITranslationAdapter, PluginConfig, TranslateItemResult } from './types.ts';\nimport type { ConfigManager } from './config.ts';\nimport { MAX_CONCURRENCY } from './config.ts';\nimport type { LruDiskCache } from './cache.ts';\nimport type { KeyReader } from './credentials.ts';\nimport { BingWebAdapter } from './adapters/bing.ts';\nimport { OpenAiCompatibleAdapter } from './adapters/openai.ts';\nimport { ContentMaskingPipeline, isMaskLeakAgainst } from './pipeline/masking.ts';\n\ntype CircuitStateEnum = 'closed' | 'open' | 'half-open';\n\ninterface CircuitState {\n state: CircuitStateEnum;\n failureCount: number;\n openUntil: number;\n probeInFlight: boolean; // single-flight guard for half-open probes\n}\n\nexport class TranslationDispatcher {\n private configManager: ConfigManager;\n private cache: LruDiskCache;\n private credentials: KeyReader;\n private masking = new ContentMaskingPipeline();\n private adapters = new Map<string, ITranslationAdapter>();\n private circuitStates = new Map<string, CircuitState>();\n private inFlightMap = new Map<string, Promise<TranslateItemResult>>();\n private activeCount = 0;\n private queue: Array<() => void> = [];\n\n constructor(configManager: ConfigManager, cache: LruDiskCache, credentials?: KeyReader) {\n this.configManager = configManager;\n this.cache = cache;\n this.credentials = credentials ?? { getApiKey: () => '' };\n\n // AI channel first (primary), Bing second (fallback) \u2014 map iteration order\n // follows registration order, so computeChannels() yields ['openai', 'bing'].\n this.registerAdapter(new OpenAiCompatibleAdapter(this.credentials));\n this.registerAdapter(new BingWebAdapter());\n\n // Listen to config changes to wake up queue on concurrency increase\n this.configManager.onConfigChange(() => {\n this.processNext();\n });\n }\n\n private registerAdapter(adapter: ITranslationAdapter): void {\n this.adapters.set(adapter.id, adapter);\n }\n\n /**\n * Decide which channels are active for the current config, in priority order.\n *\n * Truth table (user contract):\n * - AI on + configured + Bing on -> [openai, bing] (AI first, Bing fallback)\n * - AI on + NOT configured + Bing on -> [bing]\n * - AI on + NOT configured + Bing off -> [] (no translation)\n * - AI off + Bing on -> [bing]\n * - AI off + Bing off -> [] (no translation)\n */\n private computeChannels(config: PluginConfig): string[] {\n const channels: string[] = [];\n for (const [id, adapter] of this.adapters) {\n if (id === 'openai') {\n if (\n config.aiEnabled &&\n config.baseUrl?.trim() &&\n config.model?.trim() &&\n this.credentials.getApiKey()\n ) {\n channels.push(id);\n }\n continue;\n }\n if (id === 'bing') {\n if (config.bingEnabled) channels.push(id);\n continue;\n }\n // Custom/test adapters honor their own availability.\n if (adapter.isAvailable(config)) channels.push(id);\n }\n return channels;\n }\n\n async translateBatch(\n texts: string[],\n forceRefresh = false\n ): Promise<TranslateItemResult[]> {\n return Promise.all(texts.map((t) => this.translateOne(t, forceRefresh)));\n }\n\n async translateOne(\n rawText: string,\n forceRefresh = false\n ): Promise<TranslateItemResult> {\n const text = rawText.trim();\n if (!text) {\n return { original: rawText, translated: rawText, channel: 'none', cached: true };\n }\n\n const config = this.configManager.getConfig();\n if (!config.enabled) {\n return { original: rawText, translated: rawText, channel: 'disabled', cached: true };\n }\n\n const cacheKey = text.toLowerCase();\n\n // 1. Check L1/L2 Cache\n if (!forceRefresh) {\n const cached = this.cache.get(cacheKey);\n if (cached) {\n return { original: rawText, translated: cached, channel: 'cache', cached: true };\n }\n }\n\n // 2. In-flight Promise deduplication (only when not forceRefresh)\n if (!forceRefresh) {\n const inFlight = this.inFlightMap.get(cacheKey);\n if (inFlight) {\n return inFlight;\n }\n }\n\n // Mask code blocks, inline code, paths, urls, flags\n const { maskedText, unmask } = this.masking.mask(text);\n\n // 3. Queue task with concurrency limit\n const taskPromise = this.enqueueTask(async () => {\n const currentConfig = this.configManager.getConfig();\n const channels = this.computeChannels(currentConfig);\n\n for (const chId of channels) {\n const adapter = this.adapters.get(chId);\n if (!adapter || !adapter.isAvailable(currentConfig) || this.isCircuitOpen(chId)) {\n continue;\n }\n\n try {\n const timeout = chId === 'openai'\n ? currentConfig.aiTimeoutMs || 30000\n : currentConfig.timeoutMs || 2000;\n const abortCtrl = new AbortController();\n const timer = setTimeout(() => abortCtrl.abort(), timeout);\n\n let translatedMasked = '';\n try {\n translatedMasked = await adapter.translate(maskedText, abortCtrl.signal, currentConfig);\n } finally {\n clearTimeout(timer);\n }\n\n const cleaned = translatedMasked?.trim();\n if (cleaned && cleaned.length > 0) {\n const finalTranslated = unmask(cleaned);\n // A leftover placeholder means the engine rewrote it beyond repair:\n // never show `__DSHMASK\u2026__` to the user and never cache it. Treat\n // the whole response as a failed attempt and fall through to the\n // next channel (the caller then keeps the original text). Tokens\n // the source text already carried are legitimate content, not leaks.\n if (isMaskLeakAgainst(text, finalTranslated)) {\n this.recordFailure(chId);\n console.warn(\n `[dsh-chat-translate] channel ${chId} leaked a mask placeholder, discarding its result | text: ${text.slice(0, 60)}`\n );\n continue;\n }\n this.recordSuccess(chId);\n this.cache.set(cacheKey, finalTranslated);\n return {\n original: rawText,\n translated: finalTranslated,\n channel: chId,\n cached: false,\n };\n }\n // Empty result counts as a failure: it releases a half-open probe\n // flag (which would otherwise leak and permanently bypass the\n // channel) and feeds the circuit-breaker failure counter.\n this.recordFailure(chId);\n console.warn(\n `[dsh-chat-translate] channel ${chId} returned an empty translation | text: ${text.slice(0, 60)}`\n );\n } catch (err: any) {\n this.recordFailure(chId);\n console.warn(\n `[dsh-chat-translate] channel ${chId} failed: ${describeError(err)} | text: ${text.slice(0, 60)}`\n );\n // Continue to next channel\n }\n }\n\n return { original: rawText, translated: rawText, channel: 'fallback', cached: false };\n });\n\n if (!forceRefresh) {\n this.inFlightMap.set(cacheKey, taskPromise);\n }\n\n try {\n return await taskPromise;\n } finally {\n if (!forceRefresh) {\n this.inFlightMap.delete(cacheKey);\n }\n }\n }\n\n async testChannel(channelId: string): Promise<{ ok: boolean; latencyMs: number; error?: string }> {\n const adapter = this.adapters.get(channelId);\n const config = this.configManager.getConfig();\n if (!adapter) {\n return { ok: false, latencyMs: 0, error: `Channel ${channelId} not found` };\n }\n if (!adapter.isAvailable(config)) {\n return { ok: false, latencyMs: 0, error: `Channel ${channelId} is not configured or disabled` };\n }\n\n const testText = 'List files in current directory';\n const start = Date.now();\n try {\n const timeout = channelId === 'openai' ? Math.min(config.aiTimeoutMs || 30000, 30000) : 4000;\n const abortCtrl = new AbortController();\n const timer = setTimeout(() => abortCtrl.abort(), timeout);\n let res = '';\n try {\n res = await adapter.translate(testText, abortCtrl.signal, config);\n } finally {\n clearTimeout(timer);\n }\n\n const latencyMs = Date.now() - start;\n if (res && res.trim()) {\n return { ok: true, latencyMs };\n }\n return { ok: false, latencyMs, error: 'Empty translation returned' };\n } catch (err: any) {\n return { ok: false, latencyMs: Date.now() - start, error: describeError(err) };\n }\n }\n\n private enqueueTask<T>(task: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const exec = async () => {\n this.activeCount++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.activeCount--;\n this.processNext();\n }\n };\n\n const maxConcurrency = Math.min(\n Math.max(this.configManager.getConfig().concurrency || 3, 1),\n MAX_CONCURRENCY\n );\n\n if (this.activeCount < maxConcurrency) {\n exec();\n } else {\n this.queue.push(exec);\n }\n });\n }\n\n private processNext(): void {\n const maxConcurrency = Math.min(\n Math.max(this.configManager.getConfig().concurrency || 3, 1),\n MAX_CONCURRENCY\n );\n\n while (this.queue.length > 0 && this.activeCount < maxConcurrency) {\n const next = this.queue.shift();\n if (next) {\n next();\n }\n }\n }\n\n private isCircuitOpen(channelId: string): boolean {\n let state = this.circuitStates.get(channelId);\n if (!state) return false;\n\n if (state.state === 'open') {\n if (Date.now() >= state.openUntil) {\n // Timeout elapsed -> transition to half-open; the first caller becomes\n // the single in-flight probe.\n state.state = 'half-open';\n state.probeInFlight = true;\n return false;\n }\n return true;\n }\n\n if (state.state === 'half-open') {\n // Single-flight: exactly one probe may run at a time, all others wait.\n if (state.probeInFlight) return true;\n state.probeInFlight = true;\n return false;\n }\n\n return false;\n }\n\n private recordSuccess(channelId: string): void {\n const state = this.circuitStates.get(channelId);\n if (state) {\n state.state = 'closed';\n state.failureCount = 0;\n state.openUntil = 0;\n state.probeInFlight = false;\n }\n }\n\n private recordFailure(channelId: string): void {\n let state = this.circuitStates.get(channelId);\n if (!state) {\n state = { state: 'closed', failureCount: 0, openUntil: 0, probeInFlight: false };\n this.circuitStates.set(channelId, state);\n }\n\n if (state.state === 'half-open') {\n // Probe failed -> trip back to open for 30s\n state.state = 'open';\n state.failureCount = 3;\n state.openUntil = Date.now() + 30000;\n state.probeInFlight = false;\n return;\n }\n\n state.failureCount++;\n if (state.failureCount >= 3) {\n state.state = 'open';\n state.openUntil = Date.now() + 30000; // Open circuit for 30 seconds\n }\n }\n}\n", "import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { describeError } from '../describe-error.ts';\nimport type { ConfigManager } from './config.ts';\nimport type { TranslationDispatcher } from './dispatcher.ts';\n\nconst MAX_BODY_BYTES = 1024 * 1024; // 1MB body limit to prevent DoS\n\n/**\n * HTTP surface for the translation proxy only.\n *\n * Config and credentials no longer have HTTP endpoints: since 1.2 the\n * settings panel reads/writes through DSH's own channels \u2014 the\n * `settingsScope` client service and the `credentials` Remote API \u2014 so the\n * plugin exposes exactly one route family to the browser: translation.\n */\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n const json = JSON.stringify(body);\n res.writeHead(status, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Content-Length': Buffer.byteLength(json),\n });\n res.end(json);\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let totalLength = 0;\n\n req.on('data', (chunk) => {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalLength += buf.length;\n if (totalLength > MAX_BODY_BYTES) {\n if (typeof req.destroy === 'function') {\n req.destroy();\n }\n reject(new Error('Request body exceeded maximum allowed size (1MB)'));\n return;\n }\n chunks.push(buf);\n });\n\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));\n req.on('error', reject);\n });\n}\n\nexport function createHttpHandler(configManager: ConfigManager, dispatcher: TranslationDispatcher) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const url = new URL(req.url || '/', 'http://localhost');\n const pathParts = url.pathname.split('/').filter(Boolean);\n // pathParts will start with ['api', 'dsh-chat-translate', ...]\n const endpoint = pathParts[2] || '';\n\n try {\n if (endpoint === 'translate' && req.method === 'POST') {\n const raw = await readBody(req);\n let parsed: any;\n try {\n parsed = JSON.parse(raw || '{}');\n } catch {\n sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });\n return;\n }\n const rawTexts: unknown = parsed.texts !== undefined ? parsed.texts : parsed.text;\n\n let texts: string[] = [];\n if (Array.isArray(rawTexts)) {\n texts = rawTexts.filter((t): t is string => typeof t === 'string');\n } else if (typeof rawTexts === 'string') {\n texts = [rawTexts];\n }\n\n const forceRefresh = Boolean(parsed.forceRefresh);\n\n if (texts.length === 0) {\n sendJson(res, 200, { ok: true, results: [] });\n return;\n }\n\n const results = await dispatcher.translateBatch(texts, forceRefresh);\n sendJson(res, 200, { ok: true, results });\n return;\n }\n\n if (endpoint === 'test-channel' && req.method === 'POST') {\n const raw = await readBody(req);\n let parsed: any;\n try {\n parsed = JSON.parse(raw || '{}');\n } catch {\n sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });\n return;\n }\n const channelId = typeof parsed.channel === 'string' ? parsed.channel : '';\n const result = await dispatcher.testChannel(channelId);\n sendJson(res, 200, result);\n return;\n }\n\n sendJson(res, 404, { ok: false, error: 'Endpoint not found' });\n } catch (err: any) {\n const status = err?.message?.includes('exceeded maximum allowed size') ? 413 : 500;\n sendJson(res, status, { ok: false, error: describeError(err) });\n }\n };\n}\n", "import z from '@deepseek-ai/schemastery';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport {\n ConfigManager,\n migrateLegacyConfigFile,\n SETTINGS_NAMESPACE,\n DEFAULT_CONFIG,\n MAX_CONCURRENCY,\n AI_TIMEOUT_MIN,\n AI_TIMEOUT_MAX,\n} from './server/config.ts';\nimport { CredentialsReader, TRANSLATE_API_KEY_REF } from './server/credentials.ts';\nimport { LruDiskCache } from './server/cache.ts';\nimport { TranslationDispatcher } from './server/dispatcher.ts';\nimport { createHttpHandler } from './server/router.ts';\n\n/** Stable Cordis loader name. */\nexport const name = 'dsh-chat-translate';\n\n/**\n * Hard dependencies: webServer serves the translation proxy; settings and\n * credentials are the DSH-owned config/secret surfaces this plugin now rides\n * on (no standalone config file since 1.2).\n */\nexport const inject = ['webServer', 'settings', 'credentials'];\n\n/** Settings namespace schema: defaults + bounds, resolved by DSH itself. */\nconst CONFIG_SCHEMA = z.object({\n enabled: z.boolean().default(DEFAULT_CONFIG.enabled),\n concurrency: z.number().min(1).max(MAX_CONCURRENCY).default(DEFAULT_CONFIG.concurrency),\n timeoutMs: z.number().min(500).max(10000).default(DEFAULT_CONFIG.timeoutMs),\n aiTimeoutMs: z.number().min(AI_TIMEOUT_MIN).max(AI_TIMEOUT_MAX).default(DEFAULT_CONFIG.aiTimeoutMs),\n aiEnabled: z.boolean().default(DEFAULT_CONFIG.aiEnabled),\n bingEnabled: z.boolean().default(DEFAULT_CONFIG.bingEnabled),\n baseUrl: z.string().default(DEFAULT_CONFIG.baseUrl),\n model: z.string().default(DEFAULT_CONFIG.model),\n targetLang: z.string().default(DEFAULT_CONFIG.targetLang),\n});\n\ninterface HostContext {\n webServer?: {\n register(route: {\n kind: 'prefix' | 'exact';\n path: string;\n handler: (req: any, res: any) => Promise<void> | void;\n }): () => void;\n };\n settings: {\n register(ns: string, schema: unknown): {\n get(): any;\n watch(listener: (config: any) => void): () => void;\n update(patch: Record<string, unknown>): Promise<unknown>;\n };\n describe(): Array<{ ns: string; user?: unknown }>;\n update(ns: string, patch: Record<string, unknown>): Promise<unknown>;\n };\n credentials: {\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n set(ref: string, value: string): Promise<void>;\n unset(ref: string): Promise<void>;\n };\n on(event: string, listener: (...args: any[]) => void): () => void;\n effect(factory: () => void | (() => void), label: string): void;\n get?(serviceName: string): any;\n}\n\n/** Mount the host half; provides the translation proxy and rides DSH config. */\nexport function apply(ctx: HostContext): void {\n const credentials = new CredentialsReader(ctx.credentials);\n const configManager = new ConfigManager(ctx.settings.register(SETTINGS_NAMESPACE, CONFIG_SCHEMA), credentials);\n const cache = new LruDiskCache(1000);\n const dispatcher = new TranslationDispatcher(configManager, cache, credentials);\n\n // Initialize async resources: credentials cache, disk cache relocation, and\n // the one-shot migration of the legacy dsh-chat-translate-config.json.\n const legacyConfigPath = dshHomePath('dsh-chat-translate-config.json');\n const initPromise = Promise.all([\n credentials.init(),\n cache.init(),\n migrateLegacyConfigFile(ctx.settings, legacyConfigPath),\n ]).catch((err) => {\n console.warn('[dsh-chat-translate] Initialization error:', err);\n });\n\n // Keep the synchronous key cache warm: the credentials service fans this\n // event out after every committed write or external reload.\n ctx.on('credentials/reference-updated', (ref: unknown) => {\n if (ref === TRANSLATE_API_KEY_REF) {\n void credentials.refresh();\n }\n });\n\n const webServer = ctx.webServer || (ctx.get ? ctx.get('webServer') : null);\n if (webServer && typeof webServer.register === 'function') {\n const rawHandler = createHttpHandler(configManager, dispatcher);\n const handler = async (req: any, res: any) => {\n await initPromise;\n return rawHandler(req, res);\n };\n\n ctx.effect(\n () => {\n const unregister = webServer.register({\n kind: 'prefix',\n path: '/api/dsh-chat-translate',\n handler,\n });\n return () => {\n if (typeof unregister === 'function') {\n unregister();\n }\n cache.dispose().catch((err) => {\n console.warn('[dsh-chat-translate] Dispose cache error:', err);\n });\n };\n },\n 'dsh-chat-translate: translation API routes'\n );\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAIA,SAAS,WAAW,OAAO;AAC1B,SAAO,UAAU,QAAQ,UAAU;AACpC;AAMA,SAAS,cAAc,MAAM;AAC5B,SAAO,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI;AAC/D;AAEA,SAAS,WAAW,QAAQ,QAAQ;AACnC,SAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,KAAK,MAAM,OAAO,KAAK,KAAK,CAAC,CAAC;AAC9F;AAEA,SAAS,UAAU,QAAQ,WAAW;AACrC,SAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,GAAG,CAAC,CAAC,CAAC;AACrG;AAEA,SAAS,KAAK,QAAQ,MAAM,QAAQ;AACnC,MAAI,CAAC,KAAM,QAAO,EAAE,GAAG,OAAO;AAC9B,QAAM,SAAS,CAAC;AAChB,aAAW,OAAO,KAAM,KAAI,UAAU,OAAO,GAAG,MAAM,OAAQ,QAAO,GAAG,IAAI,OAAO,GAAG;AACtF,SAAO;AACR;AAqDA,SAAS,GAAG,MAAM,OAAO;AACxB,MAAI,UAAU,WAAW,EAAG,QAAO,CAACA,WAAU,GAAG,MAAMA,MAAK;AAC5D,SAAO,QAAQ,cAAc,iBAAiB,WAAW,IAAI,KAAK,OAAO,UAAU,SAAS,KAAK,KAAK,EAAE,MAAM,GAAG,EAAE,MAAM;AAC1H;AACA,SAAS,kBAAkB,OAAO;AACjC,SAAO,GAAG,eAAe,KAAK,KAAK,GAAG,qBAAqB,KAAK;AACjE;AACA,SAAS,oBAAoB,OAAO;AACnC,SAAO,kBAAkB,KAAK,KAAK,YAAY,OAAO,KAAK;AAC5D;AAEA,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", "resolve", "toJSON", "date", "toString", "name", "key", "resolve", "path", "resolve", "fs", "
|
|
3
|
+
"sources": ["../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.3/node_modules/@deepseek-ai/cosmokit/lib/index.js", "../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.2/node_modules/@deepseek-ai/schemastery/lib/index.mjs", "../node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.1.6-alpha.2_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js", "../src/server/config.ts", "../src/server/credentials.ts", "../src/server/cache.ts", "../src/server/pipeline/mask-tokens.ts", "../src/server/pipeline/masking.ts", "../src/describe-error.ts", "../src/server/adapters/bing.ts", "../src/server/adapters/openai.ts", "../src/server/pipeline/think.ts", "../src/server/dispatcher.ts", "../src/server/router.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */\nfunction deepEqual(a, b, strict) {\n\tif (a === b) return true;\n\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\tif (typeof a !== typeof b) return false;\n\tif (typeof a !== \"object\") return false;\n\tif (!a || !b) return false;\n\tfunction check(test, then) {\n\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t}\n\treturn check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is(\"Date\"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is(\"RegExp\"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {\n\t\tif (a.byteLength !== b.byteLength) return false;\n\t\tconst viewA = new Uint8Array(a);\n\t\tconst viewB = new Uint8Array(b);\n\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\treturn true;\n\t}) ?? Object.keys({\n\t\t...a,\n\t\t...b\n\t}).every((key) => deepEqual(a[key], b[key], strict));\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (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);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn 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));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union };\n", "import { Binary, clone, deepEqual, filterKeys, isNullable, isPlainObject, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nconst resolvers = {};\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n", "import { opendir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n//#region lib/types/index.js\n/**\n* Shared filesystem path helpers for DeepSeek Harness user data.\n*\n* @module @deepseek-ai/dsh-home-paths\n*/\n/** Directory name for the default DeepSeek Harness home under the OS home. */\nconst DSH_HOME_DIR_NAME = \".dsh\";\n/** Stable user-facing display form for the default DeepSeek Harness home. */\nconst DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default DeepSeek Harness home. */\nconst DSH_HOME_ENV = \"DSH_HOME\";\n/**\n* Give a native filesystem watcher one canonical spelling of a path, even\n* when its final components do not exist yet. The deepest existing ancestor\n* is resolved through {@link realpath}; when a suffix is missing, that\n* ancestor is also proved to be an enumerable directory before the suffix is\n* restored. This prevents Windows from treating a regular-file ancestor as\n* ordinary absence, and prevents short-name aliases from being mixed with\n* long paths emitted by the native watcher backend.\n* @param path - Watch target or root, resolved against the current directory.\n* @returns the target with its existing ancestor canonicalized.\n* @throws when ancestor traversal encounters an error other than absence, or\n* the existing ancestor of a missing suffix is not an enumerable directory.\n*/\nasync function canonicalizeWatchPath(path) {\n\tlet current = resolve(path);\n\tconst missing = [];\n\twhile (true) try {\n\t\tconst canonical = await realpath(current);\n\t\tif (missing.length > 0) await (await opendir(canonical)).close();\n\t\treturn join(canonical, ...missing.reverse());\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tconst parent = dirname(current);\n\t\t/* v8 ignore next -- a filesystem root exists, so traversal resolves before this guard */\n\t\tif (parent === current) throw error;\n\t\tmissing.push(basename(current));\n\t\tcurrent = parent;\n\t}\n}\n/**\n* Resolve the default DeepSeek Harness home using Node's platform path rules.\n* @returns the absolute default harness home path.\n*/\nfunction defaultDshHome() {\n\treturn join(homedir(), DSH_HOME_DIR_NAME);\n}\n/**\n* Expand supported tilde prefixes against the operating-system home.\n* @param path - configured path that may begin with `~`, `~/`, or `~\\`.\n* @returns the expanded path, or the original value when no supported prefix is present.\n*/\nfunction expandHomePath(path) {\n\tif (path === \"~\") return homedir();\n\tif (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(homedir(), path.slice(2));\n\treturn path;\n}\n/**\n* Resolve the single-root DeepSeek Harness home.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_HOME`, then\n* `~/.dsh`. The harness keeps all user data under one root. An empty or\n* whitespace-only `$DSH_HOME` is treated as unset, so a blank override never\n* resolves the home to the current working directory.\n* @param configured - explicit harness-home override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_HOME`.\n* @returns the normalized absolute harness home path.\n*/\nfunction resolveDshHome(configured, env = process.env) {\n\tconst fromEnv = env[DSH_HOME_ENV];\n\treturn resolve(expandHomePath(configured ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : defaultDshHome())));\n}\n/**\n* Join path segments onto the resolved DeepSeek Harness home.\n* @param segments - path segments appended to the Harness home; an empty list returns the home itself.\n* @returns the normalized absolute joined path.\n*/\nfunction dshHomePath(...segments) {\n\treturn join(resolveDshHome(), ...segments);\n}\n/**\n* Join path segments onto the resolved Harness home's `cache` directory without creating it; no arguments returns the directory itself.\n* @param optionsOrSegment - explicit home override, or the first path segment; omission uses the default home resolution.\n* @param segments - additional path segments after the first child, if any.\n* @returns the normalized absolute cache path.\n*/\nfunction dshCachePath(optionsOrSegment = {}, ...segments) {\n\tif (typeof optionsOrSegment === \"string\") return dshHomePath(\"cache\", optionsOrSegment, ...segments);\n\treturn join(resolveDshHome(optionsOrSegment.dshHome), \"cache\", ...segments);\n}\n/**\n* Describe a resolved harness home symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default home is labelled\n* `~/.dsh`, and any configured home is labelled `$DSH_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveDshHome}.\n* @returns `~/.dsh` for the default home, otherwise `$DSH_HOME`.\n*/\nfunction dshHomeDisplay(resolvedHome) {\n\treturn resolvedHome === resolve(defaultDshHome()) ? DEFAULT_DSH_HOME_DISPLAY : `$${DSH_HOME_ENV}`;\n}\n//#endregion\nexport { DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_DIR_NAME, DSH_HOME_ENV, canonicalizeWatchPath, defaultDshHome, dshCachePath, dshHomeDisplay, dshHomePath, expandHomePath, resolveDshHome };\n", "import * as fs from 'node:fs/promises';\nimport type { PluginConfig } from './types.ts';\nimport type { CredentialsReader } from './credentials.ts';\n\n/** Hard cap for the translation concurrency pool. */\nexport const MAX_CONCURRENCY = 100;\n\n/** Bounds for the AI channel request timeout. */\nexport const AI_TIMEOUT_MIN = 500;\nexport const AI_TIMEOUT_MAX = 120000;\n\n/**\n * Bounds for the think-chain request timeout. A full reasoning block can take\n * minutes on a local model, so this budget is far larger than the short-text\n * AI timeout and is bounded separately.\n */\nexport const THINK_TIMEOUT_MIN = 500;\nexport const THINK_TIMEOUT_MAX = 900000;\n\n/** Entries kept in the think-chain cache pool, separate from the title pool. */\nexport const THINK_CACHE_ENTRIES = 300;\n\n/**\n * The settings namespace this plugin owns. The user-editable layer lives in\n * the DSH-managed document (~/.dsh/settings.yaml) under this key; the\n * standalone ~/.dsh/dsh-chat-translate-config.json file is legacy (<=1.1).\n */\nexport const SETTINGS_NAMESPACE = 'dsh-chat-translate';\n\nexport const DEFAULT_CONFIG: PluginConfig = {\n enabled: true,\n concurrency: 3,\n timeoutMs: 2000,\n aiTimeoutMs: 30000,\n thinkTimeoutMs: 600000,\n aiEnabled: true,\n bingEnabled: true,\n thinkEnabled: true,\n baseUrl: '',\n model: '',\n targetLang: 'zh-Hans',\n};\n\n/**\n * Minimal shape of the owner scope returned by `ctx.settings.register()`.\n * Keeping this structural (instead of importing the DSH package) lets tests\n * inject an in-memory fake and keeps the bundle free of host-service code.\n */\nexport interface SettingsScopeLike {\n /** Resolved value: schema defaults, then composition base, then user layer. */\n get(): PluginConfig;\n /** Observe resolved-value changes; returns the disposer. */\n watch(listener: (config: PluginConfig) => void): () => void;\n /** Merge a patch into the user layer and persist through the provider. */\n update(patch: Partial<PluginConfig>): Promise<unknown>;\n}\n\n/**\n * One path-addressed edit to a settings namespace's user section, matching\n * DSH's `SettingsPathOp` wire shape.\n */\nexport type SettingsPathOpLike =\n | { op: 'set'; path: string[]; value: unknown }\n | { op: 'unset'; path: string[] };\n\n/**\n * Provider-level write face the legacy migration needs: the settings service\n * itself (not the per-namespace owner scope), whose `mutate` applies path ops\n * under one revision fence.\n */\nexport interface SettingsMigrationTarget {\n describe(): Array<{ ns: string; user?: unknown; revision?: number }>;\n mutate(ns: string, ops: readonly SettingsPathOpLike[], expectedRevision?: number): Promise<unknown>;\n}\n\n/**\n * Config facade over the DSH `ctx.settings` service. No file I/O lives here\n * anymore: persistence, atomic writes, external-edit hot reload and the\n * browser-facing describe/mutate API are all owned by DSH itself.\n */\nexport class ConfigManager {\n private scope: SettingsScopeLike;\n private credentials: CredentialsReader;\n\n constructor(scope: SettingsScopeLike, credentials: CredentialsReader) {\n this.scope = scope;\n this.credentials = credentials;\n }\n\n getConfig(): PluginConfig {\n return this.scope.get();\n }\n\n /** Whether the AI channel has every required piece: baseUrl, model and key. */\n isAiConfigured(): boolean {\n const config = this.getConfig();\n return Boolean(\n config.baseUrl.trim() &&\n config.model.trim() &&\n this.credentials.getApiKey()\n );\n }\n\n onConfigChange(listener: (config: PluginConfig) => void): () => void {\n return this.scope.watch(listener);\n }\n\n /**\n * Merge a partial update into the settings namespace. Values are sanitized\n * here (bounds, trimming) so the schema's own constraints act as a second\n * line of defence rather than the only one.\n *\n * @internal Test-only. No production path calls this: the host writes the\n * settings namespace from the browser through the DSH settings service, and\n * this facade is only driven by `scripts/test-*.mjs` (regression suite).\n * Kept (with this marker) so those tests keep exercising the sanitizer.\n */\n async updateConfig(partial: Partial<PluginConfig>): Promise<PluginConfig> {\n await this.scope.update(sanitizePatch({ ...partial }));\n return this.getConfig();\n }\n}\n\n/**\n * Coerce a raw record (legacy config file, HTTP-era partials) into a\n * validated partial config patch. Unknown fields are dropped, type-mismatched\n * values are skipped (the schema default wins), and numerics are clamped \u2014\n * so one bad field never takes down a whole migration.\n */\nexport function sanitizePatch(input: Record<string, unknown>): Partial<PluginConfig> {\n const next: Partial<PluginConfig> = {};\n if (typeof input.enabled === 'boolean') next.enabled = input.enabled;\n if (typeof input.aiEnabled === 'boolean') next.aiEnabled = input.aiEnabled;\n if (typeof input.bingEnabled === 'boolean') next.bingEnabled = input.bingEnabled;\n if (typeof input.thinkEnabled === 'boolean') next.thinkEnabled = input.thinkEnabled;\n\n if (typeof input.concurrency === 'number' && Number.isFinite(input.concurrency)) {\n next.concurrency = Math.min(Math.max(Math.round(input.concurrency), 1), MAX_CONCURRENCY);\n }\n if (typeof input.timeoutMs === 'number' && Number.isFinite(input.timeoutMs)) {\n next.timeoutMs = Math.min(Math.max(Math.round(input.timeoutMs), 500), 10000);\n }\n if (typeof input.aiTimeoutMs === 'number' && Number.isFinite(input.aiTimeoutMs)) {\n next.aiTimeoutMs = Math.min(\n Math.max(Math.round(input.aiTimeoutMs), AI_TIMEOUT_MIN),\n AI_TIMEOUT_MAX\n );\n }\n if (typeof input.thinkTimeoutMs === 'number' && Number.isFinite(input.thinkTimeoutMs)) {\n next.thinkTimeoutMs = Math.min(\n Math.max(Math.round(input.thinkTimeoutMs), THINK_TIMEOUT_MIN),\n THINK_TIMEOUT_MAX\n );\n }\n if (typeof input.baseUrl === 'string') next.baseUrl = input.baseUrl.trim();\n if (typeof input.model === 'string') next.model = input.model.trim();\n if (typeof input.targetLang === 'string' && input.targetLang.trim()) {\n next.targetLang = input.targetLang.trim();\n }\n return next;\n}\n\n/**\n * One-shot migration from the pre-1.2 standalone config file. Runs only while\n * the settings namespace has no user layer yet, so values the user edited\n * after upgrading are never overwritten. The legacy file is removed whether\n * or not a migration happened.\n * @returns whether any legacy values were migrated.\n */\nexport async function migrateLegacyConfigFile(\n settings: SettingsMigrationTarget,\n legacyPath: string\n): Promise<boolean> {\n let raw: string;\n try {\n raw = await fs.readFile(legacyPath, 'utf-8');\n } catch {\n return false; // no legacy file \u2014 nothing to do\n }\n\n let legacy: unknown;\n try {\n legacy = JSON.parse(raw);\n } catch {\n // Corrupt legacy file \u2014 drop it and keep schema defaults.\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n if (typeof legacy !== 'object' || legacy === null || Array.isArray(legacy)) {\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n const record = legacy as Record<string, unknown>;\n\n // Never overwrite a user layer the user already has (e.g. edited through\n // the settings UI after upgrading). The legacy file is still retired.\n const descriptor = settings.describe().find((d) => d.ns === SETTINGS_NAMESPACE);\n if (descriptor?.user !== undefined) {\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n\n // Per-field sanitize: known fields only (retired keys like pre-1.1\n // `channels` drop by construction), type-mismatched values skipped, numeric\n // bounds clamped \u2014 one bad field never blocks the rest of the migration.\n const patch = sanitizePatch(record);\n const ops: SettingsPathOpLike[] = Object.entries(patch).map(([field, value]) => ({\n op: 'set',\n path: [field],\n value,\n }));\n if (ops.length === 0) {\n // Nothing migratable \u2014 retire the file and keep schema defaults.\n await fs.unlink(legacyPath).catch(() => {});\n return false;\n }\n\n try {\n // Revision-fenced path write: a concurrent user edit between the describe\n // above and this commit is refused instead of overwritten.\n await settings.mutate(SETTINGS_NAMESPACE, ops, descriptor?.revision);\n } catch (err) {\n // The patch is already sanitized, so a rejection here is a provider-level\n // failure (read-only document, disk trouble). Keep the file so the next\n // boot retries \u2014 destroying the only copy would lose the user's values.\n console.warn('[dsh-chat-translate] Legacy config migration failed; will retry on next boot:', err);\n return false;\n }\n\n await fs.unlink(legacyPath).catch((err) => {\n console.warn('[dsh-chat-translate] Failed to remove legacy config file:', err);\n });\n return true;\n}\n", "/**\n * API-key access through the DSH `ctx.credentials` service.\n *\n * The service owns ~/.dsh/.credentials.yaml (refs section, 0600 perms, env\n * shadowing, cross-process locking). The pre-1.2 hand-rolled YAML parser is\n * gone: reads go through `resolve`, writes through `set`/`unset`, and the\n * host's `credentials/reference-updated` event keeps the sync cache warm.\n */\n\n/** Refs key that holds the translation API key. */\nexport const TRANSLATE_API_KEY_REF = 'TRANSLATE_API_KEY';\n\n/** The sync read face the hot translation path needs. */\nexport interface KeyReader {\n getApiKey(): string;\n}\n\n/** Minimal structural shape of the DSH `ctx.credentials` service. */\nexport interface CredentialsServiceLike {\n /** Resolve a ref to its stored/inherited value; undefined when absent. */\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n /** Status-only view \u2014 never returns the plaintext value. */\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n /** Store a non-empty value under the ref. */\n set(ref: string, value: string): Promise<void>;\n /** Remove the ref from the document. */\n unset(ref: string): Promise<void>;\n}\n\nexport class CredentialsReader implements KeyReader {\n private service: CredentialsServiceLike;\n private cachedKey = '';\n private refreshing: Promise<void> | null = null;\n\n constructor(service: CredentialsServiceLike) {\n this.service = service;\n }\n\n /** Load the API key once; safe to call multiple times. */\n async init(): Promise<void> {\n await this.refresh();\n }\n\n /**\n * Re-read the key from the credentials service. Used at startup and on\n * `credentials/reference-updated` events so an external edit or a write\n * from another surface takes effect immediately.\n */\n async refresh(): Promise<void> {\n if (this.refreshing) return this.refreshing;\n this.refreshing = (async () => {\n try {\n const resolved = await this.service.resolve(TRANSLATE_API_KEY_REF);\n this.cachedKey = (resolved?.value ?? '').trim();\n } catch (err) {\n console.warn('[dsh-chat-translate] Failed to resolve TRANSLATE_API_KEY:', err);\n } finally {\n this.refreshing = null;\n }\n })();\n return this.refreshing;\n }\n\n /** Synchronous cached read \u2014 the hot translation path stays sync. */\n getApiKey(): string {\n return this.cachedKey;\n }\n\n /**\n * Status-only view of the ref (plaintext never crosses the wire).\n *\n * @internal Test-only. The settings UI reads key status through the\n * `credentials` Remote API with its own client-side shape, so nothing in\n * `src/` calls this host-side method; only `scripts/test-*.mjs` do.\n */\n async describe(): Promise<{ configured: boolean; writable: boolean }> {\n try {\n const info = await this.service.describe(TRANSLATE_API_KEY_REF);\n return { configured: info.configured, writable: info.writable };\n } catch {\n return { configured: false, writable: false };\n }\n }\n\n /** Write (or clear) the ref through the DSH credentials service. */\n async setApiKey(apiKey: string): Promise<void> {\n const normalized = apiKey.trim();\n if (normalized) {\n await this.service.set(TRANSLATE_API_KEY_REF, normalized);\n } else {\n await this.service.unset(TRANSLATE_API_KEY_REF);\n }\n // The write committed: set the cache synchronously so the hot path never\n // reads a stale key even if a concurrent refresh() is still in flight,\n // then confirm from the service (which also fans reference-updated).\n this.cachedKey = normalized;\n await this.refresh();\n }\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport { isMaskLeak } from './pipeline/masking.ts';\n\n/** Entries older than this are treated as expired. */\nconst TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\ninterface CacheEntry {\n t: number; // epoch ms; 0 = legacy entry without timestamp (never expires on its own)\n v: string;\n}\n\nexport class LruDiskCache {\n private cache = new Map<string, CacheEntry>();\n private maxEntries: number;\n private filePath: string;\n private saveTimer: NodeJS.Timeout | null = null;\n private dirty = false;\n\n /** Legacy root-level cache file (<=1.1); moved under the plugin subdir. */\n private legacyPath: string;\n /** Only the original title cache carries a pre-1.2 root-level predecessor. */\n private hasLegacyPredecessor: boolean;\n\n constructor(maxEntries = 1000, fileName = 'cache.json') {\n this.maxEntries = maxEntries;\n // Follow the DSH convention of component-owned home subdirectories\n // (sessions/, storages/, attachments/) instead of polluting ~/.dsh.\n // dshHomePath mirrors resolveDshHome exactly: explicit configured home,\n // then $DSH_HOME (tilde-expanded), then ~/.dsh.\n this.filePath = dshHomePath('dsh-chat-translate', fileName);\n this.legacyPath = dshHomePath('dsh-chat-translate-cache.json');\n this.hasLegacyPredecessor = fileName === 'cache.json';\n }\n\n async init(): Promise<void> {\n // One-shot relocation of the pre-1.2 cache file, keeping its value. When\n // the new file already exists (newer cache), the legacy file is retired.\n // The think-chain pool never had a root-level predecessor: read straight\n // from its own file.\n if (!this.hasLegacyPredecessor) {\n await this.loadFile(this.filePath);\n return;\n }\n let readPath = this.filePath;\n try {\n await fs.access(this.filePath);\n // New cache already in place \u2014 the legacy file is just garbage now.\n await fs.unlink(this.legacyPath).catch(() => {});\n } catch {\n // The plugin subdirectory may not exist on first boot; rename fails\n // with ENOENT otherwise, which would silently lose the old cache.\n try {\n await fs.mkdir(path.dirname(this.filePath), { recursive: true });\n await fs.rename(this.legacyPath, this.filePath);\n readPath = this.filePath;\n } catch {\n readPath = this.legacyPath; // rename failed \u2014 read the legacy file directly\n }\n }\n\n await this.loadFile(readPath);\n\n // Relocation fallback: the legacy file was the read source \u2014 retire it\n // now that its entries are loaded (or proved unreadable).\n if (readPath !== this.filePath) {\n await fs.unlink(this.legacyPath).catch(() => {});\n }\n }\n\n /** Load one cache document into memory, dropping poisoned or malformed entries. */\n private async loadFile(readPath: string): Promise<void> {\n try {\n const content = await fs.readFile(readPath, 'utf-8');\n const obj = JSON.parse(content);\n if (obj && typeof obj === 'object') {\n for (const [k, raw] of Object.entries(obj)) {\n if (typeof raw === 'string') {\n // Legacy entry from an older release \u2014 keep it, no known timestamp.\n if (!isMaskLeak(raw)) this.cache.set(k, { t: 0, v: raw });\n } else if (raw && typeof raw === 'object' && typeof (raw as CacheEntry).v === 'string') {\n const entry = raw as CacheEntry;\n // Poisoned translations written before the mask-leak guard existed\n // must not survive a restart: drop them so the text is re-translated.\n if (typeof entry.t === 'number' && Number.isFinite(entry.t) && !isMaskLeak(entry.v)) {\n this.cache.set(k, entry);\n }\n }\n }\n }\n } catch {\n // Ignore missing or corrupt cache file\n }\n }\n\n get(key: string): string | undefined {\n const entry = this.cache.get(key);\n if (entry === undefined) return undefined;\n if (entry.t > 0 && Date.now() - entry.t > TTL_MS) {\n this.cache.delete(key);\n return undefined;\n }\n // Safety net for entries that entered the in-memory map before the\n // mask-leak guard (e.g. a warm cache written this session).\n if (isMaskLeak(entry.v)) {\n this.cache.delete(key);\n return undefined;\n }\n // Refresh key in LRU order (re-insert at the end)\n this.cache.delete(key);\n this.cache.set(key, entry);\n return entry.v;\n }\n\n set(key: string, value: string): void {\n if (isMaskLeak(value)) {\n console.warn('[dsh-chat-translate] refusing to cache a translation with a leaked mask placeholder');\n return;\n }\n if (this.cache.has(key)) {\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxEntries) {\n // Remove least recently used entry (first in Map iterator)\n const oldestKey = this.cache.keys().next().value;\n if (oldestKey !== undefined) {\n this.cache.delete(oldestKey);\n }\n }\n this.cache.set(key, { t: Date.now(), v: value });\n this.dirty = true;\n this.scheduleSave();\n }\n\n private scheduleSave(): void {\n if (this.saveTimer) return;\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n if (this.dirty) {\n // flush() owns the dirty flag: cleared only on a committed write, so\n // a failure keeps it set and schedules its own retry.\n this.flush().catch((err) => {\n console.warn('[dsh-chat-translate] Failed to flush cache to disk:', err);\n });\n }\n }, 5000);\n }\n\n async flush(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n\n const tmpPath = `${this.filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;\n try {\n const obj: Record<string, CacheEntry> = {};\n for (const [k, v] of this.cache.entries()) {\n obj[k] = v;\n }\n await fs.mkdir(path.dirname(this.filePath), { recursive: true });\n await fs.writeFile(tmpPath, JSON.stringify(obj, null, 2), 'utf-8');\n await fs.rename(tmpPath, this.filePath);\n // Only clear the dirty flag once the write actually committed; a failed\n // flush must not silently drop pending entries.\n this.dirty = false;\n } catch (err) {\n console.warn('[dsh-chat-translate] Failed to write cache file atomically:', err);\n try {\n await fs.unlink(tmpPath);\n } catch {}\n // Schedule one retry so a transient disk failure does not lose the\n // pending entries; dispose() is the only caller that must not reschedule.\n if (this.dirty) {\n this.scheduleSave();\n }\n }\n }\n\n async dispose(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n if (this.dirty) {\n await this.flush();\n }\n }\n}\n", "/**\n * Mask placeholder tokens \u2014 single source of truth for the wire format, the\n * matcher and the leftover detector.\n *\n * Wire format: `\u27E6xkbdt3\u27E7` \u2014 U+27E6/U+27E7 (mathematical white square brackets)\n * around `<4-letter random id><index>`.\n *\n * Design constraints, each one a measured failure of an earlier format against\n * real MT engines:\n *\n * - No letters spelling a pronounceable word and no underscores. The previous\n * `__DSHMASKxkbdt_3__` format named a token that small models abbreviated\n * back to its recognizable core: the UI showed bare `DSH` runs instead of\n * the protected fragments.\n * - Random letters keep two mask passes in the same session from colliding and\n * make the token unambiguous in the translated text.\n * - `matchMaskToken` accepts exactly what this module emits (plus the same\n * token with a dropped closing bracket, an engine rewrite seen in practice).\n * It deliberately does NOT accept anything else: a translation that damaged\n * a token beyond recognition is discarded rather than repaired, because\n * repairing it is what put mixed or duplicated text on screen.\n */\n\n/** Random part of the token. Letters only: never confuses the index scan. */\nconst RANDOM_LETTERS = 'abcdefghijklmnopqrstuvwxyz';\n\nexport function randomTokenId(): string {\n let out = '';\n for (let i = 0; i < 4; i++) {\n out += RANDOM_LETTERS[Math.floor(Math.random() * RANDOM_LETTERS.length)];\n }\n return out;\n}\n\nexport interface MaskTokenFormat {\n /** Unique per `mask()` call; embedded in every token of that call. */\n id: string;\n /** Build the placeholder written into the text sent to the translator. */\n token: (index: number) => string;\n}\n\nexport function createMaskTokenFormat(): MaskTokenFormat {\n const id = randomTokenId();\n return {\n id,\n token: (index: number) => `\u27E6${id}${index}\u27E7`,\n };\n}\n\n/**\n * Scanner for complete tokens of this format. A token whose closing bracket the\n * engine dropped is still resolved (see `matchMaskToken`), but it is not\n * recognized as a complete token here: the space `mask()` inserts sits outside\n * that token, and matching a truncated one would strip a space of the\n * translation's own.\n */\nexport const MASK_TOKEN_PATTERN_SOURCE = '\u27E6([a-z]{4})(\\\\d+)\u27E7';\n\n/**\n * The opening bracket, the id and the index of a token, without its closing\n * bracket. Used to resolve a token the engine truncated.\n */\nexport const MASK_TOKEN_PREFIX_PATTERN_SOURCE = '\u27E6\\\\s*([a-z]{4})(\\\\d+)';\n\n/**\n * Retired `__DSH_MASK_<index>__` / `__DSHMASKx<id>_<index>__` tokens. Nothing\n * emits them anymore: `mask()` rewrites any that appear in the source into the\n * current format, and the detectors below evict cache entries written by\n * releases that emitted them.\n */\nconst LEGACY_MASK_PATTERN_SOURCE =\n '_{1,2}DSH\\\\s*_*\\\\s*MASKx?\\\\s*(?:_?\\\\s*\\\\d+|_*([a-z]{2,8})\\\\s*_+\\\\s*(\\\\d+))_{0,2}';\n\n/** Regex source for one retired-format token, for text that still contains one. */\nexport const LEGACY_MASK_TOKEN_PATTERN_SOURCE = LEGACY_MASK_PATTERN_SOURCE;\n\nexport interface MaskTokenMatch {\n /** Index into the mask list of the `mask()` call that produced the token. */\n index: number;\n /** Length of the matched token in characters. */\n length: number;\n /** True when the closing bracket was missing and only the prefix matched. */\n truncated: boolean;\n}\n\n/**\n * Match exactly one mask token of this format at `start` in `text`.\n *\n * The id must match the id of the masking pass that owns the token: every mask\n * pass carries its own random id, so a token carrying another id belongs to\n * another call and must not be resolved here.\n */\nexport function matchMaskToken(text: string, start: number, id: string): MaskTokenMatch | null {\n const complete = new RegExp(`^(?:${MASK_TOKEN_PATTERN_SOURCE})`, 'iu').exec(text.slice(start));\n // The closing bracket is optional here so a token the engine truncated is\n // still resolved; the id and index inside must survive intact.\n const truncated = complete\n ? null\n : new RegExp(`^(?:${MASK_TOKEN_PREFIX_PATTERN_SOURCE})`, 'iu').exec(text.slice(start));\n\n const anchored = complete ?? truncated;\n if (!anchored) return null;\n if (anchored[1].toLowerCase() !== id.toLowerCase()) return null;\n\n const index = Number.parseInt(anchored[2], 10);\n if (Number.isNaN(index)) return null;\n\n return { index, length: anchored[0].length, truncated: complete === null };\n}\n\n/** Every token of this format in `text`, left to right. */\nexport function findMaskTokens(text: string): Array<{ match: MaskTokenMatch; raw: string }> {\n const found: Array<{ match: MaskTokenMatch; raw: string }> = [];\n const pattern = new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'giu');\n let candidate = pattern.exec(text);\n while (candidate) {\n const id = candidate[1].toLowerCase();\n const index = Number.parseInt(candidate[2], 10);\n if (!Number.isNaN(index)) {\n found.push({\n match: { index, length: candidate[0].length, truncated: false },\n raw: candidate[0],\n });\n }\n if (pattern.lastIndex === candidate.index) pattern.lastIndex++;\n candidate = pattern.exec(text);\n }\n return found;\n}\n\n/** True when `text` still carries a token of the current format. */\nexport function hasMaskResidue(text: string): boolean {\n if (!text) return false;\n return new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'iu').test(text);\n}\n\n/** True when `text` carries a token of a retired format. */\nexport function hasLegacyMaskResidue(text: string): boolean {\n if (!text) return false;\n return new RegExp(LEGACY_MASK_PATTERN_SOURCE, 'iu').test(text);\n}\n\n/**\n * Residue test for a value that must never be shown or cached: either a\n * current-format token or any retired-format token.\n */\nexport function hasAnyMaskResidue(text: string): boolean {\n return hasMaskResidue(text) || hasLegacyMaskResidue(text);\n}\n\n/**\n * Retired-format tokens inside source text, so `mask()` can protect them with a\n * current-format token of their own. A source that talks about the old\n * placeholder format must survive translation, and the unmask step rejects any\n * retired-format token it sees.\n */\nexport function findLegacyMaskTokens(text: string): string[] {\n if (!text) return [];\n return text.match(new RegExp(LEGACY_MASK_TOKEN_PATTERN_SOURCE, 'giu')) ?? [];\n}\n", "import {\n createMaskTokenFormat,\n hasAnyMaskResidue,\n hasMaskResidue,\n LEGACY_MASK_TOKEN_PATTERN_SOURCE,\n matchMaskToken,\n MASK_TOKEN_PATTERN_SOURCE,\n MASK_TOKEN_PREFIX_PATTERN_SOURCE,\n} from './mask-tokens.ts';\n\nexport interface MaskResult {\n maskedText: string;\n /**\n * Restore every protected fragment. Throws `MaskRestoreError` when the\n * translated text did not carry the token sequence back intact; the caller\n * must discard that translation instead of showing a repaired guess.\n */\n unmask: (translatedText: string) => string;\n /**\n * Retired-format tokens the source itself contained. They come back on\n * purpose and are content, so the caller's leak check must not flag them.\n */\n legacyFragments: string[];\n}\n\n/** Which spaces `mask()` inserted directly before and after a token. */\nexport interface InsertedSpacing {\n leading: boolean;\n trailing: boolean;\n}\n\n/** Bound the unmask scanner so a poisoned translation cannot spin forever. */\nconst MAX_UNMASK_PASSES = 10_000;\n\n/** Chinese, Japanese and Korean text is written without spaces between words. */\nconst ASCII_WORD = /[A-Za-z0-9_]/;\n\n/** A single leading or trailing space: the one this pipeline inserted. */\nconst INSERTED_SPACE = /^ | $/;\n\nexport class MaskRestoreError extends Error {\n readonly expectedCount: number;\n readonly foundCount: number;\n\n constructor(message: string, expectedCount: number, foundCount: number) {\n super(message);\n this.name = 'MaskRestoreError';\n this.expectedCount = expectedCount;\n this.foundCount = foundCount;\n }\n}\n\nexport class ContentMaskingPipeline {\n mask(text: string): MaskResult {\n if (!text || typeof text !== 'string') {\n return {\n maskedText: text,\n unmask: (t: string) => t,\n legacyFragments: [],\n };\n }\n\n const masks: string[] = [];\n /** Indices whose fragment already was a retired-format token. */\n const legacyIndexes = new Set<number>();\n /** Which spaces `placeToken` inserted around a fragment. */\n const inserted: InsertedSpacing[] = [];\n const format = createMaskTokenFormat();\n\n /**\n * Record one protected fragment and return the text that replaces it.\n *\n * A match that already carries a token from an earlier rule is returned\n * unchanged: that inner token already protects the fragment, and recording\n * the surrounding text again would put one fragment under two indices.\n * `before` and `after` are the characters on either side of the match in the\n * never-masked text. A token touching a Latin word gets one space on that\n * side: the engine then sees a standalone word and keeps it separate, while\n * a token glued to source text (`Fixsrc/\u2026`) came back merged into its\n * neighbour. The inserted spaces are recorded so `unmask` removes exactly\n * them and never a space the translation produced.\n */\n const addFragment = (\n match: string,\n before: string | undefined,\n after: string | undefined,\n onPlace?: (index: number) => void\n ): string => {\n if (hasMaskResidue(match)) return match;\n const index = masks.length;\n masks.push(match);\n const leading = before !== undefined && ASCII_WORD.test(before);\n const trailing = after !== undefined && ASCII_WORD.test(after);\n inserted.push({ leading, trailing });\n onPlace?.(index);\n return `${leading ? ' ' : ''}${format.token(index)}${trailing ? ' ' : ''}`;\n };\n\n const wrapRule = (input: string, pattern: RegExp, onPlace?: (index: number) => void): string =>\n input.replace(pattern, (...args: unknown[]) => {\n const match = args[0] as string;\n const offset = args[args.length - 2] as number;\n const whole = args[args.length - 1] as string;\n return addFragment(match, whole[offset - 1], whole[offset + match.length], onPlace);\n });\n\n // 0. Retired-format placeholders in the source are protected first: the\n // unmask step rejects retired tokens, so leaving one in the text sent to\n // the engine would discard an otherwise usable translation of a sentence\n // that merely documents the old format. Runs before the code rules, so a\n // legacy token inside inline code survives as one fragment instead of\n // being swallowed by the surrounding code match.\n let processed = wrapRule(\n text,\n new RegExp(LEGACY_MASK_TOKEN_PATTERN_SOURCE, 'giu'),\n (index) => legacyIndexes.add(index)\n );\n\n // 1. Multi-line code blocks (```...``` or ~~~...~~~)\n processed = wrapRule(processed, /(?:```|~~~)[\\s\\S]*?(?:```|~~~)/g);\n\n // 2. Inline code (`...`)\n processed = wrapRule(processed, /`[^`\\n]+`/g);\n\n // 3. URLs\n processed = wrapRule(processed, /https?:\\/\\/[^\\s)\\];,;\"'<>]+/g);\n\n // 4. File paths and filenames with known extensions.\n // Every alternative is anchored on a left boundary (`.`/`/` accepted\n // only when preceded by a word char or start) so a match can never start\n // mid-path: `src/server` inside `src/server/dispatcher.ts` used to split\n // the path into `src\u27E6\u20260\u27E7`, masking the slash away.\n processed = wrapRule(\n processed,\n /(?:\\/[\\w.\\-\\\\\\/]+|(?<=[\\w.\\-])\\.\\.?[\\\\\\/][\\w.\\-\\\\\\/]+|(?<=^|[\\s([{\"'`])[a-zA-Z]:[\\\\\\/][\\w.\\-\\\\\\/]+|(?<![^\\s([{\"'`])\\b(?:[\\w.\\-]+\\/)+[\\w.\\-]+\\.[a-zA-Z0-9]+\\b|(?<![^\\s([{\"'`])\\b[\\w.\\-]+\\.(?:ts|tsx|js|jsx|json|ya?ml|md|py|go|rs|c|cpp|h|hpp|css|scss|html|sh|bash|mjs|cjs|toml|lock|log|env|svg|png|jpe?g|gif|tar|gz|zip|xml|sql)\\b)/g\n );\n\n // 5. CLI flags / options (--flag, --flag=value, -f)\n processed = wrapRule(\n processed,\n /(?<=^|[\\s(\\[{\"'])((?:--[a-zA-Z0-9_\\-]+(?:=[^\\s\"'<>]+)?)|(?:-[a-zA-Z0-9]+))(?=[\\s)\\]}\",:;!?]|$)/g\n );\n\n const unmask = (translatedText: string): string => {\n if (!translatedText) return translatedText;\n if (masks.length === 0) {\n if (hasAnyMaskResidue(translatedText)) {\n throw new MaskRestoreError(\n 'translation carries a mask token while the source had none',\n 0,\n 0\n );\n }\n return translatedText;\n }\n return replaceMaskTokens(translatedText, format.id, masks, inserted, legacyIndexes);\n };\n\n return {\n maskedText: processed,\n unmask,\n legacyFragments: [...legacyIndexes].map((index) => masks[index]).filter((f) => f !== undefined),\n };\n }\n}\n\n/**\n * Restore every token of `id` in `text` from `masks`.\n *\n * Each fragment of the pass is resolved exactly once, no matter how the engine\n * reordered the sentence: the index embedded in the token identifies the\n * fragment, and the random id identifies the masking pass that owns it. The\n * spaces recorded in `inserted` are removed together with their token, so the\n * spacing the translation produced around the fragment survives untouched.\n *\n * @throws MaskRestoreError when the text does not carry every token exactly\n * once, or still shows a current-format token or a retired token that the\n * source did not already contain \u2014 the caller discards such a translation\n * instead of rendering a repaired guess.\n */\nexport function replaceMaskTokens(\n text: string,\n id: string,\n masks: string[],\n inserted?: InsertedSpacing[],\n legacyIndexes: ReadonlySet<number> = new Set()\n): string {\n // Two scanners, one pass: the complete-token scanner drives the loop, and the\n // prefix scanner catches a complete token whose closing bracket the engine\n // dropped (the complete-token scanner steps over such a prefix entirely).\n const complete = new RegExp(MASK_TOKEN_PATTERN_SOURCE, 'giu');\n const prefix = new RegExp(MASK_TOKEN_PREFIX_PATTERN_SOURCE, 'giu');\n const seen = new Set<number>();\n let out = '';\n let cursor = 0;\n let passes = 0;\n let whole = complete.exec(text);\n let prefixCandidate = prefix.exec(text);\n\n const nextStart = (wholeMatch: RegExpExecArray | null, prefixMatch: RegExpExecArray | null): number =>\n Math.min(\n wholeMatch ? wholeMatch.index : Number.POSITIVE_INFINITY,\n prefixMatch ? prefixMatch.index : Number.POSITIVE_INFINITY\n );\n\n let start = nextStart(whole, prefixCandidate);\n while (start !== Number.POSITIVE_INFINITY && passes++ < MAX_UNMASK_PASSES) {\n // A complete token and a truncated one share a start position only when the\n // token is complete; a truncated one found past it is the shorter match.\n const isPrefix = prefixCandidate !== null && prefixCandidate.index === start && whole?.index !== start;\n const raw = isPrefix ? prefixCandidate![0] : whole![0];\n const match = matchMaskToken(text, start, id);\n if (!match) {\n // A token of another pass or a damaged one: kept verbatim. The\n // completeness check below turns any such leftover into a rejection.\n out += text.slice(cursor, start) + raw;\n cursor = start + raw.length;\n } else {\n if (match.index < 0 || match.index >= masks.length || seen.has(match.index)) {\n throw new MaskRestoreError(\n `translation does not reproduce every protected fragment (bad index ${match.index})`,\n masks.length,\n seen.size\n );\n }\n seen.add(match.index);\n const spacing = isPrefix ? undefined : inserted?.[match.index];\n let before = text.slice(cursor, start);\n // The trailing space the previous fragment brought with it.\n if (spacing?.leading) before = before.replace(INSERTED_SPACE, '');\n if (spacing?.trailing) out = out.replace(INSERTED_SPACE, '');\n out += before + masks[match.index];\n cursor = start + raw.length;\n }\n\n // Skip past every candidate the resolved token already covers.\n while (whole && whole.index < cursor) whole = complete.exec(text);\n while (prefixCandidate && prefixCandidate.index < cursor) prefixCandidate = prefix.exec(text);\n start = nextStart(whole, prefixCandidate);\n }\n\n out += text.slice(cursor);\n\n // Retired-format tokens restored from documented source text are content, not\n // residue; every other occurrence still means a token reached the screen.\n const documented = new Set<string>();\n for (const index of legacyIndexes) {\n const fragment = masks[index];\n if (fragment !== undefined) documented.add(fragment.toLowerCase());\n }\n const residue = (out.match(new RegExp(LEGACY_MASK_TOKEN_PATTERN_SOURCE, 'giu')) ?? []).filter(\n (fragment) => !documented.has(fragment.toLowerCase())\n );\n if (seen.size !== masks.length || hasMaskResidue(out) || residue.length > 0) {\n throw new MaskRestoreError(\n `translation does not reproduce every protected fragment (expected ${masks.length}, found ${seen.size})`,\n masks.length,\n seen.size\n );\n }\n\n return out;\n}\n\n/**\n * True when a translated string still shows a mask token to the user.\n * Callers use it to discard a poisoned translation (and to evict poisoned\n * cache entries written by earlier releases).\n */\nexport function isMaskLeak(translatedText: string): boolean {\n return hasAnyMaskResidue(translatedText);\n}\n\nexport { hasMaskResidue };\n", "/**\n * \u628A fetch / \u7F51\u7EDC\u5931\u8D25\u7684\u53EF\u8BFB\u539F\u56E0\u5C55\u5F00\u6210\u5355\u884C\u6587\u672C\uFF08\u5BBF\u4E3B\u4E0E\u5BA2\u6237\u7AEF\u5171\u7528\uFF09\u3002\n *\n * \u80CC\u666F\uFF1ANode 18+ \u4E0E\u6D4F\u89C8\u5668\u7684 fetch \u5728\u7F51\u7EDC\u5C42\u5931\u8D25\u65F6\u53EA\u7ED9\u4E00\u53E5 `TypeError: fetch failed`\n * \uFF08\u6D4F\u89C8\u5668\u662F `Failed to fetch`\uFF09\uFF0C\u771F\u5B9E\u539F\u56E0\u85CF\u5728 `err.cause` \u91CC\u2014\u2014\u4F8B\u5982\n * `connect ENETUNREACH 172.24.52.126:8081`\u3001`other side closed [UND_ERR_SOCKET]`\u3001\n * `getaddrinfo ENOTFOUND`\u3002\u53EA\u4E0A\u62A5 `err.message` \u4F1A\u8BA9\u300C\u7AEF\u70B9\u4E0D\u53EF\u8FBE / \u88AB\u4EE3\u7406\u65AD\u5F00\u300D\u548C\n * \u300C\u63D2\u4EF6\u81EA\u8EAB\u51FA\u9519\u300D\u957F\u5F97\u4E00\u6A21\u4E00\u6837\uFF1A\u7528\u6237\u53EA\u770B\u5230\u65E0\u4FE1\u606F\u91CF\u7684 fetch failed\uFF0C\u65E0\u4ECE\u5224\u65AD\u8BE5\u6539\u4EC0\u4E48\u3002\n *\n * \u8FD9\u91CC\u628A message \u4E0E cause \u94FE\uFF08\u542B AggregateError \u7684\u591A\u5730\u5740\u5931\u8D25\uFF09\u62FC\u6210 `A \u2190 B \u2190 C`\u3002\n */\nexport function describeError(err: unknown): string {\n if (err === null || err === undefined) return String(err);\n const parts: string[] = [];\n const push = (s: string): void => {\n const t = String(s || '').trim();\n if (t && !parts.includes(t)) parts.push(t);\n };\n const head = (err as { message?: string }).message || String(err);\n push(head);\n const headCode = (err as { code?: string }).code;\n if (headCode && !head.includes(headCode)) push('[' + headCode + ']');\n let cause = (err as { cause?: unknown }).cause as\n | { message?: string; code?: string; cause?: unknown; errors?: unknown }\n | undefined;\n for (let depth = 0; cause && depth < 4; depth++) {\n const label = cause.message || String(cause);\n push(cause.code && !label.includes(cause.code) ? label + ' [' + cause.code + ']' : label);\n // AggregateError\uFF1A\u591A\u5730\u5740\u5168\u90E8\u5931\u8D25\uFF08happy-eyeballs \u53CC\u6808\u5E38\u89C1\uFF09\uFF0C\u5C55\u5F00\u524D\u51E0\u6761\n if (Array.isArray(cause.errors)) {\n for (const sub of (cause.errors as { message?: string; code?: string }[]).slice(0, 3)) {\n if (sub) push(sub.code || sub.message || String(sub));\n }\n }\n cause = cause.cause as typeof cause;\n }\n return parts.join(' \u2190 ');\n}", "import type { ITranslationAdapter, PluginConfig } from './base.ts';\n\n/**\n * Built-in Bing Web translator channel \u2014 no key, no gateway jar, mainland\n * networks reach cn.bing.com directly. This is the same flow DeepLX and\n * Translate_Api_Free use: fetch the translator page for the IG token and the\n * abuse-prevention key/token, then POST to ttranslatev3.\n */\n\nconst TRANSLATOR_URL = 'https://cn.bing.com/translator';\nconst TRANSLATE_URL = 'https://cn.bing.com/ttranslatev3?isVertical=1&&IG={IG}&IID=translator.5025.1';\nconst UA =\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';\n\nconst IG_RES = [\n /_IG=\"([a-zA-Z0-9]+)\"/,\n /,IG:\"([a-zA-Z0-9]+)\"/,\n /IG:\"([a-zA-Z0-9]+)\"/,\n /\"IG\":\"([a-zA-Z0-9]+)\"/,\n];\nconst ABUSE_RES = [\n /params_AbusePreventionHelper\\s*=\\s*\\[\\s*(\\d+)\\s*,\\s*\"([^\"]+)\"/,\n /var\\s+params_AbusePreventionHelper\\s*=\\s*\\[\\s*(\\d+)\\s*,\\s*\"([^\"]+)\"/,\n];\n\ninterface BingTokens {\n ig: string;\n key: string;\n token: string;\n}\n\nlet cachedTokens: BingTokens | null = null;\nlet tokensFetchedAt = 0;\nconst TOKEN_TTL_MS = 15 * 60 * 1000; // 15 minutes\nlet inFlightTokenPromise: Promise<BingTokens> | null = null;\n\nfunction parseTokens(html: string): BingTokens {\n let ig: string | undefined;\n for (const re of IG_RES) {\n const m = re.exec(html);\n if (m && m[1]) {\n ig = m[1];\n break;\n }\n }\n\n let key: string | undefined;\n let token: string | undefined;\n for (const re of ABUSE_RES) {\n const m = re.exec(html);\n if (m && m[1] && m[2]) {\n key = m[1];\n token = m[2];\n break;\n }\n }\n\n if (!ig || !key || !token) {\n throw new Error(`Bing translator page: missing tokens (ig: ${!!ig}, key: ${!!key}, token: ${!!token})`);\n }\n\n return { ig, key, token };\n}\n\nexport async function fetchTokens(signal: AbortSignal, forceRefresh = false): Promise<BingTokens> {\n if (!forceRefresh && cachedTokens && Date.now() - tokensFetchedAt < TOKEN_TTL_MS) {\n return cachedTokens;\n }\n\n if (inFlightTokenPromise) {\n return inFlightTokenPromise;\n }\n\n inFlightTokenPromise = (async () => {\n try {\n const response = await fetch(TRANSLATOR_URL, {\n headers: {\n 'User-Agent': UA,\n Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n },\n signal,\n });\n if (!response.ok) {\n throw new Error(`Bing translator page responded with status ${response.status}`);\n }\n const html = await response.text();\n const tokens = parseTokens(html);\n cachedTokens = tokens;\n tokensFetchedAt = Date.now();\n return tokens;\n } finally {\n inFlightTokenPromise = null;\n }\n })();\n\n return inFlightTokenPromise;\n}\n\nexport class BingWebAdapter implements ITranslationAdapter {\n readonly id = 'bing';\n readonly name = '\u5FAE\u8F6F Bing \u7F51\u9875\u7FFB\u8BD1 (\u514DKey\u76F4\u8FDE)';\n\n isAvailable(_config: PluginConfig): boolean {\n return true; // No key, no gateway URL required\n }\n\n async translate(text: string, signal: AbortSignal, config: PluginConfig): Promise<string> {\n const targetLang = config.targetLang || 'zh-Hans';\n return this.executeTranslate(text, signal, targetLang, false);\n }\n\n private async executeTranslate(\n text: string,\n signal: AbortSignal,\n targetLang: string,\n isRetry: boolean\n ): Promise<string> {\n const tokens = await fetchTokens(signal, isRetry);\n\n const body = new URLSearchParams({\n fromLang: 'auto-detect',\n text,\n to: targetLang,\n key: tokens.key,\n token: tokens.token,\n tryFetchingGenderDebiasedTranslations: 'true',\n });\n\n const response = await fetch(TRANSLATE_URL.replace('{IG}', tokens.ig), {\n method: 'POST',\n headers: {\n 'User-Agent': UA,\n Referer: 'https://cn.bing.com/translator/',\n Origin: 'https://cn.bing.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body,\n signal,\n });\n\n if (!response.ok) {\n cachedTokens = null;\n // Auto retry once with fresh tokens if not already retrying\n if (!isRetry && (response.status === 400 || response.status === 401 || response.status === 403)) {\n return this.executeTranslate(text, signal, targetLang, true);\n }\n throw new Error(`Bing translate responded with status ${response.status}`);\n }\n\n const json = (await response.json()) as Array<{ translations?: Array<{ text?: string }> }>;\n const translated = json?.[0]?.translations?.[0]?.text?.trim();\n if (!translated) {\n cachedTokens = null;\n if (!isRetry) {\n return this.executeTranslate(text, signal, targetLang, true);\n }\n throw new Error('Bing translate returned an empty result');\n }\n return translated;\n }\n}\n", "import type {\n ITranslationAdapter,\n PluginConfig,\n TranslateAdapterOptions,\n} from './base.ts';\nimport type { KeyReader } from '../credentials.ts';\n\n/**\n * OpenAI-compatible Chat Completions translation channel.\n *\n * Talks to `POST {baseUrl}/chat/completions` with a Bearer token read from\n * ~/.dsh/.credentials.yaml (refs.TRANSLATE_API_KEY). Works with OpenAI,\n * DeepSeek, Qwen, Ollama and any other service exposing the standard endpoint.\n */\n\n/** Map Bing-style targetLang codes to a natural language name for the prompt. */\nconst LANG_HINTS: Record<string, string> = {\n 'zh-hans': 'Simplified Chinese',\n 'zh-cn': 'Simplified Chinese',\n 'zh': 'Simplified Chinese',\n 'zh-tw': 'Traditional Chinese',\n 'zh-hant': 'Traditional Chinese',\n en: 'English',\n ja: 'Japanese',\n ko: 'Korean',\n fr: 'French',\n de: 'German',\n es: 'Spanish',\n ru: 'Russian',\n pt: 'Portuguese',\n it: 'Italian',\n};\n\n/**\n * The translator instruction. The placeholder is described by its shape alone:\n * naming any of its characters gives a small model something to echo. The\n * multi-part variant adds the block markers of a packed think-chain request \u2014\n * same bracket-shape description, so the model never sees a token it could\n * reproduce as a word.\n */\nfunction buildSystemPrompt(langName: string, mode: 'plain' | 'blocks'): string {\n const base =\n `You are a professional translator. Translate the user's message into ${langName}. ` +\n `Output ONLY the translated text \u2014 no explanations, no quotation marks, no extra words. ` +\n `Some fragments of the message are opaque code between the bracket ` +\n `characters U+27E6 and U+27E7. Copy each such fragment into your output ` +\n `character-for-character, keeping its position in the sentence. ` +\n `Never invent such a fragment and never remove one.`;\n if (mode === 'plain') return base;\n return (\n base +\n ` The message is a sequence of parts. Each part starts with its own line ` +\n `holding a marker: an index between the bracket characters U+27EA and ` +\n `U+27EB. For every part, output its marker line unchanged, then that ` +\n `part's translation on the following lines. Translate each part on its ` +\n `own, keep the parts in the original order, and never merge two parts ` +\n `into one answer.`\n );\n}\n\nexport class OpenAiCompatibleAdapter implements ITranslationAdapter {\n readonly id = 'openai';\n readonly name = 'OpenAI \u517C\u5BB9 (Chat Completions)';\n\n private credentials: KeyReader;\n\n constructor(credentials: KeyReader) {\n this.credentials = credentials;\n }\n\n isAvailable(config: PluginConfig): boolean {\n return Boolean(\n config.aiEnabled && config.baseUrl?.trim() && config.model?.trim() && this.credentials.getApiKey()\n );\n }\n\n async translate(\n text: string,\n signal: AbortSignal,\n config: PluginConfig,\n options?: TranslateAdapterOptions\n ): Promise<string> {\n const apiKey = this.credentials.getApiKey();\n if (!apiKey) {\n throw new Error(`TRANSLATE_API_KEY is not configured in ~/.dsh/.credentials.yaml`);\n }\n const baseUrl = (config.baseUrl || '').trim().replace(/\\/+$/, '');\n const model = (config.model || '').trim();\n if (!baseUrl || !model) {\n throw new Error('OpenAI channel: baseUrl or model is not configured');\n }\n\n const langName = LANG_HINTS[(config.targetLang || 'zh-Hans').toLowerCase()] || config.targetLang || 'Simplified Chinese';\n\n const response = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0,\n ...(options?.maxTokens === undefined ? {} : { max_tokens: options.maxTokens }),\n messages: [\n { role: 'system', content: buildSystemPrompt(langName, options?.mode ?? 'plain') },\n { role: 'user', content: text },\n ],\n }),\n signal,\n });\n\n if (!response.ok) {\n let detail = '';\n try {\n const errBody = (await response.json()) as { error?: { message?: string }; message?: string };\n detail = errBody?.error?.message || errBody?.message || '';\n } catch {\n // ignore body parse errors\n }\n throw new Error(`OpenAI-compatible API responded with ${response.status}${detail ? `: ${detail}` : ''}`);\n }\n\n const data = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> };\n const content = data?.choices?.[0]?.message?.content;\n const translated = typeof content === 'string' ? content.trim() : '';\n if (!translated) {\n throw new Error('OpenAI-compatible API returned empty content');\n }\n return translated;\n }\n}\n", "import { randomTokenId } from './mask-tokens.ts';\n\n/**\n * \u601D\u8003\u6B63\u6587\u7FFB\u8BD1\u7684\u8BF7\u6C42\u9884\u7B97\u3002\u6BCF\u6B21\u8BF7\u6C42\u7684\u8F93\u5165\u4F30\u7B97 token \u4E0A\u9650\uFF0C\u4E0E\u672C\u5730\u670D\u52A1\u7684\n * prefill \u6279\u6B21\uFF08MAX_NUM_BATCHED_TOKENS\uFF09\u4FDD\u6301\u540C\u4E00\u91CF\u7EA7\uFF1B\u8F93\u51FA\u4E0A\u9650\u5199\u8FDB\u8BF7\u6C42\u4F53\u7684\n * max_tokens\uFF0C\u907F\u514D\u957F\u6587\u672C\u628A\u5269\u4F59\u4E0A\u4E0B\u6587\u5168\u90E8\u82B1\u5728\u751F\u6210\u4E0A\u3002\n */\nexport const THINK_MAX_INPUT_TOKENS = 4096;\nexport const THINK_MAX_OUTPUT_TOKENS = 8192;\n\n/** \u6C49\u5B57\u4E0E\u5168\u89D2\u6807\u70B9\u6309\u4E00\u5B57\u4E00 token \u8BA1\u3002 */\nconst CJK_CHAR = /[\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\\u3000-\\u303f\\uff00-\\uffef]/;\n\n/**\n * \u4FDD\u5B88\u4F30\u7B97\u4E00\u6BB5\u6587\u672C\u5360\u7528\u7684 token \u6570\uFF1A\u6C49\u5B57\u4E00\u5B57\u4E00 token\uFF0C\u5176\u4F59\u6BCF\u4E09\u4E2A\u5B57\u7B26\u4E00 token\u3002\n * \u5B9E\u6D4B\u672C\u673A hy-mt2-1.8b \u7684\u82F1\u6587\u8BED\u6599\u7EA6\u4E3A\u6BCF 3.3 \u5B57\u7B26\u4E00 token\uFF0C\u8FD9\u91CC\u53D6 3 \u4F5C\u4E3A\u4E0A\u754C\uFF0C\n * \u5B81\u53EF\u628A\u8BF7\u6C42\u5207\u5F97\u6BD4\u5B9E\u9645\u9700\u8981\u66F4\u788E\uFF0C\u4E5F\u4E0D\u8BA9\u670D\u52A1\u7AEF\u6536\u5230\u8D85\u51FA\u9884\u671F\u7684 prefill\u3002\n */\nexport function estimateTokens(text: string): number {\n let cjk = 0;\n for (const char of text) {\n if (CJK_CHAR.test(char)) cjk += 1;\n }\n return cjk + Math.ceil((text.length - cjk) / 3);\n}\n\n/** \u6309\u6355\u83B7\u7EC4\u5206\u9694\u7B26\u5207\u5206\uFF0C\u5E76\u8BA9\u5206\u9694\u7B26\u7559\u5728\u524D\u4E00\u4E2A\u7247\u6BB5\u672B\u5C3E\u3002 */\nfunction splitKeepingSeparator(text: string, pattern: RegExp): string[] {\n const parts = text.split(pattern);\n const chunks: string[] = [];\n for (let index = 0; index < parts.length; index += 2) {\n const content = parts[index] ?? '';\n const separator = parts[index + 1] ?? '';\n if (content === '' && separator === '') continue;\n chunks.push(content + separator);\n }\n return chunks;\n}\n\n/** \u6309\u53E5\u672B\u6807\u70B9\u5207\u5206\uFF0C\u4F5C\u4E3A\u7A7A\u884C\u4E0E\u5355\u884C\u90FD\u5207\u4E0D\u5F00\u65F6\u7684\u6700\u540E\u4E00\u6863\u3002 */\nfunction sentenceChunks(text: string): string[] {\n const chunks = text.match(/[^.!?\u3002\uFF01\uFF1F\\n]+[.!?\u3002\uFF01\uFF1F]*[ \\t]*\\n?/g);\n return chunks === null ? [text] : chunks.filter((chunk) => chunk.length > 0);\n}\n\n/** \u5355\u5757\u5185\u90E8\u627E\u4E0D\u5230\u81EA\u7136\u8FB9\u754C\u65F6\u7684\u515C\u5E95\uFF1A\u6309\u4F30\u7B97 token \u786C\u5207\u3002 */\nfunction hardSlice(text: string, maxTokens: number): string[] {\n const out: string[] = [];\n let current = '';\n let tokens = 0;\n for (const char of text) {\n const cost = CJK_CHAR.test(char) ? 1 : 1 / 3;\n if (current !== '' && tokens + cost > maxTokens) {\n out.push(current);\n current = '';\n tokens = 0;\n }\n current += char;\n tokens += cost;\n }\n if (current !== '') out.push(current);\n return out;\n}\n\n/**\n * \u628A\u4E00\u4E2A\u5757\u5207\u6210\u4E0D\u8D85\u8FC7\u4E0A\u9650\u7684\u7247\u6BB5\uFF1A\u4F18\u5148\u7A7A\u884C\uFF0C\u5176\u6B21\u5355\u884C\uFF0C\u518D\u6B21\u53E5\u672B\uFF0C\u6700\u540E\u786C\u5207\u3002\n * \u7247\u6BB5\u6309\u539F\u987A\u5E8F\u62FC\u56DE\u5373\u4E3A\u8BE5\u5757\u7684\u5B8C\u6574\u8BD1\u6587\u3002\n */\nexport function splitOversizedBlock(\n text: string,\n maxTokens: number = THINK_MAX_INPUT_TOKENS\n): string[] {\n if (estimateTokens(text) <= maxTokens) return [text];\n\n let chunks = splitKeepingSeparator(text, /(\\n{2,})/);\n if (chunks.length <= 1) chunks = splitKeepingSeparator(text, /(\\n)/);\n if (chunks.length <= 1) chunks = sentenceChunks(text);\n\n const out: string[] = [];\n let current = '';\n for (const chunk of chunks) {\n if (estimateTokens(chunk) > maxTokens) {\n if (current !== '') {\n out.push(current);\n current = '';\n }\n out.push(...hardSlice(chunk, maxTokens));\n continue;\n }\n if (current !== '' && estimateTokens(current + chunk) > maxTokens) {\n out.push(current);\n current = '';\n }\n current += chunk;\n }\n if (current !== '') out.push(current);\n return out;\n}\n\n/** \u4E00\u4E2A\u5F85\u7FFB\u8BD1\u7684\u7247\u6BB5\uFF1A\u5C5E\u4E8E\u54EA\u4E2A\u5757\u3001\u5757\u5185\u7B2C\u51E0\u6BB5\u3001\u4EE5\u53CA\u8BE5\u7247\u6BB5\u7684\u63A9\u7801\u7ED3\u679C\u3002 */\nexport interface ThinkPieceShell<TMask> {\n block: number;\n index: number;\n text: string;\n mask: TMask;\n}\n\n/** \u628A\u7247\u6BB5\u6309\u539F\u987A\u5E8F\u6253\u5305\u6210\u5C3D\u91CF\u5C11\u7684\u8BF7\u6C42\uFF0C\u4E14\u6BCF\u6279\u4E0D\u8D85\u8FC7\u8F93\u5165\u4E0A\u9650\u3002 */\nexport function packPieces<T extends { text: string }>(\n pieces: T[],\n maxTokens: number = THINK_MAX_INPUT_TOKENS\n): T[][] {\n const batches: T[][] = [];\n let current: T[] = [];\n let tokens = 0;\n for (const piece of pieces) {\n const cost = estimateTokens(piece.text);\n if (current.length > 0 && tokens + cost > maxTokens) {\n batches.push(current);\n current = [];\n tokens = 0;\n }\n current.push(piece);\n tokens += cost;\n }\n if (current.length > 0) batches.push(current);\n return batches;\n}\n\n/**\n * \u5757\u5206\u9694\u6807\u8BB0\uFF1A`\u27EA<4 letters><index>\u27EB`\u3002\u5916\u62EC\u53F7\u523B\u610F\u4E0E\u63A9\u7801\u5360\u4F4D\u7B26\u7684 \u27E6\u27E7 \u4E0D\u540C\u5F62\uFF0C\n * \u63A9\u7801\u6B8B\u7559\u68C0\u6D4B\uFF08\u53EA\u8BA4 \u27E6\u27E7\uFF09\u56E0\u6B64\u4E0D\u4F1A\u628A\u8FD9\u4E2A\u6807\u8BB0\u5F53\u6210\u6CC4\u6F0F\u3002\n */\nexport interface ThinkBatchFormat {\n id: string;\n token: (index: number) => string;\n}\n\nexport function createThinkBatchFormat(): ThinkBatchFormat {\n const id = randomTokenId();\n return {\n id,\n token: (index: number) => `\u27EA${id}${index}\u27EB`,\n };\n}\n\n/** \u6807\u8BB0\u51FA\u73B0\u5728\u88AB\u7FFB\u8BD1\u6587\u672C\u91CC\u7684\u901A\u7528\u5F62\u72B6\uFF0C\u4E0D\u95EE id\u3002 */\nconst BATCH_TOKEN_PATTERN_SOURCE = '\u27EA([a-z]{4})(\\\\d+)\u27EB';\n\n/** \u6BCF\u4E2A\u7247\u6BB5\u4EE5\u5355\u72EC\u4E00\u884C\u6807\u8BB0\u5F00\u5934\uFF0C\u6BB5\u4E0E\u6BB5\u4E4B\u95F4\u7A7A\u4E00\u884C\u3002 */\nexport function buildBatchPayload(pieces: string[], format: ThinkBatchFormat): string {\n return pieces.map((text, index) => `${format.token(index)}\\n${text}`).join('\\n\\n');\n}\n\n/**\n * \u6309\u6807\u8BB0\u628A\u6574\u6279\u8BD1\u6587\u5207\u56DE\u6BCF\u4E2A\u7247\u6BB5\u3002\n *\n * \u5E8F\u53F7\u5FC5\u987B\u6070\u597D\u51FA\u73B0\u4E00\u6B21\u3001\u6309 0..count-1 \u5347\u5E8F\u3001\u6BCF\u6BB5\u975E\u7A7A\uFF0C\u4E14\u4E0D\u5F97\u6DF7\u5165\u5176\u5B83\u6279\u6B21\n * \u7684\u6807\u8BB0\uFF1B\u4EFB\u4F55\u4E00\u6761\u4E0D\u6EE1\u8DB3\u90FD\u8FD4\u56DE null\uFF0C\u7531\u8C03\u7528\u65B9\u4F5C\u5E9F\u6574\u6279\u5E76\u9000\u56DE\u5355\u5757\u91CD\u8BD5\u3002\n */\nexport function splitBatchTranslation(\n translated: string,\n format: ThinkBatchFormat,\n count: number\n): string[] | null {\n const pattern = new RegExp(BATCH_TOKEN_PATTERN_SOURCE, 'gu');\n const found: Array<{ index: number; start: number; end: number }> = [];\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(translated)) !== null) {\n if (match[1].toLowerCase() !== format.id.toLowerCase()) return null;\n const index = Number.parseInt(match[2] ?? '', 10);\n if (Number.isNaN(index)) return null;\n found.push({ index, start: match.index, end: match.index + match[0].length });\n }\n if (found.length !== count) return null;\n\n const parts: string[] = [];\n for (let index = 0; index < count; index++) {\n const entry = found[index]!;\n if (entry.index !== index) return null;\n const next = found[index + 1];\n const body = translated.slice(entry.end, next === undefined ? translated.length : next.start).trim();\n if (body === '') return null;\n parts.push(body);\n }\n return parts;\n}\n\n/** \u7FFB\u8BD1\u7ED3\u679C\u91CC\u662F\u5426\u8FD8\u7559\u7740\u5757\u6807\u8BB0\uFF08\u7528\u4E8E\u5224\u5B9A\u6574\u6279\u4F5C\u5E9F\uFF09\u3002 */\nexport function hasThinkBatchResidue(text: string): boolean {\n return new RegExp(BATCH_TOKEN_PATTERN_SOURCE, 'u').test(text);\n}\n", "import { describeError } from '../describe-error.ts';\nimport type {\n ITranslationAdapter,\n PluginConfig,\n ThinkBlockResult,\n TranslateItemResult,\n} from './types.ts';\nimport type { ConfigManager } from './config.ts';\nimport { MAX_CONCURRENCY, THINK_CACHE_ENTRIES } from './config.ts';\nimport { LruDiskCache } from './cache.ts';\nimport type { KeyReader } from './credentials.ts';\nimport { BingWebAdapter } from './adapters/bing.ts';\nimport { OpenAiCompatibleAdapter } from './adapters/openai.ts';\nimport {\n ContentMaskingPipeline,\n MaskRestoreError,\n type MaskResult,\n} from './pipeline/masking.ts';\nimport { findLegacyMaskTokens, hasMaskResidue } from './pipeline/mask-tokens.ts';\nimport {\n buildBatchPayload,\n createThinkBatchFormat,\n hasThinkBatchResidue,\n packPieces,\n splitBatchTranslation,\n splitOversizedBlock,\n THINK_MAX_OUTPUT_TOKENS,\n} from './pipeline/think.ts';\n\ntype CircuitStateEnum = 'closed' | 'open' | 'half-open';\n\n/** \u601D\u8003\u6B63\u6587\u7684\u4E00\u4E2A\u5F85\u7FFB\u8BD1\u7247\u6BB5\uFF1A\u6240\u5C5E\u5757\u3001\u5757\u5185\u5E8F\u53F7\u3001\u63A9\u7801\u6587\u672C\u4E0E\u8FD8\u539F\u4FE1\u606F\u3002 */\ninterface ThinkPiece {\n block: number;\n index: number;\n text: string;\n mask: MaskResult;\n /** \u6E90\u6587\u672C\u672C\u6765\u5C31\u6709\u3001\u8FD8\u539F\u65F6\u5FC5\u987B\u653E\u884C\u7684\u65E7\u683C\u5F0F\u6807\u8BB0\u3002 */\n legacy: Set<string>;\n}\n\n/** \u7247\u6BB5\u5728\u7ED3\u679C\u6620\u5C04\u91CC\u7684\u952E\u3002 */\nfunction thinkPieceKey(piece: { block: number; index: number }): string {\n return `${piece.block}:${piece.index}`;\n}\n\ninterface CircuitState {\n state: CircuitStateEnum;\n failureCount: number;\n openUntil: number;\n probeInFlight: boolean; // single-flight guard for half-open probes\n}\n\nexport class TranslationDispatcher {\n private configManager: ConfigManager;\n private cache: LruDiskCache;\n /** \u601D\u8003\u6B63\u6587\u8BD1\u6587\u7684\u72EC\u7ACB\u7F13\u5B58\u6C60\uFF0C\u4E0E\u5DE5\u5177\u6807\u9898\u7684\u6C60\u4E92\u4E0D\u6324\u5360\u3002 */\n private thinkCache: LruDiskCache;\n private credentials: KeyReader;\n private masking = new ContentMaskingPipeline();\n private adapters = new Map<string, ITranslationAdapter>();\n private circuitStates = new Map<string, CircuitState>();\n private inFlightMap = new Map<string, Promise<TranslateItemResult>>();\n private activeCount = 0;\n private queue: Array<() => void> = [];\n /** \u601D\u8003\u94FE\u8BF7\u6C42\u7684\u4E32\u884C\u961F\u5217\u5C3E\uFF0C\u4FDD\u8BC1\u540C\u65F6\u6700\u591A\u4E00\u4E2A\u5728\u9014\u8BF7\u6C42\u3002 */\n private thinkTail: Promise<void> = Promise.resolve();\n\n constructor(\n configManager: ConfigManager,\n cache: LruDiskCache,\n credentials?: KeyReader,\n thinkCache: LruDiskCache = new LruDiskCache(THINK_CACHE_ENTRIES, 'think-cache.json')\n ) {\n this.configManager = configManager;\n this.cache = cache;\n this.thinkCache = thinkCache;\n this.credentials = credentials ?? { getApiKey: () => '' };\n\n // AI channel first (primary), Bing second (fallback) \u2014 map iteration order\n // follows registration order, so computeChannels() yields ['openai', 'bing'].\n this.registerAdapter(new OpenAiCompatibleAdapter(this.credentials));\n this.registerAdapter(new BingWebAdapter());\n\n // Listen to config changes to wake up queue on concurrency increase\n this.configManager.onConfigChange(() => {\n this.processNext();\n });\n }\n\n private registerAdapter(adapter: ITranslationAdapter): void {\n this.adapters.set(adapter.id, adapter);\n }\n\n /**\n * Decide which channels are active for the current config, in priority order.\n *\n * Truth table (user contract):\n * - AI on + configured + Bing on -> [openai, bing] (AI first, Bing fallback)\n * - AI on + NOT configured + Bing on -> [bing]\n * - AI on + NOT configured + Bing off -> [] (no translation)\n * - AI off + Bing on -> [bing]\n * - AI off + Bing off -> [] (no translation)\n */\n private computeChannels(config: PluginConfig): string[] {\n const channels: string[] = [];\n for (const [id, adapter] of this.adapters) {\n if (id === 'openai') {\n if (\n config.aiEnabled &&\n config.baseUrl?.trim() &&\n config.model?.trim() &&\n this.credentials.getApiKey()\n ) {\n channels.push(id);\n }\n continue;\n }\n if (id === 'bing') {\n if (config.bingEnabled) channels.push(id);\n continue;\n }\n // Custom/test adapters honor their own availability.\n if (adapter.isAvailable(config)) channels.push(id);\n }\n return channels;\n }\n\n async translateBatch(\n texts: string[],\n forceRefresh = false\n ): Promise<TranslateItemResult[]> {\n return Promise.all(texts.map((t) => this.translateOne(t, forceRefresh)));\n }\n\n async translateOne(\n rawText: string,\n forceRefresh = false\n ): Promise<TranslateItemResult> {\n const text = rawText.trim();\n if (!text) {\n return { original: rawText, translated: rawText, channel: 'none', cached: true };\n }\n\n const config = this.configManager.getConfig();\n if (!config.enabled) {\n return { original: rawText, translated: rawText, channel: 'disabled', cached: true };\n }\n\n const cacheKey = text.toLowerCase();\n\n // 1. Check L1/L2 Cache\n if (!forceRefresh) {\n const cached = this.cache.get(cacheKey);\n if (cached) {\n return { original: rawText, translated: cached, channel: 'cache', cached: true };\n }\n }\n\n // 2. In-flight Promise deduplication (only when not forceRefresh)\n if (!forceRefresh) {\n const inFlight = this.inFlightMap.get(cacheKey);\n if (inFlight) {\n return inFlight;\n }\n }\n\n // Mask code blocks, inline code, paths, urls, flags\n const { maskedText, unmask, legacyFragments } = this.masking.mask(text);\n // Retired-format tokens the source documented come back on purpose.\n const documentedLegacy = new Set(legacyFragments.map((fragment) => fragment.toLowerCase()));\n\n // 3. Queue task with concurrency limit\n const taskPromise = this.enqueueTask(async () => {\n const currentConfig = this.configManager.getConfig();\n const channels = this.computeChannels(currentConfig);\n\n for (const chId of channels) {\n const adapter = this.adapters.get(chId);\n if (!adapter || !adapter.isAvailable(currentConfig) || this.isCircuitOpen(chId)) {\n continue;\n }\n\n try {\n const timeout = chId === 'openai'\n ? currentConfig.aiTimeoutMs || 30000\n : currentConfig.timeoutMs || 2000;\n const abortCtrl = new AbortController();\n const timer = setTimeout(() => abortCtrl.abort(), timeout);\n\n let translatedMasked = '';\n try {\n translatedMasked = await adapter.translate(maskedText, abortCtrl.signal, currentConfig);\n } finally {\n clearTimeout(timer);\n }\n\n const cleaned = translatedMasked?.trim();\n if (cleaned && cleaned.length > 0) {\n // Restore every protected fragment. `unmask` throws when the engine\n // did not hand the whole token sequence back, and the leftover check\n // covers the same ground on the finished string; either way the\n // translation is discarded and the next channel is tried, so a\n // damaged placeholder is never rendered or cached.\n const finalTranslated = unmask(cleaned);\n // Retired-format tokens the source documented are content; anything\n // else token-shaped reaching the finished string is a leak.\n const legacyLeftovers = findLegacyMaskTokens(finalTranslated).filter(\n (fragment) => !documentedLegacy.has(fragment.toLowerCase())\n );\n if (hasMaskResidue(finalTranslated) || legacyLeftovers.length > 0) {\n this.recordFailure(chId);\n console.warn(\n `[dsh-chat-translate] channel ${chId} left a mask placeholder in the translation, discarding its result | text: ${text.slice(0, 60)}`\n );\n continue;\n }\n this.recordSuccess(chId);\n this.cache.set(cacheKey, finalTranslated);\n return {\n original: rawText,\n translated: finalTranslated,\n channel: chId,\n cached: false,\n };\n }\n // Empty result counts as a failure: it releases a half-open probe\n // flag (which would otherwise leak and permanently bypass the\n // channel) and feeds the circuit-breaker failure counter.\n this.recordFailure(chId);\n console.warn(\n `[dsh-chat-translate] channel ${chId} returned an empty translation | text: ${text.slice(0, 60)}`\n );\n } catch (err: any) {\n this.recordFailure(chId);\n const detail =\n err instanceof MaskRestoreError\n ? ` (protected fragments expected ${err.expectedCount}, restored ${err.foundCount})`\n : '';\n console.warn(\n `[dsh-chat-translate] channel ${chId} failed: ${describeError(err)}${detail} | text: ${text.slice(0, 60)}`\n );\n // Continue to next channel\n }\n }\n\n return { original: rawText, translated: rawText, channel: 'fallback', cached: false };\n });\n\n if (!forceRefresh) {\n this.inFlightMap.set(cacheKey, taskPromise);\n }\n\n try {\n return await taskPromise;\n } finally {\n if (!forceRefresh) {\n this.inFlightMap.delete(cacheKey);\n }\n }\n }\n\n /**\n * \u7FFB\u8BD1\u601D\u8003\u6B63\u6587\u7684\u5757\u3002\u6574\u6761\u94FE\u8DEF\u4E0E\u5DE5\u5177\u6807\u9898\u7FFB\u8BD1\u5206\u79BB\uFF1A\u53EA\u8D70 AI \u901A\u9053\u3001\u72EC\u7ACB\u4E32\u884C\n * \u961F\u5217\u3001\u72EC\u7ACB\u8D85\u65F6\u3001\u72EC\u7ACB\u7F13\u5B58\u6C60\uFF0CBing \u4ECE\u4E0D\u53C2\u4E0E\u3002\n *\n * \u6BCF\u4E2A\u5757\u5148\u6309\u8F93\u5165\u4E0A\u9650\u5207\u6210\u7247\u6BB5\uFF0C\u518D\u5404\u81EA\u63A9\u7801\u3001\u76F8\u90BB\u7247\u6BB5\u6253\u5305\u6210\u4E00\u4E2A\u8BF7\u6C42\uFF1B\u6574\u6279\n * \u5931\u8D25\u65F6\u9000\u56DE\u9010\u7247\u6BB5\u5355\u53D1\uFF0C\u4ECD\u5931\u8D25\u7684\u7247\u6BB5\u4FDD\u7559\u539F\u6587\u3002\u5757\u5185\u4EFB\u4E00\u7247\u6BB5\u5931\u8D25\u5373\u6574\u5757\u4E0D\u8BD1\uFF0C\n * \u907F\u514D\u534A\u4E2D\u534A\u82F1\u7684\u6BB5\u843D\u3002\n */\n async translateThinkBlocks(blocks: string[]): Promise<ThinkBlockResult[]> {\n const results: ThinkBlockResult[] = blocks.map((original) => ({\n original,\n translated: original,\n ok: false,\n cached: false,\n channel: 'none',\n }));\n\n const config = this.configManager.getConfig();\n if (!config.enabled || !config.thinkEnabled) return results;\n\n const adapter = this.adapters.get('openai');\n if (!adapter || !adapter.isAvailable(config) || this.isChannelCoolingDown('openai')) {\n return results;\n }\n\n const pieces: ThinkPiece[] = [];\n for (let block = 0; block < blocks.length; block++) {\n const text = (blocks[block] ?? '').trim();\n if (!text) continue;\n const cached = this.thinkCache.get(text.toLowerCase());\n if (cached) {\n results[block] = {\n original: blocks[block]!,\n translated: cached,\n ok: true,\n cached: true,\n channel: 'cache',\n };\n continue;\n }\n for (const [index, part] of splitOversizedBlock(text).entries()) {\n const mask = this.masking.mask(part);\n pieces.push({\n block,\n index,\n text: mask.maskedText,\n mask,\n legacy: new Set(mask.legacyFragments.map((fragment) => fragment.toLowerCase())),\n });\n }\n }\n\n const translated = new Map<string, string>();\n for (const batch of packPieces(pieces)) {\n const outcome = await this.runThinkSerial(() =>\n this.translateThinkBatch(adapter, batch, config)\n );\n for (const [key, value] of outcome) translated.set(key, value);\n }\n\n const totals = new Map<number, number>();\n for (const piece of pieces) totals.set(piece.block, (totals.get(piece.block) ?? 0) + 1);\n\n for (const [block, total] of totals) {\n const parts: string[] = [];\n let complete = true;\n for (let index = 0; index < total; index++) {\n const part = translated.get(`${block}:${index}`);\n if (part === undefined) {\n complete = false;\n break;\n }\n parts.push(part);\n }\n if (!complete) continue;\n const original = blocks[block]!;\n const finalText = parts.join('');\n this.thinkCache.set(original.trim().toLowerCase(), finalText);\n results[block] = { original, translated: finalText, ok: true, cached: false, channel: 'openai' };\n }\n\n return results;\n }\n\n /**\n * \u4E00\u6574\u6279\u4E00\u6B21\u8BF7\u6C42\uFF1B\u5931\u8D25\u5219\u8BE5\u6279\u9010\u7247\u6BB5\u5355\u53D1\u91CD\u8BD5\u4E00\u6B21\uFF0C\u4ECD\u5931\u8D25\u7684\u7247\u6BB5\u76F4\u63A5\u653E\u5F03\n * \uFF08\u4FDD\u7559\u539F\u6587\uFF09\uFF0C\u4E0D\u5728\u754C\u9762\u4E0A\u7559\u63D0\u793A\u3002\n */\n private async translateThinkBatch(\n adapter: ITranslationAdapter,\n batch: ThinkPiece[],\n config: PluginConfig\n ): Promise<Map<string, string>> {\n try {\n return await this.requestThinkBatch(adapter, batch, config);\n } catch (err) {\n console.warn(\n `[dsh-chat-translate] think batch of ${batch.length} failed, retrying per block: ${describeError(err)}`\n );\n }\n\n const out = new Map<string, string>();\n for (const piece of batch) {\n try {\n for (const [key, value] of await this.requestThinkBatch(adapter, [piece], config)) {\n out.set(key, value);\n }\n } catch (err) {\n console.warn(\n `[dsh-chat-translate] think block ${piece.block} #${piece.index} failed, keeping the original: ${describeError(err)}`\n );\n }\n }\n return out;\n }\n\n /** \u53D1\u51FA\u4E00\u6B21\u601D\u8003\u94FE\u8BF7\u6C42\u5E76\u628A\u7ED3\u679C\u8FD8\u539F\u6210\u6BCF\u4E2A\u7247\u6BB5\u7684\u6700\u7EC8\u8BD1\u6587\u3002 */\n private async requestThinkBatch(\n adapter: ITranslationAdapter,\n batch: ThinkPiece[],\n config: PluginConfig\n ): Promise<Map<string, string>> {\n const timeout = config.thinkTimeoutMs || 600000;\n const abortCtrl = new AbortController();\n const timer = setTimeout(() => abortCtrl.abort(), timeout);\n let answers: string[];\n try {\n if (batch.length === 1) {\n answers = [\n await adapter.translate(batch[0]!.text, abortCtrl.signal, config, {\n maxTokens: THINK_MAX_OUTPUT_TOKENS,\n mode: 'plain',\n }),\n ];\n } else {\n const format = createThinkBatchFormat();\n const answer = await adapter.translate(\n buildBatchPayload(batch.map((piece) => piece.text), format),\n abortCtrl.signal,\n config,\n { maxTokens: THINK_MAX_OUTPUT_TOKENS, mode: 'blocks' }\n );\n const parts = splitBatchTranslation(answer, format, batch.length);\n if (parts === null) {\n throw new Error('think block markers did not survive the translation');\n }\n answers = parts;\n }\n } finally {\n clearTimeout(timer);\n }\n\n const out = new Map<string, string>();\n batch.forEach((piece, index) => {\n const answer = (answers[index] ?? '').trim();\n if (!answer) {\n throw new Error(`think block ${piece.block} #${piece.index} came back empty`);\n }\n if (hasThinkBatchResidue(answer)) {\n throw new Error('think translation left a block marker behind');\n }\n const finalText = piece.mask.unmask(answer);\n const leftovers = findLegacyMaskTokens(finalText).filter(\n (fragment) => !piece.legacy.has(fragment.toLowerCase())\n );\n if (hasMaskResidue(finalText) || leftovers.length > 0) {\n throw new Error('think translation left a mask placeholder behind');\n }\n out.set(thinkPieceKey(piece), finalText);\n });\n return out;\n }\n\n /** \u4E32\u884C\u6267\u884C\u5668\uFF1A\u540C\u65F6\u6700\u591A\u4E00\u4E2A\u5728\u9014\u8BF7\u6C42\uFF0C\u4E0E\u5DE5\u5177\u6807\u9898\u7684\u5E76\u53D1\u6C60\u5B8C\u5168\u72EC\u7ACB\u3002 */\n private runThinkSerial<T>(task: () => Promise<T>): Promise<T> {\n const next = this.thinkTail.then(task, task);\n this.thinkTail = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n }\n\n /**\n * \u53EA\u8BFB\u5224\u65AD\u67D0\u901A\u9053\u662F\u5426\u8FD8\u5728\u7194\u65AD\u51B7\u5374\u671F\u3002\u601D\u8003\u94FE\u7FFB\u8BD1\u53EA\u501F\u7528\u8FD9\u4E2A\u5224\u65AD\u907F\u5F00\u5DF2\u7ECF\n * \u51FA\u95EE\u9898\u7684\u670D\u52A1\uFF0C\u4E0D\u6539\u52A8\u7194\u65AD\u72B6\u6001\u672C\u8EAB\uFF08\u90A3\u662F\u5DE5\u5177\u6807\u9898\u901A\u9053\u7684\u8BB0\u8D26\uFF09\u3002\n */\n private isChannelCoolingDown(channelId: string): boolean {\n const state = this.circuitStates.get(channelId);\n return state !== undefined && state.state === 'open' && Date.now() < state.openUntil;\n }\n\n async testChannel(channelId: string): Promise<{ ok: boolean; latencyMs: number; error?: string }> {\n const adapter = this.adapters.get(channelId);\n const config = this.configManager.getConfig();\n if (!adapter) {\n return { ok: false, latencyMs: 0, error: `Channel ${channelId} not found` };\n }\n if (!adapter.isAvailable(config)) {\n return { ok: false, latencyMs: 0, error: `Channel ${channelId} is not configured or disabled` };\n }\n\n const testText = 'List files in current directory';\n const start = Date.now();\n try {\n const timeout = channelId === 'openai' ? Math.min(config.aiTimeoutMs || 30000, 30000) : 4000;\n const abortCtrl = new AbortController();\n const timer = setTimeout(() => abortCtrl.abort(), timeout);\n let res = '';\n try {\n res = await adapter.translate(testText, abortCtrl.signal, config);\n } finally {\n clearTimeout(timer);\n }\n\n const latencyMs = Date.now() - start;\n if (res && res.trim()) {\n return { ok: true, latencyMs };\n }\n return { ok: false, latencyMs, error: 'Empty translation returned' };\n } catch (err: any) {\n return { ok: false, latencyMs: Date.now() - start, error: describeError(err) };\n }\n }\n\n private enqueueTask<T>(task: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const exec = async () => {\n this.activeCount++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.activeCount--;\n this.processNext();\n }\n };\n\n const maxConcurrency = Math.min(\n Math.max(this.configManager.getConfig().concurrency || 3, 1),\n MAX_CONCURRENCY\n );\n\n if (this.activeCount < maxConcurrency) {\n exec();\n } else {\n this.queue.push(exec);\n }\n });\n }\n\n private processNext(): void {\n const maxConcurrency = Math.min(\n Math.max(this.configManager.getConfig().concurrency || 3, 1),\n MAX_CONCURRENCY\n );\n\n while (this.queue.length > 0 && this.activeCount < maxConcurrency) {\n const next = this.queue.shift();\n if (next) {\n next();\n }\n }\n }\n\n private isCircuitOpen(channelId: string): boolean {\n let state = this.circuitStates.get(channelId);\n if (!state) return false;\n\n if (state.state === 'open') {\n if (Date.now() >= state.openUntil) {\n // Timeout elapsed -> transition to half-open; the first caller becomes\n // the single in-flight probe.\n state.state = 'half-open';\n state.probeInFlight = true;\n return false;\n }\n return true;\n }\n\n if (state.state === 'half-open') {\n // Single-flight: exactly one probe may run at a time, all others wait.\n if (state.probeInFlight) return true;\n state.probeInFlight = true;\n return false;\n }\n\n return false;\n }\n\n private recordSuccess(channelId: string): void {\n const state = this.circuitStates.get(channelId);\n if (state) {\n state.state = 'closed';\n state.failureCount = 0;\n state.openUntil = 0;\n state.probeInFlight = false;\n }\n }\n\n private recordFailure(channelId: string): void {\n let state = this.circuitStates.get(channelId);\n if (!state) {\n state = { state: 'closed', failureCount: 0, openUntil: 0, probeInFlight: false };\n this.circuitStates.set(channelId, state);\n }\n\n if (state.state === 'half-open') {\n // Probe failed -> trip back to open for 30s\n state.state = 'open';\n state.failureCount = 3;\n state.openUntil = Date.now() + 30000;\n state.probeInFlight = false;\n return;\n }\n\n state.failureCount++;\n if (state.failureCount >= 3) {\n state.state = 'open';\n state.openUntil = Date.now() + 30000; // Open circuit for 30 seconds\n }\n }\n}\n", "import type { ConnectionFetchRoute } from '@deepseek-ai/dsh-client-connection';\nimport { describeError } from '../describe-error.ts';\nimport type { TranslationDispatcher } from './dispatcher.ts';\n\n/**\n * Translation proxy surface, carried by Connection's exact Fetch routes below\n * the shared `/api` channel.\n *\n * Config and credentials have no HTTP endpoints: since 1.2 the settings panel\n * reads and writes through DSH's own channels \u2014 the client `SettingsScope`\n * service and the `credentials` Remote API \u2014 so the plugin owns exactly three\n * routes: short-text batch translation, think-chain block translation, and the\n * channel probe.\n */\n\n/** Batch-translation route path. */\nexport const TRANSLATE_ROUTE_PATH = '/api/dsh-chat-translate/translate';\n\n/** Single-channel probe route path. */\nexport const TEST_CHANNEL_ROUTE_PATH = '/api/dsh-chat-translate/test-channel';\n\n/** Think-chain block translation route path. */\nexport const THINK_ROUTE_PATH = '/api/dsh-chat-translate/translate-think';\n\nfunction sendJson(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json; charset=utf-8' },\n });\n}\n\n/**\n * Decode one buffered JSON request body.\n * @returns the parsed value, or the 400 response the caller must return.\n */\nasync function readJson(request: Request): Promise<\n { ok: true; value: any } | { ok: false; response: Response }\n> {\n try {\n return { ok: true, value: await request.json() };\n } catch {\n return { ok: false, response: sendJson(400, { ok: false, error: 'Invalid JSON body' }) };\n }\n}\n\n/**\n * Build the plugin's exact Fetch routes.\n * @param dispatcher - translation coordinator the routes proxy to.\n * @param ready - settles once host-side async resources are usable; every\n * request waits for it before touching the dispatcher.\n */\nexport function createFetchRoutes(\n dispatcher: TranslationDispatcher,\n ready: Promise<unknown> = Promise.resolve()\n): ConnectionFetchRoute[] {\n const translate: ConnectionFetchRoute = {\n path: TRANSLATE_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request) => {\n await ready;\n try {\n const body = await readJson(request);\n if (!body.ok) return body.response;\n const parsed = body.value;\n const rawTexts: unknown = parsed.texts !== undefined ? parsed.texts : parsed.text;\n\n let texts: string[] = [];\n if (Array.isArray(rawTexts)) {\n texts = rawTexts.filter((t): t is string => typeof t === 'string');\n } else if (typeof rawTexts === 'string') {\n texts = [rawTexts];\n }\n\n const forceRefresh = Boolean(parsed.forceRefresh);\n\n if (texts.length === 0) {\n return sendJson(200, { ok: true, results: [] });\n }\n\n const results = await dispatcher.translateBatch(texts, forceRefresh);\n return sendJson(200, { ok: true, results });\n } catch (err: any) {\n return sendJson(500, { ok: false, error: describeError(err) });\n }\n },\n };\n\n const think: ConnectionFetchRoute = {\n path: THINK_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request) => {\n await ready;\n try {\n const body = await readJson(request);\n if (!body.ok) return body.response;\n const rawBlocks: unknown = body.value?.blocks;\n const blocks = Array.isArray(rawBlocks)\n ? rawBlocks.filter((block): block is string => typeof block === 'string')\n : [];\n if (blocks.length === 0) {\n return sendJson(200, { ok: true, results: [] });\n }\n const results = await dispatcher.translateThinkBlocks(blocks);\n return sendJson(200, { ok: true, results });\n } catch (err: any) {\n return sendJson(500, { ok: false, error: describeError(err) });\n }\n },\n };\n\n const testChannel: ConnectionFetchRoute = {\n path: TEST_CHANNEL_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request) => {\n await ready;\n try {\n const body = await readJson(request);\n if (!body.ok) return body.response;\n const channelId = typeof body.value.channel === 'string' ? body.value.channel : '';\n const result = await dispatcher.testChannel(channelId);\n return sendJson(200, result);\n } catch (err: any) {\n return sendJson(500, { ok: false, error: describeError(err) });\n }\n },\n };\n\n return [translate, think, testChannel];\n}\n", "import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection';\nimport z from '@deepseek-ai/schemastery';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport {\n ConfigManager,\n migrateLegacyConfigFile,\n SETTINGS_NAMESPACE,\n DEFAULT_CONFIG,\n MAX_CONCURRENCY,\n AI_TIMEOUT_MIN,\n AI_TIMEOUT_MAX,\n THINK_TIMEOUT_MIN,\n THINK_TIMEOUT_MAX,\n THINK_CACHE_ENTRIES,\n type SettingsMigrationTarget,\n} from './server/config.ts';\nimport { CredentialsReader, TRANSLATE_API_KEY_REF } from './server/credentials.ts';\nimport { LruDiskCache } from './server/cache.ts';\nimport { TranslationDispatcher } from './server/dispatcher.ts';\nimport { createFetchRoutes } from './server/router.ts';\n\n/** Stable Cordis loader name. */\nexport const name = 'dsh-chat-translate';\n\n/**\n * Hard dependencies: settings and credentials are the DSH-owned config/secret\n * surfaces this plugin rides on (no standalone config file since 1.2). The\n * translation routes register through the connection service when a Web\n * carrier composes it, so apply takes that service through ctx.inject and the\n * plugin still loads in compositions without one.\n */\nexport const inject = ['settings', 'credentials'];\n\n/** Settings namespace schema: defaults + bounds, resolved by DSH itself. */\nconst CONFIG_SCHEMA = z.object({\n enabled: z.boolean().default(DEFAULT_CONFIG.enabled),\n concurrency: z.number().min(1).max(MAX_CONCURRENCY).default(DEFAULT_CONFIG.concurrency),\n timeoutMs: z.number().min(500).max(10000).default(DEFAULT_CONFIG.timeoutMs),\n aiTimeoutMs: z.number().min(AI_TIMEOUT_MIN).max(AI_TIMEOUT_MAX).default(DEFAULT_CONFIG.aiTimeoutMs),\n thinkTimeoutMs: z\n .number()\n .min(THINK_TIMEOUT_MIN)\n .max(THINK_TIMEOUT_MAX)\n .default(DEFAULT_CONFIG.thinkTimeoutMs),\n aiEnabled: z.boolean().default(DEFAULT_CONFIG.aiEnabled),\n bingEnabled: z.boolean().default(DEFAULT_CONFIG.bingEnabled),\n thinkEnabled: z.boolean().default(DEFAULT_CONFIG.thinkEnabled),\n baseUrl: z.string().default(DEFAULT_CONFIG.baseUrl),\n model: z.string().default(DEFAULT_CONFIG.model),\n targetLang: z.string().default(DEFAULT_CONFIG.targetLang),\n});\n\ninterface HostContext {\n connection: HostConnectionHandle;\n settings: SettingsMigrationTarget & {\n register(ns: string, schema: unknown): {\n get(): any;\n watch(listener: (config: any) => void): () => void;\n update(patch: Record<string, unknown>): Promise<unknown>;\n };\n };\n credentials: {\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n set(ref: string, value: string): Promise<void>;\n unset(ref: string): Promise<void>;\n };\n on(event: string, listener: (...args: any[]) => void): () => void;\n /** Optional-service injection: the callback runs once connection is present. */\n inject(names: string[], callback: (ctx: HostContext) => void | (() => void)): void;\n}\n\n/** Mount the host half; provides the translation proxy and rides DSH config. */\nexport function apply(ctx: HostContext): void {\n const credentials = new CredentialsReader(ctx.credentials);\n const configManager = new ConfigManager(ctx.settings.register(SETTINGS_NAMESPACE, CONFIG_SCHEMA), credentials);\n const cache = new LruDiskCache(1000);\n const thinkCache = new LruDiskCache(THINK_CACHE_ENTRIES, 'think-cache.json');\n const dispatcher = new TranslationDispatcher(configManager, cache, credentials, thinkCache);\n\n // Initialize async resources: credentials cache, both disk cache pools, and\n // the one-shot migration of the legacy dsh-chat-translate-config.json.\n const legacyConfigPath = dshHomePath('dsh-chat-translate-config.json');\n const initPromise = Promise.all([\n credentials.init(),\n cache.init(),\n thinkCache.init(),\n migrateLegacyConfigFile(ctx.settings, legacyConfigPath),\n ]).catch((err) => {\n console.warn('[dsh-chat-translate] Initialization error:', err);\n });\n\n // Keep the synchronous key cache warm: the credentials service fans this\n // event out after every committed write or external reload.\n ctx.on('credentials/reference-updated', (ref: unknown) => {\n if (ref === TRANSLATE_API_KEY_REF) {\n void credentials.refresh();\n }\n });\n\n // The routes ride Connection's authenticated /api transport, which a Web\n // carrier composes; a composition without one keeps the plugin loaded and\n // simply has no translation endpoint.\n ctx.inject(['connection'], (connectionCtx) => {\n const disposers = createFetchRoutes(dispatcher, initPromise).map((route) =>\n connectionCtx.connection.fetch.register(route)\n );\n return () => {\n void Promise.all(disposers.map((dispose) => dispose()))\n .then(() => Promise.all([cache.dispose(), thinkCache.dispose()]))\n .catch((err) => {\n console.warn('[dsh-chat-translate] Dispose translation routes error:', err);\n });\n };\n });\n}\n"],
|
|
5
|
+
"mappings": ";AAIA,SAAS,WAAW,OAAO;AAC1B,SAAO,UAAU,QAAQ,UAAU;AACpC;AAMA,SAAS,cAAc,MAAM;AAC5B,SAAO,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI;AAC/D;AAEA,SAAS,WAAW,QAAQ,QA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C,CAAC,EACnD,KAAK,MAAM,QAAQ,IAAI,CAAC,MAAM,QAAQ,GAAG,WAAW,QAAQ,CAAC,CAAC,CAAC,EAC/D,MAAM,CAAC,QAAQ;AACd,gBAAQ,KAAK,0DAA0D,GAAG;AAAA,MAC5E,CAAC;AAAA,IACL;AAAA,EACF,CAAC;AACH;",
|
|
6
|
+
"names": ["value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "name", "key", "resolve", "path", "resolve", "fs", "pattern", "push", "pattern", "resolve"]
|
|
7
7
|
}
|