@spotpatch/vite 1.1.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 wr}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 Hn=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Jn=/blob:[^\s"'<>]+/giu,Vn=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Gn=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Fn=/\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"]),Kn=500;function Wn(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Yn(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ot(e){let t=Wn(e);return qn.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function J(e){return e.replace(Hn,"[redacted inline data]").replace(Jn,"[redacted blob URL]").replace(Vn,"Bearer [redacted]").replace(Gn,"$1[redacted]@").replace(Fn,(t,o,n,a)=>{let r=a.at(0),i=r==='"'||r==="'"||r==="`";return`${o}${n}${i?r:""}[redacted]${i?r:""}`})}function Xn(e){e.username="",e.password="";for(let[t,o]of e.searchParams)ot(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 He(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=Xn(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 Yn(n,Kn)}}var Zn=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}),St=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),At=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Ct=Object.freeze(["added","modified","deleted"]),vt=Object.freeze(["passed","failed","cancelled","timed-out"]);var Et="data-spotpatch-source",Qn=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Rt(e){if(e===null)return;let t=Qn.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 Je="/__spotpatch/v1",rt="X-SpotPatch-Token",Ve=Object.freeze({sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentJobs:`${Je}/agent/jobs`});function Ge(e,t){return`${Ve.agentJobs}/${encodeURIComponent(e)}/${t}`}function zt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function to(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:zt(e.source)}})}function no(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function oo(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 ro(e){return Object.freeze({instruction:e.instruction.trim(),source:zt(e.source,e.code),react:to(e.react),element:no(e.element),styles:oo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function jt(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(ro)),createdAt:e.createdAt})}var io=new Set(Object.values(b)),ao=new Set(At),so=new Set(vt),co=new Set(Ct),Ut=new Set(St),lo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,po=/^[A-Za-z0-9_-]+$/,uo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(e,t){return Object.keys(e).every(o=>t.includes(o))}function ee(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function Xe(e){return ee(e,64,1)&&typeof e=="string"&&lo.test(e)}function Ot(e){return ee(e,128,22)&&typeof e=="string"&&po.test(e)}function it(e){return typeof e=="string"&&uo.test(e)&&Number.isFinite(Date.parse(e))}function wt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function go(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Bt(e,t){return e===void 0||ee(e,t)}function Ze(e){return typeof e=="string"&&io.has(e)}function Ht(e){return!je(e)||!ye(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:Xe(e.providerProfileId)&&ee(e.providerLabel,100)&&Xe(e.modelProfileId)&&ee(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&ao.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||it(e.checkedAt))&&(e.errorCode===void 0||Ze(e.errorCode))}function at(e){return!je(e)||!ye(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Ot(e.jobId)&&typeof e.status=="string"&&Ut.has(e.status)&&Xe(e.providerProfileId)&&ee(e.providerLabel,100)&&Xe(e.modelProfileId)&&ee(e.modelLabel,100)&&ee(e.phaseMessage,1024)&&it(e.createdAt)&&it(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Ze(e.errorCode))}function fo(e){return je(e)&&ye(e,["relativePath","kind","additions","deletions"])&&ee(e.relativePath,1024)&&typeof e.kind=="string"&&co.has(e.kind)&&wt(e.additions)&&wt(e.deletions)}function Jt(e){return je(e)&&ye(e,["checkId","label","status","durationMs","output"])&&Xe(e.checkId)&&ee(e.label,100)&&typeof e.status=="string"&&so.has(e.status)&&wt(e.durationMs)&&ee(e.output,8e4)}function mo(e){return je(e)&&ye(e,["jobId","summary","diff","files","checks"])&&Ot(e.jobId)&&ee(e.summary,8e4)&&ee(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(fo)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(Jt)}function Vt(e){return je(e)&&ye(e,["snapshot","result"])&&at(e.snapshot)&&(e.result===void 0||mo(e.result)&&e.result.jobId===e.snapshot.jobId)}function ho(e){return je(e)&&ye(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===1&&go(e.sequence)&&Ot(e.jobId)&&typeof e.status=="string"&&Ut.has(e.status)&&it(e.timestamp)&&typeof e.type=="string"&&je(e.data)}function Gt(e){if(!ho(e))return!1;let t=e.data;switch(e.type){case"snapshot":return ye(t,["snapshot"])&&at(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return ye(t,["message"])&&ee(t.message,1024);case"tool":return ye(t,["toolCallId","toolName","state","relativePath","checkLabel"])&&ee(t.toolCallId,256)&&ee(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&Bt(t.relativePath,1024)&&Bt(t.checkLabel,100);case"check":return ye(t,["result"])&&Jt(t.result);case"result-ready":return ye(t,["hasResult"])&&t.hasResult===!0;case"error":return ye(t,["code","message"])&&Ze(t.code)&&ee(t.message,1024);default:return!1}}var bo=2e6,Ft=1e5,yo=4e6,D=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 xo(e){if(!(!Qe(e)||e.ok!==!1||!Qe(e.error)))return Ze(e.error.code)?e.error.code:void 0}function So(e){if(!Qe(e)||e.ok!==!0||!("data"in e))throw new D;return e.data}function Ao(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 Kt(e){if(!(!Qe(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Kt(t);Object.freeze(e)}}function ct(e){return Kt(e),e}async function Co(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new D;if(e.body===null)throw new D;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 D;i+=a.decode(c.value,{stream:!0})}}catch(c){throw c instanceof D?c:new D}finally{n.releaseLock()}}function Wt(e){try{return JSON.parse(e)}catch{throw new D}}async function qt(e){let t=Wt(await Co(e,bo));if(!e.ok)throw new D(xo(t));return So(t)}function vo(e,t){if(!Ht(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new D;return ct(e)}function st(e,t){if(!at(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new D;return ct(e)}function Eo(e,t){if(!Vt(e)||e.snapshot.jobId!==t)throw new D;return ct(e)}function Ro(e){if(!Gt(e))throw new D;return ct(e)}function To(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 Yt(e){return e instanceof D?e.code:void 0}function Xt(e){let t=new Set;function o(){for(let i of t)i.abort();t.clear()}async function n(i,c,y){let S=new AbortController;t.add(S);try{let d=await e.fetch(i,{method:c,headers:{...y===void 0?{}:{"Content-Type":"application/json"},[rt]:e.sessionToken},...y===void 0?{}:{body:JSON.stringify(y)},signal:S.signal});return await qt(d)}finally{t.delete(S)}}async function a(i,c){let y=new AbortController;t.add(y);try{let S=await e.fetch(Ge(i,"events"),{method:"POST",headers:{"Content-Type":"application/json",[rt]:e.sessionToken},body:JSON.stringify({}),signal:y.signal});if(!S.ok){await qt(S);return}if(S.body===null)throw new D;let d=S.body.getReader(),w=new TextDecoder("utf-8",{fatal:!0}),m="",k=0,A=0,R=M=>{if(M.trim().length===0)return;if(new TextEncoder().encode(M).byteLength>Ft)throw new D;let I=Ro(Wt(M));if(I.jobId!==i||I.sequence<=A)throw new D;A=I.sequence,c(I)};try{for(;;){let M=await d.read();if(M.done){m+=w.decode(),R(m);return}if(k+=M.value.byteLength,k>yo)throw await d.cancel(),new D;m+=w.decode(M.value,{stream:!0});let I=m.split(`
2
- `);if(m=I.pop()??"",new TextEncoder().encode(m).byteLength>Ft)throw await d.cancel(),new D;for(let z of I)R(z)}}catch(M){throw M instanceof D||M instanceof DOMException&&M.name==="AbortError"?M:new D}finally{d.releaseLock()}}finally{t.delete(y)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(i){let c=await n(Ve.sourceContext,"POST",i);if(!Ao(c))throw new D;return Object.freeze({...c})},async openEditor(i){await n(Ve.openEditor,"POST",i)},async agentCapability(i){return vo(await n(Ve.agentCapability,"POST",i),i)},async createAgentJob(i){let c=To(i);return st(await n(Ve.agentJobs,"POST",c),i)},agentEvents:a,async agentResult(i){return Eo(await n(Ge(i,"result"),"POST",r),i)},async cancelAgentJob(i){return st(await n(Ge(i,"cancel"),"POST",r),{jobId:i})},async applyAgentJob(i){return st(await n(Ge(i,"apply"),"POST",r),{jobId:i})},async revertAgentJob(i){return st(await n(Ge(i,"revert"),"POST",r),{jobId:i})},dispose(){o()}})}var wo=500,Zt=256;function Oo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Po(e){return ot(e)}function Qt(e,t,o){if(!Po(e))return e==="href"||e==="src"?He(t,o):e==="d"&&t.length>Zt?`${t.slice(0,Zt)}…`:Oo(J(t),wo)}function ue(e){return J(e)}var en=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 et=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 Lo(e){return"selectorText"in e&&"style"in e}function Io(e){return"cssRules"in e}function _o(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 No(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 ko(e,t){return e.href===null?void 0:He(e.href,t)}function tn(e,t,o,n,a,r){for(let i of t){if(Lo(i)){let c=!1;try{c=e.matches(i.selectorText)}catch{r.add(et.selector);continue}c&&a.push(Object.freeze({selector:ue(i.selectorText),declarations:ue(i.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Io(i)){let c=_o(i);tn(e,i.cssRules,o,c===void 0?n:[...n,c],a,r)}}}function Mo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let a of en){let r=ue(o.getPropertyValue(a).trim());r.length>0&&(n[a]=r)}return n}function nn(e){let t=new Set([et.state,et.cssInJs,et.cascade]),o=[],n=e.readCssRules??(d=>d.cssRules);for(let d of e.document.styleSheets){let w;try{w=n(d)}catch{t.add(et.inaccessibleStylesheet);continue}tn(e.element,w,ko(d,e.document.baseURI),[],o,t)}let a=Array.from(e.element.classList),r=e.element.getAttribute("style"),i=r===null?void 0:ue(r),c=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),y=Object.entries(Mo(e.element,c)),S=Array.from(t);for(;No(a,i,o,Object.fromEntries(y),S)>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(S)})}var Be=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),$o=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"]),Do=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function rn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function zo(e){return $o.has(e)||e.startsWith("aria-")||e==="data-testid"}function an(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let a of e.attributes){let r=a.name.toLowerCase();if(!zo(r))continue;let i=Qt(r,a.value,n);i!==void 0&&o.push(`${r}="${rn(i)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function sn(e){return J(e).replaceAll(/\s+/gu," ").trim()}function cn(e,t,o,n){if(o.nodeCount>=Be.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let a=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${a}${an(e)}`),!Do.has(r)){for(let i of e.childNodes){if(o.nodeCount>=Be.maxNodes){o.truncated=!0;break}if(i.nodeType===3){let c=sn(i.textContent??"");if(c.length>0){o.nodeCount+=1;let y=c.length<=Be.maxTextCharacters?c:`${c.slice(0,Be.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${rn(y)}`)}continue}if(i.nodeType===1){if(t>=Be.maxDepth){o.truncated=!0;continue}cn(i,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${a}</${r}>`)}}function jo(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Be.maxParentDepth;)t.push(an(o)),o=o.parentElement;return t}function Bo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function on(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Uo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ho(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${on(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Uo(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(c=>`.${on(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 Jo(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Ho(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function ln(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};cn(e.element,0,o,t);let n=jo(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let a=sn(e.element.textContent),r=e.element.getBoundingClientRect(),i=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:Jo(e.element),sanitizedHtml:Bo(t.join(`
4
- `),e.maxCharacters),...a.length===0?{}:{textPreview:a.length<=Be.maxTextCharacters?a:`${a.slice(0,Be.maxTextCharacters)}…`},...i===null?{}:{role:i},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function dn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Vo(e){return e.toLowerCase()}function pn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function un(e,t,o){let n=t.split("+").map(d=>d.trim().toLowerCase()).filter(d=>d.length>0),a=n.find(d=>d!=="mod"&&d!=="meta"&&d!=="ctrl"&&d!=="control"&&d!=="alt"&&d!=="option"&&d!=="shift");if(a===void 0||Vo(e.key)!==a)return!1;let r=n.includes("mod"),i=n.includes("meta")||r&&dn(o),c=n.includes("ctrl")||n.includes("control")||r&&!dn(o),y=n.includes("alt")||n.includes("option"),S=n.includes("shift");return e.metaKey===i&&e.ctrlKey===c&&e.altKey===y&&e.shiftKey===S}function Go(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function Fo(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 Pt(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=Fo(Array.from(e.getClientRects()));if(n!==void 0)return n}return Go(e.getBoundingClientRect())}var Fe="data-spotpatch-ui",tt=Object.freeze({highlight:2147483646,controls:2147483647});function gn(e){if(e.closest(`[${Fe}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(Fe)}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 Ko(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Lt(e,t,o,n){let a=e.elementsFromPoint(o,n).filter(r=>!gn(r)&&qo(r,t));return a.find(r=>!Ko(r))??a[0]}function fn(e){return e instanceof Element&&gn(e)}var It=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 Wo(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function lt(e,t){let o="`".repeat(Math.max(3,Wo(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 hn(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 bn(e,t){return e.split(`
7
- `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Yo(e){let t=[e.source===void 0?void 0:`/* source: ${ue(e.source)} */`,e.media===void 0?void 0:`/* condition: ${ue(e.media)} */`].filter(n=>n!==void 0),o=`${ue(e.selector)} {
8
- ${ue(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 Xo(e,t,o){let a=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(ue).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${ue(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(Yo)];return a.length===0?o.unavailable:lt("css",a.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 Zo(e,t){return e.length===0?t.unavailable:lt("css",e.map(([o,n])=>`${ue(o)}: ${ue(n)};`).join(`
13
- `))}function Qo(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}
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
- ${lt(e.code.language,J(t.codeLines.join(`
15
+ ${gt(e.code.language,J(t.codeLines.join(`
16
16
  `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,a.join(`
17
- `),`#### ${n.source}`,`- ${n.file}: ${hn(e,n)}
17
+ `),`#### ${n.source}`,`- ${n.file}: ${En(e,n)}
18
18
  - ${n.origin}: ${e.source.origin}
19
- - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,lt("html",J(t.dom)),`#### ${n.styles}`,Xo(e,t.matchedRules,n),`#### ${n.computedStyles}`,Zo(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(i=>`- ${J(i)}`).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 mn(e,t){let o=He(e.page.url,e.page.url),n=It[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
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
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((a,r)=>{let i=t.targets[r];if(i===void 0)throw new RangeError("Prompt target draft is missing.");return Qo(a,i,r,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 er(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 tr(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 nr(e){return{pageTitle:J(e.page.title),targets:e.targets.map(tr)}}function or(e,t,o){let n=It[e.locale],a=[(r,i)=>i.computedEntries.pop()!==void 0,(r,i)=>i.reactStack.pop()!==void 0,(r,i)=>{let c=bn(i.dom,n.unavailable);return i.dom===c?!1:(i.dom=c,!0)},(r,i)=>i.matchedRules.shift()!==void 0,er,(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],S=t.targets[c];if(y!==void 0&&S!==void 0&&r(y,S))return(c+1)%e.targets.length}}function rr(e,t){let o=It[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}: ${hn(a,o)}`,...c===void 0?[]:[`- ${o.component}: ${J(c)}`],`- ${o.element}: ${J(bn(i?.dom??a.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 ir(e,t){let o=nr(e),n=mn(e,o),a=0;for(;n.length>t;){let i=or(e,o,a);if(i===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else a=i;n=mn(e,o)}if(n.length<=t)return n;let r=rr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function yn(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 ir(t,e.maxCharacters)}})}var de=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),_t=de.idle;function ar(e){return e.type==="ACTIVATE"?de.inspecting:de.idle}function sr(e){switch(e.type){case"HOVER":return de.inspecting;case"SELECT":return de.selected;case"CANCEL":return de.idle;default:return de.inspecting}}function cr(e){switch(e.type){case"RESELECT":return de.inspecting;case"CLOSE":return de.idle;case"PREVIEW":return de.previewing;case"OPEN_EDITOR":return de.selected;default:return de.selected}}function lr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return de.selected;case"COPY_FAILURE":return de.previewing;default:return de.previewing}}function xn(e,t){switch(e.status){case"idle":return ar(t);case"inspecting":return sr(t);case"selected":return cr(t);case"previewing":return lr(t)}}var Sn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Cn(e){return Rt(e.getAttribute(Et))}function dr(e){let t=e.parentElement;for(;t!==null;){let o=Cn(t);if(o!==void 0)return o;t=t.parentElement}}function An(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function pr(){return Object.freeze({origin:"none",confidence:"unknown"})}function vn(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 En(e){let t=!0;function o(n){if(!t)return Sn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Sn}}return Object.freeze({resolve(n){let a=Cn(n),r=o(n);if(a!==void 0)return Object.freeze({react:r,source:An(a,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let i=dr(n);return Object.freeze(i!==void 0?{react:r,source:An(i,"dom-ancestor","approximate")}:{react:r,source:pr()})},dispose(){t=!1,e.adapter.dispose()}})}function l(e,t){let o=e.createElement(t);return o.setAttribute(Fe,""),o}function F(e,t,o=""){let n=l(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Tn=`
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 @@ ${lt(e.code.language,J(t.codeLines.join(`
162
162
  white-space: pre;
163
163
  user-select: text;
164
164
  }
165
- `;function Rn(e,t,o,n){let a=e.createElement("option");a.value=o,a.textContent=n,t.append(a)}function wn(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 S=l(e,"div");S.className="spotpatch-agent-selectors";let d=l(e,"label"),w=l(e,"span"),m=l(e,"select");d.append(w,m);let k=l(e,"label"),A=l(e,"span"),R=l(e,"select");k.append(A,R),S.append(d,k);let M=l(e,"label");M.className="spotpatch-consent";let I=l(e,"input");I.type="checkbox";let z=l(e,"span");M.append(I,z);let g=l(e,"p");g.className="spotpatch-agent-capability",g.dataset.state="idle",y.append(S,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 O=l(e,"span");O.className="spotpatch-agent-model";let V=l(e,"span");V.className="spotpatch-agent-status",C.append(O,V);let ie=l(e,"p");ie.className="spotpatch-agent-phase";let _=l(e,"p");_.className="spotpatch-agent-error",_.hidden=!0;let xe=l(e,"ul");xe.className="spotpatch-agent-activity";let te=l(e,"div");te.className="spotpatch-agent-result",te.hidden=!0;let H=l(e,"p");H.className="spotpatch-agent-summary";let ve=l(e,"ul");ve.className="spotpatch-agent-files";let ge=l(e,"div");ge.className="spotpatch-agent-checks";let j=l(e,"pre");j.className="spotpatch-agent-diff",j.tabIndex=0,j.setAttribute("aria-label",n.agent.diffAriaLabel),te.append(H,ve,ge,j),x.append(C,ie,_,xe,te),a.append(r,y,x);let fe=F(e,n.agent.testConnection),Ee=F(e,n.agent.verifyAndRun,"spotpatch-run"),Re=F(e,n.agent.cancel),ne=F(e,n.agent.apply,"spotpatch-primary"),q=F(e,n.agent.revert),X=F(e,n.agent.revise),ae=t.enabled?t.providers:[],Te=new Map(ae.map(f=>[f.id,f])),Me=!1,_e=!0,oe=!1,P=!1,T=!1,me=!1,se,Ne,he=[],Se,Z="idle",Q=n.agent.connectionNotTested,be;for(let f of ae)Rn(e,m,f.id,f.label);t.enabled&&(m.value=t.defaultProvider);let K=()=>Te.get(m.value),Ae=()=>{let f=K();if(R.replaceChildren(),f===void 0){z.textContent=n.agent.providerUnavailable;return}for(let B of f.models)Rn(e,R,B.id,B.label);R.value=f.defaultModel,z.textContent=n.agent.consent(f.label)},G=()=>{let f=t.enabled&&oe&&!P;Ee.textContent=T?n.agent.verifying:me?n.agent.run:n.agent.verifyAndRun,Ee.classList.toggle("spotpatch-primary",me),fe.hidden=!f,Ee.hidden=!f,fe.disabled=!_e||T||K()===void 0,Ee.disabled=!_e||T||!Me||!I.checked||K()===void 0||R.value.length===0,(!P||!oe)&&(Re.hidden=!0,ne.hidden=!0,q.hidden=!0,X.hidden=!0)};Ae(),m.addEventListener("change",()=>{Ae(),I.checked=!1,g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Z="idle",Q=n.agent.connectionNotTested,be=void 0,me=!1,G()}),R.addEventListener("change",()=>{g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Z="idle",Q=n.agent.connectionNotTested,be=void 0,me=!1,G()}),I.addEventListener("change",G);function Oe(){if(se===void 0)return;let f=se,B=Ne;O.textContent=`${f.providerLabel} · ${f.modelLabel}`,V.textContent=n.agent.status(f.status),ie.textContent=f.phaseMessage;let W=Se??f.errorCode;_.hidden=W===void 0,_.textContent=W===void 0?"":n.errors[W],xe.replaceChildren();for(let N of he.slice(-8)){let re=l(e,"li");re.dataset.state=N.state,re.textContent=N.label,xe.append(re)}te.hidden=B===void 0,H.textContent=B?.summary??"",ve.replaceChildren(),ge.replaceChildren(),j.textContent=B?.diff??"";for(let N of B?.files??[]){let re=l(e,"li");re.textContent=`${N.kind} ${N.relativePath} (+${String(N.additions)} / -${String(N.deletions)})`,ve.append(re)}for(let N of B?.checks??[]){let re=l(e,"details"),qe=l(e,"summary");qe.textContent=`${N.label}: ${N.status} · ${String(N.durationMs)} ms`;let s=l(e,"pre");s.textContent=N.output.length===0?n.agent.noOutput:N.output,re.append(qe,s),ge.append(re)}fe.hidden=!0,Ee.hidden=!0,Re.hidden=!oe||!f.canCancel,Re.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ne.hidden=!oe||!f.canApply,q.hidden=!oe||!f.canRevert,X.hidden=!oe||!["completed","cancelled","reverted","failed"].includes(f.status)}function Pe(){n=o.messages(),i.textContent=n.agent.title,c.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,w.textContent=n.agent.provider,A.textContent=n.agent.model,m.setAttribute("aria-label",n.agent.providerAriaLabel),R.setAttribute("aria-label",n.agent.modelAriaLabel),j.setAttribute("aria-label",n.agent.diffAriaLabel),fe.textContent=n.agent.testConnection,ne.textContent=n.agent.apply,q.textContent=n.agent.revert,X.textContent=n.agent.revise;let f=K();z.textContent=f===void 0?n.agent.providerUnavailable:n.agent.consent(f.label),Z==="idle"?g.textContent=n.agent.connectionNotTested:Z==="probing"?g.textContent=n.agent.testingCapability:Z==="ready"?g.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:be!==void 0?g.textContent=n.errors[be]:K()===void 0?g.textContent=n.agent.providerUnavailable:g.textContent=Q,G(),Oe()}let $e=o.subscribe(Pe);return Pe(),Object.freeze({root:a,providerSelect:m,modelSelect:R,consentCheckbox:I,testButton:fe,runButton:Ee,cancelButton:Re,applyButton:ne,revertButton:q,resetButton:X,consentGranted(){return I.checked},readSelection(){let f=K(),B=f?.models.find(W=>W.id===R.value);return f===void 0||B===void 0?void 0:Object.freeze({providerProfileId:f.id,modelProfileId:B.id})},renderCapability(f,B,W,N){Z=f,Q=B,be=N,T=f==="probing",me=f==="ready"&&W?.state==="agent-ready",g.dataset.state=f,g.textContent=W?.state==="agent-ready"?`${B} · ${n.agent.toolsReady}`:B,G()},renderJob(f,B,W,N){P=!0,y.hidden=!0,x.hidden=!1,m.disabled=!0,R.disabled=!0,I.disabled=!0,se=f,Ne=B,he=W,Se=N,Oe()},resetJob(){P=!1,se=void 0,Ne=void 0,he=[],Se=void 0,y.hidden=!1,x.hidden=!0,m.disabled=!1,R.disabled=!1,I.disabled=!1,xe.replaceChildren(),ve.replaceChildren(),ge.replaceChildren(),j.textContent="",_.textContent="",_.hidden=!0,G()},setContextReady(f){Me=f,G()},setEditingEnabled(f){_e=f,m.disabled=!f||P,R.disabled=!f||P,I.disabled=!f||P,G()},setProviderConsent(f){I.checked=f,G()},setSelectionVisible(f){oe=f,G(),f||(Re.hidden=!0,ne.hidden=!0,q.hidden=!0,X.hidden=!0)},dispose(){$e()}})}var ur="http://www.w3.org/2000/svg";function we(e,t,o){let n=e.createElementNS(ur,t);for(let[a,r]of Object.entries(o))n.setAttribute(a,r);return n}function On(e){let t=we(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=we(e,"defs",{}),n=we(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(we(e,"stop",{offset:"0","stop-color":"#7c22ff"}),we(e,"stop",{offset:".52","stop-color":"#4a69ff"}),we(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=we(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=we(e,"path",{d:"M106 25v42",...a,"stroke-width":"14"}),c=we(e,"path",{d:"M35 109h20m102 0h38",...a,"stroke-width":"13"}),y=we(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...a,"stroke-width":"9"}),S=we(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,S),t}function dt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Pn({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,S=dt(c-t/2,16,r),d=dt(y-e/2,16,i),w=S,m=d,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?(w=o.x+o.width+14,k="right"):o.x-t-14>=16&&(w=o.x-t-14,k="left"),Object.freeze({anchorX:dt(c-w,22,t-22),anchorY:dt(y-m,22,e-22),left:w,mode:k,top:m})}var gr=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"}),fr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),mr=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."}),hr=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 任务失败,私有细节未暴露到浏览器。"}),br=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"}),yr=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:"警告"}),xr=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context"}),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:br,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open in VS Code",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=>gr[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.",editorOpened:"VS Code open request sent.",editorFailed:"VS Code could not be opened.",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:mr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文"}),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:yr,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"在 VS Code 中打开",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=>fr[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:"浏览器上下文采集完成。",editorOpened:"已发送 VS Code 打开请求。",editorFailed:"无法打开 VS Code。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:hr})});function Ln(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 Sr(e,t){if(e!=="auto")return e;let o=Ln(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(Ln).find(a=>a!==void 0)??"en-US"}function In(e,t="auto"){let o=Sr(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>xr[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 Ar=560,Cr=Object.freeze({previewing:640,selected:720});function vr(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 @@ ${lt(e.code.language,J(t.codeLines.join(`
197
197
  position: fixed;
198
198
  right: 24px;
199
199
  bottom: 24px;
200
- z-index: ${String(tt.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 @@ ${lt(e.code.language,J(t.codeLines.join(`
231
231
  position: fixed;
232
232
  top: 0;
233
233
  left: 0;
234
- z-index: ${String(tt.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 @@ ${lt(e.code.language,J(t.codeLines.join(`
258
258
  .spotpatch-selection-highlights {
259
259
  position: fixed;
260
260
  inset: 0;
261
- z-index: ${String(tt.highlight)};
261
+ z-index: ${String(ot.highlight)};
262
262
  pointer-events: none;
263
263
  }
264
264
  .spotpatch-selection-highlight {
@@ -299,7 +299,7 @@ ${lt(e.code.language,J(t.codeLines.join(`
299
299
  position: fixed;
300
300
  top: 16px;
301
301
  left: 16px;
302
- z-index: ${String(tt.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,14 +397,27 @@ ${lt(e.code.language,J(t.codeLines.join(`
397
397
  gap: 8px;
398
398
  flex: none;
399
399
  }
400
- .spotpatch-locale {
401
- min-width: 38px;
400
+ .spotpatch-repository,
401
+ .spotpatch-locale,
402
+ .spotpatch-close {
402
403
  height: 30px;
403
404
  border: 1px solid rgb(255 255 255 / 11%);
404
405
  border-radius: 9px;
406
+ background: rgb(255 255 255 / 4%);
407
+ }
408
+ .spotpatch-repository {
409
+ display: inline-flex;
410
+ align-items: center;
411
+ padding: 0 10px;
412
+ color: #bcecf2;
413
+ font-size: 11px;
414
+ font-weight: 680;
415
+ text-decoration: none;
416
+ }
417
+ .spotpatch-locale {
418
+ min-width: 38px;
405
419
  padding: 0 9px;
406
420
  color: #c5cad5;
407
- background: rgb(255 255 255 / 4%);
408
421
  cursor: pointer;
409
422
  font-size: 12px;
410
423
  font-weight: 650;
@@ -412,20 +425,17 @@ ${lt(e.code.language,J(t.codeLines.join(`
412
425
  .spotpatch-close {
413
426
  display: inline-grid;
414
427
  width: 30px;
415
- height: 30px;
416
428
  padding: 0;
417
429
  place-items: center;
418
- border: 1px solid rgb(255 255 255 / 11%);
419
- border-radius: 9px;
420
430
  color: #9da5b4;
421
- background: rgb(255 255 255 / 4%);
422
431
  cursor: pointer;
423
432
  font-size: 17px;
424
433
  line-height: 1;
425
434
  transition: border-color 150ms ease, color 150ms ease, background 150ms ease;
426
435
  }
427
436
  .spotpatch-close:hover,
428
- .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%); }
429
439
  .spotpatch-title {
430
440
  margin: 0;
431
441
  color: #fff;
@@ -475,10 +485,14 @@ ${lt(e.code.language,J(t.codeLines.join(`
475
485
  background: #f59e0b;
476
486
  content: "";
477
487
  }
478
- .spotpatch-context-state[data-state="ready"] { color: #9fe3c4; }
479
- .spotpatch-context-state[data-state="ready"]::before { background: #34d399; }
480
- .spotpatch-context-state[data-state="warning"] { color: #fecaca; }
481
- .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; }
482
496
  .spotpatch-body {
483
497
  min-height: 0;
484
498
  overflow: auto;
@@ -540,7 +554,7 @@ ${lt(e.code.language,J(t.codeLines.join(`
540
554
  }
541
555
  .spotpatch-target-summary {
542
556
  display: grid;
543
- grid-template-columns: minmax(0, 1fr) 34px;
557
+ grid-template-columns: minmax(0, 1fr) 34px 34px;
544
558
  align-items: stretch;
545
559
  gap: 4px;
546
560
  padding: 5px;
@@ -591,6 +605,7 @@ ${lt(e.code.language,J(t.codeLines.join(`
591
605
  white-space: nowrap;
592
606
  }
593
607
  .spotpatch-target-state[data-complete="false"] { color: #f5c97a; background: rgb(245 158 11 / 9%); }
608
+ .spotpatch-target-open,
594
609
  .spotpatch-target-remove {
595
610
  display: inline-grid;
596
611
  width: 34px;
@@ -604,6 +619,8 @@ ${lt(e.code.language,J(t.codeLines.join(`
604
619
  background: transparent;
605
620
  cursor: pointer;
606
621
  }
622
+ .spotpatch-target-open { color: #79d9e7; }
623
+ .spotpatch-target-open:hover:not(:disabled) { border-color: rgb(68 202 224 / 30%); color: #c8f7ff; background: rgb(8 145 178 / 11%); }
607
624
  .spotpatch-target-remove:hover:not(:disabled) { border-color: rgb(251 113 133 / 24%); color: #fda4af; background: rgb(127 29 29 / 12%); }
608
625
  .spotpatch-target-editor {
609
626
  border-top: 1px solid rgb(255 255 255 / 7%);
@@ -713,6 +730,10 @@ ${lt(e.code.language,J(t.codeLines.join(`
713
730
  border-top: 1px solid rgb(255 255 255 / 8%);
714
731
  background: rgb(8 12 22 / 82%);
715
732
  }
733
+ .spotpatch-editor-feedback {
734
+ flex-basis: 100%;
735
+ white-space: normal;
736
+ }
716
737
  .spotpatch-actions button {
717
738
  display: inline-flex;
718
739
  min-height: 40px;
@@ -744,6 +765,8 @@ ${lt(e.code.language,J(t.codeLines.join(`
744
765
  .spotpatch-actions .spotpatch-primary::after { margin-left: 8px; content: "↗"; font-size: 12px; }
745
766
  .spotpatch-actions button:disabled { cursor: not-allowed; opacity: .4; transform: none; }
746
767
  .spotpatch-actions button:focus-visible,
768
+ .spotpatch-repository:focus-visible,
769
+ .spotpatch-target-open:focus-visible,
747
770
  .spotpatch-target-remove:focus-visible,
748
771
  .spotpatch-close:focus-visible,
749
772
  .spotpatch-trigger:focus-visible,
@@ -777,10 +800,10 @@ ${lt(e.code.language,J(t.codeLines.join(`
777
800
  .spotpatch-target-select { grid-template-columns: 32px minmax(0, 1fr); }
778
801
  .spotpatch-target-state { display: none; }
779
802
  }
780
- ${Tn}
781
- `,t}function Er(e,t){return e.split(`
782
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function _n(e,t,o=Object.freeze({enabled:!1}),n="auto"){let a=In(e,n),r=a.messages(),i=e.createElement("spotpatch-root");i.setAttribute(Fe,"");let c=i.attachShadow({mode:"open"}),y=F(e,r.trigger.select,"spotpatch-trigger");y.title=r.trigger.title(t),y.setAttribute("aria-pressed","false");let S=l(e,"div");S.className="spotpatch-highlight",S.hidden=!0;let d=l(e,"span");d.className="spotpatch-highlight-label",S.append(d);let w=l(e,"div");w.className="spotpatch-selection-highlights",w.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 R=l(e,"header");R.className="spotpatch-header";let M=l(e,"div");M.className="spotpatch-brand-row";let I=l(e,"div");I.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),I.append(On(e),z);let C=l(e,"span");C.className="spotpatch-header-controls";let O=F(e,"","spotpatch-locale"),V=F(e,"×","spotpatch-close");C.append(O,V),M.append(I,C);let ie=l(e,"h2");ie.id="spotpatch-selection-title",ie.className="spotpatch-title";let _=l(e,"p");_.className="spotpatch-subtitle";let xe=l(e,"div");xe.className="spotpatch-target-row";let te=l(e,"span");te.className="spotpatch-target-label";let H=l(e,"span");H.className="spotpatch-context-state",H.dataset.state="loading",H.textContent=r.context.collecting,xe.append(te,H),R.append(M,ie,_,xe);let ve=l(e,"div");ve.className="spotpatch-body";let ge=l(e,"div");ge.className="spotpatch-selection-panel";let j=l(e,"section");j.className="spotpatch-targets";let fe=l(e,"div");fe.className="spotpatch-targets-heading";let Ee=l(e,"span"),Re=l(e,"span");Re.className="spotpatch-targets-meta";let ne=l(e,"span");ne.className="spotpatch-target-complete";let q=l(e,"span");q.className="spotpatch-target-budget",q.setAttribute("aria-live","polite");let X=l(e,"span");X.className="spotpatch-target-count",Re.append(ne,q),fe.append(Ee,X);let ae=l(e,"div");ae.className="spotpatch-target-list",j.append(fe,Re,ae);let Te=l(e,"details");Te.className="spotpatch-diagnostics";let Me=l(e,"summary"),_e=l(e,"span"),oe=l(e,"span");oe.className="spotpatch-source-peek",oe.textContent=r.diagnostics.resolving,Me.append(_e,oe);let P=l(e,"pre");P.className="spotpatch-summary",Te.append(Me,P);let T=wn(e,o,a);ge.append(j,Te,T.root);let me=l(e,"div");me.className="spotpatch-preview-panel",me.hidden=!0;let se=l(e,"pre");se.className="spotpatch-prompt",se.tabIndex=0,se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),me.append(se),ve.append(ge,me);let Ne=l(e,"footer");Ne.className="spotpatch-actions";let he=F(e,r.actions.addElement),Se=F(e,r.actions.reselect),Z=F(e,r.actions.openEditor),Q=F(e,r.actions.preview,"spotpatch-primary"),be=F(e,r.actions.copy,"spotpatch-primary"),K=F(e,r.actions.back);Ne.append(T.runButton,Q,T.testButton,T.cancelButton,T.applyButton,T.revertButton,T.resetButton,he,Z,Se,be,K),A.append(R,ve,Ne),m.append(k,A);let Ae=l(e,"div");Ae.className="spotpatch-live",Ae.setAttribute("aria-live","polite"),Ae.setAttribute("aria-atomic","true"),c.append(vr(e),w,S,m,y,Ae),e.documentElement.append(i);let G,Oe,Pe="idle",$e=!1,f=!1,B="",W=!0,N=[],re=0;function qe(p){return p.status==="ready"?r.targets.statusReady:p.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function s(p){let h=ae.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(h).find(E=>p===void 0||E.dataset.targetInstructionId===p)}function u(p,h){let E=c.activeElement?.closest("textarea[data-target-instruction-id]"),$=E?.dataset.targetInstructionId,ce=E?.selectionStart,Ie=E?.selectionEnd;N=p.map(pe=>Object.freeze({...pe})),re=h,ae.replaceChildren();let ke=p.filter(pe=>pe.instruction.trim().length>0).length,le=p.reduce((pe,Y)=>pe+Y.instruction.trim().length,0);X.textContent=r.targets.count(p.length,h),ne.textContent=r.targets.complete(ke,p.length);let Ce=le>4e3;q.dataset.state=Ce?"over":"ready",q.textContent=Ce?r.targets.instructionBudgetExceeded(le,4e3):r.targets.instructionBudget(le,4e3),he.disabled=!W||p.length>=h,he.title=p.length>=h?r.targets.limitTitle(h):r.targets.addTitle,te.textContent=p.length===1?p[0]?.label??r.context.selectedElement:r.context.selectedCount(p.length);for(let[pe,Y]of p.entries()){let Ue=l(e,"div");Ue.className="spotpatch-target-item",Ue.dataset.active=String(Y.active),Ue.dataset.status=Y.status,Ue.dataset.targetId=Y.id;let pt=l(e,"div");pt.className="spotpatch-target-summary";let We=F(e,"","spotpatch-target-select");We.dataset.activateTargetId=Y.id,We.setAttribute("aria-label",r.targets.activate(pe+1)),We.setAttribute("aria-expanded",String(Y.active));let ut=l(e,"span");ut.className="spotpatch-target-index",ut.textContent=String(pe+1);let gt=l(e,"span");gt.className="spotpatch-target-copy";let ft=l(e,"span");ft.className="spotpatch-target-name",ft.textContent=Y.label;let mt=l(e,"span");mt.className="spotpatch-target-source",mt.textContent=`${qe(Y)} · ${Y.source}`,gt.append(ft,mt);let Dt=Y.instruction.trim().length>0,nt=l(e,"span");nt.className="spotpatch-target-state",nt.dataset.complete=String(Dt),nt.textContent=Dt?r.targets.instructionReady:r.targets.instructionMissing,We.append(ut,gt,nt);let Ye=F(e,"×","spotpatch-target-remove");if(Ye.dataset.removeTargetId=Y.id,Ye.disabled=!W,Ye.setAttribute("aria-label",r.targets.remove(pe+1)),Ye.title=r.targets.removeTitle,pt.append(We,Ye),Ue.append(pt),Y.active){let ht=l(e,"label");ht.className="spotpatch-target-editor";let bt=l(e,"span");bt.className="spotpatch-target-editor-head";let yt=l(e,"span");yt.className="spotpatch-target-editor-label",yt.textContent=r.targets.instructionLabel(Y.label);let xt=l(e,"span");xt.className="spotpatch-target-editor-count",xt.textContent=r.targets.instructionCount(Y.instruction.length,2e3),bt.append(yt,xt);let De=l(e,"textarea");De.rows=4,De.maxLength=2e3,De.value=Y.instruction,De.placeholder=r.targets.instructionPlaceholder,De.disabled=!W,De.dataset.targetInstructionId=Y.id,De.setAttribute("aria-label",r.targets.instructionLabel(Y.label)),ht.append(bt,De),Ue.append(ht)}ae.append(Ue)}if($!==void 0){let pe=s($);pe?.focus({preventScroll:!0}),ce!==void 0&&Ie!==void 0&&pe?.setSelectionRange(ce,Ie)}}function v(p,h){N=N.map(Ce=>Ce.id===p?Object.freeze({...Ce,instruction:h}):Ce);let E=Array.from(ae.querySelectorAll(".spotpatch-target-item")).find(Ce=>Ce.dataset.targetId===p);if(E===void 0)return;let $=h.trim().length>0,ce=E.querySelector(".spotpatch-target-state"),Ie=E.querySelector(".spotpatch-target-editor-count");ce!==null&&(ce.dataset.complete=String($),ce.textContent=$?r.targets.instructionReady:r.targets.instructionMissing),Ie!==null&&(Ie.textContent=r.targets.instructionCount(h.length,2e3)),ne.textContent=r.targets.complete(N.filter(Ce=>Ce.instruction.trim().length>0).length,N.length);let ke=N.reduce((Ce,pe)=>Ce+pe.instruction.trim().length,0),le=ke>4e3;q.dataset.state=le?"over":"ready",q.textContent=le?r.targets.instructionBudgetExceeded(ke,4e3):r.targets.instructionBudget(ke,4e3)}function U(p){w.replaceChildren(),Oe=p.find(h=>h.active)?.rect,G=Oe;for(let[h,E]of p.entries()){let $=l(e,"div");$.className="spotpatch-selection-highlight",$.dataset.targetId=E.id,$.dataset.active=String(E.active),$.style.transform=`translate(${String(E.rect.x)}px, ${String(E.rect.y)}px)`,$.style.width=`${String(E.rect.width)}px`,$.style.height=`${String(E.rect.height)}px`;let ce=l(e,"span");ce.textContent=`${String(h+1)} · ${E.label}`,$.append(ce),w.append($)}L()}function L(){if(m.hidden||G===void 0)return;let p=e.defaultView,h=p?.innerWidth??e.documentElement.clientWidth,E=p?.innerHeight??e.documentElement.clientHeight,$=m.getBoundingClientRect(),ce=Pe==="previewing"?"previewing":"selected",Ie=$.width>0?$.width:Math.min(Ar,h-32),ke=$.height>0?$.height:Math.min(Cr[ce],E-32),le=Pn({target:G,dialogWidth:Ie,dialogHeight:ke,viewportWidth:h,viewportHeight:E});m.style.left=`${String(le.left)}px`,m.style.top=`${String(le.top)}px`,m.style.setProperty("--spotpatch-anchor-x",`${String(le.anchorX)}px`),m.style.setProperty("--spotpatch-anchor-y",`${String(le.anchorY)}px`),m.dataset.placement=le.mode}function Le(p){let h=r.summary,E=Er(p,h.source);oe.textContent=E??r.diagnostics.noExactSource;let $=`${h.browserContext}: ${h.collectionStatuses.ready}`,ce=`${h.browserContext}: ${h.collectionStatuses.loading}`,Ie=`${h.browserContext}: ${h.collectionStatuses.failed}`,ke=`${h.api}: ${h.apiStatuses.loading}`,le=`${h.api}: ${h.apiStatuses.failed}`;p.includes($)&&!p.includes(ce)&&!p.includes(ke)&&!p.includes(Ie)&&!p.includes(le)?(H.dataset.state="ready",H.textContent=r.context.ready):p.includes(Ie)||p.includes(le)?(H.dataset.state="warning",H.textContent=r.context.partial):(H.dataset.state="loading",H.textContent=r.context.collecting)}function Ke(p,h,E){$e=h,f=E,B=p,P.textContent=p,Z.disabled=!h,Q.disabled=!E,T.setContextReady(E),Le(p),L()}function Mt(p){Pe=p;let h=p==="selected",E=p==="previewing";y.hidden=h||E,ge.hidden=!h,me.hidden=!E,Se.hidden=!h,he.hidden=!h,Z.hidden=!h,Q.hidden=!h,T.setSelectionVisible(h),be.hidden=!E,K.hidden=!E,ie.textContent=E?r.dialog.previewTitle:r.dialog.editTitle,_.textContent=E?r.dialog.previewSubtitle:r.dialog.editSubtitle,L()}function $t(){r=a.messages(),g.textContent=r.brand.name,x.textContent=r.brand.context,O.textContent=r.alternateLocaleName,O.title=r.switchLocale,O.setAttribute("aria-label",r.switchLocale),V.setAttribute("aria-label",r.dialog.close),V.title=r.dialog.close,j.setAttribute("aria-label",r.targets.ariaLabel),Ee.textContent=r.targets.title,_e.textContent=r.diagnostics.title,se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),he.textContent=r.actions.addElement,Se.textContent=r.actions.reselect,Z.textContent=r.actions.openEditor,Q.textContent=r.actions.preview,be.textContent=r.actions.copy,K.textContent=r.actions.back,y.title=r.trigger.title(t),y.textContent=Pe==="inspecting"?r.trigger.stop:r.trigger.select,Mt(Pe),N.length>0?u(N,re):(X.textContent=r.targets.count(0,re),ne.textContent=r.targets.complete(0,0),q.dataset.state="ready",q.textContent=r.targets.instructionBudget(0,4e3),te.textContent=r.context.selectedElement),B.length>0?Le(B):(oe.textContent=r.diagnostics.resolving,H.textContent=r.context.collecting)}Te.addEventListener("toggle",L),O.addEventListener("click",a.toggle);let Un=a.subscribe($t);return $t(),Object.freeze({host:i,triggerButton:y,addTargetButton:he,targetList:ae,reselectButton:Se,openEditorButton:Z,previewButton:Q,copyButton:be,backButton:K,closeButton:V,agentProviderSelect:T.providerSelect,agentModelSelect:T.modelSelect,agentConsentCheckbox:T.consentCheckbox,agentTestButton:T.testButton,agentRunButton:T.runButton,agentCancelButton:T.cancelButton,agentApplyButton:T.applyButton,agentRevertButton:T.revertButton,agentResetButton:T.resetButton,renderStatus(p){let h=p==="inspecting";y.setAttribute("aria-pressed",String(h)),y.textContent=h?r.trigger.stop:r.trigger.select,Mt(p)},showHighlight(p,h){G=p,S.hidden=!1,S.style.transform=`translate(${String(p.x)}px, ${String(p.y)}px)`,S.style.width=`${String(p.width)}px`,S.style.height=`${String(p.height)}px`,d.textContent=h,te.textContent=h,L()},hideHighlight(){G=Oe,S.hidden=!0,d.textContent="",L()},showSelectionHighlights:U,hideSelectionHighlights(){w.replaceChildren(),Oe=void 0,G=void 0},showSelection(p,h,E){Ke(p,h,E),y.hidden=!0,m.hidden=!1,L()},updateSelection:Ke,renderTargets:u,updateTargetInstruction:v,setPreviewEnabled(p){f=p,Q.disabled=!p,T.setContextReady(p)},hideSelection(){m.hidden=!0,y.hidden=!1,ae.replaceChildren(),N=[],re=0,B="",X.textContent=r.targets.count(0,0),ne.textContent=r.targets.complete(0,0),te.textContent=r.context.selectedElement,P.textContent="",se.textContent="",oe.textContent=r.diagnostics.resolving,H.dataset.state="loading",H.textContent=r.context.collecting,Z.disabled=!0,Q.disabled=!0,$e=!1,f=!1,T.setContextReady(!1),T.setSelectionVisible(!1),T.setEditingEnabled(!0),T.resetJob()},hideSelectionTemporarily(){m.hidden=!0,y.hidden=!1},showPreview(p){se.textContent=p,L()},readAgentSelection(){return T.readSelection()},agentConsentGranted(){return T.consentGranted()},setAgentProviderConsent(p){T.setProviderConsent(p)},setAgentEditingEnabled(p){W=p,he.disabled=!p,Se.disabled=!p,ae.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(h=>{h.disabled=!p}),Z.disabled=!p||!$e,Q.disabled=!p||!f,T.setEditingEnabled(p),L()},renderAgentCapability(p,h,E,$){T.renderCapability(p,h,E,$);let ce=p==="ready"&&E?.state==="agent-ready";Q.classList.toggle("spotpatch-primary",!ce),L()},renderAgentJob(p,h,E,$){T.renderJob(p,h,E,$),L()},resetAgentJob(){T.resetJob(),L()},focusTargetInstruction(p){s(p)?.focus({preventScroll:!0})},focusPrompt(){se.focus({preventScroll:!0})},announce(p){Ae.textContent="",Ae.textContent=p},locale:a.locale,messages:a.messages,subscribeLocale:a.subscribe,dispose(){Te.removeEventListener("toggle",L),O.removeEventListener("click",a.toggle),Un(),T.dispose(),i.remove()}})}function Rr(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 Nn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`Vite: ${e.viteVersion}`,`${t.source}: ${Rr(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(`
783
- `)}function kn(e,t){return`${e}:${t}`}function Tr(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 Mn(e){let t=g=>Yt(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,S=!1,d=!1,w=()=>e.view.readAgentSelection(),m=g=>{c!==void 0&&e.view.renderAgentJob(c,y,Object.freeze([...r.values()]),g??c.errorCode)},k=()=>{let g=w();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(kn(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=w();if(x===void 0)throw new Error("Agent provider selection is unavailable.");let C=kn(x.providerProfileId,x.modelProfileId),O=n.get(C);if(O!==void 0)return O;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let V=await e.api.agentCapability(x);if(g!==i)return V;if(V.state!=="agent-ready")throw new D(V.errorCode??b.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(C,V),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,V),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),V},R=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"&&!S&&(S=!0,e.onApplied()));let O=Tr(C);O!==void 0&&r.set(O.key,O),m()}),x===i&&await R(g,x)}catch(C){x===i&&!(C instanceof DOMException&&C.name==="AbortError")&&m(t(C))}},I=async g=>{let x=c;if(x===void 0||d)return;d=!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 O=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=O,O.status==="applied"&&!S&&(S=!0,e.onApplied()),await R(O.jobId,C)}catch(O){if(C!==i)return;c=x,await R(x.jobId,C),m(t(O)),e.view.announce(o(O))}finally{C===i&&(d=!1)}},z=()=>{i+=1,c=void 0,y=void 0,r.clear(),S=!1,d=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),k()};return Object.freeze({apply(){c?.canApply===!0&&I("apply")},beginSelection(){z()},cancel(){c?.canCancel===!0&&I("cancel")},consentChanged(){let g=w();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(),S=!1,d=!1,g!==void 0&&e.api.cancelAgentJob(g).catch(()=>{})},providerOrModelChanged(){i+=1,k()},reset(){let g=S;z(),g&&e.onReselectRequired()},revert(){c?.canRevert===!0&&I("revert")},run(){if(!e.ai.enabled||c!==void 0)return;let g=w(),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 O=await e.api.createAgentJob({annotation:x,providerProfileId:g.providerProfileId,modelProfileId:g.modelProfileId,providerDataConsent:!0});C===i&&(c=O,y=void 0,r.clear(),m(),M(O.jobId,C))}).catch(O=>{C===i&&(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=++i;A(g).catch(x=>{g===i&&(e.view.renderAgentCapability("error",o(x),void 0,t(x)),e.view.announce(o(x)))})}})}function $n(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 Dn(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 zn(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var Or=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Nt(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 Pr(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 Lr(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Ir(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 jn(e,t={}){let o=Ir(t),n=t.view??_n(o.document,e.shortcut,e.ai,e.locale),a=t.api??Xt({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??yn({maxCharacters:e.budget.totalCharacters}),i=t.clipboard??zn(o.window.navigator),c=t.createId??(()=>$n(o.window)),y=t.now??(()=>new Date().toISOString()),S=En({adapter:t.reactAdapter??wr({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.")}}),d=_t,w=!1,m,k,A=[],R,M=0,I=0,z=!1,g="",x,C,O,V,ie=new Map;function _(s){d=xn(d,s),n.renderStatus(d.status)}function xe(){return A.find(s=>s.id===R)??A.at(-1)}function te(s,u){return w&&u===I&&d.status!=="idle"&&A.includes(s)}function H(){let s=A.reduce((u,v)=>u+v.instruction.trim().length,0);return A.length>0&&s<=4e3&&A.every(u=>u.instruction.trim().length>0&&u.element!==void 0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function ve(){let s=n.messages().summary;return A.map((u,v)=>{let U=Nn({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(v+1,u.id===R)}
784
- ${U}`}).join(`
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(`
785
808
 
786
- `)}function ge(){let s=A.flatMap(u=>u.element?.isConnected?[{id:u.id,label:Nt(u.element),rect:Pt(u.element,o.window),active:u.id===R}]:[]);s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function j(s=!1){if(A.length===0)return;n.renderTargets(A.map(L=>({id:L.id,label:L.resolution.react.componentName??(L.element===void 0?L.elementContext?.tagName??"Element":Nt(L.element)),source:Pr(L,n.messages().context.sourceUnavailable),status:Lr(L),active:L.id===R,instruction:L.instruction})),e.maxTargets),ge();let u=xe(),v=ve(),U=u?.marker!==void 0;s?n.showSelection(v,U,H()):n.updateSelection(v,U,H())}function fe(){if(!H())return;let s=A.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let v=[...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:v}});return jt({id:c(),locale:n.locale(),createdAt:y(),page:Dn(o.document,o.window),targets:s})}function Ee(s){n.showHighlight(Pt(s,o.window),Nt(s))}function Re(){x?.isConnected===!0&&x.focus({preventScroll:!0}),x=void 0}function ne(){for(let s of ie.values())o.window.clearTimeout(s);ie.clear()}function q(){I+=1,a.cancelPending(),P.disposeSelection(),ne(),C?.disconnect(),A=[],R=void 0,z=!1,g="",n.hideSelection(),n.hideSelectionHighlights(),Re()}function X(){d.status==="inspecting"?_({type:"CANCEL"}):d.status==="selected"?_({type:"CLOSE"}):d.status==="previewing"&&(_({type:"BACK"}),_({type:"CLOSE"})),q(),n.hideHighlight()}function ae(){if(d.status!=="inspecting"||!z||A.length===0){X();return}z=!1,_({type:"SELECT"}),n.hideHighlight(),j(!0),n.focusTargetInstruction(R),n.announce(n.messages().announcements.addCancelled)}function Te(){if(d.status==="inspecting"&&z){ae();return}if(d.status!=="idle"){X();return}_({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Me(s=n.messages().announcements.chooseAnother){d.status==="selected"&&(_({type:"RESELECT"}),q(),n.hideHighlight(),n.announce(s))}function _e(){if(d.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}z=!0,_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function oe(){I+=1,ne(),C?.disconnect();for(let s of A)s.element=void 0,s.marker=void 0;n.hideHighlight(),n.hideSelectionHighlights(),j(),n.announce(n.messages().announcements.appliedTargetsDetached)}let P=Mn({ai:e.ai,api:a,getAnnotation:fe,onApplied:oe,onReselectRequired(){Me(n.messages().announcements.reselectAfterChange)},view:n});async function T(s,u){let v=s.marker;if(v!==void 0)try{let U=await a.sourceContext({fileId:v.fileId,line:v.line,column:v.column,maxLines:e.budget.maxCodeLines});te(s,u)&&(s.code=U,s.apiStatus="connected",j(),n.announce(n.messages().announcements.sourceLoaded))}catch(U){te(s,u)&&(s.code=void 0,s.apiStatus="failed",j(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(U instanceof DOMException&&U.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function me(s,u){let v=s.element;if(v===void 0)return;let U=o.window.setTimeout(()=>{if(ie.delete(s.id),!te(s,u))return;let L=!1;try{s.elementContext=ln({element:v,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,L=!0}try{s.styles=nn({document:o.document,element:v,maxCharacters:e.budget.cssCharacters})}catch{s.styles=Or,L=!0}s.collectionStatus=L?"failed":"ready",j(),n.announce(L?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);ie.set(s.id,U)}function se(s,u){return u!==void 0?A.find(v=>v.marker?.fileId===u.fileId&&v.marker.line===u.line&&v.marker.column===u.column):A.find(v=>v.element===s)}function Ne(s){let u=S.resolve(s),v=vn(u.source),U=se(s,v);if(U!==void 0){R=U.id,z=!1,_({type:"SELECT"}),n.hideHighlight(),j(!0),n.focusTargetInstruction(U.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){z=!1,_({type:"SELECT"}),n.hideHighlight(),j(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}A.length===0&&(x=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,g="",P.beginSelection()),M+=1;let Le={id:`target-${String(M)}`,element:s,resolution:u,marker:v,code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:v===void 0?"not-required":"loading",collectionStatus:"loading"};A.push(Le),R=Le.id,z=!1;let Ke=I;_({type:"SELECT"}),n.hideHighlight(),C?.observe(s),j(!0),n.focusTargetInstruction(Le.id),me(Le,Ke),v!==void 0?T(Le,Ke):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function he(){if(m=void 0,d.status!=="inspecting"||k===void 0)return;let s=Lt(o.document,o.window,k.x,k.y);if(_({type:"HOVER"}),s===void 0){n.hideHighlight();return}Ee(s)}function Se(s){d.status==="inspecting"&&(k={x:s.clientX,y:s.clientY},m??=o.window.requestAnimationFrame(he))}function Z(s){if(d.status!=="inspecting"||fn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let u=Lt(o.document,o.window,s.clientX,s.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}Ne(u)}function Q(s){if(s.key==="Escape"&&d.status!=="idle"){s.preventDefault(),d.status==="inspecting"&&z?ae():d.status==="inspecting"||d.status==="selected"?X():(_({type:"BACK"}),n.focusTargetInstruction(R));return}pn(s.target)||!un(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),Te())}function be(s){if(d.status!=="selected"&&d.status!=="inspecting")return;let u=A.findIndex(L=>L.id===s);if(u<0)return;let[v]=A.splice(u,1);if(v===void 0)return;let U=ie.get(v.id);if(U!==void 0&&(o.window.clearTimeout(U),ie.delete(v.id)),v.element!==void 0&&C?.unobserve(v.element),R===v.id&&(R=A.at(-1)?.id),A.length===0){z=!0,d.status==="selected"&&_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),n.announce(n.messages().announcements.allTargetsRemoved);return}j(),n.announce(n.messages().announcements.targetRemoved)}function K(){if(d.status==="idle"||A.length===0)return;let s=A.filter(u=>u.element!==void 0&&!u.element.isConnected);if(s.length>0){d.status==="previewing"&&_({type:"BACK"});for(let u of s)be(u.id);A.length>0&&n.announce(n.messages().announcements.detachedTargetRemoved);return}ge()}function Ae(){let s=xe();if(d.status!=="selected"||s?.marker===void 0)return;let u=s.marker;_({type:"OPEN_EDITOR"}),a.openEditor({fileId:u.fileId,line:u.line,column:u.column}).then(()=>{w&&d.status==="selected"&&n.announce(n.messages().announcements.editorOpened)}).catch(()=>{w&&d.status==="selected"&&n.announce(n.messages().announcements.editorFailed)})}function G(s){if(d.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let u=s.target.dataset.targetInstructionId,v=A.find(U=>U.id===u);v!==void 0&&(v.instruction=s.target.value,n.updateTargetInstruction(v.id,v.instruction),n.setPreviewEnabled(H()))}function Oe(s){e.ai.enabled&&d.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),P.run())}function Pe(){if(d.status!=="selected")return;let s=fe();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}g=r.compose(s),_({type:"PREVIEW"}),n.showPreview(g),n.focusPrompt()}function $e(){if(d.status!=="previewing"||g.length===0)return;if(i===void 0){_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=I;i.writeText(g).then(()=>{w&&s===I&&d.status==="previewing"&&(_({type:"COPY_SUCCESS"}),n.focusTargetInstruction(R),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{w&&s===I&&d.status==="previewing"&&(_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function f(){d.status==="previewing"&&(_({type:"BACK"}),n.focusTargetInstruction(R))}function B(){if(!(!w||A.length===0)&&(j(),d.status==="previewing")){let s=fe();s!==void 0&&(g=r.compose(s),n.showPreview(g))}}function W(s){let u=s.target;if(!(u instanceof Element))return;let v=u.closest("button[data-remove-target-id]");if(v?.dataset.removeTargetId!==void 0){be(v.dataset.removeTargetId);return}let L=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;d.status!=="selected"||L===void 0||!A.some(Le=>Le.id===L)||(R=L,j(),n.focusTargetInstruction(L))}function N(){Me()}function re(){w||(w=!0,n.renderStatus(d.status),o.document.addEventListener("pointermove",Se,!0),o.document.addEventListener("click",Z,!0),o.document.addEventListener("keydown",Q,!0),o.window.addEventListener("scroll",K,!0),o.window.addEventListener("resize",K),n.triggerButton.addEventListener("click",Te),n.addTargetButton.addEventListener("click",_e),n.reselectButton.addEventListener("click",N),n.targetList.addEventListener("click",W),n.targetList.addEventListener("input",G),n.targetList.addEventListener("keydown",Oe),n.openEditorButton.addEventListener("click",Ae),n.previewButton.addEventListener("click",Pe),n.copyButton.addEventListener("click",$e),n.backButton.addEventListener("click",f),n.closeButton.addEventListener("click",X),n.agentProviderSelect.addEventListener("change",P.providerOrModelChanged),n.agentModelSelect.addEventListener("change",P.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",P.consentChanged),n.agentTestButton.addEventListener("click",P.testCapability),n.agentRunButton.addEventListener("click",P.run),n.agentCancelButton.addEventListener("click",P.cancel),n.agentApplyButton.addEventListener("click",P.apply),n.agentRevertButton.addEventListener("click",P.revert),n.agentResetButton.addEventListener("click",P.reset),V=n.subscribeLocale(B),o.resizeObserver!==void 0&&(C=new o.resizeObserver(K)),o.mutationObserver!==void 0&&(O=new o.mutationObserver(K),O.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function qe(){if(!w){V?.(),V=void 0,n.dispose(),a.cancelPending(),a.dispose(),P.disposeSelection(),S.dispose();return}w=!1,V?.(),V=void 0,o.document.removeEventListener("pointermove",Se,!0),o.document.removeEventListener("click",Z,!0),o.document.removeEventListener("keydown",Q,!0),o.window.removeEventListener("scroll",K,!0),o.window.removeEventListener("resize",K),n.triggerButton.removeEventListener("click",Te),n.addTargetButton.removeEventListener("click",_e),n.reselectButton.removeEventListener("click",N),n.targetList.removeEventListener("click",W),n.targetList.removeEventListener("input",G),n.targetList.removeEventListener("keydown",Oe),n.openEditorButton.removeEventListener("click",Ae),n.previewButton.removeEventListener("click",Pe),n.copyButton.removeEventListener("click",$e),n.backButton.removeEventListener("click",f),n.closeButton.removeEventListener("click",X),n.agentProviderSelect.removeEventListener("change",P.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",P.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",P.consentChanged),n.agentTestButton.removeEventListener("click",P.testCapability),n.agentRunButton.removeEventListener("click",P.run),n.agentCancelButton.removeEventListener("click",P.cancel),n.agentApplyButton.removeEventListener("click",P.apply),n.agentRevertButton.removeEventListener("click",P.revert),n.agentResetButton.removeEventListener("click",P.reset),m!==void 0&&(o.window.cancelAnimationFrame(m),m=void 0),ne(),C?.disconnect(),O?.disconnect(),C=void 0,O=void 0,A=[],R=void 0,g="",k=void 0,x=void 0,a.cancelPending(),a.dispose(),P.disposeSelection(),S.dispose(),n.dispose(),d=_t}return Object.freeze({mount:re,dispose:qe,getState:()=>d})}var Bn="__spotpatchRuntime__";function kt(e){let t=globalThis;t[Bn]?.dispose();let o=jn(e);t[Bn]=o,o.mount()}kt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
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});