@spotpatch/vite 1.2.2 → 1.3.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 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 Fe(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 qe="/__spotpatch/v1",st="X-SpotPatch-Token",Ke=Object.freeze({sourceContext:`${qe}/source-context`,openEditor:`${qe}/open-editor`,agentCapability:`${qe}/agent/capability`,agentJobs:`${qe}/agent/jobs`});function We(e,t){return`${Ke.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 Ee(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 tt(e){return ee(e,64,1)&&typeof e=="string"&&ho.test(e)}function _t(e){return ee(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||ee(e,t)}function nt(e){return typeof e=="string"&&uo.has(e)}function Kt(e){return!He(e)||!Ee(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:tt(e.providerProfileId)&&ee(e.providerLabel,100)&&tt(e.modelProfileId)&&ee(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||nt(e.errorCode))}function dt(e){return!He(e)||!Ee(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)&&tt(e.providerProfileId)&&ee(e.providerLabel,100)&&tt(e.modelProfileId)&&ee(e.modelLabel,100)&&ee(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||nt(e.errorCode))}function So(e){return He(e)&&Ee(e,["relativePath","kind","additions","deletions"])&&ee(e.relativePath,1024)&&typeof e.kind=="string"&&mo.has(e.kind)&&It(e.additions)&&It(e.deletions)}function Wt(e){return He(e)&&Ee(e,["checkId","label","status","durationMs","output"])&&tt(e.checkId)&&ee(e.label,100)&&typeof e.status=="string"&&fo.has(e.status)&&It(e.durationMs)&&ee(e.output,8e4)}function Ao(e){return He(e)&&Ee(e,["jobId","summary","diff","files","checks"])&&_t(e.jobId)&&ee(e.summary,8e4)&&ee(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)&&Ee(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)&&Ee(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 Ee(t,["snapshot"])&&dt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Ee(t,["message"])&&ee(t.message,1024);case"tool":return Ee(t,["toolCallId","toolName","state","relativePath","checkLabel"])&&ee(t.toolCallId,256)&&ee(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&Ft(t.relativePath,1024)&&Ft(t.checkLabel,100);case"check":return Ee(t,["result"])&&Wt(t.result);case"result-ready":return Ee(t,["hasResult"])&&t.hasResult===!0;case"error":return Ee(t,["code","message"])&&nt(t.code)&&ee(t.message,1024);default:return!1}}var vo=2e6,Zt=1e5,Co=4e6,k=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ro(e){if(!(!Xe(e)||e.ok!==!1||!Xe(e.error)))return nt(e.error.code)?e.error.code:void 0}function To(e){if(!Xe(e)||e.ok!==!0||!("data"in e))throw new k;return e.data}function wo(e){return Xe(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(!(!Xe(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 k;if(e.body===null)throw new k;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 k;i+=a.decode(c.value,{stream:!0})}}catch(c){throw c instanceof k?c:new k}finally{n.releaseLock()}}function tn(e){try{return JSON.parse(e)}catch{throw new k}}async function Qt(e){let t=tn(await Oo(e,vo));if(!e.ok)throw new k(Ro(t));return To(t)}function Po(e,t){if(!Kt(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new k;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 k;return ut(e)}function Lo(e,t){if(!Yt(e)||e.snapshot.jobId!==t)throw new k;return ut(e)}function Io(e){if(!Xt(e))throw new k;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 k?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(We(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 k;let u=E.body.getReader(),P=new TextDecoder("utf-8",{fatal:!0}),m="",M=0,A=0,v=$=>{if($.trim().length===0)return;if(new TextEncoder().encode($).byteLength>Zt)throw new k;let w=Io(tn($));if(w.jobId!==i||w.sequence<=A)throw new k;A=w.sequence,c(w)};try{for(;;){let $=await u.read();if($.done){m+=P.decode(),v(m);return}if(M+=$.value.byteLength,M>Co)throw await u.cancel(),new k;m+=P.decode($.value,{stream:!0});let w=m.split(`
2
- `);if(m=w.pop()??"",new TextEncoder().encode(m).byteLength>Zt)throw await u.cancel(),new k;for(let Z of w)v(Z)}}catch($){throw $ instanceof k||$ instanceof DOMException&&$.name==="AbortError"?$:new k}finally{u.releaseLock()}}finally{t.delete(y)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(i){let c=await n(Ke.sourceContext,"POST",i);if(!wo(c))throw new k;return Object.freeze({...c})},async openEditor(i){let c=await n(Ke.openEditor,"POST",i);if(!Xe(c)||c.editor!=="auto"&&c.editor!=="vscode"&&c.editor!=="cursor")throw new k;return Object.freeze({editor:c.editor})},async agentCapability(i){return Po(await n(Ke.agentCapability,"POST",i),i)},async createAgentJob(i){let c=_o(i);return pt(await n(Ke.agentJobs,"POST",c),i)},agentEvents:a,async agentResult(i){return Lo(await n(We(i,"result"),"POST",r),i)},async cancelAgentJob(i){return pt(await n(We(i,"cancel"),"POST",r),{jobId:i})},async applyAgentJob(i){return pt(await n(We(i,"apply"),"POST",r),{jobId:i})},async revertAgentJob(i){return pt(await n(We(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"?Fe(t,o):e==="d"&&t.length>rn?`${t.slice(0,rn)}…`:ko(J(t),No)}function xe(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 ot=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:Fe(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(ot.selector);continue}c&&a.push(Object.freeze({selector:xe(i.selectorText),declarations:xe(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=xe(o.getPropertyValue(a).trim());r.length>0&&(n[a]=r)}return n}function ln(e){let t=new Set([ot.state,ot.cssInJs,ot.cascade]),o=[],n=e.readCssRules??(u=>u.cssRules);for(let u of e.document.styleSheets){let P;try{P=n(u)}catch{t.add(ot.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:xe(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 Ye="data-spotpatch-ui",rt=Object.freeze({highlight:2147483646,controls:2147483647});function xn(e){if(e.closest(`[${Ye}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(Ye)}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}
1
+ import{createReact18Adapter as Dr}from"@spotpatch/react-adapter";var h={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_PATH_DENIED:"TOOL_PATH_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,Yn=/blob:[^\s"'<>]+/giu,Xn=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Zn=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Qn=/\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,eo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),to=500;function no(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function oo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ft(e){let t=no(e);return eo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(Kn,"[redacted inline data]").replace(Yn,"[redacted blob URL]").replace(Xn,"Bearer [redacted]").replace(Zn,"$1[redacted]@").replace(Qn,(t,o,n,i)=>{let r=i.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function ro(e){e.username="",e.password="";for(let[t,o]of e.searchParams)ft(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Ze(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let i=new URL(n,t),r=ro(i),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===a.origin?`${i.pathname}${i.search}${i.hash}`:r}catch{return oo(n,to)}}var ao=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}),Lt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),kt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),io=Object.freeze(["ready","consent-required","blocked"]),so=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),_t=Object.freeze(["added","modified","deleted"]),It=Object.freeze(["passed","failed","cancelled","timed-out"]);var Nt="data-spotpatch-source",co=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Mt(e){if(e===null)return;let t=co.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var Ve="/__spotpatch/v1",ht="X-SpotPatch-Token",qe=Object.freeze({sourceContext:`${Ve}/source-context`,openEditor:`${Ve}/open-editor`,agentCapability:`${Ve}/agent/capability`,agentWorkspaceHealth:`${Ve}/agent/workspace-health`,agentJobs:`${Ve}/agent/jobs`});function Qe(e,t){return`${qe.agentJobs}/${encodeURIComponent(e)}/${t}`}var Dt="https://github.com/huanglvjing/spotpatch";function Jt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function po(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Jt(e.source)}})}function uo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function go(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 fo(e){return Object.freeze({instruction:e.instruction.trim(),source:Jt(e.source,e.code),react:po(e.react),element:uo(e.element),styles:go(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function Vt(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(fo)),createdAt:e.createdAt})}var ho=new Set(Object.values(h)),mo=new Set(kt),bo=new Set(It),yo=new Set(_t),Ft=new Set(Lt),xo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,So=/^[A-Za-z0-9_-]+$/,Eo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function ne(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function st(e){return ne(e,64,1)&&typeof e=="string"&&xo.test(e)}function $t(e){return ne(e,128,22)&&typeof e=="string"&&So.test(e)}function ct(e){return typeof e=="string"&&Eo.test(e)&&Number.isFinite(Date.parse(e))}function Fe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ao(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function qt(e,t){return e===void 0||ne(e,t)}function tt(e){return typeof e=="string"&&ho.has(e)}function Kt(e){return!ze(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:st(e.providerProfileId)&&ne(e.providerLabel,100)&&st(e.modelProfileId)&&ne(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&mo.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||ct(e.checkedAt))&&(e.errorCode===void 0||tt(e.errorCode))}function Yt(e){if(!ze(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ct(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!tt(e.errorCode)||!ze(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:r,total:a}=t;return!Fe(o)||!Fe(n)||!Fe(i)||!Fe(r)||!Fe(a)||a<o||a<n||a<i||a<r||a>o+n+i?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function bt(e){return!ze(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:$t(e.jobId)&&typeof e.status=="string"&&Ft.has(e.status)&&st(e.providerProfileId)&&ne(e.providerLabel,100)&&st(e.modelProfileId)&&ne(e.modelLabel,100)&&ne(e.phaseMessage,1024)&&ct(e.createdAt)&&ct(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||tt(e.errorCode))}function Co(e){return ze(e)&&fe(e,["relativePath","kind","additions","deletions"])&&ne(e.relativePath,1024)&&typeof e.kind=="string"&&yo.has(e.kind)&&Fe(e.additions)&&Fe(e.deletions)}function Xt(e){return ze(e)&&fe(e,["checkId","label","status","durationMs","output"])&&st(e.checkId)&&ne(e.label,100)&&typeof e.status=="string"&&bo.has(e.status)&&Fe(e.durationMs)&&ne(e.output,8e4)}function Ro(e){return ze(e)&&fe(e,["jobId","summary","diff","files","checks"])&&$t(e.jobId)&&ne(e.summary,8e4)&&ne(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Co)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(Xt)}function Zt(e){return ze(e)&&fe(e,["snapshot","result"])&&bt(e.snapshot)&&(e.result===void 0||Ro(e.result)&&e.result.jobId===e.snapshot.jobId)}function vo(e){return ze(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===1&&Ao(e.sequence)&&$t(e.jobId)&&typeof e.status=="string"&&Ft.has(e.status)&&ct(e.timestamp)&&typeof e.type=="string"&&ze(e.data)}function Qt(e){if(!vo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&bt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&ne(t.message,1024);case"tool":return fe(t,["toolCallId","toolName","state","relativePath","checkLabel"])&&ne(t.toolCallId,256)&&ne(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&qt(t.relativePath,1024)&&qt(t.checkLabel,100);case"check":return fe(t,["result"])&&Xt(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&tt(t.code)&&ne(t.message,1024);default:return!1}}var To=2e6,en=1e5,wo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oo(e){if(!(!nt(e)||e.ok!==!1||!nt(e.error)))return tt(e.error.code)?e.error.code:void 0}function Po(e){if(!nt(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function Lo(e){return nt(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 nn(e){if(!(!nt(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))nn(t);Object.freeze(e)}}function lt(e){return nn(e),e}async function ko(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let c=await n.read();if(c.done)return a+=i.decode(),a;if(r+=c.value.byteLength,r>t)throw await n.cancel(),new M;a+=i.decode(c.value,{stream:!0})}}catch(c){throw c instanceof M?c:new M}finally{n.releaseLock()}}function on(e){try{return JSON.parse(e)}catch{throw new M}}async function tn(e){let t=on(await ko(e,To));if(!e.ok)throw new M(Oo(t));return Po(t)}function _o(e,t){if(!Kt(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return lt(e)}function yt(e,t){if(!bt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return lt(e)}function Io(e,t){if(!Zt(e)||e.snapshot.jobId!==t)throw new M;return lt(e)}function No(e){if(!Qt(e))throw new M;return lt(e)}function Mo(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 rn(e){return e instanceof M?e.code:void 0}function an(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,c,S){let C=new AbortController;t.add(C);try{let u=await e.fetch(a,{method:c,headers:{...S===void 0?{}:{"Content-Type":"application/json"},[ht]:e.sessionToken},...S===void 0?{}:{body:JSON.stringify(S)},signal:C.signal});return await tn(u)}finally{t.delete(C)}}async function i(a,c){let S=new AbortController;t.add(S);try{let C=await e.fetch(Qe(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[ht]:e.sessionToken},body:JSON.stringify({}),signal:S.signal});if(!C.ok){await tn(C);return}if(C.body===null)throw new M;let u=C.body.getReader(),k=new TextDecoder("utf-8",{fatal:!0}),b="",N=0,A=0,R=D=>{if(D.trim().length===0)return;if(new TextEncoder().encode(D).byteLength>en)throw new M;let P=No(on(D));if(P.jobId!==a||P.sequence<=A)throw new M;A=P.sequence,c(P)};try{for(;;){let D=await u.read();if(D.done){b+=k.decode(),R(b);return}if(N+=D.value.byteLength,N>wo)throw await u.cancel(),new M;b+=k.decode(D.value,{stream:!0});let P=b.split(`
2
+ `);if(b=P.pop()??"",new TextEncoder().encode(b).byteLength>en)throw await u.cancel(),new M;for(let Z of P)R(Z)}}catch(D){throw D instanceof M||D instanceof DOMException&&D.name==="AbortError"?D:new M}finally{u.releaseLock()}}finally{t.delete(S)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let c=await n(qe.sourceContext,"POST",a);if(!Lo(c))throw new M;return Object.freeze({...c})},async openEditor(a){let c=await n(qe.openEditor,"POST",a);if(!nt(c)||c.editor!=="auto"&&c.editor!=="vscode"&&c.editor!=="cursor")throw new M;return Object.freeze({editor:c.editor})},async agentCapability(a){return _o(await n(qe.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(qe.agentWorkspaceHealth,"POST",r);if(!Yt(a))throw new M;return lt(a)},async createAgentJob(a){let c=Mo(a);return yt(await n(qe.agentJobs,"POST",c),a)},agentEvents:i,async agentResult(a){return Io(await n(Qe(a,"result"),"POST",r),a)},async cancelAgentJob(a){return yt(await n(Qe(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return yt(await n(Qe(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return yt(await n(Qe(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var Do=500,sn=256;function $o(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function zo(e){return ft(e)}function cn(e,t,o){if(!zo(e))return e==="href"||e==="src"?Ze(t,o):e==="d"&&t.length>sn?`${t.slice(0,sn)}…`:$o(G(t),Do)}function xe(e){return G(e)}var ln=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 dt=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 jo(e){return"selectorText"in e&&"style"in e}function Uo(e){return"cssRules"in e}function Bo(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 Ho(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((r,a)=>r+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((r,[a,c])=>r+a.length+c.length,0)+i.join(`
3
+ `).length}function Go(e,t){return e.href===null?void 0:Ze(e.href,t)}function dn(e,t,o,n,i,r){for(let a of t){if(jo(a)){let c=!1;try{c=e.matches(a.selectorText)}catch{r.add(dt.selector);continue}c&&i.push(Object.freeze({selector:xe(a.selectorText),declarations:xe(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Uo(a)){let c=Bo(a);dn(e,a.cssRules,o,c===void 0?n:[...n,c],i,r)}}}function Wo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of ln){let r=xe(o.getPropertyValue(i).trim());r.length>0&&(n[i]=r)}return n}function pn(e){let t=new Set([dt.state,dt.cssInJs,dt.cascade]),o=[],n=e.readCssRules??(u=>u.cssRules);for(let u of e.document.styleSheets){let k;try{k=n(u)}catch{t.add(dt.inaccessibleStylesheet);continue}dn(e.element,k,Go(u,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:xe(r),c=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),S=Object.entries(Wo(e.element,c)),C=Array.from(t);for(;Ho(i,a,o,Object.fromEntries(S),C)>e.maxCharacters;){if(S.length>0){S.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(S)),warnings:Object.freeze(C)})}var Ke=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Jo=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"]),Vo=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function gn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function qo(e){return Jo.has(e)||e.startsWith("aria-")||e==="data-testid"}function fn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let r=i.name.toLowerCase();if(!qo(r))continue;let a=cn(r,i.value,n);a!==void 0&&o.push(`${r}="${gn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function hn(e){return G(e).replaceAll(/\s+/gu," ").trim()}function mn(e,t,o,n){if(o.nodeCount>=Ke.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${i}${fn(e)}`),!Vo.has(r)){for(let a of e.childNodes){if(o.nodeCount>=Ke.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let c=hn(a.textContent??"");if(c.length>0){o.nodeCount+=1;let S=c.length<=Ke.maxTextCharacters?c:`${c.slice(0,Ke.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${gn(S)}`)}continue}if(a.nodeType===1){if(t>=Ke.maxDepth){o.truncated=!0;continue}mn(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${r}>`)}}function Fo(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Ke.maxParentDepth;)t.push(fn(o)),o=o.parentElement;return t}function Ko(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function un(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Yo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Xo(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${un(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Yo(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(c=>`.${un(c)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(c=>c.tagName===e.tagName),r=i.indexOf(e),a=i.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function Zo(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Xo(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function bn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};mn(e.element,0,o,t);let n=Fo(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=hn(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:Zo(e.element),sanitizedHtml:Ko(t.join(`
4
+ `),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=Ke.maxTextCharacters?i:`${i.slice(0,Ke.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function yn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Qo(e){return e.toLowerCase()}function xn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Sn(e,t,o){let n=t.split("+").map(u=>u.trim().toLowerCase()).filter(u=>u.length>0),i=n.find(u=>u!=="mod"&&u!=="meta"&&u!=="ctrl"&&u!=="control"&&u!=="alt"&&u!=="option"&&u!=="shift");if(i===void 0||Qo(e.key)!==i)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&yn(o),c=n.includes("ctrl")||n.includes("control")||r&&!yn(o),S=n.includes("alt")||n.includes("option"),C=n.includes("shift");return e.metaKey===a&&e.ctrlKey===c&&e.altKey===S&&e.shiftKey===C}function er(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function tr(e){let t=e.filter(c=>c.width>0&&c.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,r=o.right,a=o.bottom;for(let c of t.slice(1))n=Math.min(n,c.left),i=Math.min(i,c.top),r=Math.max(r,c.right),a=Math.max(a,c.bottom);return Object.freeze({x:n,y:i,width:r-n,height:a-i})}function zt(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=tr(Array.from(e.getClientRects()));if(n!==void 0)return n}return er(e.getBoundingClientRect())}var et="data-spotpatch-ui",pt=Object.freeze({highlight:2147483646,controls:2147483647});function En(e){if(e.closest(`[${et}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(et)}function nr(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 or(e){return e.tagName==="HTML"||e.tagName==="BODY"}function jt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(r=>!En(r)&&nr(r,t));return i.find(r=>!or(r))??i[0]}function An(e){return e instanceof Element&&En(e)}var Ut=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 rr(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function xt(e,t){let o="`".repeat(Math.max(3,rr(t)+1));return`${o}${e}
5
5
  ${t}
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: ${xe(e.source)} */`,e.media===void 0?void 0:`/* condition: ${xe(e.media)} */`].filter(n=>n!==void 0),o=`${xe(e.selector)} {
6
+ ${o}`}function Rn(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${G(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function vn(e,t){return e.split(`
7
+ `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function ar(e){let t=[e.source===void 0?void 0:`/* source: ${xe(e.source)} */`,e.media===void 0?void 0:`/* condition: ${xe(e.media)} */`].filter(n=>n!==void 0),o=`${xe(e.selector)} {
8
8
  ${xe(e.declarations)}
9
9
  }`;return[...t,o].join(`
10
- `)}function or(e,t,o){let a=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(xe).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${xe(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(nr)];return a.length===0?o.unavailable:gt("css",a.join(`
10
+ `)}function ir(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(xe).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${xe(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(ar)];return i.length===0?o.unavailable:xt("css",i.join(`
11
11
 
12
- `))}function rr(e,t){return e.length===0?t.unavailable:gt("css",e.map(([o,n])=>`${xe(o)}: ${xe(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}
12
+ `))}function sr(e,t){return e.length===0?t.unavailable:xt("css",e.map(([o,n])=>`${xe(o)}: ${xe(n)};`).join(`
13
+ `))}function cr(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${G(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${G(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(G).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
14
14
 
15
- ${gt(e.code.language,J(t.codeLines.join(`
16
- `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,a.join(`
17
- `),`#### ${n.source}`,`- ${n.file}: ${En(e,n)}
15
+ ${xt(e.code.language,G(t.codeLines.join(`
16
+ `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,i.join(`
17
+ `),`#### ${n.source}`,`- ${n.file}: ${Rn(e,n)}
18
18
  - ${n.origin}: ${e.source.origin}
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(`
19
+ - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,xt("html",G(t.dom)),`#### ${n.styles}`,ir(e,t.matchedRules,n),`#### ${n.computedStyles}`,sr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${G(a)}`).join(`
20
20
  `)].join(`
21
21
 
22
- `)}function An(e,t){let o=Fe(e.page.url,e.page.url),n=Mt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
23
- - ${n.pathname}: ${J(e.page.pathname)}
22
+ `)}function Cn(e,t){let o=Ze(e.page.url,e.page.url),n=Ut[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
23
+ - ${n.pathname}: ${G(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 ir(a,i,r,n)}).join(`
26
+ - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((i,r)=>{let a=t.targets[r];if(a===void 0)throw new RangeError("Prompt target draft is missing.");return cr(i,a,r,n)}).join(`
27
27
 
28
28
  `),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
29
29
 
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(`
30
+ `)}function lr(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let a=t.codeLines[0]??"";return a.length<=120?t.codeLines=[]:t.codeLines=[`${a.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function dr(e){return{instruction:G(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 pr(e){return{pageTitle:G(e.page.title),targets:e.targets.map(dr)}}function ur(e,t,o){let n=Ut[e.locale],i=[(r,a)=>a.computedEntries.pop()!==void 0,(r,a)=>a.reactStack.pop()!==void 0,(r,a)=>{let c=vn(a.dom,n.unavailable);return a.dom===c?!1:(a.dom=c,!0)},(r,a)=>a.matchedRules.shift()!==void 0,lr,(r,a)=>a.warnings.pop()!==void 0];for(let r of i)for(let a=0;a<e.targets.length;a+=1){let c=(o+a)%e.targets.length,S=e.targets[c],C=t.targets[c];if(S!==void 0&&C!==void 0&&r(S,C))return(c+1)%e.targets.length}}function gr(e,t){let o=Ut[e.locale],n=e.targets.map((i,r)=>{let a=t.targets[r],c=i.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${a?.instruction??G(i.instruction)}`,`- ${o.file}: ${Rn(i,o)}`,...c===void 0?[]:[`- ${o.component}: ${G(c)}`],`- ${o.element}: ${G(vn(a?.dom??i.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 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 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 ur(e){return e.type==="ACTIVATE"?de.inspecting:de.idle}function gr(e){switch(e.type){case"HOVER":return de.inspecting;case"SELECT":return de.selected;case"CANCEL":return de.idle;default:return de.inspecting}}function fr(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 mr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return de.selected;case"COPY_FAILURE":return de.previewing;default:return de.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(Ye,""),o}function G(e,t,o=""){let n=l(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var _n=`
35
+ `)}function fr(e,t){let o=pr(e),n=Cn(e,o),i=0;for(;n.length>t;){let a=ur(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=Cn(e,o)}if(n.length<=t)return n;let r=gr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function Tn(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 fr(t,e.maxCharacters)}})}var he=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Bt=he.idle;function hr(e){return e.type==="ACTIVATE"?he.inspecting:he.idle}function mr(e){switch(e.type){case"HOVER":return he.inspecting;case"SELECT":return he.selected;case"CANCEL":return he.idle;default:return he.inspecting}}function br(e){switch(e.type){case"RESELECT":return he.inspecting;case"CLOSE":return he.idle;case"PREVIEW":return he.previewing;case"OPEN_EDITOR":return he.selected;default:return he.selected}}function yr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return he.selected;case"COPY_FAILURE":return he.previewing;default:return he.previewing}}function wn(e,t){switch(e.status){case"idle":return hr(t);case"inspecting":return mr(t);case"selected":return br(t);case"previewing":return yr(t)}}var On=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Ln(e){return Mt(e.getAttribute(Nt))}function xr(e){let t=e.parentElement;for(;t!==null;){let o=Ln(t);if(o!==void 0)return o;t=t.parentElement}}function Pn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Sr(){return Object.freeze({origin:"none",confidence:"unknown"})}function kn(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 _n(e){let t=!0;function o(n){if(!t)return On;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),On}}return Object.freeze({resolve(n){let i=Ln(n),r=o(n);if(i!==void 0)return Object.freeze({react:r,source:Pn(i,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let a=xr(n);return Object.freeze(a!==void 0?{react:r,source:Pn(a,"dom-ancestor","approximate")}:{react:r,source:Sr()})},dispose(){t=!1,e.adapter.dispose()}})}function l(e,t){let o=e.createElement(t);return o.setAttribute(et,""),o}function F(e,t,o=""){let n=l(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Nn=`
36
36
  .spotpatch-agent {
37
37
  margin-top: 14px;
38
38
  overflow: hidden;
@@ -68,15 +68,62 @@ ${gt(e.code.language,J(t.codeLines.join(`
68
68
  min-height: 46px;
69
69
  margin-top: 7px;
70
70
  border: 1px solid var(--spotpatch-border);
71
- border-radius: 10px;
72
- padding: 8px 30px 8px 10px;
71
+ border-radius: 12px;
72
+ padding: 10px 38px 10px 13px;
73
73
  color: #e8ebf2;
74
74
  color-scheme: dark;
75
- background: var(--spotpatch-bg-raised);
75
+ background: linear-gradient(180deg, rgb(255 255 255 / 4%), rgb(255 255 255 / 2%));
76
76
  font-size: 15px;
77
+ font-weight: 560;
78
+ line-height: 1.35;
77
79
  outline: none;
80
+ transition: 160ms ease;
81
+ }
82
+ .spotpatch-agent select:hover { border-color: rgb(148 163 184 / 38%); background-color: rgb(255 255 255 / 5%); }
83
+ .spotpatch-agent select:focus-visible { border-color: rgb(139 124 247 / 76%); box-shadow: 0 0 0 3px rgb(109 93 246 / 18%); }
84
+ .spotpatch-agent select option { min-height: 42px; color: #e8ebf2; background: #10151e; }
85
+ @supports (appearance: base-select) {
86
+ .spotpatch-agent select,
87
+ ::picker(select) { appearance: base-select; }
88
+ .spotpatch-agent select { padding: 10px 13px; }
89
+ .spotpatch-agent select::picker-icon {
90
+ color: #9da6b5;
91
+ transition: rotate 180ms cubic-bezier(.2, .8, .2, 1);
92
+ }
93
+ .spotpatch-agent select:open::picker-icon { rotate: 180deg; color: #c4b5fd; }
94
+ .spotpatch-agent select::picker(select) {
95
+ top: calc(anchor(bottom) + 7px);
96
+ left: anchor(left);
97
+ width: anchor-size(width);
98
+ max-height: min(280px, 40vh);
99
+ margin: 0;
100
+ overflow: hidden;
101
+ border: 1px solid rgb(139 124 247 / 28%);
102
+ border-radius: 12px;
103
+ padding: 6px;
104
+ background: #10151e;
105
+ box-shadow: 0 18px 50px rgb(0 0 0 / 38%);
106
+ opacity: 0;
107
+ transform: translateY(-5px) scale(.985);
108
+ transition: opacity 150ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1), overlay 180ms allow-discrete, display 180ms allow-discrete;
109
+ }
110
+ ::picker(select):popover-open { opacity: 1; transform: translateY(0) scale(1); }
111
+ @starting-style {
112
+ ::picker(select):popover-open { opacity: 0; transform: translateY(-5px) scale(.985); }
113
+ }
114
+ .spotpatch-agent select option {
115
+ min-height: 42px;
116
+ border-radius: 8px;
117
+ padding: 10px 12px;
118
+ color: #dfe4ee;
119
+ background: transparent;
120
+ cursor: pointer;
121
+ }
122
+ .spotpatch-agent select option:hover,
123
+ .spotpatch-agent select option:focus { color: #fff; background: rgb(109 93 246 / 16%); }
124
+ .spotpatch-agent select option:checked { color: #fff; background: rgb(109 93 246 / 24%); }
125
+ .spotpatch-agent select option::checkmark { color: #8b7cf7; }
78
126
  }
79
- .spotpatch-agent select option { color: #e8ebf2; background: #10151e; }
80
127
  .spotpatch-agent select:focus-visible,
81
128
  .spotpatch-consent input:focus-visible {
82
129
  outline: 2px solid #8b7cf7;
@@ -93,11 +140,22 @@ ${gt(e.code.language,J(t.codeLines.join(`
93
140
  line-height: 1.6;
94
141
  }
95
142
  .spotpatch-consent input { width: 16px; height: 16px; flex: none; margin: 3px 0 0; accent-color: var(--spotpatch-accent); }
143
+ .spotpatch-workspace-consent {
144
+ margin-top: 12px;
145
+ border: 1px solid rgb(251 191 36 / 18%);
146
+ border-radius: 10px;
147
+ padding: 11px 12px;
148
+ background: rgb(120 53 15 / 9%);
149
+ }
150
+ .spotpatch-workspace-consent strong { display: block; color: #fde68a; font-size: 13px; font-weight: 620; }
151
+ .spotpatch-workspace-consent small { display: block; margin-top: 2px; color: #aeb6c4; font-size: 12px; line-height: 1.5; }
152
+ .spotpatch-agent-health-list { display: grid; gap: 8px; margin-top: 14px; }
153
+ .spotpatch-agent-workspace,
96
154
  .spotpatch-agent-capability {
97
155
  display: flex;
98
156
  align-items: center;
99
157
  gap: 8px;
100
- margin: 14px 0 0;
158
+ margin: 0;
101
159
  color: #929bab;
102
160
  font-size: 13px;
103
161
  }
@@ -114,6 +172,21 @@ ${gt(e.code.language,J(t.codeLines.join(`
114
172
  .spotpatch-agent-capability[data-state="ready"]::before { background: var(--spotpatch-success); }
115
173
  .spotpatch-agent-capability[data-state="error"] { color: #fecaca; }
116
174
  .spotpatch-agent-capability[data-state="error"]::before { background: var(--spotpatch-danger); }
175
+ .spotpatch-agent-workspace::before {
176
+ width: 6px;
177
+ height: 6px;
178
+ flex: none;
179
+ border-radius: 999px;
180
+ background: #64748b;
181
+ content: "";
182
+ }
183
+ .spotpatch-agent-workspace[data-state="checking"]::before { background: var(--spotpatch-warning); }
184
+ .spotpatch-agent-workspace[data-state="ready"] { color: #a7f3d0; }
185
+ .spotpatch-agent-workspace[data-state="ready"]::before { background: var(--spotpatch-success); }
186
+ .spotpatch-agent-workspace[data-state="consent-required"] { color: #fde68a; }
187
+ .spotpatch-agent-workspace[data-state="consent-required"]::before { background: #fbbf24; }
188
+ .spotpatch-agent-workspace[data-state="blocked"] { color: #fecaca; }
189
+ .spotpatch-agent-workspace[data-state="blocked"]::before { background: var(--spotpatch-danger); }
117
190
  .spotpatch-agent-job { padding: 16px; }
118
191
  .spotpatch-agent-job-meta { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
119
192
  .spotpatch-agent-model { min-width: 0; overflow: hidden; color: #d6dafe; font-size: 13px; text-overflow: ellipsis; white-space: nowrap; }
@@ -164,7 +237,7 @@ ${gt(e.code.language,J(t.codeLines.join(`
164
237
  white-space: pre;
165
238
  user-select: text;
166
239
  }
167
- `;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 M=l(e,"label"),A=l(e,"span"),v=l(e,"select");M.append(A,v),E.append(u,M);let $=l(e,"label");$.className="spotpatch-consent";let w=l(e,"input");w.type="checkbox";let Z=l(e,"span");$.append(w,Z);let g=l(e,"p");g.className="spotpatch-agent-capability",g.dataset.state="idle",y.append(E,$,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 pe=l(e,"p");pe.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 ve=l(e,"div");ve.className="spotpatch-agent-result",ve.hidden=!0;let ue=l(e,"p");ue.className="spotpatch-agent-summary";let z=l(e,"ul");z.className="spotpatch-agent-files";let Pe=l(e,"div");Pe.className="spotpatch-agent-checks";let ae=l(e,"pre");ae.className="spotpatch-agent-diff",ae.tabIndex=0,ae.setAttribute("aria-label",n.agent.diffAriaLabel),ve.append(ue,z,Pe,ae),x.append(C,pe,F,I,ve),a.append(r,y,x);let U=G(e,n.agent.testConnection),ge=G(e,n.agent.verifyAndRun,"spotpatch-run"),_e=G(e,n.agent.cancel),Le=G(e,n.agent.apply,"spotpatch-primary"),te=G(e,n.agent.revert),Y=G(e,n.agent.revise),fe=t.enabled?t.providers:[],me=new Map(fe.map(f=>[f.id,f])),Ce=!1,$e=!0,Se=!1,ne=!1,L=!1,O=!1,Re,he,De=[],se,Q="idle",Ae=n.agent.connectionNotTested,oe;for(let f of fe)In(e,m,f.id,f.label);t.enabled&&(m.value=t.defaultProvider);let q=()=>me.get(m.value),be=()=>{let f=q();if(v.replaceChildren(),f===void 0){Z.textContent=n.agent.providerUnavailable;return}for(let j of f.models)In(e,v,j.id,j.label);v.value=f.defaultModel,Z.textContent=n.agent.consent(f.label)},K=()=>{let f=t.enabled&&Se&&!ne;ge.textContent=L?n.agent.verifying:O?n.agent.run:n.agent.verifyAndRun,ge.classList.toggle("spotpatch-primary",O),U.hidden=!f,ge.hidden=!f,U.disabled=!$e||L||q()===void 0,ge.disabled=!$e||L||!Ce||!w.checked||q()===void 0||v.value.length===0,(!ne||!Se)&&(_e.hidden=!0,Le.hidden=!0,te.hidden=!0,Y.hidden=!0)};function Te(){be(),w.checked=!1,g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Q="idle",Ae=n.agent.connectionNotTested,oe=void 0,O=!1,K()}function we(){g.dataset.state="idle",g.textContent=n.agent.connectionNotTested,Q="idle",Ae=n.agent.connectionNotTested,oe=void 0,O=!1,K()}be(),m.addEventListener("change",Te),v.addEventListener("change",we),w.addEventListener("change",K);function Ne(){if(Re===void 0)return;let f=Re,j=he;R.textContent=`${f.providerLabel} · ${f.modelLabel}`,H.textContent=n.agent.status(f.status),pe.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 _ of De.slice(-8)){let re=l(e,"li");re.dataset.state=_.state,re.textContent=_.label,I.append(re)}ve.hidden=j===void 0,ue.textContent=j?.summary??"",z.replaceChildren(),Pe.replaceChildren(),ae.textContent=j?.diff??"";for(let _ of j?.files??[]){let re=l(e,"li");re.textContent=`${_.kind} ${_.relativePath} (+${String(_.additions)} / -${String(_.deletions)})`,z.append(re)}for(let _ of j?.checks??[]){let re=l(e,"details"),Ve=l(e,"summary");Ve.textContent=`${_.label}: ${_.status} · ${String(_.durationMs)} ms`;let s=l(e,"pre");s.textContent=_.output.length===0?n.agent.noOutput:_.output,re.append(Ve,s),Pe.append(re)}U.hidden=!0,ge.hidden=!0,_e.hidden=!Se||!f.canCancel,_e.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,Le.hidden=!Se||!f.canApply,te.hidden=!Se||!f.canRevert,Y.hidden=!Se||!["completed","cancelled","reverted","failed"].includes(f.status)}function ke(){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,Le.textContent=n.agent.apply,te.textContent=n.agent.revert,Y.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}`:oe!==void 0?g.textContent=n.errors[oe]:q()===void 0?g.textContent=n.agent.providerUnavailable:g.textContent=Ae,K(),Ne()}let Be=o.subscribe(ke);return ke(),Object.freeze({root:a,providerSelect:m,modelSelect:v,consentCheckbox:w,testButton:U,runButton:ge,cancelButton:_e,applyButton:Le,revertButton:te,resetButton:Y,consentGranted(){return w.checked},readSelection(){let f=q(),j=f?.models.find(X=>X.id===v.value);return f===void 0||j===void 0?void 0:Object.freeze({providerProfileId:f.id,modelProfileId:j.id})},renderCapability(f,j,X,_){Q=f,Ae=j,oe=_,L=f==="probing",O=f==="ready"&&X?.state==="agent-ready",g.dataset.state=f,g.textContent=X?.state==="agent-ready"?`${j} · ${n.agent.toolsReady}`:j,K()},renderJob(f,j,X,_){ne=!0,y.hidden=!0,x.hidden=!1,m.disabled=!0,v.disabled=!0,w.disabled=!0,Re=f,he=j,De=X,se=_,Ne()},resetJob(){ne=!1,Re=void 0,he=void 0,De=[],se=void 0,y.hidden=!1,x.hidden=!0,m.disabled=!1,v.disabled=!1,w.disabled=!1,I.replaceChildren(),z.replaceChildren(),Pe.replaceChildren(),ae.textContent="",F.textContent="",F.hidden=!0,K()},setContextReady(f){Ce=f,K()},setEditingEnabled(f){$e=f,m.disabled=!f||ne,v.disabled=!f||ne,w.disabled=!f||ne,K()},setProviderConsent(f){w.checked=f,K()},setSelectionVisible(f){Se=f,K(),f||(_e.hidden=!0,Le.hidden=!0,te.hidden=!0,Y.hidden=!0)},dispose(){Be(),m.removeEventListener("change",Te),v.removeEventListener("change",we),w.removeEventListener("change",K)}})}var yr="http://www.w3.org/2000/svg";function Ie(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=Ie(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=Ie(e,"defs",{}),n=Ie(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(Ie(e,"stop",{offset:"0","stop-color":"#7c22ff"}),Ie(e,"stop",{offset:".52","stop-color":"#4a69ff"}),Ie(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=Ie(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=Ie(e,"path",{d:"M106 25v42",...a,"stroke-width":"14"}),c=Ie(e,"path",{d:"M35 109h20m102 0h38",...a,"stroke-width":"13"}),y=Ie(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...a,"stroke-width":"9"}),E=Ie(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,M="viewport";return o.width>=t+48&&o.height>=e+48?M="center":o.y-e-14>=16?(m=o.y-e-14,M="above"):o.y+o.height+14+e<=n-16?(m=o.y+o.height+14,M="below"):o.x+o.width+14+t<=a-16?(P=o.x+o.width+14,M="right"):o.x-t-14>=16&&(P=o.x-t-14,M="left"),Object.freeze({anchorX:ft(c-P,22,t-22),anchorY:ft(y-m,22,e-22),left:P,mode:M,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=`
240
+ `;function In(e,t,o,n){let i=e.createElement("option");i.value=o,i.textContent=n,t.append(i)}function Mn(e,t,o){let n=o.messages(),i=l(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=l(e,"div");r.className="spotpatch-agent-head";let a=l(e,"span");a.className="spotpatch-agent-title";let c=l(e,"span");c.className="spotpatch-agent-badge",r.append(a,c);let S=l(e,"div");S.className="spotpatch-agent-setup";let C=l(e,"div");C.className="spotpatch-agent-selectors";let u=l(e,"label"),k=l(e,"span"),b=l(e,"select");u.append(k,b);let N=l(e,"label"),A=l(e,"span"),R=l(e,"select");N.append(A,R),C.append(u,N);let D=l(e,"label");D.className="spotpatch-consent";let P=l(e,"input");P.type="checkbox";let Z=l(e,"span");D.append(P,Z);let B=l(e,"label");B.className="spotpatch-consent spotpatch-workspace-consent",B.hidden=!0;let f=l(e,"input");f.type="checkbox";let y=l(e,"span"),E=l(e,"strong"),L=l(e,"small");y.append(E,L),B.append(f,y);let U=l(e,"div");U.className="spotpatch-agent-health-list";let W=l(e,"p");W.className="spotpatch-agent-workspace",W.dataset.state="idle";let T=l(e,"p");T.className="spotpatch-agent-capability",T.dataset.state="idle",U.append(W,T),S.append(C,D,B,U);let Se=l(e,"div");Se.className="spotpatch-agent-job",Se.hidden=!0;let me=l(e,"div");me.className="spotpatch-agent-job-meta";let H=l(e,"span");H.className="spotpatch-agent-model";let je=l(e,"span");je.className="spotpatch-agent-status",me.append(H,je);let Pe=l(e,"p");Pe.className="spotpatch-agent-phase";let z=l(e,"p");z.className="spotpatch-agent-error",z.hidden=!0;let Ee=l(e,"ul");Ee.className="spotpatch-agent-activity";let Ne=l(e,"div");Ne.className="spotpatch-agent-result",Ne.hidden=!0;let Ue=l(e,"p");Ue.className="spotpatch-agent-summary";let oe=l(e,"ul");oe.className="spotpatch-agent-files";let Q=l(e,"div");Q.className="spotpatch-agent-checks";let K=l(e,"pre");K.className="spotpatch-agent-diff",K.tabIndex=0,K.setAttribute("aria-label",n.agent.diffAriaLabel),Ne.append(Ue,oe,Q,K),Se.append(me,Pe,z,Ee,Ne),i.append(r,S,Se);let ee=F(e,n.agent.testConnection),re=F(e,n.agent.verifyAndRun,"spotpatch-run"),Le=F(e,n.agent.cancel),ke=F(e,n.agent.apply,"spotpatch-primary"),be=F(e,n.agent.revert),_=F(e,n.agent.revise),O=t.enabled?t.providers:[],Be=new Map(O.map(g=>[g.id,g])),Ae=!1,He=!0,Y=!1,X=!1,Ce=!1,ae=!1,te,le,_e=[],Re,ie="idle",Te=n.agent.connectionNotTested,ve,se="idle",Me,De;for(let g of O)In(e,b,g.id,g.label);t.enabled&&(b.value=t.defaultProvider);let ye=()=>Be.get(b.value),de=()=>{let g=ye();if(R.replaceChildren(),g===void 0){Z.textContent=n.agent.providerUnavailable;return}for(let w of g.models)In(e,R,w.id,w.label);R.value=g.defaultModel,Z.textContent=n.agent.consent(g.label)},J=()=>{let g=t.enabled&&Y&&!X;re.textContent=Ce?n.agent.verifying:ae?n.agent.run:n.agent.verifyAndRun,re.classList.toggle("spotpatch-primary",ae),ee.hidden=!g,re.hidden=!g,ee.disabled=!He||Ce||ye()===void 0,re.disabled=!He||Ce||!Ae||!P.checked||se==="idle"||se==="checking"||se==="blocked"||se==="consent-required"&&!f.checked||ye()===void 0||R.value.length===0,(!X||!Y)&&(Le.hidden=!0,ke.hidden=!0,be.hidden=!0,_.hidden=!0)},Ye=()=>{if(se==="idle")W.textContent=n.agent.workspaceNotChecked;else if(se==="checking")W.textContent=n.agent.checkingWorkspace;else if(se==="ready")W.textContent=n.agent.workspaceReady;else if(se==="consent-required"){let g=Me?.changes;W.textContent=n.agent.workspaceDirty(g?.staged??0,g?.unstaged??0,g?.untracked??0)}else W.textContent=De===void 0?n.errors.INTERNAL_ERROR:n.errors[De]};function s(){de(),P.checked=!1,T.dataset.state="idle",T.textContent=n.agent.connectionNotTested,ie="idle",Te=n.agent.connectionNotTested,ve=void 0,ae=!1,J()}function p(){T.dataset.state="idle",T.textContent=n.agent.connectionNotTested,ie="idle",Te=n.agent.connectionNotTested,ve=void 0,ae=!1,J()}de(),b.addEventListener("change",s),R.addEventListener("change",p),P.addEventListener("change",J),f.addEventListener("change",J);function x(){if(te===void 0)return;let g=te,w=le;H.textContent=`${g.providerLabel} · ${g.modelLabel}`,je.textContent=n.agent.status(g.status),Pe.textContent=g.phaseMessage;let pe=Re??g.errorCode;z.hidden=pe===void 0,z.textContent=pe===void 0?"":n.errors[pe],Ee.replaceChildren();for(let V of _e.slice(-8)){let we=l(e,"li");we.dataset.state=V.state,we.textContent=V.label,Ee.append(we)}Ne.hidden=w===void 0,Ue.textContent=w?.summary??"",oe.replaceChildren(),Q.replaceChildren(),K.textContent=w?.diff??"";for(let V of w?.files??[]){let we=l(e,"li");we.textContent=`${V.kind} ${V.relativePath} (+${String(V.additions)} / -${String(V.deletions)})`,oe.append(we)}for(let V of w?.checks??[]){let we=l(e,"details"),ot=l(e,"summary");ot.textContent=`${V.label}: ${V.status} · ${String(V.durationMs)} ms`;let ut=l(e,"pre");ut.textContent=V.output.length===0?n.agent.noOutput:V.output,we.append(ot,ut),Q.append(we)}ee.hidden=!0,re.hidden=!0,Le.hidden=!Y||!g.canCancel,Le.textContent=g.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ke.hidden=!Y||!g.canApply,be.hidden=!Y||!g.canRevert,_.hidden=!Y||!["completed","cancelled","reverted","failed"].includes(g.status)}function I(){n=o.messages(),a.textContent=n.agent.title,c.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,k.textContent=n.agent.provider,A.textContent=n.agent.model,b.setAttribute("aria-label",n.agent.providerAriaLabel),R.setAttribute("aria-label",n.agent.modelAriaLabel),E.textContent=n.agent.includeLocalChanges,L.textContent=n.agent.includeLocalChangesHelp,K.setAttribute("aria-label",n.agent.diffAriaLabel),ee.textContent=n.agent.testConnection,ke.textContent=n.agent.apply,be.textContent=n.agent.revert,_.textContent=n.agent.revise;let g=ye();Z.textContent=g===void 0?n.agent.providerUnavailable:n.agent.consent(g.label),ie==="idle"?T.textContent=n.agent.connectionNotTested:ie==="probing"?T.textContent=n.agent.testingCapability:ie==="ready"?T.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ve!==void 0?T.textContent=n.errors[ve]:ye()===void 0?T.textContent=n.agent.providerUnavailable:T.textContent=Te,Ye(),J(),x()}let $=o.subscribe(I);return I(),Object.freeze({root:i,providerSelect:b,modelSelect:R,consentCheckbox:P,workspaceConsentCheckbox:f,testButton:ee,runButton:re,cancelButton:Le,applyButton:ke,revertButton:be,resetButton:_,consentGranted(){return P.checked},workspaceConsentGranted(){return f.checked},readSelection(){let g=ye(),w=g?.models.find(pe=>pe.id===R.value);return g===void 0||w===void 0?void 0:Object.freeze({providerProfileId:g.id,modelProfileId:w.id})},renderCapability(g,w,pe,V){ie=g,Te=w,ve=V,Ce=g==="probing",ae=g==="ready"&&pe?.state==="agent-ready",T.dataset.state=g,T.textContent=pe?.state==="agent-ready"?`${w} · ${n.agent.toolsReady}`:w,J()},renderWorkspaceHealth(g,w,pe){se=g,Me=w,De=pe??w?.errorCode,W.dataset.state=g,g!=="checking"&&(B.hidden=g!=="consent-required"),(g==="idle"||g==="ready"||g==="blocked")&&(f.checked=!1),Ye(),J()},renderJob(g,w,pe,V){X=!0,S.hidden=!0,Se.hidden=!1,b.disabled=!0,R.disabled=!0,P.disabled=!0,f.disabled=!0,te=g,le=w,_e=pe,Re=V,x()},resetJob(){X=!1,te=void 0,le=void 0,_e=[],Re=void 0,S.hidden=!1,Se.hidden=!0,b.disabled=!1,R.disabled=!1,P.disabled=!1,f.disabled=!1,Ee.replaceChildren(),oe.replaceChildren(),Q.replaceChildren(),K.textContent="",z.textContent="",z.hidden=!0,J()},setContextReady(g){Ae=g,J()},setEditingEnabled(g){He=g,b.disabled=!g||X,R.disabled=!g||X,P.disabled=!g||X,f.disabled=!g||X,J()},setProviderConsent(g){P.checked=g,J()},setSelectionVisible(g){Y=g,J(),g||(Le.hidden=!0,ke.hidden=!0,be.hidden=!0,_.hidden=!0)},dispose(){$(),b.removeEventListener("change",s),R.removeEventListener("change",p),P.removeEventListener("change",J),f.removeEventListener("change",J)}})}var Er="http://www.w3.org/2000/svg";function Ie(e,t,o){let n=e.createElementNS(Er,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Dn(e){let t=Ie(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=Ie(e,"defs",{}),n=Ie(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(Ie(e,"stop",{offset:"0","stop-color":"#7c22ff"}),Ie(e,"stop",{offset:".52","stop-color":"#4a69ff"}),Ie(e,"stop",{offset:"1","stop-color":"#06d9ef"})),o.append(n);let i={fill:"none",stroke:"url(#spotpatch-brand-gradient)","stroke-linecap":"square","stroke-linejoin":"miter"},r=Ie(e,"path",{d:"M106 42C67 42 43 68 43 105c0 36 24 61 63 96 39-35 63-60 63-96 0-37-24-63-63-63Z",...i,"stroke-width":"14"}),a=Ie(e,"path",{d:"M106 25v42",...i,"stroke-width":"14"}),c=Ie(e,"path",{d:"M35 109h20m102 0h38",...i,"stroke-width":"13"}),S=Ie(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...i,"stroke-width":"9"}),C=Ie(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,a,c,S,C),t}function St(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function $n({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,c=o.x+o.width/2,S=o.y+o.height/2,C=St(c-t/2,16,r),u=St(S-e/2,16,a),k=C,b=u,N="viewport";return o.width>=t+48&&o.height>=e+48?N="center":o.y-e-14>=16?(b=o.y-e-14,N="above"):o.y+o.height+14+e<=n-16?(b=o.y+o.height+14,N="below"):o.x+o.width+14+t<=i-16?(k=o.x+o.width+14,N="right"):o.x-t-14>=16&&(k=o.x-t-14,N="left"),Object.freeze({anchorX:St(c-k,22,t-22),anchorY:St(S-b,22,e-22),left:k,mode:N,top:b})}var Ar=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"}),Cr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Rr=Object.freeze({[h.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[h.INVALID_TOKEN]:"The local SpotPatch session expired.",[h.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[h.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[h.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[h.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[h.EDITOR_OPEN_FAILED]:"The editor request failed.",[h.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[h.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[h.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[h.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[h.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[h.AGENT_BUSY]:"Another write Agent job is still active.",[h.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[h.AGENT_CANCELLED]:"The Agent job was cancelled.",[h.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[h.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[h.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[h.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[h.TOOL_DENIED]:"A model tool request violated the local safety policy.",[h.TOOL_INPUT_INVALID]:"The model sent invalid tool arguments or reused a tool ID.",[h.TOOL_PATH_DENIED]:"The model requested a protected, linked, non-text, or external path.",[h.PATCH_REJECTED]:"The proposed patch did not pass local policy.",[h.VALIDATION_FAILED]:"Required project checks failed. The change cannot be applied.",[h.APPLY_CONFLICT]:"Project files changed after the Agent baseline; no overwrite was performed.",[h.INTERNAL_ERROR]:"The Agent job failed without exposing private details."}),vr=Object.freeze({[h.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[h.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[h.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[h.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[h.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[h.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[h.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[h.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[h.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[h.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[h.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[h.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[h.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[h.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[h.AGENT_CANCELLED]:"Agent 任务已取消。",[h.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[h.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[h.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[h.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[h.TOOL_DENIED]:"模型工具请求违反本地安全策略。",[h.TOOL_INPUT_INVALID]:"模型发送了无效工具参数,或复用了工具调用 ID。",[h.TOOL_PATH_DENIED]:"模型请求了受保护、非文本、符号链接或项目外路径。",[h.PATCH_REJECTED]:"建议补丁未通过本地策略检查。",[h.VALIDATION_FAILED]:"项目必需检查失败,不能应用本次变更。",[h.APPLY_CONFLICT]:"Agent 建立基线后项目文件已变化,未执行覆盖。",[h.INTERNAL_ERROR]:"Agent 任务失败,私有细节未暴露到浏览器。"}),Tr=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"}),wr=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:"警告"}),Or=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:Tr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Connection not tested",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifyAndRun:"Verify & run",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Ar[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:Rr}),"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:wr,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未测试连接",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifyAndRun:"验证并运行",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Cr[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:vr})});function zn(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 Pr(e,t){if(e!=="auto")return e;let o=zn(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(zn).find(i=>i!==void 0)??"en-US"}function jn(e,t="auto"){let o=Pr(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Or[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var Lr=560,kr=Object.freeze({previewing:640,selected:720});function _r(e){let t=e.createElement("style");return t.textContent=`
168
241
  :host {
169
242
  all: initial;
170
243
  --spotpatch-bg: #11141a;
@@ -199,7 +272,7 @@ ${gt(e.code.language,J(t.codeLines.join(`
199
272
  position: fixed;
200
273
  right: 24px;
201
274
  bottom: 24px;
202
- z-index: ${String(rt.controls)};
275
+ z-index: ${String(pt.controls)};
203
276
  display: inline-flex;
204
277
  align-items: center;
205
278
  gap: 10px;
@@ -233,7 +306,7 @@ ${gt(e.code.language,J(t.codeLines.join(`
233
306
  position: fixed;
234
307
  top: 0;
235
308
  left: 0;
236
- z-index: ${String(rt.highlight)};
309
+ z-index: ${String(pt.highlight)};
237
310
  box-sizing: border-box;
238
311
  border: 2px solid var(--spotpatch-accent);
239
312
  border-radius: 6px;
@@ -260,7 +333,7 @@ ${gt(e.code.language,J(t.codeLines.join(`
260
333
  .spotpatch-selection-highlights {
261
334
  position: fixed;
262
335
  inset: 0;
263
- z-index: ${String(rt.highlight)};
336
+ z-index: ${String(pt.highlight)};
264
337
  pointer-events: none;
265
338
  }
266
339
  .spotpatch-selection-highlight {
@@ -301,7 +374,7 @@ ${gt(e.code.language,J(t.codeLines.join(`
301
374
  position: fixed;
302
375
  top: 16px;
303
376
  left: 16px;
304
- z-index: ${String(rt.controls)};
377
+ z-index: ${String(pt.controls)};
305
378
  box-sizing: border-box;
306
379
  width: min(560px, calc(100vw - 32px));
307
380
  color: #edf0f7;
@@ -802,10 +875,10 @@ ${gt(e.code.language,J(t.codeLines.join(`
802
875
  .spotpatch-target-select { grid-template-columns: 32px minmax(0, 1fr); }
803
876
  .spotpatch-target-state { display: none; }
804
877
  }
805
- ${_n}
806
- `,t}function Lr(e,t){return e.split(`
807
- `).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(Ye,"");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 M=l(e,"span");M.className="spotpatch-anchor",M.setAttribute("aria-hidden","true");let A=l(e,"div");A.className="spotpatch-shell";let v=l(e,"header");v.className="spotpatch-header";let $=l(e,"div");$.className="spotpatch-brand-row";let w=l(e,"div");w.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),w.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"),pe=G(e,"×","spotpatch-close");C.append(R,H,pe),$.append(w,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 ve=l(e,"div");ve.className="spotpatch-target-row";let ue=l(e,"span");ue.className="spotpatch-target-label";let z=l(e,"span");z.className="spotpatch-context-state",z.dataset.state="loading",z.textContent=r.context.collecting,ve.append(ue,z),v.append($,F,I,ve);let Pe=l(e,"div");Pe.className="spotpatch-body";let ae=l(e,"div");ae.className="spotpatch-selection-panel";let U=l(e,"section");U.className="spotpatch-targets";let ge=l(e,"div");ge.className="spotpatch-targets-heading";let _e=l(e,"span"),Le=l(e,"span");Le.className="spotpatch-targets-meta";let te=l(e,"span");te.className="spotpatch-target-complete";let Y=l(e,"span");Y.className="spotpatch-target-budget",Y.setAttribute("aria-live","polite");let fe=l(e,"span");fe.className="spotpatch-target-count",Le.append(te,Y),ge.append(_e,fe);let me=l(e,"div");me.className="spotpatch-target-list",U.append(ge,Le,me);let Ce=l(e,"details");Ce.className="spotpatch-diagnostics";let $e=l(e,"summary"),Se=l(e,"span"),ne=l(e,"span");ne.className="spotpatch-source-peek",ne.textContent=r.diagnostics.resolving,$e.append(Se,ne);let L=l(e,"pre");L.className="spotpatch-summary",Ce.append($e,L);let O=Nn(e,o,a);ae.append(U,Ce,O.root);let Re=l(e,"div");Re.className="spotpatch-preview-panel",Re.hidden=!0;let he=l(e,"pre");he.className="spotpatch-prompt",he.tabIndex=0,he.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Re.append(he),Pe.append(ae,Re);let De=l(e,"footer");De.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),Ae=G(e,r.actions.reselect),oe=G(e,r.actions.openEditor),q=G(e,r.actions.preview,"spotpatch-primary"),be=G(e,r.actions.copy,"spotpatch-primary"),K=G(e,r.actions.back);De.append(se,O.runButton,q,O.testButton,O.cancelButton,O.applyButton,O.revertButton,O.resetButton,Q,oe,Ae,be,K),A.append(v,Pe,De),m.append(M,A);let Te=l(e,"div");Te.className="spotpatch-live",Te.setAttribute("aria-live","polite"),Te.setAttribute("aria-atomic","true"),c.append(Pr(e),P,E,m,y,Te),e.documentElement.append(i);let we,Ne,ke="idle",Be=!1,f=!1,j="",X=!0,_=[],re=0,Ve="idle";function s(d){Ve=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:"",W()}function p(d){return d.status==="ready"?r.targets.statusReady:d.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function S(d){let h=me.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(h).find(T=>d===void 0||T.dataset.targetInstructionId===d)}function N(d,h){let T=c.activeElement?.closest("textarea[data-target-instruction-id]"),D=T?.dataset.targetInstructionId,ce=T?.selectionStart,Me=T?.selectionEnd;_=d.map(ie=>Object.freeze({...ie})),re=h,me.replaceChildren();let ze=d.filter(ie=>ie.instruction.trim().length>0).length,le=d.reduce((ie,V)=>ie+V.instruction.trim().length,0);fe.textContent=r.targets.count(d.length,h),te.textContent=r.targets.complete(ze,d.length);let Oe=le>4e3;Y.dataset.state=Oe?"over":"ready",Y.textContent=Oe?r.targets.instructionBudgetExceeded(le,4e3):r.targets.instructionBudget(le,4e3),Q.disabled=!X||d.length>=h,Q.title=d.length>=h?r.targets.limitTitle(h):r.targets.addTitle,ue.textContent=d.length===1?d[0]?.label??r.context.selectedElement:r.context.selectedCount(d.length);for(let[ie,V]of d.entries()){let Ge=l(e,"div");Ge.className="spotpatch-target-item",Ge.dataset.active=String(V.active),Ge.dataset.status=V.status,Ge.dataset.targetId=V.id;let mt=l(e,"div");mt.className="spotpatch-target-summary";let Ze=G(e,"","spotpatch-target-select");Ze.dataset.activateTargetId=V.id,Ze.setAttribute("aria-label",r.targets.activate(ie+1)),Ze.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,Ze.append(ht,bt,it);let Qe=G(e,"↗","spotpatch-target-open");Qe.dataset.openTargetId=V.id,Qe.disabled=!V.canOpenEditor,Qe.setAttribute("aria-label",r.actions.openTarget(ie+1)),Qe.title=r.actions.openTarget(ie+1);let et=G(e,"×","spotpatch-target-remove");if(et.dataset.removeTargetId=V.id,et.disabled=!X,et.setAttribute("aria-label",r.targets.remove(ie+1)),et.title=r.targets.removeTitle,mt.append(Ze,Qe,et),Ge.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=!X,Ue.dataset.targetInstructionId=V.id,Ue.setAttribute("aria-label",r.targets.instructionLabel(V.label)),St.append(At,Ue),Ge.append(St)}me.append(Ge)}if(D!==void 0){let ie=S(D);ie?.focus({preventScroll:!0}),ce!==void 0&&Me!==void 0&&ie?.setSelectionRange(ce,Me)}}function B(d,h){_=_.map(Oe=>Oe.id===d?Object.freeze({...Oe,instruction:h}):Oe);let T=Array.from(me.querySelectorAll(".spotpatch-target-item")).find(Oe=>Oe.dataset.targetId===d);if(T===void 0)return;let D=h.trim().length>0,ce=T.querySelector(".spotpatch-target-state"),Me=T.querySelector(".spotpatch-target-editor-count");ce!==null&&(ce.dataset.complete=String(D),ce.textContent=D?r.targets.instructionReady:r.targets.instructionMissing),Me!==null&&(Me.textContent=r.targets.instructionCount(h.length,2e3)),te.textContent=r.targets.complete(_.filter(Oe=>Oe.instruction.trim().length>0).length,_.length);let ze=_.reduce((Oe,ie)=>Oe+ie.instruction.trim().length,0),le=ze>4e3;Y.dataset.state=le?"over":"ready",Y.textContent=le?r.targets.instructionBudgetExceeded(ze,4e3):r.targets.instructionBudget(ze,4e3)}function ye(d){P.replaceChildren(),Ne=d.find(h=>h.active)?.rect,we=Ne;for(let[h,T]of d.entries()){let D=l(e,"div");D.className="spotpatch-selection-highlight",D.dataset.targetId=T.id,D.dataset.active=String(T.active),D.style.transform=`translate(${String(T.rect.x)}px, ${String(T.rect.y)}px)`,D.style.width=`${String(T.rect.width)}px`,D.style.height=`${String(T.rect.height)}px`;let ce=l(e,"span");ce.textContent=`${String(h+1)} · ${T.label}`,D.append(ce),P.append(D)}W()}function W(){if(m.hidden||we===void 0)return;let d=e.defaultView,h=d?.innerWidth??e.documentElement.clientWidth,T=d?.innerHeight??e.documentElement.clientHeight,D=m.getBoundingClientRect(),ce=ke==="previewing"?"previewing":"selected",Me=D.width>0?D.width:Math.min(wr,h-32),ze=D.height>0?D.height:Math.min(Or[ce],T-32),le=Mn({target:we,dialogWidth:Me,dialogHeight:ze,viewportWidth:h,viewportHeight:T});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 jt(d){let h=r.summary,T=Lr(d,h.source);ne.textContent=T??r.diagnostics.noExactSource;let D=`${h.browserContext}: ${h.collectionStatuses.ready}`,ce=`${h.browserContext}: ${h.collectionStatuses.loading}`,Me=`${h.browserContext}: ${h.collectionStatuses.failed}`,ze=`${h.api}: ${h.apiStatuses.loading}`,le=`${h.api}: ${h.apiStatuses.failed}`;d.includes(D)&&!d.includes(ce)&&!d.includes(ze)&&!d.includes(Me)&&!d.includes(le)?(z.dataset.state="ready",z.textContent=r.context.ready):d.includes(Me)||d.includes(le)?(z.dataset.state="warning",z.textContent=r.context.partial):(z.dataset.state="loading",z.textContent=r.context.collecting)}function Bt(d,h,T){Be=h,f=T,j=d,L.textContent=d,oe.disabled=!h,q.disabled=!T,O.setContextReady(T),jt(d),W()}function Ut(d){ke=d;let h=d==="selected",T=d==="previewing";y.hidden=h||T,ae.hidden=!h,Re.hidden=!T,Ae.hidden=!h,Q.hidden=!h,oe.hidden=!h,q.hidden=!h,O.setSelectionVisible(h),be.hidden=!T,K.hidden=!T,F.textContent=T?r.dialog.previewTitle:r.dialog.editTitle,I.textContent=T?r.dialog.previewSubtitle:r.dialog.editSubtitle,W()}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),pe.setAttribute("aria-label",r.dialog.close),pe.title=r.dialog.close,U.setAttribute("aria-label",r.targets.ariaLabel),_e.textContent=r.targets.title,Se.textContent=r.diagnostics.title,he.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Q.textContent=r.actions.addElement,Ae.textContent=r.actions.reselect,oe.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=ke==="inspecting"?r.trigger.stop:r.trigger.select,Ut(ke),s(Ve),_.length>0?N(_,re):(fe.textContent=r.targets.count(0,re),te.textContent=r.targets.complete(0,0),Y.dataset.state="ready",Y.textContent=r.targets.instructionBudget(0,4e3),ue.textContent=r.context.selectedElement),j.length>0?jt(j):(ne.textContent=r.diagnostics.resolving,z.textContent=r.context.collecting)}Ce.addEventListener("toggle",W),H.addEventListener("click",a.toggle);let qn=a.subscribe(Ht);return Ht(),Object.freeze({host:i,triggerButton:y,addTargetButton:Q,targetList:me,reselectButton:Ae,openEditorButton:oe,repositoryLink:R,previewButton:q,copyButton:be,backButton:K,closeButton:pe,agentProviderSelect:O.providerSelect,agentModelSelect:O.modelSelect,agentConsentCheckbox:O.consentCheckbox,agentTestButton:O.testButton,agentRunButton:O.runButton,agentCancelButton:O.cancelButton,agentApplyButton:O.applyButton,agentRevertButton:O.revertButton,agentResetButton:O.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){we=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,ue.textContent=h,W()},hideHighlight(){we=Ne,E.hidden=!0,u.textContent="",W()},showSelectionHighlights:ye,hideSelectionHighlights(){P.replaceChildren(),Ne=void 0,we=void 0},showSelection(d,h,T){Bt(d,h,T),y.hidden=!0,m.hidden=!1,W()},updateSelection:Bt,renderTargets:N,updateTargetInstruction:B,setPreviewEnabled(d){f=d,q.disabled=!d,O.setContextReady(d)},hideSelection(){m.hidden=!0,y.hidden=!1,me.replaceChildren(),_=[],re=0,j="",s("idle"),fe.textContent=r.targets.count(0,0),te.textContent=r.targets.complete(0,0),ue.textContent=r.context.selectedElement,L.textContent="",he.textContent="",ne.textContent=r.diagnostics.resolving,z.dataset.state="loading",z.textContent=r.context.collecting,oe.disabled=!0,q.disabled=!0,Be=!1,f=!1,O.setContextReady(!1),O.setSelectionVisible(!1),O.setEditingEnabled(!0),O.resetJob()},hideSelectionTemporarily(){m.hidden=!0,y.hidden=!1},showPreview(d){he.textContent=d,W()},readAgentSelection(){return O.readSelection()},agentConsentGranted(){return O.consentGranted()},setAgentProviderConsent(d){O.setProviderConsent(d)},setAgentEditingEnabled(d){X=d,Q.disabled=!d,Ae.disabled=!d,me.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(h=>{h.disabled=!d}),oe.disabled=!Be,q.disabled=!d||!f,O.setEditingEnabled(d),W()},renderAgentCapability(d,h,T,D){O.renderCapability(d,h,T,D);let ce=d==="ready"&&T?.state==="agent-ready";q.classList.toggle("spotpatch-primary",!ce),W()},renderAgentJob(d,h,T,D){O.renderJob(d,h,T,D),W()},resetAgentJob(){O.resetJob(),W()},focusTargetInstruction(d){S(d)?.focus({preventScroll:!0})},focusPrompt(){he.focus({preventScroll:!0})},announce(d){Te.textContent="",Te.textContent=d},locale:a.locale,messages:a.messages,subscribeLocale:a.subscribe,dispose(){Ce.removeEventListener("toggle",W),H.removeEventListener("click",a.toggle),qn(),O.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(`
808
- `)}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)},M=()=>{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 k(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))}},$=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))}},w=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),M()};return Object.freeze({apply(){c?.canApply===!0&&w("apply")},beginSelection(){Z()},cancel(){c?.canCancel===!0&&w("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,M()},reset(){let g=E;Z(),g&&e.onReselectRequired()},revert(){c?.canRevert===!0&&w("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(),$(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,M,A=[],v,$=0,w=0,Z=0,g=!1,x="",C,R,H,pe,F=new Map;function I(s){u=Rn(u,s),n.renderStatus(u.status)}function ve(){return A.find(s=>s.id===v)??A.at(-1)}function ue(s,p){return P&&p===w&&u.status!=="idle"&&A.includes(s)}function z(){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 Pe(){let s=n.messages().summary;return A.map((p,S)=>{let N=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)}
809
- ${N}`}).join(`
878
+ ${Nn}
879
+ `,t}function Ir(e,t){return e.split(`
880
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Un(e,t,o=Object.freeze({enabled:!1}),n="auto"){let i=jn(e,n),r=i.messages(),a=e.createElement("spotpatch-root");a.setAttribute(et,"");let c=a.attachShadow({mode:"open"}),S=F(e,r.trigger.select,"spotpatch-trigger");S.title=r.trigger.title(t),S.setAttribute("aria-pressed","false");let C=l(e,"div");C.className="spotpatch-highlight",C.hidden=!0;let u=l(e,"span");u.className="spotpatch-highlight-label",C.append(u);let k=l(e,"div");k.className="spotpatch-selection-highlights",k.setAttribute("aria-hidden","true");let b=l(e,"section");b.className="spotpatch-dialog",b.hidden=!0,b.tabIndex=-1,b.dataset.placement="viewport",b.setAttribute("role","dialog"),b.setAttribute("aria-labelledby","spotpatch-selection-title");let N=l(e,"span");N.className="spotpatch-anchor",N.setAttribute("aria-hidden","true");let A=l(e,"div");A.className="spotpatch-shell";let R=l(e,"header");R.className="spotpatch-header";let D=l(e,"div");D.className="spotpatch-brand-row";let P=l(e,"div");P.className="spotpatch-brand";let Z=l(e,"span");Z.className="spotpatch-brand-copy";let B=l(e,"span");B.className="spotpatch-brand-name";let f=l(e,"span");f.className="spotpatch-brand-context",Z.append(B,f),P.append(Dn(e),Z);let y=l(e,"span");y.className="spotpatch-header-controls";let E=l(e,"a");E.className="spotpatch-repository",E.href=Dt,E.target="_blank",E.rel="noopener noreferrer";let L=F(e,"","spotpatch-locale"),U=F(e,"×","spotpatch-close");y.append(E,L,U),D.append(P,y);let W=l(e,"h2");W.id="spotpatch-selection-title",W.className="spotpatch-title";let T=l(e,"p");T.className="spotpatch-subtitle";let Se=l(e,"div");Se.className="spotpatch-target-row";let me=l(e,"span");me.className="spotpatch-target-label";let H=l(e,"span");H.className="spotpatch-context-state",H.dataset.state="loading",H.textContent=r.context.collecting,Se.append(me,H),R.append(D,W,T,Se);let je=l(e,"div");je.className="spotpatch-body";let Pe=l(e,"div");Pe.className="spotpatch-selection-panel";let z=l(e,"section");z.className="spotpatch-targets";let Ee=l(e,"div");Ee.className="spotpatch-targets-heading";let Ne=l(e,"span"),Ue=l(e,"span");Ue.className="spotpatch-targets-meta";let oe=l(e,"span");oe.className="spotpatch-target-complete";let Q=l(e,"span");Q.className="spotpatch-target-budget",Q.setAttribute("aria-live","polite");let K=l(e,"span");K.className="spotpatch-target-count",Ue.append(oe,Q),Ee.append(Ne,K);let ee=l(e,"div");ee.className="spotpatch-target-list",z.append(Ee,Ue,ee);let re=l(e,"details");re.className="spotpatch-diagnostics";let Le=l(e,"summary"),ke=l(e,"span"),be=l(e,"span");be.className="spotpatch-source-peek",be.textContent=r.diagnostics.resolving,Le.append(ke,be);let _=l(e,"pre");_.className="spotpatch-summary",re.append(Le,_);let O=Mn(e,o,i);Pe.append(z,re,O.root);let Be=l(e,"div");Be.className="spotpatch-preview-panel",Be.hidden=!0;let Ae=l(e,"pre");Ae.className="spotpatch-prompt",Ae.tabIndex=0,Ae.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Be.append(Ae),je.append(Pe,Be);let He=l(e,"footer");He.className="spotpatch-actions";let Y=l(e,"div");Y.className="spotpatch-context-state spotpatch-editor-feedback",Y.dataset.state="idle",Y.setAttribute("role","status"),Y.setAttribute("aria-live","polite"),Y.hidden=!0;let X=F(e,r.actions.addElement),Ce=F(e,r.actions.reselect),ae=F(e,r.actions.openEditor),te=F(e,r.actions.preview,"spotpatch-primary"),le=F(e,r.actions.copy,"spotpatch-primary"),_e=F(e,r.actions.back);He.append(Y,O.runButton,te,O.testButton,O.cancelButton,O.applyButton,O.revertButton,O.resetButton,X,ae,Ce,le,_e),A.append(R,je,He),b.append(N,A);let Re=l(e,"div");Re.className="spotpatch-live",Re.setAttribute("aria-live","polite"),Re.setAttribute("aria-atomic","true"),c.append(_r(e),k,C,b,S,Re),e.documentElement.append(a);let ie,Te,ve="idle",se=!1,Me=!1,De="",ye=!0,de=[],J=0,Ye="idle";function s(d){Ye=d,Y.dataset.state=d,Y.hidden=d==="idle",Y.textContent=d==="opening"?r.announcements.editorOpening:d==="success"?r.announcements.editorOpened:d==="error"?r.announcements.editorFailed:"",w()}function p(d){return d.status==="ready"?r.targets.statusReady:d.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function x(d){let m=ee.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(m).find(v=>d===void 0||v.dataset.targetInstructionId===d)}function I(d,m){let v=c.activeElement?.closest("textarea[data-target-instruction-id]"),j=v?.dataset.targetInstructionId,ue=v?.selectionStart,$e=v?.selectionEnd;de=d.map(ce=>Object.freeze({...ce})),J=m,ee.replaceChildren();let Ge=d.filter(ce=>ce.instruction.trim().length>0).length,ge=d.reduce((ce,q)=>ce+q.instruction.trim().length,0);K.textContent=r.targets.count(d.length,m),oe.textContent=r.targets.complete(Ge,d.length);let Oe=ge>4e3;Q.dataset.state=Oe?"over":"ready",Q.textContent=Oe?r.targets.instructionBudgetExceeded(ge,4e3):r.targets.instructionBudget(ge,4e3),X.disabled=!ye||d.length>=m,X.title=d.length>=m?r.targets.limitTitle(m):r.targets.addTitle,me.textContent=d.length===1?d[0]?.label??r.context.selectedElement:r.context.selectedCount(d.length);for(let[ce,q]of d.entries()){let Xe=l(e,"div");Xe.className="spotpatch-target-item",Xe.dataset.active=String(q.active),Xe.dataset.status=q.status,Xe.dataset.targetId=q.id;let Et=l(e,"div");Et.className="spotpatch-target-summary";let rt=F(e,"","spotpatch-target-select");rt.dataset.activateTargetId=q.id,rt.setAttribute("aria-label",r.targets.activate(ce+1)),rt.setAttribute("aria-expanded",String(q.active));let At=l(e,"span");At.className="spotpatch-target-index",At.textContent=String(ce+1);let Ct=l(e,"span");Ct.className="spotpatch-target-copy";let Rt=l(e,"span");Rt.className="spotpatch-target-name",Rt.textContent=q.label;let vt=l(e,"span");vt.className="spotpatch-target-source",vt.textContent=`${p(q)} · ${q.source}`,Ct.append(Rt,vt);let Wt=q.instruction.trim().length>0,gt=l(e,"span");gt.className="spotpatch-target-state",gt.dataset.complete=String(Wt),gt.textContent=Wt?r.targets.instructionReady:r.targets.instructionMissing,rt.append(At,Ct,gt);let at=F(e,"↗","spotpatch-target-open");at.dataset.openTargetId=q.id,at.disabled=!q.canOpenEditor,at.setAttribute("aria-label",r.actions.openTarget(ce+1)),at.title=r.actions.openTarget(ce+1);let it=F(e,"×","spotpatch-target-remove");if(it.dataset.removeTargetId=q.id,it.disabled=!ye,it.setAttribute("aria-label",r.targets.remove(ce+1)),it.title=r.targets.removeTitle,Et.append(rt,at,it),Xe.append(Et),q.active){let Tt=l(e,"label");Tt.className="spotpatch-target-editor";let wt=l(e,"span");wt.className="spotpatch-target-editor-head";let Ot=l(e,"span");Ot.className="spotpatch-target-editor-label",Ot.textContent=r.targets.instructionLabel(q.label);let Pt=l(e,"span");Pt.className="spotpatch-target-editor-count",Pt.textContent=r.targets.instructionCount(q.instruction.length,2e3),wt.append(Ot,Pt);let Je=l(e,"textarea");Je.rows=4,Je.maxLength=2e3,Je.value=q.instruction,Je.placeholder=r.targets.instructionPlaceholder,Je.disabled=!ye,Je.dataset.targetInstructionId=q.id,Je.setAttribute("aria-label",r.targets.instructionLabel(q.label)),Tt.append(wt,Je),Xe.append(Tt)}ee.append(Xe)}if(j!==void 0){let ce=x(j);ce?.focus({preventScroll:!0}),ue!==void 0&&$e!==void 0&&ce?.setSelectionRange(ue,$e)}}function $(d,m){de=de.map(Oe=>Oe.id===d?Object.freeze({...Oe,instruction:m}):Oe);let v=Array.from(ee.querySelectorAll(".spotpatch-target-item")).find(Oe=>Oe.dataset.targetId===d);if(v===void 0)return;let j=m.trim().length>0,ue=v.querySelector(".spotpatch-target-state"),$e=v.querySelector(".spotpatch-target-editor-count");ue!==null&&(ue.dataset.complete=String(j),ue.textContent=j?r.targets.instructionReady:r.targets.instructionMissing),$e!==null&&($e.textContent=r.targets.instructionCount(m.length,2e3)),oe.textContent=r.targets.complete(de.filter(Oe=>Oe.instruction.trim().length>0).length,de.length);let Ge=de.reduce((Oe,ce)=>Oe+ce.instruction.trim().length,0),ge=Ge>4e3;Q.dataset.state=ge?"over":"ready",Q.textContent=ge?r.targets.instructionBudgetExceeded(Ge,4e3):r.targets.instructionBudget(Ge,4e3)}function g(d){k.replaceChildren(),Te=d.find(m=>m.active)?.rect,ie=Te;for(let[m,v]of d.entries()){let j=l(e,"div");j.className="spotpatch-selection-highlight",j.dataset.targetId=v.id,j.dataset.active=String(v.active),j.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,j.style.width=`${String(v.rect.width)}px`,j.style.height=`${String(v.rect.height)}px`;let ue=l(e,"span");ue.textContent=`${String(m+1)} · ${v.label}`,j.append(ue),k.append(j)}w()}function w(){if(b.hidden||ie===void 0)return;let d=e.defaultView,m=d?.innerWidth??e.documentElement.clientWidth,v=d?.innerHeight??e.documentElement.clientHeight,j=b.getBoundingClientRect(),ue=ve==="previewing"?"previewing":"selected",$e=j.width>0?j.width:Math.min(Lr,m-32),Ge=j.height>0?j.height:Math.min(kr[ue],v-32),ge=$n({target:ie,dialogWidth:$e,dialogHeight:Ge,viewportWidth:m,viewportHeight:v});b.style.left=`${String(ge.left)}px`,b.style.top=`${String(ge.top)}px`,b.style.setProperty("--spotpatch-anchor-x",`${String(ge.anchorX)}px`),b.style.setProperty("--spotpatch-anchor-y",`${String(ge.anchorY)}px`),b.dataset.placement=ge.mode}function pe(d){let m=r.summary,v=Ir(d,m.source);be.textContent=v??r.diagnostics.noExactSource;let j=`${m.browserContext}: ${m.collectionStatuses.ready}`,ue=`${m.browserContext}: ${m.collectionStatuses.loading}`,$e=`${m.browserContext}: ${m.collectionStatuses.failed}`,Ge=`${m.api}: ${m.apiStatuses.loading}`,ge=`${m.api}: ${m.apiStatuses.failed}`;d.includes(j)&&!d.includes(ue)&&!d.includes(Ge)&&!d.includes($e)&&!d.includes(ge)?(H.dataset.state="ready",H.textContent=r.context.ready):d.includes($e)||d.includes(ge)?(H.dataset.state="warning",H.textContent=r.context.partial):(H.dataset.state="loading",H.textContent=r.context.collecting)}function V(d,m,v){se=m,Me=v,De=d,_.textContent=d,ae.disabled=!m,te.disabled=!v,O.setContextReady(v),pe(d),w()}function we(d){ve=d;let m=d==="selected",v=d==="previewing";S.hidden=m||v,Pe.hidden=!m,Be.hidden=!v,Ce.hidden=!m,X.hidden=!m,ae.hidden=!m,te.hidden=!m,O.setSelectionVisible(m),le.hidden=!v,_e.hidden=!v,W.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,T.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,w()}function ot(){r=i.messages(),B.textContent=r.brand.name,f.textContent=r.brand.context,E.textContent=r.brand.repository,E.title=r.brand.repositoryTitle,E.setAttribute("aria-label",r.brand.repositoryTitle),L.textContent=r.alternateLocaleName,L.title=r.switchLocale,L.setAttribute("aria-label",r.switchLocale),U.setAttribute("aria-label",r.dialog.close),U.title=r.dialog.close,z.setAttribute("aria-label",r.targets.ariaLabel),Ne.textContent=r.targets.title,ke.textContent=r.diagnostics.title,Ae.setAttribute("aria-label",r.diagnostics.promptAriaLabel),X.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,ae.textContent=r.actions.openEditor,te.textContent=r.actions.preview,le.textContent=r.actions.copy,_e.textContent=r.actions.back,S.title=r.trigger.title(t),S.textContent=ve==="inspecting"?r.trigger.stop:r.trigger.select,we(ve),s(Ye),de.length>0?I(de,J):(K.textContent=r.targets.count(0,J),oe.textContent=r.targets.complete(0,0),Q.dataset.state="ready",Q.textContent=r.targets.instructionBudget(0,4e3),me.textContent=r.context.selectedElement),De.length>0?pe(De):(be.textContent=r.diagnostics.resolving,H.textContent=r.context.collecting)}re.addEventListener("toggle",w),L.addEventListener("click",i.toggle);let ut=i.subscribe(ot);return ot(),Object.freeze({host:a,triggerButton:S,addTargetButton:X,targetList:ee,reselectButton:Ce,openEditorButton:ae,repositoryLink:E,previewButton:te,copyButton:le,backButton:_e,closeButton:U,agentProviderSelect:O.providerSelect,agentModelSelect:O.modelSelect,agentConsentCheckbox:O.consentCheckbox,agentWorkspaceConsentCheckbox:O.workspaceConsentCheckbox,agentTestButton:O.testButton,agentRunButton:O.runButton,agentCancelButton:O.cancelButton,agentApplyButton:O.applyButton,agentRevertButton:O.revertButton,agentResetButton:O.resetButton,renderStatus(d){let m=d==="inspecting";S.setAttribute("aria-pressed",String(m)),S.textContent=m?r.trigger.stop:r.trigger.select,we(d)},renderEditorStatus:s,showHighlight(d,m){ie=d,C.hidden=!1,C.style.transform=`translate(${String(d.x)}px, ${String(d.y)}px)`,C.style.width=`${String(d.width)}px`,C.style.height=`${String(d.height)}px`,u.textContent=m,me.textContent=m,w()},hideHighlight(){ie=Te,C.hidden=!0,u.textContent="",w()},showSelectionHighlights:g,hideSelectionHighlights(){k.replaceChildren(),Te=void 0,ie=void 0},showSelection(d,m,v){V(d,m,v),S.hidden=!0,b.hidden=!1,w()},updateSelection:V,renderTargets:I,updateTargetInstruction:$,setPreviewEnabled(d){Me=d,te.disabled=!d,O.setContextReady(d)},hideSelection(){b.hidden=!0,S.hidden=!1,ee.replaceChildren(),de=[],J=0,De="",s("idle"),K.textContent=r.targets.count(0,0),oe.textContent=r.targets.complete(0,0),me.textContent=r.context.selectedElement,_.textContent="",Ae.textContent="",be.textContent=r.diagnostics.resolving,H.dataset.state="loading",H.textContent=r.context.collecting,ae.disabled=!0,te.disabled=!0,se=!1,Me=!1,O.setContextReady(!1),O.setSelectionVisible(!1),O.setEditingEnabled(!0),O.resetJob()},hideSelectionTemporarily(){b.hidden=!0,S.hidden=!1},showPreview(d){Ae.textContent=d,w()},readAgentSelection(){return O.readSelection()},agentConsentGranted(){return O.consentGranted()},setAgentProviderConsent(d){O.setProviderConsent(d)},setAgentEditingEnabled(d){ye=d,X.disabled=!d,Ce.disabled=!d,ee.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(m=>{m.disabled=!d}),ae.disabled=!se,te.disabled=!d||!Me,O.setEditingEnabled(d),w()},renderAgentCapability(d,m,v,j){O.renderCapability(d,m,v,j);let ue=d==="ready"&&v?.state==="agent-ready";te.classList.toggle("spotpatch-primary",!ue),w()},renderAgentWorkspaceHealth(d,m,v){O.renderWorkspaceHealth(d,m,v),w()},renderAgentJob(d,m,v,j){O.renderJob(d,m,v,j),w()},resetAgentJob(){O.resetJob(),w()},focusTargetInstruction(d){x(d)?.focus({preventScroll:!0})},focusPrompt(){Ae.focus({preventScroll:!0})},announce(d){Re.textContent="",Re.textContent=d},locale:i.locale,messages:i.messages,agentWorkspaceConsentGranted:O.workspaceConsentGranted,subscribeLocale:i.subscribe,dispose(){re.removeEventListener("toggle",w),L.removeEventListener("click",i.toggle),ut(),O.dispose(),a.remove()}})}function Nr(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,r=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,r):o.unavailable}function Bn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`Vite: ${e.viteVersion}`,`${t.source}: ${Nr(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(`
881
+ `)}function Hn(e,t){return`${e}:${t}`}function Mr(e){if(e.type==="tool")return Object.freeze({key:`tool:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function Gn(e){let t=f=>rn(f)??h.INTERNAL_ERROR,o=f=>e.view.messages().errors[t(f)],n=new Map,i=new Set,r=new Map,a=0,c,S,C=!1,u=!1,k=()=>e.view.readAgentSelection(),b=async f=>{e.view.renderAgentWorkspaceHealth("checking");try{let y=await e.api.agentWorkspaceHealth();return f!==a||e.view.renderAgentWorkspaceHealth(y.state,y,y.errorCode),y}catch(y){throw f===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(y)),y}},N=f=>{c!==void 0&&e.view.renderAgentJob(c,S,Object.freeze([...r.values()]),f??c.errorCode)},A=()=>{let f=k();if(f===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(f.providerProfileId));let y=n.get(Hn(f.providerProfileId,f.modelProfileId));y===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,y)},R=async f=>{let y=k();if(y===void 0)throw new Error("Agent provider selection is unavailable.");let E=Hn(y.providerProfileId,y.modelProfileId),L=n.get(E);if(L!==void 0)return L;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let U=await e.api.agentCapability(y);if(f!==a)return U;if(U.state!=="agent-ready")throw new M(U.errorCode??h.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(E,U),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,U),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),U},D=async(f,y)=>{try{let E=await e.api.agentResult(f);if(y!==a||E.snapshot.jobId!==f)return;c=E.snapshot,S=E.result,N()}catch(E){y===a&&N(t(E))}},P=async(f,y)=>{try{await e.api.agentEvents(f,E=>{if(y!==a||E.jobId!==f)return;E.type==="snapshot"&&(c=E.data.snapshot,c.status==="applied"&&!C&&(C=!0,e.onApplied()));let L=Mr(E);L!==void 0&&r.set(L.key,L),N()}),y===a&&await D(f,y)}catch(E){y===a&&!(E instanceof DOMException&&E.name==="AbortError")&&N(t(E))}},Z=async f=>{let y=c;if(y===void 0||u)return;u=!0;let E=a;c=Object.freeze({...y,status:f==="apply"?"applying":f==="cancel"?"cancelling":"reverting",phaseMessage:f==="apply"?e.view.messages().agent.applying:f==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),N();try{let L=f==="apply"?await e.api.applyAgentJob(y.jobId):f==="cancel"?await e.api.cancelAgentJob(y.jobId):await e.api.revertAgentJob(y.jobId);if(E!==a)return;c=L,L.status==="applied"&&!C&&(C=!0,e.onApplied()),await D(L.jobId,E)}catch(L){if(E!==a)return;c=y,await D(y.jobId,E),N(t(L)),e.view.announce(o(L))}finally{E===a&&(u=!1)}},B=()=>{a+=1,c=void 0,S=void 0,r.clear(),C=!1,u=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),A()};return Object.freeze({apply(){c?.canApply===!0&&Z("apply")},beginSelection(){B();let f=a;e.ai.enabled&&b(f).catch(()=>{})},cancel(){c?.canCancel===!0&&Z("cancel")},consentChanged(){let f=k();f!==void 0&&(e.view.agentConsentGranted()?i.add(f.providerProfileId):i.delete(f.providerProfileId))},disposeSelection(){let f=c?.canCancel===!0||c?.status==="cancelling"?c.jobId:void 0;a+=1,c=void 0,S=void 0,r.clear(),C=!1,u=!1,f!==void 0&&e.api.cancelAgentJob(f).catch(()=>{})},providerOrModelChanged(){a+=1,A(),b(a).catch(()=>{})},reset(){let f=C;B(),f?e.onReselectRequired():e.ai.enabled&&b(a).catch(()=>{})},revert(){c?.canRevert===!0&&Z("revert")},run(){if(!e.ai.enabled||c!==void 0)return;let f=k(),y=e.getAnnotation();if(f===void 0||y===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(f.providerProfileId);let E=++a;e.view.setAgentEditingEnabled(!1),Promise.all([R(E),b(E)]).then(async([,L])=>{if(E!==a)return;if(L.state==="blocked")throw new M(L.errorCode??h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(L.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new M(h.WORKTREE_DIRTY);let U=await e.api.createAgentJob({annotation:y,providerProfileId:f.providerProfileId,modelProfileId:f.modelProfileId,providerDataConsent:!0,workingTreeMode:L.state==="consent-required"?"include-local-changes":"require-clean"});E===a&&(c=U,S=void 0,r.clear(),N(),P(U.jobId,E))}).catch(L=>{E===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(L),void 0,t(L)),e.view.announce(o(L)))})},testCapability(){if(!e.ai.enabled||c!==void 0)return;let f=++a;Promise.all([R(f),b(f)]).catch(y=>{f===a&&(e.view.renderAgentCapability("error",o(y),void 0,t(y)),e.view.announce(o(y)))})}})}function Wn(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 $r=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Ht(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 zr(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function jr(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Ur(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 qn(e,t={}){let o=Ur(t),n=t.view??Un(o.document,e.shortcut,e.ai,e.locale),i=t.api??an({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??Tn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??Vn(o.window.navigator),c=t.createId??(()=>Wn(o.window)),S=t.now??(()=>new Date().toISOString()),C=_n({adapter:t.reactAdapter??Dr({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=Bt,k=!1,b,N,A=[],R,D=0,P=0,Z=0,B=!1,f="",y,E,L,U,W=new Map;function T(s){u=wn(u,s),n.renderStatus(u.status)}function Se(){return A.find(s=>s.id===R)??A.at(-1)}function me(s,p){return k&&p===P&&u.status!=="idle"&&A.includes(s)}function H(){let s=A.reduce((p,x)=>p+x.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 je(){let s=n.messages().summary;return A.map((p,x)=>{let I=Bn({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(x+1,p.id===R)}
882
+ ${I}`}).join(`
810
883
 
811
- `)}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=ve(),S=Pe(),N=p?.marker!==void 0;s?n.showSelection(S,N,z()):n.updateSelection(S,N,z())}function ge(){if(!z())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 _e(s){n.showHighlight(Nt(s,o.window),Dt(s))}function Le(){C?.isConnected===!0&&C.focus({preventScroll:!0}),C=void 0}function te(){for(let s of F.values())o.window.clearTimeout(s);F.clear()}function Y(){w+=1,a.cancelPending(),L.disposeSelection(),te(),R?.disconnect(),A=[],v=void 0,g=!1,x="",n.hideSelection(),n.hideSelectionHighlights(),Le()}function fe(){u.status==="inspecting"?I({type:"CANCEL"}):u.status==="selected"?I({type:"CLOSE"}):u.status==="previewing"&&(I({type:"BACK"}),I({type:"CLOSE"})),Y(),n.hideHighlight()}function me(){if(u.status!=="inspecting"||!g||A.length===0){fe();return}g=!1,I({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(v),n.announce(n.messages().announcements.addCancelled)}function Ce(){if(u.status==="inspecting"&&g){me();return}if(u.status!=="idle"){fe();return}I({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function $e(s=n.messages().announcements.chooseAnother){u.status==="selected"&&(I({type:"RESELECT"}),Y(),n.hideHighlight(),n.announce(s))}function Se(){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 ne(){w+=1,te(),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:ge,onApplied:ne,onReselectRequired(){$e(n.messages().announcements.reselectAfterChange)},view:n});async function O(s,p){let S=s.marker;if(S!==void 0)try{let N=await a.sourceContext({fileId:S.fileId,line:S.line,column:S.column,maxLines:e.budget.maxCodeLines});ue(s,p)&&(s.code=N,s.apiStatus="connected",U(),n.announce(n.messages().announcements.sourceLoaded))}catch(N){ue(s,p)&&(s.code=void 0,s.apiStatus="failed",U(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(N instanceof DOMException&&N.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Re(s,p){let S=s.element;if(S===void 0)return;let N=o.window.setTimeout(()=>{if(F.delete(s.id),!ue(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,N)}function he(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 De(s){let p=E.resolve(s),S=Pn(p.source),N=he(s,S);if(N!==void 0){v=N.id,g=!1,I({type:"SELECT"}),n.hideHighlight(),U(!0),n.focusTargetInstruction(N.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()),$+=1;let ye={id:`target-${String($)}`,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(ye),v=ye.id,g=!1;let W=w;I({type:"SELECT"}),n.hideHighlight(),R?.observe(s),U(!0),n.focusTargetInstruction(ye.id),Re(ye,W),S!==void 0?O(ye,W):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function se(){if(m=void 0,u.status!=="inspecting"||M===void 0)return;let s=kt(o.document,o.window,M.x,M.y);if(I({type:"HOVER"}),s===void 0){n.hideHighlight();return}_e(s)}function Q(s){u.status==="inspecting"&&(M={x:s.clientX,y:s.clientY},m??=o.window.requestAnimationFrame(se))}function Ae(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}De(p)}function oe(s){if(s.key==="Escape"&&u.status!=="idle"){s.preventDefault(),u.status==="inspecting"&&g?me():u.status==="inspecting"||u.status==="selected"?fe():(I({type:"BACK"}),n.focusTargetInstruction(v));return}bn(s.target)||!yn(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),Ce())}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 N=F.get(S.id);if(N!==void 0&&(o.window.clearTimeout(N),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 be(){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 K(s){let p=s===void 0?ve():A.find(ye=>ye.id===s);if(u.status!=="selected"||p?.marker===void 0)return;v!==p.id&&(v=p.id,U());let S=p.marker,N=w,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"&&N===w&&B===Z&&v===p.id&&A.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{P&&u.status==="selected"&&N===w&&B===Z&&v===p.id&&A.includes(p)&&n.renderEditorStatus("error")})}function Te(s){if(u.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,S=A.find(N=>N.id===p);S!==void 0&&(S.instruction=s.target.value,n.updateTargetInstruction(S.id,S.instruction),n.setPreviewEnabled(z()))}function we(){K()}function Ne(s){e.ai.enabled&&u.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),L.run())}function ke(){if(u.status!=="selected")return;let s=ge();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}x=r.compose(s),I({type:"PREVIEW"}),n.showPreview(x),n.focusPrompt()}function Be(){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=w;i.writeText(x).then(()=>{P&&s===w&&u.status==="previewing"&&(I({type:"COPY_SUCCESS"}),n.focusTargetInstruction(v),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{P&&s===w&&u.status==="previewing"&&(I({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function f(){u.status==="previewing"&&(I({type:"BACK"}),n.focusTargetInstruction(v))}function j(){if(!(!P||A.length===0)&&(U(),u.status==="previewing")){let s=ge();s!==void 0&&(x=r.compose(s),n.showPreview(x))}}function X(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 N=p.closest("button[data-open-target-id]");if(N?.dataset.openTargetId!==void 0){K(N.dataset.openTargetId);return}let ye=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||ye===void 0||!A.some(W=>W.id===ye)||(v=ye,U(),n.focusTargetInstruction(ye))}function _(){$e()}function re(){P||(P=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Q,!0),o.document.addEventListener("click",Ae,!0),o.document.addEventListener("keydown",oe,!0),o.window.addEventListener("scroll",be,!0),o.window.addEventListener("resize",be),n.triggerButton.addEventListener("click",Ce),n.addTargetButton.addEventListener("click",Se),n.reselectButton.addEventListener("click",_),n.targetList.addEventListener("click",X),n.targetList.addEventListener("input",Te),n.targetList.addEventListener("keydown",Ne),n.openEditorButton.addEventListener("click",we),n.previewButton.addEventListener("click",ke),n.copyButton.addEventListener("click",Be),n.backButton.addEventListener("click",f),n.closeButton.addEventListener("click",fe),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),pe=n.subscribeLocale(j),o.resizeObserver!==void 0&&(R=new o.resizeObserver(be)),o.mutationObserver!==void 0&&(H=new o.mutationObserver(be),H.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function Ve(){if(!P){pe?.(),pe=void 0,n.dispose(),a.cancelPending(),a.dispose(),L.disposeSelection(),E.dispose();return}P=!1,pe?.(),pe=void 0,o.document.removeEventListener("pointermove",Q,!0),o.document.removeEventListener("click",Ae,!0),o.document.removeEventListener("keydown",oe,!0),o.window.removeEventListener("scroll",be,!0),o.window.removeEventListener("resize",be),n.triggerButton.removeEventListener("click",Ce),n.addTargetButton.removeEventListener("click",Se),n.reselectButton.removeEventListener("click",_),n.targetList.removeEventListener("click",X),n.targetList.removeEventListener("input",Te),n.targetList.removeEventListener("keydown",Ne),n.openEditorButton.removeEventListener("click",we),n.previewButton.removeEventListener("click",ke),n.copyButton.removeEventListener("click",Be),n.backButton.removeEventListener("click",f),n.closeButton.removeEventListener("click",fe),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),te(),R?.disconnect(),H?.disconnect(),R=void 0,H=void 0,A=[],v=void 0,x="",M=void 0,C=void 0,a.cancelPending(),a.dispose(),L.disposeSelection(),E.dispose(),n.dispose(),u=$t}return Object.freeze({mount:re,dispose:Ve,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:qe});
884
+ `)}function Pe(){let s=A.flatMap(p=>p.element?.isConnected?[{id:p.id,label:Ht(p.element),rect:zt(p.element,o.window),active:p.id===R}]:[]);s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function z(s=!1){if(A.length===0)return;n.renderTargets(A.map($=>({id:$.id,label:$.resolution.react.componentName??($.element===void 0?$.elementContext?.tagName??"Element":Ht($.element)),source:zr($,n.messages().context.sourceUnavailable),canOpenEditor:$.marker!==void 0,status:jr($),active:$.id===R,instruction:$.instruction})),e.maxTargets),Pe();let p=Se(),x=je(),I=p?.marker!==void 0;s?n.showSelection(x,I,H()):n.updateSelection(x,I,H())}function Ee(){if(!H())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 x=[...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:x}});return Vt({id:c(),locale:n.locale(),createdAt:S(),page:Jn(o.document,o.window),targets:s})}function Ne(s){n.showHighlight(zt(s,o.window),Ht(s))}function Ue(){y?.isConnected===!0&&y.focus({preventScroll:!0}),y=void 0}function oe(){for(let s of W.values())o.window.clearTimeout(s);W.clear()}function Q(){P+=1,i.cancelPending(),_.disposeSelection(),oe(),E?.disconnect(),A=[],R=void 0,B=!1,f="",n.hideSelection(),n.hideSelectionHighlights(),Ue()}function K(){u.status==="inspecting"?T({type:"CANCEL"}):u.status==="selected"?T({type:"CLOSE"}):u.status==="previewing"&&(T({type:"BACK"}),T({type:"CLOSE"})),Q(),n.hideHighlight()}function ee(){if(u.status!=="inspecting"||!B||A.length===0){K();return}B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.focusTargetInstruction(R),n.announce(n.messages().announcements.addCancelled)}function re(){if(u.status==="inspecting"&&B){ee();return}if(u.status!=="idle"){K();return}T({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Le(s=n.messages().announcements.chooseAnother){u.status==="selected"&&(T({type:"RESELECT"}),Q(),n.hideHighlight(),n.announce(s))}function ke(){if(u.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}B=!0,T({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function be(){P+=1,oe(),E?.disconnect();for(let s of A)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),z(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=Gn({ai:e.ai,api:i,getAnnotation:Ee,onApplied:be,onReselectRequired(){Le(n.messages().announcements.reselectAfterChange)},view:n});async function O(s,p){let x=s.marker;if(x!==void 0)try{let I=await i.sourceContext({fileId:x.fileId,line:x.line,column:x.column,maxLines:e.budget.maxCodeLines});me(s,p)&&(s.code=I,s.apiStatus="connected",z(),n.announce(n.messages().announcements.sourceLoaded))}catch(I){me(s,p)&&(s.code=void 0,s.apiStatus="failed",z(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(I instanceof DOMException&&I.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Be(s,p){let x=s.element;if(x===void 0)return;let I=o.window.setTimeout(()=>{if(W.delete(s.id),!me(s,p))return;let $=!1;try{s.elementContext=bn({element:x,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,$=!0}try{s.styles=pn({document:o.document,element:x,maxCharacters:e.budget.cssCharacters})}catch{s.styles=$r,$=!0}s.collectionStatus=$?"failed":"ready",z(),n.announce($?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);W.set(s.id,I)}function Ae(s,p){return p!==void 0?A.find(x=>x.marker?.fileId===p.fileId&&x.marker.line===p.line&&x.marker.column===p.column):A.find(x=>x.element===s)}function He(s){let p=C.resolve(s),x=kn(p.source),I=Ae(s,x);if(I!==void 0){R=I.id,B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.focusTargetInstruction(I.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}A.length===0&&(y=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,f="",_.beginSelection()),D+=1;let g={id:`target-${String(D)}`,element:s,resolution:p,marker:x,code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:x===void 0?"not-required":"loading",collectionStatus:"loading"};A.push(g),R=g.id,B=!1;let w=P;T({type:"SELECT"}),n.hideHighlight(),E?.observe(s),z(!0),n.focusTargetInstruction(g.id),Be(g,w),x!==void 0?O(g,w):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Y(){if(b=void 0,u.status!=="inspecting"||N===void 0)return;let s=jt(o.document,o.window,N.x,N.y);if(T({type:"HOVER"}),s===void 0){n.hideHighlight();return}Ne(s)}function X(s){u.status==="inspecting"&&(N={x:s.clientX,y:s.clientY},b??=o.window.requestAnimationFrame(Y))}function Ce(s){if(u.status!=="inspecting"||An(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let p=jt(o.document,o.window,s.clientX,s.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}He(p)}function ae(s){if(s.key==="Escape"&&u.status!=="idle"){s.preventDefault(),u.status==="inspecting"&&B?ee():u.status==="inspecting"||u.status==="selected"?K():(T({type:"BACK"}),n.focusTargetInstruction(R));return}xn(s.target)||!Sn(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),re())}function te(s){if(u.status!=="selected"&&u.status!=="inspecting")return;let p=A.findIndex($=>$.id===s);if(p<0)return;let[x]=A.splice(p,1);if(x===void 0)return;let I=W.get(x.id);if(I!==void 0&&(o.window.clearTimeout(I),W.delete(x.id)),x.element!==void 0&&E?.unobserve(x.element),R===x.id&&(R=A.at(-1)?.id),A.length===0){B=!0,u.status==="selected"&&T({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),n.announce(n.messages().announcements.allTargetsRemoved);return}z(),n.announce(n.messages().announcements.targetRemoved)}function le(){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"&&T({type:"BACK"});for(let p of s)te(p.id);A.length>0&&n.announce(n.messages().announcements.detachedTargetRemoved);return}Pe()}function _e(s){let p=s===void 0?Se():A.find(g=>g.id===s);if(u.status!=="selected"||p?.marker===void 0)return;R!==p.id&&(R=p.id,z());let x=p.marker,I=P,$=++Z;T({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:x.fileId,line:x.line,column:x.column}).then(()=>{k&&u.status==="selected"&&I===P&&$===Z&&R===p.id&&A.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{k&&u.status==="selected"&&I===P&&$===Z&&R===p.id&&A.includes(p)&&n.renderEditorStatus("error")})}function Re(s){if(u.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,x=A.find(I=>I.id===p);x!==void 0&&(x.instruction=s.target.value,n.updateTargetInstruction(x.id,x.instruction),n.setPreviewEnabled(H()))}function ie(){_e()}function Te(s){e.ai.enabled&&u.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),_.run())}function ve(){if(u.status!=="selected")return;let s=Ee();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}f=r.compose(s),T({type:"PREVIEW"}),n.showPreview(f),n.focusPrompt()}function se(){if(u.status!=="previewing"||f.length===0)return;if(a===void 0){T({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=P;a.writeText(f).then(()=>{k&&s===P&&u.status==="previewing"&&(T({type:"COPY_SUCCESS"}),n.focusTargetInstruction(R),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{k&&s===P&&u.status==="previewing"&&(T({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Me(){u.status==="previewing"&&(T({type:"BACK"}),n.focusTargetInstruction(R))}function De(){if(!(!k||A.length===0)&&(z(),u.status==="previewing")){let s=Ee();s!==void 0&&(f=r.compose(s),n.showPreview(f))}}function ye(s){let p=s.target;if(!(p instanceof Element))return;let x=p.closest("button[data-remove-target-id]");if(x?.dataset.removeTargetId!==void 0){te(x.dataset.removeTargetId);return}let I=p.closest("button[data-open-target-id]");if(I?.dataset.openTargetId!==void 0){_e(I.dataset.openTargetId);return}let g=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||g===void 0||!A.some(w=>w.id===g)||(R=g,z(),n.focusTargetInstruction(g))}function de(){Le()}function J(){k||(k=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",X,!0),o.document.addEventListener("click",Ce,!0),o.document.addEventListener("keydown",ae,!0),o.window.addEventListener("scroll",le,!0),o.window.addEventListener("resize",le),n.triggerButton.addEventListener("click",re),n.addTargetButton.addEventListener("click",ke),n.reselectButton.addEventListener("click",de),n.targetList.addEventListener("click",ye),n.targetList.addEventListener("input",Re),n.targetList.addEventListener("keydown",Te),n.openEditorButton.addEventListener("click",ie),n.previewButton.addEventListener("click",ve),n.copyButton.addEventListener("click",se),n.backButton.addEventListener("click",Me),n.closeButton.addEventListener("click",K),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),U=n.subscribeLocale(De),o.resizeObserver!==void 0&&(E=new o.resizeObserver(le)),o.mutationObserver!==void 0&&(L=new o.mutationObserver(le),L.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function Ye(){if(!k){U?.(),U=void 0,n.dispose(),i.cancelPending(),i.dispose(),_.disposeSelection(),C.dispose();return}k=!1,U?.(),U=void 0,o.document.removeEventListener("pointermove",X,!0),o.document.removeEventListener("click",Ce,!0),o.document.removeEventListener("keydown",ae,!0),o.window.removeEventListener("scroll",le,!0),o.window.removeEventListener("resize",le),n.triggerButton.removeEventListener("click",re),n.addTargetButton.removeEventListener("click",ke),n.reselectButton.removeEventListener("click",de),n.targetList.removeEventListener("click",ye),n.targetList.removeEventListener("input",Re),n.targetList.removeEventListener("keydown",Te),n.openEditorButton.removeEventListener("click",ie),n.previewButton.removeEventListener("click",ve),n.copyButton.removeEventListener("click",se),n.backButton.removeEventListener("click",Me),n.closeButton.removeEventListener("click",K),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),b!==void 0&&(o.window.cancelAnimationFrame(b),b=void 0),oe(),E?.disconnect(),L?.disconnect(),E=void 0,L=void 0,A=[],R=void 0,f="",N=void 0,y=void 0,i.cancelPending(),i.dispose(),_.disposeSelection(),C.dispose(),n.dispose(),u=Bt}return Object.freeze({mount:J,dispose:Ye,getState:()=>u})}var Fn="__spotpatchRuntime__";function Gt(e){let t=globalThis;t[Fn]?.dispose();let o=qn(e);t[Fn]=o,o.mount()}Gt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Ve});