@spotpatch/vite 1.4.3 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -119,7 +119,7 @@ spotPatch({
119
119
  });
120
120
  ```
121
121
 
122
- The default Agent path is review-gated: it probes provider capabilities, works in an isolated Git worktree, exposes bounded file tools rather than an arbitrary shell, runs configured checks, and shows the complete Diff before Apply. SpotPatch does not commit, push, publish, or deploy application code.
122
+ The default Agent path is review-gated: **Check environment** provides an optional source-free capability diagnostic, while Run starts the real isolated tool session directly and proves tool continuation inline. The Agent supplies bounded nearby project conventions, exposes file tools rather than an arbitrary shell, reuses current host-run checks, and shows the complete Diff before Apply. SpotPatch does not commit, push, publish, or deploy application code.
123
123
 
124
124
  ### Security and production behavior
125
125
 
@@ -255,7 +255,7 @@ spotPatch({
255
255
  });
256
256
  ```
257
257
 
258
- 默认 Agent 路径必须经过审阅:先探测 Provider 能力,在隔离 Git worktree 中工作,只暴露有界文件工具而不是任意 Shell,执行已配置检查,并在 Apply 前展示完整 Diff。SpotPatch 不会替业务代码执行 commit、push、发包或部署。
258
+ 默认 Agent 路径必须经过审阅:“检查运行环境”提供不含源码的可选能力诊断;点击运行会直接进入真实隔离工具会话,并在会话内证明工具续接能力。Agent 会提供有界的就近项目规范,只暴露文件工具而不是任意 Shell,复用当前变更版本中由宿主实际执行的检查,并在 Apply 前展示完整 Diff。SpotPatch 不会替业务代码执行 commit、push、发包或部署。
259
259
 
260
260
  ### 安全与生产行为
261
261
 
package/dist/index.cjs CHANGED
@@ -51,7 +51,7 @@ var import_dev_server = require("@spotpatch/dev-server");
51
51
  // package.json
52
52
  var package_default = {
53
53
  name: "@spotpatch/vite",
54
- version: "1.4.3",
54
+ version: "1.4.4",
55
55
  description: "Vite development plugin for SpotPatch.",
56
56
  license: "MIT",
57
57
  repository: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts"],"sourcesContent":["export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type SpotPatchEditorPreference,\n} from \"@spotpatch/shared\";\n","import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = (config: UserConfig, environment: ConfigEnv): void => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = resolveOptions(userOptions, environmentAi);\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { createRuntimeAiConfig, type SpotPatchSession } from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n debug: options.debug,\n editor: options.editor,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.3\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createSpotPatchMiddleware,\n type AgentJobManager,\n type SourceRegistry,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n }),\n );\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => void;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n return sourceFilter.shouldTransform(path.resolve(cleanId), code);\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,oBAAiB;AAEjB,IAAAC,qBAMO;AACP,IAAAC,eAAsE;;;ACTtE,yBAA8B;AAC9B,qBAA6B;AAC7B,uBAAiB;AAEjB,wBAA6D;;;ACJ7D;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,MAAQ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AQ,YAAY,MAAM,kBAAAA,QAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,aACf,sDAAkC,iBAAiB,EAAE,KACrD;AAEN,kBAAU,mCAAe,aAAa,aAAa;AAEnD,gCAAwB,iDAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AOrDA,IAAAC,qBAKO;;;ARKP,oBAaO;","names":["import_node_path","import_dev_server","import_vite","path","VITE_VERSION","import_node_path","import_dev_server","path","import_node_path","import_compiler","import_node_path","import_compiler","path","path","path","import_dev_server"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts"],"sourcesContent":["export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type SpotPatchEditorPreference,\n} from \"@spotpatch/shared\";\n","import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = (config: UserConfig, environment: ConfigEnv): void => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = resolveOptions(userOptions, environmentAi);\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { createRuntimeAiConfig, type SpotPatchSession } from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n debug: options.debug,\n editor: options.editor,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.4\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createSpotPatchMiddleware,\n type AgentJobManager,\n type SourceRegistry,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n }),\n );\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => void;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n return sourceFilter.shouldTransform(path.resolve(cleanId), code);\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA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AE,CAAC,0BAA0B,MAAM;AAAA,UACvG;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;AL/FO,SAAS,UAAU,cAAoC,CAAC,GAAa;AAC1E,MAAI,cAAU,mCAAe,WAAW;AACxC,MAAI,wBACF,OAAO,OAAO,CAAC,CAAC;AAElB,MAAI,CAAC,QAAQ,SAAS;AACpB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,eAAW,yCAAqB;AACtC,QAAM,cAAU,kCAAc;AAC9B,QAAM,UAAU,OAAO,OAAO;AAAA,IAC5B,0BAA0B,MAAM;AAAA,IAChC,YAAY,MAAM;AAAA,EACpB,CAAkC;AAClC,QAAM,YAAY,CAAC,QAAoB,gBAAiC;AACtE,UAAM,OAAO,kBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,WAAW,QACd,QAAQ,UACR,sBAAQ,YAAY,MAAM,kBAAAA,QAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,aACf,sDAAkC,iBAAiB,EAAE,KACrD;AAEN,kBAAU,mCAAe,aAAa,aAAa;AAEnD,gCAAwB,iDAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AOrDA,IAAAC,qBAKO;;;ARKP,oBAaO;","names":["import_node_path","import_dev_server","import_vite","path","VITE_VERSION","import_node_path","import_dev_server","path","import_node_path","import_compiler","import_node_path","import_compiler","path","path","path","import_dev_server"]}
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ import { createRuntimeAiConfig } from "@spotpatch/dev-server";
18
18
  // package.json
19
19
  var package_default = {
20
20
  name: "@spotpatch/vite",
21
- version: "1.4.3",
21
+ version: "1.4.4",
22
22
  description: "Vite development plugin for SpotPatch.",
23
23
  license: "MIT",
24
24
  repository: {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts","../src/index.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = (config: UserConfig, environment: ConfigEnv): void => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = resolveOptions(userOptions, environmentAi);\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { createRuntimeAiConfig, type SpotPatchSession } from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n debug: options.debug,\n editor: options.editor,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.3\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createSpotPatchMiddleware,\n type AgentJobManager,\n type SourceRegistry,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n }),\n );\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => void;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n return sourceFilter.shouldTransform(path.resolve(cleanId), code);\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n","export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type SpotPatchEditorPreference,\n} from \"@spotpatch/shared\";\n"],"mappings":";AAAA,OAAOA,WAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAA6D;;;ACTtE,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AAEjB,SAAS,6BAAoD;;;ACJ7D;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AA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MAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,WAAW,QACd,QAAQ,MACR,QAAQ,YAAY,MAAMA,MAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,SACf,kCAAkC,iBAAiB,EAAE,KACrD;AAEN,cAAU,eAAe,aAAa,aAAa;AAEnD,4BAAwB,6BAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AOrDA;AAAA,EACE,yBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,OACK;;;ACKP;AAAA,EACE;AAAA,OAYK;","names":["path","path","path","path","path","path","createRuntimeAiConfig","resolveOptions"]}
1
+ {"version":3,"sources":["../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts","../src/index.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = (config: UserConfig, environment: ConfigEnv): void => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = resolveOptions(userOptions, environmentAi);\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { createRuntimeAiConfig, type SpotPatchSession } from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n debug: options.debug,\n editor: options.editor,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.4\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createSpotPatchMiddleware,\n type AgentJobManager,\n type SourceRegistry,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n }),\n );\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => void;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n return sourceFilter.shouldTransform(path.resolve(cleanId), code);\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n","export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type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,eAAe,MAAM,EAAE,CAAC,0BAA0B,MAAM;AAAA,UACvG;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;AL/FO,SAAS,UAAU,cAAoC,CAAC,GAAa;AAC1E,MAAI,UAAU,eAAe,WAAW;AACxC,MAAI,wBACF,OAAO,OAAO,CAAC,CAAC;AAElB,MAAI,CAAC,QAAQ,SAAS;AACpB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,WAAW,qBAAqB;AACtC,QAAM,UAAU,cAAc;AAC9B,QAAM,UAAU,OAAO,OAAO;AAAA,IAC5B,0BAA0B,MAAM;AAAA,IAChC,YAAY,MAAM;AAAA,EACpB,CAAkC;AAClC,QAAM,YAAY,CAAC,QAAoB,gBAAiC;AACtE,UAAM,OAAOC,MAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,WAAW,QACd,QAAQ,MACR,QAAQ,YAAY,MAAMA,MAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,SACf,kCAAkC,iBAAiB,EAAE,KACrD;AAEN,cAAU,eAAe,aAAa,aAAa;AAEnD,4BAAwB,6BAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AOrDA;AAAA,EACE,yBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,OACK;;;ACKP;AAAA,EACE;AAAA,OAYK;","names":["path","path","path","path","path","path","createRuntimeAiConfig","resolveOptions"]}
@@ -1,4 +1,4 @@
1
- import{createReact18Adapter as ca}from"@spotpatch/react-adapter";var f={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,So=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),xo=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function St(e){let t=Eo(e);return So.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,s)=>{let r=s.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)St(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Xe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let s=new URL(n,t),r=Co(s),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===a.origin?`${s.pathname}${s.search}${s.hash}`:r}catch{return Ao(n,xo)}}var Je="/__spotpatch/v1",xt="X-SpotPatch-Token",Ze=Object.freeze({bootstrap:`${Je}/bootstrap`,sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function at(e,t){return`${Ze.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),Mt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Dt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),vo=Object.freeze(["ready","consent-required","blocked"]),To=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),$t=Object.freeze(["added","modified","deleted"]),zt=Object.freeze(["passed","failed","cancelled","timed-out"]);var jt="data-spotpatch-source",wo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Ht(e){if(e===null)return;let t=wo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),s=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)))return Object.freeze({fileId:o,line:n,column:s})}var Bt="https://github.com/huanglvjing/spotpatch";function tn(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function _o(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:tn(e.source)}})}function Po(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Lo(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function Io(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:tn(e.source,e.code),react:_o(e.react),element:Po(e.element),styles:Lo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function nn(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(Io)),createdAt:e.createdAt})}var ko=new Set(Object.values(f)),No=new Set(Dt),Mo=new Set(zt),Do=new Set($t),rn=new Set(Mt),$o=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,zo=/^[A-Za-z0-9_-]+$/,jo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function re(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function gt(e){return re(e,64,1)&&typeof e=="string"&&$o.test(e)}function Ut(e){return re(e,128,22)&&typeof e=="string"&&zo.test(e)}function ft(e){return typeof e=="string"&&jo.test(e)&&Number.isFinite(Date.parse(e))}function Qe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function an(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function on(e,t){return e===void 0||re(e,t)}function st(e){return typeof e=="string"&&ko.has(e)}function sn(e){return!Ue(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:gt(e.providerProfileId)&&re(e.providerLabel,100)&&gt(e.modelProfileId)&&re(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&No.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||ft(e.checkedAt))&&(e.errorCode===void 0||st(e.errorCode))}function cn(e){if(!Ue(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ft(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!st(e.errorCode)||!Ue(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:r,total:a}=t;return!Qe(o)||!Qe(n)||!Qe(s)||!Qe(r)||!Qe(a)||a<o||a<n||a<s||a<r||a>o+n+s?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function At(e){return!Ue(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&gt(e.providerProfileId)&&re(e.providerLabel,100)&&gt(e.modelProfileId)&&re(e.modelLabel,100)&&re(e.phaseMessage,1024)&&ft(e.createdAt)&&ft(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||st(e.errorCode))}function Ho(e){return Ue(e)&&fe(e,["relativePath","kind","additions","deletions"])&&re(e.relativePath,1024)&&typeof e.kind=="string"&&Do.has(e.kind)&&Qe(e.additions)&&Qe(e.deletions)}function dn(e){return Ue(e)&&fe(e,["checkId","label","status","durationMs","output"])&&gt(e.checkId)&&re(e.label,100)&&typeof e.status=="string"&&Mo.has(e.status)&&Qe(e.durationMs)&&re(e.output,8e4)}function Bo(e){return Ue(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Ut(e.jobId)&&re(e.summary,8e4)&&re(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Ho)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(dn)}function ln(e){return Ue(e)&&fe(e,["snapshot","result"])&&At(e.snapshot)&&(e.result===void 0||Bo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Uo(e){return Ue(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&an(e.sequence)&&Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&ft(e.timestamp)&&typeof e.type=="string"&&Ue(e.data)}function pn(e){if(!Uo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&At(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&re(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&an(t.turn)&&re(t.toolCallId,256)&&re(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&on(t.relativePath,1024)&&on(t.checkLabel,100);case"check":return fe(t,["result"])&&dn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&st(t.code)&&re(t.message,1024);default:return!1}}var Go=2e6,un=1e5,Vo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wo(e){if(!(!ct(e)||e.ok!==!1||!ct(e.error)))return st(e.error.code)?e.error.code:void 0}function Jo(e){if(!ct(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function qo(e){return ct(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function fn(e){if(!(!ct(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))fn(t);Object.freeze(e)}}function ht(e){return fn(e),e}async function Fo(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let l=await n.read();if(l.done)return a+=s.decode(),a;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new M;a+=s.decode(l.value,{stream:!0})}}catch(l){throw l instanceof M?l:new M}finally{n.releaseLock()}}function hn(e){try{return JSON.parse(e)}catch{throw new M}}async function gn(e){let t=hn(await Fo(e,Go));if(!e.ok)throw new M(Wo(t));return Jo(t)}function Ko(e,t){if(!sn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Ct(e,t){if(!At(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Yo(e,t){if(!ln(e)||e.snapshot.jobId!==t)throw new M;return ht(e)}function Xo(e){if(!pn(e))throw new M;return ht(e)}function Zo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function mn(e){return e instanceof M?e.code:void 0}function bn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(a,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[xt]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await gn(R)}finally{t.delete(A)}}async function s(a,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(at(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[xt]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await gn(A);return}if(A.body===null)throw new M;let R=A.body.getReader(),j=new TextDecoder("utf-8",{fatal:!0}),u="",L=0,V=0,P=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>un)throw new M;let x=Xo(hn(b));if(x.jobId!==a||x.sequence<=V)throw new M;V=x.sequence,l(x)};try{for(;;){let b=await R.read();if(b.done){u+=j.decode(),P(u);return}if(L+=b.value.byteLength,L>Vo)throw await R.cancel(),new M;u+=j.decode(b.value,{stream:!0});let x=u.split(`
1
+ import{createReact18Adapter as ca}from"@spotpatch/react-adapter";var f={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,So=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),xo=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function St(e){let t=Eo(e);return So.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,s)=>{let r=s.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)St(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Xe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let s=new URL(n,t),r=Co(s),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===a.origin?`${s.pathname}${s.search}${s.hash}`:r}catch{return Ao(n,xo)}}var Je="/__spotpatch/v1",xt="X-SpotPatch-Token",Ze=Object.freeze({bootstrap:`${Je}/bootstrap`,sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function at(e,t){return`${Ze.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),Mt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Dt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),vo=Object.freeze(["ready","consent-required","blocked"]),To=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),$t=Object.freeze(["added","modified","deleted"]),zt=Object.freeze(["passed","failed","cancelled","timed-out"]);var jt="data-spotpatch-source",wo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Ht(e){if(e===null)return;let t=wo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),s=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)))return Object.freeze({fileId:o,line:n,column:s})}var Bt="https://github.com/huanglvjing/spotpatch";function tn(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function _o(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:tn(e.source)}})}function Po(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Lo(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function Io(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:tn(e.source,e.code),react:_o(e.react),element:Po(e.element),styles:Lo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function nn(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(Io)),createdAt:e.createdAt})}var ko=new Set(Object.values(f)),No=new Set(Dt),Mo=new Set(zt),Do=new Set($t),rn=new Set(Mt),$o=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,zo=/^[A-Za-z0-9_-]+$/,jo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function oe(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function gt(e){return oe(e,64,1)&&typeof e=="string"&&$o.test(e)}function Ut(e){return oe(e,128,22)&&typeof e=="string"&&zo.test(e)}function ft(e){return typeof e=="string"&&jo.test(e)&&Number.isFinite(Date.parse(e))}function Qe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function an(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function on(e,t){return e===void 0||oe(e,t)}function st(e){return typeof e=="string"&&ko.has(e)}function sn(e){return!Ue(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:gt(e.providerProfileId)&&oe(e.providerLabel,100)&&gt(e.modelProfileId)&&oe(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&No.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||ft(e.checkedAt))&&(e.errorCode===void 0||st(e.errorCode))}function cn(e){if(!Ue(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ft(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!st(e.errorCode)||!Ue(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:r,total:a}=t;return!Qe(o)||!Qe(n)||!Qe(s)||!Qe(r)||!Qe(a)||a<o||a<n||a<s||a<r||a>o+n+s?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function At(e){return!Ue(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&gt(e.providerProfileId)&&oe(e.providerLabel,100)&&gt(e.modelProfileId)&&oe(e.modelLabel,100)&&oe(e.phaseMessage,1024)&&ft(e.createdAt)&&ft(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||st(e.errorCode))}function Ho(e){return Ue(e)&&fe(e,["relativePath","kind","additions","deletions"])&&oe(e.relativePath,1024)&&typeof e.kind=="string"&&Do.has(e.kind)&&Qe(e.additions)&&Qe(e.deletions)}function dn(e){return Ue(e)&&fe(e,["checkId","label","status","durationMs","output"])&&gt(e.checkId)&&oe(e.label,100)&&typeof e.status=="string"&&Mo.has(e.status)&&Qe(e.durationMs)&&oe(e.output,8e4)}function Bo(e){return Ue(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Ut(e.jobId)&&oe(e.summary,8e4)&&oe(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Ho)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(dn)}function ln(e){return Ue(e)&&fe(e,["snapshot","result"])&&At(e.snapshot)&&(e.result===void 0||Bo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Uo(e){return Ue(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&an(e.sequence)&&Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&ft(e.timestamp)&&typeof e.type=="string"&&Ue(e.data)}function pn(e){if(!Uo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&At(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&oe(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&an(t.turn)&&oe(t.toolCallId,256)&&oe(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&on(t.relativePath,1024)&&on(t.checkLabel,100);case"check":return fe(t,["result"])&&dn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&st(t.code)&&oe(t.message,1024);default:return!1}}var Go=2e6,un=1e5,Vo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wo(e){if(!(!ct(e)||e.ok!==!1||!ct(e.error)))return st(e.error.code)?e.error.code:void 0}function Jo(e){if(!ct(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function qo(e){return ct(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function fn(e){if(!(!ct(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))fn(t);Object.freeze(e)}}function ht(e){return fn(e),e}async function Fo(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let l=await n.read();if(l.done)return a+=s.decode(),a;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new M;a+=s.decode(l.value,{stream:!0})}}catch(l){throw l instanceof M?l:new M}finally{n.releaseLock()}}function hn(e){try{return JSON.parse(e)}catch{throw new M}}async function gn(e){let t=hn(await Fo(e,Go));if(!e.ok)throw new M(Wo(t));return Jo(t)}function Ko(e,t){if(!sn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Ct(e,t){if(!At(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Yo(e,t){if(!ln(e)||e.snapshot.jobId!==t)throw new M;return ht(e)}function Xo(e){if(!pn(e))throw new M;return ht(e)}function Zo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function mn(e){return e instanceof M?e.code:void 0}function bn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(a,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[xt]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await gn(R)}finally{t.delete(A)}}async function s(a,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(at(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[xt]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await gn(A);return}if(A.body===null)throw new M;let R=A.body.getReader(),j=new TextDecoder("utf-8",{fatal:!0}),u="",L=0,V=0,P=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>un)throw new M;let x=Xo(hn(b));if(x.jobId!==a||x.sequence<=V)throw new M;V=x.sequence,l(x)};try{for(;;){let b=await R.read();if(b.done){u+=j.decode(),P(u);return}if(L+=b.value.byteLength,L>Vo)throw await R.cancel(),new M;u+=j.decode(b.value,{stream:!0});let x=u.split(`
2
2
  `);if(u=x.pop()??"",new TextEncoder().encode(u).byteLength>un)throw await R.cancel(),new M;for(let Q of x)P(Q)}}catch(b){throw b instanceof M||b instanceof DOMException&&b.name==="AbortError"?b:new M}finally{R.releaseLock()}}finally{t.delete(E)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let l=await n(Ze.sourceContext,"POST",a);if(!qo(l))throw new M;return Object.freeze({...l})},async openEditor(a){let l=await n(Ze.openEditor,"POST",a);if(!ct(l)||l.editor!=="auto"&&l.editor!=="vscode"&&l.editor!=="cursor")throw new M;return Object.freeze({editor:l.editor})},async agentCapability(a){return Ko(await n(Ze.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(Ze.agentWorkspaceHealth,"POST",r);if(!cn(a))throw new M;return ht(a)},async createAgentJob(a){let l=Zo(a);return Ct(await n(Ze.agentJobs,"POST",l),a)},agentEvents:s,async agentResult(a){return Yo(await n(at(a,"result"),"POST",r),a)},async cancelAgentJob(a){return Ct(await n(at(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return Ct(await n(at(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return Ct(await n(at(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var Qo=500,yn=256;function er(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function tr(e){return St(e)}function Sn(e,t,o){if(!tr(e))return e==="href"||e==="src"?Xe(t,o):e==="d"&&t.length>yn?`${t.slice(0,yn)}…`:er(G(t),Qo)}function Ae(e){return G(e)}var xn=Object.freeze(["display","position","inset","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height","margin","padding","box-sizing","overflow","overflow-x","overflow-y","flex","flex-direction","flex-wrap","align-items","align-content","justify-content","gap","grid-template-columns","grid-template-rows","font-family","font-size","font-weight","line-height","text-align","white-space","color","background-color","border","border-radius","opacity","visibility","z-index","transform"]);var mt=Object.freeze({cascade:"CSS shorthand and longhand cascade resolution is not available in v1.",cssInJs:"Runtime CSS-in-JS rules may not include original TypeScript source locations.",inaccessibleStylesheet:"A stylesheet could not be inspected because browser security denied access.",selector:"A stylesheet selector could not be evaluated and was skipped.",state:"Dynamic pseudo-class and pseudo-element rules may be unavailable in the current state."});function nr(e){return"selectorText"in e&&"style"in e}function or(e){return"cssRules"in e}function rr(e){if(typeof e.conditionText=="string"&&e.conditionText.length>0)return e.conditionText;let t=e.cssText.indexOf("{"),o=t<0?"":e.cssText.slice(0,t).trim();return o.length===0?void 0:o}function ar(e,t,o,n,s){return e.join(" ").length+(t?.length??0)+o.reduce((r,a)=>r+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((r,[a,l])=>r+a.length+l.length,0)+s.join(`
3
3
  `).length}function ir(e,t){return e.href===null?void 0:Xe(e.href,t)}function En(e,t,o,n,s,r){for(let a of t){if(nr(a)){let l=!1;try{l=e.matches(a.selectorText)}catch{r.add(mt.selector);continue}l&&s.push(Object.freeze({selector:Ae(a.selectorText),declarations:Ae(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(or(a)){let l=rr(a);En(e,a.cssRules,o,l===void 0?n:[...n,l],s,r)}}}function sr(e,t){if(t===void 0)return{};let o=t(e),n={};for(let s of xn){let r=Ae(o.getPropertyValue(s).trim());r.length>0&&(n[s]=r)}return n}function An(e){let t=new Set([mt.state,mt.cssInJs,mt.cascade]),o=[],n=e.readCssRules??(R=>R.cssRules);for(let R of e.document.styleSheets){let j;try{j=n(R)}catch{t.add(mt.inaccessibleStylesheet);continue}En(e.element,j,ir(R,e.document.baseURI),[],o,t)}let s=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:Ae(r),l=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),E=Object.entries(sr(e.element,l)),A=Array.from(t);for(;ar(s,a,o,Object.fromEntries(E),A)>e.maxCharacters;){if(E.length>0){E.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(s),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(E)),warnings:Object.freeze(A)})}var et=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),cr=new Set(["alt","autocomplete","checked","class","colspan","contenteditable","d","disabled","download","draggable","for","height","hidden","href","id","max","maxlength","min","minlength","multiple","name","open","pattern","placeholder","readonly","rel","required","role","rowspan","selected","src","step","style","tabindex","target","title","type","width"]),dr=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Rn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function lr(e){return cr.has(e)||e.startsWith("aria-")||e==="data-testid"}function vn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let s of e.attributes){let r=s.name.toLowerCase();if(!lr(r))continue;let a=Sn(r,s.value,n);a!==void 0&&o.push(`${r}="${Rn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Tn(e){return G(e).replaceAll(/\s+/gu," ").trim()}function wn(e,t,o,n){if(o.nodeCount>=et.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let s=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${s}${vn(e)}`),!dr.has(r)){for(let a of e.childNodes){if(o.nodeCount>=et.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let l=Tn(a.textContent??"");if(l.length>0){o.nodeCount+=1;let E=l.length<=et.maxTextCharacters?l:`${l.slice(0,et.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Rn(E)}`)}continue}if(a.nodeType===1){if(t>=et.maxDepth){o.truncated=!0;continue}wn(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${s}</${r}>`)}}function pr(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<et.maxParentDepth;)t.push(vn(o)),o=o.parentElement;return t}function ur(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Cn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function gr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function fr(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Cn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${gr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(l=>`.${Cn(l)}`).join(""),s=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(l=>l.tagName===e.tagName),r=s.indexOf(e),a=s.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function hr(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=fr(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function On(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};wn(e.element,0,o,t);let n=pr(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let s=Tn(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:hr(e.element),sanitizedHtml:ur(t.join(`
4
4
  `),e.maxCharacters),...s.length===0?{}:{textPreview:s.length<=et.maxTextCharacters?s:`${s.slice(0,et.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function _n(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function mr(e){return e.toLowerCase()}function Pn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Ln(e,t,o){let n=t.split("+").map(R=>R.trim().toLowerCase()).filter(R=>R.length>0),s=n.find(R=>R!=="mod"&&R!=="meta"&&R!=="ctrl"&&R!=="control"&&R!=="alt"&&R!=="option"&&R!=="shift");if(s===void 0||mr(e.key)!==s)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&_n(o),l=n.includes("ctrl")||n.includes("control")||r&&!_n(o),E=n.includes("alt")||n.includes("option"),A=n.includes("shift");return e.metaKey===a&&e.ctrlKey===l&&e.altKey===E&&e.shiftKey===A}function br(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function yr(e){let t=e.filter(l=>l.width>0&&l.height>0),o=t[0];if(o===void 0)return;let n=o.left,s=o.top,r=o.right,a=o.bottom;for(let l of t.slice(1))n=Math.min(n,l.left),s=Math.min(s,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom);return Object.freeze({x:n,y:s,width:r-n,height:a-s})}function In(e,t){if(t.startsWith("inline")){let o=yr(Array.from(e.getClientRects()));if(o!==void 0)return o}return br(e.getBoundingClientRect())}function kn(e,t){return In(e,t.getComputedStyle(e).display)}function Rt(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=In(e,o.display);return n.width>0&&n.height>0?n:void 0}var it="data-spotpatch-ui",bt=Object.freeze({highlight:2147483646,controls:2147483647});function Nn(e){if(e.closest(`[${it}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(it)}function Sr(e,t){return Rt(e,t)!==void 0}function xr(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Gt(e,t,o,n){let s=e.elementsFromPoint(o,n).filter(r=>!Nn(r)&&Sr(r,t));return s.find(r=>!xr(r))??s[0]}function Mn(e){return e instanceof Element&&Nn(e)}var Vt=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function Er(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function vt(e,t){let o="`".repeat(Math.max(3,Er(t)+1));return`${o}${e}
@@ -239,7 +239,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
239
239
  white-space: pre;
240
240
  user-select: text;
241
241
  }
242
- `;function Fn(e,t,o,n){let s=e.createElement("option");s.value=o,s.textContent=n,t.append(s)}function Yn(e,t,o){let n=o.messages(),s=d(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let a=d(e,"span");a.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(a,l);let E=d(e,"div");E.className="spotpatch-agent-setup";let A=d(e,"div");A.className="spotpatch-agent-selectors";let R=d(e,"label"),j=d(e,"span"),u=d(e,"select");R.append(j,u);let L=d(e,"label"),V=d(e,"span"),P=d(e,"select");L.append(V,P),A.append(R,L);let b=d(e,"label");b.className="spotpatch-consent";let x=d(e,"input");x.type="checkbox";let Q=d(e,"span");b.append(x,Q);let Y=d(e,"label");Y.className="spotpatch-consent spotpatch-workspace-consent",Y.hidden=!0;let h=d(e,"input");h.type="checkbox";let S=d(e,"span"),C=d(e,"strong"),T=d(e,"small");S.append(C,T),Y.append(h,S);let D=d(e,"div");D.className="spotpatch-agent-health-list";let F=d(e,"p");F.className="spotpatch-agent-workspace",F.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",D.append(F,$),E.append(A,b,Y,D);let ae=d(e,"div");ae.className="spotpatch-agent-job",ae.hidden=!0;let ie=d(e,"div");ie.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let k=d(e,"span");k.className="spotpatch-agent-status",ie.append(B,k);let Le=d(e,"p");Le.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let X=d(e,"ul");X.className="spotpatch-agent-activity";let Re=d(e,"div");Re.className="spotpatch-agent-result",Re.hidden=!0;let ve=d(e,"p");ve.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let ee=d(e,"div");ee.className="spotpatch-agent-checks";let N=d(e,"pre");N.className="spotpatch-agent-diff",N.tabIndex=0,N.setAttribute("aria-label",n.agent.diffAriaLabel),Re.append(ve,me,ee,N),ae.append(ie,Le,he,X,Re),s.append(r,E,ae);let be=K(e,n.agent.testConnection),Te=K(e,n.agent.verifyAndRun,"spotpatch-run"),te=K(e,n.agent.cancel),le=K(e,n.agent.apply,"spotpatch-primary"),De=K(e,n.agent.revert),ye=K(e,n.agent.revise),we=t.enabled?t.providers:[],$e=new Map(we.map(m=>[m.id,m])),w=!1,Oe=!0,ne=!1,_=!1,se=!1,oe=!1,Ce,Se,pe=[],Ie,xe="idle",_e=n.agent.connectionNotTested,ke,W="idle",Pe,Ne;for(let m of we)Fn(e,u,m.id,m.label);t.enabled&&(u.value=t.defaultProvider);let Ee=()=>$e.get(u.value),Ve=()=>{let m=Ee();if(P.replaceChildren(),m===void 0){Q.textContent=n.agent.providerUnavailable;return}for(let i of m.models)Fn(e,P,i.id,i.label);P.value=m.defaultModel,Q.textContent=n.agent.consent(m.label)},J=()=>{let m=t.enabled&&ne&&!_;Te.textContent=se?n.agent.verifying:oe?n.agent.run:n.agent.verifyAndRun,Te.classList.toggle("spotpatch-primary",oe),be.hidden=!m,Te.hidden=!m,be.disabled=!Oe||se||Ee()===void 0,Te.disabled=!Oe||se||!w||!x.checked||W==="idle"||W==="checking"||W==="blocked"||W==="consent-required"&&!h.checked||Ee()===void 0||P.value.length===0,(!_||!ne)&&(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},ze=()=>{if(W==="idle")F.textContent=n.agent.workspaceNotChecked;else if(W==="checking")F.textContent=n.agent.checkingWorkspace;else if(W==="ready")F.textContent=n.agent.workspaceReady;else if(W==="consent-required"){let m=Pe?.changes;F.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else F.textContent=Ne===void 0?n.errors.INTERNAL_ERROR:n.errors[Ne]};function je(){Ve(),x.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,oe=!1,J()}function ue(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,oe=!1,J()}Ve(),u.addEventListener("change",je),P.addEventListener("change",ue),x.addEventListener("change",J),h.addEventListener("change",J);function He(){if(Ce===void 0)return;let m=Ce,i=Se;B.textContent=`${m.providerLabel} · ${m.modelLabel}`,k.textContent=n.agent.status(m.status),Le.textContent=m.phaseMessage;let c=Ie??m.errorCode;he.hidden=c===void 0,he.textContent=c===void 0?"":n.errors[c],X.replaceChildren();for(let g of pe.slice(-8)){let O=d(e,"li");O.dataset.state=g.state,O.textContent=g.label,X.append(O)}Re.hidden=i===void 0,ve.textContent=i?.summary??"",me.replaceChildren(),ee.replaceChildren(),N.textContent=i?.diff??"";for(let g of i?.files??[]){let O=d(e,"li");O.textContent=`${g.kind} ${g.relativePath} (+${String(g.additions)} / -${String(g.deletions)})`,me.append(O)}for(let g of i?.checks??[]){let O=d(e,"details"),z=d(e,"summary");z.textContent=`${g.label}: ${g.status} · ${String(g.durationMs)} ms`;let I=d(e,"pre");I.textContent=g.output.length===0?n.agent.noOutput:g.output,O.append(z,I),ee.append(O)}be.hidden=!0,Te.hidden=!0,te.hidden=!ne||!m.canCancel,te.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,le.hidden=!ne||!m.canApply,De.hidden=!ne||!m.canRevert,ye.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function Ke(){n=o.messages(),a.textContent=n.agent.title,l.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,j.textContent=n.agent.provider,V.textContent=n.agent.model,u.setAttribute("aria-label",n.agent.providerAriaLabel),P.setAttribute("aria-label",n.agent.modelAriaLabel),C.textContent=n.agent.includeLocalChanges,T.textContent=n.agent.includeLocalChangesHelp,N.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,le.textContent=n.agent.apply,De.textContent=n.agent.revert,ye.textContent=n.agent.revise;let m=Ee();Q.textContent=m===void 0?n.agent.providerUnavailable:n.agent.consent(m.label),xe==="idle"?$.textContent=n.agent.connectionNotTested:xe==="probing"?$.textContent=n.agent.testingCapability:xe==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ke!==void 0?$.textContent=n.errors[ke]:Ee()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=_e,ze(),J(),He()}let nt=o.subscribe(Ke);return Ke(),Object.freeze({root:s,providerSelect:u,modelSelect:P,consentCheckbox:x,workspaceConsentCheckbox:h,testButton:be,runButton:Te,cancelButton:te,applyButton:le,revertButton:De,resetButton:ye,consentGranted(){return x.checked},workspaceConsentGranted(){return h.checked},readSelection(){let m=Ee(),i=m?.models.find(c=>c.id===P.value);return m===void 0||i===void 0?void 0:Object.freeze({providerProfileId:m.id,modelProfileId:i.id})},renderCapability(m,i,c,g){xe=m,_e=i,ke=g,se=m==="probing",oe=m==="ready"&&c?.state==="agent-ready",$.dataset.state=m,$.textContent=c?.state==="agent-ready"?`${i} · ${n.agent.toolsReady}`:i,J()},renderWorkspaceHealth(m,i,c){W=m,Pe=i,Ne=c??i?.errorCode,F.dataset.state=m,m!=="checking"&&(Y.hidden=m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(h.checked=!1),ze(),J()},renderJob(m,i,c,g){_=!0,E.hidden=!0,ae.hidden=!1,u.disabled=!0,P.disabled=!0,x.disabled=!0,h.disabled=!0,Ce=m,Se=i,pe=c,Ie=g,He()},resetJob(){_=!1,Ce=void 0,Se=void 0,pe=[],Ie=void 0,E.hidden=!1,ae.hidden=!0,u.disabled=!1,P.disabled=!1,x.disabled=!1,h.disabled=!1,X.replaceChildren(),me.replaceChildren(),ee.replaceChildren(),N.textContent="",he.textContent="",he.hidden=!0,J()},setContextReady(m){w=m,J()},setEditingEnabled(m){Oe=m,u.disabled=!m||_,P.disabled=!m||_,x.disabled=!m||_,h.disabled=!m||_,J()},setProviderConsent(m){x.checked=m,J()},setSelectionVisible(m){ne=m,J(),m||(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},dispose(){nt(),u.removeEventListener("change",je),P.removeEventListener("change",ue),x.removeEventListener("change",J),h.removeEventListener("change",J)}})}var Xn="http://www.w3.org/2000/svg",Jr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Jr,viewBox:"0 0 1 1"}}function Fr(e,t,o){let n=e.createElementNS(Xn,t);for(let[s,r]of Object.entries(o))n.setAttribute(s,r);return n}function Zn(e,t){let o=qr(t),n=Fr(e,"svg",{xmlns:Xn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function tt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:s}){let r=s-t-16,a=n-e-16,l=tt((s-t)/2,16,r),E=tt((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:tt(t/2,22,t-22),anchorY:tt(e/2,22,e-22),left:l,mode:"viewport",top:E});let A=o.x+o.width/2,R=o.y+o.height/2,j=tt(A-t/2,16,r),u=tt(R-e/2,16,a),L=j,V=u,P="viewport";return o.width>=t+48&&o.height>=e+48?P="center":o.y-e-14>=16?(V=o.y-e-14,P="above"):o.y+o.height+14+e<=n-16?(V=o.y+o.height+14,P="below"):o.x+o.width+14+t<=s-16?(L=o.x+o.width+14,P="right"):o.x-t-14>=16&&(L=o.x-t-14,P="left"),Object.freeze({anchorX:tt(A-L,22,t-22),anchorY:tt(R-V,22,e-22),left:L,mode:P,top:V})}var Kr=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Yr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Xr=Object.freeze({[f.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[f.INVALID_TOKEN]:"The local SpotPatch session expired.",[f.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[f.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[f.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[f.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[f.EDITOR_OPEN_FAILED]:"The editor request failed.",[f.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[f.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[f.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[f.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[f.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[f.AGENT_BUSY]:"Another write Agent job is still active.",[f.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[f.AGENT_CANCELLED]:"The Agent job was cancelled.",[f.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[f.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[f.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[f.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[f.TOOL_DENIED]:"A tool request violated local safety policy.",[f.TOOL_INPUT_INVALID]:"Invalid tool request.",[f.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[f.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[f.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[f.PATCH_REJECTED]:"The patch violated local policy.",[f.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[f.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[f.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Zr=Object.freeze({[f.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[f.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[f.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[f.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[f.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[f.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[f.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[f.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[f.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[f.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[f.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[f.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[f.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[f.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[f.AGENT_CANCELLED]:"Agent 任务已取消。",[f.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[f.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[f.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[f.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[f.TOOL_DENIED]:"工具请求违反本地安全策略。",[f.TOOL_INPUT_INVALID]:"工具请求无效。",[f.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[f.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[f.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[f.PATCH_REJECTED]:"补丁违反本地策略。",[f.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[f.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[f.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Qr=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),ea=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),ta=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Qr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Connection not tested",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifyAndRun:"Verify & run",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Kr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Xr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:ea,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未测试连接",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifyAndRun:"验证并运行",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Zr})});function eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function na(e,t){if(e!=="auto")return e;let o=eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(eo).find(s=>s!==void 0)??"en-US"}function to(e,t="auto"){let o=na(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>ta[o],subscribe(s){return n.add(s),()=>{n.delete(s)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let s of n)s()}})}var no=460,oo=620,oa=Object.freeze({previewing:560,selected:oo});function ra(e){let t=e.createElement("style");return t.textContent=`
242
+ `;function Fn(e,t,o,n){let s=e.createElement("option");s.value=o,s.textContent=n,t.append(s)}function Yn(e,t,o){let n=o.messages(),s=d(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let a=d(e,"span");a.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(a,l);let E=d(e,"div");E.className="spotpatch-agent-setup";let A=d(e,"div");A.className="spotpatch-agent-selectors";let R=d(e,"label"),j=d(e,"span"),u=d(e,"select");R.append(j,u);let L=d(e,"label"),V=d(e,"span"),P=d(e,"select");L.append(V,P),A.append(R,L);let b=d(e,"label");b.className="spotpatch-consent";let x=d(e,"input");x.type="checkbox";let Q=d(e,"span");b.append(x,Q);let Y=d(e,"label");Y.className="spotpatch-consent spotpatch-workspace-consent",Y.hidden=!0;let h=d(e,"input");h.type="checkbox";let S=d(e,"span"),C=d(e,"strong"),T=d(e,"small");S.append(C,T),Y.append(h,S);let D=d(e,"div");D.className="spotpatch-agent-health-list";let F=d(e,"p");F.className="spotpatch-agent-workspace",F.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",D.append(F,$),E.append(A,b,Y,D);let re=d(e,"div");re.className="spotpatch-agent-job",re.hidden=!0;let ae=d(e,"div");ae.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let k=d(e,"span");k.className="spotpatch-agent-status",ae.append(B,k);let Le=d(e,"p");Le.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let X=d(e,"ul");X.className="spotpatch-agent-activity";let Re=d(e,"div");Re.className="spotpatch-agent-result",Re.hidden=!0;let ve=d(e,"p");ve.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let ee=d(e,"div");ee.className="spotpatch-agent-checks";let N=d(e,"pre");N.className="spotpatch-agent-diff",N.tabIndex=0,N.setAttribute("aria-label",n.agent.diffAriaLabel),Re.append(ve,me,ee,N),re.append(ae,Le,he,X,Re),s.append(r,E,re);let be=K(e,n.agent.testConnection),Te=K(e,n.agent.run,"spotpatch-run"),te=K(e,n.agent.cancel),le=K(e,n.agent.apply,"spotpatch-primary"),De=K(e,n.agent.revert),ye=K(e,n.agent.revise),we=t.enabled?t.providers:[],$e=new Map(we.map(m=>[m.id,m])),w=!1,Oe=!0,ne=!1,_=!1,ie=!1,se=!1,Ce,Se,pe=[],Ie,xe="idle",_e=n.agent.connectionNotTested,ke,W="idle",Pe,Ne;for(let m of we)Fn(e,u,m.id,m.label);t.enabled&&(u.value=t.defaultProvider);let Ee=()=>$e.get(u.value),Ve=()=>{let m=Ee();if(P.replaceChildren(),m===void 0){Q.textContent=n.agent.providerUnavailable;return}for(let i of m.models)Fn(e,P,i.id,i.label);P.value=m.defaultModel,Q.textContent=n.agent.consent(m.label)},J=()=>{let m=t.enabled&&ne&&!_;Te.textContent=ie?n.agent.verifying:n.agent.run,Te.classList.toggle("spotpatch-primary",se),be.hidden=!m,Te.hidden=!m,be.disabled=!Oe||ie||Ee()===void 0,Te.disabled=!Oe||ie||!w||!x.checked||W==="idle"||W==="checking"||W==="blocked"||W==="consent-required"&&!h.checked||Ee()===void 0||P.value.length===0,(!_||!ne)&&(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},ze=()=>{if(W==="idle")F.textContent=n.agent.workspaceNotChecked;else if(W==="checking")F.textContent=n.agent.checkingWorkspace;else if(W==="ready")F.textContent=n.agent.workspaceReady;else if(W==="consent-required"){let m=Pe?.changes;F.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else F.textContent=Ne===void 0?n.errors.INTERNAL_ERROR:n.errors[Ne]};function je(){Ve(),x.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,se=!1,J()}function ue(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,se=!1,J()}Ve(),u.addEventListener("change",je),P.addEventListener("change",ue),x.addEventListener("change",J),h.addEventListener("change",J);function He(){if(Ce===void 0)return;let m=Ce,i=Se;B.textContent=`${m.providerLabel} · ${m.modelLabel}`,k.textContent=n.agent.status(m.status),Le.textContent=m.phaseMessage;let c=Ie??m.errorCode;he.hidden=c===void 0,he.textContent=c===void 0?"":n.errors[c],X.replaceChildren();for(let g of pe.slice(-8)){let O=d(e,"li");O.dataset.state=g.state,O.textContent=g.label,X.append(O)}Re.hidden=i===void 0,ve.textContent=i?.summary??"",me.replaceChildren(),ee.replaceChildren(),N.textContent=i?.diff??"";for(let g of i?.files??[]){let O=d(e,"li");O.textContent=`${g.kind} ${g.relativePath} (+${String(g.additions)} / -${String(g.deletions)})`,me.append(O)}for(let g of i?.checks??[]){let O=d(e,"details"),z=d(e,"summary");z.textContent=`${g.label}: ${g.status} · ${String(g.durationMs)} ms`;let I=d(e,"pre");I.textContent=g.output.length===0?n.agent.noOutput:g.output,O.append(z,I),ee.append(O)}be.hidden=!0,Te.hidden=!0,te.hidden=!ne||!m.canCancel,te.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,le.hidden=!ne||!m.canApply,De.hidden=!ne||!m.canRevert,ye.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function Ke(){n=o.messages(),a.textContent=n.agent.title,l.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,j.textContent=n.agent.provider,V.textContent=n.agent.model,u.setAttribute("aria-label",n.agent.providerAriaLabel),P.setAttribute("aria-label",n.agent.modelAriaLabel),C.textContent=n.agent.includeLocalChanges,T.textContent=n.agent.includeLocalChangesHelp,N.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,le.textContent=n.agent.apply,De.textContent=n.agent.revert,ye.textContent=n.agent.revise;let m=Ee();Q.textContent=m===void 0?n.agent.providerUnavailable:n.agent.consent(m.label),xe==="idle"?$.textContent=n.agent.connectionNotTested:xe==="probing"?$.textContent=n.agent.testingCapability:xe==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ke!==void 0?$.textContent=n.errors[ke]:Ee()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=_e,ze(),J(),He()}let nt=o.subscribe(Ke);return Ke(),Object.freeze({root:s,providerSelect:u,modelSelect:P,consentCheckbox:x,workspaceConsentCheckbox:h,testButton:be,runButton:Te,cancelButton:te,applyButton:le,revertButton:De,resetButton:ye,consentGranted(){return x.checked},workspaceConsentGranted(){return h.checked},readSelection(){let m=Ee(),i=m?.models.find(c=>c.id===P.value);return m===void 0||i===void 0?void 0:Object.freeze({providerProfileId:m.id,modelProfileId:i.id})},renderCapability(m,i,c,g){xe=m,_e=i,ke=g,ie=m==="probing",se=m==="ready"&&c?.state==="agent-ready",$.dataset.state=m,$.textContent=c?.state==="agent-ready"?`${i} · ${n.agent.toolsReady}`:i,J()},renderWorkspaceHealth(m,i,c){W=m,Pe=i,Ne=c??i?.errorCode,F.dataset.state=m,m!=="checking"&&(Y.hidden=m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(h.checked=!1),ze(),J()},renderJob(m,i,c,g){_=!0,E.hidden=!0,re.hidden=!1,u.disabled=!0,P.disabled=!0,x.disabled=!0,h.disabled=!0,Ce=m,Se=i,pe=c,Ie=g,He()},resetJob(){_=!1,Ce=void 0,Se=void 0,pe=[],Ie=void 0,E.hidden=!1,re.hidden=!0,u.disabled=!1,P.disabled=!1,x.disabled=!1,h.disabled=!1,X.replaceChildren(),me.replaceChildren(),ee.replaceChildren(),N.textContent="",he.textContent="",he.hidden=!0,J()},setContextReady(m){w=m,J()},setEditingEnabled(m){Oe=m,u.disabled=!m||_,P.disabled=!m||_,x.disabled=!m||_,h.disabled=!m||_,J()},setProviderConsent(m){x.checked=m,J()},setSelectionVisible(m){ne=m,J(),m||(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},dispose(){nt(),u.removeEventListener("change",je),P.removeEventListener("change",ue),x.removeEventListener("change",J),h.removeEventListener("change",J)}})}var Xn="http://www.w3.org/2000/svg",Jr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Jr,viewBox:"0 0 1 1"}}function Fr(e,t,o){let n=e.createElementNS(Xn,t);for(let[s,r]of Object.entries(o))n.setAttribute(s,r);return n}function Zn(e,t){let o=qr(t),n=Fr(e,"svg",{xmlns:Xn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function tt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:s}){let r=s-t-16,a=n-e-16,l=tt((s-t)/2,16,r),E=tt((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:tt(t/2,22,t-22),anchorY:tt(e/2,22,e-22),left:l,mode:"viewport",top:E});let A=o.x+o.width/2,R=o.y+o.height/2,j=tt(A-t/2,16,r),u=tt(R-e/2,16,a),L=j,V=u,P="viewport";return o.width>=t+48&&o.height>=e+48?P="center":o.y-e-14>=16?(V=o.y-e-14,P="above"):o.y+o.height+14+e<=n-16?(V=o.y+o.height+14,P="below"):o.x+o.width+14+t<=s-16?(L=o.x+o.width+14,P="right"):o.x-t-14>=16&&(L=o.x-t-14,P="left"),Object.freeze({anchorX:tt(A-L,22,t-22),anchorY:tt(R-V,22,e-22),left:L,mode:P,top:V})}var Kr=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Yr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Xr=Object.freeze({[f.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[f.INVALID_TOKEN]:"The local SpotPatch session expired.",[f.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[f.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[f.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[f.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[f.EDITOR_OPEN_FAILED]:"The editor request failed.",[f.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[f.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[f.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[f.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[f.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[f.AGENT_BUSY]:"Another write Agent job is still active.",[f.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[f.AGENT_CANCELLED]:"The Agent job was cancelled.",[f.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[f.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[f.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[f.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[f.TOOL_DENIED]:"A tool request violated local safety policy.",[f.TOOL_INPUT_INVALID]:"Invalid tool request.",[f.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[f.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[f.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[f.PATCH_REJECTED]:"The patch violated local policy.",[f.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[f.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[f.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Zr=Object.freeze({[f.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[f.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[f.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[f.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[f.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[f.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[f.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[f.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[f.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[f.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[f.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[f.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[f.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[f.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[f.AGENT_CANCELLED]:"Agent 任务已取消。",[f.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[f.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[f.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[f.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[f.TOOL_DENIED]:"工具请求违反本地安全策略。",[f.TOOL_INPUT_INVALID]:"工具请求无效。",[f.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[f.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[f.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[f.PATCH_REJECTED]:"补丁违反本地策略。",[f.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[f.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[f.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Qr=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),ea=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),ta=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Qr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Kr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Xr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:ea,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Zr})});function eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function na(e,t){if(e!=="auto")return e;let o=eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(eo).find(s=>s!==void 0)??"en-US"}function to(e,t="auto"){let o=na(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>ta[o],subscribe(s){return n.add(s),()=>{n.delete(s)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let s of n)s()}})}var no=460,oo=620,oa=Object.freeze({previewing:560,selected:oo});function ra(e){let t=e.createElement("style");return t.textContent=`
243
243
  :host {
244
244
  all: initial;
245
245
  --spotpatch-bg: #0e0e12;
@@ -941,8 +941,8 @@ ${vt(e.code.language,G(t.codeLines.join(`
941
941
  }
942
942
  ${Kn}
943
943
  `,t}function aa(e,t){return e.split(`
944
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ro(e,t,o=Object.freeze({enabled:!1}),n="auto"){let s=to(e,n),r=s.messages(),a=e.createElement("spotpatch-root");a.setAttribute(it,"");let l=a.attachShadow({mode:"open"}),E=K(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=d(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let R=d(e,"span");R.className="spotpatch-highlight-label",A.append(R);let j=d(e,"div");j.className="spotpatch-selection-highlights",j.setAttribute("aria-hidden","true");let u=d(e,"section");u.className="spotpatch-dialog",u.hidden=!0,u.tabIndex=-1,u.dataset.placement="viewport",u.setAttribute("role","dialog"),u.setAttribute("aria-labelledby","spotpatch-selection-title");let L=d(e,"span");L.className="spotpatch-anchor",L.setAttribute("aria-hidden","true");let V=d(e,"div");V.className="spotpatch-shell";let P=d(e,"header");P.className="spotpatch-header";let b=d(e,"div");b.className="spotpatch-brand-row";let x=d(e,"div");x.className="spotpatch-brand";let Q=d(e,"span");Q.className="spotpatch-brand-copy";let Y=d(e,"span");Y.className="spotpatch-brand-name";let h=d(e,"span");h.className="spotpatch-brand-context",Q.append(Y,h),x.append(Zn(e),Q);let S=d(e,"span");S.className="spotpatch-header-controls";let C=d(e,"a");C.className="spotpatch-repository",C.href=Bt,C.target="_blank",C.rel="noopener noreferrer";let T=K(e,"","spotpatch-locale"),D=K(e,"×","spotpatch-close");S.append(C,T,D),b.append(x,S);let F=d(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let ae=d(e,"div");ae.className="spotpatch-target-row";let ie=d(e,"span");ie.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,ae.append(ie,B),P.append(b,F,$,ae);let k=d(e,"div");k.className="spotpatch-body";let Le=d(e,"div");Le.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let X=d(e,"div");X.className="spotpatch-targets-heading";let Re=d(e,"span"),ve=d(e,"span");ve.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let ee=d(e,"span");ee.className="spotpatch-target-budget",ee.setAttribute("aria-live","polite");let N=d(e,"span");N.className="spotpatch-target-count",ve.append(me,ee),ae.append(N),X.append(Re,ve);let be=d(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let Te=d(e,"div");Te.className="spotpatch-target-progress-fill",be.append(Te);let te=d(e,"div");te.className="spotpatch-target-list",he.append(X,be,te);let le=d(e,"details");le.className="spotpatch-diagnostics";let De=d(e,"summary"),ye=d(e,"span"),we=d(e,"span");we.className="spotpatch-source-peek",we.textContent=r.diagnostics.resolving,De.append(ye,we);let $e=d(e,"pre");$e.className="spotpatch-summary",le.append(De,$e);let w=Yn(e,o,s);Le.append(he,le,w.root);let Oe=d(e,"div");Oe.className="spotpatch-preview-panel",Oe.hidden=!0;let ne=d(e,"pre");ne.className="spotpatch-prompt",ne.tabIndex=0,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Oe.append(ne),k.append(Le,Oe);let _=d(e,"footer");_.className="spotpatch-actions";let se=d(e,"div");se.className="spotpatch-context-state spotpatch-editor-feedback",se.dataset.state="idle",se.setAttribute("role","status"),se.setAttribute("aria-live","polite"),se.hidden=!0;let oe=K(e,r.actions.addElement),Ce=K(e,r.actions.reselect),Se=K(e,r.actions.openEditor),pe=K(e,r.actions.preview,"spotpatch-primary"),Ie=K(e,r.actions.copy,"spotpatch-primary"),xe=K(e,r.actions.back),_e=d(e,"div");_e.className="spotpatch-secondary-actions";let ke=d(e,"div");ke.className="spotpatch-primary-actions",oe.classList.add("spotpatch-icon-action"),oe.dataset.compactIcon="+",w.testButton.classList.add("spotpatch-icon-action"),w.testButton.dataset.compactIcon="✓",Se.classList.add("spotpatch-secondary-action"),Ce.classList.add("spotpatch-secondary-action"),_e.append(Se,Ce),ke.append(w.testButton,oe,w.runButton,pe,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Ie,xe),_.append(se,_e,ke),V.append(P,k,_),u.append(L,V);let W=d(e,"div");W.className="spotpatch-live",W.setAttribute("aria-live","polite"),W.setAttribute("aria-atomic","true"),l.append(ra(e),j,A,u,E,W),e.documentElement.append(a);let Pe,Ne,Ee="idle",Ve=!1,J=!1,ze="",je=!0,ue=[],He=0,Ke="idle";function nt(p){Ke=p,se.dataset.state=p,se.hidden=p==="idle",se.textContent=p==="opening"?r.announcements.editorOpening:p==="success"?r.announcements.editorOpened:p==="error"?r.announcements.editorFailed:"",I()}function m(p){return p.status==="ready"?r.targets.statusReady:p.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function i(p,y){let v=y===0?0:p/y;Te.style.width=`${String(v*100)}%`}function c(p){let y=te.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(y).find(v=>p===void 0||v.dataset.targetInstructionId===p)}function g(p,y){let v=l.activeElement?.closest("textarea[data-target-instruction-id]"),H=v?.dataset.targetInstructionId,ge=v?.selectionStart,Be=v?.selectionEnd;ue=p.map(U=>Object.freeze({...U})),He=y,te.replaceChildren();let We=p.filter(U=>U.instruction.trim().length>0).length,ce=p.reduce((U,q)=>U+q.instruction.trim().length,0);i(We,p.length),N.textContent=r.targets.count(p.length,y),me.textContent=r.targets.complete(We,p.length);let dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3),oe.disabled=!je||p.length>=y,oe.title=p.length>=y?r.targets.limitTitle(y):r.targets.addTitle,ie.textContent=p.length===1?p[0]?.label??r.context.selectedElement:r.context.selectedCount(p.length);for(let[U,q]of p.entries()){let rt=d(e,"div");rt.className="spotpatch-target-item",rt.dataset.active=String(q.active),rt.dataset.status=q.status,rt.dataset.targetId=q.id;let Tt=d(e,"div");Tt.className="spotpatch-target-summary";let lt=K(e,"","spotpatch-target-select");lt.dataset.activateTargetId=q.id,lt.setAttribute("aria-label",r.targets.activate(U+1)),lt.setAttribute("aria-expanded",String(q.active));let wt=d(e,"span");wt.className="spotpatch-target-index",wt.textContent=String(U+1);let Ot=d(e,"span");Ot.className="spotpatch-target-copy";let _t=d(e,"span");_t.className="spotpatch-target-name",_t.textContent=q.label;let Pt=d(e,"span");Pt.className="spotpatch-target-source",Pt.textContent=`${m(q)} · ${q.source}`,Ot.append(_t,Pt);let en=q.instruction.trim().length>0,yt=d(e,"span");yt.className="spotpatch-target-state",yt.dataset.complete=String(en),yt.textContent=en?r.targets.instructionReady:r.targets.instructionMissing,lt.append(wt,Ot,yt);let pt=K(e,"↗","spotpatch-target-open");pt.dataset.openTargetId=q.id,pt.disabled=!q.canOpenEditor,pt.setAttribute("aria-label",r.actions.openTarget(U+1)),pt.title=r.actions.openTarget(U+1);let ut=K(e,"×","spotpatch-target-remove");if(ut.dataset.removeTargetId=q.id,ut.disabled=!je,ut.setAttribute("aria-label",r.targets.remove(U+1)),ut.title=r.targets.removeTitle,Tt.append(lt,pt,ut),rt.append(Tt),q.active){let Lt=d(e,"label");Lt.className="spotpatch-target-editor";let It=d(e,"span");It.className="spotpatch-target-editor-head";let kt=d(e,"span");kt.className="spotpatch-target-editor-label",kt.textContent=r.targets.instructionLabel(q.label);let Nt=d(e,"span");Nt.className="spotpatch-target-editor-count",Nt.textContent=r.targets.instructionCount(q.instruction.length,2e3),It.append(kt,Nt);let Ye=d(e,"textarea");Ye.rows=4,Ye.maxLength=2e3,Ye.value=q.instruction,Ye.placeholder=r.targets.instructionPlaceholder,Ye.disabled=!je,Ye.dataset.targetInstructionId=q.id,Ye.setAttribute("aria-label",r.targets.instructionLabel(q.label)),Lt.append(It,Ye),rt.append(Lt)}te.append(rt)}if(H!==void 0){let U=c(H);U?.focus({preventScroll:!0}),ge!==void 0&&Be!==void 0&&U?.setSelectionRange(ge,Be)}}function O(p,y){ue=ue.map(U=>U.id===p?Object.freeze({...U,instruction:y}):U);let v=Array.from(te.querySelectorAll(".spotpatch-target-item")).find(U=>U.dataset.targetId===p);if(v===void 0)return;let H=y.trim().length>0,ge=v.querySelector(".spotpatch-target-state"),Be=v.querySelector(".spotpatch-target-editor-count");ge!==null&&(ge.dataset.complete=String(H),ge.textContent=H?r.targets.instructionReady:r.targets.instructionMissing),Be!==null&&(Be.textContent=r.targets.instructionCount(y.length,2e3));let We=ue.filter(U=>U.instruction.trim().length>0).length;me.textContent=r.targets.complete(We,ue.length),i(We,ue.length);let ce=ue.reduce((U,q)=>U+q.instruction.trim().length,0),dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3)}function z(p){j.replaceChildren(),Ne=p.find(y=>y.active)?.rect,Pe=Ne;for(let[y,v]of p.entries()){let H=d(e,"div");H.className="spotpatch-selection-highlight",H.dataset.targetId=v.id,H.dataset.active=String(v.active),H.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,H.style.width=`${String(v.rect.width)}px`,H.style.height=`${String(v.rect.height)}px`;let ge=d(e,"span");ge.textContent=`${String(y+1)} · ${v.label}`,H.append(ge),j.append(H)}I()}function I(){if(u.hidden)return;let p=e.defaultView,y=p?.innerWidth??e.documentElement.clientWidth,v=p?.innerHeight??e.documentElement.clientHeight,H=u.getBoundingClientRect(),ge=Ee==="previewing"?"previewing":"selected",Be=H.width>0?H.width:Math.min(no,y-32),We=H.height>0?H.height:Math.min(oa[ge],v-32),ce=Qn({dialogWidth:Be,dialogHeight:We,viewportWidth:y,viewportHeight:v,...Pe===void 0?{}:{target:Pe}});u.style.left=`${String(ce.left)}px`,u.style.top=`${String(ce.top)}px`,u.style.setProperty("--spotpatch-anchor-x",`${String(ce.anchorX)}px`),u.style.setProperty("--spotpatch-anchor-y",`${String(ce.anchorY)}px`),u.dataset.placement=ce.mode}function ot(p){let y=r.summary,v=aa(p,y.source);we.textContent=v??r.diagnostics.noExactSource;let H=`${y.browserContext}: ${y.collectionStatuses.ready}`,ge=`${y.browserContext}: ${y.collectionStatuses.loading}`,Be=`${y.browserContext}: ${y.collectionStatuses.failed}`,We=`${y.api}: ${y.apiStatuses.loading}`,ce=`${y.api}: ${y.apiStatuses.failed}`;p.includes(H)&&!p.includes(ge)&&!p.includes(We)&&!p.includes(Be)&&!p.includes(ce)?(B.dataset.state="ready",B.textContent=r.context.ready):p.includes(Be)||p.includes(ce)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function Xt(p,y,v){Ve=y,J=v,ze=p,$e.textContent=p,Se.disabled=!y,pe.disabled=!v,w.setContextReady(v),ot(p),I()}function Zt(p){Ee=p;let y=p==="selected",v=p==="previewing";E.hidden=y||v,Le.hidden=!y,Oe.hidden=!v,Ce.hidden=!y,oe.hidden=!y,Se.hidden=!y,pe.hidden=!y,_e.hidden=!y,w.setSelectionVisible(y),Ie.hidden=!v,xe.hidden=!v,F.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,I()}function Qt(){r=s.messages(),Y.textContent=r.brand.name,h.textContent=r.brand.context,C.textContent=r.brand.repository,C.title=r.brand.repositoryTitle,C.setAttribute("aria-label",r.brand.repositoryTitle),T.textContent=r.alternateLocaleName,T.title=r.switchLocale,T.setAttribute("aria-label",r.switchLocale),D.setAttribute("aria-label",r.dialog.close),D.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),Re.textContent=r.targets.title,ye.textContent=r.diagnostics.title,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),oe.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,Se.textContent=r.actions.openEditor,pe.textContent=r.actions.preview,Ie.textContent=r.actions.copy,xe.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=Ee==="inspecting"?r.trigger.stop:r.trigger.select,Zt(Ee),nt(Ke),ue.length>0?g(ue,He):(N.textContent=r.targets.count(0,He),me.textContent=r.targets.complete(0,0),i(0,0),ee.dataset.state="ready",ee.textContent=r.targets.instructionBudget(0,4e3),ie.textContent=r.context.selectedElement),ze.length>0?ot(ze):(we.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}le.addEventListener("toggle",I),T.addEventListener("click",s.toggle);let go=s.subscribe(Qt);return Qt(),Object.freeze({host:a,triggerButton:E,addTargetButton:oe,targetList:te,reselectButton:Ce,openEditorButton:Se,repositoryLink:C,previewButton:pe,copyButton:Ie,backButton:xe,closeButton:D,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentWorkspaceConsentCheckbox:w.workspaceConsentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(p){let y=p==="inspecting";E.setAttribute("aria-pressed",String(y)),E.textContent=y?r.trigger.stop:r.trigger.select,Zt(p)},renderEditorStatus:nt,showHighlight(p,y){Pe=p,A.hidden=!1,A.style.transform=`translate(${String(p.x)}px, ${String(p.y)}px)`,A.style.width=`${String(p.width)}px`,A.style.height=`${String(p.height)}px`,R.textContent=y,ie.textContent=y,I()},hideHighlight(){Pe=Ne,A.hidden=!0,R.textContent="",I()},showSelectionHighlights:z,hideSelectionHighlights(){j.replaceChildren(),Ne=void 0,Pe=void 0,I()},showSelection(p,y,v){Xt(p,y,v),E.hidden=!0,u.hidden=!1,I()},updateSelection:Xt,renderTargets:g,updateTargetInstruction:O,setPreviewEnabled(p){J=p,pe.disabled=!p,w.setContextReady(p)},hideSelection(){u.hidden=!0,E.hidden=!1,te.replaceChildren(),ue=[],He=0,ze="",nt("idle"),N.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),i(0,0),ie.textContent=r.context.selectedElement,$e.textContent="",ne.textContent="",we.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,Se.disabled=!0,pe.disabled=!0,Ve=!1,J=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){u.hidden=!0,E.hidden=!1},showPreview(p){ne.textContent=p,I()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(p){w.setProviderConsent(p)},setAgentEditingEnabled(p){je=p,oe.disabled=!p,Ce.disabled=!p,te.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(y=>{y.disabled=!p}),Se.disabled=!Ve,pe.disabled=!p||!J,w.setEditingEnabled(p),I()},renderAgentCapability(p,y,v,H){w.renderCapability(p,y,v,H);let ge=p==="ready"&&v?.state==="agent-ready";pe.classList.toggle("spotpatch-primary",!ge),I()},renderAgentWorkspaceHealth(p,y,v){w.renderWorkspaceHealth(p,y,v),I()},renderAgentJob(p,y,v,H){w.renderJob(p,y,v,H),I()},resetAgentJob(){w.resetJob(),I()},focusTargetInstruction(p){c(p)?.focus({preventScroll:!0})},focusPrompt(){ne.focus({preventScroll:!0})},announce(p){W.textContent="",W.textContent=p},locale:s.locale,messages:s.messages,agentWorkspaceConsentGranted:w.workspaceConsentGranted,subscribeLocale:s.subscribe,dispose(){le.removeEventListener("toggle",I),T.removeEventListener("click",s.toggle),go(),w.dispose(),a.remove()}})}function ia(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,r=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,r):o.unavailable}function ao(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${ia(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
945
- `)}function io(e,t){return`${e}:${t}`}function sa(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function so(e){let t=h=>mn(h)??f.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,s=new Set,r=new Map,a=0,l,E,A=!1,R=!1,j=()=>e.view.readAgentSelection(),u=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let S=await e.api.agentWorkspaceHealth();return h!==a||e.view.renderAgentWorkspaceHealth(S.state,S,S.errorCode),S}catch(S){throw h===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(S)),S}},L=h=>{l!==void 0&&e.view.renderAgentJob(l,E,Object.freeze([...r.values()]),h??l.errorCode)},V=()=>{let h=j();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(h.providerProfileId));let S=n.get(io(h.providerProfileId,h.modelProfileId));S===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,S)},P=async h=>{let S=j();if(S===void 0)throw new Error("Agent provider selection is unavailable.");let C=io(S.providerProfileId,S.modelProfileId),T=n.get(C);if(T!==void 0)return T;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let D=await e.api.agentCapability(S);if(h!==a)return D;if(D.state!=="agent-ready")throw new M(D.errorCode??f.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(C,D),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,D),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),D},b=async(h,S)=>{try{let C=await e.api.agentResult(h);if(S!==a||C.snapshot.jobId!==h)return;l=C.snapshot,E=C.result,L()}catch(C){S===a&&L(t(C))}},x=async(h,S)=>{try{await e.api.agentEvents(h,C=>{if(S!==a||C.jobId!==h)return;C.type==="snapshot"&&(l=C.data.snapshot,l.status==="applied"&&!A&&(A=!0,e.onApplied()));let T=sa(C);T!==void 0&&r.set(T.key,T),L()}),S===a&&await b(h,S)}catch(C){S===a&&!(C instanceof DOMException&&C.name==="AbortError")&&L(t(C))}},Q=async h=>{let S=l;if(S===void 0||R)return;R=!0;let C=a;l=Object.freeze({...S,status:h==="apply"?"applying":h==="cancel"?"cancelling":"reverting",phaseMessage:h==="apply"?e.view.messages().agent.applying:h==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),L();try{let T=h==="apply"?await e.api.applyAgentJob(S.jobId):h==="cancel"?await e.api.cancelAgentJob(S.jobId):await e.api.revertAgentJob(S.jobId);if(C!==a)return;l=T,T.status==="applied"&&!A&&(A=!0,e.onApplied()),await b(T.jobId,C)}catch(T){if(C!==a)return;l=S,await b(S.jobId,C),L(t(T)),e.view.announce(o(T))}finally{C===a&&(R=!1)}},Y=()=>{a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),V()};return Object.freeze({apply(){l?.canApply===!0&&Q("apply")},beginSelection(){Y();let h=a;e.ai.enabled&&u(h).catch(()=>{})},cancel(){l?.canCancel===!0&&Q("cancel")},consentChanged(){let h=j();h!==void 0&&(e.view.agentConsentGranted()?s.add(h.providerProfileId):s.delete(h.providerProfileId))},disposeSelection(){let h=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){a+=1,V(),u(a).catch(()=>{})},reset(){let h=A;Y(),h?e.onReselectRequired():e.ai.enabled&&u(a).catch(()=>{})},revert(){l?.canRevert===!0&&Q("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let h=j(),S=e.getAnnotation();if(h===void 0||S===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}s.add(h.providerProfileId);let C=++a;e.view.setAgentEditingEnabled(!1),Promise.all([P(C),u(C)]).then(async([,T])=>{if(C!==a)return;if(T.state==="blocked")throw new M(T.errorCode??f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(T.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new M(f.WORKTREE_DIRTY);let D=await e.api.createAgentJob({annotation:S,providerProfileId:h.providerProfileId,modelProfileId:h.modelProfileId,providerDataConsent:!0,workingTreeMode:T.state==="consent-required"?"include-local-changes":"require-clean"});C===a&&(l=D,E=void 0,r.clear(),L(),x(D.jobId,C))}).catch(T=>{C===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(T),void 0,t(T)),e.view.announce(o(T)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let h=++a;Promise.all([P(h),u(h)]).catch(S=>{h===a&&(e.view.renderAgentCapability("error",o(S),void 0,t(S)),e.view.announce(o(S)))})}})}function co(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function Ft(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function lo(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var da=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Kt(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function la(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,s=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function pa(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ua(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function po(e,t={}){let o=ua(t),n=t.view??ro(o.document,e.shortcut,e.ai,e.locale),s=t.api??bn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??jn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??lo(o.window.navigator),l=t.createId??(()=>co(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??Gn(o.window,e.sessionId,e.maxTargets),R=A.load(),j=qn({adapter:t.reactAdapter??ca({maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),u=Wt,L=!1,V,P,b=R?.targets.map(i=>{let c=qt(i.source);return{id:i.id,resolution:Object.freeze({source:i.source,react:i.react}),apiStatus:c===void 0?"not-required":i.code===void 0?"failed":"connected",code:i.code,collectionStatus:"ready",element:void 0,elementContext:i.element,instruction:i.instruction,marker:c,page:i.page,styles:i.styles}})??[],x=R?.activeTargetId,Q=R?.sequence??0,Y=R?.open??!1,h=!1,S=0,C=0,T=!1,D="",F,$,ae,ie,B=new Map;function k(i){u=Hn(u,i),n.renderStatus(u.status)}function Le(){return b.find(i=>i.id===x)??b.at(-1)}function he(i){if(!(i.elementContext===void 0||i.styles===void 0))return{id:i.id,instruction:i.instruction,page:i.page,source:i.resolution.source,react:i.resolution.react,element:i.elementContext,styles:i.styles,...i.code===void 0?{}:{code:i.code}}}function X(){let i=b.flatMap(g=>{let O=he(g);return O===void 0?[]:[O]});if(i.length===0){A.clear();return}let c=new Set(i.map(({id:g})=>g));A.save({...x!==void 0&&c.has(x)?{activeTargetId:x}:{},open:Y,sequence:Q,targets:i})}function Re(i,c){return L&&c===S&&u.status!=="idle"&&b.includes(i)}function ve(){let i=b.reduce((c,g)=>c+g.instruction.trim().length,0);return b.length>0&&i<=4e3&&b.every(c=>c.instruction.trim().length>0&&c.elementContext!==void 0&&c.styles!==void 0&&c.apiStatus!=="loading")}function me(){let i=n.messages().summary;return b.map((c,g)=>{let O=ao({resolution:c.resolution,...c.code===void 0?{}:{code:c.code},...c.styles===void 0?{}:{styles:c.styles},apiStatus:c.apiStatus,collectionStatus:c.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},i);return`${i.target(g+1,c.id===x)}
944
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ro(e,t,o=Object.freeze({enabled:!1}),n="auto"){let s=to(e,n),r=s.messages(),a=e.createElement("spotpatch-root");a.setAttribute(it,"");let l=a.attachShadow({mode:"open"}),E=K(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=d(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let R=d(e,"span");R.className="spotpatch-highlight-label",A.append(R);let j=d(e,"div");j.className="spotpatch-selection-highlights",j.setAttribute("aria-hidden","true");let u=d(e,"section");u.className="spotpatch-dialog",u.hidden=!0,u.tabIndex=-1,u.dataset.placement="viewport",u.setAttribute("role","dialog"),u.setAttribute("aria-labelledby","spotpatch-selection-title");let L=d(e,"span");L.className="spotpatch-anchor",L.setAttribute("aria-hidden","true");let V=d(e,"div");V.className="spotpatch-shell";let P=d(e,"header");P.className="spotpatch-header";let b=d(e,"div");b.className="spotpatch-brand-row";let x=d(e,"div");x.className="spotpatch-brand";let Q=d(e,"span");Q.className="spotpatch-brand-copy";let Y=d(e,"span");Y.className="spotpatch-brand-name";let h=d(e,"span");h.className="spotpatch-brand-context",Q.append(Y,h),x.append(Zn(e),Q);let S=d(e,"span");S.className="spotpatch-header-controls";let C=d(e,"a");C.className="spotpatch-repository",C.href=Bt,C.target="_blank",C.rel="noopener noreferrer";let T=K(e,"","spotpatch-locale"),D=K(e,"×","spotpatch-close");S.append(C,T,D),b.append(x,S);let F=d(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let re=d(e,"div");re.className="spotpatch-target-row";let ae=d(e,"span");ae.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,re.append(ae,B),P.append(b,F,$,re);let k=d(e,"div");k.className="spotpatch-body";let Le=d(e,"div");Le.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let X=d(e,"div");X.className="spotpatch-targets-heading";let Re=d(e,"span"),ve=d(e,"span");ve.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let ee=d(e,"span");ee.className="spotpatch-target-budget",ee.setAttribute("aria-live","polite");let N=d(e,"span");N.className="spotpatch-target-count",ve.append(me,ee),re.append(N),X.append(Re,ve);let be=d(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let Te=d(e,"div");Te.className="spotpatch-target-progress-fill",be.append(Te);let te=d(e,"div");te.className="spotpatch-target-list",he.append(X,be,te);let le=d(e,"details");le.className="spotpatch-diagnostics";let De=d(e,"summary"),ye=d(e,"span"),we=d(e,"span");we.className="spotpatch-source-peek",we.textContent=r.diagnostics.resolving,De.append(ye,we);let $e=d(e,"pre");$e.className="spotpatch-summary",le.append(De,$e);let w=Yn(e,o,s);Le.append(he,le,w.root);let Oe=d(e,"div");Oe.className="spotpatch-preview-panel",Oe.hidden=!0;let ne=d(e,"pre");ne.className="spotpatch-prompt",ne.tabIndex=0,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Oe.append(ne),k.append(Le,Oe);let _=d(e,"footer");_.className="spotpatch-actions";let ie=d(e,"div");ie.className="spotpatch-context-state spotpatch-editor-feedback",ie.dataset.state="idle",ie.setAttribute("role","status"),ie.setAttribute("aria-live","polite"),ie.hidden=!0;let se=K(e,r.actions.addElement),Ce=K(e,r.actions.reselect),Se=K(e,r.actions.openEditor),pe=K(e,r.actions.preview,"spotpatch-primary"),Ie=K(e,r.actions.copy,"spotpatch-primary"),xe=K(e,r.actions.back),_e=d(e,"div");_e.className="spotpatch-secondary-actions";let ke=d(e,"div");ke.className="spotpatch-primary-actions",se.classList.add("spotpatch-icon-action"),se.dataset.compactIcon="+",w.testButton.classList.add("spotpatch-icon-action"),w.testButton.dataset.compactIcon="✓",Se.classList.add("spotpatch-secondary-action"),Ce.classList.add("spotpatch-secondary-action"),_e.append(Se,Ce),ke.append(w.testButton,se,w.runButton,pe,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Ie,xe),_.append(ie,_e,ke),V.append(P,k,_),u.append(L,V);let W=d(e,"div");W.className="spotpatch-live",W.setAttribute("aria-live","polite"),W.setAttribute("aria-atomic","true"),l.append(ra(e),j,A,u,E,W),e.documentElement.append(a);let Pe,Ne,Ee="idle",Ve=!1,J=!1,ze="",je=!0,ue=[],He=0,Ke="idle";function nt(p){Ke=p,ie.dataset.state=p,ie.hidden=p==="idle",ie.textContent=p==="opening"?r.announcements.editorOpening:p==="success"?r.announcements.editorOpened:p==="error"?r.announcements.editorFailed:"",I()}function m(p){return p.status==="ready"?r.targets.statusReady:p.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function i(p,y){let v=y===0?0:p/y;Te.style.width=`${String(v*100)}%`}function c(p){let y=te.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(y).find(v=>p===void 0||v.dataset.targetInstructionId===p)}function g(p,y){let v=l.activeElement?.closest("textarea[data-target-instruction-id]"),H=v?.dataset.targetInstructionId,ge=v?.selectionStart,Be=v?.selectionEnd;ue=p.map(U=>Object.freeze({...U})),He=y,te.replaceChildren();let We=p.filter(U=>U.instruction.trim().length>0).length,ce=p.reduce((U,q)=>U+q.instruction.trim().length,0);i(We,p.length),N.textContent=r.targets.count(p.length,y),me.textContent=r.targets.complete(We,p.length);let dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3),se.disabled=!je||p.length>=y,se.title=p.length>=y?r.targets.limitTitle(y):r.targets.addTitle,ae.textContent=p.length===1?p[0]?.label??r.context.selectedElement:r.context.selectedCount(p.length);for(let[U,q]of p.entries()){let rt=d(e,"div");rt.className="spotpatch-target-item",rt.dataset.active=String(q.active),rt.dataset.status=q.status,rt.dataset.targetId=q.id;let Tt=d(e,"div");Tt.className="spotpatch-target-summary";let lt=K(e,"","spotpatch-target-select");lt.dataset.activateTargetId=q.id,lt.setAttribute("aria-label",r.targets.activate(U+1)),lt.setAttribute("aria-expanded",String(q.active));let wt=d(e,"span");wt.className="spotpatch-target-index",wt.textContent=String(U+1);let Ot=d(e,"span");Ot.className="spotpatch-target-copy";let _t=d(e,"span");_t.className="spotpatch-target-name",_t.textContent=q.label;let Pt=d(e,"span");Pt.className="spotpatch-target-source",Pt.textContent=`${m(q)} · ${q.source}`,Ot.append(_t,Pt);let en=q.instruction.trim().length>0,yt=d(e,"span");yt.className="spotpatch-target-state",yt.dataset.complete=String(en),yt.textContent=en?r.targets.instructionReady:r.targets.instructionMissing,lt.append(wt,Ot,yt);let pt=K(e,"↗","spotpatch-target-open");pt.dataset.openTargetId=q.id,pt.disabled=!q.canOpenEditor,pt.setAttribute("aria-label",r.actions.openTarget(U+1)),pt.title=r.actions.openTarget(U+1);let ut=K(e,"×","spotpatch-target-remove");if(ut.dataset.removeTargetId=q.id,ut.disabled=!je,ut.setAttribute("aria-label",r.targets.remove(U+1)),ut.title=r.targets.removeTitle,Tt.append(lt,pt,ut),rt.append(Tt),q.active){let Lt=d(e,"label");Lt.className="spotpatch-target-editor";let It=d(e,"span");It.className="spotpatch-target-editor-head";let kt=d(e,"span");kt.className="spotpatch-target-editor-label",kt.textContent=r.targets.instructionLabel(q.label);let Nt=d(e,"span");Nt.className="spotpatch-target-editor-count",Nt.textContent=r.targets.instructionCount(q.instruction.length,2e3),It.append(kt,Nt);let Ye=d(e,"textarea");Ye.rows=4,Ye.maxLength=2e3,Ye.value=q.instruction,Ye.placeholder=r.targets.instructionPlaceholder,Ye.disabled=!je,Ye.dataset.targetInstructionId=q.id,Ye.setAttribute("aria-label",r.targets.instructionLabel(q.label)),Lt.append(It,Ye),rt.append(Lt)}te.append(rt)}if(H!==void 0){let U=c(H);U?.focus({preventScroll:!0}),ge!==void 0&&Be!==void 0&&U?.setSelectionRange(ge,Be)}}function O(p,y){ue=ue.map(U=>U.id===p?Object.freeze({...U,instruction:y}):U);let v=Array.from(te.querySelectorAll(".spotpatch-target-item")).find(U=>U.dataset.targetId===p);if(v===void 0)return;let H=y.trim().length>0,ge=v.querySelector(".spotpatch-target-state"),Be=v.querySelector(".spotpatch-target-editor-count");ge!==null&&(ge.dataset.complete=String(H),ge.textContent=H?r.targets.instructionReady:r.targets.instructionMissing),Be!==null&&(Be.textContent=r.targets.instructionCount(y.length,2e3));let We=ue.filter(U=>U.instruction.trim().length>0).length;me.textContent=r.targets.complete(We,ue.length),i(We,ue.length);let ce=ue.reduce((U,q)=>U+q.instruction.trim().length,0),dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3)}function z(p){j.replaceChildren(),Ne=p.find(y=>y.active)?.rect,Pe=Ne;for(let[y,v]of p.entries()){let H=d(e,"div");H.className="spotpatch-selection-highlight",H.dataset.targetId=v.id,H.dataset.active=String(v.active),H.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,H.style.width=`${String(v.rect.width)}px`,H.style.height=`${String(v.rect.height)}px`;let ge=d(e,"span");ge.textContent=`${String(y+1)} · ${v.label}`,H.append(ge),j.append(H)}I()}function I(){if(u.hidden)return;let p=e.defaultView,y=p?.innerWidth??e.documentElement.clientWidth,v=p?.innerHeight??e.documentElement.clientHeight,H=u.getBoundingClientRect(),ge=Ee==="previewing"?"previewing":"selected",Be=H.width>0?H.width:Math.min(no,y-32),We=H.height>0?H.height:Math.min(oa[ge],v-32),ce=Qn({dialogWidth:Be,dialogHeight:We,viewportWidth:y,viewportHeight:v,...Pe===void 0?{}:{target:Pe}});u.style.left=`${String(ce.left)}px`,u.style.top=`${String(ce.top)}px`,u.style.setProperty("--spotpatch-anchor-x",`${String(ce.anchorX)}px`),u.style.setProperty("--spotpatch-anchor-y",`${String(ce.anchorY)}px`),u.dataset.placement=ce.mode}function ot(p){let y=r.summary,v=aa(p,y.source);we.textContent=v??r.diagnostics.noExactSource;let H=`${y.browserContext}: ${y.collectionStatuses.ready}`,ge=`${y.browserContext}: ${y.collectionStatuses.loading}`,Be=`${y.browserContext}: ${y.collectionStatuses.failed}`,We=`${y.api}: ${y.apiStatuses.loading}`,ce=`${y.api}: ${y.apiStatuses.failed}`;p.includes(H)&&!p.includes(ge)&&!p.includes(We)&&!p.includes(Be)&&!p.includes(ce)?(B.dataset.state="ready",B.textContent=r.context.ready):p.includes(Be)||p.includes(ce)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function Xt(p,y,v){Ve=y,J=v,ze=p,$e.textContent=p,Se.disabled=!y,pe.disabled=!v,w.setContextReady(v),ot(p),I()}function Zt(p){Ee=p;let y=p==="selected",v=p==="previewing";E.hidden=y||v,Le.hidden=!y,Oe.hidden=!v,Ce.hidden=!y,se.hidden=!y,Se.hidden=!y,pe.hidden=!y,_e.hidden=!y,w.setSelectionVisible(y),Ie.hidden=!v,xe.hidden=!v,F.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,I()}function Qt(){r=s.messages(),Y.textContent=r.brand.name,h.textContent=r.brand.context,C.textContent=r.brand.repository,C.title=r.brand.repositoryTitle,C.setAttribute("aria-label",r.brand.repositoryTitle),T.textContent=r.alternateLocaleName,T.title=r.switchLocale,T.setAttribute("aria-label",r.switchLocale),D.setAttribute("aria-label",r.dialog.close),D.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),Re.textContent=r.targets.title,ye.textContent=r.diagnostics.title,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),se.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,Se.textContent=r.actions.openEditor,pe.textContent=r.actions.preview,Ie.textContent=r.actions.copy,xe.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=Ee==="inspecting"?r.trigger.stop:r.trigger.select,Zt(Ee),nt(Ke),ue.length>0?g(ue,He):(N.textContent=r.targets.count(0,He),me.textContent=r.targets.complete(0,0),i(0,0),ee.dataset.state="ready",ee.textContent=r.targets.instructionBudget(0,4e3),ae.textContent=r.context.selectedElement),ze.length>0?ot(ze):(we.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}le.addEventListener("toggle",I),T.addEventListener("click",s.toggle);let go=s.subscribe(Qt);return Qt(),Object.freeze({host:a,triggerButton:E,addTargetButton:se,targetList:te,reselectButton:Ce,openEditorButton:Se,repositoryLink:C,previewButton:pe,copyButton:Ie,backButton:xe,closeButton:D,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentWorkspaceConsentCheckbox:w.workspaceConsentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(p){let y=p==="inspecting";E.setAttribute("aria-pressed",String(y)),E.textContent=y?r.trigger.stop:r.trigger.select,Zt(p)},renderEditorStatus:nt,showHighlight(p,y){Pe=p,A.hidden=!1,A.style.transform=`translate(${String(p.x)}px, ${String(p.y)}px)`,A.style.width=`${String(p.width)}px`,A.style.height=`${String(p.height)}px`,R.textContent=y,ae.textContent=y,I()},hideHighlight(){Pe=Ne,A.hidden=!0,R.textContent="",I()},showSelectionHighlights:z,hideSelectionHighlights(){j.replaceChildren(),Ne=void 0,Pe=void 0,I()},showSelection(p,y,v){Xt(p,y,v),E.hidden=!0,u.hidden=!1,I()},updateSelection:Xt,renderTargets:g,updateTargetInstruction:O,setPreviewEnabled(p){J=p,pe.disabled=!p,w.setContextReady(p)},hideSelection(){u.hidden=!0,E.hidden=!1,te.replaceChildren(),ue=[],He=0,ze="",nt("idle"),N.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),i(0,0),ae.textContent=r.context.selectedElement,$e.textContent="",ne.textContent="",we.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,Se.disabled=!0,pe.disabled=!0,Ve=!1,J=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){u.hidden=!0,E.hidden=!1},showPreview(p){ne.textContent=p,I()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(p){w.setProviderConsent(p)},setAgentEditingEnabled(p){je=p,se.disabled=!p,Ce.disabled=!p,te.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(y=>{y.disabled=!p}),Se.disabled=!Ve,pe.disabled=!p||!J,w.setEditingEnabled(p),I()},renderAgentCapability(p,y,v,H){w.renderCapability(p,y,v,H);let ge=p==="ready"&&v?.state==="agent-ready";pe.classList.toggle("spotpatch-primary",!ge),I()},renderAgentWorkspaceHealth(p,y,v){w.renderWorkspaceHealth(p,y,v),I()},renderAgentJob(p,y,v,H){w.renderJob(p,y,v,H),I()},resetAgentJob(){w.resetJob(),I()},focusTargetInstruction(p){c(p)?.focus({preventScroll:!0})},focusPrompt(){ne.focus({preventScroll:!0})},announce(p){W.textContent="",W.textContent=p},locale:s.locale,messages:s.messages,agentWorkspaceConsentGranted:w.workspaceConsentGranted,subscribeLocale:s.subscribe,dispose(){le.removeEventListener("toggle",I),T.removeEventListener("click",s.toggle),go(),w.dispose(),a.remove()}})}function ia(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,r=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,r):o.unavailable}function ao(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${ia(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
945
+ `)}function io(e,t){return`${e}:${t}`}function sa(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function so(e){let t=h=>mn(h)??f.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,s=new Set,r=new Map,a=0,l,E,A=!1,R=!1,j=()=>e.view.readAgentSelection(),u=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let S=await e.api.agentWorkspaceHealth();return h!==a||e.view.renderAgentWorkspaceHealth(S.state,S,S.errorCode),S}catch(S){throw h===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(S)),S}},L=h=>{l!==void 0&&e.view.renderAgentJob(l,E,Object.freeze([...r.values()]),h??l.errorCode)},V=()=>{let h=j();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(h.providerProfileId));let S=n.get(io(h.providerProfileId,h.modelProfileId));S===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,S)},P=async h=>{let S=j();if(S===void 0)throw new Error("Agent provider selection is unavailable.");let C=io(S.providerProfileId,S.modelProfileId),T=n.get(C);if(T!==void 0)return T;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let D=await e.api.agentCapability(S);if(h!==a)return D;if(D.state!=="agent-ready")throw new M(D.errorCode??f.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(C,D),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,D),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),D},b=async(h,S)=>{try{let C=await e.api.agentResult(h);if(S!==a||C.snapshot.jobId!==h)return;l=C.snapshot,E=C.result,L()}catch(C){S===a&&L(t(C))}},x=async(h,S)=>{try{await e.api.agentEvents(h,C=>{if(S!==a||C.jobId!==h)return;C.type==="snapshot"&&(l=C.data.snapshot,l.status==="applied"&&!A&&(A=!0,e.onApplied()));let T=sa(C);T!==void 0&&r.set(T.key,T),L()}),S===a&&await b(h,S)}catch(C){S===a&&!(C instanceof DOMException&&C.name==="AbortError")&&L(t(C))}},Q=async h=>{let S=l;if(S===void 0||R)return;R=!0;let C=a;l=Object.freeze({...S,status:h==="apply"?"applying":h==="cancel"?"cancelling":"reverting",phaseMessage:h==="apply"?e.view.messages().agent.applying:h==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),L();try{let T=h==="apply"?await e.api.applyAgentJob(S.jobId):h==="cancel"?await e.api.cancelAgentJob(S.jobId):await e.api.revertAgentJob(S.jobId);if(C!==a)return;l=T,T.status==="applied"&&!A&&(A=!0,e.onApplied()),await b(T.jobId,C)}catch(T){if(C!==a)return;l=S,await b(S.jobId,C),L(t(T)),e.view.announce(o(T))}finally{C===a&&(R=!1)}},Y=()=>{a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),V()};return Object.freeze({apply(){l?.canApply===!0&&Q("apply")},beginSelection(){Y();let h=a;e.ai.enabled&&u(h).catch(()=>{})},cancel(){l?.canCancel===!0&&Q("cancel")},consentChanged(){let h=j();h!==void 0&&(e.view.agentConsentGranted()?s.add(h.providerProfileId):s.delete(h.providerProfileId))},disposeSelection(){let h=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){a+=1,V(),u(a).catch(()=>{})},reset(){let h=A;Y(),h?e.onReselectRequired():e.ai.enabled&&u(a).catch(()=>{})},revert(){l?.canRevert===!0&&Q("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let h=j(),S=e.getAnnotation();if(h===void 0||S===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}s.add(h.providerProfileId);let C=++a;e.view.setAgentEditingEnabled(!1),u(C).then(async T=>{if(C!==a)return;if(T.state==="blocked")throw new M(T.errorCode??f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(T.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new M(f.WORKTREE_DIRTY);let D=await e.api.createAgentJob({annotation:S,providerProfileId:h.providerProfileId,modelProfileId:h.modelProfileId,providerDataConsent:!0,workingTreeMode:T.state==="consent-required"?"include-local-changes":"require-clean"});C===a&&(l=D,E=void 0,r.clear(),L(),x(D.jobId,C))}).catch(T=>{C===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(T),void 0,t(T)),e.view.announce(o(T)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let h=++a;Promise.all([P(h),u(h)]).catch(S=>{h===a&&(e.view.renderAgentCapability("error",o(S),void 0,t(S)),e.view.announce(o(S)))})}})}function co(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function Ft(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function lo(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var da=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Kt(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function la(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,s=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function pa(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ua(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function po(e,t={}){let o=ua(t),n=t.view??ro(o.document,e.shortcut,e.ai,e.locale),s=t.api??bn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??jn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??lo(o.window.navigator),l=t.createId??(()=>co(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??Gn(o.window,e.sessionId,e.maxTargets),R=A.load(),j=qn({adapter:t.reactAdapter??ca({maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),u=Wt,L=!1,V,P,b=R?.targets.map(i=>{let c=qt(i.source);return{id:i.id,resolution:Object.freeze({source:i.source,react:i.react}),apiStatus:c===void 0?"not-required":i.code===void 0?"failed":"connected",code:i.code,collectionStatus:"ready",element:void 0,elementContext:i.element,instruction:i.instruction,marker:c,page:i.page,styles:i.styles}})??[],x=R?.activeTargetId,Q=R?.sequence??0,Y=R?.open??!1,h=!1,S=0,C=0,T=!1,D="",F,$,re,ae,B=new Map;function k(i){u=Hn(u,i),n.renderStatus(u.status)}function Le(){return b.find(i=>i.id===x)??b.at(-1)}function he(i){if(!(i.elementContext===void 0||i.styles===void 0))return{id:i.id,instruction:i.instruction,page:i.page,source:i.resolution.source,react:i.resolution.react,element:i.elementContext,styles:i.styles,...i.code===void 0?{}:{code:i.code}}}function X(){let i=b.flatMap(g=>{let O=he(g);return O===void 0?[]:[O]});if(i.length===0){A.clear();return}let c=new Set(i.map(({id:g})=>g));A.save({...x!==void 0&&c.has(x)?{activeTargetId:x}:{},open:Y,sequence:Q,targets:i})}function Re(i,c){return L&&c===S&&u.status!=="idle"&&b.includes(i)}function ve(){let i=b.reduce((c,g)=>c+g.instruction.trim().length,0);return b.length>0&&i<=4e3&&b.every(c=>c.instruction.trim().length>0&&c.elementContext!==void 0&&c.styles!==void 0&&c.apiStatus!=="loading")}function me(){let i=n.messages().summary;return b.map((c,g)=>{let O=ao({resolution:c.resolution,...c.code===void 0?{}:{code:c.code},...c.styles===void 0?{}:{styles:c.styles},apiStatus:c.apiStatus,collectionStatus:c.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},i);return`${i.target(g+1,c.id===x)}
946
946
  ${O}`}).join(`
947
947
 
948
- `)}function ee(){let i=b.flatMap(c=>{if(!c.element?.isConnected)return[];let g=Rt(c.element,o.window);return g===void 0?[]:[{id:c.id,label:Kt(c.element),rect:g,active:c.id===x}]});i.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(i)}function N(i=!1){if(b.length===0)return;n.renderTargets(b.map(z=>({id:z.id,label:z.resolution.react.componentName??(z.element===void 0?z.elementContext?.tagName??"Element":Kt(z.element)),source:la(z,n.messages().context.sourceUnavailable),canOpenEditor:z.marker!==void 0,status:pa(z),active:z.id===x,instruction:z.instruction})),e.maxTargets),ee();let c=Le(),g=me(),O=c?.marker!==void 0;i?n.showSelection(g,O,ve()):n.updateSelection(g,O,ve())}function be(){if(!ve())return;let i=b.map(c=>{if(c.elementContext===void 0||c.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let g=[...c.apiStatus==="failed"?["Source context could not be loaded."]:[],...c.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:c.instruction.trim(),page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code},warnings:g}});return nn({id:l(),locale:n.locale(),createdAt:E(),page:Ft(o.document,o.window),targets:i})}function Te(i){n.showHighlight(kn(i,o.window),Kt(i))}function te(){F?.isConnected===!0&&F.focus({preventScroll:!0}),F=void 0}function le(){for(let i of B.values())o.window.clearTimeout(i);B.clear()}function De(){S+=1,s.cancelPending(),_.disposeSelection(),le(),$?.disconnect(),b=[],x=void 0,Y=!1,h=!1,T=!1,D="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),te()}function ye(){u.status==="inspecting"?k({type:"CANCEL"}):u.status==="selected"?k({type:"CLOSE"}):u.status==="previewing"&&(k({type:"BACK"}),k({type:"CLOSE"})),Y=!1,X(),n.hideSelection(),n.hideSelectionHighlights(),te(),n.hideHighlight()}function we(){if(u.status!=="inspecting"||!T||b.length===0){ye();return}T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(x),n.announce(n.messages().announcements.addCancelled)}function $e(){if(u.status==="inspecting"&&T){we();return}if(u.status!=="idle"){ye();return}if(b.length>0){Y=!0,k({type:"RESTORE"}),h||(_.beginSelection(),h=!0),N(!0),n.focusTargetInstruction(x),X();return}k({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function w(i=n.messages().announcements.chooseAnother){u.status==="selected"&&(k({type:"RESELECT"}),De(),n.hideHighlight(),n.announce(i))}function Oe(){if(u.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}T=!0,k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function ne(){S+=1,le(),$?.disconnect();for(let i of b)i.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),N(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=so({ai:e.ai,api:s,getAnnotation:be,onApplied:ne,onReselectRequired(){w(n.messages().announcements.reselectAfterChange)},view:n});async function se(i,c){let g=i.marker;if(g!==void 0)try{let O=await s.sourceContext({fileId:g.fileId,line:g.line,column:g.column,maxLines:e.budget.maxCodeLines});Re(i,c)&&(i.code=O,i.apiStatus="connected",X(),N(),n.announce(n.messages().announcements.sourceLoaded))}catch(O){Re(i,c)&&(i.code=void 0,i.apiStatus="failed",X(),N(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(O instanceof DOMException&&O.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function oe(i,c){let g=i.element;if(g===void 0)return;let O=o.window.setTimeout(()=>{if(B.delete(i.id),!Re(i,c))return;let z=!1;try{i.elementContext=On({element:g,maxCharacters:e.budget.domCharacters})}catch{i.elementContext=void 0,z=!0}try{i.styles=An({document:o.document,element:g,maxCharacters:e.budget.cssCharacters})}catch{i.styles=da,z=!0}i.collectionStatus=z?"failed":"ready",X(),N(),n.announce(z?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&i.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(i.styles.warnings.length)} warning(s).`)},0);B.set(i.id,O)}function Ce(i,c){return c!==void 0?b.find(g=>g.marker?.fileId===c.fileId&&g.marker.line===c.line&&g.marker.column===c.column):b.find(g=>g.element===i)}function Se(i){let c=j.resolve(i),g=qt(c.source),O=Ce(i,g);if(O!==void 0){x=O.id,T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(O.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(F=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,D="",_.beginSelection(),h=!0),Q+=1;let I={id:`target-${String(Q)}`,element:i,resolution:c,marker:g,page:Ft(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:g===void 0?"not-required":"loading",collectionStatus:"loading"};b.push(I),x=I.id,T=!1;let ot=S;k({type:"SELECT"}),n.hideHighlight(),$?.observe(i),N(!0),Y=!0,n.focusTargetInstruction(I.id),oe(I,ot),g!==void 0?se(I,ot):n.announce(c.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function pe(){if(V=void 0,u.status!=="inspecting"||P===void 0)return;let i=Gt(o.document,o.window,P.x,P.y);if(k({type:"HOVER"}),i===void 0){n.hideHighlight();return}Te(i)}function Ie(i){u.status==="inspecting"&&(P={x:i.clientX,y:i.clientY},V??=o.window.requestAnimationFrame(pe))}function xe(i){if(u.status!=="inspecting"||Mn(i.target))return;i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation();let c=Gt(o.document,o.window,i.clientX,i.clientY);if(c===void 0){n.announce(n.messages().announcements.noSelectable);return}Se(c)}function _e(i){if(i.key==="Escape"&&u.status!=="idle"){i.preventDefault(),u.status==="inspecting"&&T?we():u.status==="inspecting"||u.status==="selected"?ye():(k({type:"BACK"}),n.focusTargetInstruction(x));return}Pn(i.target)||!Ln(i,e.shortcut,o.window.navigator.userAgent)||(i.preventDefault(),$e())}function ke(i){if(u.status!=="selected"&&u.status!=="inspecting")return;let c=b.findIndex(z=>z.id===i);if(c<0)return;let[g]=b.splice(c,1);if(g===void 0)return;let O=B.get(g.id);if(O!==void 0&&(o.window.clearTimeout(O),B.delete(g.id)),g.element!==void 0&&$?.unobserve(g.element),x===g.id&&(x=b.at(-1)?.id),b.length===0){T=!0,u.status==="selected"&&k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}N(),X(),n.announce(n.messages().announcements.targetRemoved)}function W(){if(u.status==="idle"||b.length===0)return;let i=b.filter(c=>c.element!==void 0&&!c.element.isConnected);if(i.length>0){for(let c of i)c.element!==void 0&&($?.unobserve(c.element),c.element=void 0);N(),X(),n.announce(n.messages().announcements.detachedTargetPreserved);return}ee()}function Pe(i){let c=i===void 0?Le():b.find(I=>I.id===i);if(u.status!=="selected"||c?.marker===void 0)return;x!==c.id&&(x=c.id,N());let g=c.marker,O=S,z=++C;k({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:g.fileId,line:g.line,column:g.column}).then(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("success")}).catch(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("error")})}function Ne(i){if(u.status!=="selected"||!(i.target instanceof HTMLTextAreaElement))return;let c=i.target.dataset.targetInstructionId,g=b.find(O=>O.id===c);g!==void 0&&(g.instruction=i.target.value,n.updateTargetInstruction(g.id,g.instruction),n.setPreviewEnabled(ve()),X())}function Ee(){Pe()}function Ve(i){e.ai.enabled&&u.status==="selected"&&i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),_.run())}function J(){if(u.status!=="selected")return;let i=be();if(i===void 0){n.announce(n.messages().announcements.completeInstructions);return}D=r.compose(i),k({type:"PREVIEW"}),n.showPreview(D),n.focusPrompt()}function ze(){if(u.status!=="previewing"||D.length===0)return;if(a===void 0){k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let i=S;a.writeText(D).then(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_SUCCESS"}),n.focusTargetInstruction(x),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function je(){u.status==="previewing"&&(k({type:"BACK"}),n.focusTargetInstruction(x))}function ue(){if(!(!L||b.length===0)&&(N(),u.status==="previewing")){let i=be();i!==void 0&&(D=r.compose(i),n.showPreview(D))}}function He(i){let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-remove-target-id]");if(g?.dataset.removeTargetId!==void 0){ke(g.dataset.removeTargetId);return}let O=c.closest("button[data-open-target-id]");if(O?.dataset.openTargetId!==void 0){Pe(O.dataset.openTargetId);return}let I=c.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||I===void 0||!b.some(ot=>ot.id===I)||(x=I,N(),n.focusTargetInstruction(I))}function Ke(){w()}function nt(){L||(L=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Ie,!0),o.document.addEventListener("click",xe,!0),o.document.addEventListener("keydown",_e,!0),o.window.addEventListener("scroll",W,!0),o.window.addEventListener("resize",W),n.triggerButton.addEventListener("click",$e),n.addTargetButton.addEventListener("click",Oe),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",He),n.targetList.addEventListener("input",Ne),n.targetList.addEventListener("keydown",Ve),n.openEditorButton.addEventListener("click",Ee),n.previewButton.addEventListener("click",J),n.copyButton.addEventListener("click",ze),n.backButton.addEventListener("click",je),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),ie=n.subscribeLocale(ue),o.resizeObserver!==void 0&&($=new o.resizeObserver(W)),o.mutationObserver!==void 0&&(ae=new o.mutationObserver(W),ae.observe(o.document.documentElement,{childList:!0,subtree:!0})),Y&&b.length>0&&(k({type:"RESTORE"}),_.beginSelection(),h=!0,N(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function m(){if(!L){ie?.(),ie=void 0,n.dispose(),s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose();return}L=!1,ie?.(),ie=void 0,o.document.removeEventListener("pointermove",Ie,!0),o.document.removeEventListener("click",xe,!0),o.document.removeEventListener("keydown",_e,!0),o.window.removeEventListener("scroll",W,!0),o.window.removeEventListener("resize",W),n.triggerButton.removeEventListener("click",$e),n.addTargetButton.removeEventListener("click",Oe),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",He),n.targetList.removeEventListener("input",Ne),n.targetList.removeEventListener("keydown",Ve),n.openEditorButton.removeEventListener("click",Ee),n.previewButton.removeEventListener("click",J),n.copyButton.removeEventListener("click",ze),n.backButton.removeEventListener("click",je),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),V!==void 0&&(o.window.cancelAnimationFrame(V),V=void 0),le(),X(),$?.disconnect(),ae?.disconnect(),$=void 0,ae=void 0,b=[],x=void 0,D="",P=void 0,F=void 0,s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose(),n.dispose(),u=Wt}return Object.freeze({mount:nt,dispose:m,getState:()=>u})}var uo="__spotpatchRuntime__";function Yt(e){let t=globalThis;t[uo]?.dispose();let o=po(e);t[uo]=o,o.mount()}Yt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
948
+ `)}function ee(){let i=b.flatMap(c=>{if(!c.element?.isConnected)return[];let g=Rt(c.element,o.window);return g===void 0?[]:[{id:c.id,label:Kt(c.element),rect:g,active:c.id===x}]});i.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(i)}function N(i=!1){if(b.length===0)return;n.renderTargets(b.map(z=>({id:z.id,label:z.resolution.react.componentName??(z.element===void 0?z.elementContext?.tagName??"Element":Kt(z.element)),source:la(z,n.messages().context.sourceUnavailable),canOpenEditor:z.marker!==void 0,status:pa(z),active:z.id===x,instruction:z.instruction})),e.maxTargets),ee();let c=Le(),g=me(),O=c?.marker!==void 0;i?n.showSelection(g,O,ve()):n.updateSelection(g,O,ve())}function be(){if(!ve())return;let i=b.map(c=>{if(c.elementContext===void 0||c.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let g=[...c.apiStatus==="failed"?["Source context could not be loaded."]:[],...c.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:c.instruction.trim(),page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code},warnings:g}});return nn({id:l(),locale:n.locale(),createdAt:E(),page:Ft(o.document,o.window),targets:i})}function Te(i){n.showHighlight(kn(i,o.window),Kt(i))}function te(){F?.isConnected===!0&&F.focus({preventScroll:!0}),F=void 0}function le(){for(let i of B.values())o.window.clearTimeout(i);B.clear()}function De(){S+=1,s.cancelPending(),_.disposeSelection(),le(),$?.disconnect(),b=[],x=void 0,Y=!1,h=!1,T=!1,D="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),te()}function ye(){u.status==="inspecting"?k({type:"CANCEL"}):u.status==="selected"?k({type:"CLOSE"}):u.status==="previewing"&&(k({type:"BACK"}),k({type:"CLOSE"})),Y=!1,X(),n.hideSelection(),n.hideSelectionHighlights(),te(),n.hideHighlight()}function we(){if(u.status!=="inspecting"||!T||b.length===0){ye();return}T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(x),n.announce(n.messages().announcements.addCancelled)}function $e(){if(u.status==="inspecting"&&T){we();return}if(u.status!=="idle"){ye();return}if(b.length>0){Y=!0,k({type:"RESTORE"}),h||(_.beginSelection(),h=!0),N(!0),n.focusTargetInstruction(x),X();return}k({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function w(i=n.messages().announcements.chooseAnother){u.status==="selected"&&(k({type:"RESELECT"}),De(),n.hideHighlight(),n.announce(i))}function Oe(){if(u.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}T=!0,k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function ne(){S+=1,le(),$?.disconnect();for(let i of b)i.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),N(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=so({ai:e.ai,api:s,getAnnotation:be,onApplied:ne,onReselectRequired(){w(n.messages().announcements.reselectAfterChange)},view:n});async function ie(i,c){let g=i.marker;if(g!==void 0)try{let O=await s.sourceContext({fileId:g.fileId,line:g.line,column:g.column,maxLines:e.budget.maxCodeLines});Re(i,c)&&(i.code=O,i.apiStatus="connected",X(),N(),n.announce(n.messages().announcements.sourceLoaded))}catch(O){Re(i,c)&&(i.code=void 0,i.apiStatus="failed",X(),N(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(O instanceof DOMException&&O.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function se(i,c){let g=i.element;if(g===void 0)return;let O=o.window.setTimeout(()=>{if(B.delete(i.id),!Re(i,c))return;let z=!1;try{i.elementContext=On({element:g,maxCharacters:e.budget.domCharacters})}catch{i.elementContext=void 0,z=!0}try{i.styles=An({document:o.document,element:g,maxCharacters:e.budget.cssCharacters})}catch{i.styles=da,z=!0}i.collectionStatus=z?"failed":"ready",X(),N(),n.announce(z?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&i.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(i.styles.warnings.length)} warning(s).`)},0);B.set(i.id,O)}function Ce(i,c){return c!==void 0?b.find(g=>g.marker?.fileId===c.fileId&&g.marker.line===c.line&&g.marker.column===c.column):b.find(g=>g.element===i)}function Se(i){let c=j.resolve(i),g=qt(c.source),O=Ce(i,g);if(O!==void 0){x=O.id,T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(O.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(F=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,D="",_.beginSelection(),h=!0),Q+=1;let I={id:`target-${String(Q)}`,element:i,resolution:c,marker:g,page:Ft(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:g===void 0?"not-required":"loading",collectionStatus:"loading"};b.push(I),x=I.id,T=!1;let ot=S;k({type:"SELECT"}),n.hideHighlight(),$?.observe(i),N(!0),Y=!0,n.focusTargetInstruction(I.id),se(I,ot),g!==void 0?ie(I,ot):n.announce(c.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function pe(){if(V=void 0,u.status!=="inspecting"||P===void 0)return;let i=Gt(o.document,o.window,P.x,P.y);if(k({type:"HOVER"}),i===void 0){n.hideHighlight();return}Te(i)}function Ie(i){u.status==="inspecting"&&(P={x:i.clientX,y:i.clientY},V??=o.window.requestAnimationFrame(pe))}function xe(i){if(u.status!=="inspecting"||Mn(i.target))return;i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation();let c=Gt(o.document,o.window,i.clientX,i.clientY);if(c===void 0){n.announce(n.messages().announcements.noSelectable);return}Se(c)}function _e(i){if(i.key==="Escape"&&u.status!=="idle"){i.preventDefault(),u.status==="inspecting"&&T?we():u.status==="inspecting"||u.status==="selected"?ye():(k({type:"BACK"}),n.focusTargetInstruction(x));return}Pn(i.target)||!Ln(i,e.shortcut,o.window.navigator.userAgent)||(i.preventDefault(),$e())}function ke(i){if(u.status!=="selected"&&u.status!=="inspecting")return;let c=b.findIndex(z=>z.id===i);if(c<0)return;let[g]=b.splice(c,1);if(g===void 0)return;let O=B.get(g.id);if(O!==void 0&&(o.window.clearTimeout(O),B.delete(g.id)),g.element!==void 0&&$?.unobserve(g.element),x===g.id&&(x=b.at(-1)?.id),b.length===0){T=!0,u.status==="selected"&&k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}N(),X(),n.announce(n.messages().announcements.targetRemoved)}function W(){if(u.status==="idle"||b.length===0)return;let i=b.filter(c=>c.element!==void 0&&!c.element.isConnected);if(i.length>0){for(let c of i)c.element!==void 0&&($?.unobserve(c.element),c.element=void 0);N(),X(),n.announce(n.messages().announcements.detachedTargetPreserved);return}ee()}function Pe(i){let c=i===void 0?Le():b.find(I=>I.id===i);if(u.status!=="selected"||c?.marker===void 0)return;x!==c.id&&(x=c.id,N());let g=c.marker,O=S,z=++C;k({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:g.fileId,line:g.line,column:g.column}).then(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("success")}).catch(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("error")})}function Ne(i){if(u.status!=="selected"||!(i.target instanceof HTMLTextAreaElement))return;let c=i.target.dataset.targetInstructionId,g=b.find(O=>O.id===c);g!==void 0&&(g.instruction=i.target.value,n.updateTargetInstruction(g.id,g.instruction),n.setPreviewEnabled(ve()),X())}function Ee(){Pe()}function Ve(i){e.ai.enabled&&u.status==="selected"&&i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),_.run())}function J(){if(u.status!=="selected")return;let i=be();if(i===void 0){n.announce(n.messages().announcements.completeInstructions);return}D=r.compose(i),k({type:"PREVIEW"}),n.showPreview(D),n.focusPrompt()}function ze(){if(u.status!=="previewing"||D.length===0)return;if(a===void 0){k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let i=S;a.writeText(D).then(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_SUCCESS"}),n.focusTargetInstruction(x),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function je(){u.status==="previewing"&&(k({type:"BACK"}),n.focusTargetInstruction(x))}function ue(){if(!(!L||b.length===0)&&(N(),u.status==="previewing")){let i=be();i!==void 0&&(D=r.compose(i),n.showPreview(D))}}function He(i){let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-remove-target-id]");if(g?.dataset.removeTargetId!==void 0){ke(g.dataset.removeTargetId);return}let O=c.closest("button[data-open-target-id]");if(O?.dataset.openTargetId!==void 0){Pe(O.dataset.openTargetId);return}let I=c.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||I===void 0||!b.some(ot=>ot.id===I)||(x=I,N(),n.focusTargetInstruction(I))}function Ke(){w()}function nt(){L||(L=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Ie,!0),o.document.addEventListener("click",xe,!0),o.document.addEventListener("keydown",_e,!0),o.window.addEventListener("scroll",W,!0),o.window.addEventListener("resize",W),n.triggerButton.addEventListener("click",$e),n.addTargetButton.addEventListener("click",Oe),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",He),n.targetList.addEventListener("input",Ne),n.targetList.addEventListener("keydown",Ve),n.openEditorButton.addEventListener("click",Ee),n.previewButton.addEventListener("click",J),n.copyButton.addEventListener("click",ze),n.backButton.addEventListener("click",je),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),ae=n.subscribeLocale(ue),o.resizeObserver!==void 0&&($=new o.resizeObserver(W)),o.mutationObserver!==void 0&&(re=new o.mutationObserver(W),re.observe(o.document.documentElement,{childList:!0,subtree:!0})),Y&&b.length>0&&(k({type:"RESTORE"}),_.beginSelection(),h=!0,N(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function m(){if(!L){ae?.(),ae=void 0,n.dispose(),s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose();return}L=!1,ae?.(),ae=void 0,o.document.removeEventListener("pointermove",Ie,!0),o.document.removeEventListener("click",xe,!0),o.document.removeEventListener("keydown",_e,!0),o.window.removeEventListener("scroll",W,!0),o.window.removeEventListener("resize",W),n.triggerButton.removeEventListener("click",$e),n.addTargetButton.removeEventListener("click",Oe),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",He),n.targetList.removeEventListener("input",Ne),n.targetList.removeEventListener("keydown",Ve),n.openEditorButton.removeEventListener("click",Ee),n.previewButton.removeEventListener("click",J),n.copyButton.removeEventListener("click",ze),n.backButton.removeEventListener("click",je),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),V!==void 0&&(o.window.cancelAnimationFrame(V),V=void 0),le(),X(),$?.disconnect(),re?.disconnect(),$=void 0,re=void 0,b=[],x=void 0,D="",P=void 0,F=void 0,s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose(),n.dispose(),u=Wt}return Object.freeze({mount:nt,dispose:m,getState:()=>u})}var uo="__spotpatchRuntime__";function Yt(e){let t=globalThis;t[uo]?.dispose();let o=po(e);t[uo]=o,o.mount()}Yt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spotpatch/vite",
3
- "version": "1.4.3",
3
+ "version": "1.4.4",
4
4
  "description": "Vite development plugin for SpotPatch.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -44,9 +44,9 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@spotpatch/compiler": "^0.1.1",
47
- "@spotpatch/dev-server": "^0.1.1",
47
+ "@spotpatch/dev-server": "^0.1.2",
48
48
  "@spotpatch/react-adapter": "^1.0.1",
49
- "@spotpatch/runtime": "^1.5.1",
49
+ "@spotpatch/runtime": "^1.5.2",
50
50
  "@spotpatch/shared": "^1.6.0"
51
51
  },
52
52
  "peerDependencies": {