dsh-codegraph-visualizer 0.1.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 +223 -0
- package/cordis.patch.yml +17 -0
- package/dist/client/index.css +2404 -0
- package/dist/client/index.esm.js +44283 -0
- package/dist/client/index.js +46706 -0
- package/dist/client-cjs/index.cjs +44283 -0
- package/dist/client-cjs/index.css +2404 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2277 -0
- package/dist/index.js.map +1 -0
- package/package.json +96 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["value","Binary","result","a","b","Time","template","options","pattern","value","role","date","name","key","id: string","LEVEL_ORDER: Record<LogLevel, number>","level: LogLevel","scope: string","message: string","data?: unknown","entry: LogEntry","fn: (entries: LogEntry[]) => void","m: string","d?: unknown","log","NODE_KIND_MAP: Record<string, GraphNode['type']>","EDGE_KIND_MAP: Record<string, GraphEdge['type']>","kind: string","workspacePath: string","dbPath: string","repoId: string","invoke: UpstreamInvoker","nodes: GraphNode[]","files: unknown","dbNodes: DbNodeRow[]","dbEdges: DbEdgeRow[]","edges: GraphEdge[]","log","repoId: string","invoke: UpstreamInvoker","nodes: GraphNode[]","edges: GraphEdge[]","cat: string","map: Record<string, GraphNode['type']>","rel: string","map: Record<string, GraphEdge['type']>","results: AdapterResult[]","repoId: RepoId","current: GraphData","delta: AdapterResult","log","repoId: string","data: GraphData","invoke: UpstreamInvoker","source: 'codegraph' | 'lens' | 'both'","tasks: Promise<AdapterResult>[]","results: AdapterResult[]","raw: unknown","symbolId: string","ctx: Context","_args: unknown","value: unknown","args: { repoId: string }","args: { repoId: string; source?: string }","emitUpdate: (event: GraphUpdatedEvent) => void","emitData: (event: GraphDataEvent) => void","deltaSource: AdapterResult['source']","args: { symbolId: string }","options: { requestTimeout?: number }","event: GraphUpdatedEvent","event: GraphDataEvent","DEFAULT_CONFIG: VisualizerConfig","userConfig?: Partial<VisualizerConfig>","config: VisualizerConfig","errors: string[]","positiveFields: Array<[keyof VisualizerConfig, number]>","allowedWorkspaceRoots: string[]","roots: string[]","path: string","log","ctx: Context","paths: string[]","log","data: GraphData","maxNodes: number","ctx: Context","config: VisualizerConfig","tool: string","args: Record<string, unknown>","deps: RouteDeps","service: IGraphVisualizerService","repoId: string","symbolId: string","callback: (data: GraphData) => void","res: ServerResponse","code: number","data: unknown","req: IncomingMessage","maxBodyBytes: number","chunk?: Buffer","body: string","obj: Record<string, unknown>","field: string","_req: IncomingMessage","log","watchTimer: ReturnType<typeof setTimeout> | null","activeWatcher: { close: () => void } | null","ctx: Context","config: VisualizerConfig","invokeUpstream: (tool: string, args: Record<string, unknown>) => Promise<unknown | null>","path: string","_eventType: string","filename: string | null","ctx: Context","userConfig?: Partial<VisualizerConfig>","lastGraphData: GraphData | null","lastInitResult: { success: boolean; path: string; message: string; timestamp: number } | null","scanInFlight: Promise<GraphData> | null","data: GraphData | null","data: { success: boolean; path: string; message: string; timestamp: number } | null","p: Promise<GraphData> | null"],"sources":["../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.2/node_modules/@deepseek-ai/cosmokit/lib/index.js","../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs","../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.1.1-rc.2_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-invariants@0.1_2yxulatypvfilrzvurumr2xwty/node_modules/@deepseek-ai/dsh-timeout/lib/index.js","../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.1-rc.2_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-attachment@0.1.1-r_x2n35l65jyhywzqyfdn334iwva/node_modules/@deepseek-ai/dsh-llm/lib/index.js","../src/types/index.ts","../src/shared/Logger.ts","../src/adapters/CodeGraphAdapter.ts","../src/adapters/LensAdapter.ts","../src/merger/GraphDataMerger.ts","../src/tools.ts","../src/generated/version.ts","../src/host/config.ts","../src/host/security.ts","../src/host/prerequisites.ts","../src/host/routes.ts","../src/host/watcher.ts","../src/index.ts"],"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","//#region lib/types/index.js\n/**\n* Shared timeout arithmetic, signal fusion, and classification. The library\n* only notifies through abort signals; each capability still owns the mechanism\n* that stops its work and translates timeout reasons into public outcomes.\n* @module @deepseek-ai/dsh-timeout\n*/\n/**\n* Internal abort reason carrying a capability-owned code and elapsed deadline.\n* Providers translate it through {@link timeoutOf} before returning to callers.\n*/\nvar TimeoutReason = class extends Error {\n\tcode;\n\ttimeoutMs;\n\tname = \"TimeoutReason\";\n\t/**\n\t* @param code Capability-owned timeout code (e.g. `BASH_TIMEOUT`).\n\t* @param timeoutMs The deadline that elapsed, in milliseconds.\n\t*/\n\tconstructor(code, timeoutMs) {\n\t\tsuper(`${code} after ${timeoutMs}ms`);\n\t\tthis.code = code;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n};\n/** Largest delay Node schedules without clamping it to one millisecond. */\nconst MAX_TIMER_DELAY_MS = 2147483647;\nfunction assertTimerDelay(timeoutMs, name) {\n\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error(`${name} must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n}\n/**\n* Validate a caller's optional timeout hint, use the backend default, then cap\n* it. Supplied values must be positive and finite; zero is not a public\n* disable-timeout sentinel.\n*\n* @param requested The caller's optional hint; validated when present.\n* @param def The backend default applied when `requested` is absent.\n* @param max The backend upper bound the result is capped to.\n* @param name Field name used in the thrown message (so the caller sees which input was\n* bad).\n* @returns The effective timeout in milliseconds: `min(requested ?? def, max)`.\n*/\nfunction clampTimeout(requested, def, max, name = \"timeoutMs\") {\n\tif (requested !== void 0 && (!Number.isFinite(requested) || requested <= 0)) throw new Error(`${name} must be a positive finite number`);\n\treturn Math.min(requested ?? def, max);\n}\n/**\n* Fuse upstream cancellation with an identifiable timeout. `timeoutMs <= 0` is\n* the internal no-timer sentinel; the returned disposer clears an armed timer.\n* The signal only notifies, so callers must stop their own work.\n*\n* @param upstream The caller's cancellation signal, if any, fused into the result.\n* @param timeoutMs Deadline in milliseconds; `<= 0` means \"no timeout\" (arm no timer).\n* @param code Capability-owned code stamped onto the timeout's {@link TimeoutReason}.\n* @returns The fused {@link Deadline} (signal + timer cleanup).\n*/\nfunction deadline(upstream, timeoutMs, code) {\n\tif (timeoutMs <= 0) return {\n\t\tsignal: upstream ?? new AbortController().signal,\n\t\t[Symbol.dispose]() {}\n\t};\n\tassertTimerDelay(timeoutMs, \"deadline timeoutMs\");\n\tconst timer = new AbortController();\n\tconst id = setTimeout(() => {\n\t\ttimer.abort(new TimeoutReason(code, timeoutMs));\n\t}, timeoutMs);\n\treturn {\n\t\tsignal: upstream !== void 0 ? AbortSignal.any([upstream, timer.signal]) : timer.signal,\n\t\t[Symbol.dispose]() {\n\t\t\tclearTimeout(id);\n\t\t}\n\t};\n}\n/**\n* Create a rearmable idle watchdog for an async iterator. The timer exists only\n* while {@link IdleWatchdog.next} is outstanding, so consumer think time does\n* not count as provider idle time. The returned signal is stable for the whole\n* call and only notifies; the iterator must observe it to terminate its work.\n*\n* @param upstream - caller cancellation fused into the stable signal.\n* @param timeoutMs - positive finite idle interval in milliseconds.\n* @param code - capability-owned code carried by the timeout reason.\n* @returns a stable signal, guarded next operation, and timer disposer.\n*/\nfunction idleWatchdog(upstream, timeoutMs, code) {\n\tassertTimerDelay(timeoutMs, \"idleWatchdog timeoutMs\");\n\tconst timeout = new AbortController();\n\tconst signal = upstream === void 0 ? timeout.signal : AbortSignal.any([upstream, timeout.signal]);\n\tlet timer;\n\tlet outstanding = false;\n\tlet disposed = false;\n\tconst arm = () => {\n\t\tif (timer !== void 0) clearTimeout(timer);\n\t\ttimer = setTimeout(() => {\n\t\t\ttimeout.abort(new TimeoutReason(code, timeoutMs));\n\t\t}, timeoutMs);\n\t};\n\treturn {\n\t\tsignal,\n\t\tasync next(iterator) {\n\t\t\tif (disposed) throw new Error(\"idleWatchdog is disposed\");\n\t\t\tif (outstanding) throw new Error(\"idleWatchdog next is already outstanding\");\n\t\t\toutstanding = true;\n\t\t\tarm();\n\t\t\ttry {\n\t\t\t\treturn await iterator.next();\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = void 0;\n\t\t\t\toutstanding = false;\n\t\t\t}\n\t\t},\n\t\tpulse() {\n\t\t\tif (disposed || !outstanding) return;\n\t\t\tarm();\n\t\t},\n\t\t[Symbol.dispose]() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tif (timer !== void 0) clearTimeout(timer);\n\t\t\ttimer = void 0;\n\t\t}\n\t};\n}\n/**\n* Recover a timeout reason from a reason-bearing object. Supplying `code`\n* distinguishes this deadline from a nested upstream deadline; a foreign code\n* follows the ordinary cancellation path.\n*\n* @param x An {@link AbortSignal} or any `{ reason }` carrier (e.g. a caught abort error).\n* @param code When provided, only a {@link TimeoutReason} with this exact `code` matches.\n* @returns The matching {@link TimeoutReason}, else `undefined`.\n*/\nfunction timeoutOf(x, code) {\n\tconst reason = x.reason;\n\tif (!(reason instanceof TimeoutReason)) return void 0;\n\treturn code === void 0 || reason.code === code ? reason : void 0;\n}\n//#endregion\nexport { MAX_TIMER_DELAY_MS, TimeoutReason, clampTimeout, deadline, idleWatchdog, timeoutOf };\n","import { createRequire } from \"node:module\";\nimport { Service } from \"@deepseek-ai/cordis\";\nimport z from \"@deepseek-ai/schemastery\";\nimport { MAX_TIMER_DELAY_MS } from \"@deepseek-ai/dsh-timeout\";\n//#region lib/types/brand.js\n/**\n* dsh-llm's owned branded ids: tool-call correlation and provider request\n* diagnostics.\n*\n* The `Branded<B>` primitive itself lives in `@deepseek-ai/dsh-brand` (a\n* zero-dependency type-only package) so every owner of a cross-boundary id can\n* brand it without depending on dsh-llm; see that package's README for the\n* nominal-typing policy.\n*\n* @module @deepseek-ai/dsh-llm/brand\n*/\n/**\n* Brand a message identifier.\n* @param id - the opaque message identifier.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction MessageId(id) {\n\treturn id;\n}\n/**\n* Brand a string as a {@link CallId}.\n* @param id - the provider-issued (or synthesized) call id.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction CallId(id) {\n\treturn id;\n}\n/**\n* Brand a provider-issued request identifier.\n* @param id - the opaque provider-issued string.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction ProviderRequestId(id) {\n\treturn id;\n}\n/**\n* Brand an adapter-owned reasoning-effort identifier.\n* @param id - the opaque identifier exposed by one model capability.\n* @returns the same string, branded; no validation is performed.\n*/\nfunction ReasoningEffortId(id) {\n\treturn id;\n}\n//#endregion\n//#region lib/types/call-config.js\n/**\n* Conversation call configuration and freeze utilities. Provider routing,\n* model, reasoning effort, and sampling values are request-header state that\n* can affect cache reuse; request waterfalls replace them and the loop logs\n* changed snapshots instead of allowing silent per-call drift.\n* @module dsh-llm/call-config\n*/\n/** Process-local identities of request objects assembled by dsh-agent-loop. */\nconst AGENT_LOOP_REQUESTS = /* @__PURE__ */ new WeakSet();\n/**\n* Field-wise equality over {@link LlmCallConfig} — the comparison a caller\n* runs to decide whether a proposed configuration is a real change (worth a\n* logged header snapshot) or the held one restated.\n* @param a - one configuration.\n* @param b - the other.\n* @returns whether every field (including the `stop` list, element-wise) matches.\n*/\nfunction callConfigEquals(a, b) {\n\tif (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;\n\tif (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;\n\treturn a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);\n}\n/**\n* Mark one exact request object as assembled by dsh-agent-loop.\n* @param request - loop-owned request envelope before LLM dispatch.\n* @returns the same request object marked as created by the process-local agent loop.\n*/\nfunction markAgentLoopRequest(request) {\n\tAGENT_LOOP_REQUESTS.add(request);\n\treturn request;\n}\n/**\n* Test whether the exact request object was assembled by dsh-agent-loop.\n* @param request - request envelope observed at the LLM waterfall.\n* @returns whether {@link markAgentLoopRequest} recorded this object.\n*/\nfunction isAgentLoopRequest(request) {\n\treturn AGENT_LOOP_REQUESTS.has(request);\n}\n/**\n* Deep-freeze a value in place with an iterative traversal, guarding cycles,\n* so later mutation throws without imposing a JavaScript call-stack depth cap.\n* {@link AbortSignal} objects are deliberately skipped because they are the\n* request's live cancellation channel and freezing them breaks abort.\n* @param value - the value to freeze in place.\n* @returns the same value, frozen.\n*/\nfunction deepFreeze(value) {\n\tconst seen = /* @__PURE__ */ new WeakSet();\n\tconst pending = [{\n\t\tkind: \"visit\",\n\t\tnode: value\n\t}];\n\twhile (pending.length > 0) {\n\t\tconst task = pending.pop();\n\t\t/* v8 ignore next -- the loop condition guarantees one pending task. */\n\t\tif (task === void 0) continue;\n\t\tif (task.kind === \"property\") {\n\t\t\tpending.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tnode: task.source[task.key]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = task.node;\n\t\tif (node === null || typeof node !== \"object\") continue;\n\t\tif (node instanceof AbortSignal) continue;\n\t\tif (seen.has(node)) continue;\n\t\tseen.add(node);\n\t\tObject.freeze(node);\n\t\tconst keys = Object.keys(node);\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) continue;\n\t\t\tpending.push({\n\t\t\t\tkind: \"property\",\n\t\t\t\tsource: node,\n\t\t\t\tkey\n\t\t\t});\n\t\t}\n\t}\n\treturn value;\n}\n//#endregion\n//#region lib/types/message.js\n/** Message value types, identity, and immutable construction helpers. */\n/**\n* Bound for a `notice` summary. The account rides a collapsed transcript row\n* and is committed to the durable log, while its inputs — task labels, goal\n* objectives, tool arguments — are caller text with no length of their own.\n*/\nconst CONTEXT_SUMMARY_MAX_CHARS = 120;\n/**\n* Bound one `notice` summary to {@link CONTEXT_SUMMARY_MAX_CHARS}.\n* @param summary - the producer's one-line account, of any length.\n* @returns the account, ellipsized when it exceeds the bound.\n*/\nfunction boundContextSummary(summary) {\n\treturn summary.length <= 120 ? summary : `${summary.slice(0, 119)}…`;\n}\n/**\n* Detach and deep-freeze a message whose identity already exists.\n* @param message - complete message, including its stable identity.\n* @returns an immutable snapshot that preserves the identity.\n*/\nfunction freezeMessage(message) {\n\treturn deepFreeze(structuredClone(message));\n}\n/**\n* Create one identified message and freeze it before publication.\n* @param input - complete role, content, and source for a new message.\n* @returns an immutable message with a fresh stable identity.\n*/\nfunction createMessage(input) {\n\treturn freezeMessage({\n\t\t...input,\n\t\tid: MessageId(crypto.randomUUID())\n\t});\n}\n/**\n* Create one identified user-role message and freeze it before publication.\n* @param input - complete content and source for a new user message.\n* @returns an immutable user message with a fresh stable identity.\n*/\nfunction createUserMessage(input) {\n\treturn createMessage({\n\t\t...input,\n\t\trole: \"user\"\n\t});\n}\n/**\n* Create one identified model-produced assistant message and freeze it before publication.\n* @param input - complete content plus the provider, model, and optional replay state for a new assistant message.\n* @returns an immutable assistant message with fixed role/source tags and a fresh stable identity.\n*/\nfunction createAssistantMessage(input) {\n\treturn createMessage({\n\t\trole: \"assistant\",\n\t\tcontent: input.content,\n\t\tsource: {\n\t\t\tkind: \"model\",\n\t\t\t...input.source\n\t\t}\n\t});\n}\n/**\n* Create and freeze one identified tool-result message.\n* @param input - call identity, raw result blocks, and outcome.\n* @returns an immutable user-role tool-result message.\n*/\nfunction createToolResultMessage(input) {\n\treturn createUserMessage({\n\t\tsource: {\n\t\t\tkind: \"tool\",\n\t\t\tcallId: input.callId\n\t\t},\n\t\tcontent: [{\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: input.callId,\n\t\t\tcontent: input.content,\n\t\t\tisError: input.isError\n\t\t}]\n\t});\n}\n/**\n* Whether a stream chunk carries visible model output (the first-token\n* boundary shared by client step timing and the whole-log sessionStats\n* projection). Empty deltas (heartbeats, empty tool-call frames) do not count\n* as a first token.\n* @param chunk - the stream chunk to test.\n* @returns true when the chunk contains a non-empty text/reasoning/tool delta.\n*/\nfunction isTokenDelta(chunk) {\n\tswitch (chunk.type) {\n\t\tcase \"text-delta\":\n\t\tcase \"reasoning-delta\": return chunk.text !== \"\";\n\t\tcase \"tool-call-delta\": return chunk.argumentsDelta !== \"\" || chunk.name !== void 0;\n\t\tdefault: return false;\n\t}\n}\n//#endregion\n//#region lib/types/error.js\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-llm/error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n/** Canonical provider-neutral code for a model request rejected because its context window was exceeded. */\nconst CONTEXT_WINDOW_EXCEEDED_CODE = \"CONTEXT_WINDOW_EXCEEDED\";\n/** Canonical provider-neutral code for an exhausted account quota or balance. */\nconst QUOTA_EXCEEDED_CODE = \"QUOTA\";\n/**\n* Canonical provider-neutral code for a response that completed normally but\n* carried no content blocks at all. Providers occasionally emit a degenerate\n* completion (a terminal stop with zero output); adapters classify it as this\n* failure instead of yielding an empty assistant message, because an empty\n* message silently ends the turn with nothing for the user or the loop to act\n* on. The attempt produced nothing durable, so retry policy treats it as safe\n* to repeat.\n*/\nconst EMPTY_RESPONSE_CODE = \"EMPTY_RESPONSE\";\n/**\n* Canonical provider-neutral code for a credential that was supplied but\n* cannot be used — malformed rather than absent. Distinct from\n* `MISSING_CREDENTIAL` because the fix differs: correct the stored value\n* rather than supply one. Deliberately outside the default retryable set —\n* a malformed credential fails identically on every attempt.\n*/\nconst INVALID_CREDENTIAL_CODE = \"INVALID_CREDENTIAL\";\n/** Structured codes and plain phrases that explicitly name a context bound being exceeded. */\nconst STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\\s_-](?:length|window)[\\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\\s_-]exceeded)(?:$|[^a-z0-9])`, \"i\");\n/** Request-size wording that ties \"too large\" directly to model context capacity. */\nconst TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\\b(?:request|prompt|input|messages?)\\s+(?:is\\s+|are\\s+)?` + String.raw`too\\s+(?:large|long)\\s+for\\s+(?:(?:this|the)\\s+)?` + String.raw`(?:model(?:'s)?\\s+)?context(?:\\s+window)?\\b`, \"i\");\n/** \"Exceeds\" wording is safe only when its object is explicitly the model context. */\nconst EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\\b(?:input|prompt|request|messages?)\\b.{0,40}` + String.raw`\\b(?:exceed(?:s|ed)?|overflows?|is\\s+larger\\s+than)\\b.{0,40}` + String.raw`\\b(?:the\\s+)?(?:model(?:'s)?\\s+)?context(?:\\s+(?:length|window))?\\b`, \"i\");\n/**\n* Recognize the context-overflow wording used by OpenAI-compatible providers\n* and library adapters. Adapters pass all available provider code, type, and\n* message text so both thrown and in-band delivery styles share one classifier.\n* @param detail - provider error code/type/message text joined into one string.\n* @returns true when the detail identifies a request exceeding the model context window.\n*/\nfunction isContextWindowExceededError(detail) {\n\treturn STRUCTURED_CONTEXT_OVERFLOW.test(detail) || /\\b(?:maximum|max)(?:\\s+(?:allowed|supported))?\\s+context\\s+(?:length|window)\\b/i.test(detail) || TOO_LARGE_FOR_CONTEXT.test(detail) || /\\b(?:input|prompt|request)\\s+(?:is\\s+)?too\\s+(?:long|large)\\s+for\\s+(?:this|the)\\s+model\\b/i.test(detail) || EXCEEDS_MODEL_CONTEXT.test(detail);\n}\n/**\n* Recognize provider wording that identifies an exhausted account quota rather\n* than a transient request-rate limit.\n* @param detail - provider error code/type/message text joined into one string.\n* @returns true only for terminal quota, balance, credit, budget, or usage-limit wording.\n*/\nfunction isQuotaExceededError(detail) {\n\treturn /\\binsufficient[\\s_-]+(?:quota|balance|credits?)\\b/i.test(detail) || /\\b(?:quota|usage[\\s_-]+limit)[\\s_-]+(?:exceeded|exhausted|reached)\\b/i.test(detail) || /\\bexceed(?:ed|s)?[\\s_-]+(?:(?:your|the)[\\s_-]+)?(?:current[\\s_-]+)?quota\\b/i.test(detail) || /\\b(?:balance|credits?)[\\s_-]+(?:exhausted|depleted)\\b/i.test(detail) || /\\bout[\\s_-]+of[\\s_-]+(?:credits?|budget)\\b/i.test(detail);\n}\n/**\n* Render a thrown value with its full `cause` chain and AggregateError\n* members, so transport wrappers like undici's `TypeError: fetch failed`\n* surface the underlying failure instead of masking it. Plain structured\n* failures render their own data-backed `message`. Diagnostic-surface\n* rendering only (messages, notices, logs) — never parse the result; route on\n* {@link HarnessError.code}.\n* @param value - the caught value (`unknown` in catch clauses).\n* @returns the outermost message first, each cause appended with `: ` (skipped\n* when it repeats the wrapper message verbatim), and AggregateError members\n* bracketed and `; `-joined.\n*/\nfunction errorChain(value) {\n\tconst path = /* @__PURE__ */ new Set();\n\tconst render = (current) => {\n\t\tif (path.has(current)) return \"<circular cause>\";\n\t\tpath.add(current);\n\t\ttry {\n\t\t\tif (!(current instanceof Error)) {\n\t\t\t\tif (typeof current === \"object\" && current !== null) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(current, \"message\");\n\t\t\t\t\tif (descriptor !== void 0 && \"value\" in descriptor && typeof descriptor.value === \"string\") return descriptor.value;\n\t\t\t\t}\n\t\t\t\treturn String(current);\n\t\t\t}\n\t\t\tconst message = current.message === \"\" ? current.name : current.message;\n\t\t\tconst members = current instanceof AggregateError && current.errors.length > 0 ? ` [${current.errors.map(render).join(\"; \")}]` : \"\";\n\t\t\tconst causeText = current.cause === void 0 || current.cause === null ? \"\" : render(current.cause);\n\t\t\treturn `${message}${members}${causeText === \"\" || causeText === message ? \"\" : `: ${causeText}`}`;\n\t\t} catch {\n\t\t\treturn \"<unrenderable value>\";\n\t\t} finally {\n\t\t\tpath.delete(current);\n\t\t}\n\t};\n\treturn render(value);\n}\n/**\n* Narrow an arbitrary thrown value to a HarnessError (for `instanceof` at runtime boundaries).\n* @param value - the caught value (`unknown` in catch clauses).\n* @returns true only for real instances; duck-typed or cross-realm errors do not narrow.\n*/\nfunction isHarnessError(value) {\n\treturn value instanceof HarnessError;\n}\n//#endregion\n//#region lib/types/retry-policy.js\n/**\n* Provider-owned request-retry policy configuration and resolution.\n*\n* Adapters expose one resolved policy per registered provider route; the\n* optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.\n*\n* @module @deepseek-ai/dsh-llm/retry-policy\n*/\nconst DEFAULT_MAX_RETRIES = 5;\nconst DEFAULT_INITIAL_DELAY_MS = 500;\nconst DEFAULT_MAX_DELAY_MS = 1e4;\nconst DEFAULT_JITTER_RATIO = .1;\nconst DEFAULT_RETRYABLE_CODES = Object.freeze([\n\tEMPTY_RESPONSE_CODE,\n\t\"RATE_LIMIT\",\n\t\"SERVER\",\n\t\"TIMEOUT\",\n\t\"TRANSPORT\"\n]);\nconst backoffSchema = z.object({\n\tinitialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),\n\tmaxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),\n\tjitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)\n});\nconst normalPolicySchema = z.object({\n\tmode: z.const(\"normal\").required(),\n\tmaxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),\n\tretryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),\n\tbackoff: backoffSchema\n});\nconst alwaysPolicySchema = z.object({\n\tmode: z.const(\"always\").required(),\n\tbackoff: backoffSchema\n});\n/** Cordis schema embedded by each concrete provider configuration. */\nconst RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);\nconst NORMAL_POLICY_KEYS = new Set([\n\t\"mode\",\n\t\"maxRetries\",\n\t\"retryableCodes\",\n\t\"backoff\"\n]);\nconst ALWAYS_POLICY_KEYS = new Set([\n\t\"mode\",\n\t\"maxRetries\",\n\t\"retryableCodes\",\n\t\"backoff\"\n]);\nconst BACKOFF_KEYS = new Set([\n\t\"initialDelayMs\",\n\t\"maxDelayMs\",\n\t\"jitterRatio\"\n]);\nfunction validateKeys(value, allowed, path) {\n\tfor (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key \"${key}\"`);\n}\nfunction resolveBackoff(config, path) {\n\tif (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);\n\tconst initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n\tconst maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n\tconst jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;\n\tif (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n\tif (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);\n\tif (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);\n\tif (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);\n\treturn Object.freeze({\n\t\tinitialDelayMs,\n\t\tmaxDelayMs,\n\t\tjitterRatio\n\t});\n}\n/**\n* Validate, default, and detach one provider-owned retry policy.\n* @param config - optional provider configuration; omission selects normal defaults.\n* @param path - diagnostic path naming the provider config that owns the value.\n* @returns an immutable policy safe to capture in provider registration state.\n*/\nfunction resolveRetryPolicy(config, path) {\n\tif (config === void 0) return Object.freeze({\n\t\tmode: \"normal\",\n\t\tmaxRetries: DEFAULT_MAX_RETRIES,\n\t\tretryableCodes: DEFAULT_RETRYABLE_CODES,\n\t\t...resolveBackoff(void 0, `${path}.backoff`)\n\t});\n\tswitch (config.mode) {\n\t\tcase \"normal\": {\n\t\t\tvalidateKeys(config, NORMAL_POLICY_KEYS, path);\n\t\t\tconst maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\t\tconst retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];\n\t\t\tif (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);\n\t\t\tif (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);\n\t\t\tif (retryableCodes.some((code) => typeof code !== \"string\" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);\n\t\t\tif (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);\n\t\t\treturn Object.freeze({\n\t\t\t\tmode: \"normal\",\n\t\t\t\tmaxRetries,\n\t\t\t\tretryableCodes: Object.freeze([...retryableCodes]),\n\t\t\t\t...resolveBackoff(config.backoff, `${path}.backoff`)\n\t\t\t});\n\t\t}\n\t\tcase \"always\":\n\t\t\tvalidateKeys(config, ALWAYS_POLICY_KEYS, path);\n\t\t\treturn Object.freeze({\n\t\t\t\tmode: \"always\",\n\t\t\t\t...resolveBackoff(config.backoff, `${path}.backoff`)\n\t\t\t});\n\t\tdefault: throw new Error(`${path}.mode must be \"normal\" or \"always\"`);\n\t}\n}\n//#endregion\n//#region lib/types/adapter-failure.js\n/**\n* Normalization for values thrown by a final LLM adapter boundary.\n*\n* @module @deepseek-ai/dsh-llm/adapter-failure\n*/\n/**\n* Detach serializable provider facts from a value thrown by an adapter.\n* @param value - arbitrary value thrown during adapter dispatch or iteration.\n* @returns immutable provider-neutral facts suitable for a terminal finish chunk.\n* @internal\n*/\nfunction normalizeLlmFailure(value) {\n\tconst error = value instanceof Error ? value : new HarnessError(thrownMessage(value), \"UNKNOWN\", { cause: value });\n\tconst carried = ownFailureSnapshot(error);\n\tif (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;\n\treturn Object.freeze({\n\t\tmessage: errorMessage(error),\n\t\tcode: harnessErrorCode(error)\n\t});\n}\n/** Render a non-Error throw without letting hostile coercion escape normalization. */\nfunction thrownMessage(value) {\n\ttry {\n\t\tconst message = String(value);\n\t\treturn message.length > 0 ? message : \"LLM adapter failed\";\n\t} catch (_hostileThrownValue) {\n\t\treturn \"LLM adapter failed\";\n\t}\n}\n/** Read a foreign error's own data-backed `code` without invoking accessors. */\nfunction ownErrorCode(error) {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n\t\treturn descriptor !== void 0 && \"value\" in descriptor ? descriptor.value : void 0;\n\t} catch (_sdkPropertyTrap) {\n\t\treturn;\n\t}\n}\n/** Snapshot an own data property without invoking an SDK-defined accessor. */\nfunction ownFailureSnapshot(error) {\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(error, \"failure\");\n\t\treturn descriptor !== void 0 && \"value\" in descriptor ? failureSnapshot(descriptor.value) : void 0;\n\t} catch (_sdkPropertyTrap) {\n\t\treturn;\n\t}\n}\n/** Validate and detach an arbitrary serializable failure payload. */\nfunction failureSnapshot(value) {\n\tif (typeof value !== \"object\" || value === null) return void 0;\n\ttry {\n\t\tconst candidate = value;\n\t\tconst message = candidate.message;\n\t\tconst code = candidate.code;\n\t\tconst status = candidate.status;\n\t\tconst providerRetryAfterMs = candidate.providerRetryAfterMs;\n\t\tconst requestId = candidate.requestId;\n\t\tif (typeof message !== \"string\" || message.length === 0 || typeof code !== \"string\" || code.length === 0 || status !== void 0 && (!Number.isInteger(status) || status < 100 || status > 599) || providerRetryAfterMs !== void 0 && (!Number.isFinite(providerRetryAfterMs) || providerRetryAfterMs <= 0) || requestId !== void 0 && (typeof requestId !== \"string\" || requestId.length === 0)) return void 0;\n\t\treturn Object.freeze({\n\t\t\tmessage,\n\t\t\tcode,\n\t\t\t...status === void 0 ? {} : { status },\n\t\t\t...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },\n\t\t\t...requestId === void 0 ? {} : { requestId }\n\t\t});\n\t} catch (_sdkFailureGetter) {\n\t\treturn;\n\t}\n}\n/** Read an SDK error message without letting an accessor replace the primary failure. */\nfunction errorMessage(error) {\n\ttry {\n\t\tconst message = error.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t} catch (_sdkMessageGetter) {}\n\treturn \"LLM adapter failed\";\n}\n/** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */\nfunction harnessErrorCode(error) {\n\treturn error instanceof HarnessError ? error.code : \"UNKNOWN\";\n}\n//#endregion\n//#region lib/types/api-key.js\n/**\n* The one definition of a well-formed provider API key, shared by every\n* adapter that puts one in an HTTP header.\n* @module @deepseek-ai/dsh-llm/api-key\n*/\n/**\n* Characters an HTTP header value carries verbatim and every known provider\n* key uses: printable ASCII, space excluded. A key outside this set cannot\n* reach any provider — `fetch` refuses to build the header — so this is a\n* transport invariant rather than one provider's policy. Latin-1 is excluded\n* deliberately: a header could carry it, but no provider issues it, and\n* admitting it trades a local explained refusal for an opaque 401.\n*/\nconst LEGAL_API_KEY = /^[\\x21-\\x7E]+$/;\n/**\n* Judge one *supplied* API key, trimming surrounding whitespace first.\n*\n* Trimming is silent because a padded key has one unambiguous reading; every\n* other defect is reported. Absence is a configuration state this function\n* never sees — a profile naming no credential authenticates through the\n* provider's own ambient discovery or OAuth — so callers decide whether a\n* value was supplied before asking.\n* @param raw - the key exactly as configured, stored, or typed.\n* @returns the trimmed key, or why it cannot be used.\n*/\nfunction normalizeApiKey(raw) {\n\tconst value = raw.trim();\n\tif (value.length === 0) return {\n\t\tok: false,\n\t\treason: \"empty\"\n\t};\n\tif (!LEGAL_API_KEY.test(value)) return {\n\t\tok: false,\n\t\treason: \"illegalCharacters\"\n\t};\n\treturn {\n\t\tok: true,\n\t\tvalue\n\t};\n}\n//#endregion\n//#region lib/types/content.js\n/** Content-block structure helpers. @module @deepseek-ai/dsh-llm/content */\n/** Model-facing stand-in for an image removed to fit a provider request bound. */\nconst OFFLOADED_IMAGE_TEXT = \"[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]\";\n/**\n* Stable text shown to a model that cannot accept one durable image reference.\n* @param ref - durable master reference omitted from the request.\n* @returns deterministic text-only placeholder.\n*/\nfunction textOnlyImageText(ref) {\n\treturn `[image omitted because this model accepts text only; attachment sha256:${String(ref.attachmentId).slice(7, 15)}]`;\n}\n/**\n* Stable model-facing handle for one exact request image.\n* @param version - exact request image shown beside the text.\n* @returns attachment handle and request-image dimensions.\n*/\nfunction requestImageHandleText(version) {\n\treturn `Image ${version.attachment.attachmentId}; request image ${version.width}x${version.height}px.`;\n}\n/**\n* True when typed model content contains an image block, walking nested\n* tool-result content. This is the one recursive image walk shared by every\n* image policy (capability gating, text-only serialization, compaction\n* survey), so a consumer cannot silently diverge on nesting depth.\n* @param content - typed model content blocks.\n* @returns whether any nested block is an image.\n*/\nfunction contentHasImage(content) {\n\treturn content.some((block) => block.type === \"image\" || block.type === \"tool-result\" && contentHasImage(block.content));\n}\n/** Base64 length of raw image bytes, including padding. */\nfunction base64Length(bytes) {\n\treturn Math.ceil(bytes / 3) * 4;\n}\n/** Collect represented image lengths in request and nested-block order. */\nfunction collectImageLengths(blocks, lengths, policy) {\n\tfor (const block of blocks) if (block.type === \"image\") {\n\t\tconst bytes = policy.byteLength === void 0 ? block.attachment.bytes : policy.byteLength(block.attachment);\n\t\tlengths.push(policy.representation === \"base64\" ? base64Length(bytes) : bytes);\n\t} else if (block.type === \"tool-result\") collectImageLengths(block.content, lengths, policy);\n}\n/** Replace the first `remaining.count` image occurrences without mutating durable messages. */\nfunction replaceOldestImages(blocks, remaining) {\n\tlet next;\n\tfor (const [index, block] of blocks.entries()) {\n\t\tif (block.type === \"image\" && remaining.count > 0) {\n\t\t\tremaining.count -= 1;\n\t\t\tnext ??= blocks.slice(0, index);\n\t\t\tnext.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: OFFLOADED_IMAGE_TEXT\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type === \"tool-result\") {\n\t\t\tconst content = replaceOldestImages(block.content, remaining);\n\t\t\tif (content !== block.content) {\n\t\t\t\tnext ??= blocks.slice(0, index);\n\t\t\t\tnext.push({\n\t\t\t\t\t...block,\n\t\t\t\t\tcontent\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tnext?.push(block);\n\t}\n\treturn next ?? blocks;\n}\n/** Replace every image occurrence, including nested tool results, for a text-only model. */\nfunction replaceImagesForTextModel(blocks) {\n\tlet next;\n\tfor (const [index, block] of blocks.entries()) {\n\t\tif (block.type === \"image\") {\n\t\t\tnext ??= blocks.slice(0, index);\n\t\t\tnext.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: textOnlyImageText(block.attachment)\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type === \"tool-result\") {\n\t\t\tconst content = replaceImagesForTextModel(block.content);\n\t\t\tif (content !== block.content) {\n\t\t\t\tnext ??= blocks.slice(0, index);\n\t\t\t\tnext.push({\n\t\t\t\t\t...block,\n\t\t\t\t\tcontent\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tnext?.push(block);\n\t}\n\treturn next ?? blocks;\n}\n/**\n* Project durable image history into deterministic text for an exact text-only model.\n* @param messages - complete request history.\n* @returns the original list without images, otherwise shallow message copies with stable placeholders.\n*/\nfunction projectImagesForTextModel(messages) {\n\tif (!messages.some((message) => contentHasImage(message.content))) return messages;\n\treturn messages.map((message) => {\n\t\tconst content = replaceImagesForTextModel(message.content);\n\t\treturn content === message.content ? message : {\n\t\t\t...message,\n\t\t\tcontent\n\t\t};\n\t});\n}\n/**\n* Return transient request messages whose oldest images are replaced until\n* their accumulated base64 payload fits the configured bound. The selection\n* is deterministic from durable message order and attachment metadata; a\n* provider can serialize the returned messages without reading omitted bytes.\n* @param messages - complete request history, oldest first.\n* @param maxRequestImageBytes - positive bound on total base64 image payload; undefined preserves every image.\n* @returns the original messages when they already fit, otherwise shallow message copies with replaced content trees.\n*/\nfunction offloadRequestImages(messages, maxRequestImageBytes) {\n\treturn offloadRequestImagesWithPolicy(messages, {\n\t\trepresentation: \"base64\",\n\t\t...maxRequestImageBytes === void 0 ? {} : { maxBytes: maxRequestImageBytes },\n\t\tbyteQuantum: 1\n\t});\n}\n/**\n* Return a deterministic transient projection whose oldest images are replaced\n* in whole count and byte quanta after a route budget is exceeded. The target\n* depends only on complete durable history: at 129 one-megabyte images under\n* a 128 MiB bound with a 64 MiB quantum, the oldest 65 images are removed so\n* 64 MiB remain; that removed prefix stays fixed until total history exceeds\n* 192 MiB.\n* @param messages - complete request history, oldest first.\n* @param policy - route representation, budgets, and removal quanta.\n* @returns original messages below both bounds, otherwise shallow copies with deterministic placeholders.\n*/\nfunction offloadRequestImagesWithPolicy(messages, policy) {\n\tconst lengths = [];\n\tfor (const message of messages) collectImageLengths(message.content, lengths, policy);\n\tconst total = lengths.reduce((sum, bytes) => sum + bytes, 0);\n\tconst excessCount = policy.maxImages === void 0 ? 0 : Math.max(0, lengths.length - policy.maxImages);\n\tconst excessBytes = policy.maxBytes === void 0 ? 0 : Math.max(0, total - policy.maxBytes);\n\tif (excessCount === 0 && excessBytes === 0) return messages;\n\tconst countQuantum = policy.countQuantum ?? 1;\n\tconst byteQuantum = policy.byteQuantum ?? 1;\n\tconst removeCount = excessCount === 0 ? 0 : Math.ceil(excessCount / countQuantum) * countQuantum;\n\tconst removeBytes = excessBytes === 0 ? 0 : Math.ceil(excessBytes / byteQuantum) * byteQuantum;\n\tlet count = 0;\n\tlet removedBytes = 0;\n\tfor (const imageBytes of lengths) {\n\t\tif (count >= removeCount && (removeBytes === 0 || (byteQuantum === 1 ? removedBytes >= removeBytes : removedBytes > removeBytes))) break;\n\t\tremovedBytes += imageBytes;\n\t\tcount += 1;\n\t}\n\tconst remaining = { count };\n\treturn messages.map((message) => {\n\t\tconst content = replaceOldestImages(message.content, remaining);\n\t\treturn content === message.content ? message : {\n\t\t\t...message,\n\t\t\tcontent\n\t\t};\n\t});\n}\n//#endregion\n//#region lib/types/attribution.js\n/**\n* Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping\n* adapters from drifting. See\n* `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.\n*\n* App-attribution vocabulary for provider requests.\n* @module @deepseek-ai/dsh-llm/attribution\n*/\nconst { version } = createRequire(import.meta.url)(\"../package.json\");\n/**\n* The harness's own identity: the default every adapter sends. Deployments\n* that need a white-label identity pass their own {@link AppIdentity} to\n* {@link attributionHeaders} — omission falls back to this default; nothing\n* can suppress attribution entirely.\n*/\nconst APP_IDENTITY = {\n\tproduct: \"deepseek-harness\",\n\tversion,\n\turl: \"https://github.com/deepseek-ai/deepseek-harness\"\n};\n/**\n* The standard `User-Agent` value: `product/version (+url)`. The\n* parenthesized `+url` comment is the conventional self-identification form\n* (RFC 9110 §10.1.5 product + comment syntax).\n* @param identity - the identity to render; defaults to {@link APP_IDENTITY}.\n* @returns the ready-to-send header value.\n*/\nfunction userAgent(identity = APP_IDENTITY) {\n\treturn `${identity.product}/${identity.version} (+${identity.url})`;\n}\n/**\n* Build the attribution headers an adapter must send on every provider\n* request. Header names are lowercase (HTTP field names are case-insensitive\n* on the wire).\n* @param identity - the identity to send; defaults to {@link APP_IDENTITY} — omission cannot suppress attribution.\n* @returns headers to merge into the provider request (currently just `user-agent`).\n*/\nfunction attributionHeaders(identity = APP_IDENTITY) {\n\treturn { \"user-agent\": userAgent(identity) };\n}\n//#endregion\n//#region lib/types/never.js\n/**\n* Exhaustiveness helper for closed core unions. Use {@link assertNever} at the default branch so a\n* new variant fails compilation at every required handler. Do not use it for declaration-merged\n* unions such as session events or content blocks: handle known variants and explicitly fall\n* through because plugins may add valid unknown cases.\n* @module @deepseek-ai/dsh-llm/never\n*/\n/**\n* Mark an unreachable closed-union branch. A newly unhandled typed variant fails at the call site;\n* a value that escaped its type throws with diagnostics at runtime.\n* @param value - the impossible value; typed `never` so an unhandled variant fails compilation at the call site.\n* @param context - optional label (e.g. the switch site) prefixed into the throw message.\n* @returns never — it always throws, with the offending value JSON-rendered in the message.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n//#endregion\n//#region lib/types/assembler.js\n/**\n* Incremental chunk-to-message assembler. This is the single canonical assembly\n* algorithm used by the agent loop to build an assistant message from a chunk\n* stream while logging the raw chunks for replay fidelity.\n*\n* @module @deepseek-ai/dsh-llm/assembler\n*/\n/**\n* Incrementally assembles raw {@link StreamChunk}s into complete\n* {@link ContentBlock}s and a final assistant {@link Message}.\n*\n* The agent loop feeds it while logging raw chunks for replay fidelity, then\n* reads `blocks()` / `message()` / `usage` / `finish` once the stream ends,\n* or `interruptedBlocks()` when cancellation cut the stream short.\n*\n* Tolerant of delta-only protocols (no block-start/end); deltas arriving for\n* an index already closed by `block-end` are ignored (malformed stream) so a\n* misbehaving adapter cannot grow memory or corrupt a completed block.\n*/\nvar BlockAssembler = class {\n\tpartials = /* @__PURE__ */ new Map();\n\torder = [];\n\t_usage;\n\t_finish;\n\t_replayState;\n\t/**\n\t* Feed one chunk into the assembly state.\n\t* @param chunk - the next raw chunk, in stream order.\n\t*/\n\tpush(chunk) {\n\t\tswitch (chunk.type) {\n\t\t\tcase \"block-start\":\n\t\t\t\tif (!this.partials.has(chunk.index)) {\n\t\t\t\t\tthis.order.push(chunk.index);\n\t\t\t\t\tthis.partials.set(chunk.index, {\n\t\t\t\t\t\tblockType: chunk.blockType,\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\ttoolCallArguments: \"\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase \"text-delta\":\n\t\t\tcase \"reasoning-delta\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, chunk.type === \"text-delta\" ? \"text\" : \"reasoning\");\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.text += chunk.text;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-call-delta\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, \"tool-call\");\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.toolCallId = chunk.id;\n\t\t\t\tif (chunk.name) partial.toolCallName = chunk.name;\n\t\t\t\tpartial.toolCallArguments += chunk.argumentsDelta;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"block-end\": {\n\t\t\t\tconst partial = this.ensure(chunk.index, chunk.block.type);\n\t\t\t\tif (partial.block) return;\n\t\t\t\tpartial.block = chunk.block;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"usage\":\n\t\t\t\tthis._usage = chunk.usage;\n\t\t\t\treturn;\n\t\t\tcase \"finish\":\n\t\t\t\tthis._finish = chunk.reason;\n\t\t\t\tthis._replayState = chunk.replayState;\n\t\t\t\treturn;\n\t\t\tdefault: return assertNever(chunk, \"BlockAssembler.push\");\n\t\t}\n\t}\n\tensure(index, blockType) {\n\t\tlet partial = this.partials.get(index);\n\t\tif (!partial) {\n\t\t\tpartial = {\n\t\t\t\tblockType,\n\t\t\t\ttext: \"\",\n\t\t\t\ttoolCallArguments: \"\"\n\t\t\t};\n\t\t\tthis.partials.set(index, partial);\n\t\t\tthis.order.push(index);\n\t\t}\n\t\treturn partial;\n\t}\n\tassemble(partial, index) {\n\t\tif (partial.block) return partial.block;\n\t\tswitch (partial.blockType) {\n\t\t\tcase \"text\": return {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: partial.text\n\t\t\t};\n\t\t\tcase \"reasoning\": return {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\ttext: partial.text\n\t\t\t};\n\t\t\tcase \"tool-call\": return {\n\t\t\t\ttype: \"tool-call\",\n\t\t\t\tid: partial.toolCallId ?? CallId(`call-${index}`),\n\t\t\t\tname: partial.toolCallName ?? \"\",\n\t\t\t\targuments: partial.toolCallArguments\n\t\t\t};\n\t\t\tdefault: throw new Error(`cannot assemble incomplete block of type \"${partial.blockType}\"`);\n\t\t}\n\t}\n\t/** Invariant accessor: every index in `order` has a partial. */\n\tmustGet(index) {\n\t\tconst partial = this.partials.get(index);\n\t\tif (!partial) throw new Error(`BlockAssembler invariant violated: no partial for index ${index}`);\n\t\treturn partial;\n\t}\n\t/**\n\t* The one shared keep/drop decision over all seen blocks: max-token\n\t* truncation drops tool calls that cannot be executed safely. Emitted blocks\n\t* and replay metadata both derive from this result, so they cannot disagree.\n\t*/\n\tassembled() {\n\t\tconst all = this.order.map((index) => this.assemble(this.mustGet(index), index));\n\t\tconst kept = this.finish.kind === \"max-tokens\" ? all.map((block) => block.type !== \"tool-call\") : void 0;\n\t\tconst blocks = kept === void 0 ? all : all.filter((_, position) => kept[position]);\n\t\tconst envelope = this._replayState;\n\t\tif (envelope?.blocks === void 0) return {\n\t\t\tblocks,\n\t\t\treplay: envelope\n\t\t};\n\t\tif (envelope.blocks.length !== all.length) return {\n\t\t\tblocks,\n\t\t\treplay: void 0\n\t\t};\n\t\treturn {\n\t\t\tblocks,\n\t\t\treplay: kept === void 0 || blocks.length === all.length ? envelope : {\n\t\t\t\tresponse: envelope.response,\n\t\t\t\tblocks: envelope.blocks.filter((_, position) => kept[position])\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Assemble all blocks seen so far, in stream order.\n\t* @returns one block per seen index, except that max-token truncation drops\n\t* tool calls that cannot be executed safely; an open block assembles from\n\t* its accumulated deltas (an unknown block type never closed by `block-end` throws).\n\t*/\n\tblocks() {\n\t\treturn this.assembled().blocks;\n\t}\n\t/**\n\t* Assemble the prefix an interrupted stream can safely finalize: closed and\n\t* open text/reasoning blocks with non-whitespace content, in stream order.\n\t* Tool calls are omitted because interruption precedes dispatch; retaining\n\t* one would require a fabricated result. Open unknown blocks are also omitted.\n\t* @returns the kept blocks; empty when nothing streamed before the interruption.\n\t*/\n\tinterruptedBlocks() {\n\t\treturn this.order.map((index) => {\n\t\t\tconst partial = this.mustGet(index);\n\t\t\tconst type = partial.block?.type ?? partial.blockType;\n\t\t\tif (type !== \"text\" && type !== \"reasoning\") return void 0;\n\t\t\treturn this.assemble(partial, index);\n\t\t}).filter((block) => (block?.type === \"text\" || block?.type === \"reasoning\") && block.text.trim() !== \"\");\n\t}\n\t/** Usage from the `usage` chunk; undefined until one arrives. */\n\tget usage() {\n\t\treturn this._usage;\n\t}\n\t/** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */\n\tget finish() {\n\t\treturn this._finish ?? { kind: \"stop\" };\n\t}\n\t/**\n\t* Replay metadata from the terminal finish chunk, if any, with per-block\n\t* entries pruned in step with {@link blocks}. Undefined when the envelope's\n\t* entries do not align with the emitted blocks.\n\t*/\n\tget replayState() {\n\t\treturn this.assembled().replay;\n\t}\n\t/**\n\t* The assembled assistant message.\n\t* @param source - producer attribution for the assembled message.\n\t* @returns a frozen assistant-role message over `blocks()` (same open-block assembly rules).\n\t*/\n\tmessage(source = {\n\t\tkind: \"plugin\",\n\t\tplugin: \"dsh-llm/assembler\"\n\t}) {\n\t\treturn createMessage({\n\t\t\trole: \"assistant\",\n\t\t\tcontent: this.blocks(),\n\t\t\tsource\n\t\t});\n\t}\n};\n//#endregion\n//#region lib/types/index.js\n/**\n* LLM service: adapter registry with a waterfall-interceptable streaming call\n* API. Exports the `LlmRuntime` default, the abstract `LlmAdapter` for\n* provider backends, and `BlockAssembler` for chunk assembly.\n*\n* @module @deepseek-ai/dsh-llm\n*/\n/**\n* Typed error for LLM-related failures. Extends {@link HarnessError}, so the\n* `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.\n*/\nvar LlmError = class extends HarnessError {\n\t/** Serializable facts retained beside this live Error. */\n\tfailure;\n\t/**\n\t* @param message - non-empty human-readable failure summary.\n\t* @param code - non-empty stable provider-neutral machine code.\n\t* @param options - optional cause and validated serializable provider facts.\n\t*/\n\tconstructor(message, code, options) {\n\t\tif (typeof message !== \"string\" || message.length === 0) throw new Error(\"LlmError message must be a non-empty string\");\n\t\tif (typeof code !== \"string\" || code.length === 0) throw new Error(\"LlmError code must be a non-empty string\");\n\t\tif (options?.status !== void 0 && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) throw new Error(\"LlmError status must be an integer from 100 through 599\");\n\t\tif (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error(\"LlmError providerRetryAfterMs must be a positive finite number\");\n\t\tif (options?.requestId !== void 0 && (typeof options.requestId !== \"string\" || options.requestId.length === 0)) throw new Error(\"LlmError requestId must be a non-empty string\");\n\t\tsuper(message, code, options);\n\t\tthis.name = \"LlmError\";\n\t\tthis.failure = Object.freeze({\n\t\t\tmessage,\n\t\t\tcode,\n\t\t\t...options?.status === void 0 ? {} : { status: options.status },\n\t\t\t...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },\n\t\t\t...options?.requestId === void 0 ? {} : { requestId: options.requestId }\n\t\t});\n\t}\n};\n/**\n* Accept one supplied credential, or refuse it as unusable.\n*\n* A stored key arrives from the credentials seam, a `.env` line, or a shell\n* export, all of which pick up surrounding whitespace, so trimming is silent.\n* Anything else fails here rather than inside `fetch`, whose ByteString\n* refusal names a UTF-16 code point instead of the setting to change. The key\n* never enters the message: `ref` names where to fix it, and echoing any part\n* of a secret into a log or a UI is the failure this diagnosis avoids.\n*\n* Lives beside {@link LlmError} rather than in `./api-key.ts` so the predicate\n* module stays dependency-free; both adapters share this one diagnosis instead\n* of keeping near-identical local copies.\n* @param raw - the credential exactly as supplied.\n* @param pkg - the refusing package name, prefixed to the diagnostic.\n* @param ref - the credential reference the value resolved through.\n* @returns the trimmed, usable key.\n*/\nfunction assertUsableApiKey(raw, pkg, ref) {\n\tconst checked = normalizeApiKey(raw);\n\tif (checked.ok) return checked.value;\n\tthrow new LlmError(checked.reason === \"empty\" ? `${pkg}: the API key resolved from ${ref} is blank; set ${ref} to the raw key (the web Models page writes it) or export it in the launching environment` : `${pkg}: the API key resolved from ${ref} contains characters no HTTP header can carry; set ${ref} to the raw key alone (the web Models page writes it)`, INVALID_CREDENTIAL_CODE);\n}\n/**\n* Provider-wire adapter for the harness message and stream vocabulary. Register implementations\n* with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include\n* `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch\n* DeepSeek and library-backed pi-ai adapters meet this contract through different internals.\n*/\nvar LlmAdapter = class {\n\t/**\n\t* Describe one provider route owned by this adapter.\n\t* @param provider - a route passed to `registerAdapter()` for this instance.\n\t* @returns detached display metadata whose id must equal `provider`.\n\t*/\n\tproviderInfo(provider) {\n\t\treturn {\n\t\t\tid: provider,\n\t\t\tname: provider\n\t\t};\n\t}\n\t/**\n\t* Return the provider-owned retry policy captured with this route.\n\t* @param _provider - a route passed to `registerAdapter()` for this instance.\n\t* @returns a resolved policy, or `undefined` to use the normal defaults.\n\t*/\n\tproviderRetryPolicy(_provider) {}\n\t/**\n\t* List models this adapter can currently advertise for one owned provider.\n\t* The result is advisory: an adapter may accept unlisted model ids, and\n\t* consumers must not turn absence into request rejection.\n\t* @param _provider - one provider route owned by this adapter.\n\t* @returns discoverable models in adapter-preferred order.\n\t*/\n\tlistModels(_provider) {\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Resolve all metadata available for one exact model. This query is\n\t* independent of the advisory catalog and does not validate request routing.\n\t* @param provider - one provider route owned by this adapter.\n\t* @param model - exact model id passed to {@link GenerateOptions.model}.\n\t* @param _signal - cancellation for this exact-model lookup; asynchronous\n\t* implementations must settle promptly after it aborts.\n\t* @returns provider/model identity plus any context, call-default, and reasoning metadata.\n\t*/\n\tresolveModel(provider, model, _signal) {\n\t\treturn Promise.resolve({\n\t\t\tprovider,\n\t\t\tid: model,\n\t\t\tname: model\n\t\t});\n\t}\n\t/**\n\t* Bind exact model metadata and the eventual request dispatch to one adapter generation.\n\t* Dynamic adapters override this so settings changes between preparation and\n\t* dispatch cannot combine one generation's capabilities with another's endpoint.\n\t* @param provider - registered provider route.\n\t* @param model - exact model id.\n\t* @param signal - cancellation for model resolution.\n\t* @returns model metadata and a one-generation stream entry point.\n\t*/\n\tasync prepareCall(provider, model, signal) {\n\t\treturn {\n\t\t\tmodel: await this.resolveModel(provider, model, signal),\n\t\t\tstream: (options) => this.stream(options)\n\t\t};\n\t}\n};\n/**\n* The abstract `llm` service: an adapter registry plus a streaming model-call\n* API, interceptable via the `llm/stream` waterfall.\n*/\nvar LlmRuntime = class extends Service {\n\tadapters = /* @__PURE__ */ new Map();\n\tdirectory = /* @__PURE__ */ new Map();\n\tdiscoveries = /* @__PURE__ */ new Map();\n\tconstructor(ctx) {\n\t\tsuper(ctx, \"llm\");\n\t}\n\t/** Notify topology observers without letting one broken listener veto the commit. */\n\temitAdaptersUpdated() {\n\t\tlet invariantFailure;\n\t\tfor (const listener of this.ctx.events.dispatch(\"emit\", [\"llm/adapters-updated\"])) try {\n\t\t\tconst returned = listener();\n\t\t\tif (returned != null && typeof returned.then === \"function\") Promise.resolve(returned).then(void 0, (error) => {\n\t\t\t\tthis.warnAdaptersListenerFailure(error);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error?.code === \"INVARIANT\") {\n\t\t\t\tinvariantFailure ??= error;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.warnAdaptersListenerFailure(error);\n\t\t}\n\t\tif (invariantFailure !== void 0) throw invariantFailure;\n\t}\n\t/** Contained-listener diagnostic shared by the sync and async failure paths. */\n\twarnAdaptersListenerFailure(error) {\n\t\tthis.ctx.logger.warn(\"llm: an llm/adapters-updated listener failed\");\n\t\tthis.ctx.logger.warn(error);\n\t}\n\t/**\n\t* Register an adapter for the given provider routes. Throws `LlmError` with code\n\t* `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).\n\t* Disposed with the fiber.\n\t* @param providers - every provider route this adapter should serve.\n\t* @param adapter - the adapter that streams calls for those providers.\n\t* @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.\n\t*/\n\tregisterAdapter(providers, adapter) {\n\t\tconst owned = /* @__PURE__ */ new Set();\n\t\tlet released = false;\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (providers.length === 0) throw new LlmError(\"an adapter must register at least one provider\", \"INVALID_ADAPTER\");\n\t\t\tthis.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));\n\t\t\tyield () => {\n\t\t\t\treleased = true;\n\t\t\t\tfor (const provider of owned) this.adapters.delete(provider);\n\t\t\t\towned.clear();\n\t\t\t\tthis.emitAdaptersUpdated();\n\t\t\t};\n\t\t}.bind(this), \"llm.registerAdapter()\");\n\t\tconst handle = (() => void dispose());\n\t\thandle.replace = (next) => {\n\t\t\tif (released) throw new LlmError(\"a disposed adapter registration cannot replace its routes\", \"REGISTRATION_DISPOSED\");\n\t\t\tthis.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));\n\t\t};\n\t\treturn handle;\n\t}\n\t/**\n\t* Validate one candidate route set for `adapter`, treating routes this\n\t* registration already holds as available. Nothing is mutated: a rejected\n\t* candidate leaves the registry exactly as it was.\n\t*/\n\tprepareRoutes(providers, adapter, owned) {\n\t\tconst unique = /* @__PURE__ */ new Set();\n\t\tconst registrations = [];\n\t\tfor (const provider of providers) {\n\t\t\tif (provider.length === 0) throw new LlmError(\"adapter provider names must be non-empty\", \"INVALID_ADAPTER\");\n\t\t\tif (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider \"${provider}\" is already registered`, \"DUPLICATE_ADAPTER\");\n\t\t\tconst info = adapter.providerInfo(provider);\n\t\t\tif (typeof info.id !== \"string\" || info.id !== provider || typeof info.name !== \"string\" || info.name.length === 0) throw new LlmError(`adapter metadata for provider \"${provider}\" must preserve its id and have a non-empty name`, \"INVALID_ADAPTER\");\n\t\t\tunique.add(provider);\n\t\t\tconst retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider \"${provider}\" retryPolicy`);\n\t\t\tregistrations.push({\n\t\t\t\tadapter,\n\t\t\t\tprovider: {\n\t\t\t\t\tid: info.id,\n\t\t\t\t\tname: info.name\n\t\t\t\t},\n\t\t\t\tretryPolicy\n\t\t\t});\n\t\t}\n\t\treturn registrations;\n\t}\n\t/**\n\t* Swap this registration's routes for the prepared ones in one synchronous\n\t* section, so no observer can see the registry between the release and the\n\t* re-registration. The route set's one mutation point is also where\n\t* `llm/adapters-updated` is published, so a `replace` announces itself\n\t* exactly like a first registration.\n\t*/\n\tcommitRoutes(owned, registrations) {\n\t\tfor (const provider of owned) this.adapters.delete(provider);\n\t\towned.clear();\n\t\tfor (const registration of registrations) {\n\t\t\tthis.adapters.set(registration.provider.id, registration);\n\t\t\towned.add(registration.provider.id);\n\t\t}\n\t\tthis.emitAdaptersUpdated();\n\t}\n\t/**\n\t* Describe provider routes with a registered adapter.\n\t* @returns detached provider metadata in registration order.\n\t*/\n\tlistProviders() {\n\t\treturn [...this.adapters.values()].map(({ provider }) => ({ ...provider }));\n\t}\n\t/**\n\t* Declare provider routes an adapter plugin can activate through\n\t* configuration. Registration is all-or-nothing: an empty list, invalid\n\t* entry, or a provider already declared by any registration throws\n\t* `LlmError` without registering the rest. Disposed with the fiber.\n\t* @param entries - every configurable provider this plugin owns.\n\t* @returns a handle that withdraws all of them, and can atomically replace them.\n\t*/\n\tregisterConfigurableProviders(entries) {\n\t\tlet held = [];\n\t\tlet disposed = false;\n\t\t/**\n\t\t* Validate a candidate set in full against everything this registration\n\t\t* does not already hold, then publish it. Nothing is written until the\n\t\t* whole set passes, so a refused candidate leaves the current entries in\n\t\t* place — the property that makes `replace` a swap rather than a\n\t\t* delete-then-add that can strand the directory empty.\n\t\t*/\n\t\tconst commit = (candidates) => {\n\t\t\tconst detached = [];\n\t\t\tconst own = new Set(held.map((entry) => entry.provider));\n\t\t\tfor (const entry of candidates) {\n\t\t\t\tif (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError(\"configurable providers need a non-empty provider, displayName, and settingsNs\", \"INVALID_DIRECTORY\");\n\t\t\t\tif (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider \"${entry.provider}\" has an empty settingsPath segment`, \"INVALID_DIRECTORY\");\n\t\t\t\tif (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider \"${entry.provider}\" is already declared`, \"DUPLICATE_DIRECTORY\");\n\t\t\t\tdetached.push({\n\t\t\t\t\t...entry,\n\t\t\t\t\tsettingsPath: [...entry.settingsPath]\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const entry of held) this.directory.delete(entry.provider);\n\t\t\tfor (const entry of detached) this.directory.set(entry.provider, entry);\n\t\t\theld = detached;\n\t\t\tthis.emitAdaptersUpdated();\n\t\t};\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (entries.length === 0) throw new LlmError(\"a configurable-provider registration must declare at least one provider\", \"INVALID_DIRECTORY\");\n\t\t\tcommit(entries);\n\t\t\tyield () => {\n\t\t\t\tdisposed = true;\n\t\t\t\tfor (const entry of held) this.directory.delete(entry.provider);\n\t\t\t\theld = [];\n\t\t\t\tthis.emitAdaptersUpdated();\n\t\t\t};\n\t\t}.bind(this), \"llm.registerConfigurableProviders()\");\n\t\tconst handle = (() => void dispose());\n\t\thandle.replace = (next) => {\n\t\t\tif (disposed) throw new LlmError(\"this configurable-provider registration was disposed\", \"REGISTRATION_DISPOSED\");\n\t\t\tcommit(next);\n\t\t};\n\t\treturn handle;\n\t}\n\t/**\n\t* List every declared configurable provider, registered or dormant.\n\t* @returns detached directory entries in declaration order.\n\t*/\n\tlistConfigurableProviders() {\n\t\treturn [...this.directory.values()].map((entry) => ({\n\t\t\t...entry,\n\t\t\tsettingsPath: [...entry.settingsPath]\n\t\t}));\n\t}\n\t/**\n\t* Offer to interrogate provider endpoints on behalf of the settings\n\t* namespace this plugin owns. The namespace is the key because that is what\n\t* a configuration surface already holds from the configurable-provider\n\t* directory, and because a provider being *added* has no route to name yet.\n\t* Disposed with the fiber.\n\t* @param settingsNs - the namespace whose profiles this discovery serves.\n\t* @param discover - interrogates one endpoint; must honor `request.signal`.\n\t* @returns the disposer that withdraws the offer.\n\t*/\n\tregisterModelDiscovery(settingsNs, discover) {\n\t\tconst dispose = this.ctx.effect(function* () {\n\t\t\tif (settingsNs.length === 0) throw new LlmError(\"model discovery needs a non-empty settings namespace\", \"INVALID_DISCOVERY\");\n\t\t\tif (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for \"${settingsNs}\" is already registered`, \"DUPLICATE_DISCOVERY\");\n\t\t\tthis.discoveries.set(settingsNs, discover);\n\t\t\tyield () => {\n\t\t\t\tthis.discoveries.delete(settingsNs);\n\t\t\t};\n\t\t}.bind(this), \"llm.registerModelDiscovery()\");\n\t\treturn () => void dispose();\n\t}\n\t/**\n\t* Interrogate one provider endpoint for the models it advertises. The\n\t* request describes a draft, not a stored route, so nothing here reads or\n\t* writes settings or credentials — the caller owns both, and the reply is\n\t* candidate metadata a surface may offer for adoption.\n\t* @param settingsNs - namespace whose registered discovery serves this draft.\n\t* @param request - the endpoint, protocol, and one-shot credential to use.\n\t* @returns the advertised models, deduplicated in endpoint order.\n\t*/\n\tasync discoverModels(settingsNs, request) {\n\t\tconst discover = this.discoveries.get(settingsNs);\n\t\tif (discover === void 0) throw new LlmError(`no model discovery is registered for \"${settingsNs}\"`, \"NO_DISCOVERY\");\n\t\tif ((request.provider ?? \"\").length === 0 && (request.baseURL ?? \"\").length === 0) throw new LlmError(\"model discovery needs a provider route or a baseURL\", \"INVALID_DISCOVERY\");\n\t\tconst discovered = await discover(request);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst models = [];\n\t\tfor (const model of discovered) {\n\t\t\tif (typeof model.id !== \"string\" || model.id.length === 0 || seen.has(model.id)) continue;\n\t\t\tseen.add(model.id);\n\t\t\tmodels.push({\n\t\t\t\tid: model.id,\n\t\t\t\t...model.name === void 0 ? {} : { name: model.name },\n\t\t\t\t...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },\n\t\t\t\t...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }\n\t\t\t});\n\t\t}\n\t\treturn models;\n\t}\n\t/**\n\t* Resolve the retry policy captured when one provider route was registered.\n\t* @param provider - registered provider route to inspect.\n\t* @returns the provider-owned policy, with normal defaults already resolved.\n\t*/\n\tproviderRetryPolicy(provider) {\n\t\treturn this.registration(provider).retryPolicy;\n\t}\n\t/** Detach typed adapter-owned modality metadata. */\n\tdetachedModalities(modalities) {\n\t\treturn modalities === void 0 ? void 0 : [...modalities];\n\t}\n\t/**\n\t* Discover models advertised by one registered provider. Catalog membership\n\t* is advisory and never changes routing or request validation.\n\t* @param provider - registered provider route to inspect.\n\t* @returns detached model metadata in adapter-preferred order.\n\t*/\n\tasync listModels(provider) {\n\t\tconst models = await this.registration(provider).adapter.listModels(provider);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\treturn models.map((model) => {\n\t\t\tif (typeof model.provider !== \"string\" || model.provider !== provider || typeof model.id !== \"string\" || model.id.length === 0 || typeof model.name !== \"string\" || model.name.length === 0 || model.description !== void 0 && typeof model.description !== \"string\" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider \"${provider}\"`, \"INVALID_CATALOG\");\n\t\t\tseen.add(model.id);\n\t\t\tconst inputModalities = this.detachedModalities(model.inputModalities);\n\t\t\treturn {\n\t\t\t\tprovider: model.provider,\n\t\t\t\tid: model.id,\n\t\t\t\tname: model.name,\n\t\t\t\t...model.description === void 0 ? {} : { description: model.description },\n\t\t\t\t...inputModalities === void 0 ? {} : { inputModalities }\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Resolve and validate all metadata from the adapter that owns one exact\n\t* route. The result is detached from adapter-owned objects; catalog\n\t* membership remains advisory and does not control request routing.\n\t* @param provider - registered provider route to inspect.\n\t* @param model - exact model id passed to the adapter.\n\t* @param signal - optional cancellation for adapter-owned asynchronous lookup.\n\t* @returns exact model identity plus available context and reasoning metadata.\n\t*/\n\tasync resolveModelInfo(provider, model, signal) {\n\t\treturn this.resolveModelInfoFor(this.registration(provider), model, signal);\n\t}\n\tasync resolveModelInfoFor(registration, model, signal) {\n\t\tconst resolved = await registration.adapter.resolveModel(registration.provider.id, model, signal);\n\t\treturn this.normalizeModelInfo(registration, model, resolved);\n\t}\n\t/** Validate and detach one adapter-returned exact model result. */\n\tnormalizeModelInfo(registration, model, resolved) {\n\t\tconst provider = registration.provider.id;\n\t\tif (typeof resolved.provider !== \"string\" || resolved.provider !== provider || typeof resolved.id !== \"string\" || resolved.id !== model || typeof resolved.name !== \"string\" || resolved.name.length === 0 || resolved.description !== void 0 && typeof resolved.description !== \"string\") throw new LlmError(`adapter returned invalid exact model metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_INFO\");\n\t\tconst context = resolved.context;\n\t\tif (context !== void 0 && (!Number.isInteger(context.contextWindow) || context.contextWindow <= 0)) throw new LlmError(`adapter returned invalid context metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_CONTEXT\");\n\t\tconst inputModalities = this.detachedModalities(resolved.inputModalities);\n\t\tconst defaultMaxTokens = resolved.defaultMaxTokens;\n\t\tif (defaultMaxTokens !== void 0 && (!Number.isSafeInteger(defaultMaxTokens) || defaultMaxTokens <= 0)) throw new LlmError(`adapter returned invalid default maxTokens for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_MAX_TOKENS\");\n\t\tconst info = {\n\t\t\tprovider,\n\t\t\tid: model,\n\t\t\tname: resolved.name,\n\t\t\t...resolved.description === void 0 ? {} : { description: resolved.description },\n\t\t\t...inputModalities === void 0 ? {} : { inputModalities },\n\t\t\t...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },\n\t\t\t...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens }\n\t\t};\n\t\tconst reasoning = resolved.reasoning;\n\t\tif (reasoning === void 0) return info;\n\t\tif (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst efforts = reasoning.efforts.map((effort) => {\n\t\t\tif (typeof effort.id !== \"string\" || effort.id.length === 0 || typeof effort.name !== \"string\" || effort.name.length === 0 || effort.description !== void 0 && typeof effort.description !== \"string\" || seen.has(effort.id)) throw new LlmError(`adapter returned invalid or duplicate reasoning effort metadata for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\t\tseen.add(effort.id);\n\t\t\treturn {\n\t\t\t\tid: effort.id,\n\t\t\t\tname: effort.name,\n\t\t\t\t...effort.description === void 0 ? {} : { description: effort.description }\n\t\t\t};\n\t\t});\n\t\tif (reasoning.defaultEffort !== void 0 && !seen.has(reasoning.defaultEffort)) throw new LlmError(`adapter returned an unknown default reasoning effort for provider \"${provider}\" model \"${model}\"`, \"INVALID_MODEL_REASONING\");\n\t\treturn {\n\t\t\t...info,\n\t\t\treasoning: {\n\t\t\t\tefforts,\n\t\t\t\t...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Validate a conversation call config against its exact model capability and\n\t* materialize adapter-configured defaults. Unsupported explicit efforts\n\t* reject before provider I/O; no clamping or aliasing is performed. This\n\t* standalone query does not bind a later dispatch; use {@link prepareCall}\n\t* when logging and streaming must share one adapter registration.\n\t* @param config - provider/model route and optional request controls.\n\t* @param signal - optional cancellation for adapter-owned capability lookup.\n\t* @returns a detached config only when a default must be materialized.\n\t*/\n\tasync resolveCallConfig(config, signal) {\n\t\treturn (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;\n\t}\n\tasync resolveCallFor(registration, config, signal) {\n\t\tconst info = await this.resolveModelInfoFor(registration, config.model, signal);\n\t\treturn this.resolveCallWithInfo(config, info);\n\t}\n\t/** Validate request controls against one already-bound exact model result. */\n\tresolveCallWithInfo(config, info) {\n\t\tconst defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {\n\t\t\t...config,\n\t\t\tmaxTokens: info.defaultMaxTokens\n\t\t} : config;\n\t\tconst reasoning = info.reasoning;\n\t\tconst requested = defaulted.reasoningEffort;\n\t\tlet resolvedConfig = defaulted;\n\t\tif (reasoning === void 0) {\n\t\t\tif (requested !== void 0) throw new LlmError(`provider \"${config.provider}\" model \"${config.model}\" does not support reasoning effort \"${requested}\"`, \"UNSUPPORTED_REASONING_EFFORT\");\n\t\t} else {\n\t\t\tconst effective = requested ?? reasoning.defaultEffort;\n\t\t\tif (effective !== void 0) {\n\t\t\t\tif (!reasoning.efforts.some((effort) => effort.id === effective)) throw new LlmError(`provider \"${config.provider}\" model \"${config.model}\" does not support reasoning effort \"${effective}\"`, \"UNSUPPORTED_REASONING_EFFORT\");\n\t\t\t\tif (requested !== effective) resolvedConfig = {\n\t\t\t\t\t...defaulted,\n\t\t\t\t\treasoningEffort: effective\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tconfig: resolvedConfig,\n\t\t\t...info.context === void 0 ? {} : { context: info.context },\n\t\t\tmodelInfo: info\n\t\t};\n\t}\n\t/**\n\t* Resolve one call under its current adapter registration. The returned\n\t* one-shot handle keeps that registration across header logging and dispatch,\n\t* so HMR cannot combine one adapter's capability result with another adapter.\n\t* @param config - provider/model route and optional request controls.\n\t* @param signal - optional cancellation for adapter-owned capability lookup.\n\t* @returns a prepared config and its registration-bound stream entry point.\n\t*/\n\tasync prepareCall(config, signal) {\n\t\tconst registration = this.registration(config.provider);\n\t\tconst adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal);\n\t\tconst modelInfo = this.normalizeModelInfo(registration, config.model, adapterCall.model);\n\t\tconst resolved = this.resolveCallWithInfo(config, modelInfo);\n\t\tconst resolvedConfig = deepFreeze(structuredClone(resolved.config));\n\t\tconst context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));\n\t\tconst adapterDefaults = deepFreeze({\n\t\t\t...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},\n\t\t\t...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}\n\t\t});\n\t\tlet dispatched = false;\n\t\treturn Object.freeze({\n\t\t\tconfig: resolvedConfig,\n\t\t\tretryPolicy: registration.retryPolicy,\n\t\t\tadapterDefaults,\n\t\t\t...context === void 0 ? {} : { context },\n\t\t\t...modelInfo.inputModalities === void 0 ? {} : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },\n\t\t\tstream: (options) => {\n\t\t\t\tif (dispatched) throw new LlmError(\"a prepared LLM call can only be dispatched once\", \"INVALID_PREPARED_CALL\");\n\t\t\t\tif (!callConfigEquals(options, resolvedConfig)) throw new LlmError(\"prepared LLM call config changed before adapter dispatch\", \"INVALID_PREPARED_CALL\");\n\t\t\t\tdispatched = true;\n\t\t\t\treturn this.streamWithRegistration(options, {\n\t\t\t\t\tregistration,\n\t\t\t\t\tconfig: resolvedConfig,\n\t\t\t\t\tmodelInfo,\n\t\t\t\t\tdispatch: (options) => adapterCall.stream(options)\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\tregistration(provider) {\n\t\tconst registration = this.adapters.get(provider);\n\t\tif (!registration) throw new LlmError(`no adapter registered for provider \"${provider}\"`, \"NO_ADAPTER\");\n\t\treturn registration;\n\t}\n\t/** Remove replay state whose historical route is owned by another adapter. */\n\tforAdapter(options, adapter) {\n\t\tconst messages = options.messages.map((message) => {\n\t\t\tconst source = message.source;\n\t\t\tif (message.role !== \"assistant\" || source.kind !== \"model\" || source.replayState === void 0) return message;\n\t\t\tif (this.adapters.get(source.provider)?.adapter === adapter) return message;\n\t\t\treturn freezeMessage({\n\t\t\t\t...message,\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"model\",\n\t\t\t\t\tprovider: source.provider,\n\t\t\t\t\tmodel: source.model\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (messages.every((message, index) => message === options.messages[index])) return options;\n\t\tconst filtered = {\n\t\t\t...options,\n\t\t\tmessages\n\t\t};\n\t\treturn Object.isFrozen(options) ? deepFreeze(filtered) : filtered;\n\t}\n\t/**\n\t* Final adapter boundary. Adapter selection, dispatch, iterator construction,\n\t* and iteration failures become one terminal failure chunk. Middleware and\n\t* downstream consumer failures remain thrown plugin or consumer errors.\n\t*/\n\tasync *adapterStream(options, prepared) {\n\t\tlet iterator;\n\t\ttry {\n\t\t\tconst registration = prepared?.registration ?? this.registration(options.provider);\n\t\t\tconst adapter = registration.adapter;\n\t\t\tlet modelInfo;\n\t\t\tlet resolvedConfig;\n\t\t\tlet dispatch;\n\t\t\tif (prepared === void 0) {\n\t\t\t\tconst adapterCall = await adapter.prepareCall(options.provider, options.model, options.signal);\n\t\t\t\tmodelInfo = this.normalizeModelInfo(registration, options.model, adapterCall.model);\n\t\t\t\tresolvedConfig = this.resolveCallWithInfo(options, modelInfo).config;\n\t\t\t\tdispatch = (options) => adapterCall.stream(options);\n\t\t\t} else {\n\t\t\t\tmodelInfo = prepared.modelInfo;\n\t\t\t\tresolvedConfig = prepared.config;\n\t\t\t\tdispatch = prepared.dispatch;\n\t\t\t}\n\t\t\tif (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError(\"prepared LLM call config changed before adapter dispatch\", \"INVALID_PREPARED_CALL\");\n\t\t\tconst resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({\n\t\t\t\t...options,\n\t\t\t\t...resolvedConfig\n\t\t\t}) : {\n\t\t\t\t...options,\n\t\t\t\t...resolvedConfig\n\t\t\t};\n\t\t\tconst projectedOptions = modelInfo.inputModalities !== void 0 && !modelInfo.inputModalities.includes(\"image\") && resolvedOptions.messages.some((message) => contentHasImage(message.content)) ? Object.isFrozen(resolvedOptions) ? deepFreeze({\n\t\t\t\t...resolvedOptions,\n\t\t\t\tmessages: projectImagesForTextModel(resolvedOptions.messages)\n\t\t\t}) : {\n\t\t\t\t...resolvedOptions,\n\t\t\t\tmessages: projectImagesForTextModel(resolvedOptions.messages)\n\t\t\t} : resolvedOptions;\n\t\t\titerator = dispatch(this.forAdapter(projectedOptions, adapter))[Symbol.asyncIterator]();\n\t\t} catch (error) {\n\t\t\tyield adapterFailureChunk(error, options.signal);\n\t\t\treturn;\n\t\t}\n\t\tlet completed = false;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tlet item;\n\t\t\t\ttry {\n\t\t\t\t\tconst next = await iterator.next();\n\t\t\t\t\titem = next.done ? { done: true } : {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: next.value\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\tyield adapterFailureChunk(error, options.signal);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (item.done) {\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tyield item.value;\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed) {\n\t\t\t\tconst close = iterator.return?.bind(iterator);\n\t\t\t\tif (close) await close();\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Stream one model call as raw chunks (token-level deltas). Replay state is\n\t* retained only when the same adapter instance owns its historical provider\n\t* and the target provider. Final adapter selection remains fixed through\n\t* asynchronous exact-model resolution and dispatch. Adapter selection,\n\t* dispatch, and iteration failures become terminal `error` or `aborted`\n\t* finish chunks; middleware, nested-call, cleanup, and consumer failures\n\t* remain thrown.\n\t* @param options - the full request; `options.provider` selects the adapter.\n\t* @returns the chunk stream, possibly wrapped by `llm/stream` listeners.\n\t*/\n\tstream(options) {\n\t\treturn this.streamWithRegistration(options);\n\t}\n\tstreamWithRegistration(options, prepared) {\n\t\treturn this.ctx.waterfall(this, \"llm/stream\", options, () => this.adapterStream(options, prepared));\n\t}\n};\n/** Convert one adapter throw into the stream protocol's terminal outcome. */\nfunction adapterFailureChunk(error, signal) {\n\tconst failure = normalizeLlmFailure(error);\n\treturn {\n\t\ttype: \"finish\",\n\t\treason: signal?.aborted || failure.code === \"ABORTED\" ? {\n\t\t\tkind: \"aborted\",\n\t\t\tfailure\n\t\t} : {\n\t\t\tkind: \"error\",\n\t\t\tfailure\n\t\t}\n\t};\n}\n//#endregion\nexport { APP_IDENTITY, BlockAssembler, CONTEXT_SUMMARY_MAX_CHARS, CONTEXT_WINDOW_EXCEEDED_CODE, CallId, EMPTY_RESPONSE_CODE, HarnessError, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, LlmRuntime, LlmRuntime as default, MessageId, OFFLOADED_IMAGE_TEXT, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId, RetryPolicySchema, assertNever, assertUsableApiKey, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createAssistantMessage, createMessage, createToolResultMessage, createUserMessage, deepFreeze, errorChain, freezeMessage, isAgentLoopRequest, isContextWindowExceededError, isHarnessError, isQuotaExceededError, isTokenDelta, markAgentLoopRequest, normalizeApiKey, offloadRequestImages, offloadRequestImagesWithPolicy, projectImagesForTextModel, requestImageHandleText, resolveRetryPolicy, textOnlyImageText, userAgent };\n","// Branded types and graph data structures shared across the Host/Client boundary.\n// Graph heat-update events are declared here via Cordis declaration merging.\n\nexport type Branded<T, Brand> = T & { __brand: Brand };\n\nexport type RepoId = Branded<string, 'RepoId'>;\nexport type SymbolId = Branded<string, 'SymbolId'>;\nexport type NodeId = Branded<string, 'NodeId'>;\nexport type EdgeId = Branded<string, 'EdgeId'>;\n\nexport const RepoId = (id: string): RepoId => id as RepoId;\nexport const SymbolId = (id: string): SymbolId => id as SymbolId;\nexport const NodeId = (id: string): NodeId => id as NodeId;\nexport const EdgeId = (id: string): EdgeId => id as EdgeId;\n\nexport interface GraphNode {\n id: NodeId;\n label: string;\n type: 'function' | 'class' | 'variable' | 'module' | 'interface' | 'type';\n filePath: string;\n lineNumber: number;\n properties: Record<string, unknown>;\n parentId?: NodeId;\n}\n\nexport interface GraphEdge {\n id: EdgeId;\n source: NodeId;\n target: NodeId;\n type: 'call' | 'import' | 'extend' | 'implement' | 'dependency';\n properties: Record<string, unknown>;\n}\n\nexport interface GraphData {\n nodes: GraphNode[];\n edges: GraphEdge[];\n metadata: {\n repoId: RepoId;\n timestamp: number;\n nodeCount: number;\n edgeCount: number;\n truncated?: boolean;\n totalNodeCount?: number;\n totalEdgeCount?: number;\n };\n}\n\nexport type DataSourceType = 'codegraph' | 'lens';\n\nexport interface AdapterResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n source: DataSourceType;\n timestamp: number;\n error?: string;\n}\n\n// ---- Graph heat-update event payloads -------------------------------------\n\nexport interface GraphUpdatedEvent {\n repoId: string;\n nodeCount: number;\n edgeCount: number;\n timestamp: number;\n}\n\nexport interface GraphDataEvent {\n repoId: string;\n nodes: GraphNode[];\n edges: GraphEdge[];\n timestamp: number;\n}\n\nexport interface RepoImportedEvent {\n repoId: string;\n path: string;\n timestamp: number;\n}\n\nexport interface RepoScannedEvent {\n repoId: string;\n fileCount: number;\n timestamp: number;\n}\n\nexport interface RepoRequestScanEvent {\n path: string;\n timestamp: number;\n}\n\nexport interface SourceOpenEvent {\n filePath: string;\n lineNumber: number;\n}\n\nexport interface PrerequisiteStatusEvent {\n codegraph: boolean;\n lens: boolean;\n timestamp: number;\n}\n\nexport interface GraphInitEvent {\n path: string;\n timestamp: number;\n}\n\nexport interface GraphInitResultEvent {\n success: boolean;\n path: string;\n message: string;\n timestamp: number;\n}\n\nexport interface WatchToggleEvent {\n enabled: boolean;\n path: string;\n timestamp: number;\n}\n\n// ---- Cordis event declaration merging ------------------------------------\n// These are emitted by the host plugin; Client/host listeners subscribe via\n// `ctx.on(...)`. Keep them writer-only so consumers never redefine the contract.\ndeclare module '@deepseek-ai/cordis' {\n interface Events {\n 'codegraph/repo/imported'(event: RepoImportedEvent): void;\n 'codegraph/repo/scanned'(event: RepoScannedEvent): void;\n 'codegraph/repo/request-scan'(event: RepoRequestScanEvent): void;\n 'codegraph/graph/updated'(event: GraphUpdatedEvent): void;\n 'codegraph/graph/data'(event: GraphDataEvent): void;\n 'codegraph/source/open'(event: SourceOpenEvent): void;\n 'codegraph/prerequisite/status'(event: PrerequisiteStatusEvent): void;\n 'codegraph/prerequisite/request'(event: { timestamp: number }): void;\n 'codegraph/graph/init'(event: GraphInitEvent): void;\n 'codegraph/graph/init-result'(event: GraphInitResultEvent): void;\n 'codegraph/watch/toggle'(event: WatchToggleEvent): void;\n }\n interface Context {\n webServer: WebServerService;\n effect(execute: () => (() => void) | void, label?: string): () => void;\n emit<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): void;\n on<K extends keyof Events>(name: K, listener: Events[K]): () => boolean;\n get(name: string, strict?: boolean): unknown;\n provide(name: string, service: unknown): () => void;\n slots: {\n inject(slotName: string, callback: () => void): void;\n register(options: { name: string; id: string; order?: number; label?: () => string }, component?: unknown): (() => void) | void;\n };\n betterSidebar?: {\n registerTab(descriptor: {\n id: string;\n title: string | (() => string);\n icon?: unknown;\n order?: number;\n single?: boolean;\n component: (props: { visible: boolean }) => unknown;\n }): () => void;\n openTab(seed: { type: string }): void;\n };\n spotlight?: {\n registerCommand(cmd: { id: string; title: string; handler: () => void }): (() => void) | void;\n };\n }\n}\n\n// ---- DSH WebServer service (Host-side HTTP route registration) -----------\n\nexport interface IGraphVisualizerService {\n getCurrentGraph(): GraphData | null;\n getGraphData(repoId: string): Promise<GraphData | null>;\n getSymbolDetail(symbolId: string): Promise<unknown>;\n getImpactAnalysis(symbolId: string): Promise<unknown>;\n onGraphUpdate(callback: (data: GraphData) => void): () => void;\n}\n\nexport interface WebServerRoute {\n kind: 'exact' | 'prefix';\n path: string;\n handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;\n}\n\nexport interface WebServerService {\n register(route: WebServerRoute): () => void;\n registerFallback(handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>): () => void;\n}\n\n// Minimal Node.js HTTP types (avoid pulling in @types/node for client builds)\nexport interface IncomingMessage {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n on(event: 'data', handler: (chunk: Buffer) => void): void;\n on(event: 'end', handler: () => void): void;\n on(event: 'error', handler: (err: Error) => void): void;\n}\n\nexport interface ServerResponse {\n writeHead(code: number, headers?: Record<string, string>): void;\n end(data?: string): void;\n}\n\n// ---- DSH Module Loader (runtime global) ----------------------------------\n// Injected by the DSH web app boot script. Client bundles register themselves\n// via __ModuleLoader__.load({ id, factory }) so the shell can wire them into\n// the page (slots, overlays, etc.). The factory receives a `require` function\n// for resolving platform externals (react, react-dom, cordis, etc.).\ninterface ModuleLoader {\n load(registration: { id: string; factory: (require: (id: string) => unknown) => Record<string, unknown> }): void;\n}\n\ndeclare const __ModuleLoader__: ModuleLoader | undefined;","// Lightweight structured logger with an in-memory ring buffer for UI surfacing.\n// Ponytail: no deps, ~60 lines. Levels respect host console when available.\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LogEntry {\n ts: number;\n level: LogLevel;\n scope: string;\n message: string;\n data?: unknown;\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };\nconst RING_SIZE = 200;\n\nclass LoggerImpl {\n private buffer: LogEntry[] = [];\n private listeners = new Set<(entries: LogEntry[]) => void>();\n minLevel: LogLevel = (typeof globalThis !== 'undefined' &&\n (globalThis as unknown as { __CG_DEBUG?: boolean }).__CG_DEBUG) ? 'debug' : 'info';\n\n log(level: LogLevel, scope: string, message: string, data?: unknown): void {\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel]) return;\n const entry: LogEntry = { ts: Date.now(), level, scope, message, data };\n this.buffer.push(entry);\n if (this.buffer.length > RING_SIZE) this.buffer.splice(0, this.buffer.length - RING_SIZE);\n this.emit();\n const fn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;\n try { fn(`[codegraph:${scope}] ${message}`, data ?? ''); } catch { /* console unavailable */ }\n }\n\n debug(scope: string, message: string, data?: unknown): void { this.log('debug', scope, message, data); }\n info(scope: string, message: string, data?: unknown): void { this.log('info', scope, message, data); }\n warn(scope: string, message: string, data?: unknown): void { this.log('warn', scope, message, data); }\n error(scope: string, message: string, data?: unknown): void { this.log('error', scope, message, data); }\n\n entries(): LogEntry[] { return this.buffer.slice(); }\n clear(): void { this.buffer = []; this.emit(); }\n\n subscribe(fn: (entries: LogEntry[]) => void): () => void {\n this.listeners.add(fn);\n fn(this.entries());\n return () => { this.listeners.delete(fn); };\n }\n\n private emit(): void {\n const snapshot = this.entries();\n for (const fn of this.listeners) { try { fn(snapshot); } catch { /* listener fault */ } }\n }\n}\n\nexport const logger = new LoggerImpl();\n\n// Convenience scoped logger factory.\nexport function scoped(scope: string) {\n return {\n debug: (m: string, d?: unknown) => logger.debug(scope, m, d),\n info: (m: string, d?: unknown) => logger.info(scope, m, d),\n warn: (m: string, d?: unknown) => logger.warn(scope, m, d),\n error: (m: string, d?: unknown) => logger.error(scope, m, d),\n };\n}","// CodeGraphAdapter - adapter for the optional dsh-codegraph data source.\n//\n// Primary path: read the .codegraph/codegraph.db SQLite index directly\n// (node:sqlite, Node >= 22.5). One O(N+E) query returns the whole graph —\n// no N+1 tool calls, works even when dsh-codegraph's tool surface is 'core'\n// (which exposes no full-graph query tool).\n//\n// Fallback path: upstream tools (codegraph_query / codegraph_callers /\n// codegraph_callees) when the DB cannot be read (e.g. remote sandboxed fs).\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport type { GraphNode, GraphEdge, AdapterResult, DataSourceType } from '../types/index.ts';\nimport { NodeId, EdgeId } from '../types/index.ts';\nimport { scoped } from '../shared/Logger.ts';\n\nconst log = scoped('codegraph-adapter');\n\nconst require = createRequire(import.meta.url);\n\nexport type UpstreamInvoker = (tool: string, args: Record<string, unknown>) => Promise<unknown | null>;\n\n// ---- codegraph.db schema (upstream @colbymchenry/codegraph) ----------------\n\ninterface DbNodeRow {\n id: string;\n kind: string;\n name: string;\n file_path: string;\n start_line: number;\n signature: string | null;\n docstring: string | null;\n is_exported: number;\n}\n\ninterface DbEdgeRow {\n id: number;\n source: string;\n target: string;\n kind: string;\n line: number | null;\n}\n\nconst NODE_KIND_MAP: Record<string, GraphNode['type']> = {\n function: 'function',\n method: 'function',\n class: 'class',\n interface: 'interface',\n type_alias: 'type',\n constant: 'variable',\n variable: 'variable',\n property: 'variable',\n file: 'module',\n import: 'module',\n module: 'module',\n};\n\nconst EDGE_KIND_MAP: Record<string, GraphEdge['type']> = {\n call: 'call',\n calls: 'call',\n import: 'import',\n imports: 'import',\n extend: 'extend',\n extends: 'extend',\n implement: 'implement',\n implements: 'implement',\n contains: 'dependency',\n dependency: 'dependency',\n depends: 'dependency',\n};\n\nexport function mapNodeKind(kind: string): GraphNode['type'] {\n return NODE_KIND_MAP[kind] ?? 'module';\n}\n\nexport function mapEdgeKind(kind: string): GraphEdge['type'] {\n return EDGE_KIND_MAP[kind] ?? 'dependency';\n}\n\n/** Locate the .codegraph/codegraph.db for a workspace path. */\nexport function resolveDbPath(workspacePath: string): string {\n const root = workspacePath && workspacePath !== '.' ? workspacePath : process.cwd();\n return join(root, '.codegraph', 'codegraph.db');\n}\n\n/** Read the whole graph from a codegraph.db. Returns null when unreadable. */\nexport function readGraphFromDb(dbPath: string): { nodes: DbNodeRow[]; edges: DbEdgeRow[] } | null {\n if (!existsSync(dbPath)) return null;\n try {\n // node:sqlite is available on Node >= 22.5 (project engines: >=22.19 || >=24).\n // createRequire keeps the built-in out of the ESM graph while staying sync.\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(dbPath, { readOnly: true });\n try {\n const nodes = db.prepare(\n 'SELECT id, kind, name, file_path, start_line, signature, docstring, is_exported FROM nodes',\n ).all() as unknown as DbNodeRow[];\n const edges = db.prepare(\n 'SELECT id, source, target, kind, line FROM edges',\n ).all() as unknown as DbEdgeRow[];\n return { nodes, edges };\n } finally {\n db.close();\n }\n } catch (e) {\n log.warn('readGraphFromDb failed', e);\n return null;\n }\n}\n\nexport class CodeGraphAdapter {\n private readonly source: DataSourceType = 'codegraph';\n\n async fetchData(repoId: string, invoke: UpstreamInvoker): Promise<AdapterResult> {\n // Primary: direct SQLite read of the upstream index (single O(N+E) query).\n const dbRows = readGraphFromDb(resolveDbPath(repoId));\n if (dbRows && dbRows.nodes.length > 0) {\n return this.toAdapterResult(dbRows.nodes, dbRows.edges);\n }\n\n // Fallback (DB unreadable): assemble a file-structure skeleton from the\n // upstream `codegraph_files` tool so the panel at least shows the project\n // layout. No relations — the full graph needs the DB.\n const files = await invoke('codegraph_files', { path: repoId, format: 'flat' });\n if (!files || typeof files !== 'object') {\n return { nodes: [], edges: [], source: this.source, timestamp: Date.now() };\n }\n const rawFiles = this.extractFileList(files);\n const nodes: GraphNode[] = rawFiles.map((f, i) => ({\n id: NodeId(`file:${f.path}`),\n label: f.path.split('/').pop() ?? f.path,\n type: 'module',\n filePath: f.path,\n lineNumber: 1,\n properties: { kind: 'file', language: f.language ?? null, index: i },\n }));\n return { nodes, edges: [], source: this.source, timestamp: Date.now() };\n }\n\n private extractFileList(files: unknown): Array<{ path: string; language?: string }> {\n // codegraph_files --json returns either an array of file records or an\n // object with a files/files[] key, depending on CLI version.\n if (Array.isArray(files)) {\n return files.flatMap((f) => {\n if (typeof f === 'string') return [{ path: f }];\n const rec = f as Record<string, unknown>;\n if (typeof rec.path === 'string') return [{ path: rec.path, language: rec.language as string | undefined }];\n return [];\n });\n }\n const obj = files as Record<string, unknown>;\n const inner = obj?.files ?? obj?.items;\n return Array.isArray(inner) ? this.extractFileList(inner) : [];\n }\n\n private toAdapterResult(dbNodes: DbNodeRow[], dbEdges: DbEdgeRow[]): AdapterResult {\n const nodeIds = new Set(dbNodes.map((n) => n.id));\n\n const fileNodeIds = new Map<string, string>();\n for (const n of dbNodes) {\n if (n.kind === 'file' || n.kind === 'module') {\n fileNodeIds.set(n.file_path, n.id);\n }\n }\n\n const nodes: GraphNode[] = dbNodes.map((n) => {\n const parentId = (n.kind !== 'file' && n.kind !== 'module' && n.kind !== 'import')\n ? fileNodeIds.get(n.file_path) ?? undefined\n : undefined;\n return {\n id: NodeId(n.id),\n label: n.name,\n type: mapNodeKind(n.kind),\n filePath: n.file_path,\n lineNumber: n.start_line ?? 1,\n properties: {\n kind: n.kind,\n ...(n.signature ? { signature: n.signature } : {}),\n ...(n.docstring ? { docstring: n.docstring } : {}),\n exported: n.is_exported === 1,\n },\n ...(parentId ? { parentId: NodeId(parentId) } : {}),\n };\n });\n\n const edges: GraphEdge[] = dbEdges\n .filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target))\n .map((e) => ({\n id: EdgeId(String(e.id)),\n source: NodeId(e.source),\n target: NodeId(e.target),\n type: mapEdgeKind(e.kind),\n properties: e.line != null ? { line: e.line } : {},\n }));\n\n return { nodes, edges, source: this.source, timestamp: Date.now() };\n }\n}\n","// LensAdapter - adapter for the optional dsh-tool-lens data source.\nimport type { GraphNode, GraphEdge, AdapterResult, DataSourceType } from '../types/index.ts';\nimport { NodeId, EdgeId } from '../types/index.ts';\nimport type { UpstreamInvoker } from './CodeGraphAdapter.ts';\nimport { scoped } from '../shared/Logger.ts';\n\nconst log = scoped('lens-adapter');\n\ninterface LensToolResult {\n symbols: Array<{\n id: string;\n name: string;\n scope: string;\n file: string;\n line: number;\n category: string;\n }>;\n references: Array<{\n from: string;\n to: string;\n relation: string;\n }>;\n}\n\n\nexport class LensAdapter {\n private readonly source: DataSourceType = 'lens';\n\n async fetchData(repoId: string, invoke: UpstreamInvoker): Promise<AdapterResult> {\n try {\n const raw = (await invoke('lens_analyze', { repoId })) as LensToolResult | null;\n if (!raw) return { nodes: [], edges: [], source: this.source, timestamp: Date.now() };\n\n const symbols = Array.isArray(raw.symbols) ? raw.symbols : [];\n const references = Array.isArray(raw.references) ? raw.references : [];\n\n const fileNodeMap = new Map<string, string>();\n for (const s of symbols) {\n if (s.category === 'module' || s.category === 'file') {\n fileNodeMap.set(s.file, s.id);\n }\n }\n\n const nodes: GraphNode[] = symbols.map(s => {\n const parentId = (s.category !== 'module' && s.category !== 'file')\n ? fileNodeMap.get(s.file)\n : undefined;\n return {\n id: NodeId(s.id),\n label: s.name,\n type: this.mapCategory(s.category),\n filePath: s.file,\n lineNumber: s.line,\n properties: { scope: s.scope },\n ...(parentId ? { parentId: NodeId(parentId) } : {}),\n };\n });\n\n const edges: GraphEdge[] = references.map(r => ({\n id: EdgeId(`${r.from}->${r.to}`),\n source: NodeId(r.from),\n target: NodeId(r.to),\n type: this.mapRelation(r.relation),\n properties: {},\n }));\n\n return { nodes, edges, source: this.source, timestamp: Date.now() };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n log.warn('Lens fetchData failed — lens is optional, returning empty', e);\n return { nodes: [], edges: [], source: this.source, timestamp: Date.now(), error: errorMsg };\n }\n }\n\n private mapCategory(cat: string): GraphNode['type'] {\n const map: Record<string, GraphNode['type']> = {\n function: 'function',\n class: 'class',\n variable: 'variable',\n module: 'module',\n interface: 'interface',\n type: 'type',\n };\n return map[cat] ?? 'module';\n }\n\n private mapRelation(rel: string): GraphEdge['type'] {\n const map: Record<string, GraphEdge['type']> = {\n call: 'call',\n reference: 'dependency',\n import: 'import',\n extend: 'extend',\n implement: 'implement',\n };\n return map[rel] ?? 'dependency';\n }\n}","// GraphDataMerger - multi-source aggregation with dedup + delta merge.\nimport type { GraphNode, GraphEdge, GraphData, AdapterResult } from '../types/index.ts';\nimport { RepoId } from '../types/index.ts';\n\nexport class GraphDataMerger {\n merge(results: AdapterResult[], repoId: RepoId): GraphData {\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n\n for (const r of results) {\n for (const node of r.nodes) {\n nodes.set(node.id, {\n ...node,\n properties: { ...node.properties, __source: r.source },\n });\n }\n for (const edge of r.edges) {\n edges.set(edge.id, {\n ...edge,\n properties: { ...edge.properties, __source: r.source },\n });\n }\n }\n\n return {\n nodes: Array.from(nodes.values()),\n edges: Array.from(edges.values()),\n metadata: {\n repoId: RepoId(repoId),\n timestamp: Date.now(),\n nodeCount: nodes.size,\n edgeCount: edges.size,\n },\n };\n }\n\n // Delta merge for incremental heat-updates.\n applyDelta(current: GraphData, delta: AdapterResult): GraphData {\n const nodes = new Map(current.nodes.map(n => [n.id, n]));\n const edges = new Map(current.edges.map(e => [e.id, e]));\n\n for (const node of delta.nodes) {\n const existing = nodes.get(node.id);\n if (existing) {\n nodes.set(node.id, {\n ...existing,\n ...node,\n properties: { ...existing.properties, ...node.properties },\n });\n } else {\n nodes.set(node.id, node);\n }\n }\n for (const edge of delta.edges) {\n const existing = edges.get(edge.id);\n if (existing) {\n edges.set(edge.id, {\n ...existing,\n ...edge,\n properties: { ...existing.properties, ...edge.properties },\n });\n } else {\n edges.set(edge.id, edge);\n }\n }\n\n return {\n nodes: Array.from(nodes.values()),\n edges: Array.from(edges.values()),\n metadata: {\n ...current.metadata,\n timestamp: Date.now(),\n nodeCount: nodes.size,\n edgeCount: edges.size,\n },\n };\n }\n}","// Graph tool definitions: adapters + merger wrapped as DSH `defineTool` tools.\nimport type { Context } from '@deepseek-ai/cordis';\nimport { defineTool } from '@deepseek-ai/dsh-tools';\nimport { CallId } from '@deepseek-ai/dsh-llm';\nimport type { JsonValue } from '@deepseek-ai/dsh-session';\nimport { CodeGraphAdapter } from './adapters/CodeGraphAdapter.ts';\nimport { LensAdapter } from './adapters/LensAdapter.ts';\nimport { GraphDataMerger } from './merger/GraphDataMerger.ts';\nimport type { AdapterResult, GraphData, GraphUpdatedEvent, GraphDataEvent, RepoId } from './types/index.ts';\nimport { RepoId as makeRepoId } from './types/index.ts';\nimport { scoped } from './shared/Logger.ts';\n\nconst log = scoped('tools');\n\nexport type { UpstreamInvoker } from './adapters/CodeGraphAdapter.ts';\nimport type { UpstreamInvoker } from './adapters/CodeGraphAdapter.ts';\n\nconst codegraphAdapter = new CodeGraphAdapter();\nconst lensAdapter = new LensAdapter();\nconst merger = new GraphDataMerger();\n\nconst GRAPH_CACHE_LIMIT = 8;\nconst graphCache = new Map<string, GraphData>();\n\nfunction cacheGraph(repoId: string, data: GraphData): void {\n graphCache.delete(repoId);\n graphCache.set(repoId, data);\n if (graphCache.size > GRAPH_CACHE_LIMIT) {\n const oldest = graphCache.keys().next().value;\n if (oldest !== undefined) graphCache.delete(oldest);\n }\n}\n\nasync function fetchMergedGraph(\n invoke: UpstreamInvoker,\n repoId: string,\n source: 'codegraph' | 'lens' | 'both' = 'both',\n): Promise<GraphData> {\n const tasks: Promise<AdapterResult>[] = [];\n if (source === 'codegraph' || source === 'both') {\n tasks.push(codegraphAdapter.fetchData(repoId, invoke));\n }\n if (source === 'lens' || source === 'both') {\n tasks.push(lensAdapter.fetchData(repoId, invoke));\n }\n const settled = await Promise.allSettled(tasks);\n const results: AdapterResult[] = settled\n .filter((r): r is PromiseFulfilledResult<AdapterResult> => r.status === 'fulfilled')\n .map((r) => r.value);\n return merger.merge(results, makeRepoId(repoId));\n}\n\nfunction summarizeGraph(data: GraphData): string {\n const nodeByType = new Map<string, number>();\n const edgeByType = new Map<string, number>();\n for (const n of data.nodes) nodeByType.set(n.type, (nodeByType.get(n.type) ?? 0) + 1);\n for (const e of data.edges) edgeByType.set(e.type, (edgeByType.get(e.type) ?? 0) + 1);\n\n const nodeStats = [...nodeByType.entries()].map(([t, c]) => `${t}:${c}`).join(', ');\n const edgeStats = [...edgeByType.entries()].map(([t, c]) => `${t}:${c}`).join(', ');\n\n const topNodes = data.nodes.slice(0, 10)\n .map(n => ` • ${n.label} (${n.type}) @ ${n.filePath}:${n.lineNumber}`)\n .join('\\n');\n\n const topEdges = data.edges.slice(0, 10)\n .map(e => ` ${e.source} →${e.type}→ ${e.target}`)\n .join('\\n');\n\n return [\n `Graph: ${data.metadata.nodeCount} nodes [${nodeStats}], ${data.metadata.edgeCount} edges [${edgeStats}]`,\n topNodes ? `\\nTop nodes:\\n${topNodes}` : '',\n topEdges ? `\\nTop edges:\\n${topEdges}` : '',\n ].join('');\n}\n\nexport function normalizeImpact(raw: unknown): { affected: string[]; depth: number } | null {\n if (typeof raw === 'string') {\n try { raw = JSON.parse(raw) as unknown; } catch { log.warn('normalizeImpact: JSON.parse failed'); return null; }\n }\n if (!raw || typeof raw !== 'object') return null;\n const obj = raw as Record<string, unknown>;\n const list = obj.affected ?? obj.affectedNodes ?? obj.nodes;\n if (!Array.isArray(list)) return null;\n return {\n affected: list.map((it) => {\n if (typeof it === 'string') return it;\n const rec = it as Record<string, unknown>;\n return String(rec.name ?? rec.id ?? '?');\n }),\n depth: typeof obj.depth === 'number' ? obj.depth : 2,\n };\n}\n\nexport function pickBestMatch(raw: unknown, symbolId: string): Record<string, unknown> | null {\n let payload = raw;\n if (typeof payload === 'string') {\n try { payload = JSON.parse(payload) as unknown; } catch { log.warn('normalizeCallers: JSON.parse failed'); return null; }\n }\n const items = Array.isArray(payload)\n ? payload\n : (payload as Record<string, unknown>)?.results ?? (payload as Record<string, unknown>)?.nodes;\n if (!Array.isArray(items) || items.length === 0) return null;\n const wanted = symbolId.toLowerCase();\n const best = items.find((it) => {\n const rec = it as Record<string, unknown>;\n return String(rec.name ?? '').toLowerCase() === wanted || rec.id === symbolId;\n }) as Record<string, unknown> | undefined;\n const chosen = best ?? (items[0] as Record<string, unknown>);\n return {\n symbolId,\n name: chosen.name ?? chosen.qualified_name ?? symbolId,\n category: chosen.kind ?? 'unknown',\n file: chosen.filePath ?? chosen.file_path ?? '?',\n line: chosen.startLine ?? chosen.start_line ?? 0,\n signature: chosen.signature ?? null,\n };\n}\n\n// ── Extracted execute/render functions for testability ──────────────────\n\nexport function createInvoke(ctx: Context, requestTimeout = 5000): UpstreamInvoker {\n return async (tool, args) => {\n try {\n const result = await ctx.tools.execute({\n callId: CallId(`codegraph:${tool}`),\n name: tool,\n arguments: args,\n signal: AbortSignal.timeout(requestTimeout),\n });\n if (result.isError) return null;\n return result.value ?? null;\n } catch (e) {\n log.warn('createInvoke: tool execution failed', { tool, error: e });\n return null;\n }\n };\n}\n\nexport function renderGraphStatus(_args: unknown, value: unknown) {\n const v = value as { status: string; nodeCount: number; edgeCount: number; sources?: Record<string, boolean> };\n const srcInfo = v.sources ? ` [codegraph:${v.sources.codegraph ? '✓' : '✗'} lens:${v.sources.lens ? '✓' : '✗'}]` : '';\n return [\n { type: 'text' as const, text: `Graph status: ${v.status} (${v.nodeCount} nodes, ${v.edgeCount} edges)${srcInfo}` },\n ];\n}\n\nexport async function executeGraphStatus(args: { repoId: string }, invoke: UpstreamInvoker) {\n const [cgResult, lensResult] = await Promise.allSettled([\n codegraphAdapter.fetchData(args.repoId, invoke),\n lensAdapter.fetchData(args.repoId, invoke),\n ]);\n const results: AdapterResult[] = [cgResult, lensResult]\n .filter((r): r is PromiseFulfilledResult<AdapterResult> => r.status === 'fulfilled')\n .map((r) => r.value);\n const data = merger.merge(results, makeRepoId(args.repoId));\n return {\n status: data.nodes.length > 0 ? 'ready' : 'unavailable',\n nodeCount: data.metadata.nodeCount,\n edgeCount: data.metadata.edgeCount,\n sources: {\n codegraph: cgResult.status === 'fulfilled' && cgResult.value.nodes.length > 0,\n lens: lensResult.status === 'fulfilled' && lensResult.value.nodes.length > 0,\n },\n };\n}\n\nexport function renderGraphData(_args: unknown, value: unknown) {\n const data = value as unknown as GraphData;\n return [{ type: 'text' as const, text: summarizeGraph(data) }];\n}\n\nexport async function executeGraphData(\n args: { repoId: string; source?: string },\n invoke: UpstreamInvoker,\n emitUpdate: (event: GraphUpdatedEvent) => void,\n emitData: (event: GraphDataEvent) => void,\n) {\n const source = (args.source ?? 'both') as 'codegraph' | 'lens' | 'both';\n const fresh = await fetchMergedGraph(invoke, args.repoId, source);\n\n const cached = graphCache.get(args.repoId);\n const deltaSource: AdapterResult['source'] = source === 'lens' ? 'lens' : 'codegraph';\n const merged = cached\n ? merger.applyDelta(cached, { nodes: fresh.nodes, edges: fresh.edges, source: deltaSource, timestamp: fresh.metadata.timestamp })\n : fresh;\n cacheGraph(args.repoId, merged);\n\n emitUpdate({\n repoId: args.repoId,\n nodeCount: merged.metadata.nodeCount,\n edgeCount: merged.metadata.edgeCount,\n timestamp: merged.metadata.timestamp,\n });\n emitData({\n repoId: args.repoId,\n nodes: merged.nodes,\n edges: merged.edges,\n timestamp: merged.metadata.timestamp,\n });\n return merged as unknown as JsonValue;\n}\n\nexport function renderGraphSymbol(_args: unknown, value: unknown) {\n const v = value as { name?: string; file?: string; line?: number; category?: string; symbolId?: string } | null;\n if (!v) return [{ type: 'text' as const, text: 'Symbol not found.' }];\n return [{ type: 'text' as const, text: `${v.name ?? v.symbolId ?? '?'} (${v.category ?? 'unknown'}) @ ${v.file ?? '?'}:${v.line ?? '?'}` }];\n}\n\nexport async function executeGraphSymbol(args: { symbolId: string }, invoke: UpstreamInvoker) {\n const raw = await invoke('codegraph_query', { search: args.symbolId, limit: 1 });\n return pickBestMatch(raw, args.symbolId) as JsonValue;\n}\n\nexport function renderGraphImpact(_args: unknown, value: unknown) {\n const v = value as { affected?: string[]; depth?: number };\n const count = v.affected?.length ?? 0;\n const list = v.affected?.slice(0, 10).join(', ') ?? '';\n return [{ type: 'text' as const, text: `Impact: ${count} symbols affected (depth ${v.depth ?? 0})${list ? `\\n ${list}` : ''}` }];\n}\n\nexport async function executeGraphImpact(args: { symbolId: string }, invoke: UpstreamInvoker) {\n const raw = await invoke('codegraph_impact', { symbol: args.symbolId, depth: 2 });\n const normalized = normalizeImpact(raw);\n if (normalized) return normalized as JsonValue;\n const lens = await invoke('lens_impact', { symbolId: args.symbolId });\n return (lens ?? { affected: [], depth: 0 }) as JsonValue;\n}\n\n// ── Tool factory ────────────────────────────────────────────────────────\n\nexport const createGraphTools = (ctx: Context, options: { requestTimeout?: number } = {}) => {\n const invoke = createInvoke(ctx, options.requestTimeout);\n\n const emitUpdate = (event: GraphUpdatedEvent) => {\n ctx.emit('codegraph/graph/updated', event);\n };\n\n const emitData = (event: GraphDataEvent) => {\n ctx.emit('codegraph/graph/data', event);\n };\n\n const graphStatus = defineTool({\n name: 'graph_status',\n description: 'Check whether an interactive code graph is available for a repository.',\n parameters: {\n repoId: { type: 'string', required: true, description: 'Repository id.' },\n },\n output: {\n schema: { type: 'json' },\n render: renderGraphStatus,\n },\n execute: (args) => executeGraphStatus(args as { repoId: string }, invoke),\n });\n\n const graphData = defineTool({\n name: 'graph_data',\n description: 'Fetch the merged code relationship graph for a repository (calls + dependencies). Uses incremental delta merge on repeat calls.',\n parameters: {\n repoId: { type: 'string', required: true, description: 'Repository id.' },\n source: {\n type: 'string',\n enum: ['codegraph', 'lens', 'both'],\n description: 'Data source; defaults to both.',\n },\n },\n output: {\n schema: { type: 'json' },\n render: renderGraphData,\n },\n execute: (args) => executeGraphData(args as { repoId: string; source?: string }, invoke, emitUpdate, emitData),\n });\n\n const graphSymbol = defineTool({\n name: 'graph_symbol',\n description: 'Resolve the details (file path and line number) of one graph node by symbol id.',\n parameters: {\n symbolId: { type: 'string', required: true, description: 'Symbol id.' },\n },\n output: {\n schema: { type: 'json' },\n render: renderGraphSymbol,\n },\n execute: (args) => executeGraphSymbol(args as { symbolId: string }, invoke),\n });\n\n const graphImpact = defineTool({\n name: 'graph_impact',\n description: 'Analyze the impact of changing one symbol: which symbols are transitively affected.',\n parameters: {\n symbolId: { type: 'string', required: true, description: 'Symbol id to analyze.' },\n },\n output: {\n schema: { type: 'json' },\n render: renderGraphImpact,\n },\n execute: (args) => executeGraphImpact(args as { symbolId: string }, invoke),\n });\n\n return { graphStatus, graphData, graphSymbol, graphImpact };\n};\n\nexport { fetchMergedGraph, summarizeGraph };\nexport const makeRepo = (id: string): RepoId => makeRepoId(id);\n","export const PLUGIN_VERSION = '0.1.0';\n","export interface VisualizerConfig {\n dataSource: 'auto' | 'codegraph' | 'lens';\n requestTimeout: number;\n scanCacheTtl: number;\n scanCacheLimit: number;\n maxBodyBytes: number;\n prerequisiteRetryDelay: number;\n watchDebounce: number;\n maxNodes: number;\n}\n\nexport const DEFAULT_CONFIG: VisualizerConfig = {\n dataSource: 'auto',\n requestTimeout: 5000,\n scanCacheTtl: 30_000,\n scanCacheLimit: 4,\n maxBodyBytes: 1024 * 1024,\n prerequisiteRetryDelay: 3000,\n watchDebounce: 500,\n maxNodes: 10_000,\n};\n\nexport function resolveConfig(userConfig?: Partial<VisualizerConfig>): VisualizerConfig {\n const config: VisualizerConfig = { ...DEFAULT_CONFIG, ...userConfig };\n const errors: string[] = [];\n if (config.dataSource !== 'auto' && config.dataSource !== 'codegraph' && config.dataSource !== 'lens') {\n errors.push(`dataSource must be auto|codegraph|lens, got ${String(config.dataSource)}`);\n }\n const positiveFields: Array<[keyof VisualizerConfig, number]> = [\n ['requestTimeout', config.requestTimeout],\n ['scanCacheTtl', config.scanCacheTtl],\n ['scanCacheLimit', config.scanCacheLimit],\n ['maxBodyBytes', config.maxBodyBytes],\n ['prerequisiteRetryDelay', config.prerequisiteRetryDelay],\n ['watchDebounce', config.watchDebounce],\n ['maxNodes', config.maxNodes],\n ];\n for (const [field, value] of positiveFields) {\n if (!Number.isFinite(value) || value <= 0) {\n errors.push(`${field} must be a positive finite number, got ${String(value)}`);\n }\n }\n if (errors.length > 0) {\n throw new Error(`[dsh-codegraph-visualizer] invalid config: ${errors.join('; ')}`);\n }\n return config;\n}","import { normalize, isAbsolute } from 'node:path';\n\nlet allowedWorkspaceRoots: string[] = [];\n\nexport function setAllowedWorkspaceRoots(roots: string[]): void {\n allowedWorkspaceRoots = roots.map(r => normalize(r));\n}\n\nexport function isPathAllowed(path: string): boolean {\n if (!path || path === '.') return true;\n const normalized = normalize(path);\n if (!isAbsolute(normalized)) return false;\n if (normalized.includes('..')) return false;\n if (allowedWorkspaceRoots.length === 0) return false;\n return allowedWorkspaceRoots.some((root) => normalized === root || normalized.startsWith(root + '\\\\') || normalized.startsWith(root + '/'));\n}","import { spawnSync } from 'node:child_process';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { scoped } from '../shared/Logger.ts';\n\nconst log = scoped('host');\n\nexport interface ContextWithSessions {\n sessions?: { list?: () => Array<{ header?: { cwd?: string } }> };\n workspaceRegistry?: { list?: () => Array<{ path?: string }> };\n}\n\nexport function detectCodegraphCli(): boolean {\n try {\n const cmd = process.platform === 'win32' ? 'codegraph.cmd' : 'codegraph';\n const r = spawnSync(cmd, ['--version'], { encoding: 'utf8', timeout: 3000, shell: process.platform === 'win32' });\n return r.status === 0;\n } catch (e) {\n log.warn('detectCodegraphCli failed', e);\n return false;\n }\n}\n\nexport function checkPrerequisites(ctx: Context): { codegraph: boolean; lens: boolean } {\n try {\n const cg = ctx.tools.get('codegraph_status') ?? ctx.tools.get('codegraph_graph') ?? ctx.tools.get('codegraph_query');\n const lens = ctx.tools.get('lens_analyze');\n return { codegraph: !!cg || detectCodegraphCli(), lens: !!lens };\n } catch (e) {\n log.warn('checkPrerequisites failed', e);\n return { codegraph: detectCodegraphCli(), lens: false };\n }\n}\n\nexport function extractWorkspacePaths(ctx: Context): string[] {\n try {\n const wsr = (ctx as unknown as ContextWithSessions).workspaceRegistry;\n if (wsr?.list) {\n const workspaces = wsr.list();\n const paths = workspaces.map((w) => w.path).filter((p): p is string => !!p);\n if (paths.length > 0) return paths;\n }\n } catch (e) { log.warn('extractWorkspacePaths: workspaceRegistry failed', e); }\n try {\n const sessions = (ctx as unknown as ContextWithSessions).sessions;\n if (sessions?.list) {\n const all = sessions.list();\n const seen = new Set<string>();\n const paths: string[] = [];\n for (const session of all) {\n const cwd = session?.header?.cwd;\n if (cwd && !seen.has(cwd)) {\n seen.add(cwd);\n paths.push(cwd);\n }\n }\n if (paths.length > 0) return paths;\n }\n } catch (e) { log.warn('extractWorkspacePaths: sessions failed', e); }\n return [process.cwd()];\n}\n\nexport function findWorkspacePath(ctx: Context): string {\n try {\n const wsr = (ctx as unknown as ContextWithSessions).workspaceRegistry;\n if (wsr?.list) {\n const workspaces = wsr.list();\n if (workspaces.length > 0 && workspaces[0]?.path) {\n return workspaces[0].path;\n }\n }\n } catch (e) { log.warn('findWorkspacePath: workspaceRegistry failed', e); }\n try {\n const sessions = (ctx as unknown as ContextWithSessions).sessions;\n if (sessions?.list) {\n const all = sessions.list();\n for (const session of all) {\n const cwd = session?.header?.cwd;\n if (cwd) return cwd;\n }\n }\n } catch (e) { log.warn('findWorkspacePath: sessions failed', e); }\n return process.cwd();\n}","import type { Context } from '@deepseek-ai/cordis';\nimport { CallId } from '@deepseek-ai/dsh-llm';\nimport { scoped } from '../shared/Logger.ts';\nimport type { GraphData, GraphNode, GraphEdge, IncomingMessage, ServerResponse, IGraphVisualizerService } from '../types/index.ts';\nimport { fetchMergedGraph } from '../tools.ts';\nimport { isPathAllowed } from './security.ts';\nimport { findWorkspacePath, extractWorkspacePaths, checkPrerequisites } from './prerequisites.ts';\nimport type { VisualizerConfig } from './config.ts';\n\nconst log = scoped('host');\n\nexport interface RouteDeps {\n ctx: Context;\n config: VisualizerConfig;\n getLastGraphData: () => GraphData | null;\n setLastGraphData: (data: GraphData | null) => void;\n getLastInitResult: () => { success: boolean; path: string; message: string; timestamp: number } | null;\n setLastInitResult: (data: { success: boolean; path: string; message: string; timestamp: number } | null) => void;\n getScanCache: () => Map<string, { data: GraphData; timestamp: number }>;\n getScanInFlight: () => Promise<GraphData> | null;\n setScanInFlight: (p: Promise<GraphData> | null) => void;\n}\n\nexport function slimGraphData(data: GraphData, maxNodes: number): GraphData {\n const cap = maxNodes;\n const truncated = data.nodes.length > cap;\n const slimNodes = (truncated ? data.nodes.slice(0, cap) : data.nodes).map((n) => ({\n id: n.id,\n label: n.label,\n type: n.type,\n filePath: n.filePath,\n lineNumber: n.lineNumber,\n properties: n.properties?.exported === true ? { exported: true } : {},\n }));\n const allowedIds = new Set(slimNodes.map((n) => n.id));\n const slimEdges = data.edges\n .filter((e) => allowedIds.has(e.source) && allowedIds.has(e.target))\n .map((e) => ({\n id: e.id,\n source: e.source,\n target: e.target,\n type: e.type,\n properties: {},\n }));\n return {\n nodes: slimNodes as GraphNode[],\n edges: slimEdges as GraphEdge[],\n metadata: {\n ...data.metadata,\n truncated,\n nodeCount: slimNodes.length,\n edgeCount: slimEdges.length,\n totalNodeCount: data.metadata.totalNodeCount ?? data.nodes.length,\n totalEdgeCount: data.metadata.totalEdgeCount ?? data.edges.length,\n },\n };\n}\n\nexport function createInvokeUpstream(ctx: Context, config: VisualizerConfig) {\n return async (tool: string, args: Record<string, unknown>): Promise<unknown | null> => {\n try {\n const result = await ctx.tools.execute({\n callId: CallId(`codegraph:${tool}`),\n name: tool,\n arguments: args,\n signal: AbortSignal.timeout(config.requestTimeout),\n });\n if (result.isError) return null;\n return result.value ?? null;\n } catch (e) {\n log.warn('invokeUpstream failed', { tool, error: e });\n return null;\n }\n };\n}\n\nexport function registerService(deps: RouteDeps): void {\n const { ctx, config } = deps;\n const invokeUpstream = createInvokeUpstream(ctx, config);\n\n ctx.effect(() => {\n const service: IGraphVisualizerService = {\n getCurrentGraph: () => deps.getLastGraphData(),\n getGraphData: async (repoId: string) => {\n try {\n const raw = await fetchMergedGraph(invokeUpstream, repoId, 'both');\n return slimGraphData(raw, config.maxNodes);\n } catch { return null; }\n },\n getSymbolDetail: async (symbolId: string) => {\n return invokeUpstream('codegraph_query', { search: symbolId, limit: 1 });\n },\n getImpactAnalysis: async (symbolId: string) => {\n return invokeUpstream('codegraph_impact', { symbol: symbolId, depth: 2 });\n },\n onGraphUpdate: (callback: (data: GraphData) => void) => {\n return ctx.on('codegraph/graph/data', (event) => {\n callback({\n nodes: event.nodes as GraphNode[],\n edges: event.edges as GraphEdge[],\n metadata: {\n repoId: event.repoId as GraphData['metadata']['repoId'],\n timestamp: event.timestamp,\n nodeCount: event.nodes.length,\n edgeCount: event.edges.length,\n },\n });\n });\n },\n };\n return ctx.provide('graphVisualizer', service);\n }, 'codegraph: service registration');\n}\n\nfunction sendJson(res: ServerResponse, code: number, data: unknown): void {\n res.writeHead(code, { 'content-type': 'application/json' });\n res.end(JSON.stringify(data));\n}\n\nfunction readBody(req: IncomingMessage, maxBodyBytes: number): Promise<string> {\n return new Promise((resolve, reject) => {\n let body = '';\n let totalBytes = 0;\n req.on('data', (chunk?: Buffer) => {\n if (!chunk) return;\n totalBytes += chunk.length;\n if (totalBytes > maxBodyBytes) {\n reject(new Error('Request body too large'));\n return;\n }\n body += chunk.toString();\n });\n req.on('end', () => resolve(body));\n req.on('error', reject);\n });\n}\n\nfunction parseJsonBody(body: string): Record<string, unknown> {\n const parsed = JSON.parse(body || '{}');\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('Invalid JSON body: expected object');\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction extractStringField(obj: Record<string, unknown>, field: string): string | undefined {\n const v = obj[field];\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction extractBooleanField(obj: Record<string, unknown>, field: string): boolean | undefined {\n const v = obj[field];\n return typeof v === 'boolean' ? v : undefined;\n}\n\nexport function registerRoutes(deps: RouteDeps): void {\n const { ctx, config } = deps;\n const invokeUpstream = createInvokeUpstream(ctx, config);\n\n // GET /api/codegraph/status\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/status',\n handler: (_req: IncomingMessage, res: ServerResponse) => {\n const status = checkPrerequisites(ctx);\n sendJson(res, 200, { codegraph: status.codegraph, lens: status.lens });\n },\n }), 'codegraph: status route');\n\n // GET /api/codegraph/workspace\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/workspace',\n handler: (_req: IncomingMessage, res: ServerResponse) => {\n const current = findWorkspacePath(ctx);\n const list = extractWorkspacePaths(ctx);\n sendJson(res, 200, { path: current, list });\n },\n }), 'codegraph: workspace route');\n\n // GET /api/codegraph/data\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/data',\n handler: (req: IncomingMessage, res: ServerResponse) => {\n const ifNoneMatch = req.headers['if-none-match'];\n const lastGraphData = deps.getLastGraphData();\n if (ifNoneMatch && lastGraphData) {\n const clientTimestamp = parseInt(String(ifNoneMatch), 10);\n if (clientTimestamp >= lastGraphData.metadata.timestamp) {\n res.writeHead(304, { 'etag': String(lastGraphData.metadata.timestamp) });\n res.end();\n return;\n }\n }\n if (lastGraphData) {\n res.writeHead(200, {\n 'content-type': 'application/json',\n 'etag': String(lastGraphData.metadata.timestamp),\n });\n res.end(JSON.stringify(lastGraphData));\n } else {\n sendJson(res, 200, { nodes: [], edges: [], metadata: { repoId: null, timestamp: 0, nodeCount: 0, edgeCount: 0 } });\n }\n },\n }), 'codegraph: data route');\n\n // POST /api/codegraph/scan\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/scan',\n handler: async (req: IncomingMessage, res: ServerResponse) => {\n try {\n const body = await readBody(req, config.maxBodyBytes);\n const parsed = parseJsonBody(body);\n const path = extractStringField(parsed, 'path');\n if (path && path !== '.' && !isPathAllowed(path)) {\n sendJson(res, 403, { success: false, nodes: [], edges: [], metadata: { repoId: null, timestamp: 0, nodeCount: 0, edgeCount: 0 } });\n return;\n }\n const scanPath = path && path !== '.' ? path : findWorkspacePath(ctx);\n const repoId = scanPath || `workspace-${Date.now()}`;\n const scanCache = deps.getScanCache();\n\n const cached = scanCache.get(scanPath);\n if (cached && Date.now() - cached.timestamp < config.scanCacheTtl) {\n deps.setLastGraphData(cached.data);\n sendJson(res, 200, { success: true, ...cached.data });\n return;\n }\n\n const inFlight = deps.getScanInFlight();\n if (inFlight) {\n const data = await inFlight;\n sendJson(res, 200, { success: true, ...data });\n return;\n }\n\n const scanPromise = fetchMergedGraph(invokeUpstream, repoId, 'both');\n deps.setScanInFlight(scanPromise);\n try {\n const raw = await scanPromise;\n deps.setScanInFlight(null);\n const data = slimGraphData(raw, config.maxNodes);\n deps.setLastGraphData(data);\n scanCache.set(scanPath, { data, timestamp: Date.now() });\n if (scanCache.size > config.scanCacheLimit) {\n const oldest = scanCache.keys().next().value;\n if (oldest !== undefined) scanCache.delete(oldest);\n }\n ctx.emit('codegraph/graph/updated', {\n repoId,\n nodeCount: data.metadata.nodeCount,\n edgeCount: data.metadata.edgeCount,\n timestamp: data.metadata.timestamp,\n });\n ctx.emit('codegraph/graph/data', {\n repoId,\n nodes: data.nodes,\n edges: data.edges,\n timestamp: data.metadata.timestamp,\n });\n log.info('scan completed', { repoId, nodes: data.metadata.nodeCount, edges: data.metadata.edgeCount });\n sendJson(res, 200, { success: true, ...data });\n } catch (e) {\n deps.setScanInFlight(null);\n throw e;\n }\n } catch (e) {\n log.error('scan failed', e);\n sendJson(res, 500, { success: false, nodes: [], edges: [], metadata: { repoId: null, timestamp: 0, nodeCount: 0, edgeCount: 0 } });\n }\n },\n }), 'codegraph: scan route');\n\n // POST /api/codegraph/init\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/init',\n handler: async (req: IncomingMessage, res: ServerResponse) => {\n try {\n const body = await readBody(req, config.maxBodyBytes);\n const parsed = parseJsonBody(body);\n const path = extractStringField(parsed, 'path');\n if (path && path !== '.' && !isPathAllowed(path)) {\n sendJson(res, 403, { success: false, path: '', message: 'Path not allowed', timestamp: Date.now() });\n return;\n }\n const initPath = path && path !== '.' ? path : findWorkspacePath(ctx);\n log.info('init requested', { path: initPath });\n const result = await invokeUpstream('codegraph_init', { path: initPath, force: true });\n const success = result !== null;\n const initResult = {\n success,\n path: initPath,\n message: success ? 'Graph initialized successfully' : 'Initialization failed — is dsh-codegraph installed?',\n timestamp: Date.now(),\n };\n deps.setLastInitResult(initResult);\n ctx.emit('codegraph/graph/init-result', initResult);\n if (success) {\n const repoId = initPath || `workspace-${Date.now()}`;\n const data = await fetchMergedGraph(invokeUpstream, repoId, 'both');\n deps.setLastGraphData(data);\n ctx.emit('codegraph/graph/data', {\n repoId,\n nodes: data.nodes,\n edges: data.edges,\n timestamp: data.metadata.timestamp,\n });\n }\n sendJson(res, 200, initResult);\n } catch (e) {\n const errorResult = {\n success: false,\n path: '',\n message: e instanceof Error ? e.message : String(e),\n timestamp: Date.now(),\n };\n deps.setLastInitResult(errorResult);\n sendJson(res, 500, errorResult);\n }\n },\n }), 'codegraph: init route');\n\n // POST /api/codegraph/watch\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: '/api/codegraph/watch',\n handler: async (req: IncomingMessage, res: ServerResponse) => {\n try {\n const body = await readBody(req, config.maxBodyBytes);\n const parsed = parseJsonBody(body);\n const enabled = extractBooleanField(parsed, 'enabled');\n const path = extractStringField(parsed, 'path');\n if (path && path !== '.' && !isPathAllowed(path)) {\n sendJson(res, 403, { success: false, message: 'Path not allowed' });\n return;\n }\n const watchPath = path && path !== '.' ? path : findWorkspacePath(ctx);\n ctx.emit('codegraph/watch/toggle', { enabled: !!enabled, path: watchPath, timestamp: Date.now() });\n sendJson(res, 200, { success: true });\n } catch (e) {\n sendJson(res, 500, { success: false, message: e instanceof Error ? e.message : String(e) });\n }\n },\n }), 'codegraph: watch route');\n}","import { watch } from 'node:fs';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { scoped } from '../shared/Logger.ts';\nimport { fetchMergedGraph } from '../tools.ts';\nimport type { VisualizerConfig } from './config.ts';\n\nconst log = scoped('host');\n\nlet watchTimer: ReturnType<typeof setTimeout> | null = null;\nlet activeWatcher: { close: () => void } | null = null;\n\nfunction closeActiveWatcher(): void {\n if (activeWatcher) {\n try { activeWatcher.close(); } catch { /* best-effort */ }\n activeWatcher = null;\n }\n if (watchTimer) { clearTimeout(watchTimer); watchTimer = null; }\n}\n\nexport function registerWatcher(ctx: Context, config: VisualizerConfig, invokeUpstream: (tool: string, args: Record<string, unknown>) => Promise<unknown | null>): void {\n const scanAndPush = async (path: string) => {\n log.info('scan requested', { path });\n try {\n const repoId = path || `workspace-${Date.now()}`;\n const data = await fetchMergedGraph(invokeUpstream, repoId, 'both');\n ctx.emit('codegraph/graph/updated', {\n repoId,\n nodeCount: data.metadata.nodeCount,\n edgeCount: data.metadata.edgeCount,\n timestamp: data.metadata.timestamp,\n });\n ctx.emit('codegraph/graph/data', {\n repoId,\n nodes: data.nodes,\n edges: data.edges,\n timestamp: data.metadata.timestamp,\n });\n log.info('scan completed', { repoId, nodes: data.metadata.nodeCount, edges: data.metadata.edgeCount });\n } catch (e) {\n log.error('scan failed', e);\n }\n };\n\n ctx.effect(() => {\n const dispose = ctx.on('codegraph/watch/toggle', (event) => {\n closeActiveWatcher();\n\n if (!event.enabled) {\n log.info('watch disabled');\n return;\n }\n\n log.info('watch enabled', { path: event.path });\n try {\n activeWatcher = watch(event.path, { recursive: true }, (_eventType: string, filename: string | null) => {\n if (filename && filename.includes('.codegraph')) return;\n if (filename && filename.includes('node_modules')) return;\n if (filename && filename.includes('.git')) return;\n\n if (watchTimer) clearTimeout(watchTimer);\n watchTimer = setTimeout(() => {\n watchTimer = null;\n log.info('file changed, syncing + re-scanning', { filename });\n invokeUpstream('codegraph_sync', { path: event.path })\n .then(() => scanAndPush(event.path))\n .catch((e) => log.error('watch re-scan failed', e));\n }, config.watchDebounce);\n });\n } catch (e) {\n log.error('watch setup failed', e);\n }\n });\n return () => {\n dispose();\n closeActiveWatcher();\n };\n }, 'codegraph: watch toggle listener');\n}\n\nexport function registerEventListeners(ctx: Context, invokeUpstream: (tool: string, args: Record<string, unknown>) => Promise<unknown | null>): void {\n const scanAndPush = async (path: string) => {\n log.info('scan requested', { path });\n try {\n const repoId = path || `workspace-${Date.now()}`;\n const data = await fetchMergedGraph(invokeUpstream, repoId, 'both');\n ctx.emit('codegraph/graph/updated', {\n repoId,\n nodeCount: data.metadata.nodeCount,\n edgeCount: data.metadata.edgeCount,\n timestamp: data.metadata.timestamp,\n });\n ctx.emit('codegraph/graph/data', {\n repoId,\n nodes: data.nodes,\n edges: data.edges,\n timestamp: data.metadata.timestamp,\n });\n log.info('scan completed', { repoId, nodes: data.metadata.nodeCount, edges: data.metadata.edgeCount });\n } catch (e) {\n log.error('scan failed', e);\n }\n };\n\n ctx.effect(() => ctx.on('codegraph/repo/imported', (event) => {\n ctx.emit('codegraph/graph/updated', { repoId: event.repoId, nodeCount: 0, edgeCount: 0, timestamp: event.timestamp });\n }), 'codegraph: repo imported listener');\n\n ctx.effect(() => ctx.on('codegraph/repo/scanned', (event) => {\n ctx.emit('codegraph/graph/updated', { repoId: event.repoId, nodeCount: 0, edgeCount: 0, timestamp: event.timestamp });\n }), 'codegraph: repo scanned listener');\n\n ctx.effect(() => ctx.on('codegraph/repo/request-scan', async (event) => {\n await scanAndPush(event.path);\n }), 'codegraph: repo request-scan listener');\n\n ctx.effect(() => ctx.on('codegraph/graph/init', async (event) => {\n log.info('init requested', { path: event.path });\n try {\n const result = await invokeUpstream('codegraph_init', { path: event.path, force: true });\n const success = result !== null;\n ctx.emit('codegraph/graph/init-result', {\n success,\n path: event.path,\n message: success ? 'Graph initialized successfully' : 'Initialization failed — is dsh-codegraph installed?',\n timestamp: Date.now(),\n });\n if (success) {\n await scanAndPush(event.path);\n }\n } catch (e) {\n ctx.emit('codegraph/graph/init-result', {\n success: false,\n path: event.path,\n message: e instanceof Error ? e.message : String(e),\n timestamp: Date.now(),\n });\n }\n }), 'codegraph: graph init listener');\n}","import type { Context } from '@deepseek-ai/cordis';\nimport { createGraphTools } from './tools.ts';\nimport { scoped } from './shared/Logger.ts';\nimport type { GraphData } from './types/index.ts';\nimport { PLUGIN_VERSION } from './generated/version.ts';\nimport { resolveConfig } from './host/config.ts';\nimport type { VisualizerConfig } from './host/config.ts';\nimport { setAllowedWorkspaceRoots } from './host/security.ts';\nimport { extractWorkspacePaths, checkPrerequisites } from './host/prerequisites.ts';\nimport { createInvokeUpstream, registerRoutes, registerService } from './host/routes.ts';\nimport { registerWatcher, registerEventListeners } from './host/watcher.ts';\n\nexport { PLUGIN_VERSION };\nexport { resolveConfig, DEFAULT_CONFIG } from './host/config.ts';\nexport type { VisualizerConfig } from './host/config.ts';\nexport { isPathAllowed, setAllowedWorkspaceRoots } from './host/security.ts';\n\nconst log = scoped('host');\n\nexport const name = 'dsh-codegraph-visualizer';\nexport const inject = ['tools', 'webServer', 'sessions', 'workspaceRegistry'];\n\nexport function apply(ctx: Context, userConfig?: Partial<VisualizerConfig>) {\n const config = resolveConfig(userConfig);\n setAllowedWorkspaceRoots(extractWorkspacePaths(ctx));\n\n const { graphStatus, graphData, graphSymbol, graphImpact } = createGraphTools(ctx, { requestTimeout: config.requestTimeout });\n\n ctx.effect(() => {\n const d1 = ctx.tools.register(graphStatus);\n const d2 = ctx.tools.register(graphData);\n const d3 = ctx.tools.register(graphSymbol);\n const d4 = ctx.tools.register(graphImpact);\n return () => { d1(); d2(); d3(); d4(); };\n }, 'codegraph: tool registrations');\n\n let lastGraphData: GraphData | null = null;\n let lastInitResult: { success: boolean; path: string; message: string; timestamp: number } | null = null;\n let scanInFlight: Promise<GraphData> | null = null;\n const scanCache = new Map<string, { data: GraphData; timestamp: number }>();\n\n const routeDeps = {\n ctx,\n config,\n getLastGraphData: () => lastGraphData,\n setLastGraphData: (data: GraphData | null) => { lastGraphData = data; },\n getLastInitResult: () => lastInitResult,\n setLastInitResult: (data: { success: boolean; path: string; message: string; timestamp: number } | null) => { lastInitResult = data; },\n getScanCache: () => scanCache,\n getScanInFlight: () => scanInFlight,\n setScanInFlight: (p: Promise<GraphData> | null) => { scanInFlight = p; },\n };\n\n registerService(routeDeps);\n registerRoutes(routeDeps);\n\n const invokeUpstream = createInvokeUpstream(ctx, config);\n\n const emitPrereqStatus = () => {\n const status = checkPrerequisites(ctx);\n ctx.emit('codegraph/prerequisite/status', {\n codegraph: status.codegraph,\n lens: status.lens,\n timestamp: Date.now(),\n });\n log.info('prerequisite status', status);\n };\n emitPrereqStatus();\n const prereqTimer = setTimeout(emitPrereqStatus, config.prerequisiteRetryDelay);\n ctx.effect(() => () => clearTimeout(prereqTimer), 'codegraph: prereq re-check timer');\n\n ctx.effect(() => ctx.on('codegraph/prerequisite/request', () => {\n emitPrereqStatus();\n }), 'codegraph: prerequisite request listener');\n\n registerEventListeners(ctx, invokeUpstream);\n registerWatcher(ctx, config, invokeUpstream);\n}\n"],"x_google_ignoreList":[0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