@spotpatch/vite 1.2.0 → 1.2.1

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.
@@ -1,38 +1,38 @@
1
- import{createReact18Adapter as zr}from"@spotpatch/react-adapter";var h={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",TOOL_DENIED:"TOOL_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var Zn=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Qn=/blob:[^\s"'<>]+/giu,eo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,to=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,no=/\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,oo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),ro=500;function io(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function dt(e){let t=io(e);return oo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function H(e){return e.replace(Zn,"[redacted inline data]").replace(Qn,"[redacted blob URL]").replace(eo,"Bearer [redacted]").replace(to,"$1[redacted]@").replace(no,(t,o,n,i)=>{let a=i.at(0),r=a==='"'||a==="'"||a==="`";return`${o}${n}${r?a:""}[redacted]${r?a:""}`})}function so(e){e.username="",e.password="";for(let[t,o]of e.searchParams)dt(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,H(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function qe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=H(o);try{let i=new URL(n,t),a=so(i),r=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===r.origin?`${i.pathname}${i.search}${i.hash}`:a}catch{return ao(n,ro)}}var wt=["auto","vscode","cursor"];var co=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}),Pt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Ot=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Lt=Object.freeze(["added","modified","deleted"]),It=Object.freeze(["passed","failed","cancelled","timed-out"]);var _t="data-spotpatch-source",lo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Nt(e){if(e===null)return;let t=lo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var Ke="/__spotpatch/v1",lt="X-SpotPatch-Token",We=Object.freeze({sourceContext:`${Ke}/source-context`,openEditor:`${Ke}/open-editor`,agentCapability:`${Ke}/agent/capability`,agentJobs:`${Ke}/agent/jobs`});function Ye(e,t){return`${We.agentJobs}/${encodeURIComponent(e)}/${t}`}var kt="https://github.com/huanglvjing/spotpatch";function Kt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function uo(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Kt(e.source)}})}function go(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function fo(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 mo(e){return Object.freeze({instruction:e.instruction.trim(),source:Kt(e.source,e.code),react:uo(e.react),element:go(e.element),styles:fo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function Wt(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(mo)),createdAt:e.createdAt})}var ho=new Set(Object.values(h)),bo=new Set(Ot),yo=new Set(It),xo=new Set(Lt),Xt=new Set(Pt),So=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Eo=/^[A-Za-z0-9_-]+$/,Ao=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ae(e,t){return Object.keys(e).every(o=>t.includes(o))}function ne(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function ot(e){return ne(e,64,1)&&typeof e=="string"&&So.test(e)}function $t(e){return ne(e,128,22)&&typeof e=="string"&&Eo.test(e)}function ut(e){return typeof e=="string"&&Ao.test(e)&&Number.isFinite(Date.parse(e))}function Mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function vo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Yt(e,t){return e===void 0||ne(e,t)}function rt(e){return typeof e=="string"&&ho.has(e)}function Zt(e){return!Ve(e)||!Ae(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:ot(e.providerProfileId)&&ne(e.providerLabel,100)&&ot(e.modelProfileId)&&ne(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&bo.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||ut(e.checkedAt))&&(e.errorCode===void 0||rt(e.errorCode))}function gt(e){return!Ve(e)||!Ae(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:$t(e.jobId)&&typeof e.status=="string"&&Xt.has(e.status)&&ot(e.providerProfileId)&&ne(e.providerLabel,100)&&ot(e.modelProfileId)&&ne(e.modelLabel,100)&&ne(e.phaseMessage,1024)&&ut(e.createdAt)&&ut(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||rt(e.errorCode))}function Co(e){return Ve(e)&&Ae(e,["relativePath","kind","additions","deletions"])&&ne(e.relativePath,1024)&&typeof e.kind=="string"&&xo.has(e.kind)&&Mt(e.additions)&&Mt(e.deletions)}function Qt(e){return Ve(e)&&Ae(e,["checkId","label","status","durationMs","output"])&&ot(e.checkId)&&ne(e.label,100)&&typeof e.status=="string"&&yo.has(e.status)&&Mt(e.durationMs)&&ne(e.output,8e4)}function Ro(e){return Ve(e)&&Ae(e,["jobId","summary","diff","files","checks"])&&$t(e.jobId)&&ne(e.summary,8e4)&&ne(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Co)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(Qt)}function en(e){return Ve(e)&&Ae(e,["snapshot","result"])&&gt(e.snapshot)&&(e.result===void 0||Ro(e.result)&&e.result.jobId===e.snapshot.jobId)}function To(e){return Ve(e)&&Ae(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===1&&vo(e.sequence)&&$t(e.jobId)&&typeof e.status=="string"&&Xt.has(e.status)&&ut(e.timestamp)&&typeof e.type=="string"&&Ve(e.data)}function tn(e){if(!To(e))return!1;let t=e.data;switch(e.type){case"snapshot":return Ae(t,["snapshot"])&&gt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Ae(t,["message"])&&ne(t.message,1024);case"tool":return Ae(t,["toolCallId","toolName","state","relativePath","checkLabel"])&&ne(t.toolCallId,256)&&ne(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&Yt(t.relativePath,1024)&&Yt(t.checkLabel,100);case"check":return Ae(t,["result"])&&Qt(t.result);case"result-ready":return Ae(t,["hasResult"])&&t.hasResult===!0;case"error":return Ae(t,["code","message"])&&rt(t.code)&&ne(t.message,1024);default:return!1}}var wo=2e6,nn=1e5,Po=4e6,k=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oo(e){if(!(!Qe(e)||e.ok!==!1||!Qe(e.error)))return rt(e.error.code)?e.error.code:void 0}function Lo(e){if(!Qe(e)||e.ok!==!0||!("data"in e))throw new k;return e.data}function Io(e){return Qe(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 _o(e){return Qe(e)&&typeof e.editor=="string"&&wt.includes(e.editor)}function rn(e){if(!(!Qe(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))rn(t);Object.freeze(e)}}function mt(e){return rn(e),e}async function No(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new k;if(e.body===null)throw new k;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),a=0,r="";try{for(;;){let c=await n.read();if(c.done)return r+=i.decode(),r;if(a+=c.value.byteLength,a>t)throw await n.cancel(),new k;r+=i.decode(c.value,{stream:!0})}}catch(c){throw c instanceof k?c:new k}finally{n.releaseLock()}}function an(e){try{return JSON.parse(e)}catch{throw new k}}async function on(e){let t=an(await No(e,wo));if(!e.ok)throw new k(Oo(t));return Lo(t)}function ko(e,t){if(!Zt(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new k;return mt(e)}function ft(e,t){if(!gt(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 k;return mt(e)}function Mo(e,t){if(!en(e)||e.snapshot.jobId!==t)throw new k;return mt(e)}function $o(e){if(!tn(e))throw new k;return mt(e)}function Do(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 sn(e){return e instanceof k?e.code:void 0}function cn(e){let t=new Set;function o(){for(let r of t)r.abort();t.clear()}async function n(r,c,C){let x=new AbortController;t.add(x);try{let p=await e.fetch(r,{method:c,headers:{...C===void 0?{}:{"Content-Type":"application/json"},[lt]:e.sessionToken},...C===void 0?{}:{body:JSON.stringify(C)},signal:x.signal});return await on(p)}finally{t.delete(x)}}async function i(r,c){let C=new AbortController;t.add(C);try{let x=await e.fetch(Ye(r,"events"),{method:"POST",headers:{"Content-Type":"application/json",[lt]:e.sessionToken},body:JSON.stringify({}),signal:C.signal});if(!x.ok){await on(x);return}if(x.body===null)throw new k;let p=x.body.getReader(),I=new TextDecoder("utf-8",{fatal:!0}),E="",R=0,S=0,A=M=>{if(M.trim().length===0)return;if(new TextEncoder().encode(M).byteLength>nn)throw new k;let w=$o(an(M));if(w.jobId!==r||w.sequence<=S)throw new k;S=w.sequence,c(w)};try{for(;;){let M=await p.read();if(M.done){E+=I.decode(),A(E);return}if(R+=M.value.byteLength,R>Po)throw await p.cancel(),new k;E+=I.decode(M.value,{stream:!0});let w=E.split(`
2
- `);if(E=w.pop()??"",new TextEncoder().encode(E).byteLength>nn)throw await p.cancel(),new k;for(let X of w)A(X)}}catch(M){throw M instanceof k||M instanceof DOMException&&M.name==="AbortError"?M:new k}finally{p.releaseLock()}}finally{t.delete(C)}}let a=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(r){let c=await n(We.sourceContext,"POST",r);if(!Io(c))throw new k;return Object.freeze({...c})},async openEditor(r){let c=await n(We.openEditor,"POST",r);if(!_o(c))throw new k;return Object.freeze({editor:c.editor})},async agentCapability(r){return ko(await n(We.agentCapability,"POST",r),r)},async createAgentJob(r){let c=Do(r);return ft(await n(We.agentJobs,"POST",c),r)},agentEvents:i,async agentResult(r){return Mo(await n(Ye(r,"result"),"POST",a),r)},async cancelAgentJob(r){return ft(await n(Ye(r,"cancel"),"POST",a),{jobId:r})},async applyAgentJob(r){return ft(await n(Ye(r,"apply"),"POST",a),{jobId:r})},async revertAgentJob(r){return ft(await n(Ye(r,"revert"),"POST",a),{jobId:r})},dispose(){o()}})}var zo=500,dn=256;function jo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Bo(e){return dt(e)}function ln(e,t,o){if(!Bo(e))return e==="href"||e==="src"?qe(t,o):e==="d"&&t.length>dn?`${t.slice(0,dn)}…`:jo(H(t),zo)}function ye(e){return H(e)}var pn=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 it=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 Uo(e){return"selectorText"in e&&"style"in e}function Ho(e){return"cssRules"in e}function Jo(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 Vo(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((a,r)=>a+r.selector.length+r.declarations.length+(r.source?.length??0)+(r.media?.length??0),0)+Object.entries(n).reduce((a,[r,c])=>a+r.length+c.length,0)+i.join(`
3
- `).length}function Go(e,t){return e.href===null?void 0:qe(e.href,t)}function un(e,t,o,n,i,a){for(let r of t){if(Uo(r)){let c=!1;try{c=e.matches(r.selectorText)}catch{a.add(it.selector);continue}c&&i.push(Object.freeze({selector:ye(r.selectorText),declarations:ye(r.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Ho(r)){let c=Jo(r);un(e,r.cssRules,o,c===void 0?n:[...n,c],i,a)}}}function Fo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of pn){let a=ye(o.getPropertyValue(i).trim());a.length>0&&(n[i]=a)}return n}function gn(e){let t=new Set([it.state,it.cssInJs,it.cascade]),o=[],n=e.readCssRules??(p=>p.cssRules);for(let p of e.document.styleSheets){let I;try{I=n(p)}catch{t.add(it.inaccessibleStylesheet);continue}un(e.element,I,Go(p,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),a=e.element.getAttribute("style"),r=a===null?void 0:ye(a),c=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),C=Object.entries(Fo(e.element,c)),x=Array.from(t);for(;Vo(i,r,o,Object.fromEntries(C),x)>e.maxCharacters;){if(C.length>0){C.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...r===void 0?{}:{inlineStyle:r},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(C)),warnings:Object.freeze(x)})}var Ge=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),qo=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"]),Ko=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function mn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Wo(e){return qo.has(e)||e.startsWith("aria-")||e==="data-testid"}function hn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let a=i.name.toLowerCase();if(!Wo(a))continue;let r=ln(a,i.value,n);r!==void 0&&o.push(`${a}="${mn(r)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function bn(e){return H(e).replaceAll(/\s+/gu," ").trim()}function yn(e,t,o,n){if(o.nodeCount>=Ge.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),a=e.tagName.toLowerCase();if(n.push(`${i}${hn(e)}`),!Ko.has(a)){for(let r of e.childNodes){if(o.nodeCount>=Ge.maxNodes){o.truncated=!0;break}if(r.nodeType===3){let c=bn(r.textContent??"");if(c.length>0){o.nodeCount+=1;let C=c.length<=Ge.maxTextCharacters?c:`${c.slice(0,Ge.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${mn(C)}`)}continue}if(r.nodeType===1){if(t>=Ge.maxDepth){o.truncated=!0;continue}yn(r,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${a}>`)}}function Yo(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Ge.maxParentDepth;)t.push(hn(o)),o=o.parentElement;return t}function Xo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function fn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Zo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Qo(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${fn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Zo(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(c=>`.${fn(c)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(c=>c.tagName===e.tagName),a=i.indexOf(e),r=i.length>1&&a>=0?`:nth-of-type(${String(a+1)})`:"";return`${t}${n}${r}`}function er(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Qo(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function xn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};yn(e.element,0,o,t);let n=Yo(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=bn(e.element.textContent),a=e.element.getBoundingClientRect(),r=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:er(e.element),sanitizedHtml:Xo(t.join(`
4
- `),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=Ge.maxTextCharacters?i:`${i.slice(0,Ge.maxTextCharacters)}…`},...r===null?{}:{role:r},rect:Object.freeze({x:a.x,y:a.y,width:a.width,height:a.height})})}function Sn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function tr(e){return e.toLowerCase()}function En(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function An(e,t,o){let n=t.split("+").map(p=>p.trim().toLowerCase()).filter(p=>p.length>0),i=n.find(p=>p!=="mod"&&p!=="meta"&&p!=="ctrl"&&p!=="control"&&p!=="alt"&&p!=="option"&&p!=="shift");if(i===void 0||tr(e.key)!==i)return!1;let a=n.includes("mod"),r=n.includes("meta")||a&&Sn(o),c=n.includes("ctrl")||n.includes("control")||a&&!Sn(o),C=n.includes("alt")||n.includes("option"),x=n.includes("shift");return e.metaKey===r&&e.ctrlKey===c&&e.altKey===C&&e.shiftKey===x}function nr(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function or(e){let t=e.filter(c=>c.width>0&&c.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,a=o.right,r=o.bottom;for(let c of t.slice(1))n=Math.min(n,c.left),i=Math.min(i,c.top),a=Math.max(a,c.right),r=Math.max(r,c.bottom);return Object.freeze({x:n,y:i,width:a-n,height:r-i})}function Dt(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=or(Array.from(e.getClientRects()));if(n!==void 0)return n}return nr(e.getBoundingClientRect())}var Xe="data-spotpatch-ui",at=Object.freeze({highlight:2147483646,controls:2147483647});function vn(e){if(e.closest(`[${Xe}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(Xe)}function rr(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}function ir(e){return e.tagName==="HTML"||e.tagName==="BODY"}function zt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(a=>!vn(a)&&rr(a,t));return i.find(a=>!ir(a))??i[0]}function Cn(e){return e instanceof Element&&vn(e)}var jt=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 ar(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function ht(e,t){let o="`".repeat(Math.max(3,ar(t)+1));return`${o}${e}
1
+ import{createReact18Adapter as Nr}from"@spotpatch/react-adapter";var b={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",TOOL_DENIED:"TOOL_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var Kn=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Wn=/blob:[^\s"'<>]+/giu,Yn=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Xn=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Zn=/\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,Qn=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),eo=500;function to(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function no(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function at(e){let t=to(e);return Qn.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function J(e){return e.replace(Kn,"[redacted inline data]").replace(Wn,"[redacted blob URL]").replace(Yn,"Bearer [redacted]").replace(Xn,"$1[redacted]@").replace(Zn,(t,o,n,a)=>{let r=a.at(0),i=r==='"'||r==="'"||r==="`";return`${o}${n}${i?r:""}[redacted]${i?r:""}`})}function oo(e){e.username="",e.password="";for(let[t,o]of e.searchParams)at(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,J(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Ge(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=J(o);try{let a=new URL(n,t),r=oo(a),i=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&a.origin===i.origin?`${a.pathname}${a.search}${a.hash}`:r}catch{return no(n,eo)}}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}),Ct=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Rt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Tt=Object.freeze(["added","modified","deleted"]),wt=Object.freeze(["passed","failed","cancelled","timed-out"]);var Ot="data-spotpatch-source",io=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Pt(e){if(e===null)return;let t=io.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),a=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(a)))return Object.freeze({fileId:o,line:n,column:a})}var Fe="/__spotpatch/v1",st="X-SpotPatch-Token",qe=Object.freeze({sourceContext:`${Fe}/source-context`,openEditor:`${Fe}/open-editor`,agentCapability:`${Fe}/agent/capability`,agentJobs:`${Fe}/agent/jobs`});function Ke(e,t){return`${qe.agentJobs}/${encodeURIComponent(e)}/${t}`}var Lt="https://github.com/huanglvjing/spotpatch";function Vt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function so(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Vt(e.source)}})}function co(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 po(e){return Object.freeze({instruction:e.instruction.trim(),source:Vt(e.source,e.code),react:so(e.react),element:co(e.element),styles:lo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function Gt(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(po)),createdAt:e.createdAt})}var uo=new Set(Object.values(b)),go=new Set(Rt),fo=new Set(wt),mo=new Set(Tt),qt=new Set(Ct),ho=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,bo=/^[A-Za-z0-9_-]+$/,yo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function He(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){return Object.keys(e).every(o=>t.includes(o))}function te(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function et(e){return te(e,64,1)&&typeof e=="string"&&ho.test(e)}function _t(e){return te(e,128,22)&&typeof e=="string"&&bo.test(e)}function lt(e){return typeof e=="string"&&yo.test(e)&&Number.isFinite(Date.parse(e))}function It(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function xo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Ft(e,t){return e===void 0||te(e,t)}function tt(e){return typeof e=="string"&&uo.has(e)}function Kt(e){return!He(e)||!ve(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:et(e.providerProfileId)&&te(e.providerLabel,100)&&et(e.modelProfileId)&&te(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&go.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||lt(e.checkedAt))&&(e.errorCode===void 0||tt(e.errorCode))}function dt(e){return!He(e)||!ve(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:_t(e.jobId)&&typeof e.status=="string"&&qt.has(e.status)&&et(e.providerProfileId)&&te(e.providerLabel,100)&&et(e.modelProfileId)&&te(e.modelLabel,100)&&te(e.phaseMessage,1024)&&lt(e.createdAt)&&lt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||tt(e.errorCode))}function So(e){return He(e)&&ve(e,["relativePath","kind","additions","deletions"])&&te(e.relativePath,1024)&&typeof e.kind=="string"&&mo.has(e.kind)&&It(e.additions)&&It(e.deletions)}function Wt(e){return He(e)&&ve(e,["checkId","label","status","durationMs","output"])&&et(e.checkId)&&te(e.label,100)&&typeof e.status=="string"&&fo.has(e.status)&&It(e.durationMs)&&te(e.output,8e4)}function Ao(e){return He(e)&&ve(e,["jobId","summary","diff","files","checks"])&&_t(e.jobId)&&te(e.summary,8e4)&&te(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(So)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(Wt)}function Yt(e){return He(e)&&ve(e,["snapshot","result"])&&dt(e.snapshot)&&(e.result===void 0||Ao(e.result)&&e.result.jobId===e.snapshot.jobId)}function Eo(e){return He(e)&&ve(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===1&&xo(e.sequence)&&_t(e.jobId)&&typeof e.status=="string"&&qt.has(e.status)&&lt(e.timestamp)&&typeof e.type=="string"&&He(e.data)}function Xt(e){if(!Eo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return ve(t,["snapshot"])&&dt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return ve(t,["message"])&&te(t.message,1024);case"tool":return ve(t,["toolCallId","toolName","state","relativePath","checkLabel"])&&te(t.toolCallId,256)&&te(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&Ft(t.relativePath,1024)&&Ft(t.checkLabel,100);case"check":return ve(t,["result"])&&Wt(t.result);case"result-ready":return ve(t,["hasResult"])&&t.hasResult===!0;case"error":return ve(t,["code","message"])&&tt(t.code)&&te(t.message,1024);default:return!1}}var vo=2e6,Zt=1e5,Co=4e6,N=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ro(e){if(!(!Ye(e)||e.ok!==!1||!Ye(e.error)))return tt(e.error.code)?e.error.code:void 0}function To(e){if(!Ye(e)||e.ok!==!0||!("data"in e))throw new N;return e.data}function wo(e){return Ye(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 en(e){if(!(!Ye(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))en(t);Object.freeze(e)}}function ut(e){return en(e),e}async function Oo(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new N;if(e.body===null)throw new N;let n=e.body.getReader(),a=new TextDecoder("utf-8",{fatal:!0}),r=0,i="";try{for(;;){let c=await n.read();if(c.done)return i+=a.decode(),i;if(r+=c.value.byteLength,r>t)throw await n.cancel(),new N;i+=a.decode(c.value,{stream:!0})}}catch(c){throw c instanceof N?c:new N}finally{n.releaseLock()}}function tn(e){try{return JSON.parse(e)}catch{throw new N}}async function Qt(e){let t=tn(await Oo(e,vo));if(!e.ok)throw new N(Ro(t));return To(t)}function Po(e,t){if(!Kt(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new N;return ut(e)}function pt(e,t){if(!dt(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 N;return ut(e)}function Lo(e,t){if(!Yt(e)||e.snapshot.jobId!==t)throw new N;return ut(e)}function Io(e){if(!Xt(e))throw new N;return ut(e)}function _o(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 nn(e){return e instanceof N?e.code:void 0}function on(e){let t=new Set;function o(){for(let i of t)i.abort();t.clear()}async function n(i,c,y){let E=new AbortController;t.add(E);try{let u=await e.fetch(i,{method:c,headers:{...y===void 0?{}:{"Content-Type":"application/json"},[st]:e.sessionToken},...y===void 0?{}:{body:JSON.stringify(y)},signal:E.signal});return await Qt(u)}finally{t.delete(E)}}async function a(i,c){let y=new AbortController;t.add(y);try{let E=await e.fetch(Ke(i,"events"),{method:"POST",headers:{"Content-Type":"application/json",[st]:e.sessionToken},body:JSON.stringify({}),signal:y.signal});if(!E.ok){await Qt(E);return}if(E.body===null)throw new N;let u=E.body.getReader(),P=new TextDecoder("utf-8",{fatal:!0}),m="",k=0,A=0,v=M=>{if(M.trim().length===0)return;if(new TextEncoder().encode(M).byteLength>Zt)throw new N;let O=Io(tn(M));if(O.jobId!==i||O.sequence<=A)throw new N;A=O.sequence,c(O)};try{for(;;){let M=await u.read();if(M.done){m+=P.decode(),v(m);return}if(k+=M.value.byteLength,k>Co)throw await u.cancel(),new N;m+=P.decode(M.value,{stream:!0});let O=m.split(`
2
+ `);if(m=O.pop()??"",new TextEncoder().encode(m).byteLength>Zt)throw await u.cancel(),new N;for(let Z of O)v(Z)}}catch(M){throw M instanceof N||M instanceof DOMException&&M.name==="AbortError"?M:new N}finally{u.releaseLock()}}finally{t.delete(y)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(i){let c=await n(qe.sourceContext,"POST",i);if(!wo(c))throw new N;return Object.freeze({...c})},async openEditor(i){let c=await n(qe.openEditor,"POST",i);if(!Ye(c)||c.editor!=="auto"&&c.editor!=="vscode"&&c.editor!=="cursor")throw new N;return Object.freeze({editor:c.editor})},async agentCapability(i){return Po(await n(qe.agentCapability,"POST",i),i)},async createAgentJob(i){let c=_o(i);return pt(await n(qe.agentJobs,"POST",c),i)},agentEvents:a,async agentResult(i){return Lo(await n(Ke(i,"result"),"POST",r),i)},async cancelAgentJob(i){return pt(await n(Ke(i,"cancel"),"POST",r),{jobId:i})},async applyAgentJob(i){return pt(await n(Ke(i,"apply"),"POST",r),{jobId:i})},async revertAgentJob(i){return pt(await n(Ke(i,"revert"),"POST",r),{jobId:i})},dispose(){o()}})}var No=500,rn=256;function ko(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Mo(e){return at(e)}function an(e,t,o){if(!Mo(e))return e==="href"||e==="src"?Ge(t,o):e==="d"&&t.length>rn?`${t.slice(0,rn)}…`:ko(J(t),No)}function Se(e){return J(e)}var sn=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 nt=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 $o(e){return"selectorText"in e&&"style"in e}function Do(e){return"cssRules"in e}function zo(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 jo(e,t,o,n,a){return e.join(" ").length+(t?.length??0)+o.reduce((r,i)=>r+i.selector.length+i.declarations.length+(i.source?.length??0)+(i.media?.length??0),0)+Object.entries(n).reduce((r,[i,c])=>r+i.length+c.length,0)+a.join(`
3
+ `).length}function Bo(e,t){return e.href===null?void 0:Ge(e.href,t)}function cn(e,t,o,n,a,r){for(let i of t){if($o(i)){let c=!1;try{c=e.matches(i.selectorText)}catch{r.add(nt.selector);continue}c&&a.push(Object.freeze({selector:Se(i.selectorText),declarations:Se(i.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Do(i)){let c=zo(i);cn(e,i.cssRules,o,c===void 0?n:[...n,c],a,r)}}}function Uo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let a of sn){let r=Se(o.getPropertyValue(a).trim());r.length>0&&(n[a]=r)}return n}function ln(e){let t=new Set([nt.state,nt.cssInJs,nt.cascade]),o=[],n=e.readCssRules??(u=>u.cssRules);for(let u of e.document.styleSheets){let P;try{P=n(u)}catch{t.add(nt.inaccessibleStylesheet);continue}cn(e.element,P,Bo(u,e.document.baseURI),[],o,t)}let a=Array.from(e.element.classList),r=e.element.getAttribute("style"),i=r===null?void 0:Se(r),c=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),y=Object.entries(Uo(e.element,c)),E=Array.from(t);for(;jo(a,i,o,Object.fromEntries(y),E)>e.maxCharacters;){if(y.length>0){y.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(a),...i===void 0?{}:{inlineStyle:i},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(y)),warnings:Object.freeze(E)})}var Je=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Ho=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"]),Jo=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function pn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Vo(e){return Ho.has(e)||e.startsWith("aria-")||e==="data-testid"}function un(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let a of e.attributes){let r=a.name.toLowerCase();if(!Vo(r))continue;let i=an(r,a.value,n);i!==void 0&&o.push(`${r}="${pn(i)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function gn(e){return J(e).replaceAll(/\s+/gu," ").trim()}function fn(e,t,o,n){if(o.nodeCount>=Je.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let a=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${a}${un(e)}`),!Jo.has(r)){for(let i of e.childNodes){if(o.nodeCount>=Je.maxNodes){o.truncated=!0;break}if(i.nodeType===3){let c=gn(i.textContent??"");if(c.length>0){o.nodeCount+=1;let y=c.length<=Je.maxTextCharacters?c:`${c.slice(0,Je.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${pn(y)}`)}continue}if(i.nodeType===1){if(t>=Je.maxDepth){o.truncated=!0;continue}fn(i,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${a}</${r}>`)}}function Go(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Je.maxParentDepth;)t.push(un(o)),o=o.parentElement;return t}function Fo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function dn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function qo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ko(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${dn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${qo(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(c=>`.${dn(c)}`).join(""),a=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(c=>c.tagName===e.tagName),r=a.indexOf(e),i=a.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${i}`}function Wo(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Ko(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function mn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};fn(e.element,0,o,t);let n=Go(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let a=gn(e.element.textContent),r=e.element.getBoundingClientRect(),i=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:Wo(e.element),sanitizedHtml:Fo(t.join(`
4
+ `),e.maxCharacters),...a.length===0?{}:{textPreview:a.length<=Je.maxTextCharacters?a:`${a.slice(0,Je.maxTextCharacters)}…`},...i===null?{}:{role:i},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function hn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Yo(e){return e.toLowerCase()}function bn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function yn(e,t,o){let n=t.split("+").map(u=>u.trim().toLowerCase()).filter(u=>u.length>0),a=n.find(u=>u!=="mod"&&u!=="meta"&&u!=="ctrl"&&u!=="control"&&u!=="alt"&&u!=="option"&&u!=="shift");if(a===void 0||Yo(e.key)!==a)return!1;let r=n.includes("mod"),i=n.includes("meta")||r&&hn(o),c=n.includes("ctrl")||n.includes("control")||r&&!hn(o),y=n.includes("alt")||n.includes("option"),E=n.includes("shift");return e.metaKey===i&&e.ctrlKey===c&&e.altKey===y&&e.shiftKey===E}function Xo(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function Zo(e){let t=e.filter(c=>c.width>0&&c.height>0),o=t[0];if(o===void 0)return;let n=o.left,a=o.top,r=o.right,i=o.bottom;for(let c of t.slice(1))n=Math.min(n,c.left),a=Math.min(a,c.top),r=Math.max(r,c.right),i=Math.max(i,c.bottom);return Object.freeze({x:n,y:a,width:r-n,height:i-a})}function Nt(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=Zo(Array.from(e.getClientRects()));if(n!==void 0)return n}return Xo(e.getBoundingClientRect())}var We="data-spotpatch-ui",ot=Object.freeze({highlight:2147483646,controls:2147483647});function xn(e){if(e.closest(`[${We}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(We)}function Qo(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}function er(e){return e.tagName==="HTML"||e.tagName==="BODY"}function kt(e,t,o,n){let a=e.elementsFromPoint(o,n).filter(r=>!xn(r)&&Qo(r,t));return a.find(r=>!er(r))??a[0]}function Sn(e){return e instanceof Element&&xn(e)}var Mt=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 tr(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function gt(e,t){let o="`".repeat(Math.max(3,tr(t)+1));return`${o}${e}
5
5
  ${t}
6
- ${o}`}function Tn(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${H(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function wn(e,t){return e.split(`
7
- `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function sr(e){let t=[e.source===void 0?void 0:`/* source: ${ye(e.source)} */`,e.media===void 0?void 0:`/* condition: ${ye(e.media)} */`].filter(n=>n!==void 0),o=`${ye(e.selector)} {
8
- ${ye(e.declarations)}
6
+ ${o}`}function En(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,a=e.source.column;return o===void 0?t.unavailable:`${J(o)}${n===void 0?"":`:${String(n)}`}${a===void 0?"":`:${String(a)}`}`}function vn(e,t){return e.split(`
7
+ `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function nr(e){let t=[e.source===void 0?void 0:`/* source: ${Se(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Se(e.media)} */`].filter(n=>n!==void 0),o=`${Se(e.selector)} {
8
+ ${Se(e.declarations)}
9
9
  }`;return[...t,o].join(`
10
- `)}function cr(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(ye).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${ye(e.styles.inlineStyle)} */`].filter(a=>a!==void 0),...t.map(sr)];return i.length===0?o.unavailable:ht("css",i.join(`
10
+ `)}function or(e,t,o){let a=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Se).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Se(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(nr)];return a.length===0?o.unavailable:gt("css",a.join(`
11
11
 
12
- `))}function dr(e,t){return e.length===0?t.unavailable:ht("css",e.map(([o,n])=>`${ye(o)}: ${ye(n)};`).join(`
13
- `))}function lr(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${H(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${H(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(H).join(" > ")}`]],a=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
12
+ `))}function rr(e,t){return e.length===0?t.unavailable:gt("css",e.map(([o,n])=>`${Se(o)}: ${Se(n)};`).join(`
13
+ `))}function ir(e,t,o,n){let a=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${J(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${J(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(J).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
14
14
 
15
- ${ht(e.code.language,H(t.codeLines.join(`
16
- `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,i.join(`
17
- `),`#### ${n.source}`,`- ${n.file}: ${Tn(e,n)}
15
+ ${gt(e.code.language,J(t.codeLines.join(`
16
+ `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,a.join(`
17
+ `),`#### ${n.source}`,`- ${n.file}: ${En(e,n)}
18
18
  - ${n.origin}: ${e.source.origin}
19
- - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,ht("html",H(t.dom)),`#### ${n.styles}`,cr(e,t.matchedRules,n),`#### ${n.computedStyles}`,dr(t.computedEntries,n),`#### ${n.code}`,a,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(r=>`- ${H(r)}`).join(`
19
+ - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,gt("html",J(t.dom)),`#### ${n.styles}`,or(e,t.matchedRules,n),`#### ${n.computedStyles}`,rr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(i=>`- ${J(i)}`).join(`
20
20
  `)].join(`
21
21
 
22
- `)}function Rn(e,t){let o=qe(e.page.url,e.page.url),n=jt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
23
- - ${n.pathname}: ${H(e.page.pathname)}
22
+ `)}function An(e,t){let o=Ge(e.page.url,e.page.url),n=Mt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
23
+ - ${n.pathname}: ${J(e.page.pathname)}
24
24
  - ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
25
25
  - ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
26
- - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((i,a)=>{let r=t.targets[a];if(r===void 0)throw new RangeError("Prompt target draft is missing.");return lr(i,r,a,n)}).join(`
26
+ - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((a,r)=>{let i=t.targets[r];if(i===void 0)throw new RangeError("Prompt target draft is missing.");return ir(a,i,r,n)}).join(`
27
27
 
28
28
  `),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
29
29
 
30
- `)}function pr(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let r=t.codeLines[0]??"";return r.length<=120?t.codeLines=[]:t.codeLines=[`${r.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function ur(e){return{instruction:H(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function gr(e){return{pageTitle:H(e.page.title),targets:e.targets.map(ur)}}function fr(e,t,o){let n=jt[e.locale],i=[(a,r)=>r.computedEntries.pop()!==void 0,(a,r)=>r.reactStack.pop()!==void 0,(a,r)=>{let c=wn(r.dom,n.unavailable);return r.dom===c?!1:(r.dom=c,!0)},(a,r)=>r.matchedRules.shift()!==void 0,pr,(a,r)=>r.warnings.pop()!==void 0];for(let a of i)for(let r=0;r<e.targets.length;r+=1){let c=(o+r)%e.targets.length,C=e.targets[c],x=t.targets[c];if(C!==void 0&&x!==void 0&&a(C,x))return(c+1)%e.targets.length}}function mr(e,t){let o=jt[e.locale],n=e.targets.map((i,a)=>{let r=t.targets[a],c=i.react.componentName;return[`### ${o.target(a+1)}`,`- ${o.requestedChange}: ${r?.instruction??H(i.instruction)}`,`- ${o.file}: ${Tn(i,o)}`,...c===void 0?[]:[`- ${o.component}: ${H(c)}`],`- ${o.element}: ${H(wn(r?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
30
+ `)}function ar(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let i=t.codeLines[0]??"";return i.length<=120?t.codeLines=[]:t.codeLines=[`${i.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),a=e.code.startLine+t.codeLines.length-1;return Math.abs(a-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function sr(e){return{instruction:J(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function cr(e){return{pageTitle:J(e.page.title),targets:e.targets.map(sr)}}function lr(e,t,o){let n=Mt[e.locale],a=[(r,i)=>i.computedEntries.pop()!==void 0,(r,i)=>i.reactStack.pop()!==void 0,(r,i)=>{let c=vn(i.dom,n.unavailable);return i.dom===c?!1:(i.dom=c,!0)},(r,i)=>i.matchedRules.shift()!==void 0,ar,(r,i)=>i.warnings.pop()!==void 0];for(let r of a)for(let i=0;i<e.targets.length;i+=1){let c=(o+i)%e.targets.length,y=e.targets[c],E=t.targets[c];if(y!==void 0&&E!==void 0&&r(y,E))return(c+1)%e.targets.length}}function dr(e,t){let o=Mt[e.locale],n=e.targets.map((a,r)=>{let i=t.targets[r],c=a.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${i?.instruction??J(a.instruction)}`,`- ${o.file}: ${En(a,o)}`,...c===void 0?[]:[`- ${o.component}: ${J(c)}`],`- ${o.element}: ${J(vn(i?.dom??a.element.sanitizedHtml,o.unavailable))}`].join(`
31
31
  `)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
32
32
 
33
33
  `),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
34
34
 
35
- `)}function hr(e,t){let o=gr(e),n=Rn(e,o),i=0;for(;n.length>t;){let r=fr(e,o,i);if(r===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=r;n=Rn(e,o)}if(n.length<=t)return n;let a=mr(e,o);if(a.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return a}function Pn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return hr(t,e.maxCharacters)}})}var ue=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Bt=ue.idle;function br(e){return e.type==="ACTIVATE"?ue.inspecting:ue.idle}function yr(e){switch(e.type){case"HOVER":return ue.inspecting;case"SELECT":return ue.selected;case"CANCEL":return ue.idle;default:return ue.inspecting}}function xr(e){switch(e.type){case"RESELECT":return ue.inspecting;case"CLOSE":return ue.idle;case"PREVIEW":return ue.previewing;case"OPEN_EDITOR":return ue.selected;default:return ue.selected}}function Sr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return ue.selected;case"COPY_FAILURE":return ue.previewing;default:return ue.previewing}}function On(e,t){switch(e.status){case"idle":return br(t);case"inspecting":return yr(t);case"selected":return xr(t);case"previewing":return Sr(t)}}var Ln=Object.freeze({supported:!1,componentStack:Object.freeze([])});function _n(e){return Nt(e.getAttribute(_t))}function Er(e){let t=e.parentElement;for(;t!==null;){let o=_n(t);if(o!==void 0)return o;t=t.parentElement}}function In(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Ar(){return Object.freeze({origin:"none",confidence:"unknown"})}function Nn(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function kn(e){let t=!0;function o(n){if(!t)return Ln;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Ln}}return Object.freeze({resolve(n){let i=_n(n),a=o(n);if(i!==void 0)return Object.freeze({react:a,source:In(i,"jsx-host","exact")});if(a.source!==void 0)return Object.freeze({react:a,source:a.source});let r=Er(n);return Object.freeze(r!==void 0?{react:a,source:In(r,"dom-ancestor","approximate")}:{react:a,source:Ar()})},dispose(){t=!1,e.adapter.dispose()}})}function d(e,t){let o=e.createElement(t);return o.setAttribute(Xe,""),o}function G(e,t,o=""){let n=d(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var $n=`
35
+ `)}function pr(e,t){let o=cr(e),n=An(e,o),a=0;for(;n.length>t;){let i=lr(e,o,a);if(i===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else a=i;n=An(e,o)}if(n.length<=t)return n;let r=dr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function Cn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return pr(t,e.maxCharacters)}})}var pe=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),$t=pe.idle;function ur(e){return e.type==="ACTIVATE"?pe.inspecting:pe.idle}function gr(e){switch(e.type){case"HOVER":return pe.inspecting;case"SELECT":return pe.selected;case"CANCEL":return pe.idle;default:return pe.inspecting}}function fr(e){switch(e.type){case"RESELECT":return pe.inspecting;case"CLOSE":return pe.idle;case"PREVIEW":return pe.previewing;case"OPEN_EDITOR":return pe.selected;default:return pe.selected}}function mr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return pe.selected;case"COPY_FAILURE":return pe.previewing;default:return pe.previewing}}function Rn(e,t){switch(e.status){case"idle":return ur(t);case"inspecting":return gr(t);case"selected":return fr(t);case"previewing":return mr(t)}}var Tn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function On(e){return Pt(e.getAttribute(Ot))}function hr(e){let t=e.parentElement;for(;t!==null;){let o=On(t);if(o!==void 0)return o;t=t.parentElement}}function wn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function br(){return Object.freeze({origin:"none",confidence:"unknown"})}function Pn(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function Ln(e){let t=!0;function o(n){if(!t)return Tn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Tn}}return Object.freeze({resolve(n){let a=On(n),r=o(n);if(a!==void 0)return Object.freeze({react:r,source:wn(a,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let i=hr(n);return Object.freeze(i!==void 0?{react:r,source:wn(i,"dom-ancestor","approximate")}:{react:r,source:br()})},dispose(){t=!1,e.adapter.dispose()}})}function l(e,t){let o=e.createElement(t);return o.setAttribute(We,""),o}function G(e,t,o=""){let n=l(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var _n=`
36
36
  .spotpatch-agent {
37
37
  margin-top: 14px;
38
38
  overflow: hidden;
@@ -162,7 +162,7 @@ ${ht(e.code.language,H(t.codeLines.join(`
162
162
  white-space: pre;
163
163
  user-select: text;
164
164
  }
165
- `;function Mn(e,t,o,n){let i=e.createElement("option");i.value=o,i.textContent=n,t.append(i)}function Dn(e,t,o){let n=o.messages(),i=d(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let a=d(e,"div");a.className="spotpatch-agent-head";let r=d(e,"span");r.className="spotpatch-agent-title";let c=d(e,"span");c.className="spotpatch-agent-badge",a.append(r,c);let C=d(e,"div");C.className="spotpatch-agent-setup";let x=d(e,"div");x.className="spotpatch-agent-selectors";let p=d(e,"label"),I=d(e,"span"),E=d(e,"select");p.append(I,E);let R=d(e,"label"),S=d(e,"span"),A=d(e,"select");R.append(S,A),x.append(p,R);let M=d(e,"label");M.className="spotpatch-consent";let w=d(e,"input");w.type="checkbox";let X=d(e,"span");M.append(w,X);let g=d(e,"p");g.className="spotpatch-agent-capability",g.dataset.state="idle",C.append(x,M,g);let b=d(e,"div");b.className="spotpatch-agent-job",b.hidden=!0;let v=d(e,"div");v.className="spotpatch-agent-job-meta";let O=d(e,"span");O.className="spotpatch-agent-model";let $=d(e,"span");$.className="spotpatch-agent-status",v.append(O,$);let oe=d(e,"p");oe.className="spotpatch-agent-phase";let F=d(e,"p");F.className="spotpatch-agent-error",F.hidden=!0;let _=d(e,"ul");_.className="spotpatch-agent-activity";let ve=d(e,"div");ve.className="spotpatch-agent-result",ve.hidden=!0;let Oe=d(e,"p");Oe.className="spotpatch-agent-summary";let Z=d(e,"ul");Z.className="spotpatch-agent-files";let J=d(e,"div");J.className="spotpatch-agent-checks";let ge=d(e,"pre");ge.className="spotpatch-agent-diff",ge.tabIndex=0,ge.setAttribute("aria-label",n.agent.diffAriaLabel),ve.append(Oe,Z,J,ge),b.append(v,oe,F,_,ve),i.append(a,C,b);let U=G(e,n.agent.testConnection),se=G(e,n.agent.verifyAndRun,"spotpatch-run"),Le=G(e,n.agent.cancel),ke=G(e,n.agent.apply,"spotpatch-primary"),xe=G(e,n.agent.revert),ce=G(e,n.agent.revise),W=t.enabled?t.providers:[],Me=new Map(W.map(f=>[f.id,f])),re=!1,Ce=!0,Se=!1,Re=!1,L=!1,Te=!1,P,Ie,fe=[],Be,q="idle",de=n.agent.connectionNotTested,me;for(let f of W)Mn(e,E,f.id,f.label);t.enabled&&(E.value=t.defaultProvider);let Q=()=>Me.get(E.value),K=()=>{let f=Q();if(A.replaceChildren(),f===void 0){X.textContent=n.agent.providerUnavailable;return}for(let D of f.models)Mn(e,A,D.id,D.label);A.value=f.defaultModel,X.textContent=n.agent.consent(f.label)},Y=()=>{let f=t.enabled&&Se&&!Re;se.textContent=L?n.agent.verifying:Te?n.agent.run:n.agent.verifyAndRun,se.classList.toggle("spotpatch-primary",Te),U.hidden=!f,se.hidden=!f,U.disabled=!Ce||L||Q()===void 0,se.disabled=!Ce||L||!re||!w.checked||Q()===void 0||A.value.length===0,(!Re||!Se)&&(Le.hidden=!0,ke.hidden=!0,xe.hidden=!0,ce.hidden=!0)};K(),E.addEventListener("change",()=>{K(),w.checked=!1,g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,q="idle",de=n.agent.connectionNotTested,me=void 0,Te=!1,Y()}),A.addEventListener("change",()=>{g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,q="idle",de=n.agent.connectionNotTested,me=void 0,Te=!1,Y()}),w.addEventListener("change",Y);function $e(){if(P===void 0)return;let f=P,D=Ie;O.textContent=`${f.providerLabel} · ${f.modelLabel}`,$.textContent=n.agent.status(f.status),oe.textContent=f.phaseMessage;let ee=Be??f.errorCode;F.hidden=ee===void 0,F.textContent=ee===void 0?"":n.errors[ee],_.replaceChildren();for(let B of fe.slice(-8)){let te=d(e,"li");te.dataset.state=B.state,te.textContent=B.label,_.append(te)}ve.hidden=D===void 0,Oe.textContent=D?.summary??"",Z.replaceChildren(),J.replaceChildren(),ge.textContent=D?.diff??"";for(let B of D?.files??[]){let te=d(e,"li");te.textContent=`${B.kind} ${B.relativePath} (+${String(B.additions)} / -${String(B.deletions)})`,Z.append(te)}for(let B of D?.checks??[]){let te=d(e,"details"),De=d(e,"summary");De.textContent=`${B.label}: ${B.status} · ${String(B.durationMs)} ms`;let he=d(e,"pre");he.textContent=B.output.length===0?n.agent.noOutput:B.output,te.append(De,he),J.append(te)}U.hidden=!0,se.hidden=!0,Le.hidden=!Se||!f.canCancel,Le.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ke.hidden=!Se||!f.canApply,xe.hidden=!Se||!f.canRevert,ce.hidden=!Se||!["completed","cancelled","reverted","failed"].includes(f.status)}function we(){n=o.messages(),r.textContent=n.agent.title,c.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,I.textContent=n.agent.provider,S.textContent=n.agent.model,E.setAttribute("aria-label",n.agent.providerAriaLabel),A.setAttribute("aria-label",n.agent.modelAriaLabel),ge.setAttribute("aria-label",n.agent.diffAriaLabel),U.textContent=n.agent.testConnection,ke.textContent=n.agent.apply,xe.textContent=n.agent.revert,ce.textContent=n.agent.revise;let f=Q();X.textContent=f===void 0?n.agent.providerUnavailable:n.agent.consent(f.label),q==="idle"?g.textContent=n.agent.connectionNotTested:q==="probing"?g.textContent=n.agent.testingCapability:q==="ready"?g.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:me!==void 0?g.textContent=n.errors[me]:Q()===void 0?g.textContent=n.agent.providerUnavailable:g.textContent=de,Y(),$e()}let _e=o.subscribe(we);return we(),Object.freeze({root:i,providerSelect:E,modelSelect:A,consentCheckbox:w,testButton:U,runButton:se,cancelButton:Le,applyButton:ke,revertButton:xe,resetButton:ce,consentGranted(){return w.checked},readSelection(){let f=Q(),D=f?.models.find(ee=>ee.id===A.value);return f===void 0||D===void 0?void 0:Object.freeze({providerProfileId:f.id,modelProfileId:D.id})},renderCapability(f,D,ee,B){q=f,de=D,me=B,L=f==="probing",Te=f==="ready"&&ee?.state==="agent-ready",g.dataset.state=f,g.textContent=ee?.state==="agent-ready"?`${D} · ${n.agent.toolsReady}`:D,Y()},renderJob(f,D,ee,B){Re=!0,C.hidden=!0,b.hidden=!1,E.disabled=!0,A.disabled=!0,w.disabled=!0,P=f,Ie=D,fe=ee,Be=B,$e()},resetJob(){Re=!1,P=void 0,Ie=void 0,fe=[],Be=void 0,C.hidden=!1,b.hidden=!0,E.disabled=!1,A.disabled=!1,w.disabled=!1,_.replaceChildren(),Z.replaceChildren(),J.replaceChildren(),ge.textContent="",F.textContent="",F.hidden=!0,Y()},setContextReady(f){re=f,Y()},setEditingEnabled(f){Ce=f,E.disabled=!f||Re,A.disabled=!f||Re,w.disabled=!f||Re,Y()},setProviderConsent(f){w.checked=f,Y()},setSelectionVisible(f){Se=f,Y(),f||(Le.hidden=!0,ke.hidden=!0,xe.hidden=!0,ce.hidden=!0)},dispose(){_e()}})}var vr="http://www.w3.org/2000/svg";function Ne(e,t,o){let n=e.createElementNS(vr,t);for(let[i,a]of Object.entries(o))n.setAttribute(i,a);return n}function zn(e){let t=Ne(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=Ne(e,"defs",{}),n=Ne(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(Ne(e,"stop",{offset:"0","stop-color":"#7c22ff"}),Ne(e,"stop",{offset:".52","stop-color":"#4a69ff"}),Ne(e,"stop",{offset:"1","stop-color":"#06d9ef"})),o.append(n);let i={fill:"none",stroke:"url(#spotpatch-brand-gradient)","stroke-linecap":"square","stroke-linejoin":"miter"},a=Ne(e,"path",{d:"M106 42C67 42 43 68 43 105c0 36 24 61 63 96 39-35 63-60 63-96 0-37-24-63-63-63Z",...i,"stroke-width":"14"}),r=Ne(e,"path",{d:"M106 25v42",...i,"stroke-width":"14"}),c=Ne(e,"path",{d:"M35 109h20m102 0h38",...i,"stroke-width":"13"}),C=Ne(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...i,"stroke-width":"9"}),x=Ne(e,"path",{d:"m119 61-20 45 15 11-13 47 30-56-16-12 4-35Z",fill:"url(#spotpatch-brand-gradient)"});return t.append(o,a,r,c,C,x),t}function bt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function jn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let a=i-t-16,r=n-e-16,c=o.x+o.width/2,C=o.y+o.height/2,x=bt(c-t/2,16,a),p=bt(C-e/2,16,r),I=x,E=p,R="viewport";return o.width>=t+48&&o.height>=e+48?R="center":o.y-e-14>=16?(E=o.y-e-14,R="above"):o.y+o.height+14+e<=n-16?(E=o.y+o.height+14,R="below"):o.x+o.width+14+t<=i-16?(I=o.x+o.width+14,R="right"):o.x-t-14>=16&&(I=o.x-t-14,R="left"),Object.freeze({anchorX:bt(c-I,22,t-22),anchorY:bt(C-E,22,e-22),left:I,mode:R,top:E})}var Cr=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"}),Rr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"});function je(e,t){return e==="vscode"?"VS Code":e==="cursor"?"Cursor":t}var Tr=Object.freeze({[h.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[h.INVALID_TOKEN]:"The local SpotPatch session expired.",[h.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[h.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[h.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[h.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[h.EDITOR_OPEN_FAILED]:"The editor request failed.",[h.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[h.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[h.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[h.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[h.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[h.AGENT_BUSY]:"Another write Agent job is still active.",[h.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[h.AGENT_CANCELLED]:"The Agent job was cancelled.",[h.WORKTREE_DIRTY]:"Commit or otherwise clean staged, unstaged, and untracked files before running AI.",[h.TOOL_DENIED]:"A model tool request violated the local safety policy.",[h.PATCH_REJECTED]:"The proposed patch did not pass local policy.",[h.VALIDATION_FAILED]:"Required project checks failed. The change cannot be applied.",[h.APPLY_CONFLICT]:"Project files changed after the Agent baseline; no overwrite was performed.",[h.INTERNAL_ERROR]:"The Agent job failed without exposing private details."}),wr=Object.freeze({[h.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[h.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[h.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[h.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[h.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[h.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[h.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[h.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[h.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[h.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[h.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[h.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[h.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[h.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[h.AGENT_CANCELLED]:"Agent 任务已取消。",[h.WORKTREE_DIRTY]:"运行 AI 前,请先提交或清理暂存、未暂存与未跟踪文件。",[h.TOOL_DENIED]:"模型工具请求违反本地安全策略。",[h.PATCH_REJECTED]:"建议补丁未通过本地策略检查。",[h.VALIDATION_FAILED]:"项目必需检查失败,不能应用本次变更。",[h.APPLY_CONFLICT]:"Agent 建立基线后项目文件已变化,未执行覆盖。",[h.INTERNAL_ERROR]:"Agent 任务失败,私有细节未暴露到浏览器。"}),Pr=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"}),Or=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:"警告"}),Lr=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:Pr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:e=>e==="auto"?"Open source":`Open in ${je(e,"editor")}`,openTarget:(e,t)=>`Open target ${String(e)} in ${je(t,"the detected editor")}`,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",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:"Test connection",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=>Cr[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.",detachedTargetRemoved:"A removed page element was dropped from the selection.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:e=>`Opening ${je(e,"the detected editor")}…`,editorOpened:e=>`Opened the source in ${je(e,"the detected editor")}.`,editorFailed:e=>`Could not open ${je(e,"an editor")}. Start the editor or configure editor: "cursor" / "vscode".`,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:Tr}),"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:Or,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:e=>e==="auto"?"打开源码":`在 ${je(e,"编辑器")} 中打开`,openTarget:(e,t)=>`在${je(t,"自动检测的编辑器")}中打开目标 ${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:"尚未测试连接",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=>Rr[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:"已移除选中目标。",detachedTargetRemoved:"页面中的目标已卸载,已从当前选择中移除。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:e=>`正在打开${je(e,"自动检测的编辑器")}……`,editorOpened:e=>`已在${je(e,"自动检测的编辑器")}中打开源码。`,editorFailed:e=>`无法打开${je(e,"编辑器")}。请先启动编辑器,或配置 editor: "cursor" / "vscode"。`,completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:wr})});function Bn(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 Ir(e,t){if(e!=="auto")return e;let o=Bn(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(Bn).find(i=>i!==void 0)??"en-US"}function Un(e,t="auto"){let o=Ir(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Lr[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var _r=560,Nr=Object.freeze({previewing:640,selected:720});function kr(e){let t=e.createElement("style");return t.textContent=`
165
+ `;function In(e,t,o,n){let a=e.createElement("option");a.value=o,a.textContent=n,t.append(a)}function Nn(e,t,o){let n=o.messages(),a=l(e,"section");a.className="spotpatch-agent",a.hidden=!t.enabled;let r=l(e,"div");r.className="spotpatch-agent-head";let i=l(e,"span");i.className="spotpatch-agent-title";let c=l(e,"span");c.className="spotpatch-agent-badge",r.append(i,c);let y=l(e,"div");y.className="spotpatch-agent-setup";let E=l(e,"div");E.className="spotpatch-agent-selectors";let u=l(e,"label"),P=l(e,"span"),m=l(e,"select");u.append(P,m);let k=l(e,"label"),A=l(e,"span"),v=l(e,"select");k.append(A,v),E.append(u,k);let M=l(e,"label");M.className="spotpatch-consent";let O=l(e,"input");O.type="checkbox";let Z=l(e,"span");M.append(O,Z);let g=l(e,"p");g.className="spotpatch-agent-capability",g.dataset.state="idle",y.append(E,M,g);let x=l(e,"div");x.className="spotpatch-agent-job",x.hidden=!0;let C=l(e,"div");C.className="spotpatch-agent-job-meta";let R=l(e,"span");R.className="spotpatch-agent-model";let H=l(e,"span");H.className="spotpatch-agent-status",C.append(R,H);let ue=l(e,"p");ue.className="spotpatch-agent-phase";let F=l(e,"p");F.className="spotpatch-agent-error",F.hidden=!0;let I=l(e,"ul");I.className="spotpatch-agent-activity";let Ce=l(e,"div");Ce.className="spotpatch-agent-result",Ce.hidden=!0;let ge=l(e,"p");ge.className="spotpatch-agent-summary";let D=l(e,"ul");D.className="spotpatch-agent-files";let Le=l(e,"div");Le.className="spotpatch-agent-checks";let ae=l(e,"pre");ae.className="spotpatch-agent-diff",ae.tabIndex=0,ae.setAttribute("aria-label",n.agent.diffAriaLabel),Ce.append(ge,D,Le,ae),x.append(C,ue,F,I,Ce),a.append(r,y,x);let U=G(e,n.agent.testConnection),fe=G(e,n.agent.verifyAndRun,"spotpatch-run"),Ne=G(e,n.agent.cancel),Ie=G(e,n.agent.apply,"spotpatch-primary"),ne=G(e,n.agent.revert),W=G(e,n.agent.revise),me=t.enabled?t.providers:[],he=new Map(me.map(f=>[f.id,f])),Re=!1,Me=!0,Ae=!1,oe=!1,L=!1,w=!1,Te,be,$e=[],se,Q="idle",Ee=n.agent.connectionNotTested,re;for(let f of me)In(e,m,f.id,f.label);t.enabled&&(m.value=t.defaultProvider);let q=()=>he.get(m.value),ye=()=>{let f=q();if(v.replaceChildren(),f===void 0){Z.textContent=n.agent.providerUnavailable;return}for(let z of f.models)In(e,v,z.id,z.label);v.value=f.defaultModel,Z.textContent=n.agent.consent(f.label)},Y=()=>{let f=t.enabled&&Ae&&!oe;fe.textContent=L?n.agent.verifying:w?n.agent.run:n.agent.verifyAndRun,fe.classList.toggle("spotpatch-primary",w),U.hidden=!f,fe.hidden=!f,U.disabled=!Me||L||q()===void 0,fe.disabled=!Me||L||!Re||!O.checked||q()===void 0||v.value.length===0,(!oe||!Ae)&&(Ne.hidden=!0,Ie.hidden=!0,ne.hidden=!0,W.hidden=!0)};ye(),m.addEventListener("change",()=>{ye(),O.checked=!1,g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Q="idle",Ee=n.agent.connectionNotTested,re=void 0,w=!1,Y()}),v.addEventListener("change",()=>{g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Q="idle",Ee=n.agent.connectionNotTested,re=void 0,w=!1,Y()}),O.addEventListener("change",Y);function we(){if(Te===void 0)return;let f=Te,z=be;R.textContent=`${f.providerLabel} · ${f.modelLabel}`,H.textContent=n.agent.status(f.status),ue.textContent=f.phaseMessage;let X=se??f.errorCode;F.hidden=X===void 0,F.textContent=X===void 0?"":n.errors[X],I.replaceChildren();for(let j of $e.slice(-8)){let ee=l(e,"li");ee.dataset.state=j.state,ee.textContent=j.label,I.append(ee)}Ce.hidden=z===void 0,ge.textContent=z?.summary??"",D.replaceChildren(),Le.replaceChildren(),ae.textContent=z?.diff??"";for(let j of z?.files??[]){let ee=l(e,"li");ee.textContent=`${j.kind} ${j.relativePath} (+${String(j.additions)} / -${String(j.deletions)})`,D.append(ee)}for(let j of z?.checks??[]){let ee=l(e,"details"),ce=l(e,"summary");ce.textContent=`${j.label}: ${j.status} · ${String(j.durationMs)} ms`;let ze=l(e,"pre");ze.textContent=j.output.length===0?n.agent.noOutput:j.output,ee.append(ce,ze),Le.append(ee)}U.hidden=!0,fe.hidden=!0,Ne.hidden=!Ae||!f.canCancel,Ne.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,Ie.hidden=!Ae||!f.canApply,ne.hidden=!Ae||!f.canRevert,W.hidden=!Ae||!["completed","cancelled","reverted","failed"].includes(f.status)}function Oe(){n=o.messages(),i.textContent=n.agent.title,c.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,P.textContent=n.agent.provider,A.textContent=n.agent.model,m.setAttribute("aria-label",n.agent.providerAriaLabel),v.setAttribute("aria-label",n.agent.modelAriaLabel),ae.setAttribute("aria-label",n.agent.diffAriaLabel),U.textContent=n.agent.testConnection,Ie.textContent=n.agent.apply,ne.textContent=n.agent.revert,W.textContent=n.agent.revise;let f=q();Z.textContent=f===void 0?n.agent.providerUnavailable:n.agent.consent(f.label),Q==="idle"?g.textContent=n.agent.connectionNotTested:Q==="probing"?g.textContent=n.agent.testingCapability:Q==="ready"?g.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:re!==void 0?g.textContent=n.errors[re]:q()===void 0?g.textContent=n.agent.providerUnavailable:g.textContent=Ee,Y(),we()}let De=o.subscribe(Oe);return Oe(),Object.freeze({root:a,providerSelect:m,modelSelect:v,consentCheckbox:O,testButton:U,runButton:fe,cancelButton:Ne,applyButton:Ie,revertButton:ne,resetButton:W,consentGranted(){return O.checked},readSelection(){let f=q(),z=f?.models.find(X=>X.id===v.value);return f===void 0||z===void 0?void 0:Object.freeze({providerProfileId:f.id,modelProfileId:z.id})},renderCapability(f,z,X,j){Q=f,Ee=z,re=j,L=f==="probing",w=f==="ready"&&X?.state==="agent-ready",g.dataset.state=f,g.textContent=X?.state==="agent-ready"?`${z} · ${n.agent.toolsReady}`:z,Y()},renderJob(f,z,X,j){oe=!0,y.hidden=!0,x.hidden=!1,m.disabled=!0,v.disabled=!0,O.disabled=!0,Te=f,be=z,$e=X,se=j,we()},resetJob(){oe=!1,Te=void 0,be=void 0,$e=[],se=void 0,y.hidden=!1,x.hidden=!0,m.disabled=!1,v.disabled=!1,O.disabled=!1,I.replaceChildren(),D.replaceChildren(),Le.replaceChildren(),ae.textContent="",F.textContent="",F.hidden=!0,Y()},setContextReady(f){Re=f,Y()},setEditingEnabled(f){Me=f,m.disabled=!f||oe,v.disabled=!f||oe,O.disabled=!f||oe,Y()},setProviderConsent(f){O.checked=f,Y()},setSelectionVisible(f){Ae=f,Y(),f||(Ne.hidden=!0,Ie.hidden=!0,ne.hidden=!0,W.hidden=!0)},dispose(){De()}})}var yr="http://www.w3.org/2000/svg";function _e(e,t,o){let n=e.createElementNS(yr,t);for(let[a,r]of Object.entries(o))n.setAttribute(a,r);return n}function kn(e){let t=_e(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=_e(e,"defs",{}),n=_e(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(_e(e,"stop",{offset:"0","stop-color":"#7c22ff"}),_e(e,"stop",{offset:".52","stop-color":"#4a69ff"}),_e(e,"stop",{offset:"1","stop-color":"#06d9ef"})),o.append(n);let a={fill:"none",stroke:"url(#spotpatch-brand-gradient)","stroke-linecap":"square","stroke-linejoin":"miter"},r=_e(e,"path",{d:"M106 42C67 42 43 68 43 105c0 36 24 61 63 96 39-35 63-60 63-96 0-37-24-63-63-63Z",...a,"stroke-width":"14"}),i=_e(e,"path",{d:"M106 25v42",...a,"stroke-width":"14"}),c=_e(e,"path",{d:"M35 109h20m102 0h38",...a,"stroke-width":"13"}),y=_e(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...a,"stroke-width":"9"}),E=_e(e,"path",{d:"m119 61-20 45 15 11-13 47 30-56-16-12 4-35Z",fill:"url(#spotpatch-brand-gradient)"});return t.append(o,r,i,c,y,E),t}function ft(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Mn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:a}){let r=a-t-16,i=n-e-16,c=o.x+o.width/2,y=o.y+o.height/2,E=ft(c-t/2,16,r),u=ft(y-e/2,16,i),P=E,m=u,k="viewport";return o.width>=t+48&&o.height>=e+48?k="center":o.y-e-14>=16?(m=o.y-e-14,k="above"):o.y+o.height+14+e<=n-16?(m=o.y+o.height+14,k="below"):o.x+o.width+14+t<=a-16?(P=o.x+o.width+14,k="right"):o.x-t-14>=16&&(P=o.x-t-14,k="left"),Object.freeze({anchorX:ft(c-P,22,t-22),anchorY:ft(y-m,22,e-22),left:P,mode:k,top:m})}var xr=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"}),Sr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ar=Object.freeze({[b.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[b.INVALID_TOKEN]:"The local SpotPatch session expired.",[b.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[b.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[b.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[b.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[b.EDITOR_OPEN_FAILED]:"The editor request failed.",[b.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[b.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[b.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[b.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[b.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[b.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[b.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[b.AGENT_BUSY]:"Another write Agent job is still active.",[b.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[b.AGENT_CANCELLED]:"The Agent job was cancelled.",[b.WORKTREE_DIRTY]:"Commit or otherwise clean staged, unstaged, and untracked files before running AI.",[b.TOOL_DENIED]:"A model tool request violated the local safety policy.",[b.PATCH_REJECTED]:"The proposed patch did not pass local policy.",[b.VALIDATION_FAILED]:"Required project checks failed. The change cannot be applied.",[b.APPLY_CONFLICT]:"Project files changed after the Agent baseline; no overwrite was performed.",[b.INTERNAL_ERROR]:"The Agent job failed without exposing private details."}),Er=Object.freeze({[b.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[b.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[b.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[b.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[b.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[b.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[b.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[b.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[b.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[b.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[b.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[b.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[b.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[b.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[b.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[b.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[b.AGENT_CANCELLED]:"Agent 任务已取消。",[b.WORKTREE_DIRTY]:"运行 AI 前,请先提交或清理暂存、未暂存与未跟踪文件。",[b.TOOL_DENIED]:"模型工具请求违反本地安全策略。",[b.PATCH_REJECTED]:"建议补丁未通过本地策略检查。",[b.VALIDATION_FAILED]:"项目必需检查失败,不能应用本次变更。",[b.APPLY_CONFLICT]:"Agent 建立基线后项目文件已变化,未执行覆盖。",[b.INTERNAL_ERROR]:"Agent 任务失败,私有细节未暴露到浏览器。"}),vr=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"}),Cr=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:"警告"}),Rr=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:vr,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",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:"Test connection",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=>xr[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.",detachedTargetRemoved:"A removed page element was dropped from the selection.",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:Ar}),"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:Cr,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:"尚未测试连接",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=>Sr[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:"已移除选中目标。",detachedTargetRemoved:"页面中的目标已卸载,已从当前选择中移除。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Er})});function $n(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 Tr(e,t){if(e!=="auto")return e;let o=$n(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map($n).find(a=>a!==void 0)??"en-US"}function Dn(e,t="auto"){let o=Tr(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Rr[o],subscribe(a){return n.add(a),()=>{n.delete(a)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let a of n)a()}})}var wr=560,Or=Object.freeze({previewing:640,selected:720});function Pr(e){let t=e.createElement("style");return t.textContent=`
166
166
  :host {
167
167
  all: initial;
168
168
  --spotpatch-bg: #11141a;
@@ -197,7 +197,7 @@ ${ht(e.code.language,H(t.codeLines.join(`
197
197
  position: fixed;
198
198
  right: 24px;
199
199
  bottom: 24px;
200
- z-index: ${String(at.controls)};
200
+ z-index: ${String(ot.controls)};
201
201
  display: inline-flex;
202
202
  align-items: center;
203
203
  gap: 10px;
@@ -231,7 +231,7 @@ ${ht(e.code.language,H(t.codeLines.join(`
231
231
  position: fixed;
232
232
  top: 0;
233
233
  left: 0;
234
- z-index: ${String(at.highlight)};
234
+ z-index: ${String(ot.highlight)};
235
235
  box-sizing: border-box;
236
236
  border: 2px solid var(--spotpatch-accent);
237
237
  border-radius: 6px;
@@ -258,7 +258,7 @@ ${ht(e.code.language,H(t.codeLines.join(`
258
258
  .spotpatch-selection-highlights {
259
259
  position: fixed;
260
260
  inset: 0;
261
- z-index: ${String(at.highlight)};
261
+ z-index: ${String(ot.highlight)};
262
262
  pointer-events: none;
263
263
  }
264
264
  .spotpatch-selection-highlight {
@@ -299,7 +299,7 @@ ${ht(e.code.language,H(t.codeLines.join(`
299
299
  position: fixed;
300
300
  top: 16px;
301
301
  left: 16px;
302
- z-index: ${String(at.controls)};
302
+ z-index: ${String(ot.controls)};
303
303
  box-sizing: border-box;
304
304
  width: min(560px, calc(100vw - 32px));
305
305
  color: #edf0f7;
@@ -397,36 +397,27 @@ ${ht(e.code.language,H(t.codeLines.join(`
397
397
  gap: 8px;
398
398
  flex: none;
399
399
  }
400
+ .spotpatch-repository,
401
+ .spotpatch-locale,
402
+ .spotpatch-close {
403
+ height: 30px;
404
+ border: 1px solid rgb(255 255 255 / 11%);
405
+ border-radius: 9px;
406
+ background: rgb(255 255 255 / 4%);
407
+ }
400
408
  .spotpatch-repository {
401
409
  display: inline-flex;
402
- height: 30px;
403
410
  align-items: center;
404
- gap: 5px;
405
- border: 1px solid rgb(68 202 224 / 20%);
406
- border-radius: 9px;
407
411
  padding: 0 10px;
408
412
  color: #bcecf2;
409
- background: rgb(8 145 178 / 7%);
410
413
  font-size: 11px;
411
414
  font-weight: 680;
412
415
  text-decoration: none;
413
- transition: border-color 150ms ease, color 150ms ease, background 150ms ease, transform 150ms ease;
414
- }
415
- .spotpatch-repository::after { content: "↗"; font-size: 10px; }
416
- .spotpatch-repository:hover {
417
- border-color: rgb(68 202 224 / 42%);
418
- color: #e6fbff;
419
- background: rgb(8 145 178 / 12%);
420
- transform: translateY(-1px);
421
416
  }
422
417
  .spotpatch-locale {
423
418
  min-width: 38px;
424
- height: 30px;
425
- border: 1px solid rgb(255 255 255 / 11%);
426
- border-radius: 9px;
427
419
  padding: 0 9px;
428
420
  color: #c5cad5;
429
- background: rgb(255 255 255 / 4%);
430
421
  cursor: pointer;
431
422
  font-size: 12px;
432
423
  font-weight: 650;
@@ -434,20 +425,17 @@ ${ht(e.code.language,H(t.codeLines.join(`
434
425
  .spotpatch-close {
435
426
  display: inline-grid;
436
427
  width: 30px;
437
- height: 30px;
438
428
  padding: 0;
439
429
  place-items: center;
440
- border: 1px solid rgb(255 255 255 / 11%);
441
- border-radius: 9px;
442
430
  color: #9da5b4;
443
- background: rgb(255 255 255 / 4%);
444
431
  cursor: pointer;
445
432
  font-size: 17px;
446
433
  line-height: 1;
447
434
  transition: border-color 150ms ease, color 150ms ease, background 150ms ease;
448
435
  }
449
436
  .spotpatch-close:hover,
450
- .spotpatch-locale:hover { border-color: rgb(129 112 247 / 45%); color: #fff; background: rgb(109 93 246 / 10%); }
437
+ .spotpatch-locale:hover,
438
+ .spotpatch-repository:hover { border-color: rgb(129 112 247 / 45%); color: #fff; background: rgb(109 93 246 / 10%); }
451
439
  .spotpatch-title {
452
440
  margin: 0;
453
441
  color: #fff;
@@ -497,10 +485,14 @@ ${ht(e.code.language,H(t.codeLines.join(`
497
485
  background: #f59e0b;
498
486
  content: "";
499
487
  }
500
- .spotpatch-context-state[data-state="ready"] { color: #9fe3c4; }
501
- .spotpatch-context-state[data-state="ready"]::before { background: #34d399; }
502
- .spotpatch-context-state[data-state="warning"] { color: #fecaca; }
503
- .spotpatch-context-state[data-state="warning"]::before { background: #fb7185; }
488
+ .spotpatch-context-state[data-state="ready"],
489
+ .spotpatch-editor-feedback[data-state="success"] { color: #9fe3c4; }
490
+ .spotpatch-context-state[data-state="ready"]::before,
491
+ .spotpatch-editor-feedback[data-state="success"]::before { background: #34d399; }
492
+ .spotpatch-context-state[data-state="warning"],
493
+ .spotpatch-editor-feedback[data-state="error"] { color: #fecaca; }
494
+ .spotpatch-context-state[data-state="warning"]::before,
495
+ .spotpatch-editor-feedback[data-state="error"]::before { background: #fb7185; }
504
496
  .spotpatch-body {
505
497
  min-height: 0;
506
498
  overflow: auto;
@@ -739,29 +731,9 @@ ${ht(e.code.language,H(t.codeLines.join(`
739
731
  background: rgb(8 12 22 / 82%);
740
732
  }
741
733
  .spotpatch-editor-feedback {
742
- display: flex;
743
- width: 100%;
744
- align-items: center;
745
- gap: 7px;
746
- margin-bottom: 1px;
747
- color: #9ca5b5;
748
- font-size: 11px;
749
- line-height: 1.45;
734
+ flex-basis: 100%;
735
+ white-space: normal;
750
736
  }
751
- .spotpatch-editor-feedback[hidden] { display: none; }
752
- .spotpatch-editor-feedback::before {
753
- width: 6px;
754
- height: 6px;
755
- flex: none;
756
- border-radius: 999px;
757
- background: #94a3b8;
758
- content: "";
759
- }
760
- .spotpatch-editor-feedback[data-state="opening"]::before { background: #38bdf8; }
761
- .spotpatch-editor-feedback[data-state="success"] { color: #9fe3c4; }
762
- .spotpatch-editor-feedback[data-state="success"]::before { background: #34d399; }
763
- .spotpatch-editor-feedback[data-state="error"] { color: #fecaca; }
764
- .spotpatch-editor-feedback[data-state="error"]::before { background: #fb7185; }
765
737
  .spotpatch-actions button {
766
738
  display: inline-flex;
767
739
  min-height: 40px;
@@ -827,13 +799,11 @@ ${ht(e.code.language,H(t.codeLines.join(`
827
799
  .spotpatch-actions { padding-left: 16px; padding-right: 16px; }
828
800
  .spotpatch-target-select { grid-template-columns: 32px minmax(0, 1fr); }
829
801
  .spotpatch-target-state { display: none; }
830
- .spotpatch-repository { width: 30px; overflow: hidden; padding: 0; justify-content: center; color: transparent; }
831
- .spotpatch-repository::after { color: #bcecf2; content: "↗"; }
832
- }
833
- ${$n}
834
- `,t}function Mr(e,t){return e.split(`
835
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Hn(e,t,o=Object.freeze({enabled:!1}),n="auto",i="auto"){let a=Un(e,n),r=a.messages(),c=e.createElement("spotpatch-root");c.setAttribute(Xe,"");let C=c.attachShadow({mode:"open"}),x=G(e,r.trigger.select,"spotpatch-trigger");x.title=r.trigger.title(t),x.setAttribute("aria-pressed","false");let p=d(e,"div");p.className="spotpatch-highlight",p.hidden=!0;let I=d(e,"span");I.className="spotpatch-highlight-label",p.append(I);let E=d(e,"div");E.className="spotpatch-selection-highlights",E.setAttribute("aria-hidden","true");let R=d(e,"section");R.className="spotpatch-dialog",R.hidden=!0,R.tabIndex=-1,R.dataset.placement="viewport",R.setAttribute("role","dialog"),R.setAttribute("aria-labelledby","spotpatch-selection-title");let S=d(e,"span");S.className="spotpatch-anchor",S.setAttribute("aria-hidden","true");let A=d(e,"div");A.className="spotpatch-shell";let M=d(e,"header");M.className="spotpatch-header";let w=d(e,"div");w.className="spotpatch-brand-row";let X=d(e,"div");X.className="spotpatch-brand";let g=d(e,"span");g.className="spotpatch-brand-copy";let b=d(e,"span");b.className="spotpatch-brand-name";let v=d(e,"span");v.className="spotpatch-brand-context",g.append(b,v),X.append(zn(e),g);let O=d(e,"span");O.className="spotpatch-header-controls";let $=d(e,"a");$.className="spotpatch-repository",$.href=kt,$.target="_blank",$.rel="noopener noreferrer";let oe=G(e,"","spotpatch-locale"),F=G(e,"×","spotpatch-close");O.append($,oe,F),w.append(X,O);let _=d(e,"h2");_.id="spotpatch-selection-title",_.className="spotpatch-title";let ve=d(e,"p");ve.className="spotpatch-subtitle";let Oe=d(e,"div");Oe.className="spotpatch-target-row";let Z=d(e,"span");Z.className="spotpatch-target-label";let J=d(e,"span");J.className="spotpatch-context-state",J.dataset.state="loading",J.textContent=r.context.collecting,Oe.append(Z,J),M.append(w,_,ve,Oe);let ge=d(e,"div");ge.className="spotpatch-body";let U=d(e,"div");U.className="spotpatch-selection-panel";let se=d(e,"section");se.className="spotpatch-targets";let Le=d(e,"div");Le.className="spotpatch-targets-heading";let ke=d(e,"span"),xe=d(e,"span");xe.className="spotpatch-targets-meta";let ce=d(e,"span");ce.className="spotpatch-target-complete";let W=d(e,"span");W.className="spotpatch-target-budget",W.setAttribute("aria-live","polite");let Me=d(e,"span");Me.className="spotpatch-target-count",xe.append(ce,W),Le.append(ke,Me);let re=d(e,"div");re.className="spotpatch-target-list",se.append(Le,xe,re);let Ce=d(e,"details");Ce.className="spotpatch-diagnostics";let Se=d(e,"summary"),Re=d(e,"span"),L=d(e,"span");L.className="spotpatch-source-peek",L.textContent=r.diagnostics.resolving,Se.append(Re,L);let Te=d(e,"pre");Te.className="spotpatch-summary",Ce.append(Se,Te);let P=Dn(e,o,a);U.append(se,Ce,P.root);let Ie=d(e,"div");Ie.className="spotpatch-preview-panel",Ie.hidden=!0;let fe=d(e,"pre");fe.className="spotpatch-prompt",fe.tabIndex=0,fe.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Ie.append(fe),ge.append(U,Ie);let Be=d(e,"footer");Be.className="spotpatch-actions";let q=d(e,"div");q.className="spotpatch-editor-feedback",q.dataset.state="idle",q.setAttribute("role","status"),q.setAttribute("aria-live","polite"),q.hidden=!0;let de=G(e,r.actions.addElement),me=G(e,r.actions.reselect),Q=G(e,r.actions.openEditor(i)),K=G(e,r.actions.preview,"spotpatch-primary"),Y=G(e,r.actions.copy,"spotpatch-primary"),$e=G(e,r.actions.back);Be.append(q,P.runButton,K,P.testButton,P.cancelButton,P.applyButton,P.revertButton,P.resetButton,de,Q,me,Y,$e),A.append(M,ge,Be),R.append(S,A);let we=d(e,"div");we.className="spotpatch-live",we.setAttribute("aria-live","polite"),we.setAttribute("aria-atomic","true"),C.append(kr(e),E,p,R,x,we),e.documentElement.append(c);let _e,f,D="idle",ee=!1,B=!1,te="",De=!0,he=[],Ze=0,s="idle";function u(l){return l==="opening"?r.announcements.editorOpening(i):l==="success"?r.announcements.editorOpened(i):l==="error"?r.announcements.editorFailed(i):""}function y(l,m=u(l)){s=l,q.dataset.state=l,q.hidden=l==="idle",q.textContent=m,be()}function N(l){return l.status==="ready"?r.targets.statusReady:l.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function z(l){let m=re.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(m).find(T=>l===void 0||T.dataset.targetInstructionId===l)}function ie(l,m){let T=C.activeElement?.closest("textarea[data-target-instruction-id]"),j=T?.dataset.targetInstructionId,le=T?.selectionStart,ze=T?.selectionEnd;he=l.map(ae=>Object.freeze({...ae})),Ze=m,re.replaceChildren();let Ue=l.filter(ae=>ae.instruction.trim().length>0).length,pe=l.reduce((ae,V)=>ae+V.instruction.trim().length,0);Me.textContent=r.targets.count(l.length,m),ce.textContent=r.targets.complete(Ue,l.length);let Pe=pe>4e3;W.dataset.state=Pe?"over":"ready",W.textContent=Pe?r.targets.instructionBudgetExceeded(pe,4e3):r.targets.instructionBudget(pe,4e3),de.disabled=!De||l.length>=m,de.title=l.length>=m?r.targets.limitTitle(m):r.targets.addTitle,Z.textContent=l.length===1?l[0]?.label??r.context.selectedElement:r.context.selectedCount(l.length);for(let[ae,V]of l.entries()){let Fe=d(e,"div");Fe.className="spotpatch-target-item",Fe.dataset.active=String(V.active),Fe.dataset.status=V.status,Fe.dataset.targetId=V.id;let yt=d(e,"div");yt.className="spotpatch-target-summary";let et=G(e,"","spotpatch-target-select");et.dataset.activateTargetId=V.id,et.setAttribute("aria-label",r.targets.activate(ae+1)),et.setAttribute("aria-expanded",String(V.active));let xt=d(e,"span");xt.className="spotpatch-target-index",xt.textContent=String(ae+1);let St=d(e,"span");St.className="spotpatch-target-copy";let Et=d(e,"span");Et.className="spotpatch-target-name",Et.textContent=V.label;let At=d(e,"span");At.className="spotpatch-target-source",At.textContent=`${N(V)} · ${V.source}`,St.append(Et,At);let qt=V.instruction.trim().length>0,ct=d(e,"span");ct.className="spotpatch-target-state",ct.dataset.complete=String(qt),ct.textContent=qt?r.targets.instructionReady:r.targets.instructionMissing,et.append(xt,St,ct);let tt=G(e,"↗","spotpatch-target-open");tt.dataset.openTargetId=V.id,tt.disabled=!V.canOpenEditor,tt.setAttribute("aria-label",r.actions.openTarget(ae+1,i)),tt.title=r.actions.openTarget(ae+1,i);let nt=G(e,"×","spotpatch-target-remove");if(nt.dataset.removeTargetId=V.id,nt.disabled=!De,nt.setAttribute("aria-label",r.targets.remove(ae+1)),nt.title=r.targets.removeTitle,yt.append(et,tt,nt),Fe.append(yt),V.active){let vt=d(e,"label");vt.className="spotpatch-target-editor";let Ct=d(e,"span");Ct.className="spotpatch-target-editor-head";let Rt=d(e,"span");Rt.className="spotpatch-target-editor-label",Rt.textContent=r.targets.instructionLabel(V.label);let Tt=d(e,"span");Tt.className="spotpatch-target-editor-count",Tt.textContent=r.targets.instructionCount(V.instruction.length,2e3),Ct.append(Rt,Tt);let Je=d(e,"textarea");Je.rows=4,Je.maxLength=2e3,Je.value=V.instruction,Je.placeholder=r.targets.instructionPlaceholder,Je.disabled=!De,Je.dataset.targetInstructionId=V.id,Je.setAttribute("aria-label",r.targets.instructionLabel(V.label)),vt.append(Ct,Je),Fe.append(vt)}re.append(Fe)}if(j!==void 0){let ae=z(j);ae?.focus({preventScroll:!0}),le!==void 0&&ze!==void 0&&ae?.setSelectionRange(le,ze)}}function Ee(l,m){he=he.map(Pe=>Pe.id===l?Object.freeze({...Pe,instruction:m}):Pe);let T=Array.from(re.querySelectorAll(".spotpatch-target-item")).find(Pe=>Pe.dataset.targetId===l);if(T===void 0)return;let j=m.trim().length>0,le=T.querySelector(".spotpatch-target-state"),ze=T.querySelector(".spotpatch-target-editor-count");le!==null&&(le.dataset.complete=String(j),le.textContent=j?r.targets.instructionReady:r.targets.instructionMissing),ze!==null&&(ze.textContent=r.targets.instructionCount(m.length,2e3)),ce.textContent=r.targets.complete(he.filter(Pe=>Pe.instruction.trim().length>0).length,he.length);let Ue=he.reduce((Pe,ae)=>Pe+ae.instruction.trim().length,0),pe=Ue>4e3;W.dataset.state=pe?"over":"ready",W.textContent=pe?r.targets.instructionBudgetExceeded(Ue,4e3):r.targets.instructionBudget(Ue,4e3)}function st(l){E.replaceChildren(),f=l.find(m=>m.active)?.rect,_e=f;for(let[m,T]of l.entries()){let j=d(e,"div");j.className="spotpatch-selection-highlight",j.dataset.targetId=T.id,j.dataset.active=String(T.active),j.style.transform=`translate(${String(T.rect.x)}px, ${String(T.rect.y)}px)`,j.style.width=`${String(T.rect.width)}px`,j.style.height=`${String(T.rect.height)}px`;let le=d(e,"span");le.textContent=`${String(m+1)} · ${T.label}`,j.append(le),E.append(j)}be()}function be(){if(R.hidden||_e===void 0)return;let l=e.defaultView,m=l?.innerWidth??e.documentElement.clientWidth,T=l?.innerHeight??e.documentElement.clientHeight,j=R.getBoundingClientRect(),le=D==="previewing"?"previewing":"selected",ze=j.width>0?j.width:Math.min(_r,m-32),Ue=j.height>0?j.height:Math.min(Nr[le],T-32),pe=jn({target:_e,dialogWidth:ze,dialogHeight:Ue,viewportWidth:m,viewportHeight:T});R.style.left=`${String(pe.left)}px`,R.style.top=`${String(pe.top)}px`,R.style.setProperty("--spotpatch-anchor-x",`${String(pe.anchorX)}px`),R.style.setProperty("--spotpatch-anchor-y",`${String(pe.anchorY)}px`),R.dataset.placement=pe.mode}function Jt(l){let m=r.summary,T=Mr(l,m.source);L.textContent=T??r.diagnostics.noExactSource;let j=`${m.browserContext}: ${m.collectionStatuses.ready}`,le=`${m.browserContext}: ${m.collectionStatuses.loading}`,ze=`${m.browserContext}: ${m.collectionStatuses.failed}`,Ue=`${m.api}: ${m.apiStatuses.loading}`,pe=`${m.api}: ${m.apiStatuses.failed}`;l.includes(j)&&!l.includes(le)&&!l.includes(Ue)&&!l.includes(ze)&&!l.includes(pe)?(J.dataset.state="ready",J.textContent=r.context.ready):l.includes(ze)||l.includes(pe)?(J.dataset.state="warning",J.textContent=r.context.partial):(J.dataset.state="loading",J.textContent=r.context.collecting)}function Vt(l,m,T){ee=m,B=T,te=l,Te.textContent=l,Q.disabled=!m,K.disabled=!T,P.setContextReady(T),Jt(l),be()}function Gt(l){D=l;let m=l==="selected",T=l==="previewing";x.hidden=m||T,U.hidden=!m,Ie.hidden=!T,me.hidden=!m,de.hidden=!m,Q.hidden=!m,K.hidden=!m,P.setSelectionVisible(m),Y.hidden=!T,$e.hidden=!T,_.textContent=T?r.dialog.previewTitle:r.dialog.editTitle,ve.textContent=T?r.dialog.previewSubtitle:r.dialog.editSubtitle,be()}function Ft(){r=a.messages(),b.textContent=r.brand.name,v.textContent=r.brand.context,$.textContent=r.brand.repository,$.title=r.brand.repositoryTitle,$.setAttribute("aria-label",r.brand.repositoryTitle),oe.textContent=r.alternateLocaleName,oe.title=r.switchLocale,oe.setAttribute("aria-label",r.switchLocale),F.setAttribute("aria-label",r.dialog.close),F.title=r.dialog.close,se.setAttribute("aria-label",r.targets.ariaLabel),ke.textContent=r.targets.title,Re.textContent=r.diagnostics.title,fe.setAttribute("aria-label",r.diagnostics.promptAriaLabel),de.textContent=r.actions.addElement,me.textContent=r.actions.reselect,Q.textContent=r.actions.openEditor(i),K.textContent=r.actions.preview,Y.textContent=r.actions.copy,$e.textContent=r.actions.back,x.title=r.trigger.title(t),x.textContent=D==="inspecting"?r.trigger.stop:r.trigger.select,Gt(D),y(s),he.length>0?ie(he,Ze):(Me.textContent=r.targets.count(0,Ze),ce.textContent=r.targets.complete(0,0),W.dataset.state="ready",W.textContent=r.targets.instructionBudget(0,4e3),Z.textContent=r.context.selectedElement),te.length>0?Jt(te):(L.textContent=r.diagnostics.resolving,J.textContent=r.context.collecting)}Ce.addEventListener("toggle",be),oe.addEventListener("click",a.toggle);let Xn=a.subscribe(Ft);return Ft(),Object.freeze({host:c,triggerButton:x,addTargetButton:de,targetList:re,reselectButton:me,openEditorButton:Q,repositoryLink:$,previewButton:K,copyButton:Y,backButton:$e,closeButton:F,agentProviderSelect:P.providerSelect,agentModelSelect:P.modelSelect,agentConsentCheckbox:P.consentCheckbox,agentTestButton:P.testButton,agentRunButton:P.runButton,agentCancelButton:P.cancelButton,agentApplyButton:P.applyButton,agentRevertButton:P.revertButton,agentResetButton:P.resetButton,renderStatus(l){let m=l==="inspecting";x.setAttribute("aria-pressed",String(m)),x.textContent=m?r.trigger.stop:r.trigger.select,Gt(l)},renderEditorStatus:y,showHighlight(l,m){_e=l,p.hidden=!1,p.style.transform=`translate(${String(l.x)}px, ${String(l.y)}px)`,p.style.width=`${String(l.width)}px`,p.style.height=`${String(l.height)}px`,I.textContent=m,Z.textContent=m,be()},hideHighlight(){_e=f,p.hidden=!0,I.textContent="",be()},showSelectionHighlights:st,hideSelectionHighlights(){E.replaceChildren(),f=void 0,_e=void 0},showSelection(l,m,T){Vt(l,m,T),x.hidden=!0,R.hidden=!1,be()},updateSelection:Vt,renderTargets:ie,updateTargetInstruction:Ee,setPreviewEnabled(l){B=l,K.disabled=!l,P.setContextReady(l)},hideSelection(){R.hidden=!0,x.hidden=!1,re.replaceChildren(),he=[],Ze=0,te="",y("idle"),Me.textContent=r.targets.count(0,0),ce.textContent=r.targets.complete(0,0),Z.textContent=r.context.selectedElement,Te.textContent="",fe.textContent="",L.textContent=r.diagnostics.resolving,J.dataset.state="loading",J.textContent=r.context.collecting,Q.disabled=!0,K.disabled=!0,ee=!1,B=!1,P.setContextReady(!1),P.setSelectionVisible(!1),P.setEditingEnabled(!0),P.resetJob()},hideSelectionTemporarily(){R.hidden=!0,x.hidden=!1},showPreview(l){fe.textContent=l,be()},readAgentSelection(){return P.readSelection()},agentConsentGranted(){return P.consentGranted()},setAgentProviderConsent(l){P.setProviderConsent(l)},setAgentEditingEnabled(l){De=l,de.disabled=!l,me.disabled=!l,re.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(m=>{m.disabled=!l}),Q.disabled=!ee,K.disabled=!l||!B,P.setEditingEnabled(l),be()},renderAgentCapability(l,m,T,j){P.renderCapability(l,m,T,j);let le=l==="ready"&&T?.state==="agent-ready";K.classList.toggle("spotpatch-primary",!le),be()},renderAgentJob(l,m,T,j){P.renderJob(l,m,T,j),be()},resetAgentJob(){P.resetJob(),be()},focusTargetInstruction(l){z(l)?.focus({preventScroll:!0})},focusPrompt(){fe.focus({preventScroll:!0})},announce(l){we.textContent="",we.textContent=l},locale:a.locale,messages:a.messages,subscribeLocale:a.subscribe,dispose(){Ce.removeEventListener("toggle",be),oe.removeEventListener("click",a.toggle),Xn(),P.dispose(),c.remove()}})}function $r(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,a=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${a===void 0?"":`:${String(a)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,a):o.unavailable}function Jn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`Vite: ${e.viteVersion}`,`${t.source}: ${$r(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(`
836
- `)}function Vn(e,t){return`${e}:${t}`}function Dr(e){if(e.type==="tool")return Object.freeze({key:`tool:${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 Gn(e){let t=g=>sn(g)??h.INTERNAL_ERROR,o=g=>e.view.messages().errors[t(g)],n=new Map,i=new Set,a=new Map,r=0,c,C,x=!1,p=!1,I=()=>e.view.readAgentSelection(),E=g=>{c!==void 0&&e.view.renderAgentJob(c,C,Object.freeze([...a.values()]),g??c.errorCode)},R=()=>{let g=I();if(g===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(g.providerProfileId));let b=n.get(Vn(g.providerProfileId,g.modelProfileId));b===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,b)},S=async g=>{let b=I();if(b===void 0)throw new Error("Agent provider selection is unavailable.");let v=Vn(b.providerProfileId,b.modelProfileId),O=n.get(v);if(O!==void 0)return O;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let $=await e.api.agentCapability(b);if(g!==r)return $;if($.state!=="agent-ready")throw new k($.errorCode??h.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(v,$),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,$),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),$},A=async(g,b)=>{try{let v=await e.api.agentResult(g);if(b!==r||v.snapshot.jobId!==g)return;c=v.snapshot,C=v.result,E()}catch(v){b===r&&E(t(v))}},M=async(g,b)=>{try{await e.api.agentEvents(g,v=>{if(b!==r||v.jobId!==g)return;v.type==="snapshot"&&(c=v.data.snapshot,c.status==="applied"&&!x&&(x=!0,e.onApplied()));let O=Dr(v);O!==void 0&&a.set(O.key,O),E()}),b===r&&await A(g,b)}catch(v){b===r&&!(v instanceof DOMException&&v.name==="AbortError")&&E(t(v))}},w=async g=>{let b=c;if(b===void 0||p)return;p=!0;let v=r;c=Object.freeze({...b,status:g==="apply"?"applying":g==="cancel"?"cancelling":"reverting",phaseMessage:g==="apply"?e.view.messages().agent.applying:g==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),E();try{let O=g==="apply"?await e.api.applyAgentJob(b.jobId):g==="cancel"?await e.api.cancelAgentJob(b.jobId):await e.api.revertAgentJob(b.jobId);if(v!==r)return;c=O,O.status==="applied"&&!x&&(x=!0,e.onApplied()),await A(O.jobId,v)}catch(O){if(v!==r)return;c=b,await A(b.jobId,v),E(t(O)),e.view.announce(o(O))}finally{v===r&&(p=!1)}},X=()=>{r+=1,c=void 0,C=void 0,a.clear(),x=!1,p=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),R()};return Object.freeze({apply(){c?.canApply===!0&&w("apply")},beginSelection(){X()},cancel(){c?.canCancel===!0&&w("cancel")},consentChanged(){let g=I();g!==void 0&&(e.view.agentConsentGranted()?i.add(g.providerProfileId):i.delete(g.providerProfileId))},disposeSelection(){let g=c?.canCancel===!0||c?.status==="cancelling"?c.jobId:void 0;r+=1,c=void 0,C=void 0,a.clear(),x=!1,p=!1,g!==void 0&&e.api.cancelAgentJob(g).catch(()=>{})},providerOrModelChanged(){r+=1,R()},reset(){let g=x;X(),g&&e.onReselectRequired()},revert(){c?.canRevert===!0&&w("revert")},run(){if(!e.ai.enabled||c!==void 0)return;let g=I(),b=e.getAnnotation();if(g===void 0||b===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(g.providerProfileId);let v=++r;e.view.setAgentEditingEnabled(!1),S(v).then(async()=>{if(v!==r)return;let O=await e.api.createAgentJob({annotation:b,providerProfileId:g.providerProfileId,modelProfileId:g.modelProfileId,providerDataConsent:!0});v===r&&(c=O,C=void 0,a.clear(),E(),M(O.jobId,v))}).catch(O=>{v===r&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(O),void 0,t(O)),e.view.announce(o(O)))})},testCapability(){if(!e.ai.enabled||c!==void 0)return;let g=++r;S(g).catch(b=>{g===r&&(e.view.renderAgentCapability("error",o(b),void 0,t(b)),e.view.announce(o(b)))})}})}function Fn(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 qn(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 Kn(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var jr=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Ut(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 Br(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function Ur(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Hr(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 Wn(e,t={}){let o=Hr(t),n=t.view??Hn(o.document,e.shortcut,e.ai,e.locale,e.editor),i=t.api??cn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),a=t.promptComposer??Pn({maxCharacters:e.budget.totalCharacters}),r=t.clipboard??Kn(o.window.navigator),c=t.createId??(()=>Fn(o.window)),C=t.now??(()=>new Date().toISOString()),x=kn({adapter:t.reactAdapter??zr({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.")}}),p=Bt,I=!1,E,R,S=[],A,M=0,w=0,X=0,g=!1,b="",v,O,$,oe,F=new Map;function _(s){p=On(p,s),n.renderStatus(p.status)}function ve(){return S.find(s=>s.id===A)??S.at(-1)}function Oe(s,u){return I&&u===w&&p.status!=="idle"&&S.includes(s)}function Z(){let s=S.reduce((u,y)=>u+y.instruction.trim().length,0);return S.length>0&&s<=4e3&&S.every(u=>u.instruction.trim().length>0&&u.element!==void 0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function J(){let s=n.messages().summary;return S.map((u,y)=>{let N=Jn({resolution:u.resolution,...u.code===void 0?{}:{code:u.code},...u.styles===void 0?{}:{styles:u.styles},apiStatus:u.apiStatus,collectionStatus:u.collectionStatus,spotPatchVersion:e.spotPatchVersion,viteVersion:e.viteVersion},s);return`${s.target(y+1,u.id===A)}
837
- ${N}`}).join(`
802
+ }
803
+ ${_n}
804
+ `,t}function Lr(e,t){return e.split(`
805
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function zn(e,t,o=Object.freeze({enabled:!1}),n="auto"){let a=Dn(e,n),r=a.messages(),i=e.createElement("spotpatch-root");i.setAttribute(We,"");let c=i.attachShadow({mode:"open"}),y=G(e,r.trigger.select,"spotpatch-trigger");y.title=r.trigger.title(t),y.setAttribute("aria-pressed","false");let E=l(e,"div");E.className="spotpatch-highlight",E.hidden=!0;let u=l(e,"span");u.className="spotpatch-highlight-label",E.append(u);let P=l(e,"div");P.className="spotpatch-selection-highlights",P.setAttribute("aria-hidden","true");let m=l(e,"section");m.className="spotpatch-dialog",m.hidden=!0,m.tabIndex=-1,m.dataset.placement="viewport",m.setAttribute("role","dialog"),m.setAttribute("aria-labelledby","spotpatch-selection-title");let k=l(e,"span");k.className="spotpatch-anchor",k.setAttribute("aria-hidden","true");let A=l(e,"div");A.className="spotpatch-shell";let v=l(e,"header");v.className="spotpatch-header";let M=l(e,"div");M.className="spotpatch-brand-row";let O=l(e,"div");O.className="spotpatch-brand";let Z=l(e,"span");Z.className="spotpatch-brand-copy";let g=l(e,"span");g.className="spotpatch-brand-name";let x=l(e,"span");x.className="spotpatch-brand-context",Z.append(g,x),O.append(kn(e),Z);let C=l(e,"span");C.className="spotpatch-header-controls";let R=l(e,"a");R.className="spotpatch-repository",R.href=Lt,R.target="_blank",R.rel="noopener noreferrer";let H=G(e,"","spotpatch-locale"),ue=G(e,"×","spotpatch-close");C.append(R,H,ue),M.append(O,C);let F=l(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let I=l(e,"p");I.className="spotpatch-subtitle";let Ce=l(e,"div");Ce.className="spotpatch-target-row";let ge=l(e,"span");ge.className="spotpatch-target-label";let D=l(e,"span");D.className="spotpatch-context-state",D.dataset.state="loading",D.textContent=r.context.collecting,Ce.append(ge,D),v.append(M,F,I,Ce);let Le=l(e,"div");Le.className="spotpatch-body";let ae=l(e,"div");ae.className="spotpatch-selection-panel";let U=l(e,"section");U.className="spotpatch-targets";let fe=l(e,"div");fe.className="spotpatch-targets-heading";let Ne=l(e,"span"),Ie=l(e,"span");Ie.className="spotpatch-targets-meta";let ne=l(e,"span");ne.className="spotpatch-target-complete";let W=l(e,"span");W.className="spotpatch-target-budget",W.setAttribute("aria-live","polite");let me=l(e,"span");me.className="spotpatch-target-count",Ie.append(ne,W),fe.append(Ne,me);let he=l(e,"div");he.className="spotpatch-target-list",U.append(fe,Ie,he);let Re=l(e,"details");Re.className="spotpatch-diagnostics";let Me=l(e,"summary"),Ae=l(e,"span"),oe=l(e,"span");oe.className="spotpatch-source-peek",oe.textContent=r.diagnostics.resolving,Me.append(Ae,oe);let L=l(e,"pre");L.className="spotpatch-summary",Re.append(Me,L);let w=Nn(e,o,a);ae.append(U,Re,w.root);let Te=l(e,"div");Te.className="spotpatch-preview-panel",Te.hidden=!0;let be=l(e,"pre");be.className="spotpatch-prompt",be.tabIndex=0,be.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Te.append(be),Le.append(ae,Te);let $e=l(e,"footer");$e.className="spotpatch-actions";let se=l(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 Q=G(e,r.actions.addElement),Ee=G(e,r.actions.reselect),re=G(e,r.actions.openEditor),q=G(e,r.actions.preview,"spotpatch-primary"),ye=G(e,r.actions.copy,"spotpatch-primary"),Y=G(e,r.actions.back);$e.append(se,w.runButton,q,w.testButton,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Q,re,Ee,ye,Y),A.append(v,Le,$e),m.append(k,A);let we=l(e,"div");we.className="spotpatch-live",we.setAttribute("aria-live","polite"),we.setAttribute("aria-atomic","true"),c.append(Pr(e),P,E,m,y,we),e.documentElement.append(i);let Oe,De,f="idle",z=!1,X=!1,j="",ee=!0,ce=[],ze=0,rt="idle";function s(d){rt=d,se.dataset.state=d,se.hidden=d==="idle",se.textContent=d==="opening"?r.announcements.editorOpening:d==="success"?r.announcements.editorOpened:d==="error"?r.announcements.editorFailed:"",K()}function p(d){return d.status==="ready"?r.targets.statusReady:d.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function S(d){let h=he.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(h).find(T=>d===void 0||T.dataset.targetInstructionId===d)}function _(d,h){let T=c.activeElement?.closest("textarea[data-target-instruction-id]"),$=T?.dataset.targetInstructionId,le=T?.selectionStart,ke=T?.selectionEnd;ce=d.map(ie=>Object.freeze({...ie})),ze=h,he.replaceChildren();let je=d.filter(ie=>ie.instruction.trim().length>0).length,de=d.reduce((ie,V)=>ie+V.instruction.trim().length,0);me.textContent=r.targets.count(d.length,h),ne.textContent=r.targets.complete(je,d.length);let Pe=de>4e3;W.dataset.state=Pe?"over":"ready",W.textContent=Pe?r.targets.instructionBudgetExceeded(de,4e3):r.targets.instructionBudget(de,4e3),Q.disabled=!ee||d.length>=h,Q.title=d.length>=h?r.targets.limitTitle(h):r.targets.addTitle,ge.textContent=d.length===1?d[0]?.label??r.context.selectedElement:r.context.selectedCount(d.length);for(let[ie,V]of d.entries()){let Ve=l(e,"div");Ve.className="spotpatch-target-item",Ve.dataset.active=String(V.active),Ve.dataset.status=V.status,Ve.dataset.targetId=V.id;let mt=l(e,"div");mt.className="spotpatch-target-summary";let Xe=G(e,"","spotpatch-target-select");Xe.dataset.activateTargetId=V.id,Xe.setAttribute("aria-label",r.targets.activate(ie+1)),Xe.setAttribute("aria-expanded",String(V.active));let ht=l(e,"span");ht.className="spotpatch-target-index",ht.textContent=String(ie+1);let bt=l(e,"span");bt.className="spotpatch-target-copy";let yt=l(e,"span");yt.className="spotpatch-target-name",yt.textContent=V.label;let xt=l(e,"span");xt.className="spotpatch-target-source",xt.textContent=`${p(V)} · ${V.source}`,bt.append(yt,xt);let Jt=V.instruction.trim().length>0,it=l(e,"span");it.className="spotpatch-target-state",it.dataset.complete=String(Jt),it.textContent=Jt?r.targets.instructionReady:r.targets.instructionMissing,Xe.append(ht,bt,it);let Ze=G(e,"↗","spotpatch-target-open");Ze.dataset.openTargetId=V.id,Ze.disabled=!V.canOpenEditor,Ze.setAttribute("aria-label",r.actions.openTarget(ie+1)),Ze.title=r.actions.openTarget(ie+1);let Qe=G(e,"×","spotpatch-target-remove");if(Qe.dataset.removeTargetId=V.id,Qe.disabled=!ee,Qe.setAttribute("aria-label",r.targets.remove(ie+1)),Qe.title=r.targets.removeTitle,mt.append(Xe,Ze,Qe),Ve.append(mt),V.active){let St=l(e,"label");St.className="spotpatch-target-editor";let At=l(e,"span");At.className="spotpatch-target-editor-head";let Et=l(e,"span");Et.className="spotpatch-target-editor-label",Et.textContent=r.targets.instructionLabel(V.label);let vt=l(e,"span");vt.className="spotpatch-target-editor-count",vt.textContent=r.targets.instructionCount(V.instruction.length,2e3),At.append(Et,vt);let Ue=l(e,"textarea");Ue.rows=4,Ue.maxLength=2e3,Ue.value=V.instruction,Ue.placeholder=r.targets.instructionPlaceholder,Ue.disabled=!ee,Ue.dataset.targetInstructionId=V.id,Ue.setAttribute("aria-label",r.targets.instructionLabel(V.label)),St.append(At,Ue),Ve.append(St)}he.append(Ve)}if($!==void 0){let ie=S($);ie?.focus({preventScroll:!0}),le!==void 0&&ke!==void 0&&ie?.setSelectionRange(le,ke)}}function B(d,h){ce=ce.map(Pe=>Pe.id===d?Object.freeze({...Pe,instruction:h}):Pe);let T=Array.from(he.querySelectorAll(".spotpatch-target-item")).find(Pe=>Pe.dataset.targetId===d);if(T===void 0)return;let $=h.trim().length>0,le=T.querySelector(".spotpatch-target-state"),ke=T.querySelector(".spotpatch-target-editor-count");le!==null&&(le.dataset.complete=String($),le.textContent=$?r.targets.instructionReady:r.targets.instructionMissing),ke!==null&&(ke.textContent=r.targets.instructionCount(h.length,2e3)),ne.textContent=r.targets.complete(ce.filter(Pe=>Pe.instruction.trim().length>0).length,ce.length);let je=ce.reduce((Pe,ie)=>Pe+ie.instruction.trim().length,0),de=je>4e3;W.dataset.state=de?"over":"ready",W.textContent=de?r.targets.instructionBudgetExceeded(je,4e3):r.targets.instructionBudget(je,4e3)}function xe(d){P.replaceChildren(),De=d.find(h=>h.active)?.rect,Oe=De;for(let[h,T]of d.entries()){let $=l(e,"div");$.className="spotpatch-selection-highlight",$.dataset.targetId=T.id,$.dataset.active=String(T.active),$.style.transform=`translate(${String(T.rect.x)}px, ${String(T.rect.y)}px)`,$.style.width=`${String(T.rect.width)}px`,$.style.height=`${String(T.rect.height)}px`;let le=l(e,"span");le.textContent=`${String(h+1)} · ${T.label}`,$.append(le),P.append($)}K()}function K(){if(m.hidden||Oe===void 0)return;let d=e.defaultView,h=d?.innerWidth??e.documentElement.clientWidth,T=d?.innerHeight??e.documentElement.clientHeight,$=m.getBoundingClientRect(),le=f==="previewing"?"previewing":"selected",ke=$.width>0?$.width:Math.min(wr,h-32),je=$.height>0?$.height:Math.min(Or[le],T-32),de=Mn({target:Oe,dialogWidth:ke,dialogHeight:je,viewportWidth:h,viewportHeight:T});m.style.left=`${String(de.left)}px`,m.style.top=`${String(de.top)}px`,m.style.setProperty("--spotpatch-anchor-x",`${String(de.anchorX)}px`),m.style.setProperty("--spotpatch-anchor-y",`${String(de.anchorY)}px`),m.dataset.placement=de.mode}function jt(d){let h=r.summary,T=Lr(d,h.source);oe.textContent=T??r.diagnostics.noExactSource;let $=`${h.browserContext}: ${h.collectionStatuses.ready}`,le=`${h.browserContext}: ${h.collectionStatuses.loading}`,ke=`${h.browserContext}: ${h.collectionStatuses.failed}`,je=`${h.api}: ${h.apiStatuses.loading}`,de=`${h.api}: ${h.apiStatuses.failed}`;d.includes($)&&!d.includes(le)&&!d.includes(je)&&!d.includes(ke)&&!d.includes(de)?(D.dataset.state="ready",D.textContent=r.context.ready):d.includes(ke)||d.includes(de)?(D.dataset.state="warning",D.textContent=r.context.partial):(D.dataset.state="loading",D.textContent=r.context.collecting)}function Bt(d,h,T){z=h,X=T,j=d,L.textContent=d,re.disabled=!h,q.disabled=!T,w.setContextReady(T),jt(d),K()}function Ut(d){f=d;let h=d==="selected",T=d==="previewing";y.hidden=h||T,ae.hidden=!h,Te.hidden=!T,Ee.hidden=!h,Q.hidden=!h,re.hidden=!h,q.hidden=!h,w.setSelectionVisible(h),ye.hidden=!T,Y.hidden=!T,F.textContent=T?r.dialog.previewTitle:r.dialog.editTitle,I.textContent=T?r.dialog.previewSubtitle:r.dialog.editSubtitle,K()}function Ht(){r=a.messages(),g.textContent=r.brand.name,x.textContent=r.brand.context,R.textContent=r.brand.repository,R.title=r.brand.repositoryTitle,R.setAttribute("aria-label",r.brand.repositoryTitle),H.textContent=r.alternateLocaleName,H.title=r.switchLocale,H.setAttribute("aria-label",r.switchLocale),ue.setAttribute("aria-label",r.dialog.close),ue.title=r.dialog.close,U.setAttribute("aria-label",r.targets.ariaLabel),Ne.textContent=r.targets.title,Ae.textContent=r.diagnostics.title,be.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Q.textContent=r.actions.addElement,Ee.textContent=r.actions.reselect,re.textContent=r.actions.openEditor,q.textContent=r.actions.preview,ye.textContent=r.actions.copy,Y.textContent=r.actions.back,y.title=r.trigger.title(t),y.textContent=f==="inspecting"?r.trigger.stop:r.trigger.select,Ut(f),s(rt),ce.length>0?_(ce,ze):(me.textContent=r.targets.count(0,ze),ne.textContent=r.targets.complete(0,0),W.dataset.state="ready",W.textContent=r.targets.instructionBudget(0,4e3),ge.textContent=r.context.selectedElement),j.length>0?jt(j):(oe.textContent=r.diagnostics.resolving,D.textContent=r.context.collecting)}Re.addEventListener("toggle",K),H.addEventListener("click",a.toggle);let qn=a.subscribe(Ht);return Ht(),Object.freeze({host:i,triggerButton:y,addTargetButton:Q,targetList:he,reselectButton:Ee,openEditorButton:re,repositoryLink:R,previewButton:q,copyButton:ye,backButton:Y,closeButton:ue,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(d){let h=d==="inspecting";y.setAttribute("aria-pressed",String(h)),y.textContent=h?r.trigger.stop:r.trigger.select,Ut(d)},renderEditorStatus:s,showHighlight(d,h){Oe=d,E.hidden=!1,E.style.transform=`translate(${String(d.x)}px, ${String(d.y)}px)`,E.style.width=`${String(d.width)}px`,E.style.height=`${String(d.height)}px`,u.textContent=h,ge.textContent=h,K()},hideHighlight(){Oe=De,E.hidden=!0,u.textContent="",K()},showSelectionHighlights:xe,hideSelectionHighlights(){P.replaceChildren(),De=void 0,Oe=void 0},showSelection(d,h,T){Bt(d,h,T),y.hidden=!0,m.hidden=!1,K()},updateSelection:Bt,renderTargets:_,updateTargetInstruction:B,setPreviewEnabled(d){X=d,q.disabled=!d,w.setContextReady(d)},hideSelection(){m.hidden=!0,y.hidden=!1,he.replaceChildren(),ce=[],ze=0,j="",s("idle"),me.textContent=r.targets.count(0,0),ne.textContent=r.targets.complete(0,0),ge.textContent=r.context.selectedElement,L.textContent="",be.textContent="",oe.textContent=r.diagnostics.resolving,D.dataset.state="loading",D.textContent=r.context.collecting,re.disabled=!0,q.disabled=!0,z=!1,X=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){m.hidden=!0,y.hidden=!1},showPreview(d){be.textContent=d,K()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(d){w.setProviderConsent(d)},setAgentEditingEnabled(d){ee=d,Q.disabled=!d,Ee.disabled=!d,he.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(h=>{h.disabled=!d}),re.disabled=!z,q.disabled=!d||!X,w.setEditingEnabled(d),K()},renderAgentCapability(d,h,T,$){w.renderCapability(d,h,T,$);let le=d==="ready"&&T?.state==="agent-ready";q.classList.toggle("spotpatch-primary",!le),K()},renderAgentJob(d,h,T,$){w.renderJob(d,h,T,$),K()},resetAgentJob(){w.resetJob(),K()},focusTargetInstruction(d){S(d)?.focus({preventScroll:!0})},focusPrompt(){be.focus({preventScroll:!0})},announce(d){we.textContent="",we.textContent=d},locale:a.locale,messages:a.messages,subscribeLocale:a.subscribe,dispose(){Re.removeEventListener("toggle",K),H.removeEventListener("click",a.toggle),qn(),w.dispose(),i.remove()}})}function Ir(e,t,o){let n=t?.relativePath??e.source.relativePath,a=e.source.line,r=e.source.column;return n!==void 0&&a!==void 0?`${n}:${String(a)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:a!==void 0?o.lineLocation(a,r):o.unavailable}function jn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`Vite: ${e.viteVersion}`,`${t.source}: ${Ir(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(`
806
+ `)}function Bn(e,t){return`${e}:${t}`}function _r(e){if(e.type==="tool")return Object.freeze({key:`tool:${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 Un(e){let t=g=>nn(g)??b.INTERNAL_ERROR,o=g=>e.view.messages().errors[t(g)],n=new Map,a=new Set,r=new Map,i=0,c,y,E=!1,u=!1,P=()=>e.view.readAgentSelection(),m=g=>{c!==void 0&&e.view.renderAgentJob(c,y,Object.freeze([...r.values()]),g??c.errorCode)},k=()=>{let g=P();if(g===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(a.has(g.providerProfileId));let x=n.get(Bn(g.providerProfileId,g.modelProfileId));x===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,x)},A=async g=>{let x=P();if(x===void 0)throw new Error("Agent provider selection is unavailable.");let C=Bn(x.providerProfileId,x.modelProfileId),R=n.get(C);if(R!==void 0)return R;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let H=await e.api.agentCapability(x);if(g!==i)return H;if(H.state!=="agent-ready")throw new N(H.errorCode??b.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(C,H),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,H),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),H},v=async(g,x)=>{try{let C=await e.api.agentResult(g);if(x!==i||C.snapshot.jobId!==g)return;c=C.snapshot,y=C.result,m()}catch(C){x===i&&m(t(C))}},M=async(g,x)=>{try{await e.api.agentEvents(g,C=>{if(x!==i||C.jobId!==g)return;C.type==="snapshot"&&(c=C.data.snapshot,c.status==="applied"&&!E&&(E=!0,e.onApplied()));let R=_r(C);R!==void 0&&r.set(R.key,R),m()}),x===i&&await v(g,x)}catch(C){x===i&&!(C instanceof DOMException&&C.name==="AbortError")&&m(t(C))}},O=async g=>{let x=c;if(x===void 0||u)return;u=!0;let C=i;c=Object.freeze({...x,status:g==="apply"?"applying":g==="cancel"?"cancelling":"reverting",phaseMessage:g==="apply"?e.view.messages().agent.applying:g==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),m();try{let R=g==="apply"?await e.api.applyAgentJob(x.jobId):g==="cancel"?await e.api.cancelAgentJob(x.jobId):await e.api.revertAgentJob(x.jobId);if(C!==i)return;c=R,R.status==="applied"&&!E&&(E=!0,e.onApplied()),await v(R.jobId,C)}catch(R){if(C!==i)return;c=x,await v(x.jobId,C),m(t(R)),e.view.announce(o(R))}finally{C===i&&(u=!1)}},Z=()=>{i+=1,c=void 0,y=void 0,r.clear(),E=!1,u=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),k()};return Object.freeze({apply(){c?.canApply===!0&&O("apply")},beginSelection(){Z()},cancel(){c?.canCancel===!0&&O("cancel")},consentChanged(){let g=P();g!==void 0&&(e.view.agentConsentGranted()?a.add(g.providerProfileId):a.delete(g.providerProfileId))},disposeSelection(){let g=c?.canCancel===!0||c?.status==="cancelling"?c.jobId:void 0;i+=1,c=void 0,y=void 0,r.clear(),E=!1,u=!1,g!==void 0&&e.api.cancelAgentJob(g).catch(()=>{})},providerOrModelChanged(){i+=1,k()},reset(){let g=E;Z(),g&&e.onReselectRequired()},revert(){c?.canRevert===!0&&O("revert")},run(){if(!e.ai.enabled||c!==void 0)return;let g=P(),x=e.getAnnotation();if(g===void 0||x===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}a.add(g.providerProfileId);let C=++i;e.view.setAgentEditingEnabled(!1),A(C).then(async()=>{if(C!==i)return;let R=await e.api.createAgentJob({annotation:x,providerProfileId:g.providerProfileId,modelProfileId:g.modelProfileId,providerDataConsent:!0});C===i&&(c=R,y=void 0,r.clear(),m(),M(R.jobId,C))}).catch(R=>{C===i&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(R),void 0,t(R)),e.view.announce(o(R)))})},testCapability(){if(!e.ai.enabled||c!==void 0)return;let g=++i;A(g).catch(x=>{g===i&&(e.view.renderAgentCapability("error",o(x),void 0,t(x)),e.view.announce(o(x)))})}})}function Hn(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 Jn(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 Vn(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var kr=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Dt(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 Mr(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,a=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${a===void 0?"":`:${String(a)}`}`}function $r(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Dr(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 Gn(e,t={}){let o=Dr(t),n=t.view??zn(o.document,e.shortcut,e.ai,e.locale),a=t.api??on({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??Cn({maxCharacters:e.budget.totalCharacters}),i=t.clipboard??Vn(o.window.navigator),c=t.createId??(()=>Hn(o.window)),y=t.now??(()=>new Date().toISOString()),E=Ln({adapter:t.reactAdapter??Nr({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=$t,P=!1,m,k,A=[],v,M=0,O=0,Z=0,g=!1,x="",C,R,H,ue,F=new Map;function I(s){u=Rn(u,s),n.renderStatus(u.status)}function Ce(){return A.find(s=>s.id===v)??A.at(-1)}function ge(s,p){return P&&p===O&&u.status!=="idle"&&A.includes(s)}function D(){let s=A.reduce((p,S)=>p+S.instruction.trim().length,0);return A.length>0&&s<=4e3&&A.every(p=>p.instruction.trim().length>0&&p.element!==void 0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function Le(){let s=n.messages().summary;return A.map((p,S)=>{let _=jn({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,spotPatchVersion:e.spotPatchVersion,viteVersion:e.viteVersion},s);return`${s.target(S+1,p.id===v)}
807
+ ${_}`}).join(`
838
808
 
839
- `)}function ge(){let s=S.flatMap(u=>u.element?.isConnected?[{id:u.id,label:Ut(u.element),rect:Dt(u.element,o.window),active:u.id===A}]:[]);s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function U(s=!1){if(S.length===0)return;n.renderTargets(S.map(z=>({id:z.id,label:z.resolution.react.componentName??(z.element===void 0?z.elementContext?.tagName??"Element":Ut(z.element)),source:Br(z,n.messages().context.sourceUnavailable),canOpenEditor:z.marker!==void 0,status:Ur(z),active:z.id===A,instruction:z.instruction})),e.maxTargets),ge();let u=ve(),y=J(),N=u?.marker!==void 0;s?n.showSelection(y,N,Z()):n.updateSelection(y,N,Z())}function se(){if(!Z())return;let s=S.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let y=[...u.apiStatus==="failed"?["Source context could not be loaded."]:[],...u.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:u.instruction.trim(),source:u.resolution.source,react:u.resolution.react,element:u.elementContext,styles:u.styles,...u.code===void 0?{}:{code:u.code},warnings:y}});return Wt({id:c(),locale:n.locale(),createdAt:C(),page:qn(o.document,o.window),targets:s})}function Le(s){n.showHighlight(Dt(s,o.window),Ut(s))}function ke(){v?.isConnected===!0&&v.focus({preventScroll:!0}),v=void 0}function xe(){for(let s of F.values())o.window.clearTimeout(s);F.clear()}function ce(){w+=1,i.cancelPending(),L.disposeSelection(),xe(),O?.disconnect(),S=[],A=void 0,g=!1,b="",n.hideSelection(),n.hideSelectionHighlights(),ke()}function W(){p.status==="inspecting"?_({type:"CANCEL"}):p.status==="selected"?_({type:"CLOSE"}):p.status==="previewing"&&(_({type:"BACK"}),_({type:"CLOSE"})),ce(),n.hideHighlight()}function Me(){if(p.status!=="inspecting"||!g||S.length===0){W();return}g=!1,_({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(A),n.announce(n.messages().announcements.addCancelled)}function re(){if(p.status==="inspecting"&&g){Me();return}if(p.status!=="idle"){W();return}_({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Ce(s=n.messages().announcements.chooseAnother){p.status==="selected"&&(_({type:"RESELECT"}),ce(),n.hideHighlight(),n.announce(s))}function Se(){if(p.status==="selected"){if(S.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}g=!0,_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(S.length,e.maxTargets))}}function Re(){w+=1,xe(),O?.disconnect();for(let s of S)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),U(),n.announce(n.messages().announcements.appliedTargetsDetached)}let L=Gn({ai:e.ai,api:i,getAnnotation:se,onApplied:Re,onReselectRequired(){Ce(n.messages().announcements.reselectAfterChange)},view:n});async function Te(s,u){let y=s.marker;if(y!==void 0)try{let N=await i.sourceContext({fileId:y.fileId,line:y.line,column:y.column,maxLines:e.budget.maxCodeLines});Oe(s,u)&&(s.code=N,s.apiStatus="connected",U(),n.announce(n.messages().announcements.sourceLoaded))}catch(N){Oe(s,u)&&(s.code=void 0,s.apiStatus="failed",U(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(N instanceof DOMException&&N.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function P(s,u){let y=s.element;if(y===void 0)return;let N=o.window.setTimeout(()=>{if(F.delete(s.id),!Oe(s,u))return;let z=!1;try{s.elementContext=xn({element:y,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,z=!0}try{s.styles=gn({document:o.document,element:y,maxCharacters:e.budget.cssCharacters})}catch{s.styles=jr,z=!0}s.collectionStatus=z?"failed":"ready",U(),n.announce(z?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&s.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(s.styles.warnings.length)} warning(s).`)},0);F.set(s.id,N)}function Ie(s,u){return u!==void 0?S.find(y=>y.marker?.fileId===u.fileId&&y.marker.line===u.line&&y.marker.column===u.column):S.find(y=>y.element===s)}function fe(s){let u=x.resolve(s),y=Nn(u.source),N=Ie(s,y);if(N!==void 0){A=N.id,g=!1,_({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(N.id),n.announce(n.messages().announcements.duplicate);return}if(S.length>=e.maxTargets){g=!1,_({type:"SELECT"}),n.hideHighlight(),U(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}S.length===0&&(v=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,b="",L.beginSelection()),M+=1;let ie={id:`target-${String(M)}`,element:s,resolution:u,marker:y,code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:y===void 0?"not-required":"loading",collectionStatus:"loading"};S.push(ie),A=ie.id,g=!1;let Ee=w;_({type:"SELECT"}),n.hideHighlight(),O?.observe(s),U(!0),n.focusTargetInstruction(ie.id),P(ie,Ee),y!==void 0?Te(ie,Ee):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Be(){if(E=void 0,p.status!=="inspecting"||R===void 0)return;let s=zt(o.document,o.window,R.x,R.y);if(_({type:"HOVER"}),s===void 0){n.hideHighlight();return}Le(s)}function q(s){p.status==="inspecting"&&(R={x:s.clientX,y:s.clientY},E??=o.window.requestAnimationFrame(Be))}function de(s){if(p.status!=="inspecting"||Cn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let u=zt(o.document,o.window,s.clientX,s.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}fe(u)}function me(s){if(s.key==="Escape"&&p.status!=="idle"){s.preventDefault(),p.status==="inspecting"&&g?Me():p.status==="inspecting"||p.status==="selected"?W():(_({type:"BACK"}),n.focusTargetInstruction(A));return}En(s.target)||!An(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),re())}function Q(s){if(p.status!=="selected"&&p.status!=="inspecting")return;let u=S.findIndex(z=>z.id===s);if(u<0)return;let[y]=S.splice(u,1);if(y===void 0)return;let N=F.get(y.id);if(N!==void 0&&(o.window.clearTimeout(N),F.delete(y.id)),y.element!==void 0&&O?.unobserve(y.element),A===y.id&&(A=S.at(-1)?.id),S.length===0){g=!0,p.status==="selected"&&_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),n.announce(n.messages().announcements.allTargetsRemoved);return}U(),n.announce(n.messages().announcements.targetRemoved)}function K(){if(p.status==="idle"||S.length===0)return;let s=S.filter(u=>u.element!==void 0&&!u.element.isConnected);if(s.length>0){p.status==="previewing"&&_({type:"BACK"});for(let u of s)Q(u.id);S.length>0&&n.announce(n.messages().announcements.detachedTargetRemoved);return}ge()}function Y(s){let u=s===void 0?ve():S.find(Ee=>Ee.id===s);if(p.status!=="selected"||u?.marker===void 0)return;A!==u.id&&(A=u.id,U());let y=u.marker,N=w,z=++X;_({type:"OPEN_EDITOR"});let ie=n.messages().announcements.editorOpening(e.editor);n.renderEditorStatus("opening",ie),n.announce(ie),i.openEditor({fileId:y.fileId,line:y.line,column:y.column}).then(Ee=>{if(I&&p.status==="selected"&&N===w&&z===X&&A===u.id&&S.includes(u)){let st=n.messages().announcements.editorOpened(Ee.editor);n.renderEditorStatus("success",st),n.announce(st)}}).catch(()=>{if(I&&p.status==="selected"&&N===w&&z===X&&A===u.id&&S.includes(u)){let Ee=n.messages().announcements.editorFailed(e.editor);n.renderEditorStatus("error",Ee),n.announce(Ee)}})}function $e(s){if(p.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let u=s.target.dataset.targetInstructionId,y=S.find(N=>N.id===u);y!==void 0&&(y.instruction=s.target.value,n.updateTargetInstruction(y.id,y.instruction),n.setPreviewEnabled(Z()))}function we(){Y()}function _e(s){e.ai.enabled&&p.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),L.run())}function f(){if(p.status!=="selected")return;let s=se();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}b=a.compose(s),_({type:"PREVIEW"}),n.showPreview(b),n.focusPrompt()}function D(){if(p.status!=="previewing"||b.length===0)return;if(r===void 0){_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=w;r.writeText(b).then(()=>{I&&s===w&&p.status==="previewing"&&(_({type:"COPY_SUCCESS"}),n.focusTargetInstruction(A),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{I&&s===w&&p.status==="previewing"&&(_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function ee(){p.status==="previewing"&&(_({type:"BACK"}),n.focusTargetInstruction(A))}function B(){if(!(!I||S.length===0)&&(U(),p.status==="previewing")){let s=se();s!==void 0&&(b=a.compose(s),n.showPreview(b))}}function te(s){let u=s.target;if(!(u instanceof Element))return;let y=u.closest("button[data-remove-target-id]");if(y?.dataset.removeTargetId!==void 0){Q(y.dataset.removeTargetId);return}let N=u.closest("button[data-open-target-id]");if(N?.dataset.openTargetId!==void 0){Y(N.dataset.openTargetId);return}let ie=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;p.status!=="selected"||ie===void 0||!S.some(Ee=>Ee.id===ie)||(A=ie,U(),n.focusTargetInstruction(ie))}function De(){Ce()}function he(){I||(I=!0,n.renderStatus(p.status),o.document.addEventListener("pointermove",q,!0),o.document.addEventListener("click",de,!0),o.document.addEventListener("keydown",me,!0),o.window.addEventListener("scroll",K,!0),o.window.addEventListener("resize",K),n.triggerButton.addEventListener("click",re),n.addTargetButton.addEventListener("click",Se),n.reselectButton.addEventListener("click",De),n.targetList.addEventListener("click",te),n.targetList.addEventListener("input",$e),n.targetList.addEventListener("keydown",_e),n.openEditorButton.addEventListener("click",we),n.previewButton.addEventListener("click",f),n.copyButton.addEventListener("click",D),n.backButton.addEventListener("click",ee),n.closeButton.addEventListener("click",W),n.agentProviderSelect.addEventListener("change",L.providerOrModelChanged),n.agentModelSelect.addEventListener("change",L.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",L.consentChanged),n.agentTestButton.addEventListener("click",L.testCapability),n.agentRunButton.addEventListener("click",L.run),n.agentCancelButton.addEventListener("click",L.cancel),n.agentApplyButton.addEventListener("click",L.apply),n.agentRevertButton.addEventListener("click",L.revert),n.agentResetButton.addEventListener("click",L.reset),oe=n.subscribeLocale(B),o.resizeObserver!==void 0&&(O=new o.resizeObserver(K)),o.mutationObserver!==void 0&&($=new o.mutationObserver(K),$.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function Ze(){if(!I){oe?.(),oe=void 0,n.dispose(),i.cancelPending(),i.dispose(),L.disposeSelection(),x.dispose();return}I=!1,oe?.(),oe=void 0,o.document.removeEventListener("pointermove",q,!0),o.document.removeEventListener("click",de,!0),o.document.removeEventListener("keydown",me,!0),o.window.removeEventListener("scroll",K,!0),o.window.removeEventListener("resize",K),n.triggerButton.removeEventListener("click",re),n.addTargetButton.removeEventListener("click",Se),n.reselectButton.removeEventListener("click",De),n.targetList.removeEventListener("click",te),n.targetList.removeEventListener("input",$e),n.targetList.removeEventListener("keydown",_e),n.openEditorButton.removeEventListener("click",we),n.previewButton.removeEventListener("click",f),n.copyButton.removeEventListener("click",D),n.backButton.removeEventListener("click",ee),n.closeButton.removeEventListener("click",W),n.agentProviderSelect.removeEventListener("change",L.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",L.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",L.consentChanged),n.agentTestButton.removeEventListener("click",L.testCapability),n.agentRunButton.removeEventListener("click",L.run),n.agentCancelButton.removeEventListener("click",L.cancel),n.agentApplyButton.removeEventListener("click",L.apply),n.agentRevertButton.removeEventListener("click",L.revert),n.agentResetButton.removeEventListener("click",L.reset),E!==void 0&&(o.window.cancelAnimationFrame(E),E=void 0),xe(),O?.disconnect(),$?.disconnect(),O=void 0,$=void 0,S=[],A=void 0,b="",R=void 0,v=void 0,i.cancelPending(),i.dispose(),L.disposeSelection(),x.dispose(),n.dispose(),p=Bt}return Object.freeze({mount:he,dispose:Ze,getState:()=>p})}var Yn="__spotpatchRuntime__";function Ht(e){let t=globalThis;t[Yn]?.dispose();let o=Wn(e);t[Yn]=o,o.mount()}Ht({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Ke});
809
+ `)}function ae(){let s=A.flatMap(p=>p.element?.isConnected?[{id:p.id,label:Dt(p.element),rect:Nt(p.element,o.window),active:p.id===v}]:[]);s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function U(s=!1){if(A.length===0)return;n.renderTargets(A.map(B=>({id:B.id,label:B.resolution.react.componentName??(B.element===void 0?B.elementContext?.tagName??"Element":Dt(B.element)),source:Mr(B,n.messages().context.sourceUnavailable),canOpenEditor:B.marker!==void 0,status:$r(B),active:B.id===v,instruction:B.instruction})),e.maxTargets),ae();let p=Ce(),S=Le(),_=p?.marker!==void 0;s?n.showSelection(S,_,D()):n.updateSelection(S,_,D())}function fe(){if(!D())return;let s=A.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let S=[...p.apiStatus==="failed"?["Source context could not be loaded."]:[],...p.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:p.instruction.trim(),source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:S}});return Gt({id:c(),locale:n.locale(),createdAt:y(),page:Jn(o.document,o.window),targets:s})}function Ne(s){n.showHighlight(Nt(s,o.window),Dt(s))}function Ie(){C?.isConnected===!0&&C.focus({preventScroll:!0}),C=void 0}function ne(){for(let s of F.values())o.window.clearTimeout(s);F.clear()}function W(){O+=1,a.cancelPending(),L.disposeSelection(),ne(),R?.disconnect(),A=[],v=void 0,g=!1,x="",n.hideSelection(),n.hideSelectionHighlights(),Ie()}function me(){u.status==="inspecting"?I({type:"CANCEL"}):u.status==="selected"?I({type:"CLOSE"}):u.status==="previewing"&&(I({type:"BACK"}),I({type:"CLOSE"})),W(),n.hideHighlight()}function he(){if(u.status!=="inspecting"||!g||A.length===0){me();return}g=!1,I({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(v),n.announce(n.messages().announcements.addCancelled)}function Re(){if(u.status==="inspecting"&&g){he();return}if(u.status!=="idle"){me();return}I({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Me(s=n.messages().announcements.chooseAnother){u.status==="selected"&&(I({type:"RESELECT"}),W(),n.hideHighlight(),n.announce(s))}function Ae(){if(u.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}g=!0,I({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function oe(){O+=1,ne(),R?.disconnect();for(let s of A)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),U(),n.announce(n.messages().announcements.appliedTargetsDetached)}let L=Un({ai:e.ai,api:a,getAnnotation:fe,onApplied:oe,onReselectRequired(){Me(n.messages().announcements.reselectAfterChange)},view:n});async function w(s,p){let S=s.marker;if(S!==void 0)try{let _=await a.sourceContext({fileId:S.fileId,line:S.line,column:S.column,maxLines:e.budget.maxCodeLines});ge(s,p)&&(s.code=_,s.apiStatus="connected",U(),n.announce(n.messages().announcements.sourceLoaded))}catch(_){ge(s,p)&&(s.code=void 0,s.apiStatus="failed",U(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(_ instanceof DOMException&&_.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Te(s,p){let S=s.element;if(S===void 0)return;let _=o.window.setTimeout(()=>{if(F.delete(s.id),!ge(s,p))return;let B=!1;try{s.elementContext=mn({element:S,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,B=!0}try{s.styles=ln({document:o.document,element:S,maxCharacters:e.budget.cssCharacters})}catch{s.styles=kr,B=!0}s.collectionStatus=B?"failed":"ready",U(),n.announce(B?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&s.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(s.styles.warnings.length)} warning(s).`)},0);F.set(s.id,_)}function be(s,p){return p!==void 0?A.find(S=>S.marker?.fileId===p.fileId&&S.marker.line===p.line&&S.marker.column===p.column):A.find(S=>S.element===s)}function $e(s){let p=E.resolve(s),S=Pn(p.source),_=be(s,S);if(_!==void 0){v=_.id,g=!1,I({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(_.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){g=!1,I({type:"SELECT"}),n.hideHighlight(),U(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}A.length===0&&(C=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,x="",L.beginSelection()),M+=1;let xe={id:`target-${String(M)}`,element:s,resolution:p,marker:S,code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:S===void 0?"not-required":"loading",collectionStatus:"loading"};A.push(xe),v=xe.id,g=!1;let K=O;I({type:"SELECT"}),n.hideHighlight(),R?.observe(s),U(!0),n.focusTargetInstruction(xe.id),Te(xe,K),S!==void 0?w(xe,K):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function se(){if(m=void 0,u.status!=="inspecting"||k===void 0)return;let s=kt(o.document,o.window,k.x,k.y);if(I({type:"HOVER"}),s===void 0){n.hideHighlight();return}Ne(s)}function Q(s){u.status==="inspecting"&&(k={x:s.clientX,y:s.clientY},m??=o.window.requestAnimationFrame(se))}function Ee(s){if(u.status!=="inspecting"||Sn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let p=kt(o.document,o.window,s.clientX,s.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}$e(p)}function re(s){if(s.key==="Escape"&&u.status!=="idle"){s.preventDefault(),u.status==="inspecting"&&g?he():u.status==="inspecting"||u.status==="selected"?me():(I({type:"BACK"}),n.focusTargetInstruction(v));return}bn(s.target)||!yn(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),Re())}function q(s){if(u.status!=="selected"&&u.status!=="inspecting")return;let p=A.findIndex(B=>B.id===s);if(p<0)return;let[S]=A.splice(p,1);if(S===void 0)return;let _=F.get(S.id);if(_!==void 0&&(o.window.clearTimeout(_),F.delete(S.id)),S.element!==void 0&&R?.unobserve(S.element),v===S.id&&(v=A.at(-1)?.id),A.length===0){g=!0,u.status==="selected"&&I({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),n.announce(n.messages().announcements.allTargetsRemoved);return}U(),n.announce(n.messages().announcements.targetRemoved)}function ye(){if(u.status==="idle"||A.length===0)return;let s=A.filter(p=>p.element!==void 0&&!p.element.isConnected);if(s.length>0){u.status==="previewing"&&I({type:"BACK"});for(let p of s)q(p.id);A.length>0&&n.announce(n.messages().announcements.detachedTargetRemoved);return}ae()}function Y(s){let p=s===void 0?Ce():A.find(xe=>xe.id===s);if(u.status!=="selected"||p?.marker===void 0)return;v!==p.id&&(v=p.id,U());let S=p.marker,_=O,B=++Z;I({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),a.openEditor({fileId:S.fileId,line:S.line,column:S.column}).then(()=>{P&&u.status==="selected"&&_===O&&B===Z&&v===p.id&&A.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{P&&u.status==="selected"&&_===O&&B===Z&&v===p.id&&A.includes(p)&&n.renderEditorStatus("error")})}function we(s){if(u.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,S=A.find(_=>_.id===p);S!==void 0&&(S.instruction=s.target.value,n.updateTargetInstruction(S.id,S.instruction),n.setPreviewEnabled(D()))}function Oe(){Y()}function De(s){e.ai.enabled&&u.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),L.run())}function f(){if(u.status!=="selected")return;let s=fe();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}x=r.compose(s),I({type:"PREVIEW"}),n.showPreview(x),n.focusPrompt()}function z(){if(u.status!=="previewing"||x.length===0)return;if(i===void 0){I({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=O;i.writeText(x).then(()=>{P&&s===O&&u.status==="previewing"&&(I({type:"COPY_SUCCESS"}),n.focusTargetInstruction(v),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{P&&s===O&&u.status==="previewing"&&(I({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function X(){u.status==="previewing"&&(I({type:"BACK"}),n.focusTargetInstruction(v))}function j(){if(!(!P||A.length===0)&&(U(),u.status==="previewing")){let s=fe();s!==void 0&&(x=r.compose(s),n.showPreview(x))}}function ee(s){let p=s.target;if(!(p instanceof Element))return;let S=p.closest("button[data-remove-target-id]");if(S?.dataset.removeTargetId!==void 0){q(S.dataset.removeTargetId);return}let _=p.closest("button[data-open-target-id]");if(_?.dataset.openTargetId!==void 0){Y(_.dataset.openTargetId);return}let xe=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||xe===void 0||!A.some(K=>K.id===xe)||(v=xe,U(),n.focusTargetInstruction(xe))}function ce(){Me()}function ze(){P||(P=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Q,!0),o.document.addEventListener("click",Ee,!0),o.document.addEventListener("keydown",re,!0),o.window.addEventListener("scroll",ye,!0),o.window.addEventListener("resize",ye),n.triggerButton.addEventListener("click",Re),n.addTargetButton.addEventListener("click",Ae),n.reselectButton.addEventListener("click",ce),n.targetList.addEventListener("click",ee),n.targetList.addEventListener("input",we),n.targetList.addEventListener("keydown",De),n.openEditorButton.addEventListener("click",Oe),n.previewButton.addEventListener("click",f),n.copyButton.addEventListener("click",z),n.backButton.addEventListener("click",X),n.closeButton.addEventListener("click",me),n.agentProviderSelect.addEventListener("change",L.providerOrModelChanged),n.agentModelSelect.addEventListener("change",L.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",L.consentChanged),n.agentTestButton.addEventListener("click",L.testCapability),n.agentRunButton.addEventListener("click",L.run),n.agentCancelButton.addEventListener("click",L.cancel),n.agentApplyButton.addEventListener("click",L.apply),n.agentRevertButton.addEventListener("click",L.revert),n.agentResetButton.addEventListener("click",L.reset),ue=n.subscribeLocale(j),o.resizeObserver!==void 0&&(R=new o.resizeObserver(ye)),o.mutationObserver!==void 0&&(H=new o.mutationObserver(ye),H.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function rt(){if(!P){ue?.(),ue=void 0,n.dispose(),a.cancelPending(),a.dispose(),L.disposeSelection(),E.dispose();return}P=!1,ue?.(),ue=void 0,o.document.removeEventListener("pointermove",Q,!0),o.document.removeEventListener("click",Ee,!0),o.document.removeEventListener("keydown",re,!0),o.window.removeEventListener("scroll",ye,!0),o.window.removeEventListener("resize",ye),n.triggerButton.removeEventListener("click",Re),n.addTargetButton.removeEventListener("click",Ae),n.reselectButton.removeEventListener("click",ce),n.targetList.removeEventListener("click",ee),n.targetList.removeEventListener("input",we),n.targetList.removeEventListener("keydown",De),n.openEditorButton.removeEventListener("click",Oe),n.previewButton.removeEventListener("click",f),n.copyButton.removeEventListener("click",z),n.backButton.removeEventListener("click",X),n.closeButton.removeEventListener("click",me),n.agentProviderSelect.removeEventListener("change",L.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",L.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",L.consentChanged),n.agentTestButton.removeEventListener("click",L.testCapability),n.agentRunButton.removeEventListener("click",L.run),n.agentCancelButton.removeEventListener("click",L.cancel),n.agentApplyButton.removeEventListener("click",L.apply),n.agentRevertButton.removeEventListener("click",L.revert),n.agentResetButton.removeEventListener("click",L.reset),m!==void 0&&(o.window.cancelAnimationFrame(m),m=void 0),ne(),R?.disconnect(),H?.disconnect(),R=void 0,H=void 0,A=[],v=void 0,x="",k=void 0,C=void 0,a.cancelPending(),a.dispose(),L.disposeSelection(),E.dispose(),n.dispose(),u=$t}return Object.freeze({mount:ze,dispose:rt,getState:()=>u})}var Fn="__spotpatchRuntime__";function zt(e){let t=globalThis;t[Fn]?.dispose();let o=Gn(e);t[Fn]=o,o.mount()}zt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Fe});