@inspecto-dev/plugin 0.3.10 → 0.3.11
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/dist/astro.cjs +210 -84
- package/dist/astro.cjs.map +1 -1
- package/dist/astro.js +180 -53
- package/dist/astro.js.map +1 -1
- package/dist/index.cjs +210 -84
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +180 -53
- package/dist/index.js.map +1 -1
- package/dist/legacy/rspack/index.cjs +210 -84
- package/dist/legacy/rspack/index.cjs.map +1 -1
- package/dist/legacy/rspack/index.js +180 -53
- package/dist/legacy/rspack/index.js.map +1 -1
- package/dist/legacy/webpack4/index.cjs +210 -84
- package/dist/legacy/webpack4/index.cjs.map +1 -1
- package/dist/legacy/webpack4/index.js +180 -53
- package/dist/legacy/webpack4/index.js.map +1 -1
- package/dist/rollup.cjs +210 -84
- package/dist/rollup.cjs.map +1 -1
- package/dist/rollup.js +180 -53
- package/dist/rollup.js.map +1 -1
- package/dist/rspack.cjs +210 -84
- package/dist/rspack.cjs.map +1 -1
- package/dist/rspack.js +180 -53
- package/dist/rspack.js.map +1 -1
- package/dist/vite.cjs +210 -84
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.js +180 -53
- package/dist/vite.js.map +1 -1
- package/dist/webpack.cjs +210 -84
- package/dist/webpack.cjs.map +1 -1
- package/dist/webpack.js +180 -53
- package/dist/webpack.js.map +1 -1
- package/package.json +2 -2
package/dist/rollup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/transform/utils.ts","../src/transform/index.ts","../src/transform/transform-jsx.ts","../src/transform/transform-vue.ts","../src/transform/transform-svelte.ts","../src/transform/transform-astro.ts","../../../node_modules/.pnpm/@astrojs+compiler@3.0.1/node_modules/@astrojs/compiler/dist/chunk-W5DTLHV4.js","../../../node_modules/.pnpm/@astrojs+compiler@3.0.1/node_modules/@astrojs/compiler/dist/node/sync.js","../src/server/index.ts","../src/server/snippet.ts","../src/config.ts","../src/utils/logger.ts","../src/server/dispatch-transport.ts","../src/server/dispatch-runtime.ts","../src/server/path-guards.ts","../src/server/session-store.ts","../src/server/annotation-dispatch.ts","../src/server/client-config.ts","../src/server/open-file.ts","../src/server/project-root.ts","../src/server/server-url.ts","../src/injectors/utils.ts","../src/injectors/webpack.ts","../src/injectors/rspack.ts","../src/injectors/vite.ts"],"sourcesContent":["import { createUnplugin } from 'unplugin'\nimport type { UnpluginOptions } from '@inspecto-dev/types'\nimport { extractTransformFilePath, shouldTransform } from './transform/utils.js'\nimport { transformRouter, transformJsx } from './transform/index.js'\nimport { startServer, serverState } from './server/index.js'\nimport { resolvePublicServerUrl } from './server/server-url.js'\nimport { resolveClientModule } from './injectors/utils.js'\nimport { injectWebpack } from './injectors/webpack.js'\nimport { injectRspack } from './injectors/rspack.js'\nimport { setGlobalLogLevel } from './config.js'\nimport { createLogger } from './utils/logger.js'\nimport {\n getViteVirtualModuleScript,\n VITE_VIRTUAL_MODULE_ID,\n VITE_VIRTUAL_IMPORT_ID,\n} from './injectors/vite.js'\n\nimport type { ViteDevServer } from 'vite'\n\nexport type { UnpluginOptions }\n\nconst DEFAULT_OPTIONS: Required<UnpluginOptions> = {\n include: [],\n exclude: [],\n escapeTags: [],\n pathType: 'absolute',\n attributeName: 'data-inspecto',\n logLevel: 'warn',\n}\n\nconst DEFAULT_PORT = 5678\n\nconst InspectoPlugin = createUnplugin<UnpluginOptions | undefined>((userOptions = {}) => {\n const options: Required<UnpluginOptions> = {\n ...DEFAULT_OPTIONS,\n ...userOptions,\n }\n\n // Sync global log level based on user config\n setGlobalLogLevel(options.logLevel)\n const pluginLogger = createLogger('inspecto:plugin', { logLevel: options.logLevel })\n\n // Skip everything in production\n const isProduction = process.env['NODE_ENV'] === 'production'\n\n let projectRoot = process.cwd()\n let serverPort: number | null = null\n\n // Helper to ensure server is started\n const ensureServer = async () => {\n if (serverPort === null) {\n serverPort = await startServer()\n }\n return serverPort\n }\n\n const getPublicServerUrl = (port: number) =>\n resolvePublicServerUrl({\n cwd: serverState.cwd || process.cwd(),\n configRoot: serverState.configRoot || projectRoot,\n port,\n })\n\n return {\n name: 'inspecto-overlay',\n enforce: 'pre',\n\n buildStart() {\n if (isProduction) return\n projectRoot = serverState.cwd || process.cwd()\n\n // For pure bundlers (Rollup, Esbuild) that don't have devServer hooks\n // we need to ensure the server starts early enough.\n ensureServer().catch(err => pluginLogger.error('Failed to start server:', err))\n },\n\n buildEnd() {\n // Server cleanup is handled by process exit (server is unref'd, port file\n // removed via process.once('exit')). Calling stopServer() here would break\n // esbuild watch mode (which fires buildEnd after every incremental rebuild)\n // and is unnecessary for Vite/Rspack which manage their own lifecycles.\n },\n\n webpack: compiler => {\n if (isProduction) return\n injectWebpack(compiler, ensureServer, getPublicServerUrl, resolveClientModule)\n },\n\n rspack: compiler => {\n if (isProduction) return\n injectRspack(compiler, ensureServer, resolveClientModule)\n },\n\n vite: {\n config(config) {\n if (isProduction) return config\n return {\n ...config,\n define: {\n ...config.define,\n __AI_INSPECTOR_PORT__: JSON.stringify(DEFAULT_PORT), // Placeholder, rewritten in configureServer\n },\n }\n },\n\n resolveId(id) {\n if (id === 'virtual:inspecto-client') {\n return VITE_VIRTUAL_MODULE_ID\n }\n return null\n },\n\n load(id) {\n if (id === VITE_VIRTUAL_MODULE_ID) {\n // serverPort is guaranteed to be set by the time Vite requests this module\n // (configureServer awaits ensureServer before the dev server accepts requests)\n return getViteVirtualModuleScript(\n serverPort ?? DEFAULT_PORT,\n getPublicServerUrl(serverPort ?? DEFAULT_PORT),\n )\n }\n return null\n },\n\n async configureServer(server: ViteDevServer) {\n if (isProduction) return\n const port = await ensureServer()\n if (!server.config.define) {\n ;(server.config as any).define = {}\n }\n ;(server.config as any).define['__AI_INSPECTOR_PORT__'] = JSON.stringify(port)\n // Invalidate the virtual module so load() re-runs with the correct port\n // (guards against the race where load() was called before configureServer resolved)\n const mod = server.moduleGraph.getModuleById(VITE_VIRTUAL_MODULE_ID)\n if (mod) server.moduleGraph.invalidateModule(mod)\n },\n\n transformIndexHtml(html) {\n if (isProduction || !serverPort) return html\n return {\n html,\n tags: [\n {\n tag: 'script',\n attrs: { type: 'module' },\n children: `import '${VITE_VIRTUAL_IMPORT_ID}';`,\n },\n ],\n }\n },\n },\n\n transformInclude(id) {\n if (isProduction || !id) return false\n return shouldTransform(id, options)\n },\n\n transform(code, id) {\n if (isProduction || !id) return null\n\n const { filePath } = extractTransformFilePath(id)\n\n const result = transformRouter({\n filePath,\n source: code,\n projectRoot,\n pluginOptions: options,\n })\n\n if (!result || !result.changed) return null\n\n return {\n code: result.code,\n map: result.map,\n }\n },\n }\n})\n\nexport const unplugin = InspectoPlugin\nexport const vitePlugin = InspectoPlugin.vite\nexport const webpackPlugin: (options?: UnpluginOptions) => any = InspectoPlugin.webpack\nexport const rspackPlugin = InspectoPlugin.rspack\nexport const rollupPlugin = InspectoPlugin.rollup\nexport const esbuildPlugin = InspectoPlugin.esbuild\nexport { transformJsx, transformRouter }\nexport { transformAstro } from './transform/transform-astro.js'\nexport default InspectoPlugin\n","import type { UnpluginOptions } from '@inspecto-dev/types'\nimport type MagicString from 'magic-string'\n\nexport interface TransformResult {\n code: string\n map: ReturnType<MagicString['generateMap']> | null\n changed: boolean\n}\n\nexport interface NormalizedTransformTarget {\n requestId: string\n filePath: string\n wrapped: boolean\n}\n\n/** Default tags whose JSX elements should NOT receive data-inspecto attributes */\nexport const DEFAULT_ESCAPE_TAGS = new Set([\n 'template',\n 'script',\n 'style',\n // React special elements\n 'Fragment',\n 'React.Fragment',\n 'StrictMode',\n 'React.StrictMode',\n 'Suspense',\n 'React.Suspense',\n 'Profiler',\n 'React.Profiler',\n // React transitions\n 'Transition',\n 'TransitionGroup',\n // Vue built-in components\n 'KeepAlive',\n 'Teleport',\n 'Suspense',\n // Vue router built-ins\n 'RouterView',\n 'RouterLink',\n 'NuxtPage',\n 'NuxtLink',\n])\n\n/** File extensions that contain JSX/TSX syntax */\nexport const JSX_EXTENSIONS = new Set(['.jsx', '.tsx', '.js', '.ts', '.mjs', '.mts'])\n\nfunction normalizeWebpackModuleRequest(id: string): string {\n return id.replace(/!+$/, '').replace(/^\\((?:app-pages-browser|rsc|ssr)\\)\\/\\.\\//, '')\n}\n\nfunction extractNextModuleRequest(id: string): string | undefined {\n if (!id.includes('next-flight-client-entry-loader.js?')) {\n return undefined\n }\n\n const queryIndex = id.indexOf('?')\n if (queryIndex === -1) {\n return undefined\n }\n\n const params = new URLSearchParams(id.slice(queryIndex + 1).replace(/!+$/, ''))\n for (const entry of params.getAll('modules')) {\n try {\n const parsed = JSON.parse(entry) as { request?: unknown }\n if (typeof parsed.request === 'string' && parsed.request.length > 0) {\n return parsed.request\n }\n } catch {\n continue\n }\n }\n\n return undefined\n}\n\nexport function extractTransformFilePath(requestId: string): NormalizedTransformTarget {\n const normalizedRequestId = normalizeWebpackModuleRequest(requestId)\n const nextModuleRequest = extractNextModuleRequest(normalizedRequestId)\n if (nextModuleRequest) {\n return {\n requestId,\n filePath: nextModuleRequest,\n wrapped: true,\n }\n }\n\n const lastLoaderSeparator = normalizedRequestId.lastIndexOf('!')\n const resourceRequest =\n lastLoaderSeparator >= 0\n ? normalizedRequestId.slice(lastLoaderSeparator + 1)\n : normalizedRequestId\n const queryIndex = resourceRequest.indexOf('?')\n const filePath = queryIndex >= 0 ? resourceRequest.slice(0, queryIndex) : resourceRequest\n\n return {\n requestId,\n filePath,\n wrapped: filePath !== requestId,\n }\n}\n\n/**\n * Determine if a file should be transformed.\n * Always skips node_modules and dist directories.\n */\nexport function shouldTransform(filePath: string, _options: Required<UnpluginOptions>): boolean {\n const resolvedFilePath = extractTransformFilePath(filePath).filePath\n\n // Never transform in production\n if (process.env['NODE_ENV'] === 'production') return false\n\n // Skip node_modules always\n if (resolvedFilePath.includes('node_modules')) return false\n\n // Skip virtual modules\n if (resolvedFilePath.startsWith('\\x00')) return false\n\n // Skip dist/build directories\n if (/[/\\\\](dist|build|\\.next|\\.nuxt)[/\\\\]/.test(resolvedFilePath)) return false\n\n // Skip non-code files (like .html, .css)\n const ext = resolvedFilePath.split('.').pop()?.toLowerCase()\n if (ext && !['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts', 'vue', 'svelte', 'astro'].includes(ext)) {\n return false\n }\n\n // Check user-defined exclude patterns\n // (picomatch integration — see index.ts for how options.exclude is applied)\n\n return true\n}\n\n/**\n * Build the escape tags set from user options merged with defaults.\n */\nexport function buildEscapeTagsSet(escapeTags?: string[]): Set<string> {\n const merged = new Set(DEFAULT_ESCAPE_TAGS)\n if (escapeTags) {\n for (const tag of escapeTags) {\n merged.add(tag)\n }\n }\n return merged\n}\n\n/**\n * Format a source location value for the data-inspecto attribute.\n * Format: \"filepath:line:column\"\n */\nexport function formatAttrValue(file: string, line: number, column: number): string {\n return `${file}:${line}:${column}`\n}\n","import path from 'node:path'\nimport type { UnpluginOptions } from '@inspecto-dev/types'\nimport { transformJsx } from './transform-jsx.js'\nimport { transformVue } from './transform-vue.js'\nimport { transformSvelte } from './transform-svelte.js'\nimport { transformAstro } from './transform-astro.js'\nimport { JSX_EXTENSIONS, type TransformResult } from './utils.js'\n\nexport interface RouterOptions {\n filePath: string\n source: string\n projectRoot: string\n pluginOptions: Required<UnpluginOptions>\n}\n\n/**\n * Route a file to the appropriate transform based on extension.\n * Returns null if no transform applies.\n */\nexport function transformRouter(options: RouterOptions): TransformResult | null {\n const { filePath, source, projectRoot, pluginOptions } = options\n const ext = path.extname(filePath).toLowerCase()\n\n if (JSX_EXTENSIONS.has(ext)) {\n return transformJsx({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Vue SFC ──────────────────────────────────────────────────────────────\n if (ext === '.vue') {\n return transformVue({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Svelte ───────────────────────────────────────────────────────────────\n if (ext === '.svelte') {\n return transformSvelte({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Astro ────────────────────────────────────────────────────────────────\n if (ext === '.astro') {\n return transformAstro({\n filePath,\n source,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n return null\n}\n// Export transforms for testing\nexport { transformJsx, transformVue, transformSvelte, transformAstro }\n","import * as parser from '@babel/parser'\nimport traverse_ from '@babel/traverse'\n// Support both ESM default and CommonJS module.exports\nconst traverse =\n typeof traverse_ === 'function' ? traverse_ : (traverse_ as any).default || traverse_\nimport type { NodePath } from '@babel/traverse'\nimport type { JSXOpeningElement } from '@babel/types'\nimport MagicString from 'magic-string'\nimport path from 'node:path'\nimport type { PathType } from '@inspecto-dev/types'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformJsxOptions {\n filePath: string\n source: string\n projectRoot: string\n escapeTags?: string[]\n pathType?: PathType\n attributeName?: string\n}\n\n/**\n * Transform JSX/TSX source code by injecting data-inspecto attributes.\n */\nexport function transformJsx(options: TransformJsxOptions): TransformResult {\n const {\n filePath,\n source,\n projectRoot,\n escapeTags,\n pathType = 'absolute',\n attributeName = 'data-inspecto',\n } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // Resolve the file path based on pathType config\n const resolvedPath =\n pathType === 'absolute'\n ? path.resolve(filePath)\n : path.relative(projectRoot, path.resolve(filePath))\n\n // Normalize path separators on Windows\n const normalizedPath = resolvedPath.replace(/\\\\/g, '/')\n\n let ast: ReturnType<typeof parser.parse>\n try {\n ast = parser.parse(source, {\n sourceType: 'module',\n plugins: [\n 'jsx',\n 'typescript',\n 'decorators-legacy',\n 'classProperties',\n 'optionalChaining',\n 'nullishCoalescingOperator',\n 'importMeta',\n ],\n errorRecovery: true,\n })\n } catch {\n // If parsing fails, return source unchanged\n return { code: source, map: null, changed: false }\n }\n\n const ms = new MagicString(source)\n let changed = false\n\n traverse(ast, {\n JSXOpeningElement(nodePath: NodePath<JSXOpeningElement>) {\n const node = nodePath.node\n\n // Skip elements that already have the attribute\n const alreadyHasAttr = node.attributes.some(\n attr =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === attributeName,\n )\n if (alreadyHasAttr) return\n\n // Get element tag name\n const nameNode = node.name\n let tagName: string\n if (nameNode.type === 'JSXIdentifier') {\n tagName = nameNode.name\n } else if (nameNode.type === 'JSXMemberExpression') {\n const objName = nameNode.object.type === 'JSXIdentifier' ? nameNode.object.name : ''\n const propName = nameNode.property.type === 'JSXIdentifier' ? nameNode.property.name : ''\n tagName = objName && propName ? `${objName}.${propName}` : objName\n } else {\n tagName = ''\n }\n\n // Skip escaped tags\n if (escapeTagsSet.has(tagName)) return\n\n // Get position from AST location\n const loc = node.loc\n if (!loc) return\n\n const { line, column } = loc.start\n // Babel uses 0-based columns, convert to 1-based\n const attrValue = formatAttrValue(normalizedPath, line, column + 1)\n\n // Determine the best insertion position for the attribute\n // When a JSX element has type arguments (e.g. <Component<string> />),\n // inserting after `node.name.end` might inject inside the generic bracket `<`.\n // The safest place to insert is right before the first attribute,\n // or right before the closing slash/bracket if there are no attributes.\n let insertPos: number | null | undefined = null\n if (node.attributes && node.attributes.length > 0) {\n const firstAttr = node.attributes[0]\n if (firstAttr && firstAttr.start != null) {\n insertPos = firstAttr.start\n }\n }\n\n if (insertPos == null) {\n // Find the start of the closing bracket or self-closing slash\n // We know node.end is the index right after the '>'\n // So we look backwards. But Babel AST doesn't give us exact token positions\n // for the closing tag easily.\n // For a safe fallback, we use node.typeParameters?.end || node.name.end\n if (node.typeParameters && node.typeParameters.end != null) {\n insertPos = node.typeParameters.end\n } else if (node.name.end != null) {\n insertPos = node.name.end\n }\n }\n\n if (insertPos == null) return\n\n ms.appendLeft(\n insertPos,\n ` ${attributeName}=\"${attrValue}\"${node.attributes && node.attributes.length > 0 ? '' : ' '}`,\n )\n changed = true\n },\n })\n\n if (!changed) {\n return { code: source, map: null, changed: false }\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true, source: filePath }),\n changed: true,\n }\n}\n","import * as vueCompiler from '@vue/compiler-dom'\nimport { parse as parseSFC } from '@vue/compiler-sfc'\nimport type { ElementNode, AttributeNode } from '@vue/compiler-core'\nimport { NodeTypes } from '@vue/compiler-core'\nimport MagicString from 'magic-string'\nimport path from 'node:path'\nimport type { PathType } from '@inspecto-dev/types'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformVueOptions {\n filePath: string\n source: string\n projectRoot: string\n escapeTags?: string[]\n pathType?: PathType\n attributeName?: string\n}\n\n/**\n * Transform Vue SFC source by injecting data-inspecto attributes\n * into template elements.\n *\n * Strategy:\n * 1. Locate the <template> block in the SFC source\n * 2. Parse only the template block with @vue/compiler-dom\n * 3. Walk ElementNode nodes in the AST\n * 4. For each eligible element, inject the attribute using MagicString\n * at the exact offset within the original source\n */\nexport function transformVue(options: TransformVueOptions): TransformResult {\n const {\n filePath,\n source,\n projectRoot,\n escapeTags,\n pathType = 'absolute',\n attributeName = 'data-inspecto',\n } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // Resolve path\n const resolvedPath =\n pathType === 'absolute'\n ? path.resolve(filePath)\n : path.relative(projectRoot, path.resolve(filePath))\n\n const normalizedPath = resolvedPath.replace(/\\\\/g, '/')\n\n // ── Find <template> block boundaries ──────────────────────────────────────\n // Use @vue/compiler-sfc to parse the file and extract the template block.\n // This is much safer than regex for handling nested templates.\n const { descriptor, errors } = parseSFC(source, {\n filename: filePath,\n sourceMap: false,\n ignoreEmpty: true,\n })\n\n if (errors.length > 0 || !descriptor.template) {\n return { code: source, map: null, changed: false }\n }\n\n const templateContent = descriptor.template.content\n const templateBlockStart = descriptor.template.loc.start.offset\n\n // ── Parse template block ───────────────────────────────────────────────────\n let ast: vueCompiler.RootNode\n try {\n ast = vueCompiler.parse(templateContent, {\n parseMode: 'html',\n // Preserve source locations relative to templateContent\n onError: () => {\n /* ignore non-fatal parse errors */\n },\n })\n } catch {\n return { code: source, map: null, changed: false }\n }\n\n const ms = new MagicString(source)\n let changed = false\n\n // ── Walk AST ───────────────────────────────────────────────────────────────\n walkElement(ast, node => {\n // Skip non-element nodes\n if (node.type !== NodeTypes.ELEMENT) return\n\n const tagName = node.tag\n\n // Skip escaped tags\n if (escapeTagsSet.has(tagName)) return\n\n // Skip <template> wrapper itself (it's the root, not a real element)\n if (tagName === 'template' && node === ast.children[0]) return\n\n // Skip elements that already have the attribute (idempotency)\n const alreadyHasAttr = node.props.some(\n (p): p is AttributeNode => p.type === NodeTypes.ATTRIBUTE && p.name === attributeName,\n )\n if (alreadyHasAttr) return\n\n // node.loc is relative to templateContent — add templateBlockStart offset\n const loc = node.loc\n if (!loc) return\n\n const { line, column } = loc.start\n\n // Calculate absolute line and column in the original source\n // @vue/compiler-dom uses 1-based line and 1-based column\n const templateStartLoc = descriptor.template!.loc.start\n const absoluteLine = templateStartLoc.line + line - 1\n const absoluteColumn = line === 1 ? templateStartLoc.column + column - 1 : column\n\n const attrValue = formatAttrValue(normalizedPath, absoluteLine, absoluteColumn)\n\n // Find insert position: right after the tag name in the original source\n // node.loc.start.offset is 0-based offset within templateContent\n const tagNameEnd = loc.start.offset + tagName.length + 1 // +1 for '<'\n const absoluteOffset = templateBlockStart + tagNameEnd\n\n ms.appendLeft(absoluteOffset, ` ${attributeName}=\"${attrValue}\"`)\n changed = true\n })\n\n if (!changed) {\n return { code: source, map: null, changed: false }\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true, source: filePath }),\n changed: true,\n }\n}\n\n// ── AST walker ────────────────────────────────────────────────────────────────\n\ntype AnyNode = vueCompiler.RootNode | vueCompiler.TemplateChildNode\n\nfunction walkElement(node: AnyNode, visitor: (node: ElementNode) => void): void {\n if (node.type === NodeTypes.ELEMENT) {\n visitor(node)\n for (const child of node.children) {\n walkElement(child as AnyNode, visitor)\n }\n } else if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n walkElement(child as AnyNode, visitor)\n }\n }\n}\n","import MagicString from 'magic-string'\nimport { parse as parseSvelte } from 'svelte/compiler'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformSvelteOptions {\n filePath: string\n source: string\n projectRoot?: string\n pathType?: 'absolute' | 'relative'\n escapeTags?: string[]\n attributeName?: string\n}\n\nfunction walk(node: any, visitor: { enter: (n: any) => void }) {\n if (!node || typeof node !== 'object') return\n visitor.enter(node)\n\n for (const key in node) {\n if (key === 'parent' || key === 'prev' || key === 'next') continue\n const value = node[key]\n if (Array.isArray(value)) {\n value.forEach(child => {\n if (child && typeof child === 'object') walk(child, visitor)\n })\n } else if (value && typeof value === 'object') {\n walk(value, visitor)\n }\n }\n}\n\nexport function transformSvelte(options: TransformSvelteOptions): TransformResult {\n const { filePath, source, escapeTags, attributeName = 'data-inspecto' } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // svelte parse doesn't support ts or scss/less\n // so replace the content of <script></script> and <style></style> with space\n // to avoid parser errors while preserving character offsets.\n let replacedContent = source\n const scriptRegex =\n /<script(?:\\s+[a-zA-Z-]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^>\\s]*))?)?>[\\s\\S]*?<\\/script>/gi\n const styleRegex =\n /<style(?:\\s+[a-zA-Z-]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^>\\s]*))?)?>[\\s\\S]*?<\\/style>/gi\n\n const scriptMatches = source.match(scriptRegex) || []\n const styleMatches = source.match(styleRegex) || []\n\n ;[...scriptMatches, ...styleMatches].forEach(match => {\n // Replace with exact same number of spaces to preserve offsets\n replacedContent = replacedContent.replace(match, ' '.repeat(match.length))\n })\n\n let ast: any\n try {\n ast = parseSvelte(replacedContent)\n } catch {\n // Graceful fallback for parse errors\n return { code: source, map: null, changed: false }\n }\n\n const s = new MagicString(source)\n let changed = false\n\n function countLines(text: string, position: number): number {\n let lines = 0\n for (let i = 0; i < position; i++) {\n if (text[i] === '\\n') lines++\n }\n return lines\n }\n\n const root = ast.html || ast.fragment || ast\n\n walk(root, {\n enter(node: any) {\n if (\n node.type === 'Element' ||\n node.type === 'RegularElement' ||\n node.type === 'InlineComponent' ||\n node.type === 'Component'\n ) {\n const tagName = node.name || ''\n\n if (\n tagName &&\n !escapeTagsSet.has(tagName.toLowerCase()) &&\n !node.attributes?.some((attr: any) => attr.name === attributeName)\n ) {\n const insertPosition = node.start + tagName.length + 1\n const line = countLines(source, node.start) + 1\n const lastNewLine = source.lastIndexOf('\\n', node.start - 1)\n const column = lastNewLine === -1 ? node.start + 1 : node.start - lastNewLine\n\n const attrValue = formatAttrValue(filePath, line, column)\n const addition = ` ${attributeName}=\"${attrValue}\"`\n\n s.appendLeft(insertPosition, addition)\n changed = true\n }\n }\n },\n })\n\n return {\n code: s.toString(),\n map: changed ? s.generateMap({ source: filePath, includeContent: true }) : null,\n changed,\n }\n}\n","import MagicString from 'magic-string'\nimport { parse as parseAstro } from '@astrojs/compiler/sync'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformAstroOptions {\n filePath: string\n source: string\n pathType?: 'absolute' | 'relative'\n escapeTags?: string[]\n attributeName?: string\n}\n\nfunction walk(node: any, visitor: { enter: (n: any) => void }) {\n if (!node || typeof node !== 'object') return\n visitor.enter(node)\n\n if (Array.isArray(node.children)) {\n for (const child of node.children) {\n walk(child, visitor)\n }\n }\n}\n\nexport function transformAstro(options: TransformAstroOptions): TransformResult {\n const { filePath, source, escapeTags, attributeName = 'data-inspecto' } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n let ast: any\n try {\n ast = parseAstro(source, { position: true }).ast\n } catch (_err) {\n return { code: source, map: null, changed: false }\n }\n\n const s = new MagicString(source)\n let changed = false\n\n walk(ast, {\n enter(node: any) {\n // Element or Component in Astro AST\n if (node.type === 'element' || node.type === 'component') {\n const tagName = node.name\n\n if (\n tagName &&\n !escapeTagsSet.has(tagName) &&\n !node.attributes?.some((attr: any) => attr.name === attributeName)\n ) {\n const startOffset = node.position?.start?.offset ?? -1\n if (startOffset === -1) return\n\n // Find the exact `<` before or at the startOffset\n let tagStartIndex = startOffset\n while (tagStartIndex >= 0 && source[tagStartIndex] !== '<') {\n tagStartIndex--\n }\n\n if (tagStartIndex >= 0) {\n const substringAfterTag = source.substring(tagStartIndex)\n const escapedTagName = tagName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const strictRegex = new RegExp(`^<\\\\s*${escapedTagName}(?=\\\\s|/|>)`, 'i')\n const strictMatch = substringAfterTag.match(strictRegex)\n\n if (strictMatch) {\n const insertPosition = tagStartIndex + strictMatch[0].length\n const line = node.position.start.line\n const column = node.position.start.column\n\n const attrValue = formatAttrValue(filePath, line, column)\n const addition = ` ${attributeName}=\"${attrValue}\"`\n\n s.appendLeft(insertPosition, addition)\n changed = true\n }\n }\n }\n }\n },\n })\n\n return {\n code: s.toString(),\n map: changed ? s.generateMap({ source: filePath, includeContent: true }) : null,\n changed,\n }\n}\n","import g from\"crypto\";import _ from\"fs\";import{TextDecoder as b,TextEncoder as v}from\"util\";globalThis.fs||Object.defineProperty(globalThis,\"fs\",{value:_});globalThis.process||Object.defineProperties(globalThis,\"process\",{value:process});globalThis.crypto||Object.defineProperty(globalThis,\"crypto\",{value:g.webcrypto?g.webcrypto:{getRandomValues(m){return g.randomFillSync(m)}}});globalThis.performance||Object.defineProperty(globalThis,\"performance\",{value:{now(){let[m,o]=process.hrtime();return m*1e3+o/1e6}}});var y=new v(\"utf-8\"),w=new b(\"utf-8\");var d=class{constructor(){this.argv=[\"js\"],this.env={},this.exit=t=>{t!==0&&console.warn(\"exit code:\",t)},this._exitPromise=new Promise(t=>{this._resolveExitPromise=t}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let o=(t,e)=>{this.mem.setUint32(t+0,e,!0),this.mem.setUint32(t+4,Math.floor(e/4294967296),!0)},n=t=>{let e=this.mem.getUint32(t+0,!0),s=this.mem.getInt32(t+4,!0);return e+s*4294967296},r=t=>{let e=this.mem.getFloat64(t,!0);if(e===0)return;if(!isNaN(e))return e;let s=this.mem.getUint32(t,!0);return this._values[s]},l=(t,e)=>{if(typeof e==\"number\"&&e!==0){if(isNaN(e)){this.mem.setUint32(t+4,2146959360,!0),this.mem.setUint32(t,0,!0);return}this.mem.setFloat64(t,e,!0);return}if(e===void 0){this.mem.setFloat64(t,0,!0);return}let i=this._ids.get(e);i===void 0&&(i=this._idPool.pop(),i===void 0&&(i=this._values.length),this._values[i]=e,this._goRefCounts[i]=0,this._ids.set(e,i)),this._goRefCounts[i]++;let a=0;switch(typeof e){case\"object\":e!==null&&(a=1);break;case\"string\":a=2;break;case\"symbol\":a=3;break;case\"function\":a=4;break}this.mem.setUint32(t+4,2146959360|a,!0),this.mem.setUint32(t,i,!0)},c=t=>{let e=n(t+0),s=n(t+8);return new Uint8Array(this._inst.exports.mem.buffer,e,s)},f=t=>{let e=n(t+0),s=n(t+8),i=new Array(s);for(let a=0;a<s;a++)i[a]=r(e+a*8);return i},u=t=>{let e=n(t+0),s=n(t+8);return w.decode(new DataView(this._inst.exports.mem.buffer,e,s))},h=Date.now()-performance.now();this.importObject={gojs:{\"runtime.wasmExit\":t=>{t>>>=0;let e=this.mem.getInt32(t+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(e)},\"runtime.wasmWrite\":t=>{t>>>=0;let e=n(t+8),s=n(t+16),i=this.mem.getInt32(t+24,!0);_.writeSync(e,new Uint8Array(this._inst.exports.mem.buffer,s,i))},\"runtime.resetMemoryDataView\":t=>{t>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},\"runtime.nanotime1\":t=>{t>>>=0,o(t+8,(h+performance.now())*1e6)},\"runtime.walltime\":t=>{t>>>=0;let e=new Date().getTime();o(t+8,e/1e3),this.mem.setInt32(t+16,e%1e3*1e6,!0)},\"runtime.scheduleTimeoutEvent\":t=>{t>>>=0;let e=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(e,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(e);)console.warn(\"scheduleTimeoutEvent: missed timeout event\"),this._resume()},n(t+8)+1)),this.mem.setInt32(t+16,e,!0)},\"runtime.clearTimeoutEvent\":t=>{t>>>=0;let e=this.mem.getInt32(t+8,!0);clearTimeout(this._scheduledTimeouts.get(e)),this._scheduledTimeouts.delete(e)},\"runtime.getRandomData\":t=>{t>>>=0,globalThis.crypto.getRandomValues(c(t+8))},\"syscall/js.finalizeRef\":t=>{t>>>=0;let e=this.mem.getUint32(t+8,!0);if(this._goRefCounts[e]--,this._goRefCounts[e]===0){let s=this._values[e];this._values[e]=null,this._ids.delete(s),this._idPool.push(e)}},\"syscall/js.stringVal\":t=>{t>>>=0,l(t+24,u(t+8))},\"syscall/js.valueGet\":t=>{t>>>=0;let e=Reflect.get(r(t+8),u(t+16));t=this._inst.exports.getsp()>>>0,l(t+32,e)},\"syscall/js.valueSet\":t=>{t>>>=0,Reflect.set(r(t+8),u(t+16),r(t+32))},\"syscall/js.valueDelete\":t=>{t>>>=0,Reflect.deleteProperty(r(t+8),u(t+16))},\"syscall/js.valueIndex\":t=>{t>>>=0,l(t+24,Reflect.get(r(t+8),n(t+16)))},\"syscall/js.valueSetIndex\":t=>{t>>>=0,Reflect.set(r(t+8),n(t+16),r(t+24))},\"syscall/js.valueCall\":t=>{t>>>=0;try{let e=r(t+8),s=Reflect.get(e,u(t+16)),i=f(t+32),a=Reflect.apply(s,e,i);t=this._inst.exports.getsp()>>>0,l(t+56,a),this.mem.setUint8(t+64,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+56,e),this.mem.setUint8(t+64,0)}},\"syscall/js.valueInvoke\":t=>{t>>>=0;try{let e=r(t+8),s=f(t+16),i=Reflect.apply(e,void 0,s);t=this._inst.exports.getsp()>>>0,l(t+40,i),this.mem.setUint8(t+48,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+40,e),this.mem.setUint8(t+48,0)}},\"syscall/js.valueNew\":t=>{t>>>=0;try{let e=r(t+8),s=f(t+16),i=Reflect.construct(e,s);t=this._inst.exports.getsp()>>>0,l(t+40,i),this.mem.setUint8(t+48,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+40,e),this.mem.setUint8(t+48,0)}},\"syscall/js.valueLength\":t=>{t>>>=0,o(t+16,Number.parseInt(r(t+8).length))},\"syscall/js.valuePrepareString\":t=>{t>>>=0;let e=y.encode(String(r(t+8)));l(t+16,e),o(t+24,e.length)},\"syscall/js.valueLoadString\":t=>{t>>>=0;let e=r(t+8);c(t+16).set(e)},\"syscall/js.valueInstanceOf\":t=>{t>>>=0,this.mem.setUint8(t+24,r(t+8)instanceof r(t+16)?1:0)},\"syscall/js.copyBytesToGo\":t=>{t>>>=0;let e=c(t+8),s=r(t+32);if(!(s instanceof Uint8Array||s instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=s.subarray(0,e.length);e.set(i),o(t+40,i.length),this.mem.setUint8(t+48,1)},\"syscall/js.copyBytesToJS\":t=>{t>>>=0;let e=r(t+8),s=c(t+16);if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=s.subarray(0,e.length);e.set(i),o(t+40,i.length),this.mem.setUint8(t+48,1)},debug:t=>{console.log(t)}}}}async run(o){if(!(o instanceof WebAssembly.Instance))throw new Error(\"Go.run: WebAssembly.Instance expected\");this._inst=o,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[Number.NaN,0,null,!0,!1,globalThis,this],this._goRefCounts=new Array(this._values.length).fill(Number.POSITIVE_INFINITY),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[globalThis,5],[this,6]]),this._idPool=[],this.exited=!1;let n=4096,r=h=>{let t=n,e=y.encode(`${h}\\0`);return new Uint8Array(this.mem.buffer,n,e.length).set(e),n+=e.length,n%8!==0&&(n+=8-n%8),t},l=this.argv.length,c=[];this.argv.forEach(h=>{c.push(r(h))}),c.push(0),Object.keys(this.env).sort().forEach(h=>{c.push(r(`${h}=${this.env[h]}`))}),c.push(0);let u=n;c.forEach(h=>{this.mem.setUint32(n,h,!0),this.mem.setUint32(n+4,0,!0),n+=8}),this._inst.exports.run(l,u),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error(\"Go program has already exited\");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(o){let n=this;return function(){let r={id:o,this:this,args:arguments};return n._pendingEvent=r,n._resume(),r.result}}};export{d as a};\n","import{a as c}from\"../chunk-W5DTLHV4.js\";import{readFileSync as p}from\"fs\";import{fileURLToPath as m}from\"url\";function i(){return s||(s=f()),s}var s,l=(e,t)=>i().transform(e,t),w=(e,t)=>i().parse(e,t),h=(e,t)=>i().convertToTSX(e,t);function f(){let e=new c,t=v(m(new URL(\"../astro.wasm\",import.meta.url)),e.importObject);e.run(t);let o=globalThis[\"@astrojs/compiler\"];return{transform:(n,a)=>{try{return o.transform(n,a||{})}catch(r){throw s=void 0,r}},parse:(n,a)=>{try{let r=o.parse(n,a||{});return{...r,ast:JSON.parse(r.ast)}}catch(r){throw s=void 0,r}},convertToTSX:(n,a)=>{try{let r=o.convertToTSX(n,a||{});return{...r,map:JSON.parse(r.map)}}catch(r){throw s=void 0,r}}}}function v(e,t){let o=p(e);return new WebAssembly.Instance(new WebAssembly.Module(o),t)}export{h as convertToTSX,w as parse,f as startRunningService,l as transform};\n","import http from 'node:http'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport os from 'node:os'\nimport crypto from 'node:crypto'\nimport portfinder from 'portfinder'\nimport type {\n AnnotationSessionEvent,\n AnnotationSessionStatus,\n AnnotationSessionClaimRequest,\n AnnotationSessionReplyRequest,\n AnnotationSessionResolveRequest,\n ServerState,\n OpenFileRequest,\n SendToAiRequest,\n SendToAiResponse,\n SendAnnotationsToAiRequest,\n SendAnnotationsToAiResponse,\n} from '@inspecto-dev/types'\nimport { INSPECTO_API_PATHS } from '@inspecto-dev/types'\nimport { extractSnippet } from './snippet.js'\nimport { dispatchAnnotationsToAi } from './annotation-dispatch.js'\nimport { readTicket } from './dispatch-transport.js'\nimport { dispatchPromptThroughIde, resolvePromptDispatchRuntime } from './dispatch-runtime.js'\nimport { assertPathWithinProject, resolveWorkspacePath } from './path-guards.js'\nimport { buildClientConfig } from './client-config.js'\nimport { handleOpenFileRequest } from './open-file.js'\nimport { resolveProjectRoot } from './project-root.js'\nimport { resolveServerHost } from './server-url.js'\nimport { annotationSessionStore, hasAgentReply } from './session-store.js'\nimport { watchConfig, unwatchConfig, getGlobalLogLevel } from '../config.js'\nimport { createLogger } from '../utils/logger.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\nconst PORT_FILE_NAME = 'inspecto.port.json'\nconst LEGACY_PORT_FILE_NAME = 'inspecto.port'\n\nexport const serverState: ServerState = {\n port: null,\n running: false,\n projectRoot: '',\n configRoot: '',\n cwd: process.cwd(),\n}\n\nlet serverInstance: http.Server | null = null\n\nfunction getPortFilePath(): string {\n return path.join(os.tmpdir(), PORT_FILE_NAME)\n}\n\nfunction getProjectRootHash(): string | null {\n if (!serverState.projectRoot) return null\n return crypto.createHash('md5').update(serverState.projectRoot).digest('hex')\n}\n\nfunction readPortData(portFile: string): Record<string, number> {\n if (!fs.existsSync(portFile)) return {}\n try {\n return JSON.parse(fs.readFileSync(portFile, 'utf-8')) as Record<string, number>\n } catch {\n return {}\n }\n}\n\nfunction writeProjectPort(port: number): void {\n const rootHash = getProjectRootHash()\n if (!rootHash) return\n\n const portFile = getPortFilePath()\n const portData = readPortData(portFile)\n portData[rootHash] = port\n fs.writeFileSync(portFile, JSON.stringify(portData, null, 2), 'utf-8')\n}\n\nfunction removeProjectPort(): void {\n const rootHash = getProjectRootHash()\n if (!rootHash) return\n\n const portFile = getPortFilePath()\n if (!fs.existsSync(portFile)) return\n\n const portData = readPortData(portFile)\n delete portData[rootHash]\n\n if (Object.keys(portData).length === 0) {\n fs.unlinkSync(portFile)\n } else {\n fs.writeFileSync(portFile, JSON.stringify(portData, null, 2), 'utf-8')\n }\n}\n\nexport async function startServer(): Promise<number> {\n if (serverState.running && serverState.port !== null) {\n return serverState.port\n }\n\n // Resolve project root at server start time so process.cwd() reflects the\n // actual project directory, not the module load-time cwd.\n serverState.projectRoot = resolveProjectRoot()\n serverState.configRoot = serverState.projectRoot\n serverState.cwd = process.cwd()\n const serverHost = resolveServerHost(serverState.cwd, serverState.configRoot)\n\n portfinder.basePort = 5678\n const port = await portfinder.getPortPromise()\n\n // Watch for user config changes to trigger hot-reloads internally if needed\n watchConfig(\n () => {\n serverLogger.info('user config reloaded.')\n },\n serverState.cwd,\n serverState.configRoot,\n )\n\n serverInstance = http.createServer((req, res) => {\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type')\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204)\n res.end()\n return\n }\n\n const url = new URL(req.url ?? '/', `http://localhost:${port}`)\n handleRequest(url, req, res).catch(err => {\n serverLogger.error('server error:', err)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(err) }))\n })\n })\n\n await new Promise<void>((resolve, reject) => {\n serverInstance!.listen(port, serverHost, () => {\n serverInstance!.unref() // Allow process to exit\n resolve()\n })\n serverInstance!.once('error', reject)\n })\n\n // Add persistent error handler after successful startup\n serverInstance!.on('error', err => {\n serverLogger.error('persistent server error:', err)\n })\n\n serverState.port = port\n serverState.running = true\n\n // Write port file so the IDE extension can discover the server without scanning ports\n try {\n writeProjectPort(port)\n } catch (_e) {\n serverLogger.warn('Failed to write port file:', _e)\n /* non-fatal — extension will fall back to scanning */\n }\n // Clean up on process exit (Vite terminates the process, not stopServer)\n process.once('exit', () => {\n try {\n removeProjectPort()\n } catch {\n /* ignore */\n }\n })\n\n serverLogger.info(`server running at http://${serverHost}:${port}`)\n\n return port\n}\n\nexport function stopServer(): void {\n if (serverInstance) {\n serverInstance.close()\n serverInstance = null\n }\n unwatchConfig()\n serverState.running = false\n serverState.port = null\n try {\n removeProjectPort()\n } catch {\n /* ignore */\n }\n try {\n fs.unlinkSync(path.join(os.tmpdir(), LEGACY_PORT_FILE_NAME))\n } catch {\n /* ignore */\n }\n}\n\nasync function readBody(req: http.IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => chunks.push(chunk))\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))\n req.on('error', reject)\n })\n}\n\nexport async function handleRequest(\n url: URL,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n): Promise<void> {\n const pathname = url.pathname\n\n // Health check - root or /inspecto/api/v1/health\n if ((pathname === '/health' || pathname === INSPECTO_API_PATHS.HEALTH) && req.method === 'GET') {\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ ok: true, port: serverState.port }))\n return\n }\n\n // Browser Client requests\n if (pathname === INSPECTO_API_PATHS.CLIENT_CONFIG && req.method === 'GET') {\n const config = await buildClientConfig(serverState)\n\n // Omit providers from the response sent to the client\n delete config.providers\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(config))\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.IDE_INFO && req.method === 'POST') {\n try {\n const body = JSON.parse(await readBody(req))\n\n // Workspace matching defense mechanism against multiple IDE connections\n const ideWorkspace = body.workspaceRoot || ''\n const serverProjectRoot = serverState.projectRoot || ''\n\n const normalizedIdeRoot = ideWorkspace ? path.resolve(ideWorkspace) : ''\n const normalizedServerRoot = serverProjectRoot ? path.resolve(serverProjectRoot) : ''\n\n const isSameProject =\n !normalizedIdeRoot ||\n !normalizedServerRoot ||\n normalizedIdeRoot === normalizedServerRoot ||\n normalizedServerRoot.startsWith(normalizedIdeRoot + path.sep) ||\n normalizedIdeRoot.startsWith(normalizedServerRoot + path.sep)\n\n if (isSameProject) {\n serverState.ideInfo = body\n serverLogger.debug(\n `Accepted IDE info from matched workspace (ide-${body.ide} / schema-${body.scheme})`,\n )\n } else {\n serverLogger.debug(\n `Ignored IDE info from unrelated workspace (IDE Workspace: ${ideWorkspace}, Server: ${serverProjectRoot}, Scheme: ${body.scheme}, IDE: ${body.ide})`,\n )\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true }))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.IDE_INFO} POST request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n (pathname === INSPECTO_API_PATHS.SOURCE_OPEN || pathname === INSPECTO_API_PATHS.IDE_OPEN) &&\n req.method === 'POST'\n ) {\n let body: OpenFileRequest\n try {\n body = JSON.parse(await readBody(req)) as OpenFileRequest\n } catch (_e) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n return\n }\n\n try {\n handleOpenFileRequest(body, serverState)\n } catch (err: any) {\n serverLogger.warn(\n `Security: Blocked path traversal attempt in SOURCE_OPEN: ${body.file}. Reason: ${err.message}`,\n )\n res.writeHead(403, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Access denied: File is outside of project workspace' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true }))\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.PROJECT_SNIPPET && req.method === 'GET') {\n const file = url.searchParams.get('file') ?? ''\n const line = parseInt(url.searchParams.get('line') ?? '1', 10)\n const column = parseInt(url.searchParams.get('column') ?? '1', 10)\n const maxLines = parseInt(url.searchParams.get('maxLines') ?? '100', 10)\n\n try {\n const absolutePath = resolveWorkspacePath(file, serverState.cwd)\n\n // Security: Prevent path traversal attacks\n try {\n assertPathWithinProject(absolutePath, serverState.projectRoot)\n } catch (err: any) {\n serverLogger.warn(\n `Security: Blocked path traversal attempt in PROJECT_SNIPPET: ${file}. Reason: ${err.message}`,\n )\n res.writeHead(403, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: false,\n error: 'Access denied: File is outside of project workspace',\n errorCode: 'FORBIDDEN',\n }),\n )\n return\n }\n\n const result = await extractSnippet({ file: absolutePath, line, column, maxLines })\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(result))\n } catch (err: any) {\n const message = String(err.message || err)\n const errorCode = message.startsWith('FILE_NOT_FOUND') ? 'FILE_NOT_FOUND' : 'UNKNOWN'\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: message, errorCode }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.AI_DISPATCH && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as SendToAiRequest\n const result = await dispatchToAi(body)\n res.writeHead(result.success ? 200 : 500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(result))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.AI_DISPATCH} request:`, e)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(e), errorCode: 'INTERNAL_ERROR' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.AI_BATCH_DISPATCH && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as SendAnnotationsToAiRequest\n const result = await dispatchAnnotationsToAi(body, serverState)\n res.writeHead(getBatchDispatchStatusCode(result.errorCode, result.success), {\n 'Content-Type': 'application/json',\n })\n res.end(JSON.stringify(result))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.AI_BATCH_DISPATCH} request:`, e)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(e), errorCode: 'INTERNAL_ERROR' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSION_CLAIM_NEXT && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionClaimRequest) : {}\n const timeoutMs = normalizeSessionClaimTimeout(\n body.timeoutMs === undefined ? null : String(body.timeoutMs),\n )\n const result = await annotationSessionStore.claimNextSession({\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n })\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: true,\n timedOut: result.timedOut,\n matchedExisting: result.matchedExisting,\n ...(result.event ? { event: result.event } : {}),\n ...(result.session ? { session: result.session } : {}),\n }),\n )\n } catch (e) {\n serverLogger.error(`Error parsing session claim request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSION_EVENTS && req.method === 'GET') {\n const statusParam = url.searchParams.getAll('status')\n const statuses = statusParam.length ? new Set(statusParam as AnnotationSessionStatus[]) : null\n const sessionId = url.searchParams.get('sessionId')?.trim() || null\n\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n res.write(`event: ready\\ndata: ${JSON.stringify({ ok: true })}\\n\\n`)\n\n const unsubscribe = annotationSessionStore.subscribe(event => {\n if (sessionId && event.session.id !== sessionId) {\n return\n }\n if (statuses && !statuses.has(event.session.status)) {\n return\n }\n res.write(formatSessionSseEvent(event))\n })\n\n req.on('close', () => {\n unsubscribe()\n res.end()\n })\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSIONS && req.method === 'GET') {\n const statusParam = url.searchParams.getAll('status')\n const sessions = annotationSessionStore.listSessions(\n statusParam.length\n ? {\n status: statusParam as AnnotationSessionStatus[],\n }\n : undefined,\n )\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, sessions }))\n return\n }\n\n if (pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) && req.method === 'GET') {\n const sessionId = pathname.substring(INSPECTO_API_PATHS.SESSIONS.length + 1)\n const session = annotationSessionStore.getSession(sessionId)\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_REPLY_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_REPLY_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as AnnotationSessionReplyRequest\n\n if (!isAnnotationThreadRole(body.role)) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Reply role is invalid.' }))\n return\n }\n\n if (!body.text?.trim()) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Reply text is required.' }))\n return\n }\n\n const session = annotationSessionStore.appendMessage(sessionId, {\n role: body.role,\n text: body.text.trim(),\n })\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session reply request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_RESOLVE_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_RESOLVE_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionResolveRequest) : {}\n const message = body.message?.trim()\n const existingSession = annotationSessionStore.getSession(sessionId)\n\n if (!existingSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n if (!message && !hasAgentReply(existingSession)) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: false,\n error: 'Resolve message is required until an agent reply is recorded.',\n }),\n )\n return\n }\n\n if (message) {\n const repliedSession = annotationSessionStore.appendMessage(sessionId, {\n role: 'agent',\n text: message,\n })\n if (!repliedSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n }\n\n const session = annotationSessionStore.updateStatus(sessionId, 'resolved')\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session resolve request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_DISMISS_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_DISMISS_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionResolveRequest) : {}\n const message = body.message?.trim()\n const existingSession = annotationSessionStore.getSession(sessionId)\n\n if (!existingSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n if (message) {\n const repliedSession = annotationSessionStore.appendMessage(sessionId, {\n role: 'agent',\n text: message,\n })\n if (!repliedSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n }\n\n const session = annotationSessionStore.updateStatus(sessionId, 'dismissed')\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session dismiss request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n // Handle IDE payload ticket retrieval\n if (pathname.startsWith(`${INSPECTO_API_PATHS.AI_TICKET}/`) && req.method === 'GET') {\n const ticketId = pathname.substring(INSPECTO_API_PATHS.AI_TICKET.length + 1)\n const payloadStr = readTicket(ticketId)\n\n if (!payloadStr) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Ticket not found or expired' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(payloadStr)\n return\n }\n\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'not found' }))\n}\n\nasync function dispatchToAi(\n req: SendToAiRequest,\n): Promise<SendToAiResponse & { fallbackPayload?: { prompt: string; file: string } }> {\n const { location, snippet, prompt } = req\n\n const formattedPrompt =\n prompt ??\n `Please help me with this code from \\`${location.file}\\` (line ${location.line}):\\n\\n\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n`\n const runtime = resolvePromptDispatchRuntime(serverState)\n return dispatchPromptThroughIde(runtime, {\n prompt: formattedPrompt,\n filePath: location.file,\n line: location.line,\n column: location.column,\n snippet,\n }) as SendToAiResponse & { fallbackPayload?: { prompt: string; file: string } }\n}\n\nfunction getBatchDispatchStatusCode(\n errorCode: SendAnnotationsToAiResponse['errorCode'],\n success: boolean,\n): number {\n if (success) return 200\n if (errorCode === 'INVALID_REQUEST') return 400\n if (errorCode === 'FORBIDDEN_PATH') return 403\n return 500\n}\n\nfunction isAnnotationThreadRole(\n value: string | undefined,\n): value is AnnotationSessionReplyRequest['role'] {\n return value === 'user' || value === 'agent' || value === 'system'\n}\n\nfunction formatSessionSseEvent(event: AnnotationSessionEvent): string {\n return `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`\n}\n\nfunction normalizeSessionClaimTimeout(value: string | null): number | undefined {\n if (!value?.trim()) return 30000\n const parsed = Number.parseInt(value, 10)\n if (!Number.isFinite(parsed)) return 30000\n return Math.max(0, Math.min(parsed, 300000))\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as parser from '@babel/parser'\nimport traverse_ from '@babel/traverse'\n// Support both ESM default and CommonJS module.exports\nconst traverse =\n typeof traverse_ === 'function' ? traverse_ : (traverse_ as any).default || traverse_\nimport type { NodePath } from '@babel/traverse'\nimport type { Node } from '@babel/types'\nimport type { SnippetRequest, SnippetResponse } from '@inspecto-dev/types'\n\ninterface CacheEntry {\n mtime: number\n /** The full parsed source lines */\n lines: string[]\n}\n\n/** In-memory cache keyed by absolute file path */\nconst snippetCache = new Map<string, CacheEntry>()\n\nconst DEFAULT_MAX_LINES = 100\nconst DEFAULT_CONTEXT_LINES_BEFORE = 5\n\nexport async function extractSnippet(req: SnippetRequest): Promise<SnippetResponse> {\n const { file, line, column, maxLines = DEFAULT_MAX_LINES } = req\n\n const absolutePath = path.resolve(file)\n\n let stat: fs.Stats\n try {\n stat = await fs.promises.stat(absolutePath)\n } catch {\n throw new Error(`FILE_NOT_FOUND: ${absolutePath}`)\n }\n\n const mtime = stat.mtimeMs\n\n let lines: string[]\n const cached = snippetCache.get(absolutePath)\n if (cached && cached.mtime === mtime) {\n lines = cached.lines\n } else {\n const source = await fs.promises.readFile(absolutePath, 'utf-8')\n lines = source.split('\\n')\n snippetCache.set(absolutePath, { mtime, lines })\n }\n\n let snippetLines: string[]\n let startLine: number\n let componentName: string | undefined\n\n try {\n const result = extractComponentBoundary(lines.join('\\n'), line, column, maxLines)\n snippetLines = result.lines\n startLine = result.startLine\n componentName = result.name\n } catch {\n const before = Math.max(0, line - 1 - DEFAULT_CONTEXT_LINES_BEFORE)\n const after = Math.min(lines.length, before + maxLines)\n snippetLines = lines.slice(before, after)\n startLine = before + 1\n }\n\n if (snippetLines.length > maxLines) {\n snippetLines = snippetLines.slice(0, maxLines)\n }\n\n return {\n snippet: snippetLines.join('\\n'),\n startLine,\n file: absolutePath,\n ...(componentName ? { name: componentName } : {}),\n }\n}\n\ninterface BoundaryResult {\n lines: string[]\n startLine: number\n name?: string\n}\n\nfunction extractComponentBoundary(\n source: string,\n targetLine: number,\n _targetColumn: number,\n maxLines: number,\n): BoundaryResult {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript', 'decorators-legacy', 'classProperties'],\n errorRecovery: true,\n })\n\n const allLines = source.split('\\n')\n\n let bestStart = 0\n let bestEnd = allLines.length - 1\n let bestName: string | undefined\n\n traverse(ast, {\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ClassMethod'(\n nodePath: NodePath<Node>,\n ) {\n const node = nodePath.node\n if (!node.loc) return\n\n const nodeStart = node.loc.start.line\n const nodeEnd = node.loc.end.line\n\n if (targetLine < nodeStart || targetLine > nodeEnd) return\n\n if (nodeEnd - nodeStart < bestEnd - bestStart) {\n bestStart = nodeStart - 1\n bestEnd = nodeEnd - 1\n bestName = extractFunctionName(nodePath)\n }\n },\n })\n\n let sliceStart = bestStart\n let sliceEnd = bestEnd + 1\n\n if (sliceEnd - sliceStart > maxLines) {\n const targetIdx = targetLine - 1\n sliceStart = Math.max(bestStart, targetIdx - Math.floor(maxLines / 3))\n sliceEnd = sliceStart + maxLines\n if (sliceEnd > bestEnd + 1) {\n sliceEnd = bestEnd + 1\n sliceStart = Math.max(0, sliceEnd - maxLines)\n }\n }\n\n return {\n lines: allLines.slice(sliceStart, sliceEnd),\n startLine: sliceStart + 1,\n ...(bestName ? { name: bestName } : {}),\n }\n}\n\nfunction extractFunctionName(nodePath: NodePath<Node>): string | undefined {\n const node = nodePath.node\n\n if (node.type === 'FunctionDeclaration' && node.id) {\n return node.id.name\n }\n\n const parent = nodePath.parent\n if (\n (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') &&\n parent.type === 'VariableDeclarator' &&\n parent.id.type === 'Identifier'\n ) {\n return parent.id.name\n }\n\n if (node.type === 'ClassMethod' && node.key.type === 'Identifier') {\n return node.key.name\n }\n\n return undefined\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport os from 'node:os'\nimport { createDefu } from 'defu'\nimport type {\n InspectoSettings,\n InspectoPromptsConfig,\n Provider,\n ProviderMode,\n ToolOverrides,\n IdeType,\n LogLevel,\n} from '@inspecto-dev/types'\nimport {\n DEFAULT_PROVIDER_MODE,\n VALID_MODES,\n DEFAULT_INTENTS,\n IntentConfig,\n} from '@inspecto-dev/types'\nimport { createLogger, setLoggerGlobalLevel } from './utils/logger.js'\n\nconst configLogger = createLogger('inspecto:config')\n\nlet loadedConfig: InspectoSettings | null = null\nlet loadedPrompts: InspectoPromptsConfig | null = null\nlet globalLogLevel: LogLevel = 'warn'\nlet isWatching = false\n\n// Custom array merge behavior for defu: overwrite arrays instead of concatenating them\nconst arrayReplaceMerge = createDefu((obj, key, val) => {\n if (Array.isArray(val)) {\n obj[key] = val\n return true\n }\n})\n\nexport function setGlobalLogLevel(level?: LogLevel) {\n if (level) {\n globalLogLevel = level\n setLoggerGlobalLevel(level)\n }\n}\n\nexport function getGlobalLogLevel() {\n return globalLogLevel\n}\n\n/**\n * Walk from cwd up to gitRoot (inclusive), collecting directories that contain\n * a .inspecto/ subdirectory. Returns them ordered highest-priority first\n * (closest to cwd first).\n *\n * If cwd is not under gitRoot, only cwd itself is checked.\n */\nexport function resolveConfigRoots(cwd: string, gitRoot: string): string[] {\n const roots: string[] = []\n let current = cwd\n\n // Ensure we don't walk past gitRoot (handles cwd above gitRoot case)\n const isUnderOrEqual = current === gitRoot || current.startsWith(gitRoot + path.sep)\n if (!isUnderOrEqual) {\n // cwd is not under gitRoot — only check cwd\n if (fs.existsSync(path.join(cwd, '.inspecto'))) roots.push(cwd)\n return roots\n }\n\n while (true) {\n if (fs.existsSync(path.join(current, '.inspecto'))) {\n roots.push(current)\n }\n if (current === gitRoot) break\n const parent = path.dirname(current)\n if (parent === current) break // filesystem root guard\n current = parent\n }\n\n return roots\n}\n\n/**\n * Load and merge user config from all discovered .inspecto/ layers:\n *\n * Priority (highest → lowest):\n * <cwd>/.inspecto/settings.local.json\n * <cwd>/.inspecto/settings.json\n * ...intermediate dirs...\n * <gitRoot>/.inspecto/settings.local.json\n * <gitRoot>/.inspecto/settings.json\n * ~/.inspecto/settings.json\n *\n * @param force Bust cache and re-read from disk\n * @param cwd Working directory to start resolution from (default: process.cwd())\n * @param gitRoot Git repository root — upward traversal stops here (optional)\n */\nexport function loadUserConfigSync(\n force = false,\n cwd = process.cwd(),\n gitRoot?: string,\n): InspectoSettings {\n if (loadedConfig && !force) return loadedConfig\n loadedConfig = null // force clear\n\n const layers: Partial<InspectoSettings>[] = []\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n\n for (const root of roots) {\n layers.push(readJsonSafely(path.join(root, '.inspecto', 'settings.local.json')))\n layers.push(readJsonSafely(path.join(root, '.inspecto', 'settings.json')))\n }\n\n layers.push(readJsonSafely(path.join(os.homedir(), '.inspecto', 'settings.json')))\n layers.push({})\n\n const validLayers = layers.filter(l => l !== null)\n loadedConfig = arrayReplaceMerge(...(validLayers as [object, ...object[]])) as InspectoSettings\n return loadedConfig\n}\n\n/**\n * Load and merge prompts config from all discovered .inspecto/ layers:\n *\n * Priority (highest → lowest):\n * <cwd>/.inspecto/prompts.local.json\n * <cwd>/.inspecto/prompts.json\n * ...intermediate dirs...\n * <gitRoot>/.inspecto/prompts.local.json\n * <gitRoot>/.inspecto/prompts.json\n * ~/.inspecto/prompts.json\n *\n * Arrays in custom configurations are replaced instead of merged.\n */\nexport async function loadPromptsConfig(\n force = false,\n cwd = process.cwd(),\n gitRoot?: string,\n): Promise<InspectoPromptsConfig> {\n if (loadedPrompts && !force) return loadedPrompts\n\n const layers: any[] = []\n\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n for (const root of roots) {\n const localPath = path.join(root, '.inspecto', 'prompts.local.json')\n const jsonPath = path.join(root, '.inspecto', 'prompts.json')\n layers.push(readJsonSafely(localPath))\n layers.push(readJsonSafely(jsonPath))\n }\n\n layers.push(readJsonSafely(path.join(os.homedir(), '.inspecto', 'prompts.json')))\n\n // Find the first layer that contains a valid prompts config (array or $replace object).\n // Highest-priority layer wins — no merging across layers for prompts.\n let finalPrompts: any = []\n for (const layer of layers) {\n if (Array.isArray(layer) && layer.length > 0) {\n finalPrompts = layer\n break\n }\n if (\n layer &&\n typeof layer === 'object' &&\n layer.$replace === true &&\n Array.isArray(layer.items)\n ) {\n finalPrompts = layer\n break\n }\n }\n\n loadedPrompts = finalPrompts as InspectoPromptsConfig\n return loadedPrompts\n}\n\nfunction readJsonSafely(filePath: string): any {\n try {\n if (fs.existsSync(filePath)) {\n const content = fs.readFileSync(filePath, 'utf-8').trim()\n if (!content) return null // Return null instead of [] so we know it's empty\n const parsed = JSON.parse(content)\n // Transition helper: if user still has {\"prompts\": [...]}, extract it\n if (!Array.isArray(parsed) && parsed.prompts && Array.isArray(parsed.prompts)) {\n return parsed.prompts\n }\n return parsed\n }\n } catch (e) {\n // Ignore JSON parsing errors for empty or malformed files during watch\n if (e instanceof SyntaxError) {\n configLogger.warn(`Failed to parse config at ${filePath}: Invalid JSON`)\n } else {\n configLogger.warn(`Failed to read config at ${filePath}:`, e)\n }\n }\n return null\n}\n\n/**\n * Resolve the exact target tool to dispatch to based on user config.\n */\nexport function resolveTargetTool(config: InspectoSettings, _ide: IdeType = 'vscode'): Provider {\n // Support \"provider.default\" (e.g., \"claude-code.extension\")\n const defaultProvider = config['provider.default'] as string | undefined\n if (defaultProvider) {\n const tool = defaultProvider.split('.')[0]\n return tool as Provider\n }\n\n // Fallback\n return 'copilot'\n}\n\n/**\n * Resolve the effective mode/type for a tool in the context of an IDE.\n */\nexport function resolveProviderMode(\n tool: Provider,\n ide: IdeType,\n config: InspectoSettings,\n): ProviderMode {\n let requestedType: ProviderMode | undefined = undefined\n\n // V2 format: check provider.default for \"tool.mode\"\n const defaultProvider = config['provider.default'] as string | undefined\n if (defaultProvider && defaultProvider.startsWith(`${tool}.`)) {\n const mode = defaultProvider.split('.')[1]\n if (mode === 'extension') requestedType = 'extension'\n if (mode === 'cli') requestedType = 'cli'\n }\n\n requestedType = requestedType ?? DEFAULT_PROVIDER_MODE[tool]\n const valid = VALID_MODES[tool] || [DEFAULT_PROVIDER_MODE[tool]]\n return requestedType && valid.includes(requestedType) ? requestedType : valid[0]!\n}\n\n/**\n * Extract ToolOverrides (binaryPath, args, etc) for Extension consumption.\n */\nexport function extractToolOverrides(\n ide: IdeType,\n config: InspectoSettings,\n): Partial<Record<Provider, ToolOverrides>> {\n const result: Partial<Record<Provider, ToolOverrides>> = {}\n\n if (!config) return result\n\n // Parse new flat `provider.*` format\n for (const [key, value] of Object.entries(config)) {\n if (!key.startsWith('provider.')) continue\n\n // We only process tool specific overrides, ignore `.default`\n if (key === 'provider.default') continue\n\n // Handle `provider.[tool].[mode]`\n const toolIndex = 1\n const modeIndex = 2\n const propIndex = 3\n\n const parts = key.split('.')\n\n if (parts.length >= propIndex + 1) {\n const tool = parts[toolIndex] as Provider\n const mode = parts[modeIndex] as ProviderMode\n const prop = parts[propIndex]\n\n if (!result[tool]) {\n result[tool] = { type: mode }\n }\n\n const overrides = result[tool]!\n\n // If we see config for a mode that differs from what we've initialized,\n // it means both modes have config. In v2, mode is determined by provider.default.\n // We will just accumulate the settings for now and let resolveProviderMode decide the active type.\n\n if (prop === 'bin') overrides.binaryPath = value as string\n if (prop === 'args') overrides.args = value as string[]\n if (prop === 'cwd') overrides.cwd = value as string\n if (prop === 'coldStartDelay') overrides.coldStartDelay = value as number\n }\n }\n\n return result\n}\n\nexport function resolveIntents(serverPrompts?: InspectoPromptsConfig): IntentConfig[] {\n // Start with DEFAULT_INTENTS as base\n const baseMap = new Map<string, IntentConfig>()\n for (const intent of DEFAULT_INTENTS) {\n baseMap.set(intent.id, { ...intent } as IntentConfig)\n }\n\n const defaults = () => Array.from(baseMap.values())\n\n if (!serverPrompts) return defaults()\n\n const isReplace =\n !Array.isArray(serverPrompts) &&\n typeof serverPrompts === 'object' &&\n serverPrompts.$replace === true\n const promptsArray = Array.isArray(serverPrompts)\n ? serverPrompts\n : isReplace\n ? serverPrompts.items\n : []\n\n if (!promptsArray || promptsArray.length === 0) return defaults()\n\n if (isReplace) {\n // $replace: true — exact list, user controls everything\n const result: IntentConfig[] = []\n for (const item of promptsArray) {\n if (typeof item === 'string') {\n if (baseMap.has(item)) {\n result.push(baseMap.get(item)!)\n } else {\n configLogger.warn(\n `Unknown built-in intent id: \"${item}\". Available: ${[...baseMap.keys()].join(', ')}`,\n )\n }\n } else if (typeof item === 'object') {\n if (!item.id) {\n configLogger.warn('Intent object missing required \"id\" field, skipping.')\n continue\n }\n if (item.enabled === false) {\n configLogger.warn(\n `Intent \"${item.id}\" is listed in $replace but has enabled:false — it will be excluded.`,\n )\n continue\n }\n if (!item.aiIntent) {\n configLogger.warn(`Intent \"${item.id}\" is missing required \"aiIntent\".`)\n continue\n }\n result.push(\n (baseMap.has(item.id) ? { ...baseMap.get(item.id)!, ...item } : item) as IntentConfig,\n )\n }\n }\n return result\n }\n\n // Default: append / override mode.\n // - Objects with known id: merge over built-in (or remove if enabled:false)\n // - Objects with unknown id: append as new intent\n // - Strings: not meaningful in append mode (order is fixed to built-in order + appended)\n const merged = Array.from(baseMap.values())\n\n for (const item of promptsArray) {\n if (typeof item === 'string') {\n if (!baseMap.has(item)) {\n configLogger.warn(\n `Unknown built-in intent id: \"${item}\". In append mode, strings have no effect on ordering — use $replace to control order.`,\n )\n }\n // Known string ids are already in merged — nothing to do\n continue\n }\n\n if (typeof item === 'object') {\n if (!item.id) {\n configLogger.warn('Intent object missing required \"id\" field, skipping.')\n continue\n }\n if (!item.aiIntent) {\n configLogger.warn(`Intent \"${item.id}\" is missing required \"aiIntent\".`)\n continue\n }\n const existingIdx = merged.findIndex(i => i.id === item.id)\n if (existingIdx !== -1) {\n if (item.enabled === false) {\n merged.splice(existingIdx, 1)\n } else {\n merged[existingIdx] = { ...merged[existingIdx], ...item } as IntentConfig\n }\n } else {\n if (item.enabled !== false) {\n merged.push(item as IntentConfig)\n }\n }\n }\n }\n\n return merged\n}\n\nlet watchers: fs.FSWatcher[] = []\n\nexport function watchConfig(onReload: () => void, cwd = process.cwd(), gitRoot?: string): void {\n if (isWatching) return\n isWatching = true\n\n // Watch .inspecto/ directories rather than individual files so that newly\n // created files (e.g. prompts.local.json added after server start) are picked up.\n const watchDirs: string[] = [path.join(os.homedir(), '.inspecto')]\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n for (const root of roots) {\n watchDirs.push(path.join(root, '.inspecto'))\n }\n\n const CONFIG_FILES = new Set([\n 'settings.json',\n 'settings.local.json',\n 'prompts.json',\n 'prompts.local.json',\n ])\n\n for (const dir of watchDirs) {\n if (!fs.existsSync(dir)) continue\n try {\n const watcher = fs.watch(dir, async (eventType, filename) => {\n if (!filename || !CONFIG_FILES.has(filename)) return\n loadedConfig = null\n loadedPrompts = null\n loadUserConfigSync(true, cwd, gitRoot)\n await loadPromptsConfig(true, cwd, gitRoot)\n onReload()\n })\n watcher.unref()\n watchers.push(watcher)\n } catch (_e) {\n // ignore watch errors (e.g. unsupported fs)\n }\n }\n}\n\nexport function unwatchConfig(): void {\n for (const watcher of watchers) {\n watcher.close()\n }\n watchers = []\n isWatching = false\n}\n","import type { LogLevel } from '@inspecto-dev/types'\n\nexport interface Logger {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n setLevel?(level: LogLevel): void\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n}\n\n// Very simple implementation of a DEBUG matching string.\n// Supports `DEBUG=inspecto:*` or `DEBUG=inspecto:server,inspecto:ast`\nfunction isDebugEnabled(namespace: string): boolean {\n if (typeof process === 'undefined' || !process.env) return false\n const debugEnv = process.env.DEBUG\n if (!debugEnv) return false\n\n const namespaces = debugEnv.split(',').map(s => s.trim())\n for (const ns of namespaces) {\n if (ns === '*') return true\n if (ns.endsWith('*')) {\n const prefix = ns.slice(0, -1)\n if (namespace.startsWith(prefix)) return true\n } else if (ns === namespace) {\n return true\n }\n }\n return false\n}\n\n// Store global level locally to avoid circular dependency with config.ts\nlet globalLevel: LogLevel = 'warn'\nconst registeredLoggers: Set<Logger> = new Set()\n\nexport function setLoggerGlobalLevel(level: LogLevel) {\n globalLevel = level\n for (const logger of registeredLoggers) {\n if (logger.setLevel) {\n logger.setLevel(level)\n }\n }\n}\n\nexport function createLogger(namespace: string, options?: { logLevel?: LogLevel }): Logger {\n let currentLevel = options?.logLevel ?? globalLevel\n let numericLevel = LOG_LEVELS[currentLevel] ?? 2\n const debugEnabled = isDebugEnabled(namespace)\n\n const logger: Logger = {\n setLevel(level: LogLevel) {\n currentLevel = level\n numericLevel = LOG_LEVELS[level] ?? 2\n },\n info(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.info) {\n console.log(`\\x1b[36m[inspecto]\\x1b[0m ${msg}`, ...args)\n }\n },\n warn(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.warn) {\n console.warn(`\\x1b[33m[inspecto] WARN:\\x1b[0m ${msg}`, ...args)\n }\n },\n error(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.error) {\n console.error(`\\x1b[31m[inspecto] ERROR:\\x1b[0m ${msg}`, ...args)\n }\n },\n debug(msg: string, ...args: any[]) {\n if (debugEnabled) {\n console.log(`\\x1b[90m[${namespace}]\\x1b[0m ${msg}`, ...args)\n }\n },\n }\n\n registeredLoggers.add(logger)\n\n return logger\n}\n","import crypto from 'node:crypto'\nimport { execFileSync } from 'node:child_process'\nimport { launchIDE } from 'launch-ide'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nconst payloadTickets = new Map<string, string>()\n\nexport function createTicket(payload: unknown): string {\n const ticketId = crypto.randomUUID()\n payloadTickets.set(ticketId, JSON.stringify(payload))\n\n setTimeout(\n () => {\n payloadTickets.delete(ticketId)\n },\n 5 * 60 * 1000,\n )\n\n return ticketId\n}\n\nexport function readTicket(ticketId: string): string | undefined {\n return payloadTickets.get(ticketId)\n}\n\nexport function launchURI(uri: string): void {\n try {\n if (process.platform === 'darwin') {\n execFileSync('open', [uri])\n } else if (process.platform === 'win32') {\n execFileSync('cmd', ['/c', 'start', '\"\"', uri])\n } else {\n execFileSync('xdg-open', [uri])\n }\n } catch (e) {\n serverLogger.error('Failed to launch URI via execFileSync, falling back to launchIDE:', e)\n launchIDE({ file: uri })\n }\n}\n","import type {\n IdeType,\n Provider,\n ProviderMode,\n ServerState,\n ToolOverrides,\n} from '@inspecto-dev/types'\nimport {\n extractToolOverrides,\n loadUserConfigSync,\n resolveProviderMode,\n resolveTargetTool,\n} from '../config.js'\nimport { createTicket, launchURI } from './dispatch-transport.js'\n\nexport interface PromptDispatchRuntime {\n resolvedTarget: Provider\n finalIde: string\n mode: ProviderMode\n overrides?: ToolOverrides\n autoSend?: boolean\n}\n\nexport interface PromptDispatchPayload {\n prompt: string\n filePath?: string\n line?: number\n column?: number\n snippet?: string\n}\n\nexport interface PromptDispatchResult {\n success: true\n fallbackPayload: {\n prompt: string\n file?: string\n }\n}\n\nfunction normalizeIdeToken(value: string | undefined): string {\n return (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nexport function resolvePromptDispatchRuntime(\n state: Pick<ServerState, 'projectRoot' | 'cwd' | 'ideInfo'>,\n): PromptDispatchRuntime {\n const userConfig = loadUserConfigSync(false, state.cwd, state.projectRoot)\n const resolvedTarget = resolveTargetTool(userConfig)\n const finalIde = resolveFinalIde(userConfig.ide, state.ideInfo?.ide, state.ideInfo?.scheme)\n const mode = resolveProviderMode(resolvedTarget, finalIde as IdeType, userConfig)\n const overrides =\n extractToolOverrides(finalIde as IdeType, userConfig)[resolvedTarget] || undefined\n\n return {\n resolvedTarget,\n finalIde,\n mode,\n ...(hasOverrides(overrides) ? { overrides } : {}),\n ...(userConfig['prompt.autoSend'] !== undefined\n ? { autoSend: Boolean(userConfig['prompt.autoSend']) }\n : {}),\n }\n}\n\nexport function dispatchPromptThroughIde(\n runtime: PromptDispatchRuntime,\n payload: PromptDispatchPayload,\n): PromptDispatchResult {\n const ticketId = createTicket({\n ide: runtime.finalIde,\n target: runtime.resolvedTarget,\n targetType: runtime.mode,\n prompt: payload.prompt,\n filePath: payload.filePath,\n line: payload.line,\n column: payload.column,\n snippet: payload.snippet,\n overrides: runtime.overrides,\n autoSend: runtime.autoSend,\n })\n\n const params = new URLSearchParams()\n params.set('ticket', ticketId)\n params.set('target', runtime.resolvedTarget)\n\n launchURI(`${runtime.finalIde}://inspecto.inspecto/send?${params.toString()}`)\n\n return {\n success: true,\n fallbackPayload: {\n prompt: payload.prompt,\n ...(payload.filePath ? { file: payload.filePath } : {}),\n },\n }\n}\n\nfunction resolveFinalIde(\n configuredIde: string | undefined,\n activeIde: string | undefined,\n activeIdeScheme: string | undefined,\n): string {\n const configuredIdeMatchesActiveScheme =\n Boolean(configuredIde) &&\n Boolean(activeIdeScheme) &&\n normalizeIdeToken(configuredIde) === normalizeIdeToken(activeIdeScheme)\n\n if (configuredIdeMatchesActiveScheme) {\n return activeIdeScheme!\n }\n\n if (\n configuredIde &&\n activeIdeScheme &&\n normalizeIdeToken(activeIdeScheme).includes(normalizeIdeToken(configuredIde)) === false\n ) {\n return configuredIde\n }\n\n return configuredIde || activeIdeScheme || activeIde || 'vscode'\n}\n\nfunction hasOverrides(overrides: ToolOverrides | undefined): overrides is ToolOverrides {\n return Boolean(overrides && Object.keys(overrides).length > 0)\n}\n","import path from 'node:path'\nimport fs from 'node:fs'\n\nfunction isWindowsAbsolutePath(file: string): boolean {\n return /^[a-zA-Z]:[\\\\/]/.test(file) || /^\\\\\\\\[^\\\\]+\\\\[^\\\\]+/.test(file)\n}\n\nexport function resolveWorkspacePath(file: string, cwd: string): string {\n if (isWindowsAbsolutePath(file)) {\n return path.win32.normalize(file)\n }\n return path.isAbsolute(file) ? path.resolve(file) : path.resolve(cwd, file)\n}\n\nexport function assertPathWithinProject(file: string, projectRoot: string): void {\n let realFile = file\n let realProjectRoot = projectRoot\n try {\n if (fs.existsSync(file)) {\n realFile = fs.realpathSync(file)\n }\n } catch {\n // ignore\n }\n\n try {\n if (fs.existsSync(projectRoot)) {\n realProjectRoot = fs.realpathSync(projectRoot)\n }\n } catch {\n // ignore\n }\n\n if (isWithinPath(file, projectRoot) || isWithinPath(realFile, realProjectRoot)) {\n return\n }\n\n throw new Error(\n `Access denied: File ${normalizeForComparison(realFile)} is outside of project workspace ${normalizeForComparison(realProjectRoot)}`,\n )\n}\n\nfunction tryReadPackageName(packageRoot: string): string | undefined {\n try {\n const packageJsonPath = path.join(packageRoot, 'package.json')\n if (!fs.existsSync(packageJsonPath)) return undefined\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string }\n return typeof packageJson.name === 'string' ? packageJson.name : undefined\n } catch {\n return undefined\n }\n}\n\nfunction findNearestPackageRoot(file: string): string | undefined {\n let current = path.dirname(file)\n\n while (true) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) {\n return undefined\n }\n current = parent\n }\n}\n\nfunction normalizeForComparison(file: string): string {\n return isWindowsAbsolutePath(file) ? path.win32.normalize(file) : path.normalize(file)\n}\n\nfunction pathSeparatorFor(file: string): string {\n return isWindowsAbsolutePath(file) ? path.win32.sep : path.sep\n}\n\nfunction isWithinPath(file: string, root: string): boolean {\n const normalizedFile = normalizeForComparison(file)\n const normalizedRoot = normalizeForComparison(root)\n const separator = pathSeparatorFor(normalizedRoot)\n const rootWithSep = normalizedRoot.endsWith(separator)\n ? normalizedRoot\n : normalizedRoot + separator\n return normalizedFile === normalizedRoot || normalizedFile.startsWith(rootWithSep)\n}\n\nfunction resolveLinkedDependencyEntry(\n projectRoot: string,\n packageName: string,\n): string | undefined {\n const packageSegments = packageName.split('/')\n const dependencyPath = path.join(projectRoot, 'node_modules', ...packageSegments)\n if (!fs.existsSync(dependencyPath)) return undefined\n\n try {\n return fs.realpathSync(dependencyPath)\n } catch {\n return dependencyPath\n }\n}\n\nfunction isLinkedDependencyPath(file: string, projectRoot: string, packageName: string): boolean {\n const linkedDependencyRoot = resolveLinkedDependencyEntry(projectRoot, packageName)\n if (!linkedDependencyRoot) return false\n\n return isWithinPath(file, linkedDependencyRoot)\n}\n\nfunction isLinkedDependencySourcePath(file: string, projectRoot: string): boolean {\n const packageRoot = findNearestPackageRoot(file)\n if (!packageRoot) return false\n\n const packageName = tryReadPackageName(packageRoot)\n if (!packageName) return false\n\n return isLinkedDependencyPath(file, projectRoot, packageName)\n}\n\nexport function assertPathWithinIdeOpenScope(file: string, projectRoot: string): void {\n try {\n assertPathWithinProject(file, projectRoot)\n return\n } catch {\n if (isLinkedDependencySourcePath(file, projectRoot)) {\n return\n }\n throw new Error(`Access denied: File is outside of project workspace`)\n }\n}\n","import type {\n AnnotationSessionEvent,\n AnnotationSessionStatus,\n AnnotationWorkSession,\n AppendAnnotationThreadMessageInput,\n CreateAnnotationWorkSessionInput,\n} from '@inspecto-dev/types'\n\nexport interface AnnotationSessionStoreOptions {\n now?: () => number\n createId?: () => string\n}\n\nexport interface AnnotationSessionListOptions {\n status?: AnnotationSessionStatus | AnnotationSessionStatus[]\n}\n\nexport interface ClaimNextAnnotationSessionOptions {\n timeoutMs?: number\n}\n\nexport interface ClaimNextAnnotationSessionResult {\n session: AnnotationWorkSession | null\n timedOut: boolean\n matchedExisting: boolean\n event?: AnnotationSessionEvent['type']\n}\n\nexport interface AnnotationSessionStore {\n createSession(input: CreateAnnotationWorkSessionInput): AnnotationWorkSession\n getSession(id: string): AnnotationWorkSession | null\n listSessions(options?: AnnotationSessionListOptions): AnnotationWorkSession[]\n claimNextSession(\n options?: ClaimNextAnnotationSessionOptions,\n ): Promise<ClaimNextAnnotationSessionResult>\n appendMessage(id: string, input: AppendAnnotationThreadMessageInput): AnnotationWorkSession | null\n updateStatus(id: string, status: AnnotationSessionStatus): AnnotationWorkSession | null\n subscribe(listener: AnnotationSessionListener): () => void\n clear(): void\n}\n\nexport type AnnotationSessionListener = (event: AnnotationSessionEvent) => void\n\nconst DEFAULT_STATUS: AnnotationSessionStatus = 'pending'\n\nexport function createAnnotationSessionStore(\n options: AnnotationSessionStoreOptions = {},\n): AnnotationSessionStore {\n const sessions = new Map<string, AnnotationWorkSession>()\n const listeners = new Set<AnnotationSessionListener>()\n const now = options.now ?? (() => Date.now())\n const createId = options.createId ?? createRandomId\n\n function findNewestMatchingSession(\n statuses: Set<AnnotationSessionStatus> | null,\n ): AnnotationWorkSession | null {\n return (\n [...sessions.values()]\n .filter(session => (statuses ? statuses.has(session.status) : true))\n .sort((left, right) => right.updatedAt - left.updatedAt)[0] ?? null\n )\n }\n\n function updateSessionStatus(\n id: string,\n status: AnnotationSessionStatus,\n ): AnnotationWorkSession | null {\n const session = sessions.get(id)\n if (!session) return null\n\n const timestamp = now()\n session.status = status\n session.updatedAt = timestamp\n\n if (status === 'acknowledged') {\n session.acknowledgedAt = timestamp\n }\n if (status === 'resolved') {\n session.resolvedAt = timestamp\n }\n\n emit({ type: 'session-status-updated', session })\n return cloneSession(session)\n }\n\n function claimSession(\n id: string,\n statuses: Set<AnnotationSessionStatus> | null,\n ): AnnotationWorkSession | null {\n const session = sessions.get(id)\n if (!session || (statuses && !statuses.has(session.status))) return null\n if (session.status === 'acknowledged') return cloneSession(session)\n return updateSessionStatus(id, 'acknowledged')\n }\n\n function emit(event: AnnotationSessionEvent): void {\n const snapshot = cloneSession(event.session)\n for (const listener of listeners) {\n listener({ type: event.type, session: snapshot })\n }\n }\n\n const store: AnnotationSessionStore = {\n createSession(input) {\n const timestamp = now()\n const session: AnnotationWorkSession = {\n id: createId(),\n instruction: input.instruction?.trim() ?? '',\n annotations: cloneArray(input.annotations),\n ...(input.deliveryMode ? { deliveryMode: input.deliveryMode } : {}),\n status: DEFAULT_STATUS,\n messages: cloneArray(input.messages ?? []),\n createdAt: timestamp,\n updatedAt: timestamp,\n ...(input.runtimeContext ? { runtimeContext: cloneValue(input.runtimeContext) } : {}),\n ...(input.cssContextPrompt?.trim()\n ? { cssContextPrompt: input.cssContextPrompt.trim() }\n : {}),\n ...(input.pageUrl ? { pageUrl: input.pageUrl } : {}),\n ...(input.route ? { route: input.route } : {}),\n }\n\n sessions.set(session.id, session)\n emit({ type: 'session-created', session })\n return cloneSession(session)\n },\n\n getSession(id) {\n const session = sessions.get(id)\n return session ? cloneSession(session) : null\n },\n\n listSessions(options = {}) {\n const statuses = normalizeStatuses(options.status)\n return [...sessions.values()]\n .filter(session => (statuses ? statuses.has(session.status) : true))\n .sort((left, right) => right.updatedAt - left.updatedAt)\n .map(session => cloneSession(session))\n },\n\n async claimNextSession(options = {}) {\n const statuses = normalizeStatuses(DEFAULT_STATUS)\n const existingSession = findNewestMatchingSession(statuses)\n if (existingSession) {\n return {\n session: claimSession(existingSession.id, statuses),\n timedOut: false,\n matchedExisting: true,\n }\n }\n\n const timeoutMs = normalizeTimeoutMs(options.timeoutMs)\n if (timeoutMs === 0) {\n return {\n session: null,\n timedOut: true,\n matchedExisting: false,\n }\n }\n\n return await new Promise<ClaimNextAnnotationSessionResult>(resolve => {\n let settled = false\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n const finish = (result: ClaimNextAnnotationSessionResult): void => {\n if (settled) return\n settled = true\n unsubscribe()\n if (timeout) {\n clearTimeout(timeout)\n }\n resolve(result)\n }\n\n const unsubscribe = this.subscribe(event => {\n const session = claimSession(event.session.id, statuses)\n if (!session) return\n finish({\n session,\n timedOut: false,\n matchedExisting: false,\n event: event.type,\n })\n })\n\n if (timeoutMs !== null) {\n timeout = setTimeout(() => {\n finish({\n session: null,\n timedOut: true,\n matchedExisting: false,\n })\n }, timeoutMs)\n }\n })\n },\n\n appendMessage(id, input) {\n const session = sessions.get(id)\n if (!session) return null\n\n const timestamp = now()\n session.messages.push({\n id: createId(),\n role: input.role,\n text: input.text,\n createdAt: timestamp,\n })\n session.updatedAt = timestamp\n\n if (input.role === 'agent' && isPendingLikeStatus(session.status)) {\n session.status = 'in_progress'\n }\n\n emit({ type: 'session-message-appended', session })\n return cloneSession(session)\n },\n\n updateStatus(id, status) {\n return updateSessionStatus(id, status)\n },\n\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n\n clear() {\n sessions.clear()\n listeners.clear()\n },\n }\n\n return store\n}\n\nexport const annotationSessionStore = createAnnotationSessionStore()\n\nfunction normalizeStatuses(\n status: AnnotationSessionListOptions['status'],\n): Set<AnnotationSessionStatus> | null {\n if (!status) return null\n return new Set(Array.isArray(status) ? status : [status])\n}\n\nfunction normalizeTimeoutMs(value: number | undefined): number | null {\n if (value === undefined) return null\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.floor(value))\n}\n\nfunction isPendingLikeStatus(status: AnnotationSessionStatus): boolean {\n return status === 'pending' || status === 'acknowledged'\n}\n\nexport function hasAgentReply(session: Pick<AnnotationWorkSession, 'messages'>): boolean {\n return session.messages.some(message => message.role === 'agent' && Boolean(message.text?.trim()))\n}\n\nfunction createRandomId(): string {\n return `annotation-session-${Math.random().toString(36).slice(2, 10)}`\n}\n\nfunction cloneSession(session: AnnotationWorkSession): AnnotationWorkSession {\n return cloneValue(session)\n}\n\nfunction cloneArray<T>(value: T[]): T[] {\n return cloneValue(value)\n}\n\nfunction cloneValue<T>(value: T): T {\n if (typeof structuredClone === 'function') {\n return structuredClone(value)\n }\n return JSON.parse(JSON.stringify(value)) as T\n}\n","import type {\n Annotation,\n AnnotationIntent,\n AnnotationDeliveryMode,\n AiErrorCode,\n AnnotationWorkSessionSummary,\n RuntimeContextEnvelope,\n RuntimeEvidenceRecord,\n SendAnnotationsToAiRequest,\n SendAnnotationsToAiResponse,\n ServerState,\n} from '@inspecto-dev/types'\nimport { dispatchPromptThroughIde, resolvePromptDispatchRuntime } from './dispatch-runtime.js'\nimport { assertPathWithinProject, resolveWorkspacePath } from './path-guards.js'\nimport type { AnnotationSessionStore } from './session-store.js'\nimport { annotationSessionStore } from './session-store.js'\n\nexport interface NormalizedAnnotationTarget {\n file: string\n line: number\n column: number\n label?: string\n selector?: string\n snippet?: string\n}\n\nexport interface NormalizedAnnotation {\n index: number\n note: string\n intent: AnnotationIntent\n targets: NormalizedAnnotationTarget[]\n}\n\nexport interface NormalizedAnnotationBatch {\n instruction: string\n annotations: NormalizedAnnotation[]\n runtimeContext?: RuntimeContextEnvelope\n cssContextPrompt?: string\n}\n\nclass AnnotationDispatchError extends Error {\n readonly errorCode: AiErrorCode\n\n constructor(message: string, errorCode: AiErrorCode) {\n super(message)\n this.name = 'AnnotationDispatchError'\n this.errorCode = errorCode\n }\n}\n\nexport async function dispatchAnnotationsToAi(\n req: SendAnnotationsToAiRequest,\n state: Pick<ServerState, 'projectRoot' | 'cwd' | 'ideInfo'>,\n store: AnnotationSessionStore = annotationSessionStore,\n): Promise<SendAnnotationsToAiResponse> {\n try {\n validateAnnotationDispatchRequest(req, state)\n const batch = normalizeAnnotationBatch(req)\n const prompt = buildAnnotationBatchPrompt(batch)\n const deliveryMode = normalizeDeliveryMode(req.deliveryMode)\n const session = store.createSession({\n instruction: batch.instruction,\n annotations: toSessionAnnotations(batch.annotations),\n deliveryMode,\n ...(batch.runtimeContext ? { runtimeContext: batch.runtimeContext } : {}),\n ...(batch.cssContextPrompt ? { cssContextPrompt: batch.cssContextPrompt } : {}),\n })\n const representativeTarget = batch.annotations[0]?.targets[0]\n const dispatchResult =\n deliveryMode === 'ide'\n ? dispatchPromptThroughIde(resolvePromptDispatchRuntime(state), {\n prompt,\n ...(representativeTarget?.file ? { filePath: representativeTarget.file } : {}),\n ...(representativeTarget?.line ? { line: representativeTarget.line } : {}),\n ...(representativeTarget?.column ? { column: representativeTarget.column } : {}),\n })\n : { success: true as const }\n\n return {\n ...dispatchResult,\n session: toSessionSummary(session),\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n errorCode: getAnnotationDispatchErrorCode(error),\n }\n }\n}\n\nfunction normalizeDeliveryMode(input: AnnotationDeliveryMode | undefined): AnnotationDeliveryMode {\n return input === 'agent' ? 'agent' : 'ide'\n}\n\nfunction toSessionAnnotations(annotations: NormalizedAnnotation[]): Annotation[] {\n return annotations.map(annotation => ({\n id: `annotation-${annotation.index}`,\n note: annotation.note,\n intent: annotation.intent,\n targets: annotation.targets.map((target, targetIndex) => ({\n id: `annotation-${annotation.index}-target-${targetIndex + 1}`,\n label: target.label ?? 'Unknown target',\n location: {\n file: target.file,\n line: target.line,\n column: target.column,\n },\n ...(target.selector ? { selector: target.selector } : {}),\n ...(target.snippet ? { snippet: target.snippet } : {}),\n rect: {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n },\n })),\n }))\n}\n\nfunction toSessionSummary(session: {\n id: string\n status: AnnotationWorkSessionSummary['status']\n createdAt: number\n updatedAt: number\n}): AnnotationWorkSessionSummary {\n return {\n id: session.id,\n status: session.status,\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n }\n}\n\nexport function validateAnnotationDispatchRequest(\n req: SendAnnotationsToAiRequest,\n state: Pick<ServerState, 'projectRoot' | 'cwd'>,\n): void {\n if (!req.annotations.length) {\n throw new AnnotationDispatchError('At least one annotation is required.', 'INVALID_REQUEST')\n }\n\n for (const annotation of req.annotations) {\n if (!annotation.targets.length) {\n throw new AnnotationDispatchError(\n 'Each annotation must include at least one target.',\n 'INVALID_REQUEST',\n )\n }\n\n for (const target of annotation.targets) {\n const absolutePath = resolveWorkspacePath(target.location.file, state.cwd)\n assertPathWithinProject(absolutePath, state.projectRoot)\n }\n }\n}\n\nexport function normalizeAnnotationBatch(\n req: SendAnnotationsToAiRequest,\n): NormalizedAnnotationBatch {\n return {\n instruction: req.instruction?.trim() ?? '',\n ...(req.runtimeContext ? { runtimeContext: req.runtimeContext } : {}),\n ...(req.cssContextPrompt?.trim() ? { cssContextPrompt: req.cssContextPrompt.trim() } : {}),\n annotations: req.annotations.map((annotation, index) => ({\n index: index + 1,\n note: annotation.note.trim(),\n intent: annotation.intent,\n targets: annotation.targets.map(target => ({\n file: target.location.file,\n line: target.location.line,\n column: target.location.column,\n ...(target.label ? { label: target.label } : {}),\n ...(target.selector ? { selector: target.selector } : {}),\n ...(target.snippet ? { snippet: target.snippet } : {}),\n })),\n })),\n }\n}\n\nexport function buildAnnotationBatchPrompt(batch: NormalizedAnnotationBatch): string {\n const body = buildSelectedElementsPrompt(batch.annotations)\n const prompt = batch.instruction ? `${batch.instruction}\\n\\n${body}` : body\n\n return appendCssContextSection(\n appendRuntimeContextSection(prompt, batch.runtimeContext),\n batch.cssContextPrompt,\n )\n}\n\nfunction appendCssContextSection(prompt: string, cssContextPrompt: string | undefined): string {\n if (!cssContextPrompt) return prompt\n return `${prompt}\\n\\n${cssContextPrompt}`\n}\n\nfunction buildSelectedElementsPrompt(annotations: NormalizedAnnotation[]): string {\n const lines = ['Selected elements:']\n\n for (const annotation of annotations) {\n const trimmedNote = annotation.note.trim()\n for (const target of annotation.targets) {\n const targetLabel = (target.label || 'Unknown target').trim() || 'Unknown target'\n lines.push(`- ${targetLabel}`)\n lines.push(`file=${target.file}:${target.line}:${target.column}`)\n if (trimmedNote) {\n lines.push(`note=${trimmedNote}`)\n }\n }\n }\n\n if (lines.length === 1) {\n lines.push('- None')\n }\n\n return lines.join('\\n')\n}\n\nfunction appendRuntimeContextSection(\n prompt: string,\n runtimeContext: RuntimeContextEnvelope | undefined,\n): string {\n if (!runtimeContext?.records.length) {\n return prompt\n }\n\n return `${prompt}\\n\\n${buildRuntimeContextSection(runtimeContext.records)}`\n}\n\nfunction buildRuntimeContextSection(records: RuntimeEvidenceRecord[]): string {\n return ['Relevant runtime context:', ...records.map(formatRuntimeRecord)].join('\\n')\n}\n\nfunction formatRuntimeRecord(record: RuntimeEvidenceRecord): string {\n const requestSummary =\n record.kind === 'failed-request'\n ? `request=${record.request?.method ?? 'GET'} ${record.request?.pathname ?? record.request?.url ?? 'unknown'} status=${record.request?.status ?? 'unknown'}`\n : `occurrences=${record.occurrenceCount}`\n const reasonSummary = record.relevanceReasons.length\n ? record.relevanceReasons.join('; ')\n : 'timing-based'\n const stackSummary = record.stack\n ? `\\n stack=${record.stack.split('\\n').slice(0, 5).join(' | ')}`\n : ''\n\n return [\n `- [${record.kind}] ${record.message}`,\n ` relevance=${record.relevanceLevel} (${reasonSummary})`,\n ` ${requestSummary}`,\n stackSummary,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction getAnnotationDispatchErrorCode(error: unknown): AiErrorCode {\n if (error instanceof AnnotationDispatchError) return error.errorCode\n if (error instanceof Error && error.message.includes('outside of project workspace')) {\n return 'FORBIDDEN_PATH'\n }\n return 'UNKNOWN'\n}\n","import type { IdeType, InspectoConfig, ServerState } from '@inspecto-dev/types'\nimport { loadPromptsConfig, loadUserConfigSync, resolveIntents } from '../config.js'\n\nexport async function buildClientConfig(\n serverState: ServerState,\n): Promise<InspectoConfig & { autoSend: boolean }> {\n const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot)\n const promptsConfig = await loadPromptsConfig(false, serverState.cwd, serverState.configRoot)\n const effectiveIde = (userConfig.ide ?? 'vscode') as IdeType\n\n let info: any\n if (!serverState.ideInfo) {\n info = { ide: effectiveIde }\n } else {\n const { scheme: _scheme, ...rest } = serverState.ideInfo as any\n info = rest\n }\n\n return {\n ...info,\n prompts: resolveIntents(promptsConfig),\n hotKeys: userConfig['inspector.hotKey'] ?? 'alt',\n annotateDeliveryMode: userConfig['annotate.deliveryMode'] ?? 'both',\n includeSnippet: userConfig['prompt.includeSnippet'] ?? false,\n runtimeContext: {\n enabled: true,\n preview: true,\n maxRuntimeErrors: 3,\n maxFailedRequests: 2,\n },\n autoSend: userConfig['prompt.autoSend'] ?? false,\n }\n}\n","import { execFileSync } from 'node:child_process'\nimport { Editor, launchIDE } from 'launch-ide'\nimport type { OpenFileRequest, ServerState } from '@inspecto-dev/types'\nimport { loadUserConfigSync } from '../config.js'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\nimport { assertPathWithinIdeOpenScope, resolveWorkspacePath } from './path-guards.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nconst VSCODE_FAMILY_SCHEMES = [\n 'vscode',\n 'vscode-insiders',\n 'cursor',\n 'windsurf',\n 'trae',\n 'trae-cn',\n 'vscodium',\n 'codebuddy',\n 'codebuddy-cn',\n 'codebuddycn',\n 'antigravity',\n]\n\nfunction normalizeIdeToken(value: string | undefined): string {\n return (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nexport function handleOpenFileRequest(\n body: OpenFileRequest,\n serverState: ServerState,\n): { success: true } {\n const absolutePath = resolveWorkspacePath(body.file, serverState.cwd)\n\n assertPathWithinIdeOpenScope(absolutePath, serverState.projectRoot)\n\n const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot)\n const configuredIde = userConfig.ide\n const activeIde = serverState.ideInfo?.ide\n const activeIdeScheme = serverState.ideInfo?.scheme\n\n const configuredIdeMatchesActiveScheme =\n Boolean(configuredIde) &&\n Boolean(activeIdeScheme) &&\n normalizeIdeToken(configuredIde) === normalizeIdeToken(activeIdeScheme)\n\n const rawEditorHint = configuredIdeMatchesActiveScheme\n ? activeIdeScheme!\n : configuredIde || activeIde || activeIdeScheme || 'code'\n\n if (\n configuredIde &&\n activeIdeScheme &&\n normalizeIdeToken(activeIdeScheme).includes(normalizeIdeToken(configuredIde)) === false\n ) {\n serverLogger.warn(\n `Active IDE is ${activeIdeScheme}, but config forces ${configuredIde}. Using configured IDE.`,\n )\n }\n\n let editorHint = rawEditorHint\n if (rawEditorHint === 'vscode') editorHint = 'code'\n else if (rawEditorHint === 'vscode-insiders') editorHint = 'code-insiders'\n else if (rawEditorHint === 'vscodium') editorHint = 'codium'\n else if (rawEditorHint === 'trae-cn' || rawEditorHint === 'trae') editorHint = 'trae'\n\n serverLogger.debug(\n `SOURCE_OPEN: activeIde=${activeIde}, activeIdeScheme=${activeIdeScheme}, configuredIde=${configuredIde} -> rawEditorHint=${rawEditorHint}, finalEditorHint=${editorHint}`,\n )\n\n if (VSCODE_FAMILY_SCHEMES.includes(rawEditorHint)) {\n let normalizedPath = absolutePath.replace(/\\\\/g, '/')\n if (!normalizedPath.startsWith('/')) {\n normalizedPath = '/' + normalizedPath\n }\n const encodedPath = encodeURI(normalizedPath)\n const uri = `${rawEditorHint}://file${encodedPath}:${body.line}:${body.column}`\n serverLogger.debug(`SOURCE_OPEN: Bypassing launchIDE, using URI scheme directly: ${uri}`)\n\n try {\n if (process.platform === 'darwin') {\n execFileSync('open', [uri])\n } else if (process.platform === 'win32') {\n execFileSync('cmd', ['/c', 'start', '\"\"', uri])\n } else {\n execFileSync('xdg-open', [uri])\n }\n } catch (e) {\n serverLogger.error(`Failed to launch URI for SOURCE_OPEN (${uri}):`, e)\n launchIDE({\n file: absolutePath,\n line: body.line,\n column: body.column,\n editor: editorHint as Editor,\n type: process.platform === 'darwin' ? 'open' : 'exec',\n })\n }\n } else {\n launchIDE({\n file: absolutePath,\n line: body.line,\n column: body.column,\n editor: editorHint as Editor,\n type: process.platform === 'darwin' ? 'open' : 'exec',\n })\n }\n\n return { success: true }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { execSync } from 'node:child_process'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nexport function resolveProjectRoot(): string {\n const cwd = process.cwd()\n let gitRoot: string\n try {\n gitRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8' }).trim()\n } catch (e) {\n serverLogger.warn('Failed to resolve git root via git rev-parse:', e)\n gitRoot = cwd\n }\n\n const visited = new Set<string>()\n const search = (start: string, stop: string) => {\n let current = start\n while (!visited.has(current)) {\n visited.add(current)\n if (fs.existsSync(path.join(current, '.inspecto'))) return current\n if (current === stop) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return null\n }\n\n const cwdMatch = search(cwd, path.parse(cwd).root)\n if (cwdMatch) return cwdMatch\n\n const repoMatch = search(gitRoot, path.parse(gitRoot).root)\n if (repoMatch) return repoMatch\n\n return gitRoot\n}\n","import { loadUserConfigSync } from '../config.js'\n\nexport function resolveServerHost(cwd: string, configRoot: string): string {\n const userConfig = loadUserConfigSync(false, cwd, configRoot)\n const configuredHost = userConfig['server.host']?.trim()\n if (configuredHost) return configuredHost\n\n // Vitest sandbox environments can reject binding 0.0.0.0 even when the\n // same process can bind loopback successfully. Prefer loopback for tests so\n // plugin e2e coverage reflects real runtime behavior instead of sandbox\n // policy noise.\n if (process.env['VITEST']) return '127.0.0.1'\n return '127.0.0.1'\n}\n\nexport function resolvePublicServerUrl(args: {\n cwd: string\n configRoot: string\n port: number\n}): string {\n const userConfig = loadUserConfigSync(false, args.cwd, args.configRoot)\n const configuredPublicUrl = userConfig['server.publicUrl']?.trim()\n if (configuredPublicUrl) {\n return configuredPublicUrl.replace(/\\/$/, '')\n }\n\n const host = resolveServerHost(args.cwd, args.configRoot)\n return `http://${host}:${args.port}`\n}\n","import { createRequire } from 'node:module'\n\n// Safely resolve the client module without breaking ESM/CJS or bundling\nexport const resolveClientModule = () => {\n try {\n return createRequire(import.meta.url).resolve('@inspecto-dev/core')\n } catch {\n try {\n return require.resolve('@inspecto-dev/core')\n } catch {\n console.warn(\n '[inspecto] Could not resolve @inspecto-dev/core — falling back to bare specifier',\n )\n return '@inspecto-dev/core'\n }\n }\n}\n","export function getWebpackHtmlScript(serverPort: number, publicServerUrl?: string) {\n return `\nwindow.__AI_INSPECTOR_PORT__ = ${serverPort};\nwindow.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\n window.addEventListener('load', () => {\n if (window.InspectoClient) {\n window.InspectoClient.mountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n });\n }\n });\n`\n}\n\nexport function getWebpackAssetScript(serverPort: number, publicServerUrl?: string) {\n return `\nif (typeof window !== 'undefined') {\n window.__AI_INSPECTOR_PORT__ = ${serverPort};\n window.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\n const _initInspecto = () => {\n if (window.InspectoClient) {\n window.InspectoClient.mountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n });\n } else {\n setTimeout(_initInspecto, 100);\n }\n };\n if (document.readyState === 'complete') {\n _initInspecto();\n } else {\n window.addEventListener('load', _initInspecto);\n }\n}\n`\n}\n\nexport function injectWebpack(\n compiler: any,\n serverPortFn: () => Promise<number>,\n publicServerUrlFn: (port: number) => string,\n resolveClientModule: () => string,\n) {\n const inspectoClientPath = resolveClientModule()\n\n // Inject the client logic directly using the absolute path\n if (compiler.webpack && compiler.webpack.EntryPlugin) {\n // Webpack 5+\n new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, {\n name: undefined,\n }).apply(compiler)\n }\n\n compiler.hooks.compilation.tap('inspecto-overlay', (compilation: any) => {\n // Find HtmlWebpackPlugin (standard Webpack)\n const HtmlWebpackPlugin = compiler.options.plugins.find(\n (p: any) => p && p.constructor && p.constructor.name === 'HtmlWebpackPlugin',\n )\n if (HtmlWebpackPlugin) {\n const hooks = (HtmlWebpackPlugin.constructor as any).getHooks(compilation)\n hooks.alterAssetTagGroups.tapPromise('inspecto-overlay', async (data: any) => {\n const port = await serverPortFn()\n const publicServerUrl = publicServerUrlFn(port)\n data.headTags.unshift({\n tagName: 'script',\n voidTag: false,\n meta: { plugin: 'inspecto-overlay' },\n innerHTML: getWebpackHtmlScript(port, publicServerUrl),\n })\n return data\n })\n } else {\n // Fallback for frameworks like Next.js that don't use HtmlWebpackPlugin\n if (compilation.hooks.processAssets) {\n // Webpack 5+\n compilation.hooks.processAssets.tapPromise(\n {\n name: 'inspecto-overlay',\n stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n async (assets: any) => {\n const port = await serverPortFn()\n const publicServerUrl = publicServerUrlFn(port)\n\n // Only inject into the main client entry chunks (e.g. main-app, main.js, umi.js)\n const mainAssetKey = Object.keys(assets).find(\n key =>\n key.endsWith('.js') &&\n (key.includes('main') || key.includes('app') || key.includes('umi')),\n )\n if (!mainAssetKey) return\n\n const originalSource = assets[mainAssetKey].source()\n assets[mainAssetKey] = new compiler.webpack.sources.RawSource(\n getWebpackAssetScript(port, publicServerUrl) + '\\n' + originalSource,\n )\n },\n )\n }\n }\n })\n}\n","import { getWebpackHtmlScript } from './webpack.js'\n\nexport function injectRspack(\n compiler: any,\n serverPortFn: () => Promise<number>,\n resolveClientModule: () => string,\n) {\n const inspectoClientPath = resolveClientModule()\n\n // Use the exact same entry injection strategy as Webpack\n new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, {}).apply(compiler)\n\n compiler.hooks.compilation.tap('inspecto-overlay', (compilation: any) => {\n const HtmlRspackPlugin = compiler.options.plugins.find(\n (p: any) => p && p.constructor && p.constructor.name === 'HtmlRspackPlugin',\n )\n if (HtmlRspackPlugin) {\n const hooks = (HtmlRspackPlugin.constructor as any).getHooks(compilation)\n hooks.alterAssetTagGroups.tapPromise('inspecto-overlay', async (data: any) => {\n const port = await serverPortFn()\n\n data.headTags.unshift({\n tagName: 'script',\n voidTag: false,\n meta: { plugin: 'inspecto-overlay' },\n innerHTML: getWebpackHtmlScript(port),\n })\n return data\n })\n }\n })\n}\n","export function getViteVirtualModuleScript(serverPort: number, publicServerUrl?: string) {\n return `\nimport { mountInspector } from '@inspecto-dev/core';\nwindow.__AI_INSPECTOR_PORT__ = ${serverPort};\nwindow.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\nmountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n});\n`\n}\n\nexport const VITE_VIRTUAL_MODULE_ID = '\\0virtual:inspecto-client'\nexport const VITE_VIRTUAL_IMPORT_ID = '/@id/__x00__virtual:inspecto-client'\n"],"mappings":";;;;;;;;AAAA,SAAS,sBAAsB;;;ACgBxB,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAE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OAAe,OAAO,uBAAuB,IAAI,KAAK,UAAU,IAAI;AAG7E,cAAM,MAAM,OAAO,YAAY,cAAc,sBAAsB;AACnE,YAAI,IAAK,QAAO,YAAY,iBAAiB,GAAG;AAAA,MAClD;AAAA,MAEA,mBAAmB,MAAM;AACvB,YAAI,gBAAgB,CAAC,WAAY,QAAO;AACxC,eAAO;AAAA,UACL;AAAA,UACA,MAAM;AAAA,YACJ;AAAA,cACE,KAAK;AAAA,cACL,OAAO,EAAE,MAAM,SAAS;AAAA,cACxB,UAAU,WAAW,sBAAsB;AAAA,YAC7C;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,iBAAiB,IAAI;AACnB,UAAI,gBAAgB,CAAC,GAAI,QAAO;AAChC,aAAO,gBAAgB,IAAI,OAAO;AAAA,IACpC;AAAA,IAEA,UAAU,MAAM,IAAI;AAClB,UAAI,gBAAgB,CAAC,GAAI,QAAO;AAEhC,YAAM,EAAE,SAAS,IAAI,yBAAyB,EAAE;AAEhD,YAAM,SAAS,gBAAgB;AAAA,QAC7B;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAED,UAAI,CAAC,UAAU,CAAC,OAAO,QAAS,QAAO;AAEvC,aAAO;AAAA,QACL,MAAM,OAAO;AAAA,QACb,KAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAEM,IAAM,WAAW;AACjB,IAAM,aAAa,eAAe;AAClC,IAAM,gBAAoD,eAAe;AACzE,IAAM,eAAe,eAAe;AACpC,IAAM,eAAe,eAAe;AACpC,IAAM,gBAAgB,eAAe;AAG5C,IAAO,cAAQ;","names":["path","MagicString","path","path","MagicString","p","MagicString","s","MagicString","i","MagicString","m","s","i","f","w","v","walk","w","s","MagicString","path","fs","path","os","crypto","path","parser","traverse_","traverse","fs","path","s","path","fs","i","path","fs","options","resolve","serverState","execFileSync","launchIDE","serverLogger","normalizeIdeToken","serverState","execFileSync","launchIDE","fs","path","serverLogger","fs","path","serverLogger","path","os","crypto","fs","serverLogger","resolve","resolve","path","serverLogger","resolveClientModule","p","resolveClientModule","p"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/transform/utils.ts","../src/transform/index.ts","../src/transform/transform-jsx.ts","../src/transform/transform-vue.ts","../src/transform/transform-svelte.ts","../src/transform/transform-astro.ts","../../../node_modules/.pnpm/@astrojs+compiler@3.0.1/node_modules/@astrojs/compiler/dist/chunk-W5DTLHV4.js","../../../node_modules/.pnpm/@astrojs+compiler@3.0.1/node_modules/@astrojs/compiler/dist/node/sync.js","../src/server/index.ts","../src/server/snippet.ts","../src/config.ts","../src/utils/logger.ts","../src/server/dispatch-transport.ts","../src/server/dispatch-runtime.ts","../src/server/path-guards.ts","../src/server/annotation-dispatch.ts","../src/server/session-store.ts","../src/server/client-config.ts","../src/server/open-file.ts","../src/server/project-root.ts","../src/server/server-url.ts","../src/injectors/utils.ts","../src/injectors/webpack.ts","../src/injectors/rspack.ts","../src/injectors/vite.ts"],"sourcesContent":["import { createUnplugin } from 'unplugin'\nimport type { UnpluginOptions } from '@inspecto-dev/types'\nimport { extractTransformFilePath, shouldTransform } from './transform/utils.js'\nimport { transformRouter, transformJsx } from './transform/index.js'\nimport { startServer, serverState } from './server/index.js'\nimport { resolvePublicServerUrl } from './server/server-url.js'\nimport { resolveClientModule } from './injectors/utils.js'\nimport { injectWebpack } from './injectors/webpack.js'\nimport { injectRspack } from './injectors/rspack.js'\nimport { setGlobalLogLevel } from './config.js'\nimport { createLogger } from './utils/logger.js'\nimport {\n getViteVirtualModuleScript,\n VITE_VIRTUAL_MODULE_ID,\n VITE_VIRTUAL_IMPORT_ID,\n} from './injectors/vite.js'\n\nimport type { ViteDevServer } from 'vite'\n\nexport type { UnpluginOptions }\n\nconst DEFAULT_OPTIONS: Required<UnpluginOptions> = {\n include: [],\n exclude: [],\n escapeTags: [],\n pathType: 'absolute',\n attributeName: 'data-inspecto',\n logLevel: 'warn',\n}\n\nconst DEFAULT_PORT = 5678\n\nconst InspectoPlugin = createUnplugin<UnpluginOptions | undefined>((userOptions = {}) => {\n const options: Required<UnpluginOptions> = {\n ...DEFAULT_OPTIONS,\n ...userOptions,\n }\n\n // Sync global log level based on user config\n setGlobalLogLevel(options.logLevel)\n const pluginLogger = createLogger('inspecto:plugin', { logLevel: options.logLevel })\n\n // Skip everything in production\n const isProduction = process.env['NODE_ENV'] === 'production'\n\n let projectRoot = process.cwd()\n let serverPort: number | null = null\n\n // Helper to ensure server is started\n const ensureServer = async () => {\n if (serverPort === null) {\n serverPort = await startServer()\n }\n return serverPort\n }\n\n const getPublicServerUrl = (port: number) =>\n resolvePublicServerUrl({\n cwd: serverState.cwd || process.cwd(),\n configRoot: serverState.configRoot || projectRoot,\n port,\n })\n\n return {\n name: 'inspecto-overlay',\n enforce: 'pre',\n\n buildStart() {\n if (isProduction) return\n projectRoot = serverState.cwd || process.cwd()\n\n // For pure bundlers (Rollup, Esbuild) that don't have devServer hooks\n // we need to ensure the server starts early enough.\n ensureServer().catch(err => pluginLogger.error('Failed to start server:', err))\n },\n\n buildEnd() {\n // Server cleanup is handled by process exit (server is unref'd, port file\n // removed via process.once('exit')). Calling stopServer() here would break\n // esbuild watch mode (which fires buildEnd after every incremental rebuild)\n // and is unnecessary for Vite/Rspack which manage their own lifecycles.\n },\n\n webpack: compiler => {\n if (isProduction) return\n injectWebpack(compiler, ensureServer, getPublicServerUrl, resolveClientModule)\n },\n\n rspack: compiler => {\n if (isProduction) return\n injectRspack(compiler, ensureServer, resolveClientModule)\n },\n\n vite: {\n config(config) {\n if (isProduction) return config\n return {\n ...config,\n define: {\n ...config.define,\n __AI_INSPECTOR_PORT__: JSON.stringify(DEFAULT_PORT), // Placeholder, rewritten in configureServer\n },\n }\n },\n\n resolveId(id) {\n if (id === 'virtual:inspecto-client') {\n return VITE_VIRTUAL_MODULE_ID\n }\n return null\n },\n\n load(id) {\n if (id === VITE_VIRTUAL_MODULE_ID) {\n // serverPort is guaranteed to be set by the time Vite requests this module\n // (configureServer awaits ensureServer before the dev server accepts requests)\n return getViteVirtualModuleScript(\n serverPort ?? DEFAULT_PORT,\n getPublicServerUrl(serverPort ?? DEFAULT_PORT),\n )\n }\n return null\n },\n\n async configureServer(server: ViteDevServer) {\n if (isProduction) return\n const port = await ensureServer()\n if (!server.config.define) {\n ;(server.config as any).define = {}\n }\n ;(server.config as any).define['__AI_INSPECTOR_PORT__'] = JSON.stringify(port)\n // Invalidate the virtual module so load() re-runs with the correct port\n // (guards against the race where load() was called before configureServer resolved)\n const mod = server.moduleGraph.getModuleById(VITE_VIRTUAL_MODULE_ID)\n if (mod) server.moduleGraph.invalidateModule(mod)\n },\n\n transformIndexHtml(html) {\n if (isProduction || !serverPort) return html\n return {\n html,\n tags: [\n {\n tag: 'script',\n attrs: { type: 'module' },\n children: `import '${VITE_VIRTUAL_IMPORT_ID}';`,\n },\n ],\n }\n },\n },\n\n transformInclude(id) {\n if (isProduction || !id) return false\n return shouldTransform(id, options)\n },\n\n transform(code, id) {\n if (isProduction || !id) return null\n\n const { filePath } = extractTransformFilePath(id)\n\n const result = transformRouter({\n filePath,\n source: code,\n projectRoot,\n pluginOptions: options,\n })\n\n if (!result || !result.changed) return null\n\n return {\n code: result.code,\n map: result.map,\n }\n },\n }\n})\n\nexport const unplugin = InspectoPlugin\nexport const vitePlugin = InspectoPlugin.vite\nexport const webpackPlugin: (options?: UnpluginOptions) => any = InspectoPlugin.webpack\nexport const rspackPlugin = InspectoPlugin.rspack\nexport const rollupPlugin = InspectoPlugin.rollup\nexport const esbuildPlugin = InspectoPlugin.esbuild\nexport { transformJsx, transformRouter }\nexport { transformAstro } from './transform/transform-astro.js'\nexport default InspectoPlugin\n","import type { UnpluginOptions } from '@inspecto-dev/types'\nimport type MagicString from 'magic-string'\n\nexport interface TransformResult {\n code: string\n map: ReturnType<MagicString['generateMap']> | null\n changed: boolean\n}\n\nexport interface NormalizedTransformTarget {\n requestId: string\n filePath: string\n wrapped: boolean\n}\n\n/** Default tags whose JSX elements should NOT receive data-inspecto attributes */\nexport const DEFAULT_ESCAPE_TAGS = new Set([\n 'template',\n 'script',\n 'style',\n // React special elements\n 'Fragment',\n 'React.Fragment',\n 'StrictMode',\n 'React.StrictMode',\n 'Suspense',\n 'React.Suspense',\n 'Profiler',\n 'React.Profiler',\n // React transitions\n 'Transition',\n 'TransitionGroup',\n // Vue built-in components\n 'KeepAlive',\n 'Teleport',\n 'Suspense',\n // Vue router built-ins\n 'RouterView',\n 'RouterLink',\n 'NuxtPage',\n 'NuxtLink',\n])\n\n/** File extensions that contain JSX/TSX syntax */\nexport const JSX_EXTENSIONS = new Set(['.jsx', '.tsx', '.js', '.ts', '.mjs', '.mts'])\n\nfunction normalizeWebpackModuleRequest(id: string): string {\n return id.replace(/!+$/, '').replace(/^\\((?:app-pages-browser|rsc|ssr)\\)\\/\\.\\//, '')\n}\n\nfunction extractNextModuleRequest(id: string): string | undefined {\n if (!id.includes('next-flight-client-entry-loader.js?')) {\n return undefined\n }\n\n const queryIndex = id.indexOf('?')\n if (queryIndex === -1) {\n return undefined\n }\n\n const params = new URLSearchParams(id.slice(queryIndex + 1).replace(/!+$/, ''))\n for (const entry of params.getAll('modules')) {\n try {\n const parsed = JSON.parse(entry) as { request?: unknown }\n if (typeof parsed.request === 'string' && parsed.request.length > 0) {\n return parsed.request\n }\n } catch {\n continue\n }\n }\n\n return undefined\n}\n\nexport function extractTransformFilePath(requestId: string): NormalizedTransformTarget {\n const normalizedRequestId = normalizeWebpackModuleRequest(requestId)\n const nextModuleRequest = extractNextModuleRequest(normalizedRequestId)\n if (nextModuleRequest) {\n return {\n requestId,\n filePath: nextModuleRequest,\n wrapped: true,\n }\n }\n\n const lastLoaderSeparator = normalizedRequestId.lastIndexOf('!')\n const resourceRequest =\n lastLoaderSeparator >= 0\n ? normalizedRequestId.slice(lastLoaderSeparator + 1)\n : normalizedRequestId\n const queryIndex = resourceRequest.indexOf('?')\n const filePath = queryIndex >= 0 ? resourceRequest.slice(0, queryIndex) : resourceRequest\n\n return {\n requestId,\n filePath,\n wrapped: filePath !== requestId,\n }\n}\n\n/**\n * Determine if a file should be transformed.\n * Always skips node_modules and dist directories.\n */\nexport function shouldTransform(filePath: string, _options: Required<UnpluginOptions>): boolean {\n const resolvedFilePath = extractTransformFilePath(filePath).filePath\n\n // Never transform in production\n if (process.env['NODE_ENV'] === 'production') return false\n\n // Skip node_modules always\n if (resolvedFilePath.includes('node_modules')) return false\n\n // Skip virtual modules\n if (resolvedFilePath.startsWith('\\x00')) return false\n\n // Skip dist/build directories\n if (/[/\\\\](dist|build|\\.next|\\.nuxt)[/\\\\]/.test(resolvedFilePath)) return false\n\n // Skip non-code files (like .html, .css)\n const ext = resolvedFilePath.split('.').pop()?.toLowerCase()\n if (ext && !['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts', 'vue', 'svelte', 'astro'].includes(ext)) {\n return false\n }\n\n // Check user-defined exclude patterns\n // (picomatch integration — see index.ts for how options.exclude is applied)\n\n return true\n}\n\n/**\n * Build the escape tags set from user options merged with defaults.\n */\nexport function buildEscapeTagsSet(escapeTags?: string[]): Set<string> {\n const merged = new Set(DEFAULT_ESCAPE_TAGS)\n if (escapeTags) {\n for (const tag of escapeTags) {\n merged.add(tag)\n }\n }\n return merged\n}\n\n/**\n * Format a source location value for the data-inspecto attribute.\n * Format: \"filepath:line:column\"\n */\nexport function formatAttrValue(file: string, line: number, column: number): string {\n return `${file}:${line}:${column}`\n}\n","import path from 'node:path'\nimport type { UnpluginOptions } from '@inspecto-dev/types'\nimport { transformJsx } from './transform-jsx.js'\nimport { transformVue } from './transform-vue.js'\nimport { transformSvelte } from './transform-svelte.js'\nimport { transformAstro } from './transform-astro.js'\nimport { JSX_EXTENSIONS, type TransformResult } from './utils.js'\n\nexport interface RouterOptions {\n filePath: string\n source: string\n projectRoot: string\n pluginOptions: Required<UnpluginOptions>\n}\n\n/**\n * Route a file to the appropriate transform based on extension.\n * Returns null if no transform applies.\n */\nexport function transformRouter(options: RouterOptions): TransformResult | null {\n const { filePath, source, projectRoot, pluginOptions } = options\n const ext = path.extname(filePath).toLowerCase()\n\n if (JSX_EXTENSIONS.has(ext)) {\n return transformJsx({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Vue SFC ──────────────────────────────────────────────────────────────\n if (ext === '.vue') {\n return transformVue({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Svelte ───────────────────────────────────────────────────────────────\n if (ext === '.svelte') {\n return transformSvelte({\n filePath,\n source,\n projectRoot,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n // ── Astro ────────────────────────────────────────────────────────────────\n if (ext === '.astro') {\n return transformAstro({\n filePath,\n source,\n escapeTags: pluginOptions.escapeTags,\n pathType: pluginOptions.pathType,\n attributeName: pluginOptions.attributeName,\n })\n }\n\n return null\n}\n// Export transforms for testing\nexport { transformJsx, transformVue, transformSvelte, transformAstro }\n","import * as parser from '@babel/parser'\nimport traverse_ from '@babel/traverse'\n// Support both ESM default and CommonJS module.exports\nconst traverse =\n typeof traverse_ === 'function' ? traverse_ : (traverse_ as any).default || traverse_\nimport type { NodePath } from '@babel/traverse'\nimport type { JSXOpeningElement } from '@babel/types'\nimport MagicString from 'magic-string'\nimport path from 'node:path'\nimport type { PathType } from '@inspecto-dev/types'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformJsxOptions {\n filePath: string\n source: string\n projectRoot: string\n escapeTags?: string[]\n pathType?: PathType\n attributeName?: string\n}\n\n/**\n * Transform JSX/TSX source code by injecting data-inspecto attributes.\n */\nexport function transformJsx(options: TransformJsxOptions): TransformResult {\n const {\n filePath,\n source,\n projectRoot,\n escapeTags,\n pathType = 'absolute',\n attributeName = 'data-inspecto',\n } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // Resolve the file path based on pathType config\n const resolvedPath =\n pathType === 'absolute'\n ? path.resolve(filePath)\n : path.relative(projectRoot, path.resolve(filePath))\n\n // Normalize path separators on Windows\n const normalizedPath = resolvedPath.replace(/\\\\/g, '/')\n\n let ast: ReturnType<typeof parser.parse>\n try {\n ast = parser.parse(source, {\n sourceType: 'module',\n plugins: [\n 'jsx',\n 'typescript',\n 'decorators-legacy',\n 'classProperties',\n 'optionalChaining',\n 'nullishCoalescingOperator',\n 'importMeta',\n ],\n errorRecovery: true,\n })\n } catch {\n // If parsing fails, return source unchanged\n return { code: source, map: null, changed: false }\n }\n\n const ms = new MagicString(source)\n let changed = false\n\n traverse(ast, {\n JSXOpeningElement(nodePath: NodePath<JSXOpeningElement>) {\n const node = nodePath.node\n\n // Skip elements that already have the attribute\n const alreadyHasAttr = node.attributes.some(\n attr =>\n attr.type === 'JSXAttribute' &&\n attr.name.type === 'JSXIdentifier' &&\n attr.name.name === attributeName,\n )\n if (alreadyHasAttr) return\n\n // Get element tag name\n const nameNode = node.name\n let tagName: string\n if (nameNode.type === 'JSXIdentifier') {\n tagName = nameNode.name\n } else if (nameNode.type === 'JSXMemberExpression') {\n const objName = nameNode.object.type === 'JSXIdentifier' ? nameNode.object.name : ''\n const propName = nameNode.property.type === 'JSXIdentifier' ? nameNode.property.name : ''\n tagName = objName && propName ? `${objName}.${propName}` : objName\n } else {\n tagName = ''\n }\n\n // Skip escaped tags\n if (escapeTagsSet.has(tagName)) return\n\n // Get position from AST location\n const loc = node.loc\n if (!loc) return\n\n const { line, column } = loc.start\n // Babel uses 0-based columns, convert to 1-based\n const attrValue = formatAttrValue(normalizedPath, line, column + 1)\n\n // Determine the best insertion position for the attribute\n // When a JSX element has type arguments (e.g. <Component<string> />),\n // inserting after `node.name.end` might inject inside the generic bracket `<`.\n // The safest place to insert is right before the first attribute,\n // or right before the closing slash/bracket if there are no attributes.\n let insertPos: number | null | undefined = null\n if (node.attributes && node.attributes.length > 0) {\n const firstAttr = node.attributes[0]\n if (firstAttr && firstAttr.start != null) {\n insertPos = firstAttr.start\n }\n }\n\n if (insertPos == null) {\n // Find the start of the closing bracket or self-closing slash\n // We know node.end is the index right after the '>'\n // So we look backwards. But Babel AST doesn't give us exact token positions\n // for the closing tag easily.\n // For a safe fallback, we use node.typeParameters?.end || node.name.end\n if (node.typeParameters && node.typeParameters.end != null) {\n insertPos = node.typeParameters.end\n } else if (node.name.end != null) {\n insertPos = node.name.end\n }\n }\n\n if (insertPos == null) return\n\n ms.appendLeft(\n insertPos,\n ` ${attributeName}=\"${attrValue}\"${node.attributes && node.attributes.length > 0 ? '' : ' '}`,\n )\n changed = true\n },\n })\n\n if (!changed) {\n return { code: source, map: null, changed: false }\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true, source: filePath }),\n changed: true,\n }\n}\n","import * as vueCompiler from '@vue/compiler-dom'\nimport { parse as parseSFC } from '@vue/compiler-sfc'\nimport type { ElementNode, AttributeNode } from '@vue/compiler-core'\nimport { NodeTypes } from '@vue/compiler-core'\nimport MagicString from 'magic-string'\nimport path from 'node:path'\nimport type { PathType } from '@inspecto-dev/types'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformVueOptions {\n filePath: string\n source: string\n projectRoot: string\n escapeTags?: string[]\n pathType?: PathType\n attributeName?: string\n}\n\n/**\n * Transform Vue SFC source by injecting data-inspecto attributes\n * into template elements.\n *\n * Strategy:\n * 1. Locate the <template> block in the SFC source\n * 2. Parse only the template block with @vue/compiler-dom\n * 3. Walk ElementNode nodes in the AST\n * 4. For each eligible element, inject the attribute using MagicString\n * at the exact offset within the original source\n */\nexport function transformVue(options: TransformVueOptions): TransformResult {\n const {\n filePath,\n source,\n projectRoot,\n escapeTags,\n pathType = 'absolute',\n attributeName = 'data-inspecto',\n } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // Resolve path\n const resolvedPath =\n pathType === 'absolute'\n ? path.resolve(filePath)\n : path.relative(projectRoot, path.resolve(filePath))\n\n const normalizedPath = resolvedPath.replace(/\\\\/g, '/')\n\n // ── Find <template> block boundaries ──────────────────────────────────────\n // Use @vue/compiler-sfc to parse the file and extract the template block.\n // This is much safer than regex for handling nested templates.\n const { descriptor, errors } = parseSFC(source, {\n filename: filePath,\n sourceMap: false,\n ignoreEmpty: true,\n })\n\n if (errors.length > 0 || !descriptor.template) {\n return { code: source, map: null, changed: false }\n }\n\n const templateContent = descriptor.template.content\n const templateBlockStart = descriptor.template.loc.start.offset\n\n // ── Parse template block ───────────────────────────────────────────────────\n let ast: vueCompiler.RootNode\n try {\n ast = vueCompiler.parse(templateContent, {\n parseMode: 'html',\n // Preserve source locations relative to templateContent\n onError: () => {\n /* ignore non-fatal parse errors */\n },\n })\n } catch {\n return { code: source, map: null, changed: false }\n }\n\n const ms = new MagicString(source)\n let changed = false\n\n // ── Walk AST ───────────────────────────────────────────────────────────────\n walkElement(ast, node => {\n // Skip non-element nodes\n if (node.type !== NodeTypes.ELEMENT) return\n\n const tagName = node.tag\n\n // Skip escaped tags\n if (escapeTagsSet.has(tagName)) return\n\n // Skip <template> wrapper itself (it's the root, not a real element)\n if (tagName === 'template' && node === ast.children[0]) return\n\n // Skip elements that already have the attribute (idempotency)\n const alreadyHasAttr = node.props.some(\n (p): p is AttributeNode => p.type === NodeTypes.ATTRIBUTE && p.name === attributeName,\n )\n if (alreadyHasAttr) return\n\n // node.loc is relative to templateContent — add templateBlockStart offset\n const loc = node.loc\n if (!loc) return\n\n const { line, column } = loc.start\n\n // Calculate absolute line and column in the original source\n // @vue/compiler-dom uses 1-based line and 1-based column\n const templateStartLoc = descriptor.template!.loc.start\n const absoluteLine = templateStartLoc.line + line - 1\n const absoluteColumn = line === 1 ? templateStartLoc.column + column - 1 : column\n\n const attrValue = formatAttrValue(normalizedPath, absoluteLine, absoluteColumn)\n\n // Find insert position: right after the tag name in the original source\n // node.loc.start.offset is 0-based offset within templateContent\n const tagNameEnd = loc.start.offset + tagName.length + 1 // +1 for '<'\n const absoluteOffset = templateBlockStart + tagNameEnd\n\n ms.appendLeft(absoluteOffset, ` ${attributeName}=\"${attrValue}\"`)\n changed = true\n })\n\n if (!changed) {\n return { code: source, map: null, changed: false }\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true, source: filePath }),\n changed: true,\n }\n}\n\n// ── AST walker ────────────────────────────────────────────────────────────────\n\ntype AnyNode = vueCompiler.RootNode | vueCompiler.TemplateChildNode\n\nfunction walkElement(node: AnyNode, visitor: (node: ElementNode) => void): void {\n if (node.type === NodeTypes.ELEMENT) {\n visitor(node)\n for (const child of node.children) {\n walkElement(child as AnyNode, visitor)\n }\n } else if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n walkElement(child as AnyNode, visitor)\n }\n }\n}\n","import MagicString from 'magic-string'\nimport { parse as parseSvelte } from 'svelte/compiler'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformSvelteOptions {\n filePath: string\n source: string\n projectRoot?: string\n pathType?: 'absolute' | 'relative'\n escapeTags?: string[]\n attributeName?: string\n}\n\nfunction walk(node: any, visitor: { enter: (n: any) => void }) {\n if (!node || typeof node !== 'object') return\n visitor.enter(node)\n\n for (const key in node) {\n if (key === 'parent' || key === 'prev' || key === 'next') continue\n const value = node[key]\n if (Array.isArray(value)) {\n value.forEach(child => {\n if (child && typeof child === 'object') walk(child, visitor)\n })\n } else if (value && typeof value === 'object') {\n walk(value, visitor)\n }\n }\n}\n\nexport function transformSvelte(options: TransformSvelteOptions): TransformResult {\n const { filePath, source, escapeTags, attributeName = 'data-inspecto' } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n // svelte parse doesn't support ts or scss/less\n // so replace the content of <script></script> and <style></style> with space\n // to avoid parser errors while preserving character offsets.\n let replacedContent = source\n const scriptRegex =\n /<script(?:\\s+[a-zA-Z-]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^>\\s]*))?)?>[\\s\\S]*?<\\/script>/gi\n const styleRegex =\n /<style(?:\\s+[a-zA-Z-]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^>\\s]*))?)?>[\\s\\S]*?<\\/style>/gi\n\n const scriptMatches = source.match(scriptRegex) || []\n const styleMatches = source.match(styleRegex) || []\n\n ;[...scriptMatches, ...styleMatches].forEach(match => {\n // Replace with exact same number of spaces to preserve offsets\n replacedContent = replacedContent.replace(match, ' '.repeat(match.length))\n })\n\n let ast: any\n try {\n ast = parseSvelte(replacedContent)\n } catch {\n // Graceful fallback for parse errors\n return { code: source, map: null, changed: false }\n }\n\n const s = new MagicString(source)\n let changed = false\n\n function countLines(text: string, position: number): number {\n let lines = 0\n for (let i = 0; i < position; i++) {\n if (text[i] === '\\n') lines++\n }\n return lines\n }\n\n const root = ast.html || ast.fragment || ast\n\n walk(root, {\n enter(node: any) {\n if (\n node.type === 'Element' ||\n node.type === 'RegularElement' ||\n node.type === 'InlineComponent' ||\n node.type === 'Component'\n ) {\n const tagName = node.name || ''\n\n if (\n tagName &&\n !escapeTagsSet.has(tagName.toLowerCase()) &&\n !node.attributes?.some((attr: any) => attr.name === attributeName)\n ) {\n const insertPosition = node.start + tagName.length + 1\n const line = countLines(source, node.start) + 1\n const lastNewLine = source.lastIndexOf('\\n', node.start - 1)\n const column = lastNewLine === -1 ? node.start + 1 : node.start - lastNewLine\n\n const attrValue = formatAttrValue(filePath, line, column)\n const addition = ` ${attributeName}=\"${attrValue}\"`\n\n s.appendLeft(insertPosition, addition)\n changed = true\n }\n }\n },\n })\n\n return {\n code: s.toString(),\n map: changed ? s.generateMap({ source: filePath, includeContent: true }) : null,\n changed,\n }\n}\n","import MagicString from 'magic-string'\nimport { parse as parseAstro } from '@astrojs/compiler/sync'\nimport { buildEscapeTagsSet, formatAttrValue, type TransformResult } from './utils.js'\n\nexport interface TransformAstroOptions {\n filePath: string\n source: string\n pathType?: 'absolute' | 'relative'\n escapeTags?: string[]\n attributeName?: string\n}\n\nfunction walk(node: any, visitor: { enter: (n: any) => void }) {\n if (!node || typeof node !== 'object') return\n visitor.enter(node)\n\n if (Array.isArray(node.children)) {\n for (const child of node.children) {\n walk(child, visitor)\n }\n }\n}\n\nexport function transformAstro(options: TransformAstroOptions): TransformResult {\n const { filePath, source, escapeTags, attributeName = 'data-inspecto' } = options\n\n const escapeTagsSet = buildEscapeTagsSet(escapeTags)\n\n let ast: any\n try {\n ast = parseAstro(source, { position: true }).ast\n } catch (_err) {\n return { code: source, map: null, changed: false }\n }\n\n const s = new MagicString(source)\n let changed = false\n\n walk(ast, {\n enter(node: any) {\n // Element or Component in Astro AST\n if (node.type === 'element' || node.type === 'component') {\n const tagName = node.name\n\n if (\n tagName &&\n !escapeTagsSet.has(tagName) &&\n !node.attributes?.some((attr: any) => attr.name === attributeName)\n ) {\n const startOffset = node.position?.start?.offset ?? -1\n if (startOffset === -1) return\n\n // Find the exact `<` before or at the startOffset\n let tagStartIndex = startOffset\n while (tagStartIndex >= 0 && source[tagStartIndex] !== '<') {\n tagStartIndex--\n }\n\n if (tagStartIndex >= 0) {\n const substringAfterTag = source.substring(tagStartIndex)\n const escapedTagName = tagName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const strictRegex = new RegExp(`^<\\\\s*${escapedTagName}(?=\\\\s|/|>)`, 'i')\n const strictMatch = substringAfterTag.match(strictRegex)\n\n if (strictMatch) {\n const insertPosition = tagStartIndex + strictMatch[0].length\n const line = node.position.start.line\n const column = node.position.start.column\n\n const attrValue = formatAttrValue(filePath, line, column)\n const addition = ` ${attributeName}=\"${attrValue}\"`\n\n s.appendLeft(insertPosition, addition)\n changed = true\n }\n }\n }\n }\n },\n })\n\n return {\n code: s.toString(),\n map: changed ? s.generateMap({ source: filePath, includeContent: true }) : null,\n changed,\n }\n}\n","import g from\"crypto\";import _ from\"fs\";import{TextDecoder as b,TextEncoder as v}from\"util\";globalThis.fs||Object.defineProperty(globalThis,\"fs\",{value:_});globalThis.process||Object.defineProperties(globalThis,\"process\",{value:process});globalThis.crypto||Object.defineProperty(globalThis,\"crypto\",{value:g.webcrypto?g.webcrypto:{getRandomValues(m){return g.randomFillSync(m)}}});globalThis.performance||Object.defineProperty(globalThis,\"performance\",{value:{now(){let[m,o]=process.hrtime();return m*1e3+o/1e6}}});var y=new v(\"utf-8\"),w=new b(\"utf-8\");var d=class{constructor(){this.argv=[\"js\"],this.env={},this.exit=t=>{t!==0&&console.warn(\"exit code:\",t)},this._exitPromise=new Promise(t=>{this._resolveExitPromise=t}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let o=(t,e)=>{this.mem.setUint32(t+0,e,!0),this.mem.setUint32(t+4,Math.floor(e/4294967296),!0)},n=t=>{let e=this.mem.getUint32(t+0,!0),s=this.mem.getInt32(t+4,!0);return e+s*4294967296},r=t=>{let e=this.mem.getFloat64(t,!0);if(e===0)return;if(!isNaN(e))return e;let s=this.mem.getUint32(t,!0);return this._values[s]},l=(t,e)=>{if(typeof e==\"number\"&&e!==0){if(isNaN(e)){this.mem.setUint32(t+4,2146959360,!0),this.mem.setUint32(t,0,!0);return}this.mem.setFloat64(t,e,!0);return}if(e===void 0){this.mem.setFloat64(t,0,!0);return}let i=this._ids.get(e);i===void 0&&(i=this._idPool.pop(),i===void 0&&(i=this._values.length),this._values[i]=e,this._goRefCounts[i]=0,this._ids.set(e,i)),this._goRefCounts[i]++;let a=0;switch(typeof e){case\"object\":e!==null&&(a=1);break;case\"string\":a=2;break;case\"symbol\":a=3;break;case\"function\":a=4;break}this.mem.setUint32(t+4,2146959360|a,!0),this.mem.setUint32(t,i,!0)},c=t=>{let e=n(t+0),s=n(t+8);return new Uint8Array(this._inst.exports.mem.buffer,e,s)},f=t=>{let e=n(t+0),s=n(t+8),i=new Array(s);for(let a=0;a<s;a++)i[a]=r(e+a*8);return i},u=t=>{let e=n(t+0),s=n(t+8);return w.decode(new DataView(this._inst.exports.mem.buffer,e,s))},h=Date.now()-performance.now();this.importObject={gojs:{\"runtime.wasmExit\":t=>{t>>>=0;let e=this.mem.getInt32(t+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(e)},\"runtime.wasmWrite\":t=>{t>>>=0;let e=n(t+8),s=n(t+16),i=this.mem.getInt32(t+24,!0);_.writeSync(e,new Uint8Array(this._inst.exports.mem.buffer,s,i))},\"runtime.resetMemoryDataView\":t=>{t>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},\"runtime.nanotime1\":t=>{t>>>=0,o(t+8,(h+performance.now())*1e6)},\"runtime.walltime\":t=>{t>>>=0;let e=new Date().getTime();o(t+8,e/1e3),this.mem.setInt32(t+16,e%1e3*1e6,!0)},\"runtime.scheduleTimeoutEvent\":t=>{t>>>=0;let e=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(e,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(e);)console.warn(\"scheduleTimeoutEvent: missed timeout event\"),this._resume()},n(t+8)+1)),this.mem.setInt32(t+16,e,!0)},\"runtime.clearTimeoutEvent\":t=>{t>>>=0;let e=this.mem.getInt32(t+8,!0);clearTimeout(this._scheduledTimeouts.get(e)),this._scheduledTimeouts.delete(e)},\"runtime.getRandomData\":t=>{t>>>=0,globalThis.crypto.getRandomValues(c(t+8))},\"syscall/js.finalizeRef\":t=>{t>>>=0;let e=this.mem.getUint32(t+8,!0);if(this._goRefCounts[e]--,this._goRefCounts[e]===0){let s=this._values[e];this._values[e]=null,this._ids.delete(s),this._idPool.push(e)}},\"syscall/js.stringVal\":t=>{t>>>=0,l(t+24,u(t+8))},\"syscall/js.valueGet\":t=>{t>>>=0;let e=Reflect.get(r(t+8),u(t+16));t=this._inst.exports.getsp()>>>0,l(t+32,e)},\"syscall/js.valueSet\":t=>{t>>>=0,Reflect.set(r(t+8),u(t+16),r(t+32))},\"syscall/js.valueDelete\":t=>{t>>>=0,Reflect.deleteProperty(r(t+8),u(t+16))},\"syscall/js.valueIndex\":t=>{t>>>=0,l(t+24,Reflect.get(r(t+8),n(t+16)))},\"syscall/js.valueSetIndex\":t=>{t>>>=0,Reflect.set(r(t+8),n(t+16),r(t+24))},\"syscall/js.valueCall\":t=>{t>>>=0;try{let e=r(t+8),s=Reflect.get(e,u(t+16)),i=f(t+32),a=Reflect.apply(s,e,i);t=this._inst.exports.getsp()>>>0,l(t+56,a),this.mem.setUint8(t+64,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+56,e),this.mem.setUint8(t+64,0)}},\"syscall/js.valueInvoke\":t=>{t>>>=0;try{let e=r(t+8),s=f(t+16),i=Reflect.apply(e,void 0,s);t=this._inst.exports.getsp()>>>0,l(t+40,i),this.mem.setUint8(t+48,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+40,e),this.mem.setUint8(t+48,0)}},\"syscall/js.valueNew\":t=>{t>>>=0;try{let e=r(t+8),s=f(t+16),i=Reflect.construct(e,s);t=this._inst.exports.getsp()>>>0,l(t+40,i),this.mem.setUint8(t+48,1)}catch(e){t=this._inst.exports.getsp()>>>0,l(t+40,e),this.mem.setUint8(t+48,0)}},\"syscall/js.valueLength\":t=>{t>>>=0,o(t+16,Number.parseInt(r(t+8).length))},\"syscall/js.valuePrepareString\":t=>{t>>>=0;let e=y.encode(String(r(t+8)));l(t+16,e),o(t+24,e.length)},\"syscall/js.valueLoadString\":t=>{t>>>=0;let e=r(t+8);c(t+16).set(e)},\"syscall/js.valueInstanceOf\":t=>{t>>>=0,this.mem.setUint8(t+24,r(t+8)instanceof r(t+16)?1:0)},\"syscall/js.copyBytesToGo\":t=>{t>>>=0;let e=c(t+8),s=r(t+32);if(!(s instanceof Uint8Array||s instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=s.subarray(0,e.length);e.set(i),o(t+40,i.length),this.mem.setUint8(t+48,1)},\"syscall/js.copyBytesToJS\":t=>{t>>>=0;let e=r(t+8),s=c(t+16);if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=s.subarray(0,e.length);e.set(i),o(t+40,i.length),this.mem.setUint8(t+48,1)},debug:t=>{console.log(t)}}}}async run(o){if(!(o instanceof WebAssembly.Instance))throw new Error(\"Go.run: WebAssembly.Instance expected\");this._inst=o,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[Number.NaN,0,null,!0,!1,globalThis,this],this._goRefCounts=new Array(this._values.length).fill(Number.POSITIVE_INFINITY),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[globalThis,5],[this,6]]),this._idPool=[],this.exited=!1;let n=4096,r=h=>{let t=n,e=y.encode(`${h}\\0`);return new Uint8Array(this.mem.buffer,n,e.length).set(e),n+=e.length,n%8!==0&&(n+=8-n%8),t},l=this.argv.length,c=[];this.argv.forEach(h=>{c.push(r(h))}),c.push(0),Object.keys(this.env).sort().forEach(h=>{c.push(r(`${h}=${this.env[h]}`))}),c.push(0);let u=n;c.forEach(h=>{this.mem.setUint32(n,h,!0),this.mem.setUint32(n+4,0,!0),n+=8}),this._inst.exports.run(l,u),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error(\"Go program has already exited\");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(o){let n=this;return function(){let r={id:o,this:this,args:arguments};return n._pendingEvent=r,n._resume(),r.result}}};export{d as a};\n","import{a as c}from\"../chunk-W5DTLHV4.js\";import{readFileSync as p}from\"fs\";import{fileURLToPath as m}from\"url\";function i(){return s||(s=f()),s}var s,l=(e,t)=>i().transform(e,t),w=(e,t)=>i().parse(e,t),h=(e,t)=>i().convertToTSX(e,t);function f(){let e=new c,t=v(m(new URL(\"../astro.wasm\",import.meta.url)),e.importObject);e.run(t);let o=globalThis[\"@astrojs/compiler\"];return{transform:(n,a)=>{try{return o.transform(n,a||{})}catch(r){throw s=void 0,r}},parse:(n,a)=>{try{let r=o.parse(n,a||{});return{...r,ast:JSON.parse(r.ast)}}catch(r){throw s=void 0,r}},convertToTSX:(n,a)=>{try{let r=o.convertToTSX(n,a||{});return{...r,map:JSON.parse(r.map)}}catch(r){throw s=void 0,r}}}}function v(e,t){let o=p(e);return new WebAssembly.Instance(new WebAssembly.Module(o),t)}export{h as convertToTSX,w as parse,f as startRunningService,l as transform};\n","import http from 'node:http'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport os from 'node:os'\nimport crypto from 'node:crypto'\nimport portfinder from 'portfinder'\nimport type {\n AnnotationSessionEvent,\n AnnotationSessionStatus,\n AnnotationSessionClaimRequest,\n AnnotationSessionReplyRequest,\n AnnotationSessionResolveRequest,\n ServerState,\n OpenFileRequest,\n SendToAiRequest,\n SendToAiResponse,\n SendAnnotationsToAiRequest,\n SendAnnotationsToAiResponse,\n} from '@inspecto-dev/types'\nimport { INSPECTO_API_PATHS } from '@inspecto-dev/types'\nimport { extractSnippet } from './snippet.js'\nimport { dispatchAnnotationsToAi } from './annotation-dispatch.js'\nimport { readTicket } from './dispatch-transport.js'\nimport { dispatchPromptThroughIde, resolvePromptDispatchRuntime } from './dispatch-runtime.js'\nimport { assertPathWithinProject, resolveWorkspacePath } from './path-guards.js'\nimport { buildClientConfig } from './client-config.js'\nimport { handleOpenFileRequest } from './open-file.js'\nimport { resolveProjectRoot, resolveWorkspaceRoot } from './project-root.js'\nimport { resolveServerHost } from './server-url.js'\nimport { annotationSessionStore, hasAgentReply } from './session-store.js'\nimport { watchConfig, unwatchConfig, getGlobalLogLevel } from '../config.js'\nimport { createLogger } from '../utils/logger.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\nconst PORT_FILE_NAME = 'inspecto.port.json'\nconst LEGACY_PORT_FILE_NAME = 'inspecto.port'\n\nexport const serverState: ServerState = {\n port: null,\n running: false,\n projectRoot: '',\n configRoot: '',\n cwd: process.cwd(),\n}\n\nlet serverInstance: http.Server | null = null\n\nfunction getPortFilePath(): string {\n return path.join(os.tmpdir(), PORT_FILE_NAME)\n}\n\nfunction getProjectRootHash(): string | null {\n if (!serverState.projectRoot) return null\n return crypto.createHash('md5').update(serverState.projectRoot).digest('hex')\n}\n\nfunction readPortData(portFile: string): Record<string, number> {\n if (!fs.existsSync(portFile)) return {}\n try {\n return JSON.parse(fs.readFileSync(portFile, 'utf-8')) as Record<string, number>\n } catch {\n return {}\n }\n}\n\nfunction writeProjectPort(port: number): void {\n const rootHash = getProjectRootHash()\n if (!rootHash) return\n\n const portFile = getPortFilePath()\n const portData = readPortData(portFile)\n portData[rootHash] = port\n fs.writeFileSync(portFile, JSON.stringify(portData, null, 2), 'utf-8')\n}\n\nfunction removeProjectPort(): void {\n const rootHash = getProjectRootHash()\n if (!rootHash) return\n\n const portFile = getPortFilePath()\n if (!fs.existsSync(portFile)) return\n\n const portData = readPortData(portFile)\n delete portData[rootHash]\n\n if (Object.keys(portData).length === 0) {\n fs.unlinkSync(portFile)\n } else {\n fs.writeFileSync(portFile, JSON.stringify(portData, null, 2), 'utf-8')\n }\n}\n\nexport async function startServer(): Promise<number> {\n if (serverState.running && serverState.port !== null) {\n return serverState.port\n }\n\n // Resolve project root at server start time so process.cwd() reflects the\n // actual project directory, not the module load-time cwd.\n serverState.projectRoot = resolveProjectRoot()\n serverState.configRoot = resolveWorkspaceRoot()\n serverState.cwd = process.cwd()\n const serverHost = resolveServerHost(serverState.cwd, serverState.configRoot)\n\n portfinder.basePort = 5678\n const port = await portfinder.getPortPromise()\n\n // Watch for user config changes to trigger hot-reloads internally if needed\n watchConfig(\n () => {\n serverLogger.info('user config reloaded.')\n },\n serverState.cwd,\n serverState.configRoot,\n )\n\n serverInstance = http.createServer((req, res) => {\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type')\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204)\n res.end()\n return\n }\n\n const url = new URL(req.url ?? '/', `http://localhost:${port}`)\n handleRequest(url, req, res).catch(err => {\n serverLogger.error('server error:', err)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(err) }))\n })\n })\n\n await new Promise<void>((resolve, reject) => {\n serverInstance!.listen(port, serverHost, () => {\n serverInstance!.unref() // Allow process to exit\n resolve()\n })\n serverInstance!.once('error', reject)\n })\n\n // Add persistent error handler after successful startup\n serverInstance!.on('error', err => {\n serverLogger.error('persistent server error:', err)\n })\n\n serverState.port = port\n serverState.running = true\n\n // Write port file so the IDE extension can discover the server without scanning ports\n try {\n writeProjectPort(port)\n } catch (_e) {\n serverLogger.warn('Failed to write port file:', _e)\n /* non-fatal — extension will fall back to scanning */\n }\n // Clean up on process exit (Vite terminates the process, not stopServer)\n process.once('exit', () => {\n try {\n removeProjectPort()\n } catch {\n /* ignore */\n }\n })\n\n serverLogger.info(`server running at http://${serverHost}:${port}`)\n\n return port\n}\n\nexport function stopServer(): void {\n if (serverInstance) {\n serverInstance.close()\n serverInstance = null\n }\n unwatchConfig()\n serverState.running = false\n serverState.port = null\n try {\n removeProjectPort()\n } catch {\n /* ignore */\n }\n try {\n fs.unlinkSync(path.join(os.tmpdir(), LEGACY_PORT_FILE_NAME))\n } catch {\n /* ignore */\n }\n}\n\nasync function readBody(req: http.IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => chunks.push(chunk))\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))\n req.on('error', reject)\n })\n}\n\nexport async function handleRequest(\n url: URL,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n): Promise<void> {\n const pathname = url.pathname\n\n // Health check - root or /inspecto/api/v1/health\n if ((pathname === '/health' || pathname === INSPECTO_API_PATHS.HEALTH) && req.method === 'GET') {\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ ok: true, port: serverState.port }))\n return\n }\n\n // Browser Client requests\n if (pathname === INSPECTO_API_PATHS.CLIENT_CONFIG && req.method === 'GET') {\n const config = await buildClientConfig(serverState)\n\n // Omit providers from the response sent to the client\n delete config.providers\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(config))\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.IDE_INFO && req.method === 'POST') {\n try {\n const body = JSON.parse(await readBody(req))\n\n // Workspace matching defense mechanism against multiple IDE connections\n const ideWorkspace = body.workspaceRoot || ''\n const serverProjectRoot = serverState.projectRoot || ''\n\n const normalizedIdeRoot = ideWorkspace ? path.resolve(ideWorkspace) : ''\n const normalizedServerRoot = serverProjectRoot ? path.resolve(serverProjectRoot) : ''\n\n const isSameProject =\n !normalizedIdeRoot ||\n !normalizedServerRoot ||\n normalizedIdeRoot === normalizedServerRoot ||\n normalizedServerRoot.startsWith(normalizedIdeRoot + path.sep) ||\n normalizedIdeRoot.startsWith(normalizedServerRoot + path.sep)\n\n if (isSameProject) {\n serverState.ideInfo = body\n serverLogger.debug(\n `Accepted IDE info from matched workspace (ide-${body.ide} / schema-${body.scheme})`,\n )\n } else {\n serverLogger.debug(\n `Ignored IDE info from unrelated workspace (IDE Workspace: ${ideWorkspace}, Server: ${serverProjectRoot}, Scheme: ${body.scheme}, IDE: ${body.ide})`,\n )\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true }))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.IDE_INFO} POST request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n (pathname === INSPECTO_API_PATHS.SOURCE_OPEN || pathname === INSPECTO_API_PATHS.IDE_OPEN) &&\n req.method === 'POST'\n ) {\n let body: OpenFileRequest\n try {\n body = JSON.parse(await readBody(req)) as OpenFileRequest\n } catch (_e) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n return\n }\n\n try {\n handleOpenFileRequest(body, serverState)\n } catch (err: any) {\n serverLogger.warn(\n `Security: Blocked path traversal attempt in SOURCE_OPEN: ${body.file}. Reason: ${err.message}`,\n )\n res.writeHead(403, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'Access denied: File is outside of project workspace' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true }))\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.PROJECT_SNIPPET && req.method === 'GET') {\n const file = url.searchParams.get('file') ?? ''\n const line = parseInt(url.searchParams.get('line') ?? '1', 10)\n const column = parseInt(url.searchParams.get('column') ?? '1', 10)\n const maxLines = parseInt(url.searchParams.get('maxLines') ?? '100', 10)\n\n try {\n const absolutePath = resolveWorkspacePath(file, serverState.cwd)\n\n // Security: Prevent path traversal attacks\n try {\n assertPathWithinProject(absolutePath, serverState.projectRoot)\n } catch (err: any) {\n serverLogger.warn(\n `Security: Blocked path traversal attempt in PROJECT_SNIPPET: ${file}. Reason: ${err.message}`,\n )\n res.writeHead(403, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: false,\n error: 'Access denied: File is outside of project workspace',\n errorCode: 'FORBIDDEN',\n }),\n )\n return\n }\n\n const result = await extractSnippet({ file: absolutePath, line, column, maxLines })\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(result))\n } catch (err: any) {\n const message = String(err.message || err)\n const errorCode = message.startsWith('FILE_NOT_FOUND') ? 'FILE_NOT_FOUND' : 'UNKNOWN'\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: message, errorCode }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.AI_DISPATCH && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as SendToAiRequest\n const result = await dispatchToAi(body)\n res.writeHead(result.success ? 200 : 500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(result))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.AI_DISPATCH} request:`, e)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(e), errorCode: 'INTERNAL_ERROR' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.AI_BATCH_DISPATCH && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as SendAnnotationsToAiRequest\n const result = await dispatchAnnotationsToAi(body, serverState)\n res.writeHead(getBatchDispatchStatusCode(result.errorCode, result.success), {\n 'Content-Type': 'application/json',\n })\n res.end(JSON.stringify(result))\n } catch (e) {\n serverLogger.error(`Error parsing ${INSPECTO_API_PATHS.AI_BATCH_DISPATCH} request:`, e)\n res.writeHead(500, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: String(e), errorCode: 'INTERNAL_ERROR' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSION_CLAIM_NEXT && req.method === 'POST') {\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionClaimRequest) : {}\n const timeoutMs = normalizeSessionClaimTimeout(\n body.timeoutMs === undefined ? null : String(body.timeoutMs),\n )\n const result = await annotationSessionStore.claimNextSession({\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n })\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: true,\n timedOut: result.timedOut,\n matchedExisting: result.matchedExisting,\n ...(result.event ? { event: result.event } : {}),\n ...(result.session ? { session: result.session } : {}),\n }),\n )\n } catch (e) {\n serverLogger.error(`Error parsing session claim request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSION_EVENTS && req.method === 'GET') {\n const statusParam = url.searchParams.getAll('status')\n const statuses = statusParam.length ? new Set(statusParam as AnnotationSessionStatus[]) : null\n const sessionId = url.searchParams.get('sessionId')?.trim() || null\n\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n res.write(`event: ready\\ndata: ${JSON.stringify({ ok: true })}\\n\\n`)\n\n const unsubscribe = annotationSessionStore.subscribe(event => {\n if (sessionId && event.session.id !== sessionId) {\n return\n }\n if (statuses && !statuses.has(event.session.status)) {\n return\n }\n res.write(formatSessionSseEvent(event))\n })\n\n req.on('close', () => {\n unsubscribe()\n res.end()\n })\n return\n }\n\n if (pathname === INSPECTO_API_PATHS.SESSIONS && req.method === 'GET') {\n const statusParam = url.searchParams.getAll('status')\n const sessions = annotationSessionStore.listSessions(\n statusParam.length\n ? {\n status: statusParam as AnnotationSessionStatus[],\n }\n : undefined,\n )\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, sessions }))\n return\n }\n\n if (pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) && req.method === 'GET') {\n const sessionId = pathname.substring(INSPECTO_API_PATHS.SESSIONS.length + 1)\n const session = annotationSessionStore.getSession(sessionId)\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_REPLY_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_REPLY_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = JSON.parse(rawBody) as AnnotationSessionReplyRequest\n\n if (!isAnnotationThreadRole(body.role)) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Reply role is invalid.' }))\n return\n }\n\n if (!body.text?.trim()) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Reply text is required.' }))\n return\n }\n\n const session = annotationSessionStore.appendMessage(sessionId, {\n role: body.role,\n text: body.text.trim(),\n })\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session reply request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_RESOLVE_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_RESOLVE_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionResolveRequest) : {}\n const message = body.message?.trim()\n const existingSession = annotationSessionStore.getSession(sessionId)\n\n if (!existingSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n if (!message && !hasAgentReply(existingSession)) {\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(\n JSON.stringify({\n success: false,\n error: 'Resolve message is required until an agent reply is recorded.',\n }),\n )\n return\n }\n\n if (message) {\n const repliedSession = annotationSessionStore.appendMessage(sessionId, {\n role: 'agent',\n text: message,\n })\n if (!repliedSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n }\n\n const session = annotationSessionStore.updateStatus(sessionId, 'resolved')\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session resolve request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n if (\n pathname.startsWith(`${INSPECTO_API_PATHS.SESSIONS}/`) &&\n pathname.endsWith(INSPECTO_API_PATHS.SESSION_DISMISS_SUFFIX) &&\n req.method === 'POST'\n ) {\n const sessionId = pathname.slice(\n INSPECTO_API_PATHS.SESSIONS.length + 1,\n -INSPECTO_API_PATHS.SESSION_DISMISS_SUFFIX.length,\n )\n\n try {\n const rawBody = await readBody(req)\n const body = rawBody ? (JSON.parse(rawBody) as AnnotationSessionResolveRequest) : {}\n const message = body.message?.trim()\n const existingSession = annotationSessionStore.getSession(sessionId)\n\n if (!existingSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n if (message) {\n const repliedSession = annotationSessionStore.appendMessage(sessionId, {\n role: 'agent',\n text: message,\n })\n if (!repliedSession) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n }\n\n const session = annotationSessionStore.updateStatus(sessionId, 'dismissed')\n\n if (!session) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Session not found' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: true, session }))\n } catch (e) {\n serverLogger.error(`Error parsing session dismiss request:`, e)\n res.writeHead(400, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Invalid JSON body' }))\n }\n return\n }\n\n // Handle IDE payload ticket retrieval\n if (pathname.startsWith(`${INSPECTO_API_PATHS.AI_TICKET}/`) && req.method === 'GET') {\n const ticketId = pathname.substring(INSPECTO_API_PATHS.AI_TICKET.length + 1)\n const payloadStr = readTicket(ticketId)\n\n if (!payloadStr) {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ success: false, error: 'Ticket not found or expired' }))\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' })\n res.end(payloadStr)\n return\n }\n\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ error: 'not found' }))\n}\n\nasync function dispatchToAi(\n req: SendToAiRequest,\n): Promise<SendToAiResponse & { fallbackPayload?: { prompt: string; file: string } }> {\n const { location, snippet, prompt } = req\n\n if (prompt?.trim()) {\n const runtime = resolvePromptDispatchRuntime(serverState)\n return dispatchPromptThroughIde(runtime, {\n prompt: prompt.trim(),\n }) as SendToAiResponse & { fallbackPayload?: { prompt: string; file: string } }\n }\n\n if (!location) {\n return {\n success: false,\n error: 'Source location is required when prompt is omitted.',\n errorCode: 'INVALID_REQUEST',\n }\n }\n\n const formattedPrompt = `Please help me with this code from \\`${location.file}\\` (line ${location.line}):\\n\\n\\`\\`\\`\\n${snippet ?? ''}\\n\\`\\`\\`\\n`\n const runtime = resolvePromptDispatchRuntime(serverState)\n return dispatchPromptThroughIde(runtime, {\n prompt: formattedPrompt,\n filePath: location.file,\n line: location.line,\n column: location.column,\n ...(snippet !== undefined ? { snippet } : {}),\n }) as SendToAiResponse & { fallbackPayload?: { prompt: string; file: string } }\n}\n\nfunction getBatchDispatchStatusCode(\n errorCode: SendAnnotationsToAiResponse['errorCode'],\n success: boolean,\n): number {\n if (success) return 200\n if (errorCode === 'INVALID_REQUEST') return 400\n if (errorCode === 'FORBIDDEN_PATH') return 403\n return 500\n}\n\nfunction isAnnotationThreadRole(\n value: string | undefined,\n): value is AnnotationSessionReplyRequest['role'] {\n return value === 'user' || value === 'agent' || value === 'system'\n}\n\nfunction formatSessionSseEvent(event: AnnotationSessionEvent): string {\n return `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`\n}\n\nfunction normalizeSessionClaimTimeout(value: string | null): number | undefined {\n if (!value?.trim()) return 30000\n const parsed = Number.parseInt(value, 10)\n if (!Number.isFinite(parsed)) return 30000\n return Math.max(0, Math.min(parsed, 300000))\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as parser from '@babel/parser'\nimport traverse_ from '@babel/traverse'\n// Support both ESM default and CommonJS module.exports\nconst traverse =\n typeof traverse_ === 'function' ? traverse_ : (traverse_ as any).default || traverse_\nimport type { NodePath } from '@babel/traverse'\nimport type { Node } from '@babel/types'\nimport type { SnippetRequest, SnippetResponse } from '@inspecto-dev/types'\n\ninterface CacheEntry {\n mtime: number\n /** The full parsed source lines */\n lines: string[]\n}\n\n/** In-memory cache keyed by absolute file path */\nconst snippetCache = new Map<string, CacheEntry>()\n\nconst DEFAULT_MAX_LINES = 100\nconst DEFAULT_CONTEXT_LINES_BEFORE = 5\n\nexport async function extractSnippet(req: SnippetRequest): Promise<SnippetResponse> {\n const { file, line, column, maxLines = DEFAULT_MAX_LINES } = req\n\n const absolutePath = path.resolve(file)\n\n let stat: fs.Stats\n try {\n stat = await fs.promises.stat(absolutePath)\n } catch {\n throw new Error(`FILE_NOT_FOUND: ${absolutePath}`)\n }\n\n const mtime = stat.mtimeMs\n\n let lines: string[]\n const cached = snippetCache.get(absolutePath)\n if (cached && cached.mtime === mtime) {\n lines = cached.lines\n } else {\n const source = await fs.promises.readFile(absolutePath, 'utf-8')\n lines = source.split('\\n')\n snippetCache.set(absolutePath, { mtime, lines })\n }\n\n let snippetLines: string[]\n let startLine: number\n let componentName: string | undefined\n\n try {\n const result = extractComponentBoundary(lines.join('\\n'), line, column, maxLines)\n snippetLines = result.lines\n startLine = result.startLine\n componentName = result.name\n } catch {\n const before = Math.max(0, line - 1 - DEFAULT_CONTEXT_LINES_BEFORE)\n const after = Math.min(lines.length, before + maxLines)\n snippetLines = lines.slice(before, after)\n startLine = before + 1\n }\n\n if (snippetLines.length > maxLines) {\n snippetLines = snippetLines.slice(0, maxLines)\n }\n\n return {\n snippet: snippetLines.join('\\n'),\n startLine,\n file: absolutePath,\n ...(componentName ? { name: componentName } : {}),\n }\n}\n\ninterface BoundaryResult {\n lines: string[]\n startLine: number\n name?: string\n}\n\nfunction extractComponentBoundary(\n source: string,\n targetLine: number,\n _targetColumn: number,\n maxLines: number,\n): BoundaryResult {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript', 'decorators-legacy', 'classProperties'],\n errorRecovery: true,\n })\n\n const allLines = source.split('\\n')\n\n let bestStart = 0\n let bestEnd = allLines.length - 1\n let bestName: string | undefined\n\n traverse(ast, {\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ClassMethod'(\n nodePath: NodePath<Node>,\n ) {\n const node = nodePath.node\n if (!node.loc) return\n\n const nodeStart = node.loc.start.line\n const nodeEnd = node.loc.end.line\n\n if (targetLine < nodeStart || targetLine > nodeEnd) return\n\n if (nodeEnd - nodeStart < bestEnd - bestStart) {\n bestStart = nodeStart - 1\n bestEnd = nodeEnd - 1\n bestName = extractFunctionName(nodePath)\n }\n },\n })\n\n let sliceStart = bestStart\n let sliceEnd = bestEnd + 1\n\n if (sliceEnd - sliceStart > maxLines) {\n const targetIdx = targetLine - 1\n sliceStart = Math.max(bestStart, targetIdx - Math.floor(maxLines / 3))\n sliceEnd = sliceStart + maxLines\n if (sliceEnd > bestEnd + 1) {\n sliceEnd = bestEnd + 1\n sliceStart = Math.max(0, sliceEnd - maxLines)\n }\n }\n\n return {\n lines: allLines.slice(sliceStart, sliceEnd),\n startLine: sliceStart + 1,\n ...(bestName ? { name: bestName } : {}),\n }\n}\n\nfunction extractFunctionName(nodePath: NodePath<Node>): string | undefined {\n const node = nodePath.node\n\n if (node.type === 'FunctionDeclaration' && node.id) {\n return node.id.name\n }\n\n const parent = nodePath.parent\n if (\n (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') &&\n parent.type === 'VariableDeclarator' &&\n parent.id.type === 'Identifier'\n ) {\n return parent.id.name\n }\n\n if (node.type === 'ClassMethod' && node.key.type === 'Identifier') {\n return node.key.name\n }\n\n return undefined\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport os from 'node:os'\nimport { createDefu } from 'defu'\nimport type {\n InspectoSettings,\n InspectoPromptsConfig,\n Provider,\n ProviderMode,\n ToolOverrides,\n IdeType,\n LogLevel,\n} from '@inspecto-dev/types'\nimport {\n DEFAULT_PROVIDER_MODE,\n VALID_MODES,\n DEFAULT_INTENTS,\n type IntentConfig,\n type WorkflowConfig,\n isWorkflowConfig,\n} from '@inspecto-dev/types'\nimport { createLogger, setLoggerGlobalLevel } from './utils/logger.js'\n\nconst configLogger = createLogger('inspecto:config')\n\nlet loadedConfig: InspectoSettings | null = null\nlet loadedPrompts: InspectoPromptsConfig | null = null\nlet globalLogLevel: LogLevel = 'warn'\nlet isWatching = false\n\n// Custom array merge behavior for defu: overwrite arrays instead of concatenating them\nconst arrayReplaceMerge = createDefu((obj, key, val) => {\n if (Array.isArray(val)) {\n obj[key] = val\n return true\n }\n})\n\nexport function setGlobalLogLevel(level?: LogLevel) {\n if (level) {\n globalLogLevel = level\n setLoggerGlobalLevel(level)\n }\n}\n\nexport function getGlobalLogLevel() {\n return globalLogLevel\n}\n\n/**\n * Walk from cwd up to gitRoot (inclusive), collecting directories that contain\n * a .inspecto/ subdirectory. Returns them ordered highest-priority first\n * (closest to cwd first).\n *\n * If cwd is not under gitRoot, only cwd itself is checked.\n */\nexport function resolveConfigRoots(cwd: string, gitRoot: string): string[] {\n const roots: string[] = []\n let current = cwd\n\n // Ensure we don't walk past gitRoot (handles cwd above gitRoot case)\n const isUnderOrEqual = current === gitRoot || current.startsWith(gitRoot + path.sep)\n if (!isUnderOrEqual) {\n // cwd is not under gitRoot — only check cwd\n if (fs.existsSync(path.join(cwd, '.inspecto'))) roots.push(cwd)\n return roots\n }\n\n while (true) {\n if (fs.existsSync(path.join(current, '.inspecto'))) {\n roots.push(current)\n }\n if (current === gitRoot) break\n const parent = path.dirname(current)\n if (parent === current) break // filesystem root guard\n current = parent\n }\n\n return roots\n}\n\n/**\n * Load and merge user config from all discovered .inspecto/ layers:\n *\n * Priority (highest → lowest):\n * <cwd>/.inspecto/settings.local.json\n * <cwd>/.inspecto/settings.json\n * ...intermediate dirs...\n * <gitRoot>/.inspecto/settings.local.json\n * <gitRoot>/.inspecto/settings.json\n * ~/.inspecto/settings.json\n *\n * @param force Bust cache and re-read from disk\n * @param cwd Working directory to start resolution from (default: process.cwd())\n * @param gitRoot Git repository root — upward traversal stops here (optional)\n */\nexport function loadUserConfigSync(\n force = false,\n cwd = process.cwd(),\n gitRoot?: string,\n): InspectoSettings {\n if (loadedConfig && !force) return loadedConfig\n loadedConfig = null // force clear\n\n const layers: Partial<InspectoSettings>[] = []\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n\n for (const root of roots) {\n layers.push(readJsonSafely(path.join(root, '.inspecto', 'settings.local.json')))\n layers.push(readJsonSafely(path.join(root, '.inspecto', 'settings.json')))\n }\n\n layers.push(readJsonSafely(path.join(os.homedir(), '.inspecto', 'settings.json')))\n layers.push({})\n\n const validLayers = layers.filter(l => l !== null)\n loadedConfig = arrayReplaceMerge(...(validLayers as [object, ...object[]])) as InspectoSettings\n return loadedConfig\n}\n\n/**\n * Load and merge prompts config from all discovered .inspecto/ layers:\n *\n * Priority (highest → lowest):\n * <cwd>/.inspecto/prompts.local.json\n * <cwd>/.inspecto/prompts.json\n * ...intermediate dirs...\n * <gitRoot>/.inspecto/prompts.local.json\n * <gitRoot>/.inspecto/prompts.json\n * ~/.inspecto/prompts.json\n *\n * Arrays in custom configurations are replaced instead of merged.\n */\nexport async function loadPromptsConfig(\n force = false,\n cwd = process.cwd(),\n gitRoot?: string,\n): Promise<InspectoPromptsConfig> {\n if (loadedPrompts && !force) return loadedPrompts\n\n const layers: any[] = []\n\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n for (const root of roots) {\n const localPath = path.join(root, '.inspecto', 'prompts.local.json')\n const jsonPath = path.join(root, '.inspecto', 'prompts.json')\n layers.push(readJsonSafely(localPath))\n layers.push(readJsonSafely(jsonPath))\n }\n\n layers.push(readJsonSafely(path.join(os.homedir(), '.inspecto', 'prompts.json')))\n\n // Find the first layer that contains a valid prompts config (array or $replace object).\n // Highest-priority layer wins — no merging across layers for prompts.\n let finalPrompts: any = []\n for (const layer of layers) {\n if (Array.isArray(layer) && layer.length > 0) {\n finalPrompts = layer\n break\n }\n if (\n layer &&\n typeof layer === 'object' &&\n layer.$replace === true &&\n Array.isArray(layer.items)\n ) {\n finalPrompts = layer\n break\n }\n }\n\n loadedPrompts = finalPrompts as InspectoPromptsConfig\n return loadedPrompts\n}\n\nfunction readJsonSafely(filePath: string): any {\n try {\n if (fs.existsSync(filePath)) {\n const content = fs.readFileSync(filePath, 'utf-8').trim()\n if (!content) return null // Return null instead of [] so we know it's empty\n const parsed = JSON.parse(content)\n // Transition helper: if user still has {\"prompts\": [...]}, extract it\n if (!Array.isArray(parsed) && parsed.prompts && Array.isArray(parsed.prompts)) {\n return parsed.prompts\n }\n return parsed\n }\n } catch (e) {\n // Ignore JSON parsing errors for empty or malformed files during watch\n if (e instanceof SyntaxError) {\n configLogger.warn(`Failed to parse config at ${filePath}: Invalid JSON`)\n } else {\n configLogger.warn(`Failed to read config at ${filePath}:`, e)\n }\n }\n return null\n}\n\n/**\n * Resolve the exact target tool to dispatch to based on user config.\n */\nexport function resolveTargetTool(config: InspectoSettings, _ide: IdeType = 'vscode'): Provider {\n // Support \"provider.default\" (e.g., \"claude-code.extension\")\n const defaultProvider = config['provider.default'] as string | undefined\n if (defaultProvider) {\n const tool = defaultProvider.split('.')[0]\n return tool as Provider\n }\n\n // Fallback\n return 'copilot'\n}\n\n/**\n * Resolve the effective mode/type for a tool in the context of an IDE.\n */\nexport function resolveProviderMode(\n tool: Provider,\n ide: IdeType,\n config: InspectoSettings,\n): ProviderMode {\n let requestedType: ProviderMode | undefined = undefined\n\n // V2 format: check provider.default for \"tool.mode\"\n const defaultProvider = config['provider.default'] as string | undefined\n if (defaultProvider && defaultProvider.startsWith(`${tool}.`)) {\n const mode = defaultProvider.split('.')[1]\n if (mode === 'extension') requestedType = 'extension'\n if (mode === 'cli') requestedType = 'cli'\n }\n\n requestedType = requestedType ?? DEFAULT_PROVIDER_MODE[tool]\n const valid = VALID_MODES[tool] || [DEFAULT_PROVIDER_MODE[tool]]\n return requestedType && valid.includes(requestedType) ? requestedType : valid[0]!\n}\n\n/**\n * Extract ToolOverrides (binaryPath, args, etc) for Extension consumption.\n */\nexport function extractToolOverrides(\n ide: IdeType,\n config: InspectoSettings,\n): Partial<Record<Provider, ToolOverrides>> {\n const result: Partial<Record<Provider, ToolOverrides>> = {}\n\n if (!config) return result\n\n // Parse new flat `provider.*` format\n for (const [key, value] of Object.entries(config)) {\n if (!key.startsWith('provider.')) continue\n\n // We only process tool specific overrides, ignore `.default`\n if (key === 'provider.default') continue\n\n // Handle `provider.[tool].[mode]`\n const toolIndex = 1\n const modeIndex = 2\n const propIndex = 3\n\n const parts = key.split('.')\n\n if (parts.length >= propIndex + 1) {\n const tool = parts[toolIndex] as Provider\n const mode = parts[modeIndex] as ProviderMode\n const prop = parts[propIndex]\n\n if (!result[tool]) {\n result[tool] = { type: mode }\n }\n\n const overrides = result[tool]!\n\n // If we see config for a mode that differs from what we've initialized,\n // it means both modes have config. In v2, mode is determined by provider.default.\n // We will just accumulate the settings for now and let resolveProviderMode decide the active type.\n\n if (prop === 'bin') overrides.binaryPath = value as string\n if (prop === 'args') overrides.args = value as string[]\n if (prop === 'cwd') overrides.cwd = value as string\n if (prop === 'coldStartDelay') overrides.coldStartDelay = value as number\n }\n }\n\n return result\n}\n\nexport function resolveIntents(serverPrompts?: InspectoPromptsConfig): IntentConfig[] {\n // Start with DEFAULT_INTENTS as base\n const baseMap = new Map<string, IntentConfig>()\n for (const intent of DEFAULT_INTENTS) {\n baseMap.set(intent.id, { ...intent } as IntentConfig)\n }\n\n const defaults = () => Array.from(baseMap.values())\n\n if (!serverPrompts) return defaults()\n\n const isReplace =\n !Array.isArray(serverPrompts) &&\n typeof serverPrompts === 'object' &&\n serverPrompts.$replace === true\n const promptsArray = Array.isArray(serverPrompts)\n ? serverPrompts\n : isReplace\n ? serverPrompts.items\n : []\n\n if (!promptsArray || promptsArray.length === 0) return defaults()\n\n if (isReplace) {\n // $replace: true — exact list, user controls everything\n const result: IntentConfig[] = []\n for (const item of promptsArray) {\n if (typeof item === 'string') {\n if (baseMap.has(item)) {\n result.push(baseMap.get(item)!)\n } else {\n configLogger.warn(\n `Unknown built-in intent id: \"${item}\". Available: ${[...baseMap.keys()].join(', ')}`,\n )\n }\n } else if (typeof item === 'object') {\n if (!item.id) {\n configLogger.warn('Intent object missing required \"id\" field, skipping.')\n continue\n }\n if (item.enabled === false) {\n configLogger.warn(\n `Intent \"${item.id}\" is listed in $replace but has enabled:false — it will be excluded.`,\n )\n continue\n }\n if (item.kind === 'workflow') {\n if (!item.prompt) {\n configLogger.warn(`Workflow \"${item.id}\" missing required \"prompt\", skipping`)\n continue\n }\n result.push({\n kind: 'workflow',\n id: item.id,\n label: item.label ?? item.id,\n prompt: item.prompt,\n confirm: item.confirm ?? false,\n enabled: item.enabled ?? true,\n } as WorkflowConfig)\n } else {\n if (!item.aiIntent) {\n configLogger.warn(`Intent \"${item.id}\" is missing required \"aiIntent\".`)\n continue\n }\n result.push(\n (baseMap.has(item.id) ? { ...baseMap.get(item.id)!, ...item } : item) as IntentConfig,\n )\n }\n }\n }\n return result\n }\n\n // Default: append / override mode.\n // - Objects with known id: merge over built-in (or remove if enabled:false)\n // - Objects with unknown id: append as new intent\n // - Strings: not meaningful in append mode (order is fixed to built-in order + appended)\n const merged = Array.from(baseMap.values())\n\n for (const item of promptsArray) {\n if (typeof item === 'string') {\n if (!baseMap.has(item)) {\n configLogger.warn(\n `Unknown built-in intent id: \"${item}\". In append mode, strings have no effect on ordering — use $replace to control order.`,\n )\n }\n // Known string ids are already in merged — nothing to do\n continue\n }\n\n if (typeof item === 'object') {\n if (!item.id) {\n configLogger.warn('Intent object missing required \"id\" field, skipping.')\n continue\n }\n if (item.kind === 'workflow') {\n if (!item.prompt) {\n configLogger.warn(`Workflow \"${item.id}\" missing required \"prompt\", skipping`)\n continue\n }\n const wfConfig: WorkflowConfig = {\n kind: 'workflow',\n id: item.id,\n label: item.label ?? item.id,\n prompt: item.prompt,\n confirm: item.confirm ?? false,\n enabled: item.enabled ?? true,\n }\n const existingIdx = merged.findIndex(i => i.id === item.id)\n if (existingIdx !== -1) {\n if (item.enabled === false) {\n merged.splice(existingIdx, 1)\n } else {\n merged[existingIdx] = wfConfig\n }\n } else {\n if (item.enabled !== false) {\n merged.push(wfConfig)\n }\n }\n } else {\n if (!item.aiIntent) {\n configLogger.warn(`Intent \"${item.id}\" is missing required \"aiIntent\".`)\n continue\n }\n const existingIdx = merged.findIndex(i => i.id === item.id)\n if (existingIdx !== -1) {\n if (item.enabled === false) {\n merged.splice(existingIdx, 1)\n } else {\n merged[existingIdx] = { ...merged[existingIdx], ...item } as IntentConfig\n }\n } else {\n if (item.enabled !== false) {\n merged.push(item as IntentConfig)\n }\n }\n }\n }\n }\n\n return merged\n}\n\nexport function resolveWorkflowSlots(\n intents: IntentConfig[],\n): import('@inspecto-dev/types').WorkflowSlotOption[] {\n return intents\n .filter(isWorkflowConfig)\n .filter(w => w.enabled !== false)\n .map(w => ({\n id: w.id,\n label: w.label ?? w.id,\n prompt: w.prompt,\n confirm: w.confirm ?? false,\n }))\n}\n\nlet watchers: fs.FSWatcher[] = []\n\nexport function watchConfig(onReload: () => void, cwd = process.cwd(), gitRoot?: string): void {\n if (isWatching) return\n isWatching = true\n\n // Watch .inspecto/ directories rather than individual files so that newly\n // created files (e.g. prompts.local.json added after server start) are picked up.\n const watchDirs: string[] = [path.join(os.homedir(), '.inspecto')]\n const roots = resolveConfigRoots(cwd, gitRoot ?? cwd)\n for (const root of roots) {\n watchDirs.push(path.join(root, '.inspecto'))\n }\n\n const CONFIG_FILES = new Set([\n 'settings.json',\n 'settings.local.json',\n 'prompts.json',\n 'prompts.local.json',\n ])\n\n for (const dir of watchDirs) {\n if (!fs.existsSync(dir)) continue\n try {\n const watcher = fs.watch(dir, async (eventType, filename) => {\n if (!filename || !CONFIG_FILES.has(filename)) return\n loadedConfig = null\n loadedPrompts = null\n loadUserConfigSync(true, cwd, gitRoot)\n await loadPromptsConfig(true, cwd, gitRoot)\n onReload()\n })\n watcher.unref()\n watchers.push(watcher)\n } catch (_e) {\n // ignore watch errors (e.g. unsupported fs)\n }\n }\n}\n\nexport function unwatchConfig(): void {\n for (const watcher of watchers) {\n watcher.close()\n }\n watchers = []\n isWatching = false\n}\n","import type { LogLevel } from '@inspecto-dev/types'\n\nexport interface Logger {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n setLevel?(level: LogLevel): void\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n}\n\n// Very simple implementation of a DEBUG matching string.\n// Supports `DEBUG=inspecto:*` or `DEBUG=inspecto:server,inspecto:ast`\nfunction isDebugEnabled(namespace: string): boolean {\n if (typeof process === 'undefined' || !process.env) return false\n const debugEnv = process.env.DEBUG\n if (!debugEnv) return false\n\n const namespaces = debugEnv.split(',').map(s => s.trim())\n for (const ns of namespaces) {\n if (ns === '*') return true\n if (ns.endsWith('*')) {\n const prefix = ns.slice(0, -1)\n if (namespace.startsWith(prefix)) return true\n } else if (ns === namespace) {\n return true\n }\n }\n return false\n}\n\n// Store global level locally to avoid circular dependency with config.ts\nlet globalLevel: LogLevel = 'warn'\nconst registeredLoggers: Set<Logger> = new Set()\n\nexport function setLoggerGlobalLevel(level: LogLevel) {\n globalLevel = level\n for (const logger of registeredLoggers) {\n if (logger.setLevel) {\n logger.setLevel(level)\n }\n }\n}\n\nexport function createLogger(namespace: string, options?: { logLevel?: LogLevel }): Logger {\n let currentLevel = options?.logLevel ?? globalLevel\n let numericLevel = LOG_LEVELS[currentLevel] ?? 2\n const debugEnabled = isDebugEnabled(namespace)\n\n const logger: Logger = {\n setLevel(level: LogLevel) {\n currentLevel = level\n numericLevel = LOG_LEVELS[level] ?? 2\n },\n info(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.info) {\n console.log(`\\x1b[36m[inspecto]\\x1b[0m ${msg}`, ...args)\n }\n },\n warn(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.warn) {\n console.warn(`\\x1b[33m[inspecto] WARN:\\x1b[0m ${msg}`, ...args)\n }\n },\n error(msg: string, ...args: any[]) {\n if (numericLevel >= LOG_LEVELS.error) {\n console.error(`\\x1b[31m[inspecto] ERROR:\\x1b[0m ${msg}`, ...args)\n }\n },\n debug(msg: string, ...args: any[]) {\n if (debugEnabled) {\n console.log(`\\x1b[90m[${namespace}]\\x1b[0m ${msg}`, ...args)\n }\n },\n }\n\n registeredLoggers.add(logger)\n\n return logger\n}\n","import crypto from 'node:crypto'\nimport { execFileSync } from 'node:child_process'\nimport { launchIDE } from 'launch-ide'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nconst payloadTickets = new Map<string, string>()\n\nexport function createTicket(payload: unknown): string {\n const ticketId = crypto.randomUUID()\n payloadTickets.set(ticketId, JSON.stringify(payload))\n\n setTimeout(\n () => {\n payloadTickets.delete(ticketId)\n },\n 5 * 60 * 1000,\n )\n\n return ticketId\n}\n\nexport function readTicket(ticketId: string): string | undefined {\n return payloadTickets.get(ticketId)\n}\n\nexport function launchURI(uri: string): void {\n try {\n if (process.platform === 'darwin') {\n execFileSync('open', [uri])\n } else if (process.platform === 'win32') {\n execFileSync('cmd', ['/c', 'start', '\"\"', uri])\n } else {\n execFileSync('xdg-open', [uri])\n }\n } catch (e) {\n serverLogger.error('Failed to launch URI via execFileSync, falling back to launchIDE:', e)\n launchIDE({ file: uri })\n }\n}\n","import type {\n IdeType,\n Provider,\n ProviderMode,\n ServerState,\n ToolOverrides,\n} from '@inspecto-dev/types'\nimport {\n extractToolOverrides,\n loadUserConfigSync,\n resolveProviderMode,\n resolveTargetTool,\n} from '../config.js'\nimport { createTicket, launchURI } from './dispatch-transport.js'\n\nexport interface PromptDispatchRuntime {\n resolvedTarget: Provider\n finalIde: string\n mode: ProviderMode\n overrides?: ToolOverrides\n autoSend?: boolean\n}\n\nexport interface PromptDispatchPayload {\n prompt: string\n filePath?: string\n line?: number\n column?: number\n snippet?: string\n}\n\nexport interface PromptDispatchResult {\n success: true\n fallbackPayload: {\n prompt: string\n file?: string\n }\n}\n\nfunction normalizeIdeToken(value: string | undefined): string {\n return (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nexport function resolvePromptDispatchRuntime(\n state: Pick<ServerState, 'projectRoot' | 'cwd' | 'ideInfo'>,\n): PromptDispatchRuntime {\n const userConfig = loadUserConfigSync(false, state.cwd, state.projectRoot)\n const resolvedTarget = resolveTargetTool(userConfig)\n const finalIde = resolveFinalIde(userConfig.ide, state.ideInfo?.ide, state.ideInfo?.scheme)\n const mode = resolveProviderMode(resolvedTarget, finalIde as IdeType, userConfig)\n const overrides =\n extractToolOverrides(finalIde as IdeType, userConfig)[resolvedTarget] || undefined\n\n return {\n resolvedTarget,\n finalIde,\n mode,\n ...(hasOverrides(overrides) ? { overrides } : {}),\n ...(userConfig['prompt.autoSend'] !== undefined\n ? { autoSend: Boolean(userConfig['prompt.autoSend']) }\n : {}),\n }\n}\n\nexport function dispatchPromptThroughIde(\n runtime: PromptDispatchRuntime,\n payload: PromptDispatchPayload,\n): PromptDispatchResult {\n const ticketId = createTicket({\n ide: runtime.finalIde,\n target: runtime.resolvedTarget,\n targetType: runtime.mode,\n prompt: payload.prompt,\n filePath: payload.filePath,\n line: payload.line,\n column: payload.column,\n snippet: payload.snippet,\n overrides: runtime.overrides,\n autoSend: runtime.autoSend,\n })\n\n const params = new URLSearchParams()\n params.set('ticket', ticketId)\n params.set('target', runtime.resolvedTarget)\n\n launchURI(`${runtime.finalIde}://inspecto.inspecto/send?${params.toString()}`)\n\n return {\n success: true,\n fallbackPayload: {\n prompt: payload.prompt,\n ...(payload.filePath ? { file: payload.filePath } : {}),\n },\n }\n}\n\nfunction resolveFinalIde(\n configuredIde: string | undefined,\n activeIde: string | undefined,\n activeIdeScheme: string | undefined,\n): string {\n const configuredIdeMatchesActiveScheme =\n Boolean(configuredIde) &&\n Boolean(activeIdeScheme) &&\n normalizeIdeToken(configuredIde) === normalizeIdeToken(activeIdeScheme)\n\n if (configuredIdeMatchesActiveScheme) {\n return activeIdeScheme!\n }\n\n if (\n configuredIde &&\n activeIdeScheme &&\n normalizeIdeToken(activeIdeScheme).includes(normalizeIdeToken(configuredIde)) === false\n ) {\n return configuredIde\n }\n\n return configuredIde || activeIdeScheme || activeIde || 'vscode'\n}\n\nfunction hasOverrides(overrides: ToolOverrides | undefined): overrides is ToolOverrides {\n return Boolean(overrides && Object.keys(overrides).length > 0)\n}\n","import path from 'node:path'\nimport fs from 'node:fs'\n\nfunction isWindowsAbsolutePath(file: string): boolean {\n return /^[a-zA-Z]:[\\\\/]/.test(file) || /^\\\\\\\\[^\\\\]+\\\\[^\\\\]+/.test(file)\n}\n\nexport function resolveWorkspacePath(file: string, cwd: string): string {\n if (isWindowsAbsolutePath(file)) {\n return path.win32.normalize(file)\n }\n return path.isAbsolute(file) ? path.resolve(file) : path.resolve(cwd, file)\n}\n\nexport function assertPathWithinProject(file: string, projectRoot: string): void {\n let realFile = file\n let realProjectRoot = projectRoot\n try {\n if (fs.existsSync(file)) {\n realFile = fs.realpathSync(file)\n }\n } catch {\n // ignore\n }\n\n try {\n if (fs.existsSync(projectRoot)) {\n realProjectRoot = fs.realpathSync(projectRoot)\n }\n } catch {\n // ignore\n }\n\n if (isWithinPath(file, projectRoot) || isWithinPath(realFile, realProjectRoot)) {\n return\n }\n\n throw new Error(\n `Access denied: File ${normalizeForComparison(realFile)} is outside of project workspace ${normalizeForComparison(realProjectRoot)}`,\n )\n}\n\nfunction tryReadPackageName(packageRoot: string): string | undefined {\n try {\n const packageJsonPath = path.join(packageRoot, 'package.json')\n if (!fs.existsSync(packageJsonPath)) return undefined\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string }\n return typeof packageJson.name === 'string' ? packageJson.name : undefined\n } catch {\n return undefined\n }\n}\n\nfunction findNearestPackageRoot(file: string): string | undefined {\n let current = path.dirname(file)\n\n while (true) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) {\n return undefined\n }\n current = parent\n }\n}\n\nfunction normalizeForComparison(file: string): string {\n return isWindowsAbsolutePath(file) ? path.win32.normalize(file) : path.normalize(file)\n}\n\nfunction pathSeparatorFor(file: string): string {\n return isWindowsAbsolutePath(file) ? path.win32.sep : path.sep\n}\n\nfunction isWithinPath(file: string, root: string): boolean {\n const normalizedFile = normalizeForComparison(file)\n const normalizedRoot = normalizeForComparison(root)\n const separator = pathSeparatorFor(normalizedRoot)\n const rootWithSep = normalizedRoot.endsWith(separator)\n ? normalizedRoot\n : normalizedRoot + separator\n return normalizedFile === normalizedRoot || normalizedFile.startsWith(rootWithSep)\n}\n\nfunction resolveLinkedDependencyEntry(\n projectRoot: string,\n packageName: string,\n): string | undefined {\n const packageSegments = packageName.split('/')\n const dependencyPath = path.join(projectRoot, 'node_modules', ...packageSegments)\n if (!fs.existsSync(dependencyPath)) return undefined\n\n try {\n return fs.realpathSync(dependencyPath)\n } catch {\n return dependencyPath\n }\n}\n\nfunction isLinkedDependencyPath(file: string, projectRoot: string, packageName: string): boolean {\n const linkedDependencyRoot = resolveLinkedDependencyEntry(projectRoot, packageName)\n if (!linkedDependencyRoot) return false\n\n return isWithinPath(file, linkedDependencyRoot)\n}\n\nfunction isLinkedDependencySourcePath(file: string, projectRoot: string): boolean {\n const packageRoot = findNearestPackageRoot(file)\n if (!packageRoot) return false\n\n const packageName = tryReadPackageName(packageRoot)\n if (!packageName) return false\n\n return isLinkedDependencyPath(file, projectRoot, packageName)\n}\n\nexport function assertPathWithinIdeOpenScope(file: string, projectRoot: string): void {\n try {\n assertPathWithinProject(file, projectRoot)\n return\n } catch {\n if (isLinkedDependencySourcePath(file, projectRoot)) {\n return\n }\n throw new Error(`Access denied: File is outside of project workspace`)\n }\n}\n","import type {\n Annotation,\n AnnotationIntent,\n AnnotationDeliveryMode,\n AiErrorCode,\n AnnotationWorkSessionSummary,\n RuntimeContextEnvelope,\n RuntimeEvidenceRecord,\n SendAnnotationsToAiRequest,\n SendAnnotationsToAiResponse,\n ServerState,\n} from '@inspecto-dev/types'\nimport { dispatchPromptThroughIde, resolvePromptDispatchRuntime } from './dispatch-runtime.js'\nimport { assertPathWithinProject, resolveWorkspacePath } from './path-guards.js'\nimport { exec } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execAsync = promisify(exec)\nimport type { AnnotationSessionStore } from './session-store.js'\nimport { annotationSessionStore } from './session-store.js'\n\nexport interface NormalizedAnnotationTarget {\n file: string\n line: number\n column: number\n label?: string\n selector?: string\n snippet?: string\n}\n\nexport interface NormalizedAnnotation {\n index: number\n note: string\n intent: AnnotationIntent\n targets: NormalizedAnnotationTarget[]\n}\n\nexport interface NormalizedAnnotationBatch {\n instruction: string\n annotations: NormalizedAnnotation[]\n runtimeContext?: RuntimeContextEnvelope\n cssContextPrompt?: string\n}\n\nclass AnnotationDispatchError extends Error {\n readonly errorCode: AiErrorCode\n\n constructor(message: string, errorCode: AiErrorCode) {\n super(message)\n this.name = 'AnnotationDispatchError'\n this.errorCode = errorCode\n }\n}\n\nexport async function dispatchAnnotationsToAi(\n req: SendAnnotationsToAiRequest,\n state: Pick<ServerState, 'projectRoot' | 'cwd' | 'ideInfo'>,\n store: AnnotationSessionStore = annotationSessionStore,\n): Promise<SendAnnotationsToAiResponse> {\n try {\n validateAnnotationDispatchRequest(req, state)\n const batch = normalizeAnnotationBatch(req)\n let prompt = buildAnnotationBatchPrompt(batch)\n\n // ===== 注入项目元信息 =====\n if (req.source === 'workflow') {\n prompt = await appendProjectMetadata(prompt, state)\n }\n\n const deliveryMode = normalizeDeliveryMode(req.deliveryMode)\n const session = store.createSession({\n source: req.source || 'annotation',\n ...(req.workflowId ? { workflowId: req.workflowId } : {}),\n instruction: batch.instruction,\n annotations: toSessionAnnotations(batch.annotations),\n deliveryMode,\n ...(batch.runtimeContext ? { runtimeContext: batch.runtimeContext } : {}),\n ...(batch.cssContextPrompt ? { cssContextPrompt: batch.cssContextPrompt } : {}),\n })\n const representativeTarget = batch.annotations[0]?.targets[0]\n const dispatchResult =\n deliveryMode === 'ide'\n ? dispatchPromptThroughIde(resolvePromptDispatchRuntime(state), {\n prompt,\n ...(representativeTarget?.file ? { filePath: representativeTarget.file } : {}),\n ...(representativeTarget?.line ? { line: representativeTarget.line } : {}),\n ...(representativeTarget?.column ? { column: representativeTarget.column } : {}),\n })\n : { success: true as const }\n\n return {\n ...dispatchResult,\n session: toSessionSummary(session),\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n errorCode: getAnnotationDispatchErrorCode(error),\n }\n }\n}\n\n/** 在 prompt 末尾追加项目元信息 */\nasync function appendProjectMetadata(\n prompt: string,\n state: Pick<ServerState, 'projectRoot' | 'cwd'>,\n): Promise<string> {\n const lines = ['\\n## Project']\n lines.push(`- Root: ${state.projectRoot}`)\n try {\n const options = {\n cwd: state.projectRoot,\n encoding: 'utf-8',\n timeout: 2000,\n } as const\n const { stdout: branchStdout } = await execAsync('git branch --show-current', options)\n const branch = branchStdout.trim()\n lines.push(`- Branch: ${branch}`)\n\n const { stdout: statusStdout } = await execAsync('git status --porcelain', options)\n const statusRaw = statusStdout.trim()\n const entries = statusRaw ? statusRaw.split('\\n') : []\n const staged = entries.filter(l => l[0] !== ' ' && l[0] !== '?').length\n const unstaged = entries.filter(l => l[1] !== ' ' && l[1] !== '?').length\n const untracked = entries.filter(l => l[0] === '?').length\n lines.push(`- Status: ${staged} staged, ${unstaged} unstaged, ${untracked} untracked`)\n } catch (err) {\n console.warn('[inspecto] Failed to get git status for workflow:', err)\n lines.push('- Git: unavailable or check timeout')\n }\n return `${prompt}\\n\\n${lines.join('\\n')}`\n}\n\nfunction normalizeDeliveryMode(input: AnnotationDeliveryMode | undefined): AnnotationDeliveryMode {\n return input === 'agent' ? 'agent' : 'ide'\n}\n\nfunction toSessionAnnotations(annotations: NormalizedAnnotation[]): Annotation[] {\n return annotations.map(annotation => ({\n id: `annotation-${annotation.index}`,\n note: annotation.note,\n intent: annotation.intent,\n targets: annotation.targets.map((target, targetIndex) => ({\n id: `annotation-${annotation.index}-target-${targetIndex + 1}`,\n label: target.label ?? 'Unknown target',\n location: {\n file: target.file,\n line: target.line,\n column: target.column,\n },\n ...(target.selector ? { selector: target.selector } : {}),\n ...(target.snippet ? { snippet: target.snippet } : {}),\n rect: {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n },\n })),\n }))\n}\n\nfunction toSessionSummary(session: {\n id: string\n status: AnnotationWorkSessionSummary['status']\n createdAt: number\n updatedAt: number\n}): AnnotationWorkSessionSummary {\n return {\n id: session.id,\n status: session.status,\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n }\n}\n\nexport function validateAnnotationDispatchRequest(\n req: SendAnnotationsToAiRequest,\n state: Pick<ServerState, 'projectRoot' | 'cwd'>,\n): void {\n if (!req.annotations.length && req.source !== 'workflow') {\n throw new AnnotationDispatchError('At least one annotation is required.', 'INVALID_REQUEST')\n }\n\n for (const annotation of req.annotations) {\n if (!annotation.targets.length) {\n throw new AnnotationDispatchError(\n 'Each annotation must include at least one target.',\n 'INVALID_REQUEST',\n )\n }\n\n for (const target of annotation.targets) {\n const absolutePath = resolveWorkspacePath(target.location.file, state.cwd)\n assertPathWithinProject(absolutePath, state.projectRoot)\n }\n }\n}\n\nexport function normalizeAnnotationBatch(\n req: SendAnnotationsToAiRequest,\n): NormalizedAnnotationBatch {\n return {\n instruction: req.instruction?.trim() ?? '',\n ...(req.runtimeContext ? { runtimeContext: req.runtimeContext } : {}),\n ...(req.cssContextPrompt?.trim() ? { cssContextPrompt: req.cssContextPrompt.trim() } : {}),\n annotations: req.annotations.map((annotation, index) => ({\n index: index + 1,\n note: annotation.note.trim(),\n intent: annotation.intent,\n targets: annotation.targets.map(target => ({\n file: target.location.file,\n line: target.location.line,\n column: target.location.column,\n ...(target.label ? { label: target.label } : {}),\n ...(target.selector ? { selector: target.selector } : {}),\n ...(target.snippet ? { snippet: target.snippet } : {}),\n })),\n })),\n }\n}\n\nexport function buildAnnotationBatchPrompt(batch: NormalizedAnnotationBatch): string {\n const body = buildSelectedElementsPrompt(batch.annotations)\n const prompt = batch.instruction ? `${batch.instruction}\\n\\n${body}` : body\n\n return appendCssContextSection(\n appendRuntimeContextSection(prompt, batch.runtimeContext),\n batch.cssContextPrompt,\n )\n}\n\nfunction appendCssContextSection(prompt: string, cssContextPrompt: string | undefined): string {\n if (!cssContextPrompt) return prompt\n return `${prompt}\\n\\n${cssContextPrompt}`\n}\n\nfunction buildSelectedElementsPrompt(annotations: NormalizedAnnotation[]): string {\n const lines = ['Selected elements:']\n\n for (const annotation of annotations) {\n const trimmedNote = annotation.note.trim()\n for (const target of annotation.targets) {\n const targetLabel = (target.label || 'Unknown target').trim() || 'Unknown target'\n lines.push(`- ${targetLabel}`)\n lines.push(`file=${target.file}:${target.line}:${target.column}`)\n if (trimmedNote) {\n lines.push(`note=${trimmedNote}`)\n }\n }\n }\n\n if (lines.length === 1) {\n lines.push('- None')\n }\n\n return lines.join('\\n')\n}\n\nfunction appendRuntimeContextSection(\n prompt: string,\n runtimeContext: RuntimeContextEnvelope | undefined,\n): string {\n if (!runtimeContext?.records.length) {\n return prompt\n }\n\n return `${prompt}\\n\\n${buildRuntimeContextSection(runtimeContext.records)}`\n}\n\nfunction buildRuntimeContextSection(records: RuntimeEvidenceRecord[]): string {\n return ['Relevant runtime context:', ...records.map(formatRuntimeRecord)].join('\\n')\n}\n\nfunction formatRuntimeRecord(record: RuntimeEvidenceRecord): string {\n const requestSummary =\n record.kind === 'failed-request'\n ? `request=${record.request?.method ?? 'GET'} ${record.request?.pathname ?? record.request?.url ?? 'unknown'} status=${record.request?.status ?? 'unknown'}`\n : `occurrences=${record.occurrenceCount}`\n const reasonSummary = record.relevanceReasons.length\n ? record.relevanceReasons.join('; ')\n : 'timing-based'\n const stackSummary = record.stack\n ? `\\n stack=${record.stack.split('\\n').slice(0, 5).join(' | ')}`\n : ''\n\n return [\n `- [${record.kind}] ${record.message}`,\n ` relevance=${record.relevanceLevel} (${reasonSummary})`,\n ` ${requestSummary}`,\n stackSummary,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction getAnnotationDispatchErrorCode(error: unknown): AiErrorCode {\n if (error instanceof AnnotationDispatchError) return error.errorCode\n if (error instanceof Error && error.message.includes('outside of project workspace')) {\n return 'FORBIDDEN_PATH'\n }\n return 'UNKNOWN'\n}\n","import type {\n AnnotationSessionEvent,\n AnnotationSessionStatus,\n AnnotationWorkSession,\n AppendAnnotationThreadMessageInput,\n CreateAnnotationWorkSessionInput,\n} from '@inspecto-dev/types'\n\nexport interface AnnotationSessionStoreOptions {\n now?: () => number\n createId?: () => string\n}\n\nexport interface AnnotationSessionListOptions {\n status?: AnnotationSessionStatus | AnnotationSessionStatus[]\n}\n\nexport interface ClaimNextAnnotationSessionOptions {\n timeoutMs?: number\n source?: 'annotation' | 'workflow'\n}\n\nexport interface ClaimNextAnnotationSessionResult {\n session: AnnotationWorkSession | null\n timedOut: boolean\n matchedExisting: boolean\n event?: AnnotationSessionEvent['type']\n}\n\nexport interface AnnotationSessionStore {\n createSession(input: CreateAnnotationWorkSessionInput): AnnotationWorkSession\n getSession(id: string): AnnotationWorkSession | null\n listSessions(options?: AnnotationSessionListOptions): AnnotationWorkSession[]\n claimNextSession(\n options?: ClaimNextAnnotationSessionOptions,\n ): Promise<ClaimNextAnnotationSessionResult>\n appendMessage(id: string, input: AppendAnnotationThreadMessageInput): AnnotationWorkSession | null\n updateStatus(id: string, status: AnnotationSessionStatus): AnnotationWorkSession | null\n subscribe(listener: AnnotationSessionListener): () => void\n clear(): void\n}\n\nexport type AnnotationSessionListener = (event: AnnotationSessionEvent) => void\n\nconst DEFAULT_STATUS: AnnotationSessionStatus = 'pending'\n\nexport function createAnnotationSessionStore(\n options: AnnotationSessionStoreOptions = {},\n): AnnotationSessionStore {\n const sessions = new Map<string, AnnotationWorkSession>()\n const listeners = new Set<AnnotationSessionListener>()\n const now = options.now ?? (() => Date.now())\n const createId = options.createId ?? createRandomId\n\n function findNewestMatchingSession(\n statuses: Set<AnnotationSessionStatus> | null,\n source?: 'annotation' | 'workflow',\n ): AnnotationWorkSession | null {\n return (\n [...sessions.values()]\n .filter(session => {\n if (statuses && !statuses.has(session.status)) return false\n if (source && session.source !== source) return false\n return true\n })\n .sort((left, right) => right.updatedAt - left.updatedAt)[0] ?? null\n )\n }\n\n function updateSessionStatus(\n id: string,\n status: AnnotationSessionStatus,\n ): AnnotationWorkSession | null {\n const session = sessions.get(id)\n if (!session) return null\n\n const timestamp = now()\n session.status = status\n session.updatedAt = timestamp\n\n if (status === 'acknowledged') {\n session.acknowledgedAt = timestamp\n }\n if (status === 'resolved') {\n session.resolvedAt = timestamp\n }\n\n emit({ type: 'session-status-updated', session })\n return cloneSession(session)\n }\n\n function claimSession(\n id: string,\n statuses: Set<AnnotationSessionStatus> | null,\n ): AnnotationWorkSession | null {\n const session = sessions.get(id)\n if (!session || (statuses && !statuses.has(session.status))) return null\n if (session.status === 'acknowledged') return cloneSession(session)\n return updateSessionStatus(id, 'acknowledged')\n }\n\n function emit(event: AnnotationSessionEvent): void {\n const snapshot = cloneSession(event.session)\n for (const listener of listeners) {\n listener({ type: event.type, session: snapshot })\n }\n }\n\n const store: AnnotationSessionStore = {\n createSession(input) {\n const timestamp = now()\n const session: AnnotationWorkSession = {\n id: createId(),\n instruction: input.instruction?.trim() ?? '',\n annotations: cloneArray(input.annotations),\n ...(input.deliveryMode ? { deliveryMode: input.deliveryMode } : {}),\n status: DEFAULT_STATUS,\n messages: cloneArray(input.messages ?? []),\n createdAt: timestamp,\n updatedAt: timestamp,\n ...(input.runtimeContext ? { runtimeContext: cloneValue(input.runtimeContext) } : {}),\n ...(input.cssContextPrompt?.trim()\n ? { cssContextPrompt: input.cssContextPrompt.trim() }\n : {}),\n ...(input.pageUrl ? { pageUrl: input.pageUrl } : {}),\n ...(input.route ? { route: input.route } : {}),\n }\n\n sessions.set(session.id, session)\n emit({ type: 'session-created', session })\n return cloneSession(session)\n },\n\n getSession(id) {\n const session = sessions.get(id)\n return session ? cloneSession(session) : null\n },\n\n listSessions(options = {}) {\n const statuses = normalizeStatuses(options.status)\n return [...sessions.values()]\n .filter(session => (statuses ? statuses.has(session.status) : true))\n .sort((left, right) => right.updatedAt - left.updatedAt)\n .map(session => cloneSession(session))\n },\n\n async claimNextSession(options = {}) {\n const statuses = normalizeStatuses(DEFAULT_STATUS)\n const existingSession = findNewestMatchingSession(statuses, options.source)\n if (existingSession) {\n return {\n session: claimSession(existingSession.id, statuses),\n timedOut: false,\n matchedExisting: true,\n }\n }\n\n const timeoutMs = normalizeTimeoutMs(options.timeoutMs)\n if (timeoutMs === 0) {\n return {\n session: null,\n timedOut: true,\n matchedExisting: false,\n }\n }\n\n return await new Promise<ClaimNextAnnotationSessionResult>(resolve => {\n let settled = false\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n const finish = (result: ClaimNextAnnotationSessionResult): void => {\n if (settled) return\n settled = true\n unsubscribe()\n if (timeout) {\n clearTimeout(timeout)\n }\n resolve(result)\n }\n\n const unsubscribe = this.subscribe(event => {\n const session = claimSession(event.session.id, statuses)\n if (!session) return\n finish({\n session,\n timedOut: false,\n matchedExisting: false,\n event: event.type,\n })\n })\n\n if (timeoutMs !== null) {\n timeout = setTimeout(() => {\n finish({\n session: null,\n timedOut: true,\n matchedExisting: false,\n })\n }, timeoutMs)\n }\n })\n },\n\n appendMessage(id, input) {\n const session = sessions.get(id)\n if (!session) return null\n\n const timestamp = now()\n session.messages.push({\n id: createId(),\n role: input.role,\n text: input.text,\n createdAt: timestamp,\n })\n session.updatedAt = timestamp\n\n if (input.role === 'agent' && isPendingLikeStatus(session.status)) {\n session.status = 'in_progress'\n }\n\n emit({ type: 'session-message-appended', session })\n return cloneSession(session)\n },\n\n updateStatus(id, status) {\n return updateSessionStatus(id, status)\n },\n\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n\n clear() {\n sessions.clear()\n listeners.clear()\n },\n }\n\n return store\n}\n\nexport const annotationSessionStore = createAnnotationSessionStore()\n\nfunction normalizeStatuses(\n status: AnnotationSessionListOptions['status'],\n): Set<AnnotationSessionStatus> | null {\n if (!status) return null\n return new Set(Array.isArray(status) ? status : [status])\n}\n\nfunction normalizeTimeoutMs(value: number | undefined): number | null {\n if (value === undefined) return null\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.floor(value))\n}\n\nfunction isPendingLikeStatus(status: AnnotationSessionStatus): boolean {\n return status === 'pending' || status === 'acknowledged'\n}\n\nexport function hasAgentReply(session: Pick<AnnotationWorkSession, 'messages'>): boolean {\n return session.messages.some(message => message.role === 'agent' && Boolean(message.text?.trim()))\n}\n\nfunction createRandomId(): string {\n return `annotation-session-${Math.random().toString(36).slice(2, 10)}`\n}\n\nfunction cloneSession(session: AnnotationWorkSession): AnnotationWorkSession {\n return cloneValue(session)\n}\n\nfunction cloneArray<T>(value: T[]): T[] {\n return cloneValue(value)\n}\n\nfunction cloneValue<T>(value: T): T {\n if (typeof structuredClone === 'function') {\n return structuredClone(value)\n }\n return JSON.parse(JSON.stringify(value)) as T\n}\n","import type { IdeType, InspectoConfig, ServerState } from '@inspecto-dev/types'\nimport { isAiIntentConfig } from '@inspecto-dev/types'\nimport {\n loadPromptsConfig,\n loadUserConfigSync,\n resolveIntents,\n resolveWorkflowSlots,\n} from '../config.js'\n\nexport async function buildClientConfig(\n serverState: ServerState,\n): Promise<InspectoConfig & { autoSend: boolean }> {\n const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot)\n const promptsConfig = await loadPromptsConfig(false, serverState.cwd, serverState.configRoot)\n const effectiveIde = (userConfig.ide ?? 'vscode') as IdeType\n\n let info: any\n if (!serverState.ideInfo) {\n info = { ide: effectiveIde }\n } else {\n const { scheme: _scheme, ...rest } = serverState.ideInfo as any\n info = rest\n }\n\n const allIntents = resolveIntents(promptsConfig)\n\n return {\n ...info,\n prompts: allIntents.filter(isAiIntentConfig),\n workflows: resolveWorkflowSlots(allIntents),\n hotKeys: userConfig['inspector.hotKey'] ?? 'alt',\n annotateDeliveryMode: userConfig['annotate.deliveryMode'] ?? 'agent',\n includeSnippet: userConfig['prompt.includeSnippet'] ?? false,\n runtimeContext: {\n enabled: true,\n preview: true,\n maxRuntimeErrors: 3,\n maxFailedRequests: 2,\n },\n autoSend: userConfig['prompt.autoSend'] ?? false,\n }\n}\n","import { execFileSync } from 'node:child_process'\nimport { Editor, launchIDE } from 'launch-ide'\nimport type { OpenFileRequest, ServerState } from '@inspecto-dev/types'\nimport { loadUserConfigSync } from '../config.js'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\nimport { assertPathWithinIdeOpenScope, resolveWorkspacePath } from './path-guards.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nconst VSCODE_FAMILY_SCHEMES = [\n 'vscode',\n 'vscode-insiders',\n 'cursor',\n 'windsurf',\n 'trae',\n 'trae-cn',\n 'vscodium',\n 'codebuddy',\n 'codebuddy-cn',\n 'codebuddycn',\n 'antigravity',\n]\n\nfunction normalizeIdeToken(value: string | undefined): string {\n return (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nexport function handleOpenFileRequest(\n body: OpenFileRequest,\n serverState: ServerState,\n): { success: true } {\n const absolutePath = resolveWorkspacePath(body.file, serverState.cwd)\n\n assertPathWithinIdeOpenScope(absolutePath, serverState.projectRoot)\n\n const userConfig = loadUserConfigSync(false, serverState.cwd, serverState.configRoot)\n const configuredIde = userConfig.ide\n const activeIde = serverState.ideInfo?.ide\n const activeIdeScheme = serverState.ideInfo?.scheme\n\n const configuredIdeMatchesActiveScheme =\n Boolean(configuredIde) &&\n Boolean(activeIdeScheme) &&\n normalizeIdeToken(configuredIde) === normalizeIdeToken(activeIdeScheme)\n\n const rawEditorHint = configuredIdeMatchesActiveScheme\n ? activeIdeScheme!\n : configuredIde || activeIde || activeIdeScheme || 'code'\n\n if (\n configuredIde &&\n activeIdeScheme &&\n normalizeIdeToken(activeIdeScheme).includes(normalizeIdeToken(configuredIde)) === false\n ) {\n serverLogger.warn(\n `Active IDE is ${activeIdeScheme}, but config forces ${configuredIde}. Using configured IDE.`,\n )\n }\n\n let editorHint = rawEditorHint\n if (rawEditorHint === 'vscode') editorHint = 'code'\n else if (rawEditorHint === 'vscode-insiders') editorHint = 'code-insiders'\n else if (rawEditorHint === 'vscodium') editorHint = 'codium'\n else if (rawEditorHint === 'trae-cn' || rawEditorHint === 'trae') editorHint = 'trae'\n\n serverLogger.debug(\n `SOURCE_OPEN: activeIde=${activeIde}, activeIdeScheme=${activeIdeScheme}, configuredIde=${configuredIde} -> rawEditorHint=${rawEditorHint}, finalEditorHint=${editorHint}`,\n )\n\n if (VSCODE_FAMILY_SCHEMES.includes(rawEditorHint)) {\n let normalizedPath = absolutePath.replace(/\\\\/g, '/')\n if (!normalizedPath.startsWith('/')) {\n normalizedPath = '/' + normalizedPath\n }\n const encodedPath = encodeURI(normalizedPath)\n const uri = `${rawEditorHint}://file${encodedPath}:${body.line}:${body.column}`\n serverLogger.debug(`SOURCE_OPEN: Bypassing launchIDE, using URI scheme directly: ${uri}`)\n\n try {\n if (process.platform === 'darwin') {\n execFileSync('open', [uri])\n } else if (process.platform === 'win32') {\n execFileSync('cmd', ['/c', 'start', '\"\"', uri])\n } else {\n execFileSync('xdg-open', [uri])\n }\n } catch (e) {\n serverLogger.error(`Failed to launch URI for SOURCE_OPEN (${uri}):`, e)\n launchIDE({\n file: absolutePath,\n line: body.line,\n column: body.column,\n editor: editorHint as Editor,\n type: process.platform === 'darwin' ? 'open' : 'exec',\n })\n }\n } else {\n launchIDE({\n file: absolutePath,\n line: body.line,\n column: body.column,\n editor: editorHint as Editor,\n type: process.platform === 'darwin' ? 'open' : 'exec',\n })\n }\n\n return { success: true }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { execSync } from 'node:child_process'\nimport { createLogger } from '../utils/logger.js'\nimport { getGlobalLogLevel } from '../config.js'\n\nconst serverLogger = createLogger('inspecto:server', { logLevel: getGlobalLogLevel() })\n\nfunction resolveGitRoot(_cwd: string): string | null {\n try {\n const output = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8' })\n return typeof output === 'string' ? output.trim() : null\n } catch (e) {\n serverLogger.warn('Failed to resolve git root via git rev-parse:', e)\n return null\n }\n}\n\nfunction findNearestAncestorWith(\n start: string,\n predicate: (dir: string) => boolean,\n): string | null {\n let current = start\n while (true) {\n if (predicate(current)) return current\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return null\n}\n\nexport function resolveWorkspaceRoot(): string {\n const cwd = process.cwd()\n const inspectoRoot = findNearestAncestorWith(cwd, dir =>\n fs.existsSync(path.join(dir, '.inspecto')),\n )\n if (inspectoRoot) return inspectoRoot\n\n const packageRoot = findNearestAncestorWith(cwd, dir =>\n fs.existsSync(path.join(dir, 'package.json')),\n )\n if (packageRoot) return packageRoot\n\n return resolveGitRoot(cwd) ?? cwd\n}\n\nexport function resolveProjectRoot(): string {\n const cwd = process.cwd()\n const packageRoot = findNearestAncestorWith(cwd, dir =>\n fs.existsSync(path.join(dir, 'package.json')),\n )\n if (packageRoot) return packageRoot\n\n const inspectoRoot = findNearestAncestorWith(cwd, dir =>\n fs.existsSync(path.join(dir, '.inspecto')),\n )\n if (inspectoRoot) return inspectoRoot\n\n return resolveGitRoot(cwd) ?? cwd\n}\n","import { loadUserConfigSync } from '../config.js'\n\nexport function resolveServerHost(cwd: string, configRoot: string): string {\n // Vitest sandbox environments can reject binding 0.0.0.0 even when the\n // same process can bind loopback successfully. Prefer loopback for tests so\n // plugin e2e coverage reflects real runtime behavior instead of sandbox\n // policy noise.\n if (process.env['VITEST']) return '127.0.0.1'\n\n const userConfig = loadUserConfigSync(false, cwd, configRoot)\n const configuredHost = userConfig['server.host']?.trim()\n if (configuredHost) return configuredHost\n return '127.0.0.1'\n}\n\nexport function resolvePublicServerUrl(args: {\n cwd: string\n configRoot: string\n port: number\n}): string {\n const userConfig = loadUserConfigSync(false, args.cwd, args.configRoot)\n const configuredPublicUrl = userConfig['server.publicUrl']?.trim()\n if (configuredPublicUrl) {\n return configuredPublicUrl.replace(/\\/$/, '')\n }\n\n const host = resolveServerHost(args.cwd, args.configRoot)\n return `http://${host}:${args.port}`\n}\n","import { createRequire } from 'node:module'\n\n// Safely resolve the client module without breaking ESM/CJS or bundling\nexport const resolveClientModule = () => {\n try {\n return createRequire(import.meta.url).resolve('@inspecto-dev/core')\n } catch {\n try {\n return require.resolve('@inspecto-dev/core')\n } catch {\n console.warn(\n '[inspecto] Could not resolve @inspecto-dev/core — falling back to bare specifier',\n )\n return '@inspecto-dev/core'\n }\n }\n}\n","export function getWebpackHtmlScript(serverPort: number, publicServerUrl?: string) {\n return `\nwindow.__AI_INSPECTOR_PORT__ = ${serverPort};\nwindow.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\n window.addEventListener('load', () => {\n if (window.InspectoClient) {\n window.InspectoClient.mountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n });\n }\n });\n`\n}\n\nexport function getWebpackAssetScript(serverPort: number, publicServerUrl?: string) {\n return `\nif (typeof window !== 'undefined') {\n window.__AI_INSPECTOR_PORT__ = ${serverPort};\n window.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\n const _initInspecto = () => {\n if (window.InspectoClient) {\n window.InspectoClient.mountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n });\n } else {\n setTimeout(_initInspecto, 100);\n }\n };\n if (document.readyState === 'complete') {\n _initInspecto();\n } else {\n window.addEventListener('load', _initInspecto);\n }\n}\n`\n}\n\nexport function injectWebpack(\n compiler: any,\n serverPortFn: () => Promise<number>,\n publicServerUrlFn: (port: number) => string,\n resolveClientModule: () => string,\n) {\n const inspectoClientPath = resolveClientModule()\n\n // Inject the client logic directly using the absolute path\n if (compiler.webpack && compiler.webpack.EntryPlugin) {\n // Webpack 5+\n new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, {\n name: undefined,\n }).apply(compiler)\n }\n\n compiler.hooks.compilation.tap('inspecto-overlay', (compilation: any) => {\n // Find HtmlWebpackPlugin (standard Webpack)\n const HtmlWebpackPlugin = compiler.options.plugins.find(\n (p: any) => p && p.constructor && p.constructor.name === 'HtmlWebpackPlugin',\n )\n if (HtmlWebpackPlugin) {\n const hooks = (HtmlWebpackPlugin.constructor as any).getHooks(compilation)\n hooks.alterAssetTagGroups.tapPromise('inspecto-overlay', async (data: any) => {\n const port = await serverPortFn()\n const publicServerUrl = publicServerUrlFn(port)\n data.headTags.unshift({\n tagName: 'script',\n voidTag: false,\n meta: { plugin: 'inspecto-overlay' },\n innerHTML: getWebpackHtmlScript(port, publicServerUrl),\n })\n return data\n })\n } else {\n // Fallback for frameworks like Next.js that don't use HtmlWebpackPlugin\n if (compilation.hooks.processAssets) {\n // Webpack 5+\n compilation.hooks.processAssets.tapPromise(\n {\n name: 'inspecto-overlay',\n stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n async (assets: any) => {\n const port = await serverPortFn()\n const publicServerUrl = publicServerUrlFn(port)\n\n // Only inject into the main client entry chunks (e.g. main-app, main.js, umi.js)\n const mainAssetKey = Object.keys(assets).find(\n key =>\n key.endsWith('.js') &&\n (key.includes('main') || key.includes('app') || key.includes('umi')),\n )\n if (!mainAssetKey) return\n\n const originalSource = assets[mainAssetKey].source()\n assets[mainAssetKey] = new compiler.webpack.sources.RawSource(\n getWebpackAssetScript(port, publicServerUrl) + '\\n' + originalSource,\n )\n },\n )\n }\n }\n })\n}\n","import { getWebpackHtmlScript } from './webpack.js'\n\nexport function injectRspack(\n compiler: any,\n serverPortFn: () => Promise<number>,\n resolveClientModule: () => string,\n) {\n const inspectoClientPath = resolveClientModule()\n\n // Use the exact same entry injection strategy as Webpack\n new compiler.webpack.EntryPlugin(compiler.context, inspectoClientPath, {}).apply(compiler)\n\n compiler.hooks.compilation.tap('inspecto-overlay', (compilation: any) => {\n const HtmlRspackPlugin = compiler.options.plugins.find(\n (p: any) => p && p.constructor && p.constructor.name === 'HtmlRspackPlugin',\n )\n if (HtmlRspackPlugin) {\n const hooks = (HtmlRspackPlugin.constructor as any).getHooks(compilation)\n hooks.alterAssetTagGroups.tapPromise('inspecto-overlay', async (data: any) => {\n const port = await serverPortFn()\n\n data.headTags.unshift({\n tagName: 'script',\n voidTag: false,\n meta: { plugin: 'inspecto-overlay' },\n innerHTML: getWebpackHtmlScript(port),\n })\n return data\n })\n }\n })\n}\n","export function getViteVirtualModuleScript(serverPort: number, publicServerUrl?: string) {\n return `\nimport { mountInspector } from '@inspecto-dev/core';\nwindow.__AI_INSPECTOR_PORT__ = ${serverPort};\nwindow.__AI_INSPECTOR_SERVER_URL__ = '${publicServerUrl ?? `http://127.0.0.1:${serverPort}`}';\nmountInspector({\n serverUrl: window.__AI_INSPECTOR_SERVER_URL__,\n});\n`\n}\n\nexport const VITE_VIRTUAL_MODULE_ID = '\\0virtual:inspecto-client'\nexport const VITE_VIRTUAL_IMPORT_ID = '/@id/__x00__virtual:inspecto-client'\n"],"mappings":";;;;;;;;AAAA,SAAS,sBAAsB;;;ACgBxB,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,iBAAiB,oBAAI,IAAI,CAAC,QAAQ,QAAQ,OAAO,OAAO,QAAQ,MAAM,CAAC;AAEpF,SAAS,8BAA8B,IAAoB;AACzD,SAAO,GAAG,QAAQ,OAAO,EAAE,EAAE,QAAQ,4CAA4C,EAAE;AACrF;AAEA,SAAS,yBAAyB,IAAgC;AAChE,MAAI,CAAC,GAAG,SAAS,qCAAqC,GAAG;AACvD,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,GAAG,QAAQ,GAAG;AACjC,MAAI,eAAe,IAAI;AACrB,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI,gBAAgB,GAAG,MAAM,aAAa,CAAC,EAAE,QAAQ,OAAO,EAAE,CAAC;AAC9E,aAAW,SAAS,OAAO,OAAO,SAAS,GAAG;AAC5C,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,UAAI,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,SAAS,GAAG;AACnE,eAAO,OAAO;AAAA,MAChB;AAAA,IACF,QAAQ;AACN;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT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;AAChC,YAAI,CAAC,OAAO,OAAO,QAAQ;AACzB;AAAC,UAAC,OAAO,OAAe,SAAS,CAAC;AAAA,QACpC;AACA;AAAC,QAAC,OAAO,OAAe,OAAO,uBAAuB,IAAI,KAAK,UAAU,IAAI;AAG7E,cAAM,MAAM,OAAO,YAAY,cAAc,sBAAsB;AACnE,YAAI,IAAK,QAAO,YAAY,iBAAiB,GAAG;AAAA,MAClD;AAAA,MAEA,mBAAmB,MAAM;AACvB,YAAI,gBAAgB,CAAC,WAAY,QAAO;AACxC,eAAO;AAAA,UACL;AAAA,UACA,MAAM;AAAA,YACJ;AAAA,cACE,KAAK;AAAA,cACL,OAAO,EAAE,MAAM,SAAS;AAAA,cACxB,UAAU,WAAW,sBAAsB;AAAA,YAC7C;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,iBAAiB,IAAI;AACnB,UAAI,gBAAgB,CAAC,GAAI,QAAO;AAChC,aAAO,gBAAgB,IAAI,OAAO;AAAA,IACpC;AAAA,IAEA,UAAU,MAAM,IAAI;AAClB,UAAI,gBAAgB,CAAC,GAAI,QAAO;AAEhC,YAAM,EAAE,SAAS,IAAI,yBAAyB,EAAE;AAEhD,YAAM,SAAS,gBAAgB;AAAA,QAC7B;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAED,UAAI,CAAC,UAAU,CAAC,OAAO,QAAS,QAAO;AAEvC,aAAO;AAAA,QACL,MAAM,OAAO;AAAA,QACb,KAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAEM,IAAM,WAAW;AACjB,IAAM,aAAa,eAAe;AAClC,IAAM,gBAAoD,eAAe;AACzE,IAAM,eAAe,eAAe;AACpC,IAAM,eAAe,eAAe;AACpC,IAAM,gBAAgB,eAAe;AAG5C,IAAO,cAAQ;","names":["path","MagicString","path","path","MagicString","p","MagicString","s","MagicString","i","MagicString","m","s","i","f","w","v","walk","w","s","MagicString","path","fs","path","os","crypto","path","parser","traverse_","traverse","fs","path","s","path","fs","i","w","path","fs","options","resolve","serverState","execFileSync","launchIDE","serverLogger","normalizeIdeToken","serverState","execFileSync","launchIDE","fs","path","serverLogger","path","fs","serverLogger","path","os","crypto","fs","serverLogger","resolve","resolve","path","serverLogger","runtime","resolveClientModule","p","resolveClientModule","p"]}
|