@spotpatch/vite 1.4.0 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,40 @@
1
- import{createReact18Adapter as Dr}from"@spotpatch/react-adapter";var h={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_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 Yn=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Xn=/blob:[^\s"'<>]+/giu,Zn=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Qn=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,eo=/\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,to=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),no=500;function oo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function ro(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ft(e){let t=oo(e);return to.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(Yn,"[redacted inline data]").replace(Xn,"[redacted blob URL]").replace(Zn,"Bearer [redacted]").replace(Qn,"$1[redacted]@").replace(eo,(t,o,n,i)=>{let r=i.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function ao(e){e.username="",e.password="";for(let[t,o]of e.searchParams)ft(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Ze(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let i=new URL(n,t),r=ao(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 ro(n,no)}}var io=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),Pt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),_t=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),so=Object.freeze(["ready","consent-required","blocked"]),co=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),kt=Object.freeze(["added","modified","deleted"]),It=Object.freeze(["passed","failed","cancelled","timed-out"]);var Nt="data-spotpatch-source",lo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Mt(e){if(e===null)return;let t=lo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var Je="/__spotpatch/v1",ht="X-SpotPatch-Token",qe=Object.freeze({sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function Qe(e,t){return`${qe.agentJobs}/${encodeURIComponent(e)}/${t}`}var Dt="https://github.com/huanglvjing/spotpatch";function Vt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function uo(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Vt(e.source)}})}function go(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function fo(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function ho(e){return Object.freeze({instruction:e.instruction.trim(),source:Vt(e.source,e.code),react:uo(e.react),element:go(e.element),styles:fo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function Jt(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(ho)),createdAt:e.createdAt})}var mo=new Set(Object.values(h)),bo=new Set(_t),yo=new Set(It),xo=new Set(kt),Ft=new Set(Pt),So=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Eo=/^[A-Za-z0-9_-]+$/,Ao=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function ne(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function st(e){return ne(e,64,1)&&typeof e=="string"&&So.test(e)}function $t(e){return ne(e,128,22)&&typeof e=="string"&&Eo.test(e)}function ct(e){return typeof e=="string"&&Ao.test(e)&&Number.isFinite(Date.parse(e))}function Fe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Kt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function qt(e,t){return e===void 0||ne(e,t)}function tt(e){return typeof e=="string"&&mo.has(e)}function Yt(e){return!ze(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:st(e.providerProfileId)&&ne(e.providerLabel,100)&&st(e.modelProfileId)&&ne(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&bo.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||ct(e.checkedAt))&&(e.errorCode===void 0||tt(e.errorCode))}function Xt(e){if(!ze(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ct(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!tt(e.errorCode)||!ze(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:r,total:a}=t;return!Fe(o)||!Fe(n)||!Fe(i)||!Fe(r)||!Fe(a)||a<o||a<n||a<i||a<r||a>o+n+i?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function bt(e){return!ze(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:$t(e.jobId)&&typeof e.status=="string"&&Ft.has(e.status)&&st(e.providerProfileId)&&ne(e.providerLabel,100)&&st(e.modelProfileId)&&ne(e.modelLabel,100)&&ne(e.phaseMessage,1024)&&ct(e.createdAt)&&ct(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||tt(e.errorCode))}function Co(e){return ze(e)&&fe(e,["relativePath","kind","additions","deletions"])&&ne(e.relativePath,1024)&&typeof e.kind=="string"&&xo.has(e.kind)&&Fe(e.additions)&&Fe(e.deletions)}function Zt(e){return ze(e)&&fe(e,["checkId","label","status","durationMs","output"])&&st(e.checkId)&&ne(e.label,100)&&typeof e.status=="string"&&yo.has(e.status)&&Fe(e.durationMs)&&ne(e.output,8e4)}function Ro(e){return ze(e)&&fe(e,["jobId","summary","diff","files","checks"])&&$t(e.jobId)&&ne(e.summary,8e4)&&ne(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Co)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(Zt)}function Qt(e){return ze(e)&&fe(e,["snapshot","result"])&&bt(e.snapshot)&&(e.result===void 0||Ro(e.result)&&e.result.jobId===e.snapshot.jobId)}function vo(e){return ze(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&Kt(e.sequence)&&$t(e.jobId)&&typeof e.status=="string"&&Ft.has(e.status)&&ct(e.timestamp)&&typeof e.type=="string"&&ze(e.data)}function en(e){if(!vo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&bt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&ne(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&Kt(t.turn)&&ne(t.toolCallId,256)&&ne(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&qt(t.relativePath,1024)&&qt(t.checkLabel,100);case"check":return fe(t,["result"])&&Zt(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&tt(t.code)&&ne(t.message,1024);default:return!1}}var To=2e6,tn=1e5,wo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oo(e){if(!(!nt(e)||e.ok!==!1||!nt(e.error)))return tt(e.error.code)?e.error.code:void 0}function Lo(e){if(!nt(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function Po(e){return nt(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function on(e){if(!(!nt(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))on(t);Object.freeze(e)}}function lt(e){return on(e),e}async function _o(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let c=await n.read();if(c.done)return a+=i.decode(),a;if(r+=c.value.byteLength,r>t)throw await n.cancel(),new M;a+=i.decode(c.value,{stream:!0})}}catch(c){throw c instanceof M?c:new M}finally{n.releaseLock()}}function rn(e){try{return JSON.parse(e)}catch{throw new M}}async function nn(e){let t=rn(await _o(e,To));if(!e.ok)throw new M(Oo(t));return Lo(t)}function ko(e,t){if(!Yt(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return lt(e)}function yt(e,t){if(!bt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return lt(e)}function Io(e,t){if(!Qt(e)||e.snapshot.jobId!==t)throw new M;return lt(e)}function No(e){if(!en(e))throw new M;return lt(e)}function Mo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function an(e){return e instanceof M?e.code:void 0}function sn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,c,S){let C=new AbortController;t.add(C);try{let u=await e.fetch(a,{method:c,headers:{...S===void 0?{}:{"Content-Type":"application/json"},[ht]:e.sessionToken},...S===void 0?{}:{body:JSON.stringify(S)},signal:C.signal});return await nn(u)}finally{t.delete(C)}}async function i(a,c){let S=new AbortController;t.add(S);try{let C=await e.fetch(Qe(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[ht]:e.sessionToken},body:JSON.stringify({}),signal:S.signal});if(!C.ok){await nn(C);return}if(C.body===null)throw new M;let u=C.body.getReader(),_=new TextDecoder("utf-8",{fatal:!0}),b="",N=0,A=0,R=D=>{if(D.trim().length===0)return;if(new TextEncoder().encode(D).byteLength>tn)throw new M;let L=No(rn(D));if(L.jobId!==a||L.sequence<=A)throw new M;A=L.sequence,c(L)};try{for(;;){let D=await u.read();if(D.done){b+=_.decode(),R(b);return}if(N+=D.value.byteLength,N>wo)throw await u.cancel(),new M;b+=_.decode(D.value,{stream:!0});let L=b.split(`
2
- `);if(b=L.pop()??"",new TextEncoder().encode(b).byteLength>tn)throw await u.cancel(),new M;for(let Z of L)R(Z)}}catch(D){throw D instanceof M||D instanceof DOMException&&D.name==="AbortError"?D:new M}finally{u.releaseLock()}}finally{t.delete(S)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let c=await n(qe.sourceContext,"POST",a);if(!Po(c))throw new M;return Object.freeze({...c})},async openEditor(a){let c=await n(qe.openEditor,"POST",a);if(!nt(c)||c.editor!=="auto"&&c.editor!=="vscode"&&c.editor!=="cursor")throw new M;return Object.freeze({editor:c.editor})},async agentCapability(a){return ko(await n(qe.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(qe.agentWorkspaceHealth,"POST",r);if(!Xt(a))throw new M;return lt(a)},async createAgentJob(a){let c=Mo(a);return yt(await n(qe.agentJobs,"POST",c),a)},agentEvents:i,async agentResult(a){return Io(await n(Qe(a,"result"),"POST",r),a)},async cancelAgentJob(a){return yt(await n(Qe(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return yt(await n(Qe(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return yt(await n(Qe(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var Do=500,cn=256;function $o(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function zo(e){return ft(e)}function ln(e,t,o){if(!zo(e))return e==="href"||e==="src"?Ze(t,o):e==="d"&&t.length>cn?`${t.slice(0,cn)}…`:$o(G(t),Do)}function xe(e){return G(e)}var dn=Object.freeze(["display","position","inset","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height","margin","padding","box-sizing","overflow","overflow-x","overflow-y","flex","flex-direction","flex-wrap","align-items","align-content","justify-content","gap","grid-template-columns","grid-template-rows","font-family","font-size","font-weight","line-height","text-align","white-space","color","background-color","border","border-radius","opacity","visibility","z-index","transform"]);var dt=Object.freeze({cascade:"CSS shorthand and longhand cascade resolution is not available in v1.",cssInJs:"Runtime CSS-in-JS rules may not include original TypeScript source locations.",inaccessibleStylesheet:"A stylesheet could not be inspected because browser security denied access.",selector:"A stylesheet selector could not be evaluated and was skipped.",state:"Dynamic pseudo-class and pseudo-element rules may be unavailable in the current state."});function jo(e){return"selectorText"in e&&"style"in e}function Uo(e){return"cssRules"in e}function Bo(e){if(typeof e.conditionText=="string"&&e.conditionText.length>0)return e.conditionText;let t=e.cssText.indexOf("{"),o=t<0?"":e.cssText.slice(0,t).trim();return o.length===0?void 0:o}function Ho(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((r,a)=>r+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((r,[a,c])=>r+a.length+c.length,0)+i.join(`
3
- `).length}function Go(e,t){return e.href===null?void 0:Ze(e.href,t)}function pn(e,t,o,n,i,r){for(let a of t){if(jo(a)){let c=!1;try{c=e.matches(a.selectorText)}catch{r.add(dt.selector);continue}c&&i.push(Object.freeze({selector:xe(a.selectorText),declarations:xe(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Uo(a)){let c=Bo(a);pn(e,a.cssRules,o,c===void 0?n:[...n,c],i,r)}}}function Wo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of dn){let r=xe(o.getPropertyValue(i).trim());r.length>0&&(n[i]=r)}return n}function un(e){let t=new Set([dt.state,dt.cssInJs,dt.cascade]),o=[],n=e.readCssRules??(u=>u.cssRules);for(let u of e.document.styleSheets){let _;try{_=n(u)}catch{t.add(dt.inaccessibleStylesheet);continue}pn(e.element,_,Go(u,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:xe(r),c=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),S=Object.entries(Wo(e.element,c)),C=Array.from(t);for(;Ho(i,a,o,Object.fromEntries(S),C)>e.maxCharacters;){if(S.length>0){S.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(S)),warnings:Object.freeze(C)})}var Ke=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Vo=new Set(["alt","autocomplete","checked","class","colspan","contenteditable","d","disabled","download","draggable","for","height","hidden","href","id","max","maxlength","min","minlength","multiple","name","open","pattern","placeholder","readonly","rel","required","role","rowspan","selected","src","step","style","tabindex","target","title","type","width"]),Jo=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function fn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function qo(e){return Vo.has(e)||e.startsWith("aria-")||e==="data-testid"}function hn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let r=i.name.toLowerCase();if(!qo(r))continue;let a=ln(r,i.value,n);a!==void 0&&o.push(`${r}="${fn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function mn(e){return G(e).replaceAll(/\s+/gu," ").trim()}function bn(e,t,o,n){if(o.nodeCount>=Ke.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${i}${hn(e)}`),!Jo.has(r)){for(let a of e.childNodes){if(o.nodeCount>=Ke.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let c=mn(a.textContent??"");if(c.length>0){o.nodeCount+=1;let S=c.length<=Ke.maxTextCharacters?c:`${c.slice(0,Ke.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${fn(S)}`)}continue}if(a.nodeType===1){if(t>=Ke.maxDepth){o.truncated=!0;continue}bn(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${r}>`)}}function Fo(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Ke.maxParentDepth;)t.push(hn(o)),o=o.parentElement;return t}function Ko(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function gn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Yo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Xo(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${gn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Yo(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(c=>`.${gn(c)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(c=>c.tagName===e.tagName),r=i.indexOf(e),a=i.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function Zo(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Xo(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function yn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};bn(e.element,0,o,t);let n=Fo(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=mn(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:Zo(e.element),sanitizedHtml:Ko(t.join(`
4
- `),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=Ke.maxTextCharacters?i:`${i.slice(0,Ke.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function xn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Qo(e){return e.toLowerCase()}function Sn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function En(e,t,o){let n=t.split("+").map(u=>u.trim().toLowerCase()).filter(u=>u.length>0),i=n.find(u=>u!=="mod"&&u!=="meta"&&u!=="ctrl"&&u!=="control"&&u!=="alt"&&u!=="option"&&u!=="shift");if(i===void 0||Qo(e.key)!==i)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&xn(o),c=n.includes("ctrl")||n.includes("control")||r&&!xn(o),S=n.includes("alt")||n.includes("option"),C=n.includes("shift");return e.metaKey===a&&e.ctrlKey===c&&e.altKey===S&&e.shiftKey===C}function er(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function tr(e){let t=e.filter(c=>c.width>0&&c.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,r=o.right,a=o.bottom;for(let c of t.slice(1))n=Math.min(n,c.left),i=Math.min(i,c.top),r=Math.max(r,c.right),a=Math.max(a,c.bottom);return Object.freeze({x:n,y:i,width:r-n,height:a-i})}function zt(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=tr(Array.from(e.getClientRects()));if(n!==void 0)return n}return er(e.getBoundingClientRect())}var et="data-spotpatch-ui",pt=Object.freeze({highlight:2147483646,controls:2147483647});function An(e){if(e.closest(`[${et}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(et)}function nr(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}function or(e){return e.tagName==="HTML"||e.tagName==="BODY"}function jt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(r=>!An(r)&&nr(r,t));return i.find(r=>!or(r))??i[0]}function Cn(e){return e instanceof Element&&An(e)}var Ut=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function rr(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function xt(e,t){let o="`".repeat(Math.max(3,rr(t)+1));return`${o}${e}
1
+ import{createReact18Adapter as ea}from"@spotpatch/react-adapter";var g={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 ro=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ao=/blob:[^\s"'<>]+/giu,io=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,so=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,co=/\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,lo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),po=500;function uo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function go(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function bt(e){let t=uo(e);return lo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function H(e){return e.replace(ro,"[redacted inline data]").replace(ao,"[redacted blob URL]").replace(io,"Bearer [redacted]").replace(so,"$1[redacted]@").replace(co,(t,o,n,s)=>{let r=s.at(0),i=r==='"'||r==="'"||r==="`";return`${o}${n}${i?r:""}[redacted]${i?r:""}`})}function fo(e){e.username="",e.password="";for(let[t,o]of e.searchParams)bt(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,H(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Xe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=H(o);try{let s=new URL(n,t),r=fo(s),i=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===i.origin?`${s.pathname}${s.search}${s.hash}`:r}catch{return go(n,po)}}var Ve="/__spotpatch/v1",yt="X-SpotPatch-Token",Ze=Object.freeze({bootstrap:`${Ve}/bootstrap`,sourceContext:`${Ve}/source-context`,openEditor:`${Ve}/open-editor`,agentCapability:`${Ve}/agent/capability`,agentWorkspaceHealth:`${Ve}/agent/workspace-health`,agentJobs:`${Ve}/agent/jobs`});function nt(e,t){return`${Ze.agentJobs}/${encodeURIComponent(e)}/${t}`}var ho=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}),It=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Nt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),mo=Object.freeze(["ready","consent-required","blocked"]),bo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),Mt=Object.freeze(["added","modified","deleted"]),Dt=Object.freeze(["passed","failed","cancelled","timed-out"]);var $t="data-spotpatch-source",yo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function zt(e){if(e===null)return;let t=yo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),s=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)))return Object.freeze({fileId:o,line:n,column:s})}var jt="https://github.com/huanglvjing/spotpatch";function Xt(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function xo(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Xt(e.source)}})}function Eo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Ao(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 Co(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:Xt(e.source,e.code),react:xo(e.react),element:Eo(e.element),styles:Ao(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function Zt(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(Co)),createdAt:e.createdAt})}var Ro=new Set(Object.values(g)),vo=new Set(Nt),To=new Set(Dt),wo=new Set(Mt),en=new Set(It),Oo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,_o=/^[A-Za-z0-9_-]+$/,Po=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function ne(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function pt(e){return ne(e,64,1)&&typeof e=="string"&&Oo.test(e)}function Bt(e){return ne(e,128,22)&&typeof e=="string"&&_o.test(e)}function ut(e){return typeof e=="string"&&Po.test(e)&&Number.isFinite(Date.parse(e))}function Qe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function tn(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Qt(e,t){return e===void 0||ne(e,t)}function at(e){return typeof e=="string"&&Ro.has(e)}function nn(e){return!Be(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:pt(e.providerProfileId)&&ne(e.providerLabel,100)&&pt(e.modelProfileId)&&ne(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&vo.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||ut(e.checkedAt))&&(e.errorCode===void 0||at(e.errorCode))}function on(e){if(!Be(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ut(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!at(e.errorCode)||!Be(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:r,total:i}=t;return!Qe(o)||!Qe(n)||!Qe(s)||!Qe(r)||!Qe(i)||i<o||i<n||i<s||i<r||i>o+n+s?!1:e.state==="ready"?i===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?i>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function xt(e){return!Be(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Bt(e.jobId)&&typeof e.status=="string"&&en.has(e.status)&&pt(e.providerProfileId)&&ne(e.providerLabel,100)&&pt(e.modelProfileId)&&ne(e.modelLabel,100)&&ne(e.phaseMessage,1024)&&ut(e.createdAt)&&ut(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||at(e.errorCode))}function Lo(e){return Be(e)&&fe(e,["relativePath","kind","additions","deletions"])&&ne(e.relativePath,1024)&&typeof e.kind=="string"&&wo.has(e.kind)&&Qe(e.additions)&&Qe(e.deletions)}function rn(e){return Be(e)&&fe(e,["checkId","label","status","durationMs","output"])&&pt(e.checkId)&&ne(e.label,100)&&typeof e.status=="string"&&To.has(e.status)&&Qe(e.durationMs)&&ne(e.output,8e4)}function ko(e){return Be(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Bt(e.jobId)&&ne(e.summary,8e4)&&ne(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Lo)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(rn)}function an(e){return Be(e)&&fe(e,["snapshot","result"])&&xt(e.snapshot)&&(e.result===void 0||ko(e.result)&&e.result.jobId===e.snapshot.jobId)}function Io(e){return Be(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&tn(e.sequence)&&Bt(e.jobId)&&typeof e.status=="string"&&en.has(e.status)&&ut(e.timestamp)&&typeof e.type=="string"&&Be(e.data)}function sn(e){if(!Io(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&xt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&ne(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&tn(t.turn)&&ne(t.toolCallId,256)&&ne(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&Qt(t.relativePath,1024)&&Qt(t.checkLabel,100);case"check":return fe(t,["result"])&&rn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&at(t.code)&&ne(t.message,1024);default:return!1}}var No=2e6,cn=1e5,Mo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Do(e){if(!(!it(e)||e.ok!==!1||!it(e.error)))return at(e.error.code)?e.error.code:void 0}function $o(e){if(!it(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function zo(e){return it(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 ln(e){if(!(!it(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))ln(t);Object.freeze(e)}}function gt(e){return ln(e),e}async function jo(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),r=0,i="";try{for(;;){let l=await n.read();if(l.done)return i+=s.decode(),i;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new M;i+=s.decode(l.value,{stream:!0})}}catch(l){throw l instanceof M?l:new M}finally{n.releaseLock()}}function pn(e){try{return JSON.parse(e)}catch{throw new M}}async function dn(e){let t=pn(await jo(e,No));if(!e.ok)throw new M(Do(t));return $o(t)}function Bo(e,t){if(!nn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return gt(e)}function Et(e,t){if(!xt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return gt(e)}function Ho(e,t){if(!an(e)||e.snapshot.jobId!==t)throw new M;return gt(e)}function Uo(e){if(!sn(e))throw new M;return gt(e)}function Go(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 un(e){return e instanceof M?e.code:void 0}function gn(e){let t=new Set;function o(){for(let i of t)i.abort();t.clear()}async function n(i,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(i,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[yt]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await dn(R)}finally{t.delete(A)}}async function s(i,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(nt(i,"events"),{method:"POST",headers:{"Content-Type":"application/json",[yt]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await dn(A);return}if(A.body===null)throw new M;let R=A.body.getReader(),k=new TextDecoder("utf-8",{fatal:!0}),u="",P=0,Z=0,I=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>cn)throw new M;let x=Uo(pn(b));if(x.jobId!==i||x.sequence<=Z)throw new M;Z=x.sequence,l(x)};try{for(;;){let b=await R.read();if(b.done){u+=k.decode(),I(u);return}if(P+=b.value.byteLength,P>Mo)throw await R.cancel(),new M;u+=k.decode(b.value,{stream:!0});let x=u.split(`
2
+ `);if(u=x.pop()??"",new TextEncoder().encode(u).byteLength>cn)throw await R.cancel(),new M;for(let Q of x)I(Q)}}catch(b){throw b instanceof M||b instanceof DOMException&&b.name==="AbortError"?b:new M}finally{R.releaseLock()}}finally{t.delete(E)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(i){let l=await n(Ze.sourceContext,"POST",i);if(!zo(l))throw new M;return Object.freeze({...l})},async openEditor(i){let l=await n(Ze.openEditor,"POST",i);if(!it(l)||l.editor!=="auto"&&l.editor!=="vscode"&&l.editor!=="cursor")throw new M;return Object.freeze({editor:l.editor})},async agentCapability(i){return Bo(await n(Ze.agentCapability,"POST",i),i)},async agentWorkspaceHealth(){let i=await n(Ze.agentWorkspaceHealth,"POST",r);if(!on(i))throw new M;return gt(i)},async createAgentJob(i){let l=Go(i);return Et(await n(Ze.agentJobs,"POST",l),i)},agentEvents:s,async agentResult(i){return Ho(await n(nt(i,"result"),"POST",r),i)},async cancelAgentJob(i){return Et(await n(nt(i,"cancel"),"POST",r),{jobId:i})},async applyAgentJob(i){return Et(await n(nt(i,"apply"),"POST",r),{jobId:i})},async revertAgentJob(i){return Et(await n(nt(i,"revert"),"POST",r),{jobId:i})},dispose(){o()}})}var Vo=500,fn=256;function Wo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Jo(e){return bt(e)}function hn(e,t,o){if(!Jo(e))return e==="href"||e==="src"?Xe(t,o):e==="d"&&t.length>fn?`${t.slice(0,fn)}…`:Wo(H(t),Vo)}function Ee(e){return H(e)}var mn=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 ft=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 qo(e){return"selectorText"in e&&"style"in e}function Fo(e){return"cssRules"in e}function Ko(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 Yo(e,t,o,n,s){return e.join(" ").length+(t?.length??0)+o.reduce((r,i)=>r+i.selector.length+i.declarations.length+(i.source?.length??0)+(i.media?.length??0),0)+Object.entries(n).reduce((r,[i,l])=>r+i.length+l.length,0)+s.join(`
3
+ `).length}function Xo(e,t){return e.href===null?void 0:Xe(e.href,t)}function bn(e,t,o,n,s,r){for(let i of t){if(qo(i)){let l=!1;try{l=e.matches(i.selectorText)}catch{r.add(ft.selector);continue}l&&s.push(Object.freeze({selector:Ee(i.selectorText),declarations:Ee(i.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Fo(i)){let l=Ko(i);bn(e,i.cssRules,o,l===void 0?n:[...n,l],s,r)}}}function Zo(e,t){if(t===void 0)return{};let o=t(e),n={};for(let s of mn){let r=Ee(o.getPropertyValue(s).trim());r.length>0&&(n[s]=r)}return n}function yn(e){let t=new Set([ft.state,ft.cssInJs,ft.cascade]),o=[],n=e.readCssRules??(R=>R.cssRules);for(let R of e.document.styleSheets){let k;try{k=n(R)}catch{t.add(ft.inaccessibleStylesheet);continue}bn(e.element,k,Xo(R,e.document.baseURI),[],o,t)}let s=Array.from(e.element.classList),r=e.element.getAttribute("style"),i=r===null?void 0:Ee(r),l=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),E=Object.entries(Zo(e.element,l)),A=Array.from(t);for(;Yo(s,i,o,Object.fromEntries(E),A)>e.maxCharacters;){if(E.length>0){E.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(s),...i===void 0?{}:{inlineStyle:i},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(E)),warnings:Object.freeze(A)})}var et=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Qo=new Set(["alt","autocomplete","checked","class","colspan","contenteditable","d","disabled","download","draggable","for","height","hidden","href","id","max","maxlength","min","minlength","multiple","name","open","pattern","placeholder","readonly","rel","required","role","rowspan","selected","src","step","style","tabindex","target","title","type","width"]),er=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function xn(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function tr(e){return Qo.has(e)||e.startsWith("aria-")||e==="data-testid"}function En(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let s of e.attributes){let r=s.name.toLowerCase();if(!tr(r))continue;let i=hn(r,s.value,n);i!==void 0&&o.push(`${r}="${xn(i)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function An(e){return H(e).replaceAll(/\s+/gu," ").trim()}function Cn(e,t,o,n){if(o.nodeCount>=et.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let s=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${s}${En(e)}`),!er.has(r)){for(let i of e.childNodes){if(o.nodeCount>=et.maxNodes){o.truncated=!0;break}if(i.nodeType===3){let l=An(i.textContent??"");if(l.length>0){o.nodeCount+=1;let E=l.length<=et.maxTextCharacters?l:`${l.slice(0,et.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${xn(E)}`)}continue}if(i.nodeType===1){if(t>=et.maxDepth){o.truncated=!0;continue}Cn(i,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${s}</${r}>`)}}function nr(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<et.maxParentDepth;)t.push(En(o)),o=o.parentElement;return t}function or(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Sn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function rr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ar(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Sn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${rr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(l=>`.${Sn(l)}`).join(""),s=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(l=>l.tagName===e.tagName),r=s.indexOf(e),i=s.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${i}`}function ir(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=ar(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Rn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};Cn(e.element,0,o,t);let n=nr(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let s=An(e.element.textContent),r=e.element.getBoundingClientRect(),i=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:ir(e.element),sanitizedHtml:or(t.join(`
4
+ `),e.maxCharacters),...s.length===0?{}:{textPreview:s.length<=et.maxTextCharacters?s:`${s.slice(0,et.maxTextCharacters)}…`},...i===null?{}:{role:i},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function vn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function sr(e){return e.toLowerCase()}function Tn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function wn(e,t,o){let n=t.split("+").map(R=>R.trim().toLowerCase()).filter(R=>R.length>0),s=n.find(R=>R!=="mod"&&R!=="meta"&&R!=="ctrl"&&R!=="control"&&R!=="alt"&&R!=="option"&&R!=="shift");if(s===void 0||sr(e.key)!==s)return!1;let r=n.includes("mod"),i=n.includes("meta")||r&&vn(o),l=n.includes("ctrl")||n.includes("control")||r&&!vn(o),E=n.includes("alt")||n.includes("option"),A=n.includes("shift");return e.metaKey===i&&e.ctrlKey===l&&e.altKey===E&&e.shiftKey===A}function cr(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function dr(e){let t=e.filter(l=>l.width>0&&l.height>0),o=t[0];if(o===void 0)return;let n=o.left,s=o.top,r=o.right,i=o.bottom;for(let l of t.slice(1))n=Math.min(n,l.left),s=Math.min(s,l.top),r=Math.max(r,l.right),i=Math.max(i,l.bottom);return Object.freeze({x:n,y:s,width:r-n,height:i-s})}function Ht(e,t){if(t.getComputedStyle(e).display.startsWith("inline")){let n=dr(Array.from(e.getClientRects()));if(n!==void 0)return n}return cr(e.getBoundingClientRect())}var ot="data-spotpatch-ui",ht=Object.freeze({highlight:2147483646,controls:2147483647});function On(e){if(e.closest(`[${ot}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(ot)}function lr(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}function pr(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Ut(e,t,o,n){let s=e.elementsFromPoint(o,n).filter(r=>!On(r)&&lr(r,t));return s.find(r=>!pr(r))??s[0]}function _n(e){return e instanceof Element&&On(e)}var Gt=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 ur(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function At(e,t){let o="`".repeat(Math.max(3,ur(t)+1));return`${o}${e}
5
5
  ${t}
6
- ${o}`}function vn(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 Tn(e,t){return e.split(`
7
- `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function ar(e){let t=[e.source===void 0?void 0:`/* source: ${xe(e.source)} */`,e.media===void 0?void 0:`/* condition: ${xe(e.media)} */`].filter(n=>n!==void 0),o=`${xe(e.selector)} {
8
- ${xe(e.declarations)}
6
+ ${o}`}function Ln(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,s=e.source.column;return o===void 0?t.unavailable:`${H(o)}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function kn(e,t){return e.split(`
7
+ `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function gr(e){let t=[e.source===void 0?void 0:`/* source: ${Ee(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Ee(e.media)} */`].filter(n=>n!==void 0),o=`${Ee(e.selector)} {
8
+ ${Ee(e.declarations)}
9
9
  }`;return[...t,o].join(`
10
- `)}function ir(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(xe).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${xe(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(ar)];return i.length===0?o.unavailable:xt("css",i.join(`
10
+ `)}function fr(e,t,o){let s=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Ee).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Ee(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(gr)];return s.length===0?o.unavailable:At("css",s.join(`
11
11
 
12
- `))}function sr(e,t){return e.length===0?t.unavailable:xt("css",e.map(([o,n])=>`${xe(o)}: ${xe(n)};`).join(`
13
- `))}function cr(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${G(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${G(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(G).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
12
+ `))}function hr(e,t){return e.length===0?t.unavailable:At("css",e.map(([o,n])=>`${Ee(o)}: ${Ee(n)};`).join(`
13
+ `))}function mr(e,t,o,n){let s=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${H(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${H(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(H).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
14
14
 
15
- ${xt(e.code.language,G(t.codeLines.join(`
16
- `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,`#### ${n.reactContext}`,i.join(`
17
- `),`#### ${n.source}`,`- ${n.file}: ${vn(e,n)}
15
+ ${At(e.code.language,H(t.codeLines.join(`
16
+ `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${Xe(e.page.url,e.page.url)}>
17
+ - ${n.pathname}: ${H(e.page.pathname)}
18
+ - ${n.title}: ${H(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,s.join(`
19
+ `),`#### ${n.source}`,`- ${n.file}: ${Ln(e,n)}
18
20
  - ${n.origin}: ${e.source.origin}
19
- - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,xt("html",G(t.dom)),`#### ${n.styles}`,ir(e,t.matchedRules,n),`#### ${n.computedStyles}`,sr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${G(a)}`).join(`
21
+ - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,At("html",H(t.dom)),`#### ${n.styles}`,fr(e,t.matchedRules,n),`#### ${n.computedStyles}`,hr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(i=>`- ${H(i)}`).join(`
20
22
  `)].join(`
21
23
 
22
- `)}function Rn(e,t){let o=Ze(e.page.url,e.page.url),n=Ut[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
23
- - ${n.pathname}: ${G(e.page.pathname)}
24
+ `)}function Pn(e,t){let o=Xe(e.page.url,e.page.url),n=Gt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
25
+ - ${n.pathname}: ${H(e.page.pathname)}
24
26
  - ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
25
27
  - ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
26
- - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((i,r)=>{let a=t.targets[r];if(a===void 0)throw new RangeError("Prompt target draft is missing.");return cr(i,a,r,n)}).join(`
28
+ - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((s,r)=>{let i=t.targets[r];if(i===void 0)throw new RangeError("Prompt target draft is missing.");return mr(s,i,r,n)}).join(`
27
29
 
28
30
  `),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
29
31
 
30
- `)}function lr(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let a=t.codeLines[0]??"";return a.length<=120?t.codeLines=[]:t.codeLines=[`${a.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function dr(e){return{instruction:G(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function pr(e){return{pageTitle:G(e.page.title),targets:e.targets.map(dr)}}function ur(e,t,o){let n=Ut[e.locale],i=[(r,a)=>a.computedEntries.pop()!==void 0,(r,a)=>a.reactStack.pop()!==void 0,(r,a)=>{let c=Tn(a.dom,n.unavailable);return a.dom===c?!1:(a.dom=c,!0)},(r,a)=>a.matchedRules.shift()!==void 0,lr,(r,a)=>a.warnings.pop()!==void 0];for(let r of i)for(let a=0;a<e.targets.length;a+=1){let c=(o+a)%e.targets.length,S=e.targets[c],C=t.targets[c];if(S!==void 0&&C!==void 0&&r(S,C))return(c+1)%e.targets.length}}function gr(e,t){let o=Ut[e.locale],n=e.targets.map((i,r)=>{let a=t.targets[r],c=i.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${a?.instruction??G(i.instruction)}`,`- ${o.file}: ${vn(i,o)}`,...c===void 0?[]:[`- ${o.component}: ${G(c)}`],`- ${o.element}: ${G(Tn(a?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
32
+ `)}function br(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let i=t.codeLines[0]??"";return i.length<=120?t.codeLines=[]:t.codeLines=[`${i.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),s=e.code.startLine+t.codeLines.length-1;return Math.abs(s-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function yr(e){return{instruction:H(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function Sr(e){return{pageTitle:H(e.page.title),targets:e.targets.map(yr)}}function xr(e,t,o){let n=Gt[e.locale],s=[(r,i)=>i.computedEntries.pop()!==void 0,(r,i)=>i.reactStack.pop()!==void 0,(r,i)=>{let l=kn(i.dom,n.unavailable);return i.dom===l?!1:(i.dom=l,!0)},(r,i)=>i.matchedRules.shift()!==void 0,br,(r,i)=>i.warnings.pop()!==void 0];for(let r of s)for(let i=0;i<e.targets.length;i+=1){let l=(o+i)%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 Er(e,t){let o=Gt[e.locale],n=e.targets.map((s,r)=>{let i=t.targets[r],l=s.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${i?.instruction??H(s.instruction)}`,`- ${o.file}: ${Ln(s,o)}`,...l===void 0?[]:[`- ${o.component}: ${H(l)}`],`- ${o.element}: ${H(kn(i?.dom??s.element.sanitizedHtml,o.unavailable))}`].join(`
31
33
  `)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
32
34
 
33
35
  `),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
34
36
 
35
- `)}function fr(e,t){let o=pr(e),n=Rn(e,o),i=0;for(;n.length>t;){let a=ur(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=Rn(e,o)}if(n.length<=t)return n;let r=gr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function wn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return fr(t,e.maxCharacters)}})}var he=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Bt=he.idle;function hr(e){return e.type==="ACTIVATE"?he.inspecting:he.idle}function mr(e){switch(e.type){case"HOVER":return he.inspecting;case"SELECT":return he.selected;case"CANCEL":return he.idle;default:return he.inspecting}}function br(e){switch(e.type){case"RESELECT":return he.inspecting;case"CLOSE":return he.idle;case"PREVIEW":return he.previewing;case"OPEN_EDITOR":return he.selected;default:return he.selected}}function yr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return he.selected;case"COPY_FAILURE":return he.previewing;default:return he.previewing}}function On(e,t){switch(e.status){case"idle":return hr(t);case"inspecting":return mr(t);case"selected":return br(t);case"previewing":return yr(t)}}var Ln=Object.freeze({supported:!1,componentStack:Object.freeze([])});function _n(e){return Mt(e.getAttribute(Nt))}function xr(e){let t=e.parentElement;for(;t!==null;){let o=_n(t);if(o!==void 0)return o;t=t.parentElement}}function Pn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Sr(){return Object.freeze({origin:"none",confidence:"unknown"})}function kn(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function In(e){let t=!0;function o(n){if(!t)return Ln;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Ln}}return Object.freeze({resolve(n){let i=_n(n),r=o(n);if(i!==void 0)return Object.freeze({react:r,source:Pn(i,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let a=xr(n);return Object.freeze(a!==void 0?{react:r,source:Pn(a,"dom-ancestor","approximate")}:{react:r,source:Sr()})},dispose(){t=!1,e.adapter.dispose()}})}function l(e,t){let o=e.createElement(t);return o.setAttribute(et,""),o}function F(e,t,o=""){let n=l(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Mn=`
37
+ `)}function Ar(e,t){let o=Sr(e),n=Pn(e,o),s=0;for(;n.length>t;){let i=xr(e,o,s);if(i===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else s=i;n=Pn(e,o)}if(n.length<=t)return n;let r=Er(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function In(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 Ar(t,e.maxCharacters)}})}var ce=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Vt=ce.idle;function Cr(e){return e.type==="ACTIVATE"?ce.inspecting:e.type==="RESTORE"?ce.selected:ce.idle}function Rr(e){switch(e.type){case"HOVER":return ce.inspecting;case"SELECT":return ce.selected;case"CANCEL":return ce.idle;default:return ce.inspecting}}function vr(e){switch(e.type){case"RESELECT":return ce.inspecting;case"CLOSE":return ce.idle;case"PREVIEW":return ce.previewing;case"OPEN_EDITOR":return ce.selected;default:return ce.selected}}function Tr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return ce.selected;case"COPY_FAILURE":return ce.previewing;default:return ce.previewing}}function Nn(e,t){switch(e.status){case"idle":return Cr(t);case"inspecting":return Rr(t);case"selected":return vr(t);case"previewing":return Tr(t)}}var wr="spotpatch:selection:";function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function X(e){return typeof e=="string"}function Je(e){return e===void 0||X(e)}function Wt(e){return Array.isArray(e)&&e.length<=256&&e.every(X)}function He(e){return typeof e=="number"&&Number.isFinite(e)}function Mn(e){return e===void 0||He(e)}function Dn(e){let t=Ne(e);return t!==void 0&&X(t.origin)&&X(t.confidence)&&Je(t.fileId)&&Je(t.relativePath)&&Mn(t.line)&&Mn(t.column)}function Or(e){let t=Ne(e);return t!==void 0&&typeof t.supported=="boolean"&&Je(t.version)&&Je(t.componentName)&&Wt(t.componentStack)&&(t.source===void 0||Dn(t.source))}function _r(e){let t=Ne(e);return t!==void 0&&X(t.url)&&X(t.pathname)&&X(t.title)&&He(t.viewportWidth)&&He(t.viewportHeight)&&He(t.devicePixelRatio)}function Pr(e){let t=Ne(e),o=Ne(t?.rect);return t!==void 0&&X(t.tagName)&&X(t.selector)&&X(t.sanitizedHtml)&&Je(t.textPreview)&&Je(t.role)&&o!==void 0&&He(o.x)&&He(o.y)&&He(o.width)&&He(o.height)}function Lr(e){let t=Ne(e),o=Ne(t?.computed);return t!==void 0&&Wt(t.classNames)&&Je(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let s=Ne(n);return s!==void 0&&X(s.selector)&&X(s.declarations)&&Je(s.source)&&Je(s.media)})&&o!==void 0&&Object.values(o).every(X)&&Wt(t.warnings)}function kr(e){let t=Ne(e);return t!==void 0&&X(t.relativePath)&&X(t.language)&&He(t.startLine)&&He(t.endLine)&&X(t.excerpt)&&X(t.boundary)}function Ir(e){let t=Ne(e);return t!==void 0&&X(t.id)&&X(t.instruction)&&_r(t.page)&&Dn(t.source)&&Or(t.react)&&Pr(t.element)&&Lr(t.styles)&&(t.code===void 0||kr(t.code))}function Nr(e,t){let o=Ne(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(Ir))return;let n=o.targets,s=n.map(({id:r})=>r);if(!(new Set(s).size!==s.length||o.activeTargetId!==void 0&&!s.includes(o.activeTargetId)))return{...o.activeTargetId===void 0?{}:{activeTargetId:o.activeTargetId},open:o.open,sequence:Number(o.sequence),targets:n}}function $n(e,t,o){let n=`${wr}${t}`,s;try{s=e.sessionStorage}catch{s=void 0}return Object.freeze({clear(){try{s?.removeItem(n)}catch{}},load(){let r;try{r=s?.getItem(n)??null}catch{return}if(!(r===null||r.length>1e6))try{return Nr(JSON.parse(r),o)}catch{return}},save(r){try{s?.setItem(n,JSON.stringify({version:1,...r}))}catch{}}})}var zn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Bn(e){return zt(e.getAttribute($t))}function Mr(e){let t=e.parentElement;for(;t!==null;){let o=Bn(t);if(o!==void 0)return o;t=t.parentElement}}function jn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Dr(){return Object.freeze({origin:"none",confidence:"unknown"})}function Jt(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 Hn(e){let t=!0;function o(n){if(!t)return zn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),zn}}return Object.freeze({resolve(n){let s=Bn(n),r=o(n);if(s!==void 0)return Object.freeze({react:r,source:jn(s,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let i=Mr(n);return Object.freeze(i!==void 0?{react:r,source:jn(i,"dom-ancestor","approximate")}:{react:r,source:Dr()})},dispose(){t=!1,e.adapter.dispose()}})}function d(e,t){let o=e.createElement(t);return o.setAttribute(ot,""),o}function J(e,t,o=""){let n=d(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Gn=`
36
38
  .spotpatch-agent {
37
39
  margin-top: 14px;
38
40
  overflow: hidden;
@@ -237,7 +239,7 @@ ${xt(e.code.language,G(t.codeLines.join(`
237
239
  white-space: pre;
238
240
  user-select: text;
239
241
  }
240
- `;function Nn(e,t,o,n){let i=e.createElement("option");i.value=o,i.textContent=n,t.append(i)}function Dn(e,t,o){let n=o.messages(),i=l(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=l(e,"div");r.className="spotpatch-agent-head";let a=l(e,"span");a.className="spotpatch-agent-title";let c=l(e,"span");c.className="spotpatch-agent-badge",r.append(a,c);let S=l(e,"div");S.className="spotpatch-agent-setup";let C=l(e,"div");C.className="spotpatch-agent-selectors";let u=l(e,"label"),_=l(e,"span"),b=l(e,"select");u.append(_,b);let N=l(e,"label"),A=l(e,"span"),R=l(e,"select");N.append(A,R),C.append(u,N);let D=l(e,"label");D.className="spotpatch-consent";let L=l(e,"input");L.type="checkbox";let Z=l(e,"span");D.append(L,Z);let B=l(e,"label");B.className="spotpatch-consent spotpatch-workspace-consent",B.hidden=!0;let f=l(e,"input");f.type="checkbox";let y=l(e,"span"),E=l(e,"strong"),P=l(e,"small");y.append(E,P),B.append(f,y);let U=l(e,"div");U.className="spotpatch-agent-health-list";let W=l(e,"p");W.className="spotpatch-agent-workspace",W.dataset.state="idle";let T=l(e,"p");T.className="spotpatch-agent-capability",T.dataset.state="idle",U.append(W,T),S.append(C,D,B,U);let Se=l(e,"div");Se.className="spotpatch-agent-job",Se.hidden=!0;let me=l(e,"div");me.className="spotpatch-agent-job-meta";let H=l(e,"span");H.className="spotpatch-agent-model";let je=l(e,"span");je.className="spotpatch-agent-status",me.append(H,je);let Le=l(e,"p");Le.className="spotpatch-agent-phase";let z=l(e,"p");z.className="spotpatch-agent-error",z.hidden=!0;let Ee=l(e,"ul");Ee.className="spotpatch-agent-activity";let Ne=l(e,"div");Ne.className="spotpatch-agent-result",Ne.hidden=!0;let Ue=l(e,"p");Ue.className="spotpatch-agent-summary";let oe=l(e,"ul");oe.className="spotpatch-agent-files";let Q=l(e,"div");Q.className="spotpatch-agent-checks";let K=l(e,"pre");K.className="spotpatch-agent-diff",K.tabIndex=0,K.setAttribute("aria-label",n.agent.diffAriaLabel),Ne.append(Ue,oe,Q,K),Se.append(me,Le,z,Ee,Ne),i.append(r,S,Se);let ee=F(e,n.agent.testConnection),re=F(e,n.agent.verifyAndRun,"spotpatch-run"),Pe=F(e,n.agent.cancel),_e=F(e,n.agent.apply,"spotpatch-primary"),be=F(e,n.agent.revert),k=F(e,n.agent.revise),O=t.enabled?t.providers:[],Be=new Map(O.map(g=>[g.id,g])),Ae=!1,He=!0,Y=!1,X=!1,Ce=!1,ae=!1,te,le,ke=[],Re,ie="idle",Te=n.agent.connectionNotTested,ve,se="idle",Me,De;for(let g of O)Nn(e,b,g.id,g.label);t.enabled&&(b.value=t.defaultProvider);let ye=()=>Be.get(b.value),de=()=>{let g=ye();if(R.replaceChildren(),g===void 0){Z.textContent=n.agent.providerUnavailable;return}for(let w of g.models)Nn(e,R,w.id,w.label);R.value=g.defaultModel,Z.textContent=n.agent.consent(g.label)},V=()=>{let g=t.enabled&&Y&&!X;re.textContent=Ce?n.agent.verifying:ae?n.agent.run:n.agent.verifyAndRun,re.classList.toggle("spotpatch-primary",ae),ee.hidden=!g,re.hidden=!g,ee.disabled=!He||Ce||ye()===void 0,re.disabled=!He||Ce||!Ae||!L.checked||se==="idle"||se==="checking"||se==="blocked"||se==="consent-required"&&!f.checked||ye()===void 0||R.value.length===0,(!X||!Y)&&(Pe.hidden=!0,_e.hidden=!0,be.hidden=!0,k.hidden=!0)},Ye=()=>{if(se==="idle")W.textContent=n.agent.workspaceNotChecked;else if(se==="checking")W.textContent=n.agent.checkingWorkspace;else if(se==="ready")W.textContent=n.agent.workspaceReady;else if(se==="consent-required"){let g=Me?.changes;W.textContent=n.agent.workspaceDirty(g?.staged??0,g?.unstaged??0,g?.untracked??0)}else W.textContent=De===void 0?n.errors.INTERNAL_ERROR:n.errors[De]};function s(){de(),L.checked=!1,T.dataset.state="idle",T.textContent=n.agent.connectionNotTested,ie="idle",Te=n.agent.connectionNotTested,ve=void 0,ae=!1,V()}function p(){T.dataset.state="idle",T.textContent=n.agent.connectionNotTested,ie="idle",Te=n.agent.connectionNotTested,ve=void 0,ae=!1,V()}de(),b.addEventListener("change",s),R.addEventListener("change",p),L.addEventListener("change",V),f.addEventListener("change",V);function x(){if(te===void 0)return;let g=te,w=le;H.textContent=`${g.providerLabel} · ${g.modelLabel}`,je.textContent=n.agent.status(g.status),Le.textContent=g.phaseMessage;let pe=Re??g.errorCode;z.hidden=pe===void 0,z.textContent=pe===void 0?"":n.errors[pe],Ee.replaceChildren();for(let J of ke.slice(-8)){let we=l(e,"li");we.dataset.state=J.state,we.textContent=J.label,Ee.append(we)}Ne.hidden=w===void 0,Ue.textContent=w?.summary??"",oe.replaceChildren(),Q.replaceChildren(),K.textContent=w?.diff??"";for(let J of w?.files??[]){let we=l(e,"li");we.textContent=`${J.kind} ${J.relativePath} (+${String(J.additions)} / -${String(J.deletions)})`,oe.append(we)}for(let J of w?.checks??[]){let we=l(e,"details"),ot=l(e,"summary");ot.textContent=`${J.label}: ${J.status} · ${String(J.durationMs)} ms`;let ut=l(e,"pre");ut.textContent=J.output.length===0?n.agent.noOutput:J.output,we.append(ot,ut),Q.append(we)}ee.hidden=!0,re.hidden=!0,Pe.hidden=!Y||!g.canCancel,Pe.textContent=g.status==="awaiting-review"?n.agent.discard:n.agent.cancel,_e.hidden=!Y||!g.canApply,be.hidden=!Y||!g.canRevert,k.hidden=!Y||!["completed","cancelled","reverted","failed"].includes(g.status)}function I(){n=o.messages(),a.textContent=n.agent.title,c.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,_.textContent=n.agent.provider,A.textContent=n.agent.model,b.setAttribute("aria-label",n.agent.providerAriaLabel),R.setAttribute("aria-label",n.agent.modelAriaLabel),E.textContent=n.agent.includeLocalChanges,P.textContent=n.agent.includeLocalChangesHelp,K.setAttribute("aria-label",n.agent.diffAriaLabel),ee.textContent=n.agent.testConnection,_e.textContent=n.agent.apply,be.textContent=n.agent.revert,k.textContent=n.agent.revise;let g=ye();Z.textContent=g===void 0?n.agent.providerUnavailable:n.agent.consent(g.label),ie==="idle"?T.textContent=n.agent.connectionNotTested:ie==="probing"?T.textContent=n.agent.testingCapability:ie==="ready"?T.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ve!==void 0?T.textContent=n.errors[ve]:ye()===void 0?T.textContent=n.agent.providerUnavailable:T.textContent=Te,Ye(),V(),x()}let $=o.subscribe(I);return I(),Object.freeze({root:i,providerSelect:b,modelSelect:R,consentCheckbox:L,workspaceConsentCheckbox:f,testButton:ee,runButton:re,cancelButton:Pe,applyButton:_e,revertButton:be,resetButton:k,consentGranted(){return L.checked},workspaceConsentGranted(){return f.checked},readSelection(){let g=ye(),w=g?.models.find(pe=>pe.id===R.value);return g===void 0||w===void 0?void 0:Object.freeze({providerProfileId:g.id,modelProfileId:w.id})},renderCapability(g,w,pe,J){ie=g,Te=w,ve=J,Ce=g==="probing",ae=g==="ready"&&pe?.state==="agent-ready",T.dataset.state=g,T.textContent=pe?.state==="agent-ready"?`${w} · ${n.agent.toolsReady}`:w,V()},renderWorkspaceHealth(g,w,pe){se=g,Me=w,De=pe??w?.errorCode,W.dataset.state=g,g!=="checking"&&(B.hidden=g!=="consent-required"),(g==="idle"||g==="ready"||g==="blocked")&&(f.checked=!1),Ye(),V()},renderJob(g,w,pe,J){X=!0,S.hidden=!0,Se.hidden=!1,b.disabled=!0,R.disabled=!0,L.disabled=!0,f.disabled=!0,te=g,le=w,ke=pe,Re=J,x()},resetJob(){X=!1,te=void 0,le=void 0,ke=[],Re=void 0,S.hidden=!1,Se.hidden=!0,b.disabled=!1,R.disabled=!1,L.disabled=!1,f.disabled=!1,Ee.replaceChildren(),oe.replaceChildren(),Q.replaceChildren(),K.textContent="",z.textContent="",z.hidden=!0,V()},setContextReady(g){Ae=g,V()},setEditingEnabled(g){He=g,b.disabled=!g||X,R.disabled=!g||X,L.disabled=!g||X,f.disabled=!g||X,V()},setProviderConsent(g){L.checked=g,V()},setSelectionVisible(g){Y=g,V(),g||(Pe.hidden=!0,_e.hidden=!0,be.hidden=!0,k.hidden=!0)},dispose(){$(),b.removeEventListener("change",s),R.removeEventListener("change",p),L.removeEventListener("change",V),f.removeEventListener("change",V)}})}var Er="http://www.w3.org/2000/svg";function Ie(e,t,o){let n=e.createElementNS(Er,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function $n(e){let t=Ie(e,"svg",{class:"spotpatch-brand-mark",viewBox:"0 0 210 208","aria-hidden":"true",focusable:"false"}),o=Ie(e,"defs",{}),n=Ie(e,"linearGradient",{id:"spotpatch-brand-gradient",x1:"35",y1:"42",x2:"184",y2:"176",gradientUnits:"userSpaceOnUse"});n.append(Ie(e,"stop",{offset:"0","stop-color":"#7c22ff"}),Ie(e,"stop",{offset:".52","stop-color":"#4a69ff"}),Ie(e,"stop",{offset:"1","stop-color":"#06d9ef"})),o.append(n);let i={fill:"none",stroke:"url(#spotpatch-brand-gradient)","stroke-linecap":"square","stroke-linejoin":"miter"},r=Ie(e,"path",{d:"M106 42C67 42 43 68 43 105c0 36 24 61 63 96 39-35 63-60 63-96 0-37-24-63-63-63Z",...i,"stroke-width":"14"}),a=Ie(e,"path",{d:"M106 25v42",...i,"stroke-width":"14"}),c=Ie(e,"path",{d:"M35 109h20m102 0h38",...i,"stroke-width":"13"}),S=Ie(e,"path",{d:"m94 89-18 19 18 17m39-36 18 19-18 17",...i,"stroke-width":"9"}),C=Ie(e,"path",{d:"m119 61-20 45 15 11-13 47 30-56-16-12 4-35Z",fill:"url(#spotpatch-brand-gradient)"});return t.append(o,r,a,c,S,C),t}function St(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function zn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,c=o.x+o.width/2,S=o.y+o.height/2,C=St(c-t/2,16,r),u=St(S-e/2,16,a),_=C,b=u,N="viewport";return o.width>=t+48&&o.height>=e+48?N="center":o.y-e-14>=16?(b=o.y-e-14,N="above"):o.y+o.height+14+e<=n-16?(b=o.y+o.height+14,N="below"):o.x+o.width+14+t<=i-16?(_=o.x+o.width+14,N="right"):o.x-t-14>=16&&(_=o.x-t-14,N="left"),Object.freeze({anchorX:St(c-_,22,t-22),anchorY:St(S-b,22,e-22),left:_,mode:N,top:b})}var Ar=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Cr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Rr=Object.freeze({[h.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[h.INVALID_TOKEN]:"The local SpotPatch session expired.",[h.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[h.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[h.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[h.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[h.EDITOR_OPEN_FAILED]:"The editor request failed.",[h.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[h.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[h.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[h.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[h.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[h.AGENT_BUSY]:"Another write Agent job is still active.",[h.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[h.AGENT_CANCELLED]:"The Agent job was cancelled.",[h.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[h.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[h.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[h.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[h.TOOL_DENIED]:"A 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."}),vr=Object.freeze({[h.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[h.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[h.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[h.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[h.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[h.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[h.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[h.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[h.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[h.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[h.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[h.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[h.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[h.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[h.AGENT_CANCELLED]:"Agent 任务已取消。",[h.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[h.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[h.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[h.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[h.TOOL_DENIED]:"工具请求违反本地安全策略。",[h.TOOL_INPUT_INVALID]:"工具请求无效。",[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 失败,未暴露私有细节。"}),Tr=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),wr=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),Or=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Tr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Connection not tested",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifyAndRun:"Verify & run",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Ar[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetRemoved:"A removed page element was dropped from the selection.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Rr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:wr,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未测试连接",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifyAndRun:"验证并运行",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Cr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetRemoved:"页面中的目标已卸载,已从当前选择中移除。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:vr})});function jn(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 Lr(e,t){if(e!=="auto")return e;let o=jn(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(jn).find(i=>i!==void 0)??"en-US"}function Un(e,t="auto"){let o=Lr(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Or[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var Pr=560,_r=Object.freeze({previewing:640,selected:720});function kr(e){let t=e.createElement("style");return t.textContent=`
242
+ `;function Un(e,t,o,n){let s=e.createElement("option");s.value=o,s.textContent=n,t.append(s)}function Vn(e,t,o){let n=o.messages(),s=d(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let i=d(e,"span");i.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(i,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"),k=d(e,"span"),u=d(e,"select");R.append(k,u);let P=d(e,"label"),Z=d(e,"span"),I=d(e,"select");P.append(Z,I),A.append(R,P);let b=d(e,"label");b.className="spotpatch-consent";let x=d(e,"input");x.type="checkbox";let Q=d(e,"span");b.append(x,Q);let q=d(e,"label");q.className="spotpatch-consent spotpatch-workspace-consent",q.hidden=!0;let f=d(e,"input");f.type="checkbox";let y=d(e,"span"),C=d(e,"strong"),v=d(e,"small");y.append(C,v),q.append(f,y);let D=d(e,"div");D.className="spotpatch-agent-health-list";let G=d(e,"p");G.className="spotpatch-agent-workspace",G.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",D.append(G,$),E.append(A,b,q,D);let de=d(e,"div");de.className="spotpatch-agent-job",de.hidden=!0;let oe=d(e,"div");oe.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let L=d(e,"span");L.className="spotpatch-agent-status",oe.append(B,L);let Pe=d(e,"p");Pe.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let F=d(e,"ul");F.className="spotpatch-agent-activity";let Ce=d(e,"div");Ce.className="spotpatch-agent-result",Ce.hidden=!0;let Re=d(e,"p");Re.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let ee=d(e,"div");ee.className="spotpatch-agent-checks";let N=d(e,"pre");N.className="spotpatch-agent-diff",N.tabIndex=0,N.setAttribute("aria-label",n.agent.diffAriaLabel),Ce.append(Re,me,ee,N),de.append(oe,Pe,he,F,Ce),s.append(r,E,de);let K=J(e,n.agent.testConnection),be=J(e,n.agent.verifyAndRun,"spotpatch-run"),Le=J(e,n.agent.cancel),ve=J(e,n.agent.apply,"spotpatch-primary"),ye=J(e,n.agent.revert),re=J(e,n.agent.revise),_=t.enabled?t.providers:[],ke=new Map(_.map(m=>[m.id,m])),Se=!1,Me=!0,Y=!1,T=!1,Te=!1,le=!1,ae,De,$e=[],Ae,ie="idle",we=n.agent.connectionNotTested,Oe,V="idle",ze,Ie;for(let m of _)Un(e,u,m.id,m.label);t.enabled&&(u.value=t.defaultProvider);let xe=()=>ke.get(u.value),pe=()=>{let m=xe();if(I.replaceChildren(),m===void 0){Q.textContent=n.agent.providerUnavailable;return}for(let a of m.models)Un(e,I,a.id,a.label);I.value=m.defaultModel,Q.textContent=n.agent.consent(m.label)},U=()=>{let m=t.enabled&&Y&&!T;be.textContent=Te?n.agent.verifying:le?n.agent.run:n.agent.verifyAndRun,be.classList.toggle("spotpatch-primary",le),K.hidden=!m,be.hidden=!m,K.disabled=!Me||Te||xe()===void 0,be.disabled=!Me||Te||!Se||!x.checked||V==="idle"||V==="checking"||V==="blocked"||V==="consent-required"&&!f.checked||xe()===void 0||I.value.length===0,(!T||!Y)&&(Le.hidden=!0,ve.hidden=!0,ye.hidden=!0,re.hidden=!0)},qe=()=>{if(V==="idle")G.textContent=n.agent.workspaceNotChecked;else if(V==="checking")G.textContent=n.agent.checkingWorkspace;else if(V==="ready")G.textContent=n.agent.workspaceReady;else if(V==="consent-required"){let m=ze?.changes;G.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else G.textContent=Ie===void 0?n.errors.INTERNAL_ERROR:n.errors[Ie]};function Ue(){pe(),x.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,ie="idle",we=n.agent.connectionNotTested,Oe=void 0,le=!1,U()}function rt(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,ie="idle",we=n.agent.connectionNotTested,Oe=void 0,le=!1,U()}pe(),u.addEventListener("change",Ue),I.addEventListener("change",rt),x.addEventListener("change",U),f.addEventListener("change",U);function Fe(){if(ae===void 0)return;let m=ae,a=De;B.textContent=`${m.providerLabel} · ${m.modelLabel}`,L.textContent=n.agent.status(m.status),Pe.textContent=m.phaseMessage;let c=Ae??m.errorCode;he.hidden=c===void 0,he.textContent=c===void 0?"":n.errors[c],F.replaceChildren();for(let h of $e.slice(-8)){let w=d(e,"li");w.dataset.state=h.state,w.textContent=h.label,F.append(w)}Ce.hidden=a===void 0,Re.textContent=a?.summary??"",me.replaceChildren(),ee.replaceChildren(),N.textContent=a?.diff??"";for(let h of a?.files??[]){let w=d(e,"li");w.textContent=`${h.kind} ${h.relativePath} (+${String(h.additions)} / -${String(h.deletions)})`,me.append(w)}for(let h of a?.checks??[]){let w=d(e,"details"),z=d(e,"summary");z.textContent=`${h.label}: ${h.status} · ${String(h.durationMs)} ms`;let te=d(e,"pre");te.textContent=h.output.length===0?n.agent.noOutput:h.output,w.append(z,te),ee.append(w)}K.hidden=!0,be.hidden=!0,Le.hidden=!Y||!m.canCancel,Le.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ve.hidden=!Y||!m.canApply,ye.hidden=!Y||!m.canRevert,re.hidden=!Y||!["completed","cancelled","reverted","failed"].includes(m.status)}function Ke(){n=o.messages(),i.textContent=n.agent.title,l.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,k.textContent=n.agent.provider,Z.textContent=n.agent.model,u.setAttribute("aria-label",n.agent.providerAriaLabel),I.setAttribute("aria-label",n.agent.modelAriaLabel),C.textContent=n.agent.includeLocalChanges,v.textContent=n.agent.includeLocalChangesHelp,N.setAttribute("aria-label",n.agent.diffAriaLabel),K.textContent=n.agent.testConnection,ve.textContent=n.agent.apply,ye.textContent=n.agent.revert,re.textContent=n.agent.revise;let m=xe();Q.textContent=m===void 0?n.agent.providerUnavailable:n.agent.consent(m.label),ie==="idle"?$.textContent=n.agent.connectionNotTested:ie==="probing"?$.textContent=n.agent.testingCapability:ie==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Oe!==void 0?$.textContent=n.errors[Oe]:xe()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=we,qe(),U(),Fe()}let st=o.subscribe(Ke);return Ke(),Object.freeze({root:s,providerSelect:u,modelSelect:I,consentCheckbox:x,workspaceConsentCheckbox:f,testButton:K,runButton:be,cancelButton:Le,applyButton:ve,revertButton:ye,resetButton:re,consentGranted(){return x.checked},workspaceConsentGranted(){return f.checked},readSelection(){let m=xe(),a=m?.models.find(c=>c.id===I.value);return m===void 0||a===void 0?void 0:Object.freeze({providerProfileId:m.id,modelProfileId:a.id})},renderCapability(m,a,c,h){ie=m,we=a,Oe=h,Te=m==="probing",le=m==="ready"&&c?.state==="agent-ready",$.dataset.state=m,$.textContent=c?.state==="agent-ready"?`${a} · ${n.agent.toolsReady}`:a,U()},renderWorkspaceHealth(m,a,c){V=m,ze=a,Ie=c??a?.errorCode,G.dataset.state=m,m!=="checking"&&(q.hidden=m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(f.checked=!1),qe(),U()},renderJob(m,a,c,h){T=!0,E.hidden=!0,de.hidden=!1,u.disabled=!0,I.disabled=!0,x.disabled=!0,f.disabled=!0,ae=m,De=a,$e=c,Ae=h,Fe()},resetJob(){T=!1,ae=void 0,De=void 0,$e=[],Ae=void 0,E.hidden=!1,de.hidden=!0,u.disabled=!1,I.disabled=!1,x.disabled=!1,f.disabled=!1,F.replaceChildren(),me.replaceChildren(),ee.replaceChildren(),N.textContent="",he.textContent="",he.hidden=!0,U()},setContextReady(m){Se=m,U()},setEditingEnabled(m){Me=m,u.disabled=!m||T,I.disabled=!m||T,x.disabled=!m||T,f.disabled=!m||T,U()},setProviderConsent(m){x.checked=m,U()},setSelectionVisible(m){Y=m,U(),m||(Le.hidden=!0,ve.hidden=!0,ye.hidden=!0,re.hidden=!0)},dispose(){st(),u.removeEventListener("change",Ue),I.removeEventListener("change",rt),x.removeEventListener("change",U),f.removeEventListener("change",U)}})}var Wn="http://www.w3.org/2000/svg",$r="";function zr(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:$r,viewBox:"0 0 1 1"}}function jr(e,t,o){let n=e.createElementNS(Wn,t);for(let[s,r]of Object.entries(o))n.setAttribute(s,r);return n}function Jn(e,t){let o=zr(t),n=jr(e,"svg",{xmlns:Wn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function Ct(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:s}){let r=s-t-16,i=n-e-16,l=o.x+o.width/2,E=o.y+o.height/2,A=Ct(l-t/2,16,r),R=Ct(E-e/2,16,i),k=A,u=R,P="viewport";return o.width>=t+48&&o.height>=e+48?P="center":o.y-e-14>=16?(u=o.y-e-14,P="above"):o.y+o.height+14+e<=n-16?(u=o.y+o.height+14,P="below"):o.x+o.width+14+t<=s-16?(k=o.x+o.width+14,P="right"):o.x-t-14>=16&&(k=o.x-t-14,P="left"),Object.freeze({anchorX:Ct(l-k,22,t-22),anchorY:Ct(E-u,22,e-22),left:k,mode:P,top:u})}var Br=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"}),Hr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ur=Object.freeze({[g.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[g.INVALID_TOKEN]:"The local SpotPatch session expired.",[g.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[g.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[g.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[g.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[g.EDITOR_OPEN_FAILED]:"The editor request failed.",[g.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[g.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[g.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[g.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[g.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[g.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[g.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[g.AGENT_BUSY]:"Another write Agent job is still active.",[g.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[g.AGENT_CANCELLED]:"The Agent job was cancelled.",[g.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[g.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[g.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[g.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[g.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[g.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[g.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[g.TOOL_DENIED]:"A tool request violated local safety policy.",[g.TOOL_INPUT_INVALID]:"Invalid tool request.",[g.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[g.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[g.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[g.PATCH_REJECTED]:"The patch violated local policy.",[g.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[g.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[g.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Gr=Object.freeze({[g.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[g.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[g.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[g.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[g.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[g.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[g.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[g.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[g.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[g.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[g.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[g.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[g.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[g.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[g.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[g.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[g.AGENT_CANCELLED]:"Agent 任务已取消。",[g.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[g.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[g.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[g.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[g.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[g.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[g.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[g.TOOL_DENIED]:"工具请求违反本地安全策略。",[g.TOOL_INPUT_INVALID]:"工具请求无效。",[g.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[g.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[g.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[g.PATCH_REJECTED]:"补丁违反本地策略。",[g.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[g.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[g.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Vr=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),Wr=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),Jr=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Vr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Connection not tested",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifyAndRun:"Verify & run",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Br[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:Ur}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:Wr,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未测试连接",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifyAndRun:"验证并运行",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Hr[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:Gr})});function Fn(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 qr(e,t){if(e!=="auto")return e;let o=Fn(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(Fn).find(s=>s!==void 0)??"en-US"}function Kn(e,t="auto"){let o=qr(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Jr[o],subscribe(s){return n.add(s),()=>{n.delete(s)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let s of n)s()}})}var Fr=560,Kr=Object.freeze({previewing:640,selected:720});function Yr(e){let t=e.createElement("style");return t.textContent=`
241
243
  :host {
242
244
  all: initial;
243
245
  --spotpatch-bg: #11141a;
@@ -272,7 +274,7 @@ ${xt(e.code.language,G(t.codeLines.join(`
272
274
  position: fixed;
273
275
  right: 24px;
274
276
  bottom: 24px;
275
- z-index: ${String(pt.controls)};
277
+ z-index: ${String(ht.controls)};
276
278
  display: inline-flex;
277
279
  align-items: center;
278
280
  gap: 10px;
@@ -306,7 +308,7 @@ ${xt(e.code.language,G(t.codeLines.join(`
306
308
  position: fixed;
307
309
  top: 0;
308
310
  left: 0;
309
- z-index: ${String(pt.highlight)};
311
+ z-index: ${String(ht.highlight)};
310
312
  box-sizing: border-box;
311
313
  border: 2px solid var(--spotpatch-accent);
312
314
  border-radius: 6px;
@@ -333,7 +335,7 @@ ${xt(e.code.language,G(t.codeLines.join(`
333
335
  .spotpatch-selection-highlights {
334
336
  position: fixed;
335
337
  inset: 0;
336
- z-index: ${String(pt.highlight)};
338
+ z-index: ${String(ht.highlight)};
337
339
  pointer-events: none;
338
340
  }
339
341
  .spotpatch-selection-highlight {
@@ -374,7 +376,7 @@ ${xt(e.code.language,G(t.codeLines.join(`
374
376
  position: fixed;
375
377
  top: 16px;
376
378
  left: 16px;
377
- z-index: ${String(pt.controls)};
379
+ z-index: ${String(ht.controls)};
378
380
  box-sizing: border-box;
379
381
  width: min(560px, calc(100vw - 32px));
380
382
  color: #edf0f7;
@@ -875,10 +877,10 @@ ${xt(e.code.language,G(t.codeLines.join(`
875
877
  .spotpatch-target-select { grid-template-columns: 32px minmax(0, 1fr); }
876
878
  .spotpatch-target-state { display: none; }
877
879
  }
878
- ${Mn}
879
- `,t}function Ir(e,t){return e.split(`
880
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Bn(e,t,o=Object.freeze({enabled:!1}),n="auto"){let i=Un(e,n),r=i.messages(),a=e.createElement("spotpatch-root");a.setAttribute(et,"");let c=a.attachShadow({mode:"open"}),S=F(e,r.trigger.select,"spotpatch-trigger");S.title=r.trigger.title(t),S.setAttribute("aria-pressed","false");let C=l(e,"div");C.className="spotpatch-highlight",C.hidden=!0;let u=l(e,"span");u.className="spotpatch-highlight-label",C.append(u);let _=l(e,"div");_.className="spotpatch-selection-highlights",_.setAttribute("aria-hidden","true");let b=l(e,"section");b.className="spotpatch-dialog",b.hidden=!0,b.tabIndex=-1,b.dataset.placement="viewport",b.setAttribute("role","dialog"),b.setAttribute("aria-labelledby","spotpatch-selection-title");let N=l(e,"span");N.className="spotpatch-anchor",N.setAttribute("aria-hidden","true");let A=l(e,"div");A.className="spotpatch-shell";let R=l(e,"header");R.className="spotpatch-header";let D=l(e,"div");D.className="spotpatch-brand-row";let L=l(e,"div");L.className="spotpatch-brand";let Z=l(e,"span");Z.className="spotpatch-brand-copy";let B=l(e,"span");B.className="spotpatch-brand-name";let f=l(e,"span");f.className="spotpatch-brand-context",Z.append(B,f),L.append($n(e),Z);let y=l(e,"span");y.className="spotpatch-header-controls";let E=l(e,"a");E.className="spotpatch-repository",E.href=Dt,E.target="_blank",E.rel="noopener noreferrer";let P=F(e,"","spotpatch-locale"),U=F(e,"×","spotpatch-close");y.append(E,P,U),D.append(L,y);let W=l(e,"h2");W.id="spotpatch-selection-title",W.className="spotpatch-title";let T=l(e,"p");T.className="spotpatch-subtitle";let Se=l(e,"div");Se.className="spotpatch-target-row";let me=l(e,"span");me.className="spotpatch-target-label";let H=l(e,"span");H.className="spotpatch-context-state",H.dataset.state="loading",H.textContent=r.context.collecting,Se.append(me,H),R.append(D,W,T,Se);let je=l(e,"div");je.className="spotpatch-body";let Le=l(e,"div");Le.className="spotpatch-selection-panel";let z=l(e,"section");z.className="spotpatch-targets";let Ee=l(e,"div");Ee.className="spotpatch-targets-heading";let Ne=l(e,"span"),Ue=l(e,"span");Ue.className="spotpatch-targets-meta";let oe=l(e,"span");oe.className="spotpatch-target-complete";let Q=l(e,"span");Q.className="spotpatch-target-budget",Q.setAttribute("aria-live","polite");let K=l(e,"span");K.className="spotpatch-target-count",Ue.append(oe,Q),Ee.append(Ne,K);let ee=l(e,"div");ee.className="spotpatch-target-list",z.append(Ee,Ue,ee);let re=l(e,"details");re.className="spotpatch-diagnostics";let Pe=l(e,"summary"),_e=l(e,"span"),be=l(e,"span");be.className="spotpatch-source-peek",be.textContent=r.diagnostics.resolving,Pe.append(_e,be);let k=l(e,"pre");k.className="spotpatch-summary",re.append(Pe,k);let O=Dn(e,o,i);Le.append(z,re,O.root);let Be=l(e,"div");Be.className="spotpatch-preview-panel",Be.hidden=!0;let Ae=l(e,"pre");Ae.className="spotpatch-prompt",Ae.tabIndex=0,Ae.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Be.append(Ae),je.append(Le,Be);let He=l(e,"footer");He.className="spotpatch-actions";let Y=l(e,"div");Y.className="spotpatch-context-state spotpatch-editor-feedback",Y.dataset.state="idle",Y.setAttribute("role","status"),Y.setAttribute("aria-live","polite"),Y.hidden=!0;let X=F(e,r.actions.addElement),Ce=F(e,r.actions.reselect),ae=F(e,r.actions.openEditor),te=F(e,r.actions.preview,"spotpatch-primary"),le=F(e,r.actions.copy,"spotpatch-primary"),ke=F(e,r.actions.back);He.append(Y,O.runButton,te,O.testButton,O.cancelButton,O.applyButton,O.revertButton,O.resetButton,X,ae,Ce,le,ke),A.append(R,je,He),b.append(N,A);let Re=l(e,"div");Re.className="spotpatch-live",Re.setAttribute("aria-live","polite"),Re.setAttribute("aria-atomic","true"),c.append(kr(e),_,C,b,S,Re),e.documentElement.append(a);let ie,Te,ve="idle",se=!1,Me=!1,De="",ye=!0,de=[],V=0,Ye="idle";function s(d){Ye=d,Y.dataset.state=d,Y.hidden=d==="idle",Y.textContent=d==="opening"?r.announcements.editorOpening:d==="success"?r.announcements.editorOpened:d==="error"?r.announcements.editorFailed:"",w()}function p(d){return d.status==="ready"?r.targets.statusReady:d.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function x(d){let m=ee.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(m).find(v=>d===void 0||v.dataset.targetInstructionId===d)}function I(d,m){let v=c.activeElement?.closest("textarea[data-target-instruction-id]"),j=v?.dataset.targetInstructionId,ue=v?.selectionStart,$e=v?.selectionEnd;de=d.map(ce=>Object.freeze({...ce})),V=m,ee.replaceChildren();let Ge=d.filter(ce=>ce.instruction.trim().length>0).length,ge=d.reduce((ce,q)=>ce+q.instruction.trim().length,0);K.textContent=r.targets.count(d.length,m),oe.textContent=r.targets.complete(Ge,d.length);let Oe=ge>4e3;Q.dataset.state=Oe?"over":"ready",Q.textContent=Oe?r.targets.instructionBudgetExceeded(ge,4e3):r.targets.instructionBudget(ge,4e3),X.disabled=!ye||d.length>=m,X.title=d.length>=m?r.targets.limitTitle(m):r.targets.addTitle,me.textContent=d.length===1?d[0]?.label??r.context.selectedElement:r.context.selectedCount(d.length);for(let[ce,q]of d.entries()){let Xe=l(e,"div");Xe.className="spotpatch-target-item",Xe.dataset.active=String(q.active),Xe.dataset.status=q.status,Xe.dataset.targetId=q.id;let Et=l(e,"div");Et.className="spotpatch-target-summary";let rt=F(e,"","spotpatch-target-select");rt.dataset.activateTargetId=q.id,rt.setAttribute("aria-label",r.targets.activate(ce+1)),rt.setAttribute("aria-expanded",String(q.active));let At=l(e,"span");At.className="spotpatch-target-index",At.textContent=String(ce+1);let Ct=l(e,"span");Ct.className="spotpatch-target-copy";let Rt=l(e,"span");Rt.className="spotpatch-target-name",Rt.textContent=q.label;let vt=l(e,"span");vt.className="spotpatch-target-source",vt.textContent=`${p(q)} · ${q.source}`,Ct.append(Rt,vt);let Wt=q.instruction.trim().length>0,gt=l(e,"span");gt.className="spotpatch-target-state",gt.dataset.complete=String(Wt),gt.textContent=Wt?r.targets.instructionReady:r.targets.instructionMissing,rt.append(At,Ct,gt);let at=F(e,"↗","spotpatch-target-open");at.dataset.openTargetId=q.id,at.disabled=!q.canOpenEditor,at.setAttribute("aria-label",r.actions.openTarget(ce+1)),at.title=r.actions.openTarget(ce+1);let it=F(e,"×","spotpatch-target-remove");if(it.dataset.removeTargetId=q.id,it.disabled=!ye,it.setAttribute("aria-label",r.targets.remove(ce+1)),it.title=r.targets.removeTitle,Et.append(rt,at,it),Xe.append(Et),q.active){let Tt=l(e,"label");Tt.className="spotpatch-target-editor";let wt=l(e,"span");wt.className="spotpatch-target-editor-head";let Ot=l(e,"span");Ot.className="spotpatch-target-editor-label",Ot.textContent=r.targets.instructionLabel(q.label);let Lt=l(e,"span");Lt.className="spotpatch-target-editor-count",Lt.textContent=r.targets.instructionCount(q.instruction.length,2e3),wt.append(Ot,Lt);let Ve=l(e,"textarea");Ve.rows=4,Ve.maxLength=2e3,Ve.value=q.instruction,Ve.placeholder=r.targets.instructionPlaceholder,Ve.disabled=!ye,Ve.dataset.targetInstructionId=q.id,Ve.setAttribute("aria-label",r.targets.instructionLabel(q.label)),Tt.append(wt,Ve),Xe.append(Tt)}ee.append(Xe)}if(j!==void 0){let ce=x(j);ce?.focus({preventScroll:!0}),ue!==void 0&&$e!==void 0&&ce?.setSelectionRange(ue,$e)}}function $(d,m){de=de.map(Oe=>Oe.id===d?Object.freeze({...Oe,instruction:m}):Oe);let v=Array.from(ee.querySelectorAll(".spotpatch-target-item")).find(Oe=>Oe.dataset.targetId===d);if(v===void 0)return;let j=m.trim().length>0,ue=v.querySelector(".spotpatch-target-state"),$e=v.querySelector(".spotpatch-target-editor-count");ue!==null&&(ue.dataset.complete=String(j),ue.textContent=j?r.targets.instructionReady:r.targets.instructionMissing),$e!==null&&($e.textContent=r.targets.instructionCount(m.length,2e3)),oe.textContent=r.targets.complete(de.filter(Oe=>Oe.instruction.trim().length>0).length,de.length);let Ge=de.reduce((Oe,ce)=>Oe+ce.instruction.trim().length,0),ge=Ge>4e3;Q.dataset.state=ge?"over":"ready",Q.textContent=ge?r.targets.instructionBudgetExceeded(Ge,4e3):r.targets.instructionBudget(Ge,4e3)}function g(d){_.replaceChildren(),Te=d.find(m=>m.active)?.rect,ie=Te;for(let[m,v]of d.entries()){let j=l(e,"div");j.className="spotpatch-selection-highlight",j.dataset.targetId=v.id,j.dataset.active=String(v.active),j.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,j.style.width=`${String(v.rect.width)}px`,j.style.height=`${String(v.rect.height)}px`;let ue=l(e,"span");ue.textContent=`${String(m+1)} · ${v.label}`,j.append(ue),_.append(j)}w()}function w(){if(b.hidden||ie===void 0)return;let d=e.defaultView,m=d?.innerWidth??e.documentElement.clientWidth,v=d?.innerHeight??e.documentElement.clientHeight,j=b.getBoundingClientRect(),ue=ve==="previewing"?"previewing":"selected",$e=j.width>0?j.width:Math.min(Pr,m-32),Ge=j.height>0?j.height:Math.min(_r[ue],v-32),ge=zn({target:ie,dialogWidth:$e,dialogHeight:Ge,viewportWidth:m,viewportHeight:v});b.style.left=`${String(ge.left)}px`,b.style.top=`${String(ge.top)}px`,b.style.setProperty("--spotpatch-anchor-x",`${String(ge.anchorX)}px`),b.style.setProperty("--spotpatch-anchor-y",`${String(ge.anchorY)}px`),b.dataset.placement=ge.mode}function pe(d){let m=r.summary,v=Ir(d,m.source);be.textContent=v??r.diagnostics.noExactSource;let j=`${m.browserContext}: ${m.collectionStatuses.ready}`,ue=`${m.browserContext}: ${m.collectionStatuses.loading}`,$e=`${m.browserContext}: ${m.collectionStatuses.failed}`,Ge=`${m.api}: ${m.apiStatuses.loading}`,ge=`${m.api}: ${m.apiStatuses.failed}`;d.includes(j)&&!d.includes(ue)&&!d.includes(Ge)&&!d.includes($e)&&!d.includes(ge)?(H.dataset.state="ready",H.textContent=r.context.ready):d.includes($e)||d.includes(ge)?(H.dataset.state="warning",H.textContent=r.context.partial):(H.dataset.state="loading",H.textContent=r.context.collecting)}function J(d,m,v){se=m,Me=v,De=d,k.textContent=d,ae.disabled=!m,te.disabled=!v,O.setContextReady(v),pe(d),w()}function we(d){ve=d;let m=d==="selected",v=d==="previewing";S.hidden=m||v,Le.hidden=!m,Be.hidden=!v,Ce.hidden=!m,X.hidden=!m,ae.hidden=!m,te.hidden=!m,O.setSelectionVisible(m),le.hidden=!v,ke.hidden=!v,W.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,T.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,w()}function ot(){r=i.messages(),B.textContent=r.brand.name,f.textContent=r.brand.context,E.textContent=r.brand.repository,E.title=r.brand.repositoryTitle,E.setAttribute("aria-label",r.brand.repositoryTitle),P.textContent=r.alternateLocaleName,P.title=r.switchLocale,P.setAttribute("aria-label",r.switchLocale),U.setAttribute("aria-label",r.dialog.close),U.title=r.dialog.close,z.setAttribute("aria-label",r.targets.ariaLabel),Ne.textContent=r.targets.title,_e.textContent=r.diagnostics.title,Ae.setAttribute("aria-label",r.diagnostics.promptAriaLabel),X.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,ae.textContent=r.actions.openEditor,te.textContent=r.actions.preview,le.textContent=r.actions.copy,ke.textContent=r.actions.back,S.title=r.trigger.title(t),S.textContent=ve==="inspecting"?r.trigger.stop:r.trigger.select,we(ve),s(Ye),de.length>0?I(de,V):(K.textContent=r.targets.count(0,V),oe.textContent=r.targets.complete(0,0),Q.dataset.state="ready",Q.textContent=r.targets.instructionBudget(0,4e3),me.textContent=r.context.selectedElement),De.length>0?pe(De):(be.textContent=r.diagnostics.resolving,H.textContent=r.context.collecting)}re.addEventListener("toggle",w),P.addEventListener("click",i.toggle);let ut=i.subscribe(ot);return ot(),Object.freeze({host:a,triggerButton:S,addTargetButton:X,targetList:ee,reselectButton:Ce,openEditorButton:ae,repositoryLink:E,previewButton:te,copyButton:le,backButton:ke,closeButton:U,agentProviderSelect:O.providerSelect,agentModelSelect:O.modelSelect,agentConsentCheckbox:O.consentCheckbox,agentWorkspaceConsentCheckbox:O.workspaceConsentCheckbox,agentTestButton:O.testButton,agentRunButton:O.runButton,agentCancelButton:O.cancelButton,agentApplyButton:O.applyButton,agentRevertButton:O.revertButton,agentResetButton:O.resetButton,renderStatus(d){let m=d==="inspecting";S.setAttribute("aria-pressed",String(m)),S.textContent=m?r.trigger.stop:r.trigger.select,we(d)},renderEditorStatus:s,showHighlight(d,m){ie=d,C.hidden=!1,C.style.transform=`translate(${String(d.x)}px, ${String(d.y)}px)`,C.style.width=`${String(d.width)}px`,C.style.height=`${String(d.height)}px`,u.textContent=m,me.textContent=m,w()},hideHighlight(){ie=Te,C.hidden=!0,u.textContent="",w()},showSelectionHighlights:g,hideSelectionHighlights(){_.replaceChildren(),Te=void 0,ie=void 0},showSelection(d,m,v){J(d,m,v),S.hidden=!0,b.hidden=!1,w()},updateSelection:J,renderTargets:I,updateTargetInstruction:$,setPreviewEnabled(d){Me=d,te.disabled=!d,O.setContextReady(d)},hideSelection(){b.hidden=!0,S.hidden=!1,ee.replaceChildren(),de=[],V=0,De="",s("idle"),K.textContent=r.targets.count(0,0),oe.textContent=r.targets.complete(0,0),me.textContent=r.context.selectedElement,k.textContent="",Ae.textContent="",be.textContent=r.diagnostics.resolving,H.dataset.state="loading",H.textContent=r.context.collecting,ae.disabled=!0,te.disabled=!0,se=!1,Me=!1,O.setContextReady(!1),O.setSelectionVisible(!1),O.setEditingEnabled(!0),O.resetJob()},hideSelectionTemporarily(){b.hidden=!0,S.hidden=!1},showPreview(d){Ae.textContent=d,w()},readAgentSelection(){return O.readSelection()},agentConsentGranted(){return O.consentGranted()},setAgentProviderConsent(d){O.setProviderConsent(d)},setAgentEditingEnabled(d){ye=d,X.disabled=!d,Ce.disabled=!d,ee.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(m=>{m.disabled=!d}),ae.disabled=!se,te.disabled=!d||!Me,O.setEditingEnabled(d),w()},renderAgentCapability(d,m,v,j){O.renderCapability(d,m,v,j);let ue=d==="ready"&&v?.state==="agent-ready";te.classList.toggle("spotpatch-primary",!ue),w()},renderAgentWorkspaceHealth(d,m,v){O.renderWorkspaceHealth(d,m,v),w()},renderAgentJob(d,m,v,j){O.renderJob(d,m,v,j),w()},resetAgentJob(){O.resetJob(),w()},focusTargetInstruction(d){x(d)?.focus({preventScroll:!0})},focusPrompt(){Ae.focus({preventScroll:!0})},announce(d){Re.textContent="",Re.textContent=d},locale:i.locale,messages:i.messages,agentWorkspaceConsentGranted:O.workspaceConsentGranted,subscribeLocale:i.subscribe,dispose(){re.removeEventListener("toggle",w),P.removeEventListener("click",i.toggle),ut(),O.dispose(),a.remove()}})}function Nr(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,r=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,r):o.unavailable}function Hn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`Vite: ${e.viteVersion}`,`${t.source}: ${Nr(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
881
- `)}function Gn(e,t){return`${e}:${t}`}function Mr(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 Wn(e){let t=f=>an(f)??h.INTERNAL_ERROR,o=f=>e.view.messages().errors[t(f)],n=new Map,i=new Set,r=new Map,a=0,c,S,C=!1,u=!1,_=()=>e.view.readAgentSelection(),b=async f=>{e.view.renderAgentWorkspaceHealth("checking");try{let y=await e.api.agentWorkspaceHealth();return f!==a||e.view.renderAgentWorkspaceHealth(y.state,y,y.errorCode),y}catch(y){throw f===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(y)),y}},N=f=>{c!==void 0&&e.view.renderAgentJob(c,S,Object.freeze([...r.values()]),f??c.errorCode)},A=()=>{let f=_();if(f===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(f.providerProfileId));let y=n.get(Gn(f.providerProfileId,f.modelProfileId));y===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,y)},R=async f=>{let y=_();if(y===void 0)throw new Error("Agent provider selection is unavailable.");let E=Gn(y.providerProfileId,y.modelProfileId),P=n.get(E);if(P!==void 0)return P;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let U=await e.api.agentCapability(y);if(f!==a)return U;if(U.state!=="agent-ready")throw new M(U.errorCode??h.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(E,U),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,U),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),U},D=async(f,y)=>{try{let E=await e.api.agentResult(f);if(y!==a||E.snapshot.jobId!==f)return;c=E.snapshot,S=E.result,N()}catch(E){y===a&&N(t(E))}},L=async(f,y)=>{try{await e.api.agentEvents(f,E=>{if(y!==a||E.jobId!==f)return;E.type==="snapshot"&&(c=E.data.snapshot,c.status==="applied"&&!C&&(C=!0,e.onApplied()));let P=Mr(E);P!==void 0&&r.set(P.key,P),N()}),y===a&&await D(f,y)}catch(E){y===a&&!(E instanceof DOMException&&E.name==="AbortError")&&N(t(E))}},Z=async f=>{let y=c;if(y===void 0||u)return;u=!0;let E=a;c=Object.freeze({...y,status:f==="apply"?"applying":f==="cancel"?"cancelling":"reverting",phaseMessage:f==="apply"?e.view.messages().agent.applying:f==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),N();try{let P=f==="apply"?await e.api.applyAgentJob(y.jobId):f==="cancel"?await e.api.cancelAgentJob(y.jobId):await e.api.revertAgentJob(y.jobId);if(E!==a)return;c=P,P.status==="applied"&&!C&&(C=!0,e.onApplied()),await D(P.jobId,E)}catch(P){if(E!==a)return;c=y,await D(y.jobId,E),N(t(P)),e.view.announce(o(P))}finally{E===a&&(u=!1)}},B=()=>{a+=1,c=void 0,S=void 0,r.clear(),C=!1,u=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),A()};return Object.freeze({apply(){c?.canApply===!0&&Z("apply")},beginSelection(){B();let f=a;e.ai.enabled&&b(f).catch(()=>{})},cancel(){c?.canCancel===!0&&Z("cancel")},consentChanged(){let f=_();f!==void 0&&(e.view.agentConsentGranted()?i.add(f.providerProfileId):i.delete(f.providerProfileId))},disposeSelection(){let f=c?.canCancel===!0||c?.status==="cancelling"?c.jobId:void 0;a+=1,c=void 0,S=void 0,r.clear(),C=!1,u=!1,f!==void 0&&e.api.cancelAgentJob(f).catch(()=>{})},providerOrModelChanged(){a+=1,A(),b(a).catch(()=>{})},reset(){let f=C;B(),f?e.onReselectRequired():e.ai.enabled&&b(a).catch(()=>{})},revert(){c?.canRevert===!0&&Z("revert")},run(){if(!e.ai.enabled||c!==void 0)return;let f=_(),y=e.getAnnotation();if(f===void 0||y===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(f.providerProfileId);let E=++a;e.view.setAgentEditingEnabled(!1),Promise.all([R(E),b(E)]).then(async([,P])=>{if(E!==a)return;if(P.state==="blocked")throw new M(P.errorCode??h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(P.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new M(h.WORKTREE_DIRTY);let U=await e.api.createAgentJob({annotation:y,providerProfileId:f.providerProfileId,modelProfileId:f.modelProfileId,providerDataConsent:!0,workingTreeMode:P.state==="consent-required"?"include-local-changes":"require-clean"});E===a&&(c=U,S=void 0,r.clear(),N(),L(U.jobId,E))}).catch(P=>{E===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(P),void 0,t(P)),e.view.announce(o(P)))})},testCapability(){if(!e.ai.enabled||c!==void 0)return;let f=++a;Promise.all([R(f),b(f)]).catch(y=>{f===a&&(e.view.renderAgentCapability("error",o(y),void 0,t(y)),e.view.announce(o(y)))})}})}function Vn(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function Jn(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function qn(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var $r=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Ht(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function zr(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function jr(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Ur(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function Fn(e,t={}){let o=Ur(t),n=t.view??Bn(o.document,e.shortcut,e.ai,e.locale),i=t.api??sn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??wn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??qn(o.window.navigator),c=t.createId??(()=>Vn(o.window)),S=t.now??(()=>new Date().toISOString()),C=In({adapter:t.reactAdapter??Dr({maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),u=Bt,_=!1,b,N,A=[],R,D=0,L=0,Z=0,B=!1,f="",y,E,P,U,W=new Map;function T(s){u=On(u,s),n.renderStatus(u.status)}function Se(){return A.find(s=>s.id===R)??A.at(-1)}function me(s,p){return _&&p===L&&u.status!=="idle"&&A.includes(s)}function H(){let s=A.reduce((p,x)=>p+x.instruction.trim().length,0);return A.length>0&&s<=4e3&&A.every(p=>p.instruction.trim().length>0&&p.element!==void 0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function je(){let s=n.messages().summary;return A.map((p,x)=>{let I=Hn({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,spotPatchVersion:e.spotPatchVersion,viteVersion:e.viteVersion},s);return`${s.target(x+1,p.id===R)}
882
- ${I}`}).join(`
880
+ ${Gn}
881
+ `,t}function Xr(e,t){return e.split(`
882
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Yn(e,t,o=Object.freeze({enabled:!1}),n="auto"){let s=Kn(e,n),r=s.messages(),i=e.createElement("spotpatch-root");i.setAttribute(ot,"");let l=i.attachShadow({mode:"open"}),E=J(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 k=d(e,"div");k.className="spotpatch-selection-highlights",k.setAttribute("aria-hidden","true");let u=d(e,"section");u.className="spotpatch-dialog",u.hidden=!0,u.tabIndex=-1,u.dataset.placement="viewport",u.setAttribute("role","dialog"),u.setAttribute("aria-labelledby","spotpatch-selection-title");let P=d(e,"span");P.className="spotpatch-anchor",P.setAttribute("aria-hidden","true");let Z=d(e,"div");Z.className="spotpatch-shell";let I=d(e,"header");I.className="spotpatch-header";let b=d(e,"div");b.className="spotpatch-brand-row";let x=d(e,"div");x.className="spotpatch-brand";let Q=d(e,"span");Q.className="spotpatch-brand-copy";let q=d(e,"span");q.className="spotpatch-brand-name";let f=d(e,"span");f.className="spotpatch-brand-context",Q.append(q,f),x.append(Jn(e),Q);let y=d(e,"span");y.className="spotpatch-header-controls";let C=d(e,"a");C.className="spotpatch-repository",C.href=jt,C.target="_blank",C.rel="noopener noreferrer";let v=J(e,"","spotpatch-locale"),D=J(e,"×","spotpatch-close");y.append(C,v,D),b.append(x,y);let G=d(e,"h2");G.id="spotpatch-selection-title",G.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let de=d(e,"div");de.className="spotpatch-target-row";let oe=d(e,"span");oe.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,de.append(oe,B),I.append(b,G,$,de);let L=d(e,"div");L.className="spotpatch-body";let Pe=d(e,"div");Pe.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let F=d(e,"div");F.className="spotpatch-targets-heading";let Ce=d(e,"span"),Re=d(e,"span");Re.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let ee=d(e,"span");ee.className="spotpatch-target-budget",ee.setAttribute("aria-live","polite");let N=d(e,"span");N.className="spotpatch-target-count",Re.append(me,ee),F.append(Ce,N);let K=d(e,"div");K.className="spotpatch-target-list",he.append(F,Re,K);let be=d(e,"details");be.className="spotpatch-diagnostics";let Le=d(e,"summary"),ve=d(e,"span"),ye=d(e,"span");ye.className="spotpatch-source-peek",ye.textContent=r.diagnostics.resolving,Le.append(ve,ye);let re=d(e,"pre");re.className="spotpatch-summary",be.append(Le,re);let _=Vn(e,o,s);Pe.append(he,be,_.root);let ke=d(e,"div");ke.className="spotpatch-preview-panel",ke.hidden=!0;let Se=d(e,"pre");Se.className="spotpatch-prompt",Se.tabIndex=0,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),ke.append(Se),L.append(Pe,ke);let Me=d(e,"footer");Me.className="spotpatch-actions";let Y=d(e,"div");Y.className="spotpatch-context-state spotpatch-editor-feedback",Y.dataset.state="idle",Y.setAttribute("role","status"),Y.setAttribute("aria-live","polite"),Y.hidden=!0;let T=J(e,r.actions.addElement),Te=J(e,r.actions.reselect),le=J(e,r.actions.openEditor),ae=J(e,r.actions.preview,"spotpatch-primary"),De=J(e,r.actions.copy,"spotpatch-primary"),$e=J(e,r.actions.back);Me.append(Y,_.runButton,ae,_.testButton,_.cancelButton,_.applyButton,_.revertButton,_.resetButton,T,le,Te,De,$e),Z.append(I,L,Me),u.append(P,Z);let Ae=d(e,"div");Ae.className="spotpatch-live",Ae.setAttribute("aria-live","polite"),Ae.setAttribute("aria-atomic","true"),l.append(Yr(e),k,A,u,E,Ae),e.documentElement.append(i);let ie,we,Oe="idle",V=!1,ze=!1,Ie="",xe=!0,pe=[],U=0,qe="idle";function Ue(p){qe=p,Y.dataset.state=p,Y.hidden=p==="idle",Y.textContent=p==="opening"?r.announcements.editorOpening:p==="success"?r.announcements.editorOpened:p==="error"?r.announcements.editorFailed:"",a()}function rt(p){return p.status==="ready"?r.targets.statusReady:p.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function Fe(p){let S=K.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(S).find(O=>p===void 0||O.dataset.targetInstructionId===p)}function Ke(p,S){let O=l.activeElement?.closest("textarea[data-target-instruction-id]"),j=O?.dataset.targetInstructionId,ue=O?.selectionStart,je=O?.selectionEnd;pe=p.map(se=>Object.freeze({...se})),U=S,K.replaceChildren();let Ge=p.filter(se=>se.instruction.trim().length>0).length,ge=p.reduce((se,W)=>se+W.instruction.trim().length,0);N.textContent=r.targets.count(p.length,S),me.textContent=r.targets.complete(Ge,p.length);let _e=ge>4e3;ee.dataset.state=_e?"over":"ready",ee.textContent=_e?r.targets.instructionBudgetExceeded(ge,4e3):r.targets.instructionBudget(ge,4e3),T.disabled=!xe||p.length>=S,T.title=p.length>=S?r.targets.limitTitle(S):r.targets.addTitle,oe.textContent=p.length===1?p[0]?.label??r.context.selectedElement:r.context.selectedCount(p.length);for(let[se,W]of p.entries()){let tt=d(e,"div");tt.className="spotpatch-target-item",tt.dataset.active=String(W.active),tt.dataset.status=W.status,tt.dataset.targetId=W.id;let Rt=d(e,"div");Rt.className="spotpatch-target-summary";let ct=J(e,"","spotpatch-target-select");ct.dataset.activateTargetId=W.id,ct.setAttribute("aria-label",r.targets.activate(se+1)),ct.setAttribute("aria-expanded",String(W.active));let vt=d(e,"span");vt.className="spotpatch-target-index",vt.textContent=String(se+1);let Tt=d(e,"span");Tt.className="spotpatch-target-copy";let wt=d(e,"span");wt.className="spotpatch-target-name",wt.textContent=W.label;let Ot=d(e,"span");Ot.className="spotpatch-target-source",Ot.textContent=`${rt(W)} · ${W.source}`,Tt.append(wt,Ot);let Yt=W.instruction.trim().length>0,mt=d(e,"span");mt.className="spotpatch-target-state",mt.dataset.complete=String(Yt),mt.textContent=Yt?r.targets.instructionReady:r.targets.instructionMissing,ct.append(vt,Tt,mt);let dt=J(e,"↗","spotpatch-target-open");dt.dataset.openTargetId=W.id,dt.disabled=!W.canOpenEditor,dt.setAttribute("aria-label",r.actions.openTarget(se+1)),dt.title=r.actions.openTarget(se+1);let lt=J(e,"×","spotpatch-target-remove");if(lt.dataset.removeTargetId=W.id,lt.disabled=!xe,lt.setAttribute("aria-label",r.targets.remove(se+1)),lt.title=r.targets.removeTitle,Rt.append(ct,dt,lt),tt.append(Rt),W.active){let _t=d(e,"label");_t.className="spotpatch-target-editor";let Pt=d(e,"span");Pt.className="spotpatch-target-editor-head";let Lt=d(e,"span");Lt.className="spotpatch-target-editor-label",Lt.textContent=r.targets.instructionLabel(W.label);let kt=d(e,"span");kt.className="spotpatch-target-editor-count",kt.textContent=r.targets.instructionCount(W.instruction.length,2e3),Pt.append(Lt,kt);let Ye=d(e,"textarea");Ye.rows=4,Ye.maxLength=2e3,Ye.value=W.instruction,Ye.placeholder=r.targets.instructionPlaceholder,Ye.disabled=!xe,Ye.dataset.targetInstructionId=W.id,Ye.setAttribute("aria-label",r.targets.instructionLabel(W.label)),_t.append(Pt,Ye),tt.append(_t)}K.append(tt)}if(j!==void 0){let se=Fe(j);se?.focus({preventScroll:!0}),ue!==void 0&&je!==void 0&&se?.setSelectionRange(ue,je)}}function st(p,S){pe=pe.map(_e=>_e.id===p?Object.freeze({..._e,instruction:S}):_e);let O=Array.from(K.querySelectorAll(".spotpatch-target-item")).find(_e=>_e.dataset.targetId===p);if(O===void 0)return;let j=S.trim().length>0,ue=O.querySelector(".spotpatch-target-state"),je=O.querySelector(".spotpatch-target-editor-count");ue!==null&&(ue.dataset.complete=String(j),ue.textContent=j?r.targets.instructionReady:r.targets.instructionMissing),je!==null&&(je.textContent=r.targets.instructionCount(S.length,2e3)),me.textContent=r.targets.complete(pe.filter(_e=>_e.instruction.trim().length>0).length,pe.length);let Ge=pe.reduce((_e,se)=>_e+se.instruction.trim().length,0),ge=Ge>4e3;ee.dataset.state=ge?"over":"ready",ee.textContent=ge?r.targets.instructionBudgetExceeded(Ge,4e3):r.targets.instructionBudget(Ge,4e3)}function m(p){k.replaceChildren(),we=p.find(S=>S.active)?.rect,ie=we;for(let[S,O]of p.entries()){let j=d(e,"div");j.className="spotpatch-selection-highlight",j.dataset.targetId=O.id,j.dataset.active=String(O.active),j.style.transform=`translate(${String(O.rect.x)}px, ${String(O.rect.y)}px)`,j.style.width=`${String(O.rect.width)}px`,j.style.height=`${String(O.rect.height)}px`;let ue=d(e,"span");ue.textContent=`${String(S+1)} · ${O.label}`,j.append(ue),k.append(j)}a()}function a(){if(u.hidden||ie===void 0)return;let p=e.defaultView,S=p?.innerWidth??e.documentElement.clientWidth,O=p?.innerHeight??e.documentElement.clientHeight,j=u.getBoundingClientRect(),ue=Oe==="previewing"?"previewing":"selected",je=j.width>0?j.width:Math.min(Fr,S-32),Ge=j.height>0?j.height:Math.min(Kr[ue],O-32),ge=qn({target:ie,dialogWidth:je,dialogHeight:Ge,viewportWidth:S,viewportHeight:O});u.style.left=`${String(ge.left)}px`,u.style.top=`${String(ge.top)}px`,u.style.setProperty("--spotpatch-anchor-x",`${String(ge.anchorX)}px`),u.style.setProperty("--spotpatch-anchor-y",`${String(ge.anchorY)}px`),u.dataset.placement=ge.mode}function c(p){let S=r.summary,O=Xr(p,S.source);ye.textContent=O??r.diagnostics.noExactSource;let j=`${S.browserContext}: ${S.collectionStatuses.ready}`,ue=`${S.browserContext}: ${S.collectionStatuses.loading}`,je=`${S.browserContext}: ${S.collectionStatuses.failed}`,Ge=`${S.api}: ${S.apiStatuses.loading}`,ge=`${S.api}: ${S.apiStatuses.failed}`;p.includes(j)&&!p.includes(ue)&&!p.includes(Ge)&&!p.includes(je)&&!p.includes(ge)?(B.dataset.state="ready",B.textContent=r.context.ready):p.includes(je)||p.includes(ge)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function h(p,S,O){V=S,ze=O,Ie=p,re.textContent=p,le.disabled=!S,ae.disabled=!O,_.setContextReady(O),c(p),a()}function w(p){Oe=p;let S=p==="selected",O=p==="previewing";E.hidden=S||O,Pe.hidden=!S,ke.hidden=!O,Te.hidden=!S,T.hidden=!S,le.hidden=!S,ae.hidden=!S,_.setSelectionVisible(S),De.hidden=!O,$e.hidden=!O,G.textContent=O?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=O?r.dialog.previewSubtitle:r.dialog.editSubtitle,a()}function z(){r=s.messages(),q.textContent=r.brand.name,f.textContent=r.brand.context,C.textContent=r.brand.repository,C.title=r.brand.repositoryTitle,C.setAttribute("aria-label",r.brand.repositoryTitle),v.textContent=r.alternateLocaleName,v.title=r.switchLocale,v.setAttribute("aria-label",r.switchLocale),D.setAttribute("aria-label",r.dialog.close),D.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),Ce.textContent=r.targets.title,ve.textContent=r.diagnostics.title,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),T.textContent=r.actions.addElement,Te.textContent=r.actions.reselect,le.textContent=r.actions.openEditor,ae.textContent=r.actions.preview,De.textContent=r.actions.copy,$e.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=Oe==="inspecting"?r.trigger.stop:r.trigger.select,w(Oe),Ue(qe),pe.length>0?Ke(pe,U):(N.textContent=r.targets.count(0,U),me.textContent=r.targets.complete(0,0),ee.dataset.state="ready",ee.textContent=r.targets.instructionBudget(0,4e3),oe.textContent=r.context.selectedElement),Ie.length>0?c(Ie):(ye.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}be.addEventListener("toggle",a),v.addEventListener("click",s.toggle);let te=s.subscribe(z);return z(),Object.freeze({host:i,triggerButton:E,addTargetButton:T,targetList:K,reselectButton:Te,openEditorButton:le,repositoryLink:C,previewButton:ae,copyButton:De,backButton:$e,closeButton:D,agentProviderSelect:_.providerSelect,agentModelSelect:_.modelSelect,agentConsentCheckbox:_.consentCheckbox,agentWorkspaceConsentCheckbox:_.workspaceConsentCheckbox,agentTestButton:_.testButton,agentRunButton:_.runButton,agentCancelButton:_.cancelButton,agentApplyButton:_.applyButton,agentRevertButton:_.revertButton,agentResetButton:_.resetButton,renderStatus(p){let S=p==="inspecting";E.setAttribute("aria-pressed",String(S)),E.textContent=S?r.trigger.stop:r.trigger.select,w(p)},renderEditorStatus:Ue,showHighlight(p,S){ie=p,A.hidden=!1,A.style.transform=`translate(${String(p.x)}px, ${String(p.y)}px)`,A.style.width=`${String(p.width)}px`,A.style.height=`${String(p.height)}px`,R.textContent=S,oe.textContent=S,a()},hideHighlight(){ie=we,A.hidden=!0,R.textContent="",a()},showSelectionHighlights:m,hideSelectionHighlights(){k.replaceChildren(),we=void 0,ie=void 0},showSelection(p,S,O){h(p,S,O),E.hidden=!0,u.hidden=!1,a()},updateSelection:h,renderTargets:Ke,updateTargetInstruction:st,setPreviewEnabled(p){ze=p,ae.disabled=!p,_.setContextReady(p)},hideSelection(){u.hidden=!0,E.hidden=!1,K.replaceChildren(),pe=[],U=0,Ie="",Ue("idle"),N.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),oe.textContent=r.context.selectedElement,re.textContent="",Se.textContent="",ye.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,le.disabled=!0,ae.disabled=!0,V=!1,ze=!1,_.setContextReady(!1),_.setSelectionVisible(!1),_.setEditingEnabled(!0),_.resetJob()},hideSelectionTemporarily(){u.hidden=!0,E.hidden=!1},showPreview(p){Se.textContent=p,a()},readAgentSelection(){return _.readSelection()},agentConsentGranted(){return _.consentGranted()},setAgentProviderConsent(p){_.setProviderConsent(p)},setAgentEditingEnabled(p){xe=p,T.disabled=!p,Te.disabled=!p,K.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(S=>{S.disabled=!p}),le.disabled=!V,ae.disabled=!p||!ze,_.setEditingEnabled(p),a()},renderAgentCapability(p,S,O,j){_.renderCapability(p,S,O,j);let ue=p==="ready"&&O?.state==="agent-ready";ae.classList.toggle("spotpatch-primary",!ue),a()},renderAgentWorkspaceHealth(p,S,O){_.renderWorkspaceHealth(p,S,O),a()},renderAgentJob(p,S,O,j){_.renderJob(p,S,O,j),a()},resetAgentJob(){_.resetJob(),a()},focusTargetInstruction(p){Fe(p)?.focus({preventScroll:!0})},focusPrompt(){Se.focus({preventScroll:!0})},announce(p){Ae.textContent="",Ae.textContent=p},locale:s.locale,messages:s.messages,agentWorkspaceConsentGranted:_.workspaceConsentGranted,subscribeLocale:s.subscribe,dispose(){be.removeEventListener("toggle",a),v.removeEventListener("click",s.toggle),te(),_.dispose(),i.remove()}})}function Zr(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,r=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,r):o.unavailable}function Xn(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${Zr(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(`
883
+ `)}function Zn(e,t){return`${e}:${t}`}function Qr(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 Qn(e){let t=f=>un(f)??g.INTERNAL_ERROR,o=f=>e.view.messages().errors[t(f)],n=new Map,s=new Set,r=new Map,i=0,l,E,A=!1,R=!1,k=()=>e.view.readAgentSelection(),u=async f=>{e.view.renderAgentWorkspaceHealth("checking");try{let y=await e.api.agentWorkspaceHealth();return f!==i||e.view.renderAgentWorkspaceHealth(y.state,y,y.errorCode),y}catch(y){throw f===i&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(y)),y}},P=f=>{l!==void 0&&e.view.renderAgentJob(l,E,Object.freeze([...r.values()]),f??l.errorCode)},Z=()=>{let f=k();if(f===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(f.providerProfileId));let y=n.get(Zn(f.providerProfileId,f.modelProfileId));y===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,y)},I=async f=>{let y=k();if(y===void 0)throw new Error("Agent provider selection is unavailable.");let C=Zn(y.providerProfileId,y.modelProfileId),v=n.get(C);if(v!==void 0)return v;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let D=await e.api.agentCapability(y);if(f!==i)return D;if(D.state!=="agent-ready")throw new M(D.errorCode??g.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(C,D),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,D),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),D},b=async(f,y)=>{try{let C=await e.api.agentResult(f);if(y!==i||C.snapshot.jobId!==f)return;l=C.snapshot,E=C.result,P()}catch(C){y===i&&P(t(C))}},x=async(f,y)=>{try{await e.api.agentEvents(f,C=>{if(y!==i||C.jobId!==f)return;C.type==="snapshot"&&(l=C.data.snapshot,l.status==="applied"&&!A&&(A=!0,e.onApplied()));let v=Qr(C);v!==void 0&&r.set(v.key,v),P()}),y===i&&await b(f,y)}catch(C){y===i&&!(C instanceof DOMException&&C.name==="AbortError")&&P(t(C))}},Q=async f=>{let y=l;if(y===void 0||R)return;R=!0;let C=i;l=Object.freeze({...y,status:f==="apply"?"applying":f==="cancel"?"cancelling":"reverting",phaseMessage:f==="apply"?e.view.messages().agent.applying:f==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),P();try{let v=f==="apply"?await e.api.applyAgentJob(y.jobId):f==="cancel"?await e.api.cancelAgentJob(y.jobId):await e.api.revertAgentJob(y.jobId);if(C!==i)return;l=v,v.status==="applied"&&!A&&(A=!0,e.onApplied()),await b(v.jobId,C)}catch(v){if(C!==i)return;l=y,await b(y.jobId,C),P(t(v)),e.view.announce(o(v))}finally{C===i&&(R=!1)}},q=()=>{i+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),Z()};return Object.freeze({apply(){l?.canApply===!0&&Q("apply")},beginSelection(){q();let f=i;e.ai.enabled&&u(f).catch(()=>{})},cancel(){l?.canCancel===!0&&Q("cancel")},consentChanged(){let f=k();f!==void 0&&(e.view.agentConsentGranted()?s.add(f.providerProfileId):s.delete(f.providerProfileId))},disposeSelection(){let f=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;i+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,f!==void 0&&e.api.cancelAgentJob(f).catch(()=>{})},providerOrModelChanged(){i+=1,Z(),u(i).catch(()=>{})},reset(){let f=A;q(),f?e.onReselectRequired():e.ai.enabled&&u(i).catch(()=>{})},revert(){l?.canRevert===!0&&Q("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let f=k(),y=e.getAnnotation();if(f===void 0||y===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}s.add(f.providerProfileId);let C=++i;e.view.setAgentEditingEnabled(!1),Promise.all([I(C),u(C)]).then(async([,v])=>{if(C!==i)return;if(v.state==="blocked")throw new M(v.errorCode??g.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(v.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new M(g.WORKTREE_DIRTY);let D=await e.api.createAgentJob({annotation:y,providerProfileId:f.providerProfileId,modelProfileId:f.modelProfileId,providerDataConsent:!0,workingTreeMode:v.state==="consent-required"?"include-local-changes":"require-clean"});C===i&&(l=D,E=void 0,r.clear(),P(),x(D.jobId,C))}).catch(v=>{C===i&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(v),void 0,t(v)),e.view.announce(o(v)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let f=++i;Promise.all([I(f),u(f)]).catch(y=>{f===i&&(e.view.renderAgentCapability("error",o(y),void 0,t(y)),e.view.announce(o(y)))})}})}function eo(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 to(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var ta=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Ft(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 na(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,s=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function oa(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ra(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 no(e,t={}){let o=ra(t),n=t.view??Yn(o.document,e.shortcut,e.ai,e.locale),s=t.api??gn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??In({maxCharacters:e.budget.totalCharacters}),i=t.clipboard??to(o.window.navigator),l=t.createId??(()=>eo(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??$n(o.window,e.sessionId,e.maxTargets),R=A.load(),k=Hn({adapter:t.reactAdapter??ea({maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),u=Vt,P=!1,Z,I,b=R?.targets.map(a=>{let c=Jt(a.source);return{id:a.id,resolution:Object.freeze({source:a.source,react:a.react}),apiStatus:c===void 0?"not-required":a.code===void 0?"failed":"connected",code:a.code,collectionStatus:"ready",element:void 0,elementContext:a.element,instruction:a.instruction,marker:c,page:a.page,styles:a.styles}})??[],x=R?.activeTargetId,Q=R?.sequence??0,q=R?.open??!1,f=!1,y=0,C=0,v=!1,D="",G,$,de,oe,B=new Map;function L(a){u=Nn(u,a),n.renderStatus(u.status)}function Pe(){return b.find(a=>a.id===x)??b.at(-1)}function he(a){if(!(a.elementContext===void 0||a.styles===void 0))return{id:a.id,instruction:a.instruction,page:a.page,source:a.resolution.source,react:a.resolution.react,element:a.elementContext,styles:a.styles,...a.code===void 0?{}:{code:a.code}}}function F(){let a=b.flatMap(h=>{let w=he(h);return w===void 0?[]:[w]});if(a.length===0){A.clear();return}let c=new Set(a.map(({id:h})=>h));A.save({...x!==void 0&&c.has(x)?{activeTargetId:x}:{},open:q,sequence:Q,targets:a})}function Ce(a,c){return P&&c===y&&u.status!=="idle"&&b.includes(a)}function Re(){let a=b.reduce((c,h)=>c+h.instruction.trim().length,0);return b.length>0&&a<=4e3&&b.every(c=>c.instruction.trim().length>0&&c.elementContext!==void 0&&c.styles!==void 0&&c.apiStatus!=="loading")}function me(){let a=n.messages().summary;return b.map((c,h)=>{let w=Xn({resolution:c.resolution,...c.code===void 0?{}:{code:c.code},...c.styles===void 0?{}:{styles:c.styles},apiStatus:c.apiStatus,collectionStatus:c.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},a);return`${a.target(h+1,c.id===x)}
884
+ ${w}`}).join(`
883
885
 
884
- `)}function Le(){let s=A.flatMap(p=>p.element?.isConnected?[{id:p.id,label:Ht(p.element),rect:zt(p.element,o.window),active:p.id===R}]:[]);s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function z(s=!1){if(A.length===0)return;n.renderTargets(A.map($=>({id:$.id,label:$.resolution.react.componentName??($.element===void 0?$.elementContext?.tagName??"Element":Ht($.element)),source:zr($,n.messages().context.sourceUnavailable),canOpenEditor:$.marker!==void 0,status:jr($),active:$.id===R,instruction:$.instruction})),e.maxTargets),Le();let p=Se(),x=je(),I=p?.marker!==void 0;s?n.showSelection(x,I,H()):n.updateSelection(x,I,H())}function Ee(){if(!H())return;let s=A.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let x=[...p.apiStatus==="failed"?["Source context could not be loaded."]:[],...p.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:p.instruction.trim(),source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:x}});return Jt({id:c(),locale:n.locale(),createdAt:S(),page:Jn(o.document,o.window),targets:s})}function Ne(s){n.showHighlight(zt(s,o.window),Ht(s))}function Ue(){y?.isConnected===!0&&y.focus({preventScroll:!0}),y=void 0}function oe(){for(let s of W.values())o.window.clearTimeout(s);W.clear()}function Q(){L+=1,i.cancelPending(),k.disposeSelection(),oe(),E?.disconnect(),A=[],R=void 0,B=!1,f="",n.hideSelection(),n.hideSelectionHighlights(),Ue()}function K(){u.status==="inspecting"?T({type:"CANCEL"}):u.status==="selected"?T({type:"CLOSE"}):u.status==="previewing"&&(T({type:"BACK"}),T({type:"CLOSE"})),Q(),n.hideHighlight()}function ee(){if(u.status!=="inspecting"||!B||A.length===0){K();return}B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.focusTargetInstruction(R),n.announce(n.messages().announcements.addCancelled)}function re(){if(u.status==="inspecting"&&B){ee();return}if(u.status!=="idle"){K();return}T({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Pe(s=n.messages().announcements.chooseAnother){u.status==="selected"&&(T({type:"RESELECT"}),Q(),n.hideHighlight(),n.announce(s))}function _e(){if(u.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}B=!0,T({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function be(){L+=1,oe(),E?.disconnect();for(let s of A)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),z(),n.announce(n.messages().announcements.appliedTargetsDetached)}let k=Wn({ai:e.ai,api:i,getAnnotation:Ee,onApplied:be,onReselectRequired(){Pe(n.messages().announcements.reselectAfterChange)},view:n});async function O(s,p){let x=s.marker;if(x!==void 0)try{let I=await i.sourceContext({fileId:x.fileId,line:x.line,column:x.column,maxLines:e.budget.maxCodeLines});me(s,p)&&(s.code=I,s.apiStatus="connected",z(),n.announce(n.messages().announcements.sourceLoaded))}catch(I){me(s,p)&&(s.code=void 0,s.apiStatus="failed",z(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(I instanceof DOMException&&I.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Be(s,p){let x=s.element;if(x===void 0)return;let I=o.window.setTimeout(()=>{if(W.delete(s.id),!me(s,p))return;let $=!1;try{s.elementContext=yn({element:x,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,$=!0}try{s.styles=un({document:o.document,element:x,maxCharacters:e.budget.cssCharacters})}catch{s.styles=$r,$=!0}s.collectionStatus=$?"failed":"ready",z(),n.announce($?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&s.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(s.styles.warnings.length)} warning(s).`)},0);W.set(s.id,I)}function Ae(s,p){return p!==void 0?A.find(x=>x.marker?.fileId===p.fileId&&x.marker.line===p.line&&x.marker.column===p.column):A.find(x=>x.element===s)}function He(s){let p=C.resolve(s),x=kn(p.source),I=Ae(s,x);if(I!==void 0){R=I.id,B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.focusTargetInstruction(I.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){B=!1,T({type:"SELECT"}),n.hideHighlight(),z(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}A.length===0&&(y=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,f="",k.beginSelection()),D+=1;let g={id:`target-${String(D)}`,element:s,resolution:p,marker:x,code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:x===void 0?"not-required":"loading",collectionStatus:"loading"};A.push(g),R=g.id,B=!1;let w=L;T({type:"SELECT"}),n.hideHighlight(),E?.observe(s),z(!0),n.focusTargetInstruction(g.id),Be(g,w),x!==void 0?O(g,w):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Y(){if(b=void 0,u.status!=="inspecting"||N===void 0)return;let s=jt(o.document,o.window,N.x,N.y);if(T({type:"HOVER"}),s===void 0){n.hideHighlight();return}Ne(s)}function X(s){u.status==="inspecting"&&(N={x:s.clientX,y:s.clientY},b??=o.window.requestAnimationFrame(Y))}function Ce(s){if(u.status!=="inspecting"||Cn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let p=jt(o.document,o.window,s.clientX,s.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}He(p)}function ae(s){if(s.key==="Escape"&&u.status!=="idle"){s.preventDefault(),u.status==="inspecting"&&B?ee():u.status==="inspecting"||u.status==="selected"?K():(T({type:"BACK"}),n.focusTargetInstruction(R));return}Sn(s.target)||!En(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),re())}function te(s){if(u.status!=="selected"&&u.status!=="inspecting")return;let p=A.findIndex($=>$.id===s);if(p<0)return;let[x]=A.splice(p,1);if(x===void 0)return;let I=W.get(x.id);if(I!==void 0&&(o.window.clearTimeout(I),W.delete(x.id)),x.element!==void 0&&E?.unobserve(x.element),R===x.id&&(R=A.at(-1)?.id),A.length===0){B=!0,u.status==="selected"&&T({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),n.announce(n.messages().announcements.allTargetsRemoved);return}z(),n.announce(n.messages().announcements.targetRemoved)}function le(){if(u.status==="idle"||A.length===0)return;let s=A.filter(p=>p.element!==void 0&&!p.element.isConnected);if(s.length>0){u.status==="previewing"&&T({type:"BACK"});for(let p of s)te(p.id);A.length>0&&n.announce(n.messages().announcements.detachedTargetRemoved);return}Le()}function ke(s){let p=s===void 0?Se():A.find(g=>g.id===s);if(u.status!=="selected"||p?.marker===void 0)return;R!==p.id&&(R=p.id,z());let x=p.marker,I=L,$=++Z;T({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:x.fileId,line:x.line,column:x.column}).then(()=>{_&&u.status==="selected"&&I===L&&$===Z&&R===p.id&&A.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{_&&u.status==="selected"&&I===L&&$===Z&&R===p.id&&A.includes(p)&&n.renderEditorStatus("error")})}function Re(s){if(u.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,x=A.find(I=>I.id===p);x!==void 0&&(x.instruction=s.target.value,n.updateTargetInstruction(x.id,x.instruction),n.setPreviewEnabled(H()))}function ie(){ke()}function Te(s){e.ai.enabled&&u.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),k.run())}function ve(){if(u.status!=="selected")return;let s=Ee();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}f=r.compose(s),T({type:"PREVIEW"}),n.showPreview(f),n.focusPrompt()}function se(){if(u.status!=="previewing"||f.length===0)return;if(a===void 0){T({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=L;a.writeText(f).then(()=>{_&&s===L&&u.status==="previewing"&&(T({type:"COPY_SUCCESS"}),n.focusTargetInstruction(R),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{_&&s===L&&u.status==="previewing"&&(T({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Me(){u.status==="previewing"&&(T({type:"BACK"}),n.focusTargetInstruction(R))}function De(){if(!(!_||A.length===0)&&(z(),u.status==="previewing")){let s=Ee();s!==void 0&&(f=r.compose(s),n.showPreview(f))}}function ye(s){let p=s.target;if(!(p instanceof Element))return;let x=p.closest("button[data-remove-target-id]");if(x?.dataset.removeTargetId!==void 0){te(x.dataset.removeTargetId);return}let I=p.closest("button[data-open-target-id]");if(I?.dataset.openTargetId!==void 0){ke(I.dataset.openTargetId);return}let g=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||g===void 0||!A.some(w=>w.id===g)||(R=g,z(),n.focusTargetInstruction(g))}function de(){Pe()}function V(){_||(_=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",X,!0),o.document.addEventListener("click",Ce,!0),o.document.addEventListener("keydown",ae,!0),o.window.addEventListener("scroll",le,!0),o.window.addEventListener("resize",le),n.triggerButton.addEventListener("click",re),n.addTargetButton.addEventListener("click",_e),n.reselectButton.addEventListener("click",de),n.targetList.addEventListener("click",ye),n.targetList.addEventListener("input",Re),n.targetList.addEventListener("keydown",Te),n.openEditorButton.addEventListener("click",ie),n.previewButton.addEventListener("click",ve),n.copyButton.addEventListener("click",se),n.backButton.addEventListener("click",Me),n.closeButton.addEventListener("click",K),n.agentProviderSelect.addEventListener("change",k.providerOrModelChanged),n.agentModelSelect.addEventListener("change",k.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",k.consentChanged),n.agentTestButton.addEventListener("click",k.testCapability),n.agentRunButton.addEventListener("click",k.run),n.agentCancelButton.addEventListener("click",k.cancel),n.agentApplyButton.addEventListener("click",k.apply),n.agentRevertButton.addEventListener("click",k.revert),n.agentResetButton.addEventListener("click",k.reset),U=n.subscribeLocale(De),o.resizeObserver!==void 0&&(E=new o.resizeObserver(le)),o.mutationObserver!==void 0&&(P=new o.mutationObserver(le),P.observe(o.document.documentElement,{childList:!0,subtree:!0})),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function Ye(){if(!_){U?.(),U=void 0,n.dispose(),i.cancelPending(),i.dispose(),k.disposeSelection(),C.dispose();return}_=!1,U?.(),U=void 0,o.document.removeEventListener("pointermove",X,!0),o.document.removeEventListener("click",Ce,!0),o.document.removeEventListener("keydown",ae,!0),o.window.removeEventListener("scroll",le,!0),o.window.removeEventListener("resize",le),n.triggerButton.removeEventListener("click",re),n.addTargetButton.removeEventListener("click",_e),n.reselectButton.removeEventListener("click",de),n.targetList.removeEventListener("click",ye),n.targetList.removeEventListener("input",Re),n.targetList.removeEventListener("keydown",Te),n.openEditorButton.removeEventListener("click",ie),n.previewButton.removeEventListener("click",ve),n.copyButton.removeEventListener("click",se),n.backButton.removeEventListener("click",Me),n.closeButton.removeEventListener("click",K),n.agentProviderSelect.removeEventListener("change",k.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",k.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",k.consentChanged),n.agentTestButton.removeEventListener("click",k.testCapability),n.agentRunButton.removeEventListener("click",k.run),n.agentCancelButton.removeEventListener("click",k.cancel),n.agentApplyButton.removeEventListener("click",k.apply),n.agentRevertButton.removeEventListener("click",k.revert),n.agentResetButton.removeEventListener("click",k.reset),b!==void 0&&(o.window.cancelAnimationFrame(b),b=void 0),oe(),E?.disconnect(),P?.disconnect(),E=void 0,P=void 0,A=[],R=void 0,f="",N=void 0,y=void 0,i.cancelPending(),i.dispose(),k.disposeSelection(),C.dispose(),n.dispose(),u=Bt}return Object.freeze({mount:V,dispose:Ye,getState:()=>u})}var Kn="__spotpatchRuntime__";function Gt(e){let t=globalThis;t[Kn]?.dispose();let o=Fn(e);t[Kn]=o,o.mount()}Gt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
886
+ `)}function ee(){let a=b.flatMap(c=>c.element?.isConnected?[{id:c.id,label:Ft(c.element),rect:Ht(c.element,o.window),active:c.id===x}]:[]);a.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(a)}function N(a=!1){if(b.length===0)return;n.renderTargets(b.map(z=>({id:z.id,label:z.resolution.react.componentName??(z.element===void 0?z.elementContext?.tagName??"Element":Ft(z.element)),source:na(z,n.messages().context.sourceUnavailable),canOpenEditor:z.marker!==void 0,status:oa(z),active:z.id===x,instruction:z.instruction})),e.maxTargets),ee();let c=Pe(),h=me(),w=c?.marker!==void 0;a?n.showSelection(h,w,Re()):n.updateSelection(h,w,Re())}function K(){if(!Re())return;let a=b.map(c=>{if(c.elementContext===void 0||c.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let h=[...c.apiStatus==="failed"?["Source context could not be loaded."]:[],...c.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:c.instruction.trim(),page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code},warnings:h}});return Zt({id:l(),locale:n.locale(),createdAt:E(),page:qt(o.document,o.window),targets:a})}function be(a){n.showHighlight(Ht(a,o.window),Ft(a))}function Le(){G?.isConnected===!0&&G.focus({preventScroll:!0}),G=void 0}function ve(){for(let a of B.values())o.window.clearTimeout(a);B.clear()}function ye(){y+=1,s.cancelPending(),T.disposeSelection(),ve(),$?.disconnect(),b=[],x=void 0,q=!1,f=!1,v=!1,D="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),Le()}function re(){u.status==="inspecting"?L({type:"CANCEL"}):u.status==="selected"?L({type:"CLOSE"}):u.status==="previewing"&&(L({type:"BACK"}),L({type:"CLOSE"})),q=!1,F(),n.hideSelection(),n.hideSelectionHighlights(),Le(),n.hideHighlight()}function _(){if(u.status!=="inspecting"||!v||b.length===0){re();return}v=!1,L({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(x),n.announce(n.messages().announcements.addCancelled)}function ke(){if(u.status==="inspecting"&&v){_();return}if(u.status!=="idle"){re();return}if(b.length>0){q=!0,L({type:"RESTORE"}),f||(T.beginSelection(),f=!0),N(!0),n.focusTargetInstruction(x),F();return}L({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function Se(a=n.messages().announcements.chooseAnother){u.status==="selected"&&(L({type:"RESELECT"}),ye(),n.hideHighlight(),n.announce(a))}function Me(){if(u.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}v=!0,L({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function Y(){y+=1,ve(),$?.disconnect();for(let a of b)a.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),N(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let T=Qn({ai:e.ai,api:s,getAnnotation:K,onApplied:Y,onReselectRequired(){Se(n.messages().announcements.reselectAfterChange)},view:n});async function Te(a,c){let h=a.marker;if(h!==void 0)try{let w=await s.sourceContext({fileId:h.fileId,line:h.line,column:h.column,maxLines:e.budget.maxCodeLines});Ce(a,c)&&(a.code=w,a.apiStatus="connected",F(),N(),n.announce(n.messages().announcements.sourceLoaded))}catch(w){Ce(a,c)&&(a.code=void 0,a.apiStatus="failed",F(),N(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(w instanceof DOMException&&w.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function le(a,c){let h=a.element;if(h===void 0)return;let w=o.window.setTimeout(()=>{if(B.delete(a.id),!Ce(a,c))return;let z=!1;try{a.elementContext=Rn({element:h,maxCharacters:e.budget.domCharacters})}catch{a.elementContext=void 0,z=!0}try{a.styles=yn({document:o.document,element:h,maxCharacters:e.budget.cssCharacters})}catch{a.styles=ta,z=!0}a.collectionStatus=z?"failed":"ready",F(),N(),n.announce(z?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&a.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(a.styles.warnings.length)} warning(s).`)},0);B.set(a.id,w)}function ae(a,c){return c!==void 0?b.find(h=>h.marker?.fileId===c.fileId&&h.marker.line===c.line&&h.marker.column===c.column):b.find(h=>h.element===a)}function De(a){let c=k.resolve(a),h=Jt(c.source),w=ae(a,h);if(w!==void 0){x=w.id,v=!1,L({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(w.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){v=!1,L({type:"SELECT"}),n.hideHighlight(),N(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(G=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,D="",T.beginSelection(),f=!0),Q+=1;let te={id:`target-${String(Q)}`,element:a,resolution:c,marker:h,page:qt(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:h===void 0?"not-required":"loading",collectionStatus:"loading"};b.push(te),x=te.id,v=!1;let p=y;L({type:"SELECT"}),n.hideHighlight(),$?.observe(a),N(!0),q=!0,n.focusTargetInstruction(te.id),le(te,p),h!==void 0?Te(te,p):n.announce(c.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function $e(){if(Z=void 0,u.status!=="inspecting"||I===void 0)return;let a=Ut(o.document,o.window,I.x,I.y);if(L({type:"HOVER"}),a===void 0){n.hideHighlight();return}be(a)}function Ae(a){u.status==="inspecting"&&(I={x:a.clientX,y:a.clientY},Z??=o.window.requestAnimationFrame($e))}function ie(a){if(u.status!=="inspecting"||_n(a.target))return;a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation();let c=Ut(o.document,o.window,a.clientX,a.clientY);if(c===void 0){n.announce(n.messages().announcements.noSelectable);return}De(c)}function we(a){if(a.key==="Escape"&&u.status!=="idle"){a.preventDefault(),u.status==="inspecting"&&v?_():u.status==="inspecting"||u.status==="selected"?re():(L({type:"BACK"}),n.focusTargetInstruction(x));return}Tn(a.target)||!wn(a,e.shortcut,o.window.navigator.userAgent)||(a.preventDefault(),ke())}function Oe(a){if(u.status!=="selected"&&u.status!=="inspecting")return;let c=b.findIndex(z=>z.id===a);if(c<0)return;let[h]=b.splice(c,1);if(h===void 0)return;let w=B.get(h.id);if(w!==void 0&&(o.window.clearTimeout(w),B.delete(h.id)),h.element!==void 0&&$?.unobserve(h.element),x===h.id&&(x=b.at(-1)?.id),b.length===0){v=!0,u.status==="selected"&&L({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}N(),F(),n.announce(n.messages().announcements.targetRemoved)}function V(){if(u.status==="idle"||b.length===0)return;let a=b.filter(c=>c.element!==void 0&&!c.element.isConnected);if(a.length>0){for(let c of a)c.element!==void 0&&($?.unobserve(c.element),c.element=void 0);N(),F(),n.announce(n.messages().announcements.detachedTargetPreserved);return}ee()}function ze(a){let c=a===void 0?Pe():b.find(te=>te.id===a);if(u.status!=="selected"||c?.marker===void 0)return;x!==c.id&&(x=c.id,N());let h=c.marker,w=y,z=++C;L({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:h.fileId,line:h.line,column:h.column}).then(()=>{P&&u.status==="selected"&&w===y&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("success")}).catch(()=>{P&&u.status==="selected"&&w===y&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("error")})}function Ie(a){if(u.status!=="selected"||!(a.target instanceof HTMLTextAreaElement))return;let c=a.target.dataset.targetInstructionId,h=b.find(w=>w.id===c);h!==void 0&&(h.instruction=a.target.value,n.updateTargetInstruction(h.id,h.instruction),n.setPreviewEnabled(Re()),F())}function xe(){ze()}function pe(a){e.ai.enabled&&u.status==="selected"&&a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),T.run())}function U(){if(u.status!=="selected")return;let a=K();if(a===void 0){n.announce(n.messages().announcements.completeInstructions);return}D=r.compose(a),L({type:"PREVIEW"}),n.showPreview(D),n.focusPrompt()}function qe(){if(u.status!=="previewing"||D.length===0)return;if(i===void 0){L({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let a=y;i.writeText(D).then(()=>{P&&a===y&&u.status==="previewing"&&(L({type:"COPY_SUCCESS"}),n.focusTargetInstruction(x),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{P&&a===y&&u.status==="previewing"&&(L({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Ue(){u.status==="previewing"&&(L({type:"BACK"}),n.focusTargetInstruction(x))}function rt(){if(!(!P||b.length===0)&&(N(),u.status==="previewing")){let a=K();a!==void 0&&(D=r.compose(a),n.showPreview(D))}}function Fe(a){let c=a.target;if(!(c instanceof Element))return;let h=c.closest("button[data-remove-target-id]");if(h?.dataset.removeTargetId!==void 0){Oe(h.dataset.removeTargetId);return}let w=c.closest("button[data-open-target-id]");if(w?.dataset.openTargetId!==void 0){ze(w.dataset.openTargetId);return}let te=c.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||te===void 0||!b.some(p=>p.id===te)||(x=te,N(),n.focusTargetInstruction(te))}function Ke(){Se()}function st(){P||(P=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Ae,!0),o.document.addEventListener("click",ie,!0),o.document.addEventListener("keydown",we,!0),o.window.addEventListener("scroll",V,!0),o.window.addEventListener("resize",V),n.triggerButton.addEventListener("click",ke),n.addTargetButton.addEventListener("click",Me),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",Fe),n.targetList.addEventListener("input",Ie),n.targetList.addEventListener("keydown",pe),n.openEditorButton.addEventListener("click",xe),n.previewButton.addEventListener("click",U),n.copyButton.addEventListener("click",qe),n.backButton.addEventListener("click",Ue),n.closeButton.addEventListener("click",re),n.agentProviderSelect.addEventListener("change",T.providerOrModelChanged),n.agentModelSelect.addEventListener("change",T.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",T.consentChanged),n.agentTestButton.addEventListener("click",T.testCapability),n.agentRunButton.addEventListener("click",T.run),n.agentCancelButton.addEventListener("click",T.cancel),n.agentApplyButton.addEventListener("click",T.apply),n.agentRevertButton.addEventListener("click",T.revert),n.agentResetButton.addEventListener("click",T.reset),oe=n.subscribeLocale(rt),o.resizeObserver!==void 0&&($=new o.resizeObserver(V)),o.mutationObserver!==void 0&&(de=new o.mutationObserver(V),de.observe(o.document.documentElement,{childList:!0,subtree:!0})),q&&b.length>0&&(L({type:"RESTORE"}),T.beginSelection(),f=!0,N(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function m(){if(!P){oe?.(),oe=void 0,n.dispose(),s.cancelPending(),s.dispose(),T.disposeSelection(),k.dispose();return}P=!1,oe?.(),oe=void 0,o.document.removeEventListener("pointermove",Ae,!0),o.document.removeEventListener("click",ie,!0),o.document.removeEventListener("keydown",we,!0),o.window.removeEventListener("scroll",V,!0),o.window.removeEventListener("resize",V),n.triggerButton.removeEventListener("click",ke),n.addTargetButton.removeEventListener("click",Me),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",Fe),n.targetList.removeEventListener("input",Ie),n.targetList.removeEventListener("keydown",pe),n.openEditorButton.removeEventListener("click",xe),n.previewButton.removeEventListener("click",U),n.copyButton.removeEventListener("click",qe),n.backButton.removeEventListener("click",Ue),n.closeButton.removeEventListener("click",re),n.agentProviderSelect.removeEventListener("change",T.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",T.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",T.consentChanged),n.agentTestButton.removeEventListener("click",T.testCapability),n.agentRunButton.removeEventListener("click",T.run),n.agentCancelButton.removeEventListener("click",T.cancel),n.agentApplyButton.removeEventListener("click",T.apply),n.agentRevertButton.removeEventListener("click",T.revert),n.agentResetButton.removeEventListener("click",T.reset),Z!==void 0&&(o.window.cancelAnimationFrame(Z),Z=void 0),ve(),F(),$?.disconnect(),de?.disconnect(),$=void 0,de=void 0,b=[],x=void 0,D="",I=void 0,G=void 0,s.cancelPending(),s.dispose(),T.disposeSelection(),k.dispose(),n.dispose(),u=Vt}return Object.freeze({mount:st,dispose:m,getState:()=>u})}var oo="__spotpatchRuntime__";function Kt(e){let t=globalThis;t[oo]?.dispose();let o=no(e);t[oo]=o,o.mount()}Kt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Ve});