@spotpatch/vite 1.5.0 → 1.6.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,40 +1,40 @@
1
- import{createReact18Adapter as da}from"@spotpatch/react-adapter";var f={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,xo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),So=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Et(e){let t=Eo(e);return xo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,i)=>{let r=i.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Et(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=Co(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 Ao(n,So)}}var Je="/__spotpatch/v1",At="X-SpotPatch-Token",Qe=Object.freeze({bootstrap:`${Je}/bootstrap`,sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function rt(e,t){return`${Qe.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze(["review","auto","trusted-auto"]),vo=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}),$t=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),zt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),To=Object.freeze(["ready","consent-required","blocked"]),wo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),jt=Object.freeze(["added","modified","deleted"]),Ht=Object.freeze(["passed","failed","cancelled","timed-out"]);var Bt="data-spotpatch-source",Oo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Ut(e){if(e===null)return;let t=Oo.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 Gt="https://github.com/huanglvjing/spotpatch";function tn(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:tn(e.source)}})}function Lo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Io(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 ko(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:tn(e.source,e.code),react:Po(e.react),element:Lo(e.element),styles:Io(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function nn(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(ko)),createdAt:e.createdAt})}var No=new Set(Object.values(f)),Mo=new Set(zt),Do=new Set(Ht),$o=new Set(jt),rn=new Set($t),zo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,jo=/^[A-Za-z0-9_-]+$/,Ho=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function re(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function ht(e){return re(e,64,1)&&typeof e=="string"&&zo.test(e)}function Vt(e){return re(e,128,22)&&typeof e=="string"&&jo.test(e)}function mt(e){return typeof e=="string"&&Ho.test(e)&&Number.isFinite(Date.parse(e))}function et(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function an(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function on(e,t){return e===void 0||re(e,t)}function st(e){return typeof e=="string"&&No.has(e)}function sn(e){return!Ge(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:ht(e.providerProfileId)&&re(e.providerLabel,100)&&ht(e.modelProfileId)&&re(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||mt(e.checkedAt))&&(e.errorCode===void 0||st(e.errorCode))}function cn(e){if(!Ge(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!mt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!st(e.errorCode)||!Ge(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!et(o)||!et(n)||!et(i)||!et(r)||!et(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 Rt(e){return!Ge(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Vt(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&ht(e.providerProfileId)&&re(e.providerLabel,100)&&ht(e.modelProfileId)&&re(e.modelLabel,100)&&re(e.phaseMessage,1024)&&mt(e.createdAt)&&mt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||st(e.errorCode))}function Bo(e){return Ge(e)&&fe(e,["relativePath","kind","additions","deletions"])&&re(e.relativePath,1024)&&typeof e.kind=="string"&&$o.has(e.kind)&&et(e.additions)&&et(e.deletions)}function dn(e){return Ge(e)&&fe(e,["checkId","label","status","durationMs","output"])&&ht(e.checkId)&&re(e.label,100)&&typeof e.status=="string"&&Do.has(e.status)&&et(e.durationMs)&&re(e.output,8e4)}function Uo(e){return Ge(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Vt(e.jobId)&&re(e.summary,8e4)&&re(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Bo)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(dn)}function ln(e){return Ge(e)&&fe(e,["snapshot","result"])&&Rt(e.snapshot)&&(e.result===void 0||Uo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Go(e){return Ge(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&an(e.sequence)&&Vt(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&mt(e.timestamp)&&typeof e.type=="string"&&Ge(e.data)}function pn(e){if(!Go(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&Rt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&re(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&an(t.turn)&&re(t.toolCallId,256)&&re(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&on(t.relativePath,1024)&&on(t.checkLabel,100);case"check":return fe(t,["result"])&&dn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&st(t.code)&&re(t.message,1024);default:return!1}}var Vo=2e6,un=1e5,Wo=4e6,D=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){if(!(!ct(e)||e.ok!==!1||!ct(e.error)))return st(e.error.code)?e.error.code:void 0}function Fo(e){if(!ct(e)||e.ok!==!0||!("data"in e))throw new D;return e.data}function qo(e){return ct(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function fn(e){if(!(!ct(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))fn(t);Object.freeze(e)}}function bt(e){return fn(e),e}async function Ko(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new D;if(e.body===null)throw new D;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let l=await n.read();if(l.done)return a+=i.decode(),a;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new D;a+=i.decode(l.value,{stream:!0})}}catch(l){throw l instanceof D?l:new D}finally{n.releaseLock()}}function hn(e){try{return JSON.parse(e)}catch{throw new D}}async function gn(e){let t=hn(await Ko(e,Vo));if(!e.ok)throw new D(Jo(t));return Fo(t)}function Yo(e,t){if(!sn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new D;return bt(e)}function vt(e,t){if(!Rt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new D;return bt(e)}function Xo(e,t){if(!ln(e)||e.snapshot.jobId!==t)throw new D;return bt(e)}function Zo(e){if(!pn(e))throw new D;return bt(e)}function Qo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function mn(e){return e instanceof D?e.code:void 0}function bn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(a,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[At]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await gn(R)}finally{t.delete(A)}}async function i(a,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(rt(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[At]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await gn(A);return}if(A.body===null)throw new D;let R=A.body.getReader(),j=new TextDecoder("utf-8",{fatal:!0}),g="",k=0,V=0,L=m=>{if(m.trim().length===0)return;if(new TextEncoder().encode(m).byteLength>un)throw new D;let S=Zo(hn(m));if(S.jobId!==a||S.sequence<=V)throw new D;V=S.sequence,l(S)};try{for(;;){let m=await R.read();if(m.done){g+=j.decode(),L(g);return}if(k+=m.value.byteLength,k>Wo)throw await R.cancel(),new D;g+=j.decode(m.value,{stream:!0});let S=g.split(`
2
- `);if(g=S.pop()??"",new TextEncoder().encode(g).byteLength>un)throw await R.cancel(),new D;for(let ee of S)L(ee)}}catch(m){throw m instanceof D||m instanceof DOMException&&m.name==="AbortError"?m:new D}finally{R.releaseLock()}}finally{t.delete(E)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let l=await n(Qe.sourceContext,"POST",a);if(!qo(l))throw new D;return Object.freeze({...l})},async openEditor(a){let l=await n(Qe.openEditor,"POST",a);if(!ct(l)||l.editor!=="auto"&&l.editor!=="vscode"&&l.editor!=="cursor")throw new D;return Object.freeze({editor:l.editor})},async agentCapability(a){return Yo(await n(Qe.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(Qe.agentWorkspaceHealth,"POST",r);if(!cn(a))throw new D;return bt(a)},async createAgentJob(a){let l=Qo(a);return vt(await n(Qe.agentJobs,"POST",l),a)},agentEvents:i,async agentResult(a){return Xo(await n(rt(a,"result"),"POST",r),a)},async cancelAgentJob(a){return vt(await n(rt(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return vt(await n(rt(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return vt(await n(rt(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var er=500,yn=256;function tr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nr(e){return Et(e)}function xn(e,t,o){if(!nr(e))return e==="href"||e==="src"?Ze(t,o):e==="d"&&t.length>yn?`${t.slice(0,yn)}…`:tr(G(t),er)}function Ae(e){return G(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 yt=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 or(e){return"selectorText"in e&&"style"in e}function rr(e){return"cssRules"in e}function ar(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 ir(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,l])=>r+a.length+l.length,0)+i.join(`
3
- `).length}function sr(e,t){return e.href===null?void 0:Ze(e.href,t)}function En(e,t,o,n,i,r){for(let a of t){if(or(a)){let l=!1;try{l=e.matches(a.selectorText)}catch{r.add(yt.selector);continue}l&&i.push(Object.freeze({selector:Ae(a.selectorText),declarations:Ae(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(rr(a)){let l=ar(a);En(e,a.cssRules,o,l===void 0?n:[...n,l],i,r)}}}function cr(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of Sn){let r=Ae(o.getPropertyValue(i).trim());r.length>0&&(n[i]=r)}return n}function An(e){let t=new Set([yt.state,yt.cssInJs,yt.cascade]),o=[],n=e.readCssRules??(R=>R.cssRules);for(let R of e.document.styleSheets){let j;try{j=n(R)}catch{t.add(yt.inaccessibleStylesheet);continue}En(e.element,j,sr(R,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:Ae(r),l=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),E=Object.entries(cr(e.element,l)),A=Array.from(t);for(;ir(i,a,o,Object.fromEntries(E),A)>e.maxCharacters;){if(E.length>0){E.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(E)),warnings:Object.freeze(A)})}var tt=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),dr=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"]),lr=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Rn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function pr(e){return dr.has(e)||e.startsWith("aria-")||e==="data-testid"}function vn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let r=i.name.toLowerCase();if(!pr(r))continue;let a=xn(r,i.value,n);a!==void 0&&o.push(`${r}="${Rn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Tn(e){return G(e).replaceAll(/\s+/gu," ").trim()}function wn(e,t,o,n){if(o.nodeCount>=tt.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${i}${vn(e)}`),!lr.has(r)){for(let a of e.childNodes){if(o.nodeCount>=tt.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let l=Tn(a.textContent??"");if(l.length>0){o.nodeCount+=1;let E=l.length<=tt.maxTextCharacters?l:`${l.slice(0,tt.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Rn(E)}`)}continue}if(a.nodeType===1){if(t>=tt.maxDepth){o.truncated=!0;continue}wn(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${r}>`)}}function ur(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<tt.maxParentDepth;)t.push(vn(o)),o=o.parentElement;return t}function gr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Cn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function fr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function hr(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Cn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${fr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(l=>`.${Cn(l)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(l=>l.tagName===e.tagName),r=i.indexOf(e),a=i.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function mr(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=hr(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function On(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};wn(e.element,0,o,t);let n=ur(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=Tn(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:mr(e.element),sanitizedHtml:gr(t.join(`
4
- `),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=tt.maxTextCharacters?i:`${i.slice(0,tt.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function _n(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function br(e){return e.toLowerCase()}function Pn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Ln(e,t,o){let n=t.split("+").map(R=>R.trim().toLowerCase()).filter(R=>R.length>0),i=n.find(R=>R!=="mod"&&R!=="meta"&&R!=="ctrl"&&R!=="control"&&R!=="alt"&&R!=="option"&&R!=="shift");if(i===void 0||br(e.key)!==i)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&_n(o),l=n.includes("ctrl")||n.includes("control")||r&&!_n(o),E=n.includes("alt")||n.includes("option"),A=n.includes("shift");return e.metaKey===a&&e.ctrlKey===l&&e.altKey===E&&e.shiftKey===A}function yr(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function xr(e){let t=e.filter(l=>l.width>0&&l.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 l of t.slice(1))n=Math.min(n,l.left),i=Math.min(i,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom);return Object.freeze({x:n,y:i,width:r-n,height:a-i})}function In(e,t){if(t.startsWith("inline")){let o=xr(Array.from(e.getClientRects()));if(o!==void 0)return o}return yr(e.getBoundingClientRect())}function kn(e,t){return In(e,t.getComputedStyle(e).display)}function Tt(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=In(e,o.display);return n.width>0&&n.height>0?n:void 0}var at="data-spotpatch-ui",xt=Object.freeze({highlight:2147483646,controls:2147483647});function Nn(e){if(e.closest(`[${at}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(at)}function Sr(e,t){return Tt(e,t)!==void 0}function Er(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Wt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(r=>!Nn(r)&&Sr(r,t));return i.find(r=>!Er(r))??i[0]}function Mn(e){return e instanceof Element&&Nn(e)}var Jt=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function Ar(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function wt(e,t){let o="`".repeat(Math.max(3,Ar(t)+1));return`${o}${e}
1
+ import{createReact18Adapter as da}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_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,xo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),So=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rt(e){let t=Eo(e);return xo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function J(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,i)=>{let r=i.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Rt(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 Qe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=J(o);try{let i=new URL(n,t),r=Co(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 Ao(n,So)}}var Fe="/__spotpatch/v1",vt="X-SpotPatch-Token",et=Object.freeze({bootstrap:`${Fe}/bootstrap`,sourceContext:`${Fe}/source-context`,openEditor:`${Fe}/open-editor`,agentCapability:`${Fe}/agent/capability`,agentWorkspaceHealth:`${Fe}/agent/workspace-health`,agentJobs:`${Fe}/agent/jobs`});function at(e,t){return`${et.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze(["review","auto","trusted-auto"]),vo=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}),Ht=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Bt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),To=Object.freeze(["ready","consent-required","blocked"]),wo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),Ut=Object.freeze(["added","modified","deleted"]),Gt=Object.freeze(["passed","failed","cancelled","timed-out"]);var Vt="data-spotpatch-source",Oo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Wt(e){if(e===null)return;let t=Oo.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 Jt="https://github.com/huanglvjing/spotpatch";function on(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:on(e.source)}})}function Lo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Io(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 ko(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:on(e.source,e.code),react:Po(e.react),element:Lo(e.element),styles:Io(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function rn(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(ko)),createdAt:e.createdAt})}var No=new Set(Object.values(h)),Mo=new Set(Bt),Do=new Set(Gt),$o=new Set(Ut),sn=new Set(Ht),zo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,jo=/^[A-Za-z0-9_-]+$/,Ho=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function he(e,t){return Object.keys(e).every(o=>t.includes(o))}function ce(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function mt(e){return ce(e,64,1)&&typeof e=="string"&&zo.test(e)}function Ft(e){return ce(e,128,22)&&typeof e=="string"&&jo.test(e)}function bt(e){return typeof e=="string"&&Ho.test(e)&&Number.isFinite(Date.parse(e))}function tt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function cn(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function an(e,t){return e===void 0||ce(e,t)}function ct(e){return typeof e=="string"&&No.has(e)}function dn(e){return!Ge(e)||!he(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:mt(e.providerProfileId)&&ce(e.providerLabel,100)&&mt(e.modelProfileId)&&ce(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||bt(e.checkedAt))&&(e.errorCode===void 0||ct(e.errorCode))}function ln(e){if(!Ge(e)||!he(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!bt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!ct(e.errorCode)||!Ge(e.changes)||!he(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!tt(o)||!tt(n)||!tt(i)||!tt(r)||!tt(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 wt(e){return!Ge(e)||!he(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Ft(e.jobId)&&typeof e.status=="string"&&sn.has(e.status)&&mt(e.providerProfileId)&&ce(e.providerLabel,100)&&mt(e.modelProfileId)&&ce(e.modelLabel,100)&&ce(e.phaseMessage,1024)&&bt(e.createdAt)&&bt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||ct(e.errorCode))}function Bo(e){return Ge(e)&&he(e,["relativePath","kind","additions","deletions"])&&ce(e.relativePath,1024)&&typeof e.kind=="string"&&$o.has(e.kind)&&tt(e.additions)&&tt(e.deletions)}function pn(e){return Ge(e)&&he(e,["checkId","label","status","durationMs","output"])&&mt(e.checkId)&&ce(e.label,100)&&typeof e.status=="string"&&Do.has(e.status)&&tt(e.durationMs)&&ce(e.output,8e4)}function Uo(e){return Ge(e)&&he(e,["jobId","summary","diff","files","checks"])&&Ft(e.jobId)&&ce(e.summary,8e4)&&ce(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Bo)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(pn)}function un(e){return Ge(e)&&he(e,["snapshot","result"])&&wt(e.snapshot)&&(e.result===void 0||Uo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Go(e){return Ge(e)&&he(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&cn(e.sequence)&&Ft(e.jobId)&&typeof e.status=="string"&&sn.has(e.status)&&bt(e.timestamp)&&typeof e.type=="string"&&Ge(e.data)}function gn(e){if(!Go(e))return!1;let t=e.data;switch(e.type){case"snapshot":return he(t,["snapshot"])&&wt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return he(t,["message"])&&ce(t.message,1024);case"tool":return he(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&cn(t.turn)&&ce(t.toolCallId,256)&&ce(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&an(t.relativePath,1024)&&an(t.checkLabel,100);case"check":return he(t,["result"])&&pn(t.result);case"result-ready":return he(t,["hasResult"])&&t.hasResult===!0;case"error":return he(t,["code","message"])&&ct(t.code)&&ce(t.message,1024);default:return!1}}var Vo=2e6,fn=1e5,Wo=4e6,D=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){if(!(!dt(e)||e.ok!==!1||!dt(e.error)))return ct(e.error.code)?e.error.code:void 0}function Fo(e){if(!dt(e)||e.ok!==!0||!("data"in e))throw new D;return e.data}function qo(e){return dt(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 mn(e){if(!(!dt(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))mn(t);Object.freeze(e)}}function yt(e){return mn(e),e}async function Ko(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new D;if(e.body===null)throw new D;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let p=await n.read();if(p.done)return a+=i.decode(),a;if(r+=p.value.byteLength,r>t)throw await n.cancel(),new D;a+=i.decode(p.value,{stream:!0})}}catch(p){throw p instanceof D?p:new D}finally{n.releaseLock()}}function bn(e){try{return JSON.parse(e)}catch{throw new D}}async function hn(e){let t=bn(await Ko(e,Vo));if(!e.ok)throw new D(Jo(t));return Fo(t)}function Yo(e,t){if(!dn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new D;return yt(e)}function Ot(e,t){if(!wt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new D;return yt(e)}function Xo(e,t){if(!un(e)||e.snapshot.jobId!==t)throw new D;return yt(e)}function Zo(e){if(!gn(e))throw new D;return yt(e)}function Qo(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 yn(e){return e instanceof D?e.code:void 0}function xn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,p,E){let A=new AbortController;t.add(A);try{let C=await e.fetch(a,{method:p,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[vt]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await hn(C)}finally{t.delete(A)}}async function i(a,p){let E=new AbortController;t.add(E);try{let A=await e.fetch(at(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[vt]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await hn(A);return}if(A.body===null)throw new D;let C=A.body.getReader(),U=new TextDecoder("utf-8",{fatal:!0}),g="",M=0,$=0,L=x=>{if(x.trim().length===0)return;if(new TextEncoder().encode(x).byteLength>fn)throw new D;let T=Zo(bn(x));if(T.jobId!==a||T.sequence<=$)throw new D;$=T.sequence,p(T)};try{for(;;){let x=await C.read();if(x.done){g+=U.decode(),L(g);return}if(M+=x.value.byteLength,M>Wo)throw await C.cancel(),new D;g+=U.decode(x.value,{stream:!0});let T=g.split(`
2
+ `);if(g=T.pop()??"",new TextEncoder().encode(g).byteLength>fn)throw await C.cancel(),new D;for(let V of T)L(V)}}catch(x){throw x instanceof D||x instanceof DOMException&&x.name==="AbortError"?x:new D}finally{C.releaseLock()}}finally{t.delete(E)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let p=await n(et.sourceContext,"POST",a);if(!qo(p))throw new D;return Object.freeze({...p})},async openEditor(a){let p=await n(et.openEditor,"POST",a);if(!dt(p)||p.editor!=="auto"&&p.editor!=="vscode"&&p.editor!=="cursor")throw new D;return Object.freeze({editor:p.editor})},async agentCapability(a){return Yo(await n(et.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(et.agentWorkspaceHealth,"POST",r);if(!ln(a))throw new D;return yt(a)},async createAgentJob(a){let p=Qo(a);return Ot(await n(et.agentJobs,"POST",p),a)},agentEvents:i,async agentResult(a){return Xo(await n(at(a,"result"),"POST",r),a)},async cancelAgentJob(a){return Ot(await n(at(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return Ot(await n(at(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return Ot(await n(at(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var er=500,Sn=256;function tr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nr(e){return Rt(e)}function En(e,t,o){if(!nr(e))return e==="href"||e==="src"?Qe(t,o):e==="d"&&t.length>Sn?`${t.slice(0,Sn)}…`:tr(J(t),er)}function Ce(e){return J(e)}var An=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 xt=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 or(e){return"selectorText"in e&&"style"in e}function rr(e){return"cssRules"in e}function ar(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 ir(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,p])=>r+a.length+p.length,0)+i.join(`
3
+ `).length}function sr(e,t){return e.href===null?void 0:Qe(e.href,t)}function Cn(e,t,o,n,i,r){for(let a of t){if(or(a)){let p=!1;try{p=e.matches(a.selectorText)}catch{r.add(xt.selector);continue}p&&i.push(Object.freeze({selector:Ce(a.selectorText),declarations:Ce(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(rr(a)){let p=ar(a);Cn(e,a.cssRules,o,p===void 0?n:[...n,p],i,r)}}}function cr(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of An){let r=Ce(o.getPropertyValue(i).trim());r.length>0&&(n[i]=r)}return n}function Rn(e){let t=new Set([xt.state,xt.cssInJs,xt.cascade]),o=[],n=e.readCssRules??(C=>C.cssRules);for(let C of e.document.styleSheets){let U;try{U=n(C)}catch{t.add(xt.inaccessibleStylesheet);continue}Cn(e.element,U,sr(C,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:Ce(r),p=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),E=Object.entries(cr(e.element,p)),A=Array.from(t);for(;ir(i,a,o,Object.fromEntries(E),A)>e.maxCharacters;){if(E.length>0){E.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(E)),warnings:Object.freeze(A)})}var nt=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),dr=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"]),lr=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Tn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function pr(e){return dr.has(e)||e.startsWith("aria-")||e==="data-testid"}function wn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let r=i.name.toLowerCase();if(!pr(r))continue;let a=En(r,i.value,n);a!==void 0&&o.push(`${r}="${Tn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function On(e){return J(e).replaceAll(/\s+/gu," ").trim()}function _n(e,t,o,n){if(o.nodeCount>=nt.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${i}${wn(e)}`),!lr.has(r)){for(let a of e.childNodes){if(o.nodeCount>=nt.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let p=On(a.textContent??"");if(p.length>0){o.nodeCount+=1;let E=p.length<=nt.maxTextCharacters?p:`${p.slice(0,nt.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Tn(E)}`)}continue}if(a.nodeType===1){if(t>=nt.maxDepth){o.truncated=!0;continue}_n(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${r}>`)}}function ur(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<nt.maxParentDepth;)t.push(wn(o)),o=o.parentElement;return t}function gr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function vn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function fr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function hr(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${vn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${fr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(p=>`.${vn(p)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(p=>p.tagName===e.tagName),r=i.indexOf(e),a=i.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function mr(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=hr(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Pn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};_n(e.element,0,o,t);let n=ur(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=On(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:mr(e.element),sanitizedHtml:gr(t.join(`
4
+ `),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=nt.maxTextCharacters?i:`${i.slice(0,nt.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function Ln(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function br(e){return e.toLowerCase()}function In(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function kn(e,t,o){let n=t.split("+").map(C=>C.trim().toLowerCase()).filter(C=>C.length>0),i=n.find(C=>C!=="mod"&&C!=="meta"&&C!=="ctrl"&&C!=="control"&&C!=="alt"&&C!=="option"&&C!=="shift");if(i===void 0||br(e.key)!==i)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&Ln(o),p=n.includes("ctrl")||n.includes("control")||r&&!Ln(o),E=n.includes("alt")||n.includes("option"),A=n.includes("shift");return e.metaKey===a&&e.ctrlKey===p&&e.altKey===E&&e.shiftKey===A}function yr(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function xr(e){let t=e.filter(p=>p.width>0&&p.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 p of t.slice(1))n=Math.min(n,p.left),i=Math.min(i,p.top),r=Math.max(r,p.right),a=Math.max(a,p.bottom);return Object.freeze({x:n,y:i,width:r-n,height:a-i})}function Nn(e,t){if(t.startsWith("inline")){let o=xr(Array.from(e.getClientRects()));if(o!==void 0)return o}return yr(e.getBoundingClientRect())}function Mn(e,t){return Nn(e,t.getComputedStyle(e).display)}function _t(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=Nn(e,o.display);return n.width>0&&n.height>0?n:void 0}var it="data-spotpatch-ui",St=Object.freeze({highlight:2147483646,controls:2147483647});function Dn(e){if(e.closest(`[${it}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(it)}function Sr(e,t){return _t(e,t)!==void 0}function Er(e){return e.tagName==="HTML"||e.tagName==="BODY"}function qt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(r=>!Dn(r)&&Sr(r,t));return i.find(r=>!Er(r))??i[0]}function $n(e){return e instanceof Element&&Dn(e)}var Kt=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function Ar(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function Pt(e,t){let o="`".repeat(Math.max(3,Ar(t)+1));return`${o}${e}
5
5
  ${t}
6
- ${o}`}function $n(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 zn(e,t){return e.split(`
7
- `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Cr(e){let t=[e.source===void 0?void 0:`/* source: ${Ae(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Ae(e.media)} */`].filter(n=>n!==void 0),o=`${Ae(e.selector)} {
8
- ${Ae(e.declarations)}
6
+ ${o}`}function jn(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${J(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function Hn(e,t){return e.split(`
7
+ `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Cr(e){let t=[e.source===void 0?void 0:`/* source: ${Ce(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Ce(e.media)} */`].filter(n=>n!==void 0),o=`${Ce(e.selector)} {
8
+ ${Ce(e.declarations)}
9
9
  }`;return[...t,o].join(`
10
- `)}function Rr(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Ae).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Ae(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(Cr)];return i.length===0?o.unavailable:wt("css",i.join(`
10
+ `)}function Rr(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Ce).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Ce(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(Cr)];return i.length===0?o.unavailable:Pt("css",i.join(`
11
11
 
12
- `))}function vr(e,t){return e.length===0?t.unavailable:wt("css",e.map(([o,n])=>`${Ae(o)}: ${Ae(n)};`).join(`
13
- `))}function Tr(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}
12
+ `))}function vr(e,t){return e.length===0?t.unavailable:Pt("css",e.map(([o,n])=>`${Ce(o)}: ${Ce(n)};`).join(`
13
+ `))}function Tr(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${J(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${J(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(J).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
14
14
 
15
- ${wt(e.code.language,G(t.codeLines.join(`
16
- `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${Ze(e.page.url,e.page.url)}>
17
- - ${n.pathname}: ${G(e.page.pathname)}
18
- - ${n.title}: ${G(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,i.join(`
19
- `),`#### ${n.source}`,`- ${n.file}: ${$n(e,n)}
15
+ ${Pt(e.code.language,J(t.codeLines.join(`
16
+ `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${Qe(e.page.url,e.page.url)}>
17
+ - ${n.pathname}: ${J(e.page.pathname)}
18
+ - ${n.title}: ${J(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,i.join(`
19
+ `),`#### ${n.source}`,`- ${n.file}: ${jn(e,n)}
20
20
  - ${n.origin}: ${e.source.origin}
21
- - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,wt("html",G(t.dom)),`#### ${n.styles}`,Rr(e,t.matchedRules,n),`#### ${n.computedStyles}`,vr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${G(a)}`).join(`
21
+ - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,Pt("html",J(t.dom)),`#### ${n.styles}`,Rr(e,t.matchedRules,n),`#### ${n.computedStyles}`,vr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${J(a)}`).join(`
22
22
  `)].join(`
23
23
 
24
- `)}function Dn(e,t){let o=Ze(e.page.url,e.page.url),n=Jt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
25
- - ${n.pathname}: ${G(e.page.pathname)}
24
+ `)}function zn(e,t){let o=Qe(e.page.url,e.page.url),n=Kt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
25
+ - ${n.pathname}: ${J(e.page.pathname)}
26
26
  - ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
27
27
  - ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
28
28
  - ${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 Tr(i,a,r,n)}).join(`
29
29
 
30
30
  `),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
31
31
 
32
- `)}function wr(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 Or(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 _r(e){return{pageTitle:G(e.page.title),targets:e.targets.map(Or)}}function Pr(e,t,o){let n=Jt[e.locale],i=[(r,a)=>a.computedEntries.pop()!==void 0,(r,a)=>a.reactStack.pop()!==void 0,(r,a)=>{let l=zn(a.dom,n.unavailable);return a.dom===l?!1:(a.dom=l,!0)},(r,a)=>a.matchedRules.shift()!==void 0,wr,(r,a)=>a.warnings.pop()!==void 0];for(let r of i)for(let a=0;a<e.targets.length;a+=1){let l=(o+a)%e.targets.length,E=e.targets[l],A=t.targets[l];if(E!==void 0&&A!==void 0&&r(E,A))return(l+1)%e.targets.length}}function Lr(e,t){let o=Jt[e.locale],n=e.targets.map((i,r)=>{let a=t.targets[r],l=i.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${a?.instruction??G(i.instruction)}`,`- ${o.file}: ${$n(i,o)}`,...l===void 0?[]:[`- ${o.component}: ${G(l)}`],`- ${o.element}: ${G(zn(a?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
32
+ `)}function wr(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 Or(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 _r(e){return{pageTitle:J(e.page.title),targets:e.targets.map(Or)}}function Pr(e,t,o){let n=Kt[e.locale],i=[(r,a)=>a.computedEntries.pop()!==void 0,(r,a)=>a.reactStack.pop()!==void 0,(r,a)=>{let p=Hn(a.dom,n.unavailable);return a.dom===p?!1:(a.dom=p,!0)},(r,a)=>a.matchedRules.shift()!==void 0,wr,(r,a)=>a.warnings.pop()!==void 0];for(let r of i)for(let a=0;a<e.targets.length;a+=1){let p=(o+a)%e.targets.length,E=e.targets[p],A=t.targets[p];if(E!==void 0&&A!==void 0&&r(E,A))return(p+1)%e.targets.length}}function Lr(e,t){let o=Kt[e.locale],n=e.targets.map((i,r)=>{let a=t.targets[r],p=i.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${a?.instruction??J(i.instruction)}`,`- ${o.file}: ${jn(i,o)}`,...p===void 0?[]:[`- ${o.component}: ${J(p)}`],`- ${o.element}: ${J(Hn(a?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
33
33
  `)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
34
34
 
35
35
  `),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
36
36
 
37
- `)}function Ir(e,t){let o=_r(e),n=Dn(e,o),i=0;for(;n.length>t;){let a=Pr(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=Dn(e,o)}if(n.length<=t)return n;let r=Lr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function jn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return Ir(t,e.maxCharacters)}})}var de=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Ft=de.idle;function kr(e){return e.type==="ACTIVATE"?de.inspecting:e.type==="RESTORE"?de.selected:de.idle}function Nr(e){switch(e.type){case"HOVER":return de.inspecting;case"SELECT":return de.selected;case"CANCEL":return de.idle;default:return de.inspecting}}function Mr(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 Dr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return de.selected;case"COPY_FAILURE":return de.previewing;default:return de.previewing}}function Hn(e,t){switch(e.status){case"idle":return kr(t);case"inspecting":return Nr(t);case"selected":return Mr(t);case"previewing":return Dr(t)}}var $r="spotpatch:selection:";function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Q(e){return typeof e=="string"}function qe(e){return e===void 0||Q(e)}function qt(e){return Array.isArray(e)&&e.length<=256&&e.every(Q)}function Ve(e){return typeof e=="number"&&Number.isFinite(e)}function Bn(e){return e===void 0||Ve(e)}function Un(e){let t=Me(e);return t!==void 0&&Q(t.origin)&&Q(t.confidence)&&qe(t.fileId)&&qe(t.relativePath)&&Bn(t.line)&&Bn(t.column)}function zr(e){let t=Me(e);return t!==void 0&&typeof t.supported=="boolean"&&qe(t.version)&&qe(t.componentName)&&qt(t.componentStack)&&(t.source===void 0||Un(t.source))}function jr(e){let t=Me(e);return t!==void 0&&Q(t.url)&&Q(t.pathname)&&Q(t.title)&&Ve(t.viewportWidth)&&Ve(t.viewportHeight)&&Ve(t.devicePixelRatio)}function Hr(e){let t=Me(e),o=Me(t?.rect);return t!==void 0&&Q(t.tagName)&&Q(t.selector)&&Q(t.sanitizedHtml)&&qe(t.textPreview)&&qe(t.role)&&o!==void 0&&Ve(o.x)&&Ve(o.y)&&Ve(o.width)&&Ve(o.height)}function Br(e){let t=Me(e),o=Me(t?.computed);return t!==void 0&&qt(t.classNames)&&qe(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let i=Me(n);return i!==void 0&&Q(i.selector)&&Q(i.declarations)&&qe(i.source)&&qe(i.media)})&&o!==void 0&&Object.values(o).every(Q)&&qt(t.warnings)}function Ur(e){let t=Me(e);return t!==void 0&&Q(t.relativePath)&&Q(t.language)&&Ve(t.startLine)&&Ve(t.endLine)&&Q(t.excerpt)&&Q(t.boundary)}function Gr(e){let t=Me(e);return t!==void 0&&Q(t.id)&&Q(t.instruction)&&jr(t.page)&&Un(t.source)&&zr(t.react)&&Hr(t.element)&&Br(t.styles)&&(t.code===void 0||Ur(t.code))}function Vr(e,t){let o=Me(e);if(o?.version!==1||typeof o.open!="boolean"||!Number.isSafeInteger(o.sequence)||Number(o.sequence)<0||o.activeTargetId!==void 0&&typeof o.activeTargetId!="string"||!Array.isArray(o.targets)||o.targets.length===0||o.targets.length>t||!o.targets.every(Gr))return;let n=o.targets,i=n.map(({id:r})=>r);if(!(new Set(i).size!==i.length||o.activeTargetId!==void 0&&!i.includes(o.activeTargetId)))return{...o.activeTargetId===void 0?{}:{activeTargetId:o.activeTargetId},open:o.open,sequence:Number(o.sequence),targets:n}}function Gn(e,t,o){let n=`${$r}${t}`,i;try{i=e.sessionStorage}catch{i=void 0}return Object.freeze({clear(){try{i?.removeItem(n)}catch{}},load(){let r;try{r=i?.getItem(n)??null}catch{return}if(!(r===null||r.length>1e6))try{return Vr(JSON.parse(r),o)}catch{return}},save(r){try{i?.setItem(n,JSON.stringify({version:1,...r}))}catch{}}})}var Vn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Jn(e){return Ut(e.getAttribute(Bt))}function Wr(e){let t=e.parentElement;for(;t!==null;){let o=Jn(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 Jr(){return Object.freeze({origin:"none",confidence:"unknown"})}function Kt(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 Fn(e){let t=!0;function o(n){if(!t)return Vn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Vn}}return Object.freeze({resolve(n){let i=Jn(n),r=o(n);if(i!==void 0)return Object.freeze({react:r,source:Wn(i,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let a=Wr(n);return Object.freeze(a!==void 0?{react:r,source:Wn(a,"dom-ancestor","approximate")}:{react:r,source:Jr()})},dispose(){t=!1,e.adapter.dispose()}})}function d(e,t){let o=e.createElement(t);return o.setAttribute(at,""),o}function q(e,t,o=""){let n=d(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Kn=`
37
+ `)}function Ir(e,t){let o=_r(e),n=zn(e,o),i=0;for(;n.length>t;){let a=Pr(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=zn(e,o)}if(n.length<=t)return n;let r=Lr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function Bn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return Ir(t,e.maxCharacters)}})}var pe=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Yt=pe.idle;function kr(e){return e.type==="ACTIVATE"?pe.inspecting:e.type==="RESTORE"?pe.selected:pe.idle}function Nr(e){switch(e.type){case"HOVER":return pe.inspecting;case"SELECT":return pe.selected;case"CANCEL":return pe.idle;default:return pe.inspecting}}function Mr(e){switch(e.type){case"RESELECT":return pe.inspecting;case"CLOSE":return pe.idle;case"PREVIEW":return pe.previewing;case"OPEN_EDITOR":return pe.selected;default:return pe.selected}}function Dr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return pe.selected;case"COPY_FAILURE":return pe.previewing;default:return pe.previewing}}function Un(e,t){switch(e.status){case"idle":return kr(t);case"inspecting":return Nr(t);case"selected":return Mr(t);case"previewing":return Dr(t)}}var $r="spotpatch:selection:";function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ne(e){return typeof e=="string"}function Ke(e){return e===void 0||ne(e)}function Xt(e){return Array.isArray(e)&&e.length<=256&&e.every(ne)}function Ve(e){return typeof e=="number"&&Number.isFinite(e)}function Gn(e){return e===void 0||Ve(e)}function Vn(e){let t=je(e);return t!==void 0&&ne(t.origin)&&ne(t.confidence)&&Ke(t.fileId)&&Ke(t.relativePath)&&Gn(t.line)&&Gn(t.column)}function zr(e){let t=je(e);return t!==void 0&&typeof t.supported=="boolean"&&Ke(t.version)&&Ke(t.componentName)&&Xt(t.componentStack)&&(t.source===void 0||Vn(t.source))}function jr(e){let t=je(e);return t!==void 0&&ne(t.url)&&ne(t.pathname)&&ne(t.title)&&Ve(t.viewportWidth)&&Ve(t.viewportHeight)&&Ve(t.devicePixelRatio)}function Hr(e){let t=je(e),o=je(t?.rect);return t!==void 0&&ne(t.tagName)&&ne(t.selector)&&ne(t.sanitizedHtml)&&Ke(t.textPreview)&&Ke(t.role)&&o!==void 0&&Ve(o.x)&&Ve(o.y)&&Ve(o.width)&&Ve(o.height)}function Br(e){let t=je(e),o=je(t?.computed);return t!==void 0&&Xt(t.classNames)&&Ke(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let i=je(n);return i!==void 0&&ne(i.selector)&&ne(i.declarations)&&Ke(i.source)&&Ke(i.media)})&&o!==void 0&&Object.values(o).every(ne)&&Xt(t.warnings)}function Ur(e){let t=je(e);return t!==void 0&&ne(t.relativePath)&&ne(t.language)&&Ve(t.startLine)&&Ve(t.endLine)&&ne(t.excerpt)&&ne(t.boundary)}function Gr(e){let t=je(e);return t!==void 0&&ne(t.id)&&ne(t.instruction)&&jr(t.page)&&Vn(t.source)&&zr(t.react)&&Hr(t.element)&&Br(t.styles)&&(t.code===void 0||Ur(t.code))}function Vr(e,t){let o=je(e);if(o?.version!==1||typeof o.open!="boolean"||!Number.isSafeInteger(o.sequence)||Number(o.sequence)<0||o.activeTargetId!==void 0&&typeof o.activeTargetId!="string"||!Array.isArray(o.targets)||o.targets.length===0||o.targets.length>t||!o.targets.every(Gr))return;let n=o.targets,i=n.map(({id:r})=>r);if(!(new Set(i).size!==i.length||o.activeTargetId!==void 0&&!i.includes(o.activeTargetId)))return{...o.activeTargetId===void 0?{}:{activeTargetId:o.activeTargetId},open:o.open,sequence:Number(o.sequence),targets:n}}function Wn(e,t,o){let n=`${$r}${t}`,i;try{i=e.sessionStorage}catch{i=void 0}return Object.freeze({clear(){try{i?.removeItem(n)}catch{}},load(){let r;try{r=i?.getItem(n)??null}catch{return}if(!(r===null||r.length>1e6))try{return Vr(JSON.parse(r),o)}catch{return}},save(r){try{i?.setItem(n,JSON.stringify({version:1,...r}))}catch{}}})}var Jn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function qn(e){return Wt(e.getAttribute(Vt))}function Wr(e){let t=e.parentElement;for(;t!==null;){let o=qn(t);if(o!==void 0)return o;t=t.parentElement}}function Fn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Jr(){return Object.freeze({origin:"none",confidence:"unknown"})}function Zt(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function Kn(e){let t=!0;function o(n){if(!t)return Jn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Jn}}return Object.freeze({resolve(n){let i=qn(n),r=o(n);if(i!==void 0)return Object.freeze({react:r,source:Fn(i,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let a=Wr(n);return Object.freeze(a!==void 0?{react:r,source:Fn(a,"dom-ancestor","approximate")}:{react:r,source:Jr()})},dispose(){t=!1,e.adapter.dispose()}})}function c(e,t){let o=e.createElement(t);return o.setAttribute(it,""),o}function ee(e,t,o=""){let n=c(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Yn=`
38
38
  .spotpatch-agent {
39
39
  margin-top: 10px;
40
40
  overflow: hidden;
@@ -61,7 +61,8 @@ ${wt(e.code.language,G(t.codeLines.join(`
61
61
  font-weight: 650;
62
62
  }
63
63
  .spotpatch-agent-setup { padding: 12px; }
64
- .spotpatch-agent-selectors { display: grid; grid-template-columns: 1fr; gap: 10px; }
64
+ .spotpatch-agent-selectors { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
65
+ .spotpatch-agent-mode { grid-column: 1 / -1; }
65
66
  .spotpatch-agent-selectors label { min-width: 0; color: var(--spotpatch-text-secondary); font-size: 11.5px; font-weight: 580; }
66
67
  .spotpatch-agent select {
67
68
  box-sizing: border-box;
@@ -99,19 +100,21 @@ ${wt(e.code.language,G(t.codeLines.join(`
99
100
  width: anchor-size(width);
100
101
  max-height: min(280px, 40vh);
101
102
  margin: 0;
102
- overflow: hidden;
103
+ overflow: auto;
103
104
  border: 1px solid rgb(139 124 247 / 28%);
104
105
  border-radius: 12px;
105
106
  padding: 6px;
106
107
  background: #10151e;
107
108
  box-shadow: 0 18px 50px rgb(0 0 0 / 38%);
108
- opacity: 0;
109
- transform: translateY(-5px) scale(.985);
109
+ opacity: 1;
110
+ transform: translateY(0) scale(1);
110
111
  transition: opacity 150ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1), overlay 180ms allow-discrete, display 180ms allow-discrete;
111
112
  }
112
- ::picker(select):popover-open { opacity: 1; transform: translateY(0) scale(1); }
113
113
  @starting-style {
114
- ::picker(select):popover-open { opacity: 0; transform: translateY(-5px) scale(.985); }
114
+ .spotpatch-agent select::picker(select):popover-open {
115
+ opacity: 0;
116
+ transform: translateY(-5px) scale(.985);
117
+ }
115
118
  }
116
119
  .spotpatch-agent select option {
117
120
  min-height: 42px;
@@ -246,7 +249,11 @@ ${wt(e.code.language,G(t.codeLines.join(`
246
249
  white-space: pre;
247
250
  user-select: text;
248
251
  }
249
- `;function qn(e,t,o,n){let i=e.createElement("option");i.value=o,i.textContent=n,t.append(i)}function Yn(e,t,o){let n=o.messages(),i=d(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let a=d(e,"span");a.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(a,l);let E=d(e,"div");E.className="spotpatch-agent-setup";let A=d(e,"div");A.className="spotpatch-agent-selectors";let R=d(e,"label"),j=d(e,"span"),g=d(e,"select");R.append(j,g);let k=d(e,"label"),V=d(e,"span"),L=d(e,"select");k.append(V,L),A.append(R,k);let m=d(e,"label");m.className="spotpatch-consent";let S=d(e,"input");S.type="checkbox";let ee=d(e,"span");m.append(S,ee);let K=d(e,"label");K.className="spotpatch-consent spotpatch-workspace-consent",K.hidden=!0;let h=d(e,"input");h.type="checkbox";let y=d(e,"span"),T=d(e,"strong"),O=d(e,"small");y.append(T,O),K.append(h,y);let I=d(e,"div");I.className="spotpatch-agent-health-list";let W=d(e,"p");W.className="spotpatch-agent-workspace",W.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",I.append(W,$),E.append(A,m,K,I);let ae=d(e,"div");ae.className="spotpatch-agent-job",ae.hidden=!0;let ie=d(e,"div");ie.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let N=d(e,"span");N.className="spotpatch-agent-status",ie.append(B,N);let _e=d(e,"p");_e.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let Y=d(e,"ul");Y.className="spotpatch-agent-activity";let ve=d(e,"div");ve.className="spotpatch-agent-result",ve.hidden=!0;let Te=d(e,"p");Te.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let te=d(e,"div");te.className="spotpatch-agent-checks";let M=d(e,"pre");M.className="spotpatch-agent-diff",M.tabIndex=0,M.setAttribute("aria-label",n.agent.diffAriaLabel),ve.append(Te,me,te,M),ae.append(ie,_e,he,Y,ve),i.append(r,E,ae);let be=q(e,n.agent.testConnection),we=q(e,n.agent.run,"spotpatch-run"),ne=q(e,n.agent.cancel),le=q(e,n.agent.apply,"spotpatch-primary"),De=q(e,n.agent.revert),ye=q(e,n.agent.revise),Oe=t.enabled?t.providers:[],xe=t.enabled&&t.applyMode==="trusted-auto";m.classList.toggle("spotpatch-trusted-consent",xe);let w=new Map(Oe.map(c=>[c.id,c])),Pe=!1,Se=!0,_=!1,F=!1,se=!1,Ce=!1,pe,ue,Le=[],Ie,Ee="idle",$e=n.agent.connectionNotTested,X,Z="idle",ze,ke;for(let c of Oe)qn(e,g,c.id,c.label);t.enabled&&(g.value=t.defaultProvider);let Re=()=>w.get(g.value),Ne=c=>c===void 0?n.agent.providerUnavailable:xe?n.agent.trustedFastConsent(c.label):n.agent.consent(c.label),je=()=>xe?S.checked:h.checked,He=()=>{let c=Re();if(L.replaceChildren(),c===void 0){ee.textContent=Ne(c);return}for(let x of c.models)qn(e,L,x.id,x.label);L.value=c.defaultModel,ee.textContent=Ne(c)},z=()=>{let c=t.enabled&&_&&!F;we.textContent=se?n.agent.verifying:n.agent.run,we.classList.toggle("spotpatch-primary",Ce),be.hidden=!c,we.hidden=!c,be.disabled=!Se||se||Re()===void 0,we.disabled=!Se||se||!Pe||!S.checked||Z==="idle"||Z==="checking"||Z==="blocked"||Z==="consent-required"&&!je()||Re()===void 0||L.value.length===0,(!F||!_)&&(ne.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},Be=()=>{if(Z==="idle")W.textContent=n.agent.workspaceNotChecked;else if(Z==="checking")W.textContent=n.agent.checkingWorkspace;else if(Z==="ready")W.textContent=n.agent.workspaceReady;else if(Z==="consent-required"){let c=ze?.changes;W.textContent=n.agent.workspaceDirty(c?.staged??0,c?.unstaged??0,c?.untracked??0)}else W.textContent=ke===void 0?n.errors.INTERNAL_ERROR:n.errors[ke]};function Ke(){He(),S.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,Ee="idle",$e=n.agent.connectionNotTested,X=void 0,Ce=!1,z()}function Ye(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,Ee="idle",$e=n.agent.connectionNotTested,X=void 0,Ce=!1,z()}He(),g.addEventListener("change",Ke),L.addEventListener("change",Ye),S.addEventListener("change",z),h.addEventListener("change",z);function it(){if(pe===void 0)return;let c=pe,x=ue;B.textContent=`${c.providerLabel} · ${c.modelLabel}`,N.textContent=n.agent.status(c.status),_e.textContent=c.phaseMessage;let P=Ie??c.errorCode;he.hidden=P===void 0,he.textContent=P===void 0?"":n.errors[P],Y.replaceChildren();for(let C of Le.slice(-8)){let oe=d(e,"li");oe.dataset.state=C.state,oe.textContent=C.label,Y.append(oe)}ve.hidden=x===void 0,Te.textContent=x?.summary??"",me.replaceChildren(),te.replaceChildren(),M.textContent=x?.diff??"";for(let C of x?.files??[]){let oe=d(e,"li");oe.textContent=`${C.kind} ${C.relativePath} (+${String(C.additions)} / -${String(C.deletions)})`,me.append(oe)}for(let C of x?.checks??[]){let oe=d(e,"details"),dt=d(e,"summary");dt.textContent=`${C.label}: ${C.status} · ${String(C.durationMs)} ms`;let lt=d(e,"pre");lt.textContent=C.output.length===0?n.agent.noOutput:C.output,oe.append(dt,lt),te.append(oe)}be.hidden=!0,we.hidden=!0,ne.hidden=!_||!c.canCancel,ne.textContent=c.status==="awaiting-review"?n.agent.discard:n.agent.cancel,le.hidden=!_||!c.canApply,De.hidden=!_||!c.canRevert,ye.hidden=!_||!["completed","cancelled","reverted","failed"].includes(c.status)}function s(){n=o.messages(),a.textContent=n.agent.title,l.textContent=xe?n.agent.trustedFast:t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,j.textContent=n.agent.provider,V.textContent=n.agent.model,g.setAttribute("aria-label",n.agent.providerAriaLabel),L.setAttribute("aria-label",n.agent.modelAriaLabel),T.textContent=n.agent.includeLocalChanges,O.textContent=n.agent.includeLocalChangesHelp,M.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,le.textContent=n.agent.apply,De.textContent=n.agent.revert,ye.textContent=n.agent.revise;let c=Re();ee.textContent=Ne(c),Ee==="idle"?$.textContent=n.agent.connectionNotTested:Ee==="probing"?$.textContent=n.agent.testingCapability:Ee==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:X!==void 0?$.textContent=n.errors[X]:Re()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=$e,Be(),z(),it()}let p=o.subscribe(s);return s(),Object.freeze({root:i,providerSelect:g,modelSelect:L,consentCheckbox:S,workspaceConsentCheckbox:h,testButton:be,runButton:we,cancelButton:ne,applyButton:le,revertButton:De,resetButton:ye,consentGranted(){return S.checked},workspaceConsentGranted(){return je()},readSelection(){let c=Re(),x=c?.models.find(P=>P.id===L.value);return c===void 0||x===void 0?void 0:Object.freeze({providerProfileId:c.id,modelProfileId:x.id})},renderCapability(c,x,P,C){Ee=c,$e=x,X=C,se=c==="probing",Ce=c==="ready"&&P?.state==="agent-ready",$.dataset.state=c,$.textContent=P?.state==="agent-ready"?`${x} · ${n.agent.toolsReady}`:x,z()},renderWorkspaceHealth(c,x,P){Z=c,ze=x,ke=P??x?.errorCode,W.dataset.state=c,c!=="checking"&&(K.hidden=xe||c!=="consent-required"),(c==="idle"||c==="ready"||c==="blocked")&&(h.checked=!1),Be(),z()},renderJob(c,x,P,C){F=!0,E.hidden=!0,ae.hidden=!1,g.disabled=!0,L.disabled=!0,S.disabled=!0,h.disabled=!0,pe=c,ue=x,Le=P,Ie=C,it()},resetJob(){F=!1,pe=void 0,ue=void 0,Le=[],Ie=void 0,E.hidden=!1,ae.hidden=!0,g.disabled=!1,L.disabled=!1,S.disabled=!1,h.disabled=!1,Y.replaceChildren(),me.replaceChildren(),te.replaceChildren(),M.textContent="",he.textContent="",he.hidden=!0,z()},setContextReady(c){Pe=c,z()},setEditingEnabled(c){Se=c,g.disabled=!c||F,L.disabled=!c||F,S.disabled=!c||F,h.disabled=!c||F,z()},setProviderConsent(c){S.checked=c,z()},setSelectionVisible(c){_=c,z(),c||(ne.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},dispose(){p(),g.removeEventListener("change",Ke),L.removeEventListener("change",Ye),S.removeEventListener("change",z),h.removeEventListener("change",z)}})}var Xn="http://www.w3.org/2000/svg",Fr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Fr,viewBox:"0 0 1 1"}}function Kr(e,t,o){let n=e.createElementNS(Xn,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Zn(e,t){let o=qr(t),n=Kr(e,"svg",{xmlns:Xn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function nt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,l=nt((i-t)/2,16,r),E=nt((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:nt(t/2,22,t-22),anchorY:nt(e/2,22,e-22),left:l,mode:"viewport",top:E});let A=o.x+o.width/2,R=o.y+o.height/2,j=nt(A-t/2,16,r),g=nt(R-e/2,16,a),k=j,V=g,L="viewport";return o.width>=t+48&&o.height>=e+48?L="center":o.y-e-14>=16?(V=o.y-e-14,L="above"):o.y+o.height+14+e<=n-16?(V=o.y+o.height+14,L="below"):o.x+o.width+14+t<=i-16?(k=o.x+o.width+14,L="right"):o.x-t-14>=16&&(k=o.x-t-14,L="left"),Object.freeze({anchorX:nt(A-k,22,t-22),anchorY:nt(R-V,22,e-22),left:k,mode:L,top:V})}var Yr=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"}),Xr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Zr=Object.freeze({[f.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[f.INVALID_TOKEN]:"The local SpotPatch session expired.",[f.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[f.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[f.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[f.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[f.EDITOR_OPEN_FAILED]:"The editor request failed.",[f.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[f.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[f.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[f.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[f.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[f.AGENT_BUSY]:"Another write Agent job is still active.",[f.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[f.AGENT_CANCELLED]:"The Agent job was cancelled.",[f.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[f.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[f.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[f.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[f.TOOL_DENIED]:"A tool request violated local safety policy.",[f.TOOL_INPUT_INVALID]:"Invalid tool request.",[f.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[f.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[f.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[f.PATCH_REJECTED]:"The patch violated local policy.",[f.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[f.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[f.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Qr=Object.freeze({[f.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[f.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[f.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[f.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[f.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[f.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[f.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[f.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[f.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[f.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[f.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[f.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[f.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[f.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[f.AGENT_CANCELLED]:"Agent 任务已取消。",[f.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[f.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[f.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[f.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[f.TOOL_DENIED]:"工具请求违反本地安全策略。",[f.TOOL_INPUT_INVALID]:"工具请求无效。",[f.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[f.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[f.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[f.PATCH_REJECTED]:"补丁违反本地策略。",[f.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[f.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[f.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),ea=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"}),ta=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:"警告"}),na=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:ea,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",trustedFast:"Trusted fast",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.`,trustedFastConsent:e=>`Enable trusted fast mode for ${e}: send allowed project context, include current local changes, and directly apply AI changes after required checks, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Zr}),"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:ta,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信快速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信快速模式:发送获准的项目上下文、纳入当前本地修改,并在必需检查通过后直接应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Xr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Qr})});function eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function oa(e,t){if(e!=="auto")return e;let o=eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(eo).find(i=>i!==void 0)??"en-US"}function to(e,t="auto"){let o=oa(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>na[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 no=460,oo=620,ra=Object.freeze({previewing:560,selected:oo});function aa(e){let t=e.createElement("style");return t.textContent=`
252
+ @media (max-width: 520px) {
253
+ .spotpatch-agent-selectors { grid-template-columns: 1fr; }
254
+ .spotpatch-agent-mode { grid-column: auto; }
255
+ }
256
+ `;function Et(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function Xn(e,t,o){let n=o.messages(),i=c(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=c(e,"div");r.className="spotpatch-agent-head";let a=c(e,"span");a.className="spotpatch-agent-title";let p=c(e,"span");p.className="spotpatch-agent-badge",r.append(a,p);let E=c(e,"div");E.className="spotpatch-agent-setup";let A=c(e,"div");A.className="spotpatch-agent-selectors";let C=c(e,"label");C.className="spotpatch-agent-mode";let U=c(e,"span"),g=c(e,"select");C.append(U,g);let M=c(e,"label"),$=c(e,"span"),L=c(e,"select");M.append($,L);let x=c(e,"label"),T=c(e,"span"),V=c(e,"select");x.append(T,V),A.append(C,M,x);let te=c(e,"label");te.className="spotpatch-consent";let z=c(e,"input");z.type="checkbox";let f=c(e,"span");te.append(z,f);let b=c(e,"label");b.className="spotpatch-consent spotpatch-workspace-consent",b.hidden=!0;let S=c(e,"input");S.type="checkbox";let w=c(e,"span"),F=c(e,"strong"),ue=c(e,"small");w.append(F,ue),b.append(S,w);let Re=c(e,"div");Re.className="spotpatch-agent-health-list";let Y=c(e,"p");Y.className="spotpatch-agent-workspace",Y.dataset.state="idle";let O=c(e,"p");O.className="spotpatch-agent-capability",O.dataset.state="idle",Re.append(Y,O),E.append(A,te,b,Re);let k=c(e,"div");k.className="spotpatch-agent-job",k.hidden=!0;let ke=c(e,"div");ke.className="spotpatch-agent-job-meta";let He=c(e,"span");He.className="spotpatch-agent-model";let ie=c(e,"span");ie.className="spotpatch-agent-status",ke.append(He,ie);let Be=c(e,"p");Be.className="spotpatch-agent-phase";let de=c(e,"p");de.className="spotpatch-agent-error",de.hidden=!0;let me=c(e,"ul");me.className="spotpatch-agent-activity";let oe=c(e,"div");oe.className="spotpatch-agent-result",oe.hidden=!0;let W=c(e,"p");W.className="spotpatch-agent-summary";let be=c(e,"ul");be.className="spotpatch-agent-files";let Ne=c(e,"div");Ne.className="spotpatch-agent-checks";let Q=c(e,"pre");Q.className="spotpatch-agent-diff",Q.tabIndex=0,Q.setAttribute("aria-label",n.agent.diffAriaLabel),oe.append(W,be,Ne,Q),k.append(ke,Be,de,me,oe),i.append(r,E,k);let ge=ee(e,n.agent.testConnection),Me=ee(e,n.agent.run,"spotpatch-run"),ye=ee(e,n.agent.cancel),fe=ee(e,n.agent.apply,"spotpatch-primary"),xe=ee(e,n.agent.revert),R=ee(e,n.agent.revise),De=t.enabled?t.providers:[],Se=t.enabled&&t.applyMode==="trusted-auto",P=t.enabled?t.applyMode:"review",ve=new Map(De.map(l=>[l.id,l])),Ee=!1,we=!0,re=!1,Z=!1,Oe=!1,_e=!1,Pe,We,se=[],Te,Ae="idle",Le=n.agent.connectionNotTested,Ie,ae="idle",Ue,$e;for(let l of De)Et(e,L,l.id,l.label);t.enabled&&(L.value=t.defaultProvider);let le,ze,Je;P==="auto"?Je=Et(e,g,"auto",n.agent.autoGated):(le=Et(e,g,"review",n.agent.review),Se&&(ze=Et(e,g,"trusted-auto",n.agent.trustedFast)));let Ye=Se?"review":P;g.value=Ye,C.hidden=!Se;let st=()=>g.value==="trusted-auto"?"trusted-auto":Ye,s=()=>st()==="trusted-auto",d=()=>ve.get(L.value),y=l=>l===void 0?n.agent.providerUnavailable:s()?n.agent.trustedFastConsent(l.label):n.agent.consent(l.label),I=()=>s()?z.checked:S.checked,j=()=>{let l=s();te.classList.toggle("spotpatch-trusted-consent",l),p.textContent=l?n.agent.trustedFast:P==="auto"?n.agent.autoGated:n.agent.review,f.textContent=y(d()),b.hidden=l||ae!=="consent-required"},N=()=>{let l=d();if(V.replaceChildren(),l===void 0){f.textContent=y(l);return}for(let _ of l.models)Et(e,V,_.id,_.label);V.value=l.defaultModel,f.textContent=y(l)},q=()=>{let l=t.enabled&&re&&!Z;Me.textContent=Oe?n.agent.verifying:n.agent.run,Me.classList.toggle("spotpatch-primary",_e),ge.hidden=!l,Me.hidden=!l,ge.disabled=!we||Oe||d()===void 0,Me.disabled=!we||Oe||!Ee||!z.checked||ae==="idle"||ae==="checking"||ae==="blocked"||ae==="consent-required"&&!I()||d()===void 0||V.value.length===0,(!Z||!re)&&(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},lt=()=>{if(ae==="idle")Y.textContent=n.agent.workspaceNotChecked;else if(ae==="checking")Y.textContent=n.agent.checkingWorkspace;else if(ae==="ready")Y.textContent=n.agent.workspaceReady;else if(ae==="consent-required"){let l=Ue?.changes;Y.textContent=n.agent.workspaceDirty(l?.staged??0,l?.unstaged??0,l?.untracked??0)}else Y.textContent=$e===void 0?n.errors.INTERNAL_ERROR:n.errors[$e]};function pt(){N(),z.checked=!1,O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function ut(){O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function At(){z.checked=!1,S.checked=!1,j(),q()}N(),g.addEventListener("change",At),L.addEventListener("change",pt),V.addEventListener("change",ut),z.addEventListener("change",q),S.addEventListener("change",q);function u(){if(Pe===void 0)return;let l=Pe,_=We;He.textContent=`${l.providerLabel} · ${l.modelLabel}`,ie.textContent=n.agent.status(l.status),Be.textContent=l.phaseMessage;let K=Te??l.errorCode;de.hidden=K===void 0,de.textContent=K===void 0?"":n.errors[K],me.replaceChildren();for(let H of se.slice(-8)){let G=c(e,"li");G.dataset.state=H.state,G.textContent=H.label,me.append(G)}oe.hidden=_===void 0,W.textContent=_?.summary??"",be.replaceChildren(),Ne.replaceChildren(),Q.textContent=_?.diff??"";for(let H of _?.files??[]){let G=c(e,"li");G.textContent=`${H.kind} ${H.relativePath} (+${String(H.additions)} / -${String(H.deletions)})`,be.append(G)}for(let H of _?.checks??[]){let G=c(e,"details"),Xe=c(e,"summary");Xe.textContent=`${H.label}: ${H.status} · ${String(H.durationMs)} ms`;let B=c(e,"pre");B.textContent=H.output.length===0?n.agent.noOutput:H.output,G.append(Xe,B),Ne.append(G)}ge.hidden=!0,Me.hidden=!0,ye.hidden=!re||!l.canCancel,ye.textContent=l.status==="awaiting-review"?n.agent.discard:n.agent.cancel,fe.hidden=!re||!l.canApply,xe.hidden=!re||!l.canRevert,R.hidden=!re||!["completed","cancelled","reverted","failed"].includes(l.status)}function m(){n=o.messages(),a.textContent=n.agent.title,U.textContent=n.agent.mode,le!==void 0&&(le.textContent=n.agent.review),ze!==void 0&&(ze.textContent=n.agent.trustedFast),Je!==void 0&&(Je.textContent=n.agent.autoGated),$.textContent=n.agent.provider,T.textContent=n.agent.model,L.setAttribute("aria-label",n.agent.providerAriaLabel),V.setAttribute("aria-label",n.agent.modelAriaLabel),F.textContent=n.agent.includeLocalChanges,ue.textContent=n.agent.includeLocalChangesHelp,Q.setAttribute("aria-label",n.agent.diffAriaLabel),ge.textContent=n.agent.testConnection,fe.textContent=n.agent.apply,xe.textContent=n.agent.revert,R.textContent=n.agent.revise,j(),Ae==="idle"?O.textContent=n.agent.connectionNotTested:Ae==="probing"?O.textContent=n.agent.testingCapability:Ae==="ready"?O.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ie!==void 0?O.textContent=n.errors[Ie]:d()===void 0?O.textContent=n.agent.providerUnavailable:O.textContent=Le,lt(),q(),u()}let v=o.subscribe(m);return m(),Object.freeze({root:i,modeSelect:g,providerSelect:L,modelSelect:V,consentCheckbox:z,workspaceConsentCheckbox:S,testButton:ge,runButton:Me,cancelButton:ye,applyButton:fe,revertButton:xe,resetButton:R,consentGranted(){return z.checked},workspaceConsentGranted(){return I()},readSelection(){let l=d(),_=l?.models.find(K=>K.id===V.value);return l===void 0||_===void 0?void 0:Object.freeze({applyMode:st(),providerProfileId:l.id,modelProfileId:_.id})},renderCapability(l,_,K,H){Ae=l,Le=_,Ie=H,Oe=l==="probing",_e=l==="ready"&&K?.state==="agent-ready",O.dataset.state=l,O.textContent=K?.state==="agent-ready"?`${_} · ${n.agent.toolsReady}`:_,q()},renderWorkspaceHealth(l,_,K){ae=l,Ue=_,$e=K??_?.errorCode,Y.dataset.state=l,l!=="checking"&&(b.hidden=s()||l!=="consent-required"),(l==="idle"||l==="ready"||l==="blocked")&&(S.checked=!1),lt(),q()},renderJob(l,_,K,H){Z=!0,E.hidden=!0,k.hidden=!1,L.disabled=!0,V.disabled=!0,g.disabled=!0,z.disabled=!0,S.disabled=!0,Pe=l,We=_,se=K,Te=H,u()},resetJob(){Z=!1,Pe=void 0,We=void 0,se=[],Te=void 0,E.hidden=!1,k.hidden=!0,L.disabled=!1,V.disabled=!1,g.disabled=!1,z.disabled=!1,S.disabled=!1,me.replaceChildren(),be.replaceChildren(),Ne.replaceChildren(),Q.textContent="",de.textContent="",de.hidden=!0,q()},setContextReady(l){Ee=l,q()},setEditingEnabled(l){we=l,L.disabled=!l||Z,V.disabled=!l||Z,g.disabled=!l||Z,z.disabled=!l||Z,S.disabled=!l||Z,q()},setProviderConsent(l){z.checked=l,q()},setSelectionVisible(l){re=l,q(),l||(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},dispose(){v(),L.removeEventListener("change",pt),V.removeEventListener("change",ut),g.removeEventListener("change",At),z.removeEventListener("change",q),S.removeEventListener("change",q)}})}var Zn="http://www.w3.org/2000/svg",Fr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Fr,viewBox:"0 0 1 1"}}function Kr(e,t,o){let n=e.createElementNS(Zn,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Qn(e,t){let o=qr(t),n=Kr(e,"svg",{xmlns:Zn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function ot(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function eo({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,p=ot((i-t)/2,16,r),E=ot((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:ot(t/2,22,t-22),anchorY:ot(e/2,22,e-22),left:p,mode:"viewport",top:E});let A=o.x+o.width/2,C=o.y+o.height/2,U=ot(A-t/2,16,r),g=ot(C-e/2,16,a),M=U,$=g,L="viewport";return o.width>=t+48&&o.height>=e+48?L="center":o.y-e-14>=16?($=o.y-e-14,L="above"):o.y+o.height+14+e<=n-16?($=o.y+o.height+14,L="below"):o.x+o.width+14+t<=i-16?(M=o.x+o.width+14,L="right"):o.x-t-14>=16&&(M=o.x-t-14,L="left"),Object.freeze({anchorX:ot(A-M,22,t-22),anchorY:ot(C-$,22,e-22),left:M,mode:L,top:$})}var Yr=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"}),Xr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Zr=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 start or continue the required tool call.",[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 tool request violated local safety policy.",[h.TOOL_INPUT_INVALID]:"Invalid tool request.",[h.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[h.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[h.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[h.PATCH_REJECTED]:"The patch violated local policy.",[h.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[h.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[h.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Qr=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]:"工具请求无效。",[h.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[h.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[h.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[h.PATCH_REJECTED]:"补丁违反本地策略。",[h.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[h.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[h.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),ea=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"}),ta=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:"警告"}),na=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:ea,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",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted fast",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.`,trustedFastConsent:e=>`Enable trusted fast mode for ${e}: send allowed project context, include current local changes, and directly apply AI changes after required checks, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Zr}),"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:ta,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",mode:"执行方式",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信快速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信快速模式:发送获准的项目上下文、纳入当前本地修改,并在必需检查通过后直接应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Xr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Qr})});function to(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 oa(e,t){if(e!=="auto")return e;let o=to(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(to).find(i=>i!==void 0)??"en-US"}function no(e,t="auto"){let o=oa(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>na[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 oo=460,ro=620,ra=Object.freeze({previewing:560,selected:ro});function aa(e){let t=e.createElement("style");return t.textContent=`
250
257
  :host {
251
258
  all: initial;
252
259
  --spotpatch-bg: #0e0e12;
@@ -283,7 +290,7 @@ ${wt(e.code.language,G(t.codeLines.join(`
283
290
  position: fixed;
284
291
  right: 24px;
285
292
  bottom: 24px;
286
- z-index: ${String(xt.controls)};
293
+ z-index: ${String(St.controls)};
287
294
  display: inline-flex;
288
295
  align-items: center;
289
296
  gap: 10px;
@@ -317,7 +324,7 @@ ${wt(e.code.language,G(t.codeLines.join(`
317
324
  position: fixed;
318
325
  top: 0;
319
326
  left: 0;
320
- z-index: ${String(xt.highlight)};
327
+ z-index: ${String(St.highlight)};
321
328
  box-sizing: border-box;
322
329
  border: 2px solid var(--spotpatch-accent);
323
330
  border-radius: 6px;
@@ -344,7 +351,7 @@ ${wt(e.code.language,G(t.codeLines.join(`
344
351
  .spotpatch-selection-highlights {
345
352
  position: fixed;
346
353
  inset: 0;
347
- z-index: ${String(xt.highlight)};
354
+ z-index: ${String(St.highlight)};
348
355
  pointer-events: none;
349
356
  }
350
357
  .spotpatch-selection-highlight {
@@ -385,9 +392,9 @@ ${wt(e.code.language,G(t.codeLines.join(`
385
392
  position: fixed;
386
393
  top: 16px;
387
394
  left: 16px;
388
- z-index: ${String(xt.controls)};
395
+ z-index: ${String(St.controls)};
389
396
  box-sizing: border-box;
390
- width: min(${String(no)}px, calc(100vw - 32px));
397
+ width: min(${String(oo)}px, calc(100vw - 32px));
391
398
  color: #edf0f7;
392
399
  outline: none;
393
400
  filter: drop-shadow(var(--spotpatch-shadow-panel));
@@ -432,7 +439,7 @@ ${wt(e.code.language,G(t.codeLines.join(`
432
439
  z-index: 1;
433
440
  display: flex;
434
441
  box-sizing: border-box;
435
- max-height: min(${String(oo)}px, calc(100vh - 32px));
442
+ max-height: min(${String(ro)}px, calc(100vh - 32px));
436
443
  overflow: hidden;
437
444
  flex-direction: column;
438
445
  border: 1px solid var(--spotpatch-border);
@@ -946,10 +953,10 @@ ${wt(e.code.language,G(t.codeLines.join(`
946
953
  .spotpatch-target-state { display: none; }
947
954
  .spotpatch-repository { display: none; }
948
955
  }
949
- ${Kn}
956
+ ${Yn}
950
957
  `,t}function ia(e,t){return e.split(`
951
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ro(e,t,o=Object.freeze({enabled:!1}),n="auto"){let i=to(e,n),r=i.messages(),a=e.createElement("spotpatch-root");a.setAttribute(at,"");let l=a.attachShadow({mode:"open"}),E=q(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=d(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let R=d(e,"span");R.className="spotpatch-highlight-label",A.append(R);let j=d(e,"div");j.className="spotpatch-selection-highlights",j.setAttribute("aria-hidden","true");let g=d(e,"section");g.className="spotpatch-dialog",g.hidden=!0,g.tabIndex=-1,g.dataset.placement="viewport",g.setAttribute("role","dialog"),g.setAttribute("aria-labelledby","spotpatch-selection-title");let k=d(e,"span");k.className="spotpatch-anchor",k.setAttribute("aria-hidden","true");let V=d(e,"div");V.className="spotpatch-shell";let L=d(e,"header");L.className="spotpatch-header";let m=d(e,"div");m.className="spotpatch-brand-row";let S=d(e,"div");S.className="spotpatch-brand";let ee=d(e,"span");ee.className="spotpatch-brand-copy";let K=d(e,"span");K.className="spotpatch-brand-name";let h=d(e,"span");h.className="spotpatch-brand-context",ee.append(K,h),S.append(Zn(e),ee);let y=d(e,"span");y.className="spotpatch-header-controls";let T=d(e,"a");T.className="spotpatch-repository",T.href=Gt,T.target="_blank",T.rel="noopener noreferrer";let O=q(e,"","spotpatch-locale"),I=q(e,"×","spotpatch-close");y.append(T,O,I),m.append(S,y);let W=d(e,"h2");W.id="spotpatch-selection-title",W.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let ae=d(e,"div");ae.className="spotpatch-target-row";let ie=d(e,"span");ie.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,ae.append(ie,B),L.append(m,W,$,ae);let N=d(e,"div");N.className="spotpatch-body";let _e=d(e,"div");_e.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let Y=d(e,"div");Y.className="spotpatch-targets-heading";let ve=d(e,"span"),Te=d(e,"span");Te.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let te=d(e,"span");te.className="spotpatch-target-budget",te.setAttribute("aria-live","polite");let M=d(e,"span");M.className="spotpatch-target-count",Te.append(me,te),ae.append(M),Y.append(ve,Te);let be=d(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let we=d(e,"div");we.className="spotpatch-target-progress-fill",be.append(we);let ne=d(e,"div");ne.className="spotpatch-target-list",he.append(Y,be,ne);let le=d(e,"details");le.className="spotpatch-diagnostics";let De=d(e,"summary"),ye=d(e,"span"),Oe=d(e,"span");Oe.className="spotpatch-source-peek",Oe.textContent=r.diagnostics.resolving,De.append(ye,Oe);let xe=d(e,"pre");xe.className="spotpatch-summary",le.append(De,xe);let w=Yn(e,o,i);_e.append(he,le,w.root);let Pe=d(e,"div");Pe.className="spotpatch-preview-panel",Pe.hidden=!0;let Se=d(e,"pre");Se.className="spotpatch-prompt",Se.tabIndex=0,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Pe.append(Se),N.append(_e,Pe);let _=d(e,"footer");_.className="spotpatch-actions";let F=d(e,"div");F.className="spotpatch-context-state spotpatch-editor-feedback",F.dataset.state="idle",F.setAttribute("role","status"),F.setAttribute("aria-live","polite"),F.hidden=!0;let se=q(e,r.actions.addElement),Ce=q(e,r.actions.reselect),pe=q(e,r.actions.openEditor),ue=q(e,r.actions.preview,"spotpatch-primary"),Le=q(e,r.actions.copy,"spotpatch-primary"),Ie=q(e,r.actions.back),Ee=d(e,"div");Ee.className="spotpatch-secondary-actions";let $e=d(e,"div");$e.className="spotpatch-primary-actions",se.classList.add("spotpatch-icon-action"),se.dataset.compactIcon="+",w.testButton.classList.add("spotpatch-icon-action"),w.testButton.dataset.compactIcon="✓",pe.classList.add("spotpatch-secondary-action"),Ce.classList.add("spotpatch-secondary-action"),Ee.append(pe,Ce),$e.append(w.testButton,se,w.runButton,ue,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Le,Ie),_.append(F,Ee,$e),V.append(L,N,_),g.append(k,V);let X=d(e,"div");X.className="spotpatch-live",X.setAttribute("aria-live","polite"),X.setAttribute("aria-atomic","true"),l.append(aa(e),j,A,g,E,X),e.documentElement.append(a);let Z,ze,ke="idle",Re=!1,Ne=!1,je="",He=!0,z=[],Be=0,Ke="idle";function Ye(u){Ke=u,F.dataset.state=u,F.hidden=u==="idle",F.textContent=u==="opening"?r.announcements.editorOpening:u==="success"?r.announcements.editorOpened:u==="error"?r.announcements.editorFailed:"",C()}function it(u){return u.status==="ready"?r.targets.statusReady:u.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function s(u,b){let v=b===0?0:u/b;we.style.width=`${String(v*100)}%`}function p(u){let b=ne.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(b).find(v=>u===void 0||v.dataset.targetInstructionId===u)}function c(u,b){let v=l.activeElement?.closest("textarea[data-target-instruction-id]"),H=v?.dataset.targetInstructionId,ge=v?.selectionStart,Ue=v?.selectionEnd;z=u.map(U=>Object.freeze({...U})),Be=b,ne.replaceChildren();let We=u.filter(U=>U.instruction.trim().length>0).length,ce=u.reduce((U,J)=>U+J.instruction.trim().length,0);s(We,u.length),M.textContent=r.targets.count(u.length,b),me.textContent=r.targets.complete(We,u.length);let pt=ce>4e3;te.dataset.state=pt?"over":"ready",te.textContent=pt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3),se.disabled=!He||u.length>=b,se.title=u.length>=b?r.targets.limitTitle(b):r.targets.addTitle,ie.textContent=u.length===1?u[0]?.label??r.context.selectedElement:r.context.selectedCount(u.length);for(let[U,J]of u.entries()){let ot=d(e,"div");ot.className="spotpatch-target-item",ot.dataset.active=String(J.active),ot.dataset.status=J.status,ot.dataset.targetId=J.id;let Ot=d(e,"div");Ot.className="spotpatch-target-summary";let ut=q(e,"","spotpatch-target-select");ut.dataset.activateTargetId=J.id,ut.setAttribute("aria-label",r.targets.activate(U+1)),ut.setAttribute("aria-expanded",String(J.active));let _t=d(e,"span");_t.className="spotpatch-target-index",_t.textContent=String(U+1);let Pt=d(e,"span");Pt.className="spotpatch-target-copy";let Lt=d(e,"span");Lt.className="spotpatch-target-name",Lt.textContent=J.label;let It=d(e,"span");It.className="spotpatch-target-source",It.textContent=`${it(J)} · ${J.source}`,Pt.append(Lt,It);let en=J.instruction.trim().length>0,St=d(e,"span");St.className="spotpatch-target-state",St.dataset.complete=String(en),St.textContent=en?r.targets.instructionReady:r.targets.instructionMissing,ut.append(_t,Pt,St);let gt=q(e,"↗","spotpatch-target-open");gt.dataset.openTargetId=J.id,gt.disabled=!J.canOpenEditor,gt.setAttribute("aria-label",r.actions.openTarget(U+1)),gt.title=r.actions.openTarget(U+1);let ft=q(e,"×","spotpatch-target-remove");if(ft.dataset.removeTargetId=J.id,ft.disabled=!He,ft.setAttribute("aria-label",r.targets.remove(U+1)),ft.title=r.targets.removeTitle,Ot.append(ut,gt,ft),ot.append(Ot),J.active){let kt=d(e,"label");kt.className="spotpatch-target-editor";let Nt=d(e,"span");Nt.className="spotpatch-target-editor-head";let Mt=d(e,"span");Mt.className="spotpatch-target-editor-label",Mt.textContent=r.targets.instructionLabel(J.label);let Dt=d(e,"span");Dt.className="spotpatch-target-editor-count",Dt.textContent=r.targets.instructionCount(J.instruction.length,2e3),Nt.append(Mt,Dt);let Xe=d(e,"textarea");Xe.rows=4,Xe.maxLength=2e3,Xe.value=J.instruction,Xe.placeholder=r.targets.instructionPlaceholder,Xe.disabled=!He,Xe.dataset.targetInstructionId=J.id,Xe.setAttribute("aria-label",r.targets.instructionLabel(J.label)),kt.append(Nt,Xe),ot.append(kt)}ne.append(ot)}if(H!==void 0){let U=p(H);U?.focus({preventScroll:!0}),ge!==void 0&&Ue!==void 0&&U?.setSelectionRange(ge,Ue)}}function x(u,b){z=z.map(U=>U.id===u?Object.freeze({...U,instruction:b}):U);let v=Array.from(ne.querySelectorAll(".spotpatch-target-item")).find(U=>U.dataset.targetId===u);if(v===void 0)return;let H=b.trim().length>0,ge=v.querySelector(".spotpatch-target-state"),Ue=v.querySelector(".spotpatch-target-editor-count");ge!==null&&(ge.dataset.complete=String(H),ge.textContent=H?r.targets.instructionReady:r.targets.instructionMissing),Ue!==null&&(Ue.textContent=r.targets.instructionCount(b.length,2e3));let We=z.filter(U=>U.instruction.trim().length>0).length;me.textContent=r.targets.complete(We,z.length),s(We,z.length);let ce=z.reduce((U,J)=>U+J.instruction.trim().length,0),pt=ce>4e3;te.dataset.state=pt?"over":"ready",te.textContent=pt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3)}function P(u){j.replaceChildren(),ze=u.find(b=>b.active)?.rect,Z=ze;for(let[b,v]of u.entries()){let H=d(e,"div");H.className="spotpatch-selection-highlight",H.dataset.targetId=v.id,H.dataset.active=String(v.active),H.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,H.style.width=`${String(v.rect.width)}px`,H.style.height=`${String(v.rect.height)}px`;let ge=d(e,"span");ge.textContent=`${String(b+1)} · ${v.label}`,H.append(ge),j.append(H)}C()}function C(){if(g.hidden)return;let u=e.defaultView,b=u?.innerWidth??e.documentElement.clientWidth,v=u?.innerHeight??e.documentElement.clientHeight,H=g.getBoundingClientRect(),ge=ke==="previewing"?"previewing":"selected",Ue=H.width>0?H.width:Math.min(no,b-32),We=H.height>0?H.height:Math.min(ra[ge],v-32),ce=Qn({dialogWidth:Ue,dialogHeight:We,viewportWidth:b,viewportHeight:v,...Z===void 0?{}:{target:Z}});g.style.left=`${String(ce.left)}px`,g.style.top=`${String(ce.top)}px`,g.style.setProperty("--spotpatch-anchor-x",`${String(ce.anchorX)}px`),g.style.setProperty("--spotpatch-anchor-y",`${String(ce.anchorY)}px`),g.dataset.placement=ce.mode}function oe(u){let b=r.summary,v=ia(u,b.source);Oe.textContent=v??r.diagnostics.noExactSource;let H=`${b.browserContext}: ${b.collectionStatuses.ready}`,ge=`${b.browserContext}: ${b.collectionStatuses.loading}`,Ue=`${b.browserContext}: ${b.collectionStatuses.failed}`,We=`${b.api}: ${b.apiStatuses.loading}`,ce=`${b.api}: ${b.apiStatuses.failed}`;u.includes(H)&&!u.includes(ge)&&!u.includes(We)&&!u.includes(Ue)&&!u.includes(ce)?(B.dataset.state="ready",B.textContent=r.context.ready):u.includes(Ue)||u.includes(ce)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function dt(u,b,v){Re=b,Ne=v,je=u,xe.textContent=u,pe.disabled=!b,ue.disabled=!v,w.setContextReady(v),oe(u),C()}function lt(u){ke=u;let b=u==="selected",v=u==="previewing";E.hidden=b||v,_e.hidden=!b,Pe.hidden=!v,Ce.hidden=!b,se.hidden=!b,pe.hidden=!b,ue.hidden=!b,Ee.hidden=!b,w.setSelectionVisible(b),Le.hidden=!v,Ie.hidden=!v,W.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,C()}function Qt(){r=i.messages(),K.textContent=r.brand.name,h.textContent=r.brand.context,T.textContent=r.brand.repository,T.title=r.brand.repositoryTitle,T.setAttribute("aria-label",r.brand.repositoryTitle),O.textContent=r.alternateLocaleName,O.title=r.switchLocale,O.setAttribute("aria-label",r.switchLocale),I.setAttribute("aria-label",r.dialog.close),I.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),ve.textContent=r.targets.title,ye.textContent=r.diagnostics.title,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),se.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,pe.textContent=r.actions.openEditor,ue.textContent=r.actions.preview,Le.textContent=r.actions.copy,Ie.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=ke==="inspecting"?r.trigger.stop:r.trigger.select,lt(ke),Ye(Ke),z.length>0?c(z,Be):(M.textContent=r.targets.count(0,Be),me.textContent=r.targets.complete(0,0),s(0,0),te.dataset.state="ready",te.textContent=r.targets.instructionBudget(0,4e3),ie.textContent=r.context.selectedElement),je.length>0?oe(je):(Oe.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}le.addEventListener("toggle",C),O.addEventListener("click",i.toggle);let go=i.subscribe(Qt);return Qt(),Object.freeze({host:a,triggerButton:E,addTargetButton:se,targetList:ne,reselectButton:Ce,openEditorButton:pe,repositoryLink:T,previewButton:ue,copyButton:Le,backButton:Ie,closeButton:I,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentWorkspaceConsentCheckbox:w.workspaceConsentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(u){let b=u==="inspecting";E.setAttribute("aria-pressed",String(b)),E.textContent=b?r.trigger.stop:r.trigger.select,lt(u)},renderEditorStatus:Ye,showHighlight(u,b){Z=u,A.hidden=!1,A.style.transform=`translate(${String(u.x)}px, ${String(u.y)}px)`,A.style.width=`${String(u.width)}px`,A.style.height=`${String(u.height)}px`,R.textContent=b,ie.textContent=b,C()},hideHighlight(){Z=ze,A.hidden=!0,R.textContent="",C()},showSelectionHighlights:P,hideSelectionHighlights(){j.replaceChildren(),ze=void 0,Z=void 0,C()},showSelection(u,b,v){dt(u,b,v),E.hidden=!0,g.hidden=!1,C()},updateSelection:dt,renderTargets:c,updateTargetInstruction:x,setPreviewEnabled(u){Ne=u,ue.disabled=!u,w.setContextReady(u)},hideSelection(){g.hidden=!0,E.hidden=!1,ne.replaceChildren(),z=[],Be=0,je="",Ye("idle"),M.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),s(0,0),ie.textContent=r.context.selectedElement,xe.textContent="",Se.textContent="",Oe.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,pe.disabled=!0,ue.disabled=!0,Re=!1,Ne=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){g.hidden=!0,E.hidden=!1},showPreview(u){Se.textContent=u,C()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(u){w.setProviderConsent(u)},setAgentEditingEnabled(u){He=u,se.disabled=!u,Ce.disabled=!u,ne.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(b=>{b.disabled=!u}),pe.disabled=!Re,ue.disabled=!u||!Ne,w.setEditingEnabled(u),C()},renderAgentCapability(u,b,v,H){w.renderCapability(u,b,v,H);let ge=u==="ready"&&v?.state==="agent-ready";ue.classList.toggle("spotpatch-primary",!ge),C()},renderAgentWorkspaceHealth(u,b,v){w.renderWorkspaceHealth(u,b,v),C()},renderAgentJob(u,b,v,H){w.renderJob(u,b,v,H),C()},resetAgentJob(){w.resetJob(),C()},focusTargetInstruction(u){p(u)?.focus({preventScroll:!0})},focusPrompt(){Se.focus({preventScroll:!0})},announce(u){X.textContent="",X.textContent=u},locale:i.locale,messages:i.messages,agentWorkspaceConsentGranted:w.workspaceConsentGranted,subscribeLocale:i.subscribe,dispose(){le.removeEventListener("toggle",C),O.removeEventListener("click",i.toggle),go(),w.dispose(),a.remove()}})}function sa(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 ao(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${sa(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(`
952
- `)}function io(e,t){return`${e}:${t}`}function ca(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function so(e){let t=h=>mn(h)??f.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,i=new Set,r=new Map,a=0,l,E,A=!1,R=!1,j=()=>e.view.readAgentSelection(),g=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let y=await e.api.agentWorkspaceHealth();return h!==a||e.view.renderAgentWorkspaceHealth(y.state,y,y.errorCode),y}catch(y){throw h===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(y)),y}},k=h=>{l!==void 0&&e.view.renderAgentJob(l,E,Object.freeze([...r.values()]),h??l.errorCode)},V=()=>{let h=j();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(h.providerProfileId));let y=n.get(io(h.providerProfileId,h.modelProfileId));y===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,y)},L=async h=>{let y=j();if(y===void 0)throw new Error("Agent provider selection is unavailable.");let T=io(y.providerProfileId,y.modelProfileId),O=n.get(T);if(O!==void 0)return O;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let I=await e.api.agentCapability(y);if(h!==a)return I;if(I.state!=="agent-ready")throw new D(I.errorCode??f.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(T,I),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,I),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),I},m=async(h,y)=>{try{let T=await e.api.agentResult(h);if(y!==a||T.snapshot.jobId!==h)return;l=T.snapshot,E=T.result,k()}catch(T){y===a&&k(t(T))}},S=async(h,y)=>{try{await e.api.agentEvents(h,T=>{if(y!==a||T.jobId!==h)return;T.type==="snapshot"&&(l=T.data.snapshot,l.status==="applied"&&!A&&(A=!0,e.onApplied()));let O=ca(T);O!==void 0&&r.set(O.key,O),k()}),y===a&&await m(h,y)}catch(T){y===a&&!(T instanceof DOMException&&T.name==="AbortError")&&k(t(T))}},ee=async h=>{let y=l;if(y===void 0||R)return;R=!0;let T=a;l=Object.freeze({...y,status:h==="apply"?"applying":h==="cancel"?"cancelling":"reverting",phaseMessage:h==="apply"?e.view.messages().agent.applying:h==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),k();try{let O=h==="apply"?await e.api.applyAgentJob(y.jobId):h==="cancel"?await e.api.cancelAgentJob(y.jobId):await e.api.revertAgentJob(y.jobId);if(T!==a)return;l=O,O.status==="applied"&&!A&&(A=!0,e.onApplied()),await m(O.jobId,T)}catch(O){if(T!==a)return;l=y,await m(y.jobId,T),k(t(O)),e.view.announce(o(O))}finally{T===a&&(R=!1)}},K=()=>{a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),V()};return Object.freeze({apply(){l?.canApply===!0&&ee("apply")},beginSelection(){K();let h=a;e.ai.enabled&&g(h).catch(()=>{})},cancel(){l?.canCancel===!0&&ee("cancel")},consentChanged(){let h=j();h!==void 0&&(e.view.agentConsentGranted()?i.add(h.providerProfileId):i.delete(h.providerProfileId))},disposeSelection(){let h=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){a+=1,V(),g(a).catch(()=>{})},reset(){let h=A;K(),h?e.onReselectRequired():e.ai.enabled&&g(a).catch(()=>{})},revert(){l?.canRevert===!0&&ee("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let h=e.ai.applyMode==="trusted-auto",y=j(),T=e.getAnnotation();if(y===void 0||T===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(y.providerProfileId);let O=++a;e.view.setAgentEditingEnabled(!1),g(O).then(async I=>{if(O!==a)return;if(I.state==="blocked")throw new D(I.errorCode??f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(I.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new D(f.WORKTREE_DIRTY);let W=await e.api.createAgentJob({annotation:T,providerProfileId:y.providerProfileId,modelProfileId:y.modelProfileId,providerDataConsent:!0,...h?{trustedFastModeConsent:!0}:{},workingTreeMode:I.state==="consent-required"?"include-local-changes":"require-clean"});O===a&&(l=W,E=void 0,r.clear(),k(),S(W.jobId,O))}).catch(I=>{O===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(I),void 0,t(I)),e.view.announce(o(I)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let h=++a;Promise.all([L(h),g(h)]).catch(y=>{h===a&&(e.view.renderAgentCapability("error",o(y),void 0,t(y)),e.view.announce(o(y)))})}})}function co(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function Yt(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function lo(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var la=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Xt(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 pa(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 ua(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ga(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function po(e,t={}){let o=ga(t),n=t.view??ro(o.document,e.shortcut,e.ai,e.locale),i=t.api??bn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??jn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??lo(o.window.navigator),l=t.createId??(()=>co(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??Gn(o.window,e.sessionId,e.maxTargets),R=A.load(),j=Fn({adapter:t.reactAdapter??da({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.")}}),g=Ft,k=!1,V,L,m=R?.targets.map(s=>{let p=Kt(s.source);return{id:s.id,resolution:Object.freeze({source:s.source,react:s.react}),apiStatus:p===void 0?"not-required":s.code===void 0?"failed":"connected",code:s.code,collectionStatus:"ready",element:void 0,elementContext:s.element,instruction:s.instruction,marker:p,page:s.page,styles:s.styles}})??[],S=R?.activeTargetId,ee=R?.sequence??0,K=R?.open??!1,h=!1,y=0,T=0,O=!1,I="",W,$,ae,ie,B=new Map;function N(s){g=Hn(g,s),n.renderStatus(g.status)}function _e(){return m.find(s=>s.id===S)??m.at(-1)}function he(s){if(!(s.elementContext===void 0||s.styles===void 0))return{id:s.id,instruction:s.instruction,page:s.page,source:s.resolution.source,react:s.resolution.react,element:s.elementContext,styles:s.styles,...s.code===void 0?{}:{code:s.code}}}function Y(){let s=m.flatMap(c=>{let x=he(c);return x===void 0?[]:[x]});if(s.length===0){A.clear();return}let p=new Set(s.map(({id:c})=>c));A.save({...S!==void 0&&p.has(S)?{activeTargetId:S}:{},open:K,sequence:ee,targets:s})}function ve(s,p){return k&&p===y&&g.status!=="idle"&&m.includes(s)}function Te(){let s=m.reduce((p,c)=>p+c.instruction.trim().length,0);return m.length>0&&s<=4e3&&m.every(p=>p.instruction.trim().length>0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function me(){let s=n.messages().summary;return m.map((p,c)=>{let x=ao({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},s);return`${s.target(c+1,p.id===S)}
953
- ${x}`}).join(`
958
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ao(e,t,o=Object.freeze({enabled:!1}),n="auto"){let i=no(e,n),r=i.messages(),a=e.createElement("spotpatch-root");a.setAttribute(it,"");let p=a.attachShadow({mode:"open"}),E=ee(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=c(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let C=c(e,"span");C.className="spotpatch-highlight-label",A.append(C);let U=c(e,"div");U.className="spotpatch-selection-highlights",U.setAttribute("aria-hidden","true");let g=c(e,"section");g.className="spotpatch-dialog",g.hidden=!0,g.tabIndex=-1,g.dataset.placement="viewport",g.setAttribute("role","dialog"),g.setAttribute("aria-labelledby","spotpatch-selection-title");let M=c(e,"span");M.className="spotpatch-anchor",M.setAttribute("aria-hidden","true");let $=c(e,"div");$.className="spotpatch-shell";let L=c(e,"header");L.className="spotpatch-header";let x=c(e,"div");x.className="spotpatch-brand-row";let T=c(e,"div");T.className="spotpatch-brand";let V=c(e,"span");V.className="spotpatch-brand-copy";let te=c(e,"span");te.className="spotpatch-brand-name";let z=c(e,"span");z.className="spotpatch-brand-context",V.append(te,z),T.append(Qn(e),V);let f=c(e,"span");f.className="spotpatch-header-controls";let b=c(e,"a");b.className="spotpatch-repository",b.href=Jt,b.target="_blank",b.rel="noopener noreferrer";let S=ee(e,"","spotpatch-locale"),w=ee(e,"×","spotpatch-close");f.append(b,S,w),x.append(T,f);let F=c(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let ue=c(e,"p");ue.className="spotpatch-subtitle";let Re=c(e,"div");Re.className="spotpatch-target-row";let Y=c(e,"span");Y.className="spotpatch-target-label";let O=c(e,"span");O.className="spotpatch-context-state",O.dataset.state="loading",O.textContent=r.context.collecting,Re.append(Y,O),L.append(x,F,ue,Re);let k=c(e,"div");k.className="spotpatch-body";let ke=c(e,"div");ke.className="spotpatch-selection-panel";let He=c(e,"section");He.className="spotpatch-targets";let ie=c(e,"div");ie.className="spotpatch-targets-heading";let Be=c(e,"span"),de=c(e,"span");de.className="spotpatch-targets-meta";let me=c(e,"span");me.className="spotpatch-target-complete";let oe=c(e,"span");oe.className="spotpatch-target-budget",oe.setAttribute("aria-live","polite");let W=c(e,"span");W.className="spotpatch-target-count",de.append(me,oe),Re.append(W),ie.append(Be,de);let be=c(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let Ne=c(e,"div");Ne.className="spotpatch-target-progress-fill",be.append(Ne);let Q=c(e,"div");Q.className="spotpatch-target-list",He.append(ie,be,Q);let ge=c(e,"details");ge.className="spotpatch-diagnostics";let Me=c(e,"summary"),ye=c(e,"span"),fe=c(e,"span");fe.className="spotpatch-source-peek",fe.textContent=r.diagnostics.resolving,Me.append(ye,fe);let xe=c(e,"pre");xe.className="spotpatch-summary",ge.append(Me,xe);let R=Xn(e,o,i);ke.append(He,ge,R.root);let De=c(e,"div");De.className="spotpatch-preview-panel",De.hidden=!0;let Se=c(e,"pre");Se.className="spotpatch-prompt",Se.tabIndex=0,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),De.append(Se),k.append(ke,De);let P=c(e,"footer");P.className="spotpatch-actions";let ve=c(e,"div");ve.className="spotpatch-context-state spotpatch-editor-feedback",ve.dataset.state="idle",ve.setAttribute("role","status"),ve.setAttribute("aria-live","polite"),ve.hidden=!0;let Ee=ee(e,r.actions.addElement),we=ee(e,r.actions.reselect),re=ee(e,r.actions.openEditor),Z=ee(e,r.actions.preview,"spotpatch-primary"),Oe=ee(e,r.actions.copy,"spotpatch-primary"),_e=ee(e,r.actions.back),Pe=c(e,"div");Pe.className="spotpatch-secondary-actions";let We=c(e,"div");We.className="spotpatch-primary-actions",Ee.classList.add("spotpatch-icon-action"),Ee.dataset.compactIcon="+",R.testButton.classList.add("spotpatch-icon-action"),R.testButton.dataset.compactIcon="✓",re.classList.add("spotpatch-secondary-action"),we.classList.add("spotpatch-secondary-action"),Pe.append(re,we),We.append(R.testButton,Ee,R.runButton,Z,R.cancelButton,R.applyButton,R.revertButton,R.resetButton,Oe,_e),P.append(ve,Pe,We),$.append(L,k,P),g.append(M,$);let se=c(e,"div");se.className="spotpatch-live",se.setAttribute("aria-live","polite"),se.setAttribute("aria-atomic","true"),p.append(aa(e),U,A,g,E,se),e.documentElement.append(a);let Te,Ae,Le="idle",Ie=!1,ae=!1,Ue="",$e=!0,le=[],ze=0,Je="idle";function Ye(u){Je=u,ve.dataset.state=u,ve.hidden=u==="idle",ve.textContent=u==="opening"?r.announcements.editorOpening:u==="success"?r.announcements.editorOpened:u==="error"?r.announcements.editorFailed:"",N()}function st(u){return u.status==="ready"?r.targets.statusReady:u.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function s(u,m){let v=m===0?0:u/m;Ne.style.width=`${String(v*100)}%`}function d(u){let m=Q.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(m).find(v=>u===void 0||v.dataset.targetInstructionId===u)}function y(u,m){let v=p.activeElement?.closest("textarea[data-target-instruction-id]"),l=v?.dataset.targetInstructionId,_=v?.selectionStart,K=v?.selectionEnd;le=u.map(B=>Object.freeze({...B})),ze=m,Q.replaceChildren();let H=u.filter(B=>B.instruction.trim().length>0).length,G=u.reduce((B,X)=>B+X.instruction.trim().length,0);s(H,u.length),W.textContent=r.targets.count(u.length,m),me.textContent=r.targets.complete(H,u.length);let Xe=G>4e3;oe.dataset.state=Xe?"over":"ready",oe.textContent=Xe?r.targets.instructionBudgetExceeded(G,4e3):r.targets.instructionBudget(G,4e3),Ee.disabled=!$e||u.length>=m,Ee.title=u.length>=m?r.targets.limitTitle(m):r.targets.addTitle,Y.textContent=u.length===1?u[0]?.label??r.context.selectedElement:r.context.selectedCount(u.length);for(let[B,X]of u.entries()){let rt=c(e,"div");rt.className="spotpatch-target-item",rt.dataset.active=String(X.active),rt.dataset.status=X.status,rt.dataset.targetId=X.id;let Lt=c(e,"div");Lt.className="spotpatch-target-summary";let gt=ee(e,"","spotpatch-target-select");gt.dataset.activateTargetId=X.id,gt.setAttribute("aria-label",r.targets.activate(B+1)),gt.setAttribute("aria-expanded",String(X.active));let It=c(e,"span");It.className="spotpatch-target-index",It.textContent=String(B+1);let kt=c(e,"span");kt.className="spotpatch-target-copy";let Nt=c(e,"span");Nt.className="spotpatch-target-name",Nt.textContent=X.label;let Mt=c(e,"span");Mt.className="spotpatch-target-source",Mt.textContent=`${st(X)} · ${X.source}`,kt.append(Nt,Mt);let nn=X.instruction.trim().length>0,Ct=c(e,"span");Ct.className="spotpatch-target-state",Ct.dataset.complete=String(nn),Ct.textContent=nn?r.targets.instructionReady:r.targets.instructionMissing,gt.append(It,kt,Ct);let ft=ee(e,"↗","spotpatch-target-open");ft.dataset.openTargetId=X.id,ft.disabled=!X.canOpenEditor,ft.setAttribute("aria-label",r.actions.openTarget(B+1)),ft.title=r.actions.openTarget(B+1);let ht=ee(e,"×","spotpatch-target-remove");if(ht.dataset.removeTargetId=X.id,ht.disabled=!$e,ht.setAttribute("aria-label",r.targets.remove(B+1)),ht.title=r.targets.removeTitle,Lt.append(gt,ft,ht),rt.append(Lt),X.active){let Dt=c(e,"label");Dt.className="spotpatch-target-editor";let $t=c(e,"span");$t.className="spotpatch-target-editor-head";let zt=c(e,"span");zt.className="spotpatch-target-editor-label",zt.textContent=r.targets.instructionLabel(X.label);let jt=c(e,"span");jt.className="spotpatch-target-editor-count",jt.textContent=r.targets.instructionCount(X.instruction.length,2e3),$t.append(zt,jt);let Ze=c(e,"textarea");Ze.rows=4,Ze.maxLength=2e3,Ze.value=X.instruction,Ze.placeholder=r.targets.instructionPlaceholder,Ze.disabled=!$e,Ze.dataset.targetInstructionId=X.id,Ze.setAttribute("aria-label",r.targets.instructionLabel(X.label)),Dt.append($t,Ze),rt.append(Dt)}Q.append(rt)}if(l!==void 0){let B=d(l);B?.focus({preventScroll:!0}),_!==void 0&&K!==void 0&&B?.setSelectionRange(_,K)}}function I(u,m){le=le.map(B=>B.id===u?Object.freeze({...B,instruction:m}):B);let v=Array.from(Q.querySelectorAll(".spotpatch-target-item")).find(B=>B.dataset.targetId===u);if(v===void 0)return;let l=m.trim().length>0,_=v.querySelector(".spotpatch-target-state"),K=v.querySelector(".spotpatch-target-editor-count");_!==null&&(_.dataset.complete=String(l),_.textContent=l?r.targets.instructionReady:r.targets.instructionMissing),K!==null&&(K.textContent=r.targets.instructionCount(m.length,2e3));let H=le.filter(B=>B.instruction.trim().length>0).length;me.textContent=r.targets.complete(H,le.length),s(H,le.length);let G=le.reduce((B,X)=>B+X.instruction.trim().length,0),Xe=G>4e3;oe.dataset.state=Xe?"over":"ready",oe.textContent=Xe?r.targets.instructionBudgetExceeded(G,4e3):r.targets.instructionBudget(G,4e3)}function j(u){U.replaceChildren(),Ae=u.find(m=>m.active)?.rect,Te=Ae;for(let[m,v]of u.entries()){let l=c(e,"div");l.className="spotpatch-selection-highlight",l.dataset.targetId=v.id,l.dataset.active=String(v.active),l.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,l.style.width=`${String(v.rect.width)}px`,l.style.height=`${String(v.rect.height)}px`;let _=c(e,"span");_.textContent=`${String(m+1)} · ${v.label}`,l.append(_),U.append(l)}N()}function N(){if(g.hidden)return;let u=e.defaultView,m=u?.innerWidth??e.documentElement.clientWidth,v=u?.innerHeight??e.documentElement.clientHeight,l=g.getBoundingClientRect(),_=Le==="previewing"?"previewing":"selected",K=l.width>0?l.width:Math.min(oo,m-32),H=l.height>0?l.height:Math.min(ra[_],v-32),G=eo({dialogWidth:K,dialogHeight:H,viewportWidth:m,viewportHeight:v,...Te===void 0?{}:{target:Te}});g.style.left=`${String(G.left)}px`,g.style.top=`${String(G.top)}px`,g.style.setProperty("--spotpatch-anchor-x",`${String(G.anchorX)}px`),g.style.setProperty("--spotpatch-anchor-y",`${String(G.anchorY)}px`),g.dataset.placement=G.mode}function q(u){let m=r.summary,v=ia(u,m.source);fe.textContent=v??r.diagnostics.noExactSource;let l=`${m.browserContext}: ${m.collectionStatuses.ready}`,_=`${m.browserContext}: ${m.collectionStatuses.loading}`,K=`${m.browserContext}: ${m.collectionStatuses.failed}`,H=`${m.api}: ${m.apiStatuses.loading}`,G=`${m.api}: ${m.apiStatuses.failed}`;u.includes(l)&&!u.includes(_)&&!u.includes(H)&&!u.includes(K)&&!u.includes(G)?(O.dataset.state="ready",O.textContent=r.context.ready):u.includes(K)||u.includes(G)?(O.dataset.state="warning",O.textContent=r.context.partial):(O.dataset.state="loading",O.textContent=r.context.collecting)}function lt(u,m,v){Ie=m,ae=v,Ue=u,xe.textContent=u,re.disabled=!m,Z.disabled=!v,R.setContextReady(v),q(u),N()}function pt(u){Le=u;let m=u==="selected",v=u==="previewing";E.hidden=m||v,ke.hidden=!m,De.hidden=!v,we.hidden=!m,Ee.hidden=!m,re.hidden=!m,Z.hidden=!m,Pe.hidden=!m,R.setSelectionVisible(m),Oe.hidden=!v,_e.hidden=!v,F.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,ue.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,N()}function ut(){r=i.messages(),te.textContent=r.brand.name,z.textContent=r.brand.context,b.textContent=r.brand.repository,b.title=r.brand.repositoryTitle,b.setAttribute("aria-label",r.brand.repositoryTitle),S.textContent=r.alternateLocaleName,S.title=r.switchLocale,S.setAttribute("aria-label",r.switchLocale),w.setAttribute("aria-label",r.dialog.close),w.title=r.dialog.close,He.setAttribute("aria-label",r.targets.ariaLabel),Be.textContent=r.targets.title,ye.textContent=r.diagnostics.title,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Ee.textContent=r.actions.addElement,we.textContent=r.actions.reselect,re.textContent=r.actions.openEditor,Z.textContent=r.actions.preview,Oe.textContent=r.actions.copy,_e.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=Le==="inspecting"?r.trigger.stop:r.trigger.select,pt(Le),Ye(Je),le.length>0?y(le,ze):(W.textContent=r.targets.count(0,ze),me.textContent=r.targets.complete(0,0),s(0,0),oe.dataset.state="ready",oe.textContent=r.targets.instructionBudget(0,4e3),Y.textContent=r.context.selectedElement),Ue.length>0?q(Ue):(fe.textContent=r.diagnostics.resolving,O.textContent=r.context.collecting)}ge.addEventListener("toggle",N),S.addEventListener("click",i.toggle);let At=i.subscribe(ut);return ut(),Object.freeze({host:a,triggerButton:E,addTargetButton:Ee,targetList:Q,reselectButton:we,openEditorButton:re,repositoryLink:b,previewButton:Z,copyButton:Oe,backButton:_e,closeButton:w,agentProviderSelect:R.providerSelect,agentModelSelect:R.modelSelect,agentModeSelect:R.modeSelect,agentConsentCheckbox:R.consentCheckbox,agentWorkspaceConsentCheckbox:R.workspaceConsentCheckbox,agentTestButton:R.testButton,agentRunButton:R.runButton,agentCancelButton:R.cancelButton,agentApplyButton:R.applyButton,agentRevertButton:R.revertButton,agentResetButton:R.resetButton,renderStatus(u){let m=u==="inspecting";E.setAttribute("aria-pressed",String(m)),E.textContent=m?r.trigger.stop:r.trigger.select,pt(u)},renderEditorStatus:Ye,showHighlight(u,m){Te=u,A.hidden=!1,A.style.transform=`translate(${String(u.x)}px, ${String(u.y)}px)`,A.style.width=`${String(u.width)}px`,A.style.height=`${String(u.height)}px`,C.textContent=m,Y.textContent=m,N()},hideHighlight(){Te=Ae,A.hidden=!0,C.textContent="",N()},showSelectionHighlights:j,hideSelectionHighlights(){U.replaceChildren(),Ae=void 0,Te=void 0,N()},showSelection(u,m,v){lt(u,m,v),E.hidden=!0,g.hidden=!1,N()},updateSelection:lt,renderTargets:y,updateTargetInstruction:I,setPreviewEnabled(u){ae=u,Z.disabled=!u,R.setContextReady(u)},hideSelection(){g.hidden=!0,E.hidden=!1,Q.replaceChildren(),le=[],ze=0,Ue="",Ye("idle"),W.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),s(0,0),Y.textContent=r.context.selectedElement,xe.textContent="",Se.textContent="",fe.textContent=r.diagnostics.resolving,O.dataset.state="loading",O.textContent=r.context.collecting,re.disabled=!0,Z.disabled=!0,Ie=!1,ae=!1,R.setContextReady(!1),R.setSelectionVisible(!1),R.setEditingEnabled(!0),R.resetJob()},hideSelectionTemporarily(){g.hidden=!0,E.hidden=!1},showPreview(u){Se.textContent=u,N()},readAgentSelection(){return R.readSelection()},agentConsentGranted(){return R.consentGranted()},setAgentProviderConsent(u){R.setProviderConsent(u)},setAgentEditingEnabled(u){$e=u,Ee.disabled=!u,we.disabled=!u,Q.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(m=>{m.disabled=!u}),re.disabled=!Ie,Z.disabled=!u||!ae,R.setEditingEnabled(u),N()},renderAgentCapability(u,m,v,l){R.renderCapability(u,m,v,l);let _=u==="ready"&&v?.state==="agent-ready";Z.classList.toggle("spotpatch-primary",!_),N()},renderAgentWorkspaceHealth(u,m,v){R.renderWorkspaceHealth(u,m,v),N()},renderAgentJob(u,m,v,l){R.renderJob(u,m,v,l),N()},resetAgentJob(){R.resetJob(),N()},focusTargetInstruction(u){d(u)?.focus({preventScroll:!0})},focusPrompt(){Se.focus({preventScroll:!0})},announce(u){se.textContent="",se.textContent=u},locale:i.locale,messages:i.messages,agentWorkspaceConsentGranted:R.workspaceConsentGranted,subscribeLocale:i.subscribe,dispose(){ge.removeEventListener("toggle",N),S.removeEventListener("click",i.toggle),At(),R.dispose(),a.remove()}})}function sa(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 io(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${sa(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(`
959
+ `)}function so(e,t){return`${e}:${t}`}function ca(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function co(e){let t=f=>yn(f)??h.INTERNAL_ERROR,o=f=>e.view.messages().errors[t(f)],n=new Map,i=new Set,r=new Map,a=0,p,E,A=!1,C=!1,U=()=>e.view.readAgentSelection(),g=f=>`${f.providerProfileId}:${f.applyMode}`,M=async f=>{e.view.renderAgentWorkspaceHealth("checking");try{let b=await e.api.agentWorkspaceHealth();return f!==a||e.view.renderAgentWorkspaceHealth(b.state,b,b.errorCode),b}catch(b){throw f===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(b)),b}},$=f=>{p!==void 0&&e.view.renderAgentJob(p,E,Object.freeze([...r.values()]),f??p.errorCode)},L=()=>{let f=U();if(f===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(g(f)));let b=n.get(so(f.providerProfileId,f.modelProfileId));b===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,b)},x=async f=>{let b=U();if(b===void 0)throw new Error("Agent provider selection is unavailable.");let S=so(b.providerProfileId,b.modelProfileId),w=n.get(S);if(w!==void 0)return w;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let F=await e.api.agentCapability(b);if(f!==a)return F;if(F.state!=="agent-ready")throw new D(F.errorCode??h.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(S,F),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,F),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),F},T=async(f,b)=>{try{let S=await e.api.agentResult(f);if(b!==a||S.snapshot.jobId!==f)return;p=S.snapshot,E=S.result,$()}catch(S){b===a&&$(t(S))}},V=async(f,b)=>{try{await e.api.agentEvents(f,S=>{if(b!==a||S.jobId!==f)return;S.type==="snapshot"&&(p=S.data.snapshot,p.status==="applied"&&!A&&(A=!0,e.onApplied()));let w=ca(S);w!==void 0&&r.set(w.key,w),$()}),b===a&&await T(f,b)}catch(S){b===a&&!(S instanceof DOMException&&S.name==="AbortError")&&$(t(S))}},te=async f=>{let b=p;if(b===void 0||C)return;C=!0;let S=a;p=Object.freeze({...b,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}),$();try{let w=f==="apply"?await e.api.applyAgentJob(b.jobId):f==="cancel"?await e.api.cancelAgentJob(b.jobId):await e.api.revertAgentJob(b.jobId);if(S!==a)return;p=w,w.status==="applied"&&!A&&(A=!0,e.onApplied()),await T(w.jobId,S)}catch(w){if(S!==a)return;p=b,await T(b.jobId,S),$(t(w)),e.view.announce(o(w))}finally{S===a&&(C=!1)}},z=()=>{a+=1,p=void 0,E=void 0,r.clear(),A=!1,C=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),L()};return Object.freeze({apply(){p?.canApply===!0&&te("apply")},beginSelection(){z();let f=a;e.ai.enabled&&M(f).catch(()=>{})},cancel(){p?.canCancel===!0&&te("cancel")},consentChanged(){let f=U();f!==void 0&&(e.view.agentConsentGranted()?i.add(g(f)):i.delete(g(f)))},disposeSelection(){let f=p?.canCancel===!0||p?.status==="cancelling"?p.jobId:void 0;a+=1,p=void 0,E=void 0,r.clear(),A=!1,C=!1,f!==void 0&&e.api.cancelAgentJob(f).catch(()=>{})},providerOrModelChanged(){a+=1,L(),M(a).catch(()=>{})},reset(){let f=A;z(),f?e.onReselectRequired():e.ai.enabled&&M(a).catch(()=>{})},revert(){p?.canRevert===!0&&te("revert")},run(){if(!e.ai.enabled||p!==void 0)return;let f=U(),b=e.getAnnotation();if(f===void 0||b===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(g(f));let S=++a;e.view.setAgentEditingEnabled(!1),M(S).then(async w=>{if(S!==a)return;if(w.state==="blocked")throw new D(w.errorCode??h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(w.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new D(h.WORKTREE_DIRTY);let F=await e.api.createAgentJob({annotation:b,applyMode:f.applyMode,providerProfileId:f.providerProfileId,modelProfileId:f.modelProfileId,providerDataConsent:!0,...f.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:w.state==="consent-required"?"include-local-changes":"require-clean"});S===a&&(p=F,E=void 0,r.clear(),$(),V(F.jobId,S))}).catch(w=>{S===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(w),void 0,t(w)),e.view.announce(o(w)))})},testCapability(){if(!e.ai.enabled||p!==void 0)return;let f=++a;Promise.all([x(f),M(f)]).catch(b=>{f===a&&(e.view.renderAgentCapability("error",o(b),void 0,t(b)),e.view.announce(o(b)))})}})}function lo(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 Qt(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 po(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var la=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function en(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 pa(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 ua(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ga(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 uo(e,t={}){let o=ga(t),n=t.view??ao(o.document,e.shortcut,e.ai,e.locale),i=t.api??xn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??Bn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??po(o.window.navigator),p=t.createId??(()=>lo(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??Wn(o.window,e.sessionId,e.maxTargets),C=A.load(),U=Kn({adapter:t.reactAdapter??da({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.")}}),g=Yt,M=!1,$,L,x=C?.targets.map(s=>{let d=Zt(s.source);return{id:s.id,resolution:Object.freeze({source:s.source,react:s.react}),apiStatus:d===void 0?"not-required":s.code===void 0?"failed":"connected",code:s.code,collectionStatus:"ready",element:void 0,elementContext:s.element,instruction:s.instruction,marker:d,page:s.page,styles:s.styles}})??[],T=C?.activeTargetId,V=C?.sequence??0,te=C?.open??!1,z=!1,f=0,b=0,S=!1,w="",F,ue,Re,Y,O=new Map;function k(s){g=Un(g,s),n.renderStatus(g.status)}function ke(){return x.find(s=>s.id===T)??x.at(-1)}function He(s){if(!(s.elementContext===void 0||s.styles===void 0))return{id:s.id,instruction:s.instruction,page:s.page,source:s.resolution.source,react:s.resolution.react,element:s.elementContext,styles:s.styles,...s.code===void 0?{}:{code:s.code}}}function ie(){let s=x.flatMap(y=>{let I=He(y);return I===void 0?[]:[I]});if(s.length===0){A.clear();return}let d=new Set(s.map(({id:y})=>y));A.save({...T!==void 0&&d.has(T)?{activeTargetId:T}:{},open:te,sequence:V,targets:s})}function Be(s,d){return M&&d===f&&g.status!=="idle"&&x.includes(s)}function de(){let s=x.reduce((d,y)=>d+y.instruction.trim().length,0);return x.length>0&&s<=4e3&&x.every(d=>d.instruction.trim().length>0&&d.elementContext!==void 0&&d.styles!==void 0&&d.apiStatus!=="loading")}function me(){let s=n.messages().summary;return x.map((d,y)=>{let I=io({resolution:d.resolution,...d.code===void 0?{}:{code:d.code},...d.styles===void 0?{}:{styles:d.styles},apiStatus:d.apiStatus,collectionStatus:d.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},s);return`${s.target(y+1,d.id===T)}
960
+ ${I}`}).join(`
954
961
 
955
- `)}function te(){let s=m.flatMap(p=>{if(!p.element?.isConnected)return[];let c=Tt(p.element,o.window);return c===void 0?[]:[{id:p.id,label:Xt(p.element),rect:c,active:p.id===S}]});s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function M(s=!1){if(m.length===0)return;n.renderTargets(m.map(P=>({id:P.id,label:P.resolution.react.componentName??(P.element===void 0?P.elementContext?.tagName??"Element":Xt(P.element)),source:pa(P,n.messages().context.sourceUnavailable),canOpenEditor:P.marker!==void 0,status:ua(P),active:P.id===S,instruction:P.instruction})),e.maxTargets),te();let p=_e(),c=me(),x=p?.marker!==void 0;s?n.showSelection(c,x,Te()):n.updateSelection(c,x,Te())}function be(){if(!Te())return;let s=m.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let c=[...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(),page:p.page,source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:c}});return nn({id:l(),locale:n.locale(),createdAt:E(),page:Yt(o.document,o.window),targets:s})}function we(s){n.showHighlight(kn(s,o.window),Xt(s))}function ne(){W?.isConnected===!0&&W.focus({preventScroll:!0}),W=void 0}function le(){for(let s of B.values())o.window.clearTimeout(s);B.clear()}function De(){y+=1,i.cancelPending(),_.disposeSelection(),le(),$?.disconnect(),m=[],S=void 0,K=!1,h=!1,O=!1,I="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),ne()}function ye(){g.status==="inspecting"?N({type:"CANCEL"}):g.status==="selected"?N({type:"CLOSE"}):g.status==="previewing"&&(N({type:"BACK"}),N({type:"CLOSE"})),K=!1,Y(),n.hideSelection(),n.hideSelectionHighlights(),ne(),n.hideHighlight()}function Oe(){if(g.status!=="inspecting"||!O||m.length===0){ye();return}O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.focusTargetInstruction(S),n.announce(n.messages().announcements.addCancelled)}function xe(){if(g.status==="inspecting"&&O){Oe();return}if(g.status!=="idle"){ye();return}if(m.length>0){K=!0,N({type:"RESTORE"}),h||(_.beginSelection(),h=!0),M(!0),n.focusTargetInstruction(S),Y();return}N({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function w(s=n.messages().announcements.chooseAnother){g.status==="selected"&&(N({type:"RESELECT"}),De(),n.hideHighlight(),n.announce(s))}function Pe(){if(g.status==="selected"){if(m.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}O=!0,N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(m.length,e.maxTargets))}}function Se(){y+=1,le(),$?.disconnect();for(let s of m)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),M(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=so({ai:e.ai,api:i,getAnnotation:be,onApplied:Se,onReselectRequired(){w(n.messages().announcements.reselectAfterChange)},view:n});async function F(s,p){let c=s.marker;if(c!==void 0)try{let x=await i.sourceContext({fileId:c.fileId,line:c.line,column:c.column,maxLines:e.budget.maxCodeLines});ve(s,p)&&(s.code=x,s.apiStatus="connected",Y(),M(),n.announce(n.messages().announcements.sourceLoaded))}catch(x){ve(s,p)&&(s.code=void 0,s.apiStatus="failed",Y(),M(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(x instanceof DOMException&&x.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function se(s,p){let c=s.element;if(c===void 0)return;let x=o.window.setTimeout(()=>{if(B.delete(s.id),!ve(s,p))return;let P=!1;try{s.elementContext=On({element:c,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,P=!0}try{s.styles=An({document:o.document,element:c,maxCharacters:e.budget.cssCharacters})}catch{s.styles=la,P=!0}s.collectionStatus=P?"failed":"ready",Y(),M(),n.announce(P?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);B.set(s.id,x)}function Ce(s,p){return p!==void 0?m.find(c=>c.marker?.fileId===p.fileId&&c.marker.line===p.line&&c.marker.column===p.column):m.find(c=>c.element===s)}function pe(s){let p=j.resolve(s),c=Kt(p.source),x=Ce(s,c);if(x!==void 0){S=x.id,O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.focusTargetInstruction(x.id),n.announce(n.messages().announcements.duplicate);return}if(m.length>=e.maxTargets){O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}m.length===0&&(W=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,I="",_.beginSelection(),h=!0),ee+=1;let C={id:`target-${String(ee)}`,element:s,resolution:p,marker:c,page:Yt(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:c===void 0?"not-required":"loading",collectionStatus:"loading"};m.push(C),S=C.id,O=!1;let oe=y;N({type:"SELECT"}),n.hideHighlight(),$?.observe(s),M(!0),K=!0,n.focusTargetInstruction(C.id),se(C,oe),c!==void 0?F(C,oe):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function ue(){if(V=void 0,g.status!=="inspecting"||L===void 0)return;let s=Wt(o.document,o.window,L.x,L.y);if(N({type:"HOVER"}),s===void 0){n.hideHighlight();return}we(s)}function Le(s){g.status==="inspecting"&&(L={x:s.clientX,y:s.clientY},V??=o.window.requestAnimationFrame(ue))}function Ie(s){if(g.status!=="inspecting"||Mn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let p=Wt(o.document,o.window,s.clientX,s.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}pe(p)}function Ee(s){if(s.key==="Escape"&&g.status!=="idle"){s.preventDefault(),g.status==="inspecting"&&O?Oe():g.status==="inspecting"||g.status==="selected"?ye():(N({type:"BACK"}),n.focusTargetInstruction(S));return}Pn(s.target)||!Ln(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),xe())}function $e(s){if(g.status!=="selected"&&g.status!=="inspecting")return;let p=m.findIndex(P=>P.id===s);if(p<0)return;let[c]=m.splice(p,1);if(c===void 0)return;let x=B.get(c.id);if(x!==void 0&&(o.window.clearTimeout(x),B.delete(c.id)),c.element!==void 0&&$?.unobserve(c.element),S===c.id&&(S=m.at(-1)?.id),m.length===0){O=!0,g.status==="selected"&&N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}M(),Y(),n.announce(n.messages().announcements.targetRemoved)}function X(){if(g.status==="idle"||m.length===0)return;let s=m.filter(p=>p.element!==void 0&&!p.element.isConnected);if(s.length>0){for(let p of s)p.element!==void 0&&($?.unobserve(p.element),p.element=void 0);M(),Y(),n.announce(n.messages().announcements.detachedTargetPreserved);return}te()}function Z(s){let p=s===void 0?_e():m.find(C=>C.id===s);if(g.status!=="selected"||p?.marker===void 0)return;S!==p.id&&(S=p.id,M());let c=p.marker,x=y,P=++T;N({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:c.fileId,line:c.line,column:c.column}).then(()=>{k&&g.status==="selected"&&x===y&&P===T&&S===p.id&&m.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{k&&g.status==="selected"&&x===y&&P===T&&S===p.id&&m.includes(p)&&n.renderEditorStatus("error")})}function ze(s){if(g.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,c=m.find(x=>x.id===p);c!==void 0&&(c.instruction=s.target.value,n.updateTargetInstruction(c.id,c.instruction),n.setPreviewEnabled(Te()),Y())}function ke(){Z()}function Re(s){e.ai.enabled&&g.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),_.run())}function Ne(){if(g.status!=="selected")return;let s=be();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}I=r.compose(s),N({type:"PREVIEW"}),n.showPreview(I),n.focusPrompt()}function je(){if(g.status!=="previewing"||I.length===0)return;if(a===void 0){N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=y;a.writeText(I).then(()=>{k&&s===y&&g.status==="previewing"&&(N({type:"COPY_SUCCESS"}),n.focusTargetInstruction(S),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{k&&s===y&&g.status==="previewing"&&(N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function He(){g.status==="previewing"&&(N({type:"BACK"}),n.focusTargetInstruction(S))}function z(){if(!(!k||m.length===0)&&(M(),g.status==="previewing")){let s=be();s!==void 0&&(I=r.compose(s),n.showPreview(I))}}function Be(s){let p=s.target;if(!(p instanceof Element))return;let c=p.closest("button[data-remove-target-id]");if(c?.dataset.removeTargetId!==void 0){$e(c.dataset.removeTargetId);return}let x=p.closest("button[data-open-target-id]");if(x?.dataset.openTargetId!==void 0){Z(x.dataset.openTargetId);return}let C=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;g.status!=="selected"||C===void 0||!m.some(oe=>oe.id===C)||(S=C,M(),n.focusTargetInstruction(C))}function Ke(){w()}function Ye(){k||(k=!0,n.renderStatus(g.status),o.document.addEventListener("pointermove",Le,!0),o.document.addEventListener("click",Ie,!0),o.document.addEventListener("keydown",Ee,!0),o.window.addEventListener("scroll",X,!0),o.window.addEventListener("resize",X),n.triggerButton.addEventListener("click",xe),n.addTargetButton.addEventListener("click",Pe),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",Be),n.targetList.addEventListener("input",ze),n.targetList.addEventListener("keydown",Re),n.openEditorButton.addEventListener("click",ke),n.previewButton.addEventListener("click",Ne),n.copyButton.addEventListener("click",je),n.backButton.addEventListener("click",He),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),ie=n.subscribeLocale(z),o.resizeObserver!==void 0&&($=new o.resizeObserver(X)),o.mutationObserver!==void 0&&(ae=new o.mutationObserver(X),ae.observe(o.document.documentElement,{childList:!0,subtree:!0})),K&&m.length>0&&(N({type:"RESTORE"}),_.beginSelection(),h=!0,M(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function it(){if(!k){ie?.(),ie=void 0,n.dispose(),i.cancelPending(),i.dispose(),_.disposeSelection(),j.dispose();return}k=!1,ie?.(),ie=void 0,o.document.removeEventListener("pointermove",Le,!0),o.document.removeEventListener("click",Ie,!0),o.document.removeEventListener("keydown",Ee,!0),o.window.removeEventListener("scroll",X,!0),o.window.removeEventListener("resize",X),n.triggerButton.removeEventListener("click",xe),n.addTargetButton.removeEventListener("click",Pe),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",Be),n.targetList.removeEventListener("input",ze),n.targetList.removeEventListener("keydown",Re),n.openEditorButton.removeEventListener("click",ke),n.previewButton.removeEventListener("click",Ne),n.copyButton.removeEventListener("click",je),n.backButton.removeEventListener("click",He),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),V!==void 0&&(o.window.cancelAnimationFrame(V),V=void 0),le(),Y(),$?.disconnect(),ae?.disconnect(),$=void 0,ae=void 0,m=[],S=void 0,I="",L=void 0,W=void 0,i.cancelPending(),i.dispose(),_.disposeSelection(),j.dispose(),n.dispose(),g=Ft}return Object.freeze({mount:Ye,dispose:it,getState:()=>g})}var uo="__spotpatchRuntime__";function Zt(e){let t=globalThis;t[uo]?.dispose();let o=po(e);t[uo]=o,o.mount()}Zt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
962
+ `)}function oe(){let s=x.flatMap(d=>{if(!d.element?.isConnected)return[];let y=_t(d.element,o.window);return y===void 0?[]:[{id:d.id,label:en(d.element),rect:y,active:d.id===T}]});s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function W(s=!1){if(x.length===0)return;n.renderTargets(x.map(j=>({id:j.id,label:j.resolution.react.componentName??(j.element===void 0?j.elementContext?.tagName??"Element":en(j.element)),source:pa(j,n.messages().context.sourceUnavailable),canOpenEditor:j.marker!==void 0,status:ua(j),active:j.id===T,instruction:j.instruction})),e.maxTargets),oe();let d=ke(),y=me(),I=d?.marker!==void 0;s?n.showSelection(y,I,de()):n.updateSelection(y,I,de())}function be(){if(!de())return;let s=x.map(d=>{if(d.elementContext===void 0||d.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let y=[...d.apiStatus==="failed"?["Source context could not be loaded."]:[],...d.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:d.instruction.trim(),page:d.page,source:d.resolution.source,react:d.resolution.react,element:d.elementContext,styles:d.styles,...d.code===void 0?{}:{code:d.code},warnings:y}});return rn({id:p(),locale:n.locale(),createdAt:E(),page:Qt(o.document,o.window),targets:s})}function Ne(s){n.showHighlight(Mn(s,o.window),en(s))}function Q(){F?.isConnected===!0&&F.focus({preventScroll:!0}),F=void 0}function ge(){for(let s of O.values())o.window.clearTimeout(s);O.clear()}function Me(){f+=1,i.cancelPending(),P.disposeSelection(),ge(),ue?.disconnect(),x=[],T=void 0,te=!1,z=!1,S=!1,w="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),Q()}function ye(){g.status==="inspecting"?k({type:"CANCEL"}):g.status==="selected"?k({type:"CLOSE"}):g.status==="previewing"&&(k({type:"BACK"}),k({type:"CLOSE"})),te=!1,ie(),n.hideSelection(),n.hideSelectionHighlights(),Q(),n.hideHighlight()}function fe(){if(g.status!=="inspecting"||!S||x.length===0){ye();return}S=!1,k({type:"SELECT"}),n.hideHighlight(),W(!0),n.focusTargetInstruction(T),n.announce(n.messages().announcements.addCancelled)}function xe(){if(g.status==="inspecting"&&S){fe();return}if(g.status!=="idle"){ye();return}if(x.length>0){te=!0,k({type:"RESTORE"}),z||(P.beginSelection(),z=!0),W(!0),n.focusTargetInstruction(T),ie();return}k({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function R(s=n.messages().announcements.chooseAnother){g.status==="selected"&&(k({type:"RESELECT"}),Me(),n.hideHighlight(),n.announce(s))}function De(){if(g.status==="selected"){if(x.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}S=!0,k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(x.length,e.maxTargets))}}function Se(){f+=1,ge(),ue?.disconnect();for(let s of x)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),W(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let P=co({ai:e.ai,api:i,getAnnotation:be,onApplied:Se,onReselectRequired(){R(n.messages().announcements.reselectAfterChange)},view:n});async function ve(s,d){let y=s.marker;if(y!==void 0)try{let I=await i.sourceContext({fileId:y.fileId,line:y.line,column:y.column,maxLines:e.budget.maxCodeLines});Be(s,d)&&(s.code=I,s.apiStatus="connected",ie(),W(),n.announce(n.messages().announcements.sourceLoaded))}catch(I){Be(s,d)&&(s.code=void 0,s.apiStatus="failed",ie(),W(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(I instanceof DOMException&&I.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Ee(s,d){let y=s.element;if(y===void 0)return;let I=o.window.setTimeout(()=>{if(O.delete(s.id),!Be(s,d))return;let j=!1;try{s.elementContext=Pn({element:y,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,j=!0}try{s.styles=Rn({document:o.document,element:y,maxCharacters:e.budget.cssCharacters})}catch{s.styles=la,j=!0}s.collectionStatus=j?"failed":"ready",ie(),W(),n.announce(j?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);O.set(s.id,I)}function we(s,d){return d!==void 0?x.find(y=>y.marker?.fileId===d.fileId&&y.marker.line===d.line&&y.marker.column===d.column):x.find(y=>y.element===s)}function re(s){let d=U.resolve(s),y=Zt(d.source),I=we(s,y);if(I!==void 0){T=I.id,S=!1,k({type:"SELECT"}),n.hideHighlight(),W(!0),n.focusTargetInstruction(I.id),n.announce(n.messages().announcements.duplicate);return}if(x.length>=e.maxTargets){S=!1,k({type:"SELECT"}),n.hideHighlight(),W(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}x.length===0&&(F=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,w="",P.beginSelection(),z=!0),V+=1;let N={id:`target-${String(V)}`,element:s,resolution:d,marker:y,page:Qt(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:y===void 0?"not-required":"loading",collectionStatus:"loading"};x.push(N),T=N.id,S=!1;let q=f;k({type:"SELECT"}),n.hideHighlight(),ue?.observe(s),W(!0),te=!0,n.focusTargetInstruction(N.id),Ee(N,q),y!==void 0?ve(N,q):n.announce(d.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Z(){if($=void 0,g.status!=="inspecting"||L===void 0)return;let s=qt(o.document,o.window,L.x,L.y);if(k({type:"HOVER"}),s===void 0){n.hideHighlight();return}Ne(s)}function Oe(s){g.status==="inspecting"&&(L={x:s.clientX,y:s.clientY},$??=o.window.requestAnimationFrame(Z))}function _e(s){if(g.status!=="inspecting"||$n(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let d=qt(o.document,o.window,s.clientX,s.clientY);if(d===void 0){n.announce(n.messages().announcements.noSelectable);return}re(d)}function Pe(s){if(s.key==="Escape"&&g.status!=="idle"){s.preventDefault(),g.status==="inspecting"&&S?fe():g.status==="inspecting"||g.status==="selected"?ye():(k({type:"BACK"}),n.focusTargetInstruction(T));return}In(s.target)||!kn(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),xe())}function We(s){if(g.status!=="selected"&&g.status!=="inspecting")return;let d=x.findIndex(j=>j.id===s);if(d<0)return;let[y]=x.splice(d,1);if(y===void 0)return;let I=O.get(y.id);if(I!==void 0&&(o.window.clearTimeout(I),O.delete(y.id)),y.element!==void 0&&ue?.unobserve(y.element),T===y.id&&(T=x.at(-1)?.id),x.length===0){S=!0,g.status==="selected"&&k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}W(),ie(),n.announce(n.messages().announcements.targetRemoved)}function se(){if(g.status==="idle"||x.length===0)return;let s=x.filter(d=>d.element!==void 0&&!d.element.isConnected);if(s.length>0){for(let d of s)d.element!==void 0&&(ue?.unobserve(d.element),d.element=void 0);W(),ie(),n.announce(n.messages().announcements.detachedTargetPreserved);return}oe()}function Te(s){let d=s===void 0?ke():x.find(N=>N.id===s);if(g.status!=="selected"||d?.marker===void 0)return;T!==d.id&&(T=d.id,W());let y=d.marker,I=f,j=++b;k({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:y.fileId,line:y.line,column:y.column}).then(()=>{M&&g.status==="selected"&&I===f&&j===b&&T===d.id&&x.includes(d)&&n.renderEditorStatus("success")}).catch(()=>{M&&g.status==="selected"&&I===f&&j===b&&T===d.id&&x.includes(d)&&n.renderEditorStatus("error")})}function Ae(s){if(g.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let d=s.target.dataset.targetInstructionId,y=x.find(I=>I.id===d);y!==void 0&&(y.instruction=s.target.value,n.updateTargetInstruction(y.id,y.instruction),n.setPreviewEnabled(de()),ie())}function Le(){Te()}function Ie(s){e.ai.enabled&&g.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),P.run())}function ae(){if(g.status!=="selected")return;let s=be();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}w=r.compose(s),k({type:"PREVIEW"}),n.showPreview(w),n.focusPrompt()}function Ue(){if(g.status!=="previewing"||w.length===0)return;if(a===void 0){k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=f;a.writeText(w).then(()=>{M&&s===f&&g.status==="previewing"&&(k({type:"COPY_SUCCESS"}),n.focusTargetInstruction(T),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{M&&s===f&&g.status==="previewing"&&(k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function $e(){g.status==="previewing"&&(k({type:"BACK"}),n.focusTargetInstruction(T))}function le(){if(!(!M||x.length===0)&&(W(),g.status==="previewing")){let s=be();s!==void 0&&(w=r.compose(s),n.showPreview(w))}}function ze(s){let d=s.target;if(!(d instanceof Element))return;let y=d.closest("button[data-remove-target-id]");if(y?.dataset.removeTargetId!==void 0){We(y.dataset.removeTargetId);return}let I=d.closest("button[data-open-target-id]");if(I?.dataset.openTargetId!==void 0){Te(I.dataset.openTargetId);return}let N=d.closest("button[data-activate-target-id]")?.dataset.activateTargetId;g.status!=="selected"||N===void 0||!x.some(q=>q.id===N)||(T=N,W(),n.focusTargetInstruction(N))}function Je(){R()}function Ye(){M||(M=!0,n.renderStatus(g.status),o.document.addEventListener("pointermove",Oe,!0),o.document.addEventListener("click",_e,!0),o.document.addEventListener("keydown",Pe,!0),o.window.addEventListener("scroll",se,!0),o.window.addEventListener("resize",se),n.triggerButton.addEventListener("click",xe),n.addTargetButton.addEventListener("click",De),n.reselectButton.addEventListener("click",Je),n.targetList.addEventListener("click",ze),n.targetList.addEventListener("input",Ae),n.targetList.addEventListener("keydown",Ie),n.openEditorButton.addEventListener("click",Le),n.previewButton.addEventListener("click",ae),n.copyButton.addEventListener("click",Ue),n.backButton.addEventListener("click",$e),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",P.providerOrModelChanged),n.agentModelSelect.addEventListener("change",P.providerOrModelChanged),n.agentModeSelect.addEventListener("change",P.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",P.consentChanged),n.agentTestButton.addEventListener("click",P.testCapability),n.agentRunButton.addEventListener("click",P.run),n.agentCancelButton.addEventListener("click",P.cancel),n.agentApplyButton.addEventListener("click",P.apply),n.agentRevertButton.addEventListener("click",P.revert),n.agentResetButton.addEventListener("click",P.reset),Y=n.subscribeLocale(le),o.resizeObserver!==void 0&&(ue=new o.resizeObserver(se)),o.mutationObserver!==void 0&&(Re=new o.mutationObserver(se),Re.observe(o.document.documentElement,{childList:!0,subtree:!0})),te&&x.length>0&&(k({type:"RESTORE"}),P.beginSelection(),z=!0,W(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function st(){if(!M){Y?.(),Y=void 0,n.dispose(),i.cancelPending(),i.dispose(),P.disposeSelection(),U.dispose();return}M=!1,Y?.(),Y=void 0,o.document.removeEventListener("pointermove",Oe,!0),o.document.removeEventListener("click",_e,!0),o.document.removeEventListener("keydown",Pe,!0),o.window.removeEventListener("scroll",se,!0),o.window.removeEventListener("resize",se),n.triggerButton.removeEventListener("click",xe),n.addTargetButton.removeEventListener("click",De),n.reselectButton.removeEventListener("click",Je),n.targetList.removeEventListener("click",ze),n.targetList.removeEventListener("input",Ae),n.targetList.removeEventListener("keydown",Ie),n.openEditorButton.removeEventListener("click",Le),n.previewButton.removeEventListener("click",ae),n.copyButton.removeEventListener("click",Ue),n.backButton.removeEventListener("click",$e),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",P.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",P.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",P.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",P.consentChanged),n.agentTestButton.removeEventListener("click",P.testCapability),n.agentRunButton.removeEventListener("click",P.run),n.agentCancelButton.removeEventListener("click",P.cancel),n.agentApplyButton.removeEventListener("click",P.apply),n.agentRevertButton.removeEventListener("click",P.revert),n.agentResetButton.removeEventListener("click",P.reset),$!==void 0&&(o.window.cancelAnimationFrame($),$=void 0),ge(),ie(),ue?.disconnect(),Re?.disconnect(),ue=void 0,Re=void 0,x=[],T=void 0,w="",L=void 0,F=void 0,i.cancelPending(),i.dispose(),P.disposeSelection(),U.dispose(),n.dispose(),g=Yt}return Object.freeze({mount:Ye,dispose:st,getState:()=>g})}var go="__spotpatchRuntime__";function tn(e){let t=globalThis;t[go]?.dispose();let o=uo(e);t[go]=o,o.mount()}tn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Fe});