@spotpatch/vite 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,40 +1,40 @@
1
- import{createReact18Adapter as Qi}from"@spotpatch/react-adapter";var p={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",DATA_FLOW_DISABLED:"DATA_FLOW_DISABLED",DATA_FLOW_SOURCE_STALE:"DATA_FLOW_SOURCE_STALE",DATA_FLOW_ANALYSIS_CANCELLED:"DATA_FLOW_ANALYSIS_CANCELLED",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",EXTERNAL_HANDOFF_DISABLED:"EXTERNAL_HANDOFF_DISABLED",EXTERNAL_HANDOFF_UNAVAILABLE:"EXTERNAL_HANDOFF_UNAVAILABLE",HANDOFF_VALIDATION_FAILED:"HANDOFF_VALIDATION_FAILED",HANDOFF_SOURCE_STALE:"HANDOFF_SOURCE_STALE",HANDOFF_NOT_FOUND:"HANDOFF_NOT_FOUND",HANDOFF_EXPIRED:"HANDOFF_EXPIRED",HANDOFF_CURSOR_INVALID:"HANDOFF_CURSOR_INVALID",HANDOFF_RESPONSE_TOO_LARGE:"HANDOFF_RESPONSE_TOO_LARGE",BRIDGE_UNAUTHORIZED:"BRIDGE_UNAUTHORIZED",BRIDGE_PROTOCOL_MISMATCH:"BRIDGE_PROTOCOL_MISMATCH",BRIDGE_BUSY:"BRIDGE_BUSY",EXTERNAL_AGENT_BUSY:"EXTERNAL_AGENT_BUSY",ACTIVE_ADAPTER_CONFLICT:"ACTIVE_ADAPTER_CONFLICT",ACTIVE_ADAPTER_LEASE_INVALID:"ACTIVE_ADAPTER_LEASE_INVALID",ACTIVE_DISPATCH_INVALID:"ACTIVE_DISPATCH_INVALID",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_AMBIGUOUS:"SESSION_AMBIGUOUS",SESSION_CLOSED:"SESSION_CLOSED",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"},Ir=Object.freeze(Object.values(p));var Nr=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,kr=/blob:[^\s"'<>]+/giu,Dr=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Fr=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Mr=/\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,Hr=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),$r=500;function Br(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function zr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Zt(e){let t=Br(e);return Hr.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function ee(e){return e.replace(Nr,"[redacted inline data]").replace(kr,"[redacted blob URL]").replace(Dr,"Bearer [redacted]").replace(Fr,"$1[redacted]@").replace(Mr,(t,o,n,s)=>{let d=s.at(0),i=d==='"'||d==="'"||d==="`";return`${o}${n}${i?d:""}[redacted]${i?d:""}`})}function jr(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Zt(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,ee(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Tt(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=ee(o);try{let s=new URL(n,t),d=jr(s),i=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===i.origin?`${s.pathname}${s.search}${s.hash}`:d}catch{return zr(n,$r)}}var ce="/__spotpatch/v1",Qt="X-SpotPatch-Token",gt=Object.freeze({bootstrap:`${ce}/bootstrap`,sourceContext:`${ce}/source-context`,openEditor:`${ce}/open-editor`,dataFlowComponentReport:`${ce}/data-flow/component-report`,dataFlowPageReport:`${ce}/data-flow/page-report`,agentCapability:`${ce}/agent/capability`,agentWorkspaceHealth:`${ce}/agent/workspace-health`,agentJobs:`${ce}/agent/jobs`,externalHandoffCapability:`${ce}/external-handoff/capability`,externalHandoffPublish:`${ce}/external-handoff/publish`,externalHandoffStatus:`${ce}/external-handoff/status`,externalHandoffResolveDelivery:`${ce}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${ce}/external-agent/control/status`,externalAgentControlConnect:`${ce}/external-agent/control/connect`,externalAgentControlDisconnect:`${ce}/external-agent/control/disconnect`,externalAgentControlCancel:`${ce}/external-agent/control/cancel`,externalAgentEvents:`${ce}/external-agent/events`,externalAgentResult:`${ce}/external-agent/result`});function It(e,t){return`${gt.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ur=Object.freeze(["review","auto","trusted-auto"]),Vr=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}),Sn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),En=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Wr=Object.freeze(["ready","consent-required","blocked"]),Gr=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),An=Object.freeze(["added","modified","deleted"]),xn=Object.freeze(["passed","failed","cancelled","timed-out"]);var Rn="data-spotpatch-source",qr=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Cn(e){if(e===null)return;let t=qr.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 Tn="https://github.com/huanglvjing/spotpatch";function oo(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function Jr(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:oo(e.source)}})}function Xr(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Yr(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 Zr(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:oo(e.source,e.code),react:Jr(e.react),element:Xr(e.element),styles:Yr(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function ro(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(Zr)),createdAt:e.createdAt})}var Qr=new Set(Object.values(p)),ea=new Set(En),ta=new Set(xn),na=new Set(An),io=new Set(Sn),oa=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,ra=/^[A-Za-z0-9_-]+$/,aa=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function Se(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function zt(e){return Se(e,64,1)&&typeof e=="string"&&oa.test(e)}function vn(e){return Se(e,128,22)&&typeof e=="string"&&ra.test(e)}function jt(e){return typeof e=="string"&&aa.test(e)&&Number.isFinite(Date.parse(e))}function vt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function so(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ao(e,t){return e===void 0||Se(e,t)}function Ft(e){return typeof e=="string"&&Qr.has(e)}function co(e){return!ft(e)||!Fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:zt(e.providerProfileId)&&Se(e.providerLabel,100)&&zt(e.modelProfileId)&&Se(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&ea.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||jt(e.checkedAt))&&(e.errorCode===void 0||Ft(e.errorCode))}function lo(e){if(!ft(e)||!Fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!jt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Ft(e.errorCode)||!ft(e.changes)||!Fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:d,total:i}=t;return!vt(o)||!vt(n)||!vt(s)||!vt(d)||!vt(i)||i<o||i<n||i<s||i<d||i>o+n+s?!1:e.state==="ready"?i===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?i>0&&d===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function tn(e){return!ft(e)||!Fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:vn(e.jobId)&&typeof e.status=="string"&&io.has(e.status)&&zt(e.providerProfileId)&&Se(e.providerLabel,100)&&zt(e.modelProfileId)&&Se(e.modelLabel,100)&&Se(e.phaseMessage,1024)&&jt(e.createdAt)&&jt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Ft(e.errorCode))}function ia(e){return ft(e)&&Fe(e,["relativePath","kind","additions","deletions"])&&Se(e.relativePath,1024)&&typeof e.kind=="string"&&na.has(e.kind)&&vt(e.additions)&&vt(e.deletions)}function po(e){return ft(e)&&Fe(e,["checkId","label","status","durationMs","output"])&&zt(e.checkId)&&Se(e.label,100)&&typeof e.status=="string"&&ta.has(e.status)&&vt(e.durationMs)&&Se(e.output,8e4)}function sa(e){return ft(e)&&Fe(e,["jobId","summary","diff","files","checks"])&&vn(e.jobId)&&Se(e.summary,8e4)&&Se(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ia)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(po)}function uo(e){return ft(e)&&Fe(e,["snapshot","result"])&&tn(e.snapshot)&&(e.result===void 0||sa(e.result)&&e.result.jobId===e.snapshot.jobId)}function ca(e){return ft(e)&&Fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&so(e.sequence)&&vn(e.jobId)&&typeof e.status=="string"&&io.has(e.status)&&jt(e.timestamp)&&typeof e.type=="string"&&ft(e.data)}function go(e){if(!ca(e))return!1;let t=e.data;switch(e.type){case"snapshot":return Fe(t,["snapshot"])&&tn(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Fe(t,["message"])&&Se(t.message,1024);case"tool":return Fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&so(t.turn)&&Se(t.toolCallId,256)&&Se(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&ao(t.relativePath,1024)&&ao(t.checkLabel,100);case"check":return Fe(t,["result"])&&po(t.result);case"result-ready":return Fe(t,["hasResult"])&&t.hasResult===!0;case"error":return Fe(t,["code","message"])&&Ft(t.code)&&Se(t.message,1024);default:return!1}}var ho=2e6,fo=1e5,da=4e6,q=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function la(e){if(!(!Me(e)||e.ok!==!1||!Me(e.error)))return Ft(e.error.code)?e.error.code:void 0}function pa(e){if(!Me(e)||e.ok!==!0||!("data"in e))throw new q;return e.data}function ua(e){return Me(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 yo(e){if(!(!Me(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))yo(t);Object.freeze(e)}}function Nt(e){return yo(e),e}async function ga(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new q;if(e.body===null)throw new q;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),d=0,i="";try{for(;;){let l=await n.read();if(l.done)return i+=s.decode(),i;if(d+=l.value.byteLength,d>t)throw await n.cancel(),new q;i+=s.decode(l.value,{stream:!0})}}catch(l){throw l instanceof q?l:new q}finally{n.releaseLock()}}function bo(e){try{return JSON.parse(e)}catch{throw new q}}async function mo(e,t=ho){let o=bo(await ga(e,t));if(!e.ok)throw new q(la(o));return pa(o)}function on(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function fa(e){return Me(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function ma(e){return Me(e)&&typeof e.enabled=="boolean"&&(e.staticAnalysis==="available"||e.staticAnalysis==="partial"||e.staticAnalysis==="unavailable")&&e.runtimeObservation==="dispatch-only"&&e.responseShape==="consumed-fields-only"&&e.aiAssistance==="disabled"&&Array.isArray(e.reasons)}function ha(e){return Me(e)&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.direction=="string"&&typeof e.execution=="string"&&typeof e.proof=="string"&&typeof e.association=="string"&&Array.isArray(e.parameters)&&Me(e.response)&&on(e.response.consumedFields)&&on(e.evidenceIds)&&on(e.observationIds)}function So(e){return Me(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Me(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&on(e.baseline.analyzedSourceVersions)&&ma(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(ha)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&fa(e.completeness)}function ya(e){return So(e)&&Me(e)&&Me(e.component)&&Me(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function ba(e){return So(e)}function Sa(e,t){if(!co(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new q;return Nt(e)}function nn(e,t){if(!tn(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 q;return Nt(e)}function Ea(e,t){if(!uo(e)||e.snapshot.jobId!==t)throw new q;return Nt(e)}function Aa(e){if(!go(e))throw new q;return Nt(e)}function xa(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 Eo(e){return e instanceof q?e.code:void 0}function Ao(e){let t=new Set;function o(){for(let i of t)i.abort();t.clear()}async function n(i,l,A,w=ho){let T=new AbortController;t.add(T);try{let N=await e.fetch(i,{method:l,headers:{...A===void 0?{}:{"Content-Type":"application/json"},[Qt]:e.sessionToken},...A===void 0?{}:{body:JSON.stringify(A)},signal:T.signal});return await mo(N,w)}finally{t.delete(T)}}async function s(i,l){let A=new AbortController;t.add(A);try{let w=await e.fetch(It(i,"events"),{method:"POST",headers:{"Content-Type":"application/json",[Qt]:e.sessionToken},body:JSON.stringify({}),signal:A.signal});if(!w.ok){await mo(w);return}if(w.body===null)throw new q;let T=w.body.getReader(),N=new TextDecoder("utf-8",{fatal:!0}),r="",F=0,M=0,I=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>fo)throw new q;let x=Aa(bo(b));if(x.jobId!==i||x.sequence<=M)throw new q;M=x.sequence,l(x)};try{for(;;){let b=await T.read();if(b.done){r+=N.decode(),I(r);return}if(F+=b.value.byteLength,F>da)throw await T.cancel(),new q;r+=N.decode(b.value,{stream:!0});let x=r.split(`
2
- `);if(r=x.pop()??"",new TextEncoder().encode(r).byteLength>fo)throw await T.cancel(),new q;for(let K of x)I(K)}}catch(b){throw b instanceof q||b instanceof DOMException&&b.name==="AbortError"?b:new q}finally{T.releaseLock()}}finally{t.delete(A)}}let d=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(i){let l=await n(gt.sourceContext,"POST",i);if(!ua(l))throw new q;return Object.freeze({...l})},async componentDataFlowReport(i){let l=await n(gt.dataFlowComponentReport,"POST",i,e.dataFlowReportMaxBytes);if(!ya(l))throw new q;return Nt(l)},async pageDataFlowReport(i){let l=await n(gt.dataFlowPageReport,"POST",i,e.dataFlowReportMaxBytes);if(!ba(l))throw new q;return Nt(l)},async openEditor(i){let l=await n(gt.openEditor,"POST",i);if(!Me(l)||l.editor!=="auto"&&l.editor!=="vscode"&&l.editor!=="cursor")throw new q;return Object.freeze({editor:l.editor})},async agentCapability(i){return Sa(await n(gt.agentCapability,"POST",i),i)},async agentWorkspaceHealth(){let i=await n(gt.agentWorkspaceHealth,"POST",d);if(!lo(i))throw new q;return Nt(i)},async createAgentJob(i){let l=xa(i);return nn(await n(gt.agentJobs,"POST",l),i)},agentEvents:s,async agentResult(i){return Ea(await n(It(i,"result"),"POST",d),i)},async cancelAgentJob(i){return nn(await n(It(i,"cancel"),"POST",d),{jobId:i})},async applyAgentJob(i){return nn(await n(It(i,"apply"),"POST",d),{jobId:i})},async revertAgentJob(i){return nn(await n(It(i,"revert"),"POST",d),{jobId:i})},dispose(){o()}})}var Ra=500,xo=256;function Ca(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ta(e){return Zt(e)}function Ro(e,t,o){if(!Ta(e))return e==="href"||e==="src"?Tt(t,o):e==="d"&&t.length>xo?`${t.slice(0,xo)}…`:Ca(ee(t),Ra)}function Ve(e){return ee(e)}var Co=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 Ut=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 va(e){return"selectorText"in e&&"style"in e}function wa(e){return"cssRules"in e}function Oa(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 _a(e,t,o,n,s){return e.join(" ").length+(t?.length??0)+o.reduce((d,i)=>d+i.selector.length+i.declarations.length+(i.source?.length??0)+(i.media?.length??0),0)+Object.entries(n).reduce((d,[i,l])=>d+i.length+l.length,0)+s.join(`
3
- `).length}function La(e,t){return e.href===null?void 0:Tt(e.href,t)}function To(e,t,o,n,s,d){for(let i of t){if(va(i)){let l=!1;try{l=e.matches(i.selectorText)}catch{d.add(Ut.selector);continue}l&&s.push(Object.freeze({selector:Ve(i.selectorText),declarations:Ve(i.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(wa(i)){let l=Oa(i);To(e,i.cssRules,o,l===void 0?n:[...n,l],s,d)}}}function Pa(e,t){if(t===void 0)return{};let o=t(e),n={};for(let s of Co){let d=Ve(o.getPropertyValue(s).trim());d.length>0&&(n[s]=d)}return n}function vo(e){let t=new Set([Ut.state,Ut.cssInJs,Ut.cascade]),o=[],n=e.readCssRules??(T=>T.cssRules);for(let T of e.document.styleSheets){let N;try{N=n(T)}catch{t.add(Ut.inaccessibleStylesheet);continue}To(e.element,N,La(T,e.document.baseURI),[],o,t)}let s=Array.from(e.element.classList),d=e.element.getAttribute("style"),i=d===null?void 0:Ve(d),l=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),A=Object.entries(Pa(e.element,l)),w=Array.from(t);for(;_a(s,i,o,Object.fromEntries(A),w)>e.maxCharacters;){if(A.length>0){A.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(A)),warnings:Object.freeze(w)})}var wt=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Ia=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"]),Na=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Oo(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function ka(e){return Ia.has(e)||e.startsWith("aria-")||e==="data-testid"}function _o(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let s of e.attributes){let d=s.name.toLowerCase();if(!ka(d))continue;let i=Ro(d,s.value,n);i!==void 0&&o.push(`${d}="${Oo(i)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Lo(e){return ee(e).replaceAll(/\s+/gu," ").trim()}function Po(e,t,o,n){if(o.nodeCount>=wt.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let s=" ".repeat(t),d=e.tagName.toLowerCase();if(n.push(`${s}${_o(e)}`),!Na.has(d)){for(let i of e.childNodes){if(o.nodeCount>=wt.maxNodes){o.truncated=!0;break}if(i.nodeType===3){let l=Lo(i.textContent??"");if(l.length>0){o.nodeCount+=1;let A=l.length<=wt.maxTextCharacters?l:`${l.slice(0,wt.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Oo(A)}`)}continue}if(i.nodeType===1){if(t>=wt.maxDepth){o.truncated=!0;continue}Po(i,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${s}</${d}>`)}}function Da(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<wt.maxParentDepth;)t.push(_o(o)),o=o.parentElement;return t}function Fa(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function wo(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Ma(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ha(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${wo(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Ma(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(l=>`.${wo(l)}`).join(""),s=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(l=>l.tagName===e.tagName),d=s.indexOf(e),i=s.length>1&&d>=0?`:nth-of-type(${String(d+1)})`:"";return`${t}${n}${i}`}function $a(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Ha(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Io(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};Po(e.element,0,o,t);let n=Da(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let s=Lo(e.element.textContent),d=e.element.getBoundingClientRect(),i=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:$a(e.element),sanitizedHtml:Fa(t.join(`
4
- `),e.maxCharacters),...s.length===0?{}:{textPreview:s.length<=wt.maxTextCharacters?s:`${s.slice(0,wt.maxTextCharacters)}…`},...i===null?{}:{role:i},rect:Object.freeze({x:d.x,y:d.y,width:d.width,height:d.height})})}function No(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Ba(e){return e.toLowerCase()}function ko(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Do(e,t,o){let n=t.split("+").map(T=>T.trim().toLowerCase()).filter(T=>T.length>0),s=n.find(T=>T!=="mod"&&T!=="meta"&&T!=="ctrl"&&T!=="control"&&T!=="alt"&&T!=="option"&&T!=="shift");if(s===void 0||Ba(e.key)!==s)return!1;let d=n.includes("mod"),i=n.includes("meta")||d&&No(o),l=n.includes("ctrl")||n.includes("control")||d&&!No(o),A=n.includes("alt")||n.includes("option"),w=n.includes("shift");return e.metaKey===i&&e.ctrlKey===l&&e.altKey===A&&e.shiftKey===w}function za(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function ja(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,d=o.right,i=o.bottom;for(let l of t.slice(1))n=Math.min(n,l.left),s=Math.min(s,l.top),d=Math.max(d,l.right),i=Math.max(i,l.bottom);return Object.freeze({x:n,y:s,width:d-n,height:i-s})}function Fo(e,t){if(t.startsWith("inline")){let o=ja(Array.from(e.getClientRects()));if(o!==void 0)return o}return za(e.getBoundingClientRect())}function Mo(e,t){return Fo(e,t.getComputedStyle(e).display)}function an(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=Fo(e,o.display);return n.width>0&&n.height>0?n:void 0}var kt="data-spotpatch-ui",sn=Object.freeze({highlight:2147483646,controls:2147483647}),Ot=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function Ho(e){if(e.closest(`[${kt}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(kt)}function Ua(e,t){return an(e,t)!==void 0}function Va(e){return e.tagName==="HTML"||e.tagName==="BODY"}function wn(e,t,o,n){let s=e.elementsFromPoint(o,n).filter(d=>!Ho(d)&&Ua(d,t));return s.find(d=>!Va(d))??s[0]}function $o(e){return e instanceof Element&&Ho(e)}var On=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 Wa(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function cn(e,t){let o="`".repeat(Math.max(3,Wa(t)+1));return`${o}${e}
1
+ import{createReact18Adapter as ss}from"@spotpatch/react-adapter";var p={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",DATA_FLOW_DISABLED:"DATA_FLOW_DISABLED",DATA_FLOW_SOURCE_STALE:"DATA_FLOW_SOURCE_STALE",DATA_FLOW_ANALYSIS_CANCELLED:"DATA_FLOW_ANALYSIS_CANCELLED",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",EXTERNAL_HANDOFF_DISABLED:"EXTERNAL_HANDOFF_DISABLED",EXTERNAL_HANDOFF_UNAVAILABLE:"EXTERNAL_HANDOFF_UNAVAILABLE",HANDOFF_VALIDATION_FAILED:"HANDOFF_VALIDATION_FAILED",HANDOFF_SOURCE_STALE:"HANDOFF_SOURCE_STALE",HANDOFF_NOT_FOUND:"HANDOFF_NOT_FOUND",HANDOFF_EXPIRED:"HANDOFF_EXPIRED",HANDOFF_CURSOR_INVALID:"HANDOFF_CURSOR_INVALID",HANDOFF_RESPONSE_TOO_LARGE:"HANDOFF_RESPONSE_TOO_LARGE",BRIDGE_UNAUTHORIZED:"BRIDGE_UNAUTHORIZED",BRIDGE_PROTOCOL_MISMATCH:"BRIDGE_PROTOCOL_MISMATCH",BRIDGE_BUSY:"BRIDGE_BUSY",EXTERNAL_AGENT_BUSY:"EXTERNAL_AGENT_BUSY",ACTIVE_ADAPTER_CONFLICT:"ACTIVE_ADAPTER_CONFLICT",ACTIVE_ADAPTER_LEASE_INVALID:"ACTIVE_ADAPTER_LEASE_INVALID",ACTIVE_DISPATCH_INVALID:"ACTIVE_DISPATCH_INVALID",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_AMBIGUOUS:"SESSION_AMBIGUOUS",SESSION_CLOSED:"SESSION_CLOSED",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"},Hr=Object.freeze(["ASK_DISABLED","ASK_SELECTION_REQUIRED","ASK_SELECTION_STALE","ASK_QUESTION_INVALID","ASK_EXECUTOR_UNAVAILABLE","ASK_TIMEOUT","ASK_CONSENT_REQUIRED","ASK_BUSY","ASK_IDEMPOTENCY_CONFLICT","ASK_SOURCE_SCOPE_DENIED","ASK_LIMIT_EXCEEDED","ASK_ANSWER_INVALID","ASK_WRITE_ATTEMPTED","ASK_CANCELLED","ASK_RESULT_EXPIRED","ASK_PROTOCOL_INCOMPATIBLE"]),$r=Object.freeze(Object.values(p));var Br=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Ur=/blob:[^\s"'<>]+/giu,jr=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,zr=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Vr=/\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,Wr=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),qr=500;function Gr(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Kr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nn(e){let t=Gr(e);return Wr.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function oe(e){return e.replace(Br,"[redacted inline data]").replace(Ur,"[redacted blob URL]").replace(jr,"Bearer [redacted]").replace(zr,"$1[redacted]@").replace(Vr,(t,o,n,s)=>{let l=s.at(0),a=l==='"'||l==="'"||l==="`";return`${o}${n}${a?l:""}[redacted]${a?l:""}`})}function Jr(e){e.username="",e.password="";for(let[t,o]of e.searchParams)nn(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,oe(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function vt(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=oe(o);try{let s=new URL(n,t),l=Jr(s),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===a.origin?`${s.pathname}${s.search}${s.hash}`:l}catch{return Kr(n,qr)}}var ae="/__spotpatch/v1",on="X-SpotPatch-Token",ht=Object.freeze({bootstrap:`${ae}/bootstrap`,sourceContext:`${ae}/source-context`,openEditor:`${ae}/open-editor`,dataFlowComponentReport:`${ae}/data-flow/component-report`,dataFlowPageReport:`${ae}/data-flow/page-report`,agentCapability:`${ae}/agent/capability`,agentWorkspaceHealth:`${ae}/agent/workspace-health`,agentJobs:`${ae}/agent/jobs`,askCapability:`${ae}/ask/capability`,askJobs:`${ae}/ask/jobs`,externalHandoffCapability:`${ae}/external-handoff/capability`,externalHandoffPublish:`${ae}/external-handoff/publish`,externalHandoffStatus:`${ae}/external-handoff/status`,externalHandoffResolveDelivery:`${ae}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${ae}/external-agent/control/status`,externalAgentControlConnect:`${ae}/external-agent/control/connect`,externalAgentControlDisconnect:`${ae}/external-agent/control/disconnect`,externalAgentControlCancel:`${ae}/external-agent/control/cancel`,externalAgentEvents:`${ae}/external-agent/events`,externalAgentResult:`${ae}/external-agent/result`});function kt(e,t){return`${ht.agentJobs}/${encodeURIComponent(e)}/${t}`}var Xr=Object.freeze(["review","auto","trusted-auto"]),Yr=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}),vn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),wn=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Zr=Object.freeze(["ready","consent-required","blocked"]),Qr=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),On=Object.freeze(["added","modified","deleted"]),_n=Object.freeze(["passed","failed","cancelled","timed-out"]);var Ln="data-spotpatch-source",ea=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function kn(e){if(e===null)return;let t=ea.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 Pn="https://github.com/huanglvjing/spotpatch";function lo(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function na(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:lo(e.source)}})}function oa(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function ra(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 aa(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:lo(e.source,e.code),react:na(e.react),element:oa(e.element),styles:ra(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function po(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(aa)),createdAt:e.createdAt})}var ia=new Set(Object.values(p)),sa=new Set(wn),ca=new Set(_n),la=new Set(On),go=new Set(vn),da=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,pa=/^[A-Za-z0-9_-]+$/,ua=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){return Object.keys(e).every(o=>t.includes(o))}function Ae(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function jt(e){return Ae(e,64,1)&&typeof e=="string"&&da.test(e)}function In(e){return Ae(e,128,22)&&typeof e=="string"&&pa.test(e)}function zt(e){return typeof e=="string"&&ua.test(e)&&Number.isFinite(Date.parse(e))}function wt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function fo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function uo(e,t){return e===void 0||Ae(e,t)}function Pt(e){return typeof e=="string"&&ia.has(e)}function mo(e){return!yt(e)||!Pe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&sa.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||zt(e.checkedAt))&&(e.errorCode===void 0||Pt(e.errorCode))}function ho(e){if(!yt(e)||!Pe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!zt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Pt(e.errorCode)||!yt(e.changes)||!Pe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:l,total:a}=t;return!wt(o)||!wt(n)||!wt(s)||!wt(l)||!wt(a)||a<o||a<n||a<s||a<l||a>o+n+s?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&l===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function an(e){return!yt(e)||!Pe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&Ae(e.phaseMessage,1024)&&zt(e.createdAt)&&zt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Pt(e.errorCode))}function ga(e){return yt(e)&&Pe(e,["relativePath","kind","additions","deletions"])&&Ae(e.relativePath,1024)&&typeof e.kind=="string"&&la.has(e.kind)&&wt(e.additions)&&wt(e.deletions)}function yo(e){return yt(e)&&Pe(e,["checkId","label","status","durationMs","output"])&&jt(e.checkId)&&Ae(e.label,100)&&typeof e.status=="string"&&ca.has(e.status)&&wt(e.durationMs)&&Ae(e.output,8e4)}function fa(e){return yt(e)&&Pe(e,["jobId","summary","diff","files","checks"])&&In(e.jobId)&&Ae(e.summary,8e4)&&Ae(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ga)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(yo)}function bo(e){return yt(e)&&Pe(e,["snapshot","result"])&&an(e.snapshot)&&(e.result===void 0||fa(e.result)&&e.result.jobId===e.snapshot.jobId)}function ma(e){return yt(e)&&Pe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&fo(e.sequence)&&In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&zt(e.timestamp)&&typeof e.type=="string"&&yt(e.data)}function So(e){if(!ma(e))return!1;let t=e.data;switch(e.type){case"snapshot":return Pe(t,["snapshot"])&&an(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Pe(t,["message"])&&Ae(t.message,1024);case"tool":return Pe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&fo(t.turn)&&Ae(t.toolCallId,256)&&Ae(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&uo(t.relativePath,1024)&&uo(t.checkLabel,100);case"check":return Pe(t,["result"])&&yo(t.result);case"result-ready":return Pe(t,["hasResult"])&&t.hasResult===!0;case"error":return Pe(t,["code","message"])&&Pt(t.code)&&Ae(t.message,1024);default:return!1}}var xo=2e6,Eo=1e5,ha=4e6,J=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ya(e){if(!(!Ie(e)||e.ok!==!1||!Ie(e.error)))return Pt(e.error.code)?e.error.code:void 0}function ba(e){if(!Ie(e)||e.ok!==!0||!("data"in e))throw new J;return e.data}function Sa(e){return Ie(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 Ro(e){if(!(!Ie(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Ro(t);Object.freeze(e)}}function It(e){return Ro(e),e}async function Ea(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new J;if(e.body===null)throw new J;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),l=0,a="";try{for(;;){let d=await n.read();if(d.done)return a+=s.decode(),a;if(l+=d.value.byteLength,l>t)throw await n.cancel(),new J;a+=s.decode(d.value,{stream:!0})}}catch(d){throw d instanceof J?d:new J}finally{n.releaseLock()}}function Co(e){try{return JSON.parse(e)}catch{throw new J}}async function Ao(e,t=xo){let o=Co(await Ea(e,t));if(!e.ok)throw new J(ya(o));return ba(o)}function cn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Aa(e){return Ie(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function xa(e){return Ie(e)&&typeof e.enabled=="boolean"&&(e.staticAnalysis==="available"||e.staticAnalysis==="partial"||e.staticAnalysis==="unavailable")&&e.runtimeObservation==="dispatch-only"&&e.responseShape==="consumed-fields-only"&&e.aiAssistance==="disabled"&&Array.isArray(e.reasons)}function Ra(e){return Ie(e)&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.direction=="string"&&typeof e.execution=="string"&&typeof e.proof=="string"&&typeof e.association=="string"&&Array.isArray(e.parameters)&&Ie(e.response)&&cn(e.response.consumedFields)&&cn(e.evidenceIds)&&cn(e.observationIds)}function To(e){return Ie(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Ie(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&cn(e.baseline.analyzedSourceVersions)&&xa(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(Ra)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&Aa(e.completeness)}function Ca(e){return To(e)&&Ie(e)&&Ie(e.component)&&Ie(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function Ta(e){return To(e)}function va(e,t){if(!mo(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new J;return It(e)}function sn(e,t){if(!an(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 J;return It(e)}function wa(e,t){if(!bo(e)||e.snapshot.jobId!==t)throw new J;return It(e)}function Oa(e){if(!So(e))throw new J;return It(e)}function _a(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 vo(e){return e instanceof J&&Pt(e.code)?e.code:void 0}function wo(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,d,C,x=xo){let w=new AbortController;t.add(w);try{let V=await e.fetch(a,{method:d,headers:{...C===void 0?{}:{"Content-Type":"application/json"},[on]:e.sessionToken},...C===void 0?{}:{body:JSON.stringify(C)},signal:w.signal});return await Ao(V,x)}finally{t.delete(w)}}async function s(a,d){let C=new AbortController;t.add(C);try{let x=await e.fetch(kt(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[on]:e.sessionToken},body:JSON.stringify({}),signal:C.signal});if(!x.ok){await Ao(x);return}if(x.body===null)throw new J;let w=x.body.getReader(),V=new TextDecoder("utf-8",{fatal:!0}),b="",i=0,W=0,H=A=>{if(A.trim().length===0)return;if(new TextEncoder().encode(A).byteLength>Eo)throw new J;let v=Oa(Co(A));if(v.jobId!==a||v.sequence<=W)throw new J;W=v.sequence,d(v)};try{for(;;){let A=await w.read();if(A.done){b+=V.decode(),H(b);return}if(i+=A.value.byteLength,i>ha)throw await w.cancel(),new J;b+=V.decode(A.value,{stream:!0});let v=b.split(`
2
+ `);if(b=v.pop()??"",new TextEncoder().encode(b).byteLength>Eo)throw await w.cancel(),new J;for(let q of v)H(q)}}catch(A){throw A instanceof J||A instanceof DOMException&&A.name==="AbortError"?A:new J}finally{w.releaseLock()}}finally{t.delete(C)}}let l=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let d=await n(ht.sourceContext,"POST",a);if(!Sa(d))throw new J;return Object.freeze({...d})},async componentDataFlowReport(a){let d=await n(ht.dataFlowComponentReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ca(d))throw new J;return It(d)},async pageDataFlowReport(a){let d=await n(ht.dataFlowPageReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ta(d))throw new J;return It(d)},async openEditor(a){let d=await n(ht.openEditor,"POST",a);if(!Ie(d)||d.editor!=="auto"&&d.editor!=="vscode"&&d.editor!=="cursor")throw new J;return Object.freeze({editor:d.editor})},async agentCapability(a){return va(await n(ht.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(ht.agentWorkspaceHealth,"POST",l);if(!ho(a))throw new J;return It(a)},async createAgentJob(a){let d=_a(a);return sn(await n(ht.agentJobs,"POST",d),a)},agentEvents:s,async agentResult(a){return wa(await n(kt(a,"result"),"POST",l),a)},async cancelAgentJob(a){return sn(await n(kt(a,"cancel"),"POST",l),{jobId:a})},async applyAgentJob(a){return sn(await n(kt(a,"apply"),"POST",l),{jobId:a})},async revertAgentJob(a){return sn(await n(kt(a,"revert"),"POST",l),{jobId:a})},dispose(){o()}})}var La=500,Oo=256;function ka(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Pa(e){return nn(e)}function _o(e,t,o){if(!Pa(e))return e==="href"||e==="src"?vt(t,o):e==="d"&&t.length>Oo?`${t.slice(0,Oo)}…`:ka(oe(t),La)}function Be(e){return oe(e)}var Lo=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 Vt=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 Ia(e){return"selectorText"in e&&"style"in e}function Na(e){return"cssRules"in e}function Da(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 Ma(e,t,o,n,s){return e.join(" ").length+(t?.length??0)+o.reduce((l,a)=>l+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((l,[a,d])=>l+a.length+d.length,0)+s.join(`
3
+ `).length}function Fa(e,t){return e.href===null?void 0:vt(e.href,t)}function ko(e,t,o,n,s,l){for(let a of t){if(Ia(a)){let d=!1;try{d=e.matches(a.selectorText)}catch{l.add(Vt.selector);continue}d&&s.push(Object.freeze({selector:Be(a.selectorText),declarations:Be(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Na(a)){let d=Da(a);ko(e,a.cssRules,o,d===void 0?n:[...n,d],s,l)}}}function Ha(e,t){if(t===void 0)return{};let o=t(e),n={};for(let s of Lo){let l=Be(o.getPropertyValue(s).trim());l.length>0&&(n[s]=l)}return n}function Po(e){let t=new Set([Vt.state,Vt.cssInJs,Vt.cascade]),o=[],n=e.readCssRules??(w=>w.cssRules);for(let w of e.document.styleSheets){let V;try{V=n(w)}catch{t.add(Vt.inaccessibleStylesheet);continue}ko(e.element,V,Fa(w,e.document.baseURI),[],o,t)}let s=Array.from(e.element.classList),l=e.element.getAttribute("style"),a=l===null?void 0:Be(l),d=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),C=Object.entries(Ha(e.element,d)),x=Array.from(t);for(;Ma(s,a,o,Object.fromEntries(C),x)>e.maxCharacters;){if(C.length>0){C.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(s),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(C)),warnings:Object.freeze(x)})}var Ot=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),$a=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"]),Ba=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function No(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Ua(e){return $a.has(e)||e.startsWith("aria-")||e==="data-testid"}function Do(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let s of e.attributes){let l=s.name.toLowerCase();if(!Ua(l))continue;let a=_o(l,s.value,n);a!==void 0&&o.push(`${l}="${No(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Mo(e){return oe(e).replaceAll(/\s+/gu," ").trim()}function Fo(e,t,o,n){if(o.nodeCount>=Ot.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let s=" ".repeat(t),l=e.tagName.toLowerCase();if(n.push(`${s}${Do(e)}`),!Ba.has(l)){for(let a of e.childNodes){if(o.nodeCount>=Ot.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let d=Mo(a.textContent??"");if(d.length>0){o.nodeCount+=1;let C=d.length<=Ot.maxTextCharacters?d:`${d.slice(0,Ot.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${No(C)}`)}continue}if(a.nodeType===1){if(t>=Ot.maxDepth){o.truncated=!0;continue}Fo(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${s}</${l}>`)}}function ja(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Ot.maxParentDepth;)t.push(Do(o)),o=o.parentElement;return t}function za(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Io(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Va(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Wa(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Io(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Va(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(d=>`.${Io(d)}`).join(""),s=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(d=>d.tagName===e.tagName),l=s.indexOf(e),a=s.length>1&&l>=0?`:nth-of-type(${String(l+1)})`:"";return`${t}${n}${a}`}function qa(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Wa(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Ho(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};Fo(e.element,0,o,t);let n=ja(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let s=Mo(e.element.textContent),l=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:qa(e.element),sanitizedHtml:za(t.join(`
4
+ `),e.maxCharacters),...s.length===0?{}:{textPreview:s.length<=Ot.maxTextCharacters?s:`${s.slice(0,Ot.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:l.x,y:l.y,width:l.width,height:l.height})})}function $o(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Ga(e){return e.toLowerCase()}function Bo(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Uo(e,t,o){let n=t.split("+").map(w=>w.trim().toLowerCase()).filter(w=>w.length>0),s=n.find(w=>w!=="mod"&&w!=="meta"&&w!=="ctrl"&&w!=="control"&&w!=="alt"&&w!=="option"&&w!=="shift");if(s===void 0||Ga(e.key)!==s)return!1;let l=n.includes("mod"),a=n.includes("meta")||l&&$o(o),d=n.includes("ctrl")||n.includes("control")||l&&!$o(o),C=n.includes("alt")||n.includes("option"),x=n.includes("shift");return e.metaKey===a&&e.ctrlKey===d&&e.altKey===C&&e.shiftKey===x}function Ka(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function Ja(e){let t=e.filter(d=>d.width>0&&d.height>0),o=t[0];if(o===void 0)return;let n=o.left,s=o.top,l=o.right,a=o.bottom;for(let d of t.slice(1))n=Math.min(n,d.left),s=Math.min(s,d.top),l=Math.max(l,d.right),a=Math.max(a,d.bottom);return Object.freeze({x:n,y:s,width:l-n,height:a-s})}function jo(e,t){if(t.startsWith("inline")){let o=Ja(Array.from(e.getClientRects()));if(o!==void 0)return o}return Ka(e.getBoundingClientRect())}function zo(e,t){return jo(e,t.getComputedStyle(e).display)}function dn(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=jo(e,o.display);return n.width>0&&n.height>0?n:void 0}var Nt="data-spotpatch-ui",pn=Object.freeze({highlight:2147483646,controls:2147483647}),_t=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function Vo(e){if(e.closest(`[${Nt}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(Nt)}function Xa(e,t){return dn(e,t)!==void 0}function Ya(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Nn(e,t,o,n){let s=e.elementsFromPoint(o,n).filter(l=>!Vo(l)&&Xa(l,t));return s.find(l=>!Ya(l))??s[0]}function Wo(e){return e instanceof Element&&Vo(e)}var Dn=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 Za(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function un(e,t){let o="`".repeat(Math.max(3,Za(t)+1));return`${o}${e}
5
5
  ${t}
6
- ${o}`}function zo(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,s=e.source.column;return o===void 0?t.unavailable:`${ee(o)}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function jo(e,t){return e.split(`
7
- `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Ga(e){let t=[e.source===void 0?void 0:`/* source: ${Ve(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Ve(e.media)} */`].filter(n=>n!==void 0),o=`${Ve(e.selector)} {
8
- ${Ve(e.declarations)}
6
+ ${o}`}function Go(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,s=e.source.column;return o===void 0?t.unavailable:`${oe(o)}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function Ko(e,t){return e.split(`
7
+ `).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Qa(e){let t=[e.source===void 0?void 0:`/* source: ${Be(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Be(e.media)} */`].filter(n=>n!==void 0),o=`${Be(e.selector)} {
8
+ ${Be(e.declarations)}
9
9
  }`;return[...t,o].join(`
10
- `)}function qa(e,t,o){let s=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Ve).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Ve(e.styles.inlineStyle)} */`].filter(d=>d!==void 0),...t.map(Ga)];return s.length===0?o.unavailable:cn("css",s.join(`
10
+ `)}function ei(e,t,o){let s=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Be).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Be(e.styles.inlineStyle)} */`].filter(l=>l!==void 0),...t.map(Qa)];return s.length===0?o.unavailable:un("css",s.join(`
11
11
 
12
- `))}function Ka(e,t){return e.length===0?t.unavailable:cn("css",e.map(([o,n])=>`${Ve(o)}: ${Ve(n)};`).join(`
13
- `))}function Ja(e,t,o,n){let s=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${ee(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${ee(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(ee).join(" > ")}`]],d=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
12
+ `))}function ti(e,t){return e.length===0?t.unavailable:un("css",e.map(([o,n])=>`${Be(o)}: ${Be(n)};`).join(`
13
+ `))}function ni(e,t,o,n){let s=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${oe(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${oe(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(oe).join(" > ")}`]],l=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
14
14
 
15
- ${cn(e.code.language,ee(t.codeLines.join(`
16
- `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${Tt(e.page.url,e.page.url)}>
17
- - ${n.pathname}: ${ee(e.page.pathname)}
18
- - ${n.title}: ${ee(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,s.join(`
19
- `),`#### ${n.source}`,`- ${n.file}: ${zo(e,n)}
15
+ ${un(e.code.language,oe(t.codeLines.join(`
16
+ `)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${vt(e.page.url,e.page.url)}>
17
+ - ${n.pathname}: ${oe(e.page.pathname)}
18
+ - ${n.title}: ${oe(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,s.join(`
19
+ `),`#### ${n.source}`,`- ${n.file}: ${Go(e,n)}
20
20
  - ${n.origin}: ${e.source.origin}
21
- - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,cn("html",ee(t.dom)),`#### ${n.styles}`,qa(e,t.matchedRules,n),`#### ${n.computedStyles}`,Ka(t.computedEntries,n),`#### ${n.code}`,d,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(i=>`- ${ee(i)}`).join(`
21
+ - ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,un("html",oe(t.dom)),`#### ${n.styles}`,ei(e,t.matchedRules,n),`#### ${n.computedStyles}`,ti(t.computedEntries,n),`#### ${n.code}`,l,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${oe(a)}`).join(`
22
22
  `)].join(`
23
23
 
24
- `)}function Bo(e,t){let o=Tt(e.page.url,e.page.url),n=On[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
25
- - ${n.pathname}: ${ee(e.page.pathname)}
24
+ `)}function qo(e,t){let o=vt(e.page.url,e.page.url),n=Dn[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
25
+ - ${n.pathname}: ${oe(e.page.pathname)}
26
26
  - ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
27
27
  - ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
28
- - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((s,d)=>{let i=t.targets[d];if(i===void 0)throw new RangeError("Prompt target draft is missing.");return Ja(s,i,d,n)}).join(`
28
+ - ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((s,l)=>{let a=t.targets[l];if(a===void 0)throw new RangeError("Prompt target draft is missing.");return ni(s,a,l,n)}).join(`
29
29
 
30
30
  `),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
31
31
 
32
- `)}function Xa(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 Ya(e){return{instruction:ee(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 Za(e){return{pageTitle:ee(e.page.title),targets:e.targets.map(Ya)}}function Qa(e,t,o){let n=On[e.locale],s=[(d,i)=>i.computedEntries.pop()!==void 0,(d,i)=>i.reactStack.pop()!==void 0,(d,i)=>{let l=jo(i.dom,n.unavailable);return i.dom===l?!1:(i.dom=l,!0)},(d,i)=>i.matchedRules.shift()!==void 0,Xa,(d,i)=>i.warnings.pop()!==void 0];for(let d of s)for(let i=0;i<e.targets.length;i+=1){let l=(o+i)%e.targets.length,A=e.targets[l],w=t.targets[l];if(A!==void 0&&w!==void 0&&d(A,w))return(l+1)%e.targets.length}}function ei(e,t){let o=On[e.locale],n=e.targets.map((s,d)=>{let i=t.targets[d],l=s.react.componentName;return[`### ${o.target(d+1)}`,`- ${o.requestedChange}: ${i?.instruction??ee(s.instruction)}`,`- ${o.file}: ${zo(s,o)}`,...l===void 0?[]:[`- ${o.component}: ${ee(l)}`],`- ${o.element}: ${ee(jo(i?.dom??s.element.sanitizedHtml,o.unavailable))}`].join(`
32
+ `)}function oi(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),s=e.code.startLine+t.codeLines.length-1;return Math.abs(s-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function ri(e){return{instruction:oe(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 ai(e){return{pageTitle:oe(e.page.title),targets:e.targets.map(ri)}}function ii(e,t,o){let n=Dn[e.locale],s=[(l,a)=>a.computedEntries.pop()!==void 0,(l,a)=>a.reactStack.pop()!==void 0,(l,a)=>{let d=Ko(a.dom,n.unavailable);return a.dom===d?!1:(a.dom=d,!0)},(l,a)=>a.matchedRules.shift()!==void 0,oi,(l,a)=>a.warnings.pop()!==void 0];for(let l of s)for(let a=0;a<e.targets.length;a+=1){let d=(o+a)%e.targets.length,C=e.targets[d],x=t.targets[d];if(C!==void 0&&x!==void 0&&l(C,x))return(d+1)%e.targets.length}}function si(e,t){let o=Dn[e.locale],n=e.targets.map((s,l)=>{let a=t.targets[l],d=s.react.componentName;return[`### ${o.target(l+1)}`,`- ${o.requestedChange}: ${a?.instruction??oe(s.instruction)}`,`- ${o.file}: ${Go(s,o)}`,...d===void 0?[]:[`- ${o.component}: ${oe(d)}`],`- ${o.element}: ${oe(Ko(a?.dom??s.element.sanitizedHtml,o.unavailable))}`].join(`
33
33
  `)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
34
34
 
35
35
  `),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
36
36
 
37
- `)}function ti(e,t){let o=Za(e),n=Bo(e,o),s=0;for(;n.length>t;){let i=Qa(e,o,s);if(i===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else s=i;n=Bo(e,o)}if(n.length<=t)return n;let d=ei(e,o);if(d.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return d}function Uo(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 ti(t,e.maxCharacters)}})}var Oe=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),_n=Oe.idle;function ni(e){return e.type==="ACTIVATE"?Oe.inspecting:e.type==="RESTORE"?Oe.selected:Oe.idle}function oi(e){switch(e.type){case"HOVER":return Oe.inspecting;case"SELECT":return Oe.selected;case"CANCEL":return Oe.idle;default:return Oe.inspecting}}function ri(e){switch(e.type){case"RESELECT":return Oe.inspecting;case"CLOSE":return Oe.idle;case"PREVIEW":return Oe.previewing;case"OPEN_EDITOR":return Oe.selected;default:return Oe.selected}}function ai(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return Oe.selected;case"COPY_FAILURE":return Oe.previewing;default:return Oe.previewing}}function Vo(e,t){switch(e.status){case"idle":return ni(t);case"inspecting":return oi(t);case"selected":return ri(t);case"previewing":return ai(t)}}var ii="spotpatch:selection:";function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ge(e){return typeof e=="string"}function Et(e){return e===void 0||ge(e)}function Ln(e){return Array.isArray(e)&&e.length<=256&&e.every(ge)}function mt(e){return typeof e=="number"&&Number.isFinite(e)}function Wo(e){return e===void 0||mt(e)}function Go(e){let t=it(e);return t!==void 0&&ge(t.origin)&&ge(t.confidence)&&Et(t.fileId)&&Et(t.relativePath)&&Wo(t.line)&&Wo(t.column)}function si(e){let t=it(e);return t!==void 0&&typeof t.supported=="boolean"&&Et(t.version)&&Et(t.componentName)&&Ln(t.componentStack)&&(t.source===void 0||Go(t.source))}function ci(e){let t=it(e);return t!==void 0&&ge(t.url)&&ge(t.pathname)&&ge(t.title)&&mt(t.viewportWidth)&&mt(t.viewportHeight)&&mt(t.devicePixelRatio)}function di(e){let t=it(e),o=it(t?.rect);return t!==void 0&&ge(t.tagName)&&ge(t.selector)&&ge(t.sanitizedHtml)&&Et(t.textPreview)&&Et(t.role)&&o!==void 0&&mt(o.x)&&mt(o.y)&&mt(o.width)&&mt(o.height)}function li(e){let t=it(e),o=it(t?.computed);return t!==void 0&&Ln(t.classNames)&&Et(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let s=it(n);return s!==void 0&&ge(s.selector)&&ge(s.declarations)&&Et(s.source)&&Et(s.media)})&&o!==void 0&&Object.values(o).every(ge)&&Ln(t.warnings)}function pi(e){let t=it(e);return t!==void 0&&ge(t.relativePath)&&ge(t.language)&&mt(t.startLine)&&mt(t.endLine)&&ge(t.excerpt)&&ge(t.boundary)}function ui(e){let t=it(e);return t!==void 0&&ge(t.id)&&ge(t.instruction)&&ci(t.page)&&Go(t.source)&&si(t.react)&&di(t.element)&&li(t.styles)&&(t.code===void 0||pi(t.code))}function gi(e,t){let o=it(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(ui))return;let n=o.targets,s=n.map(({id:d})=>d);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 qo(e,t,o){let n=`${ii}${t}`,s;try{s=e.sessionStorage}catch{s=void 0}return Object.freeze({clear(){try{s?.removeItem(n)}catch{}},load(){let d;try{d=s?.getItem(n)??null}catch{return}if(!(d===null||d.length>1e6))try{return gi(JSON.parse(d),o)}catch{return}},save(d){try{s?.setItem(n,JSON.stringify({version:1,...d}))}catch{}}})}var Ko=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Xo(e){return Cn(e.getAttribute(Rn))}function fi(e){let t=e.parentElement;for(;t!==null;){let o=Xo(t);if(o!==void 0)return o;t=t.parentElement}}function Jo(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function mi(){return Object.freeze({origin:"none",confidence:"unknown"})}function Pn(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function Yo(e){let t=!0;function o(n){if(!t)return Ko;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Ko}}return Object.freeze({resolve(n){let s=Xo(n),d=o(n);if(s!==void 0)return Object.freeze({react:d,source:Jo(s,"jsx-host","exact")});if(d.source!==void 0)return Object.freeze({react:d,source:d.source});let i=fi(n);return Object.freeze(i!==void 0?{react:d,source:Jo(i,"dom-ancestor","approximate")}:{react:d,source:mi()})},dispose(){t=!1,e.adapter.dispose()}})}function g(e,t){let o=e.createElement(t);return o.setAttribute(kt,""),o}function oe(e,t,o=""){let n=g(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Zo=`
37
+ `)}function ci(e,t){let o=ai(e),n=qo(e,o),s=0;for(;n.length>t;){let a=ii(e,o,s);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else s=a;n=qo(e,o)}if(n.length<=t)return n;let l=si(e,o);if(l.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return l}function Jo(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 ci(t,e.maxCharacters)}})}var Te=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Mn=Te.idle;function li(e){return e.type==="ACTIVATE"?Te.inspecting:e.type==="RESTORE"?Te.selected:Te.idle}function di(e){switch(e.type){case"HOVER":return Te.inspecting;case"SELECT":return Te.selected;case"CANCEL":return Te.idle;default:return Te.inspecting}}function pi(e){switch(e.type){case"RESELECT":return Te.inspecting;case"CLOSE":return Te.idle;case"PREVIEW":return Te.previewing;case"OPEN_EDITOR":return Te.selected;default:return Te.selected}}function ui(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return Te.selected;case"COPY_FAILURE":return Te.previewing;default:return Te.previewing}}function Xo(e,t){switch(e.status){case"idle":return li(t);case"inspecting":return di(t);case"selected":return pi(t);case"previewing":return ui(t)}}var gi="spotpatch:selection:";function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ge(e){return typeof e=="string"}function At(e){return e===void 0||ge(e)}function Fn(e){return Array.isArray(e)&&e.length<=256&&e.every(ge)}function bt(e){return typeof e=="number"&&Number.isFinite(e)}function Yo(e){return e===void 0||bt(e)}function Zo(e){let t=it(e);return t!==void 0&&ge(t.origin)&&ge(t.confidence)&&At(t.fileId)&&At(t.relativePath)&&Yo(t.line)&&Yo(t.column)}function fi(e){let t=it(e);return t!==void 0&&typeof t.supported=="boolean"&&At(t.version)&&At(t.componentName)&&Fn(t.componentStack)&&(t.source===void 0||Zo(t.source))}function mi(e){let t=it(e);return t!==void 0&&ge(t.url)&&ge(t.pathname)&&ge(t.title)&&bt(t.viewportWidth)&&bt(t.viewportHeight)&&bt(t.devicePixelRatio)}function hi(e){let t=it(e),o=it(t?.rect);return t!==void 0&&ge(t.tagName)&&ge(t.selector)&&ge(t.sanitizedHtml)&&At(t.textPreview)&&At(t.role)&&o!==void 0&&bt(o.x)&&bt(o.y)&&bt(o.width)&&bt(o.height)}function yi(e){let t=it(e),o=it(t?.computed);return t!==void 0&&Fn(t.classNames)&&At(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let s=it(n);return s!==void 0&&ge(s.selector)&&ge(s.declarations)&&At(s.source)&&At(s.media)})&&o!==void 0&&Object.values(o).every(ge)&&Fn(t.warnings)}function bi(e){let t=it(e);return t!==void 0&&ge(t.relativePath)&&ge(t.language)&&bt(t.startLine)&&bt(t.endLine)&&ge(t.excerpt)&&ge(t.boundary)}function Si(e){let t=it(e);return t!==void 0&&ge(t.id)&&ge(t.instruction)&&mi(t.page)&&Zo(t.source)&&fi(t.react)&&hi(t.element)&&yi(t.styles)&&(t.code===void 0||bi(t.code))}function Ei(e,t){let o=it(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(Si))return;let n=o.targets,s=n.map(({id:l})=>l);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 Qo(e,t,o){let n=`${gi}${t}`,s;try{s=e.sessionStorage}catch{s=void 0}return Object.freeze({clear(){try{s?.removeItem(n)}catch{}},load(){let l;try{l=s?.getItem(n)??null}catch{return}if(!(l===null||l.length>1e6))try{return Ei(JSON.parse(l),o)}catch{return}},save(l){try{s?.setItem(n,JSON.stringify({version:1,...l}))}catch{}}})}var er=Object.freeze({supported:!1,componentStack:Object.freeze([])});function nr(e){return kn(e.getAttribute(Ln))}function Ai(e){let t=e.parentElement;for(;t!==null;){let o=nr(t);if(o!==void 0)return o;t=t.parentElement}}function tr(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function xi(){return Object.freeze({origin:"none",confidence:"unknown"})}function Hn(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 or(e){let t=!0;function o(n){if(!t)return er;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),er}}return Object.freeze({resolve(n){let s=nr(n),l=o(n);if(s!==void 0)return Object.freeze({react:l,source:tr(s,"jsx-host","exact")});if(l.source!==void 0)return Object.freeze({react:l,source:l.source});let a=Ai(n);return Object.freeze(a!==void 0?{react:l,source:tr(a,"dom-ancestor","approximate")}:{react:l,source:xi()})},dispose(){t=!1,e.adapter.dispose()}})}function g(e,t){let o=e.createElement(t);return o.setAttribute(Nt,""),o}function ie(e,t,o=""){let n=g(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var rr=`
38
38
  .spotpatch-agent {
39
39
  margin-top: 10px;
40
40
  overflow: hidden;
@@ -253,7 +253,7 @@ ${cn(e.code.language,ee(t.codeLines.join(`
253
253
  .spotpatch-agent-selectors { grid-template-columns: 1fr; }
254
254
  .spotpatch-agent-mode { grid-column: auto; }
255
255
  }
256
- `;function Vt(e,t,o,n){let s=e.createElement("option");return s.value=o,s.textContent=n,t.append(s),s}function Qo(e,t,o){let n=o.messages(),s=g(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let d=g(e,"div");d.className="spotpatch-agent-head",d.setAttribute("data-spotpatch-agent-identity","");let i=g(e,"span");i.className="spotpatch-agent-title";let l=g(e,"span");l.className="spotpatch-agent-badge",d.append(i,l);let A=g(e,"div");A.className="spotpatch-agent-setup";let w=g(e,"div");w.className="spotpatch-agent-selectors";let T=g(e,"label");T.className="spotpatch-agent-mode";let N=g(e,"span"),r=g(e,"select");T.append(N,r);let F=g(e,"label"),M=g(e,"span"),I=g(e,"select");F.append(M,I);let b=g(e,"label"),x=g(e,"span"),K=g(e,"select");b.append(x,K),w.append(T,F,b);let J=g(e,"label");J.className="spotpatch-consent";let G=g(e,"input");G.type="checkbox";let h=g(e,"span");J.append(G,h);let R=g(e,"label");R.className="spotpatch-consent spotpatch-workspace-consent",R.hidden=!0;let O=g(e,"input");O.type="checkbox";let _=g(e,"span"),U=g(e,"strong"),S=g(e,"small");_.append(U,S),R.append(O,_);let C=g(e,"div");C.className="spotpatch-agent-health-list";let v=g(e,"p");v.className="spotpatch-agent-workspace",v.dataset.state="idle";let L=g(e,"p");L.className="spotpatch-agent-capability",L.dataset.state="idle",C.append(v,L),A.append(w,J,R,C);let te=g(e,"div");te.className="spotpatch-agent-job",te.hidden=!0;let Ee=g(e,"div");Ee.className="spotpatch-agent-job-meta";let $=g(e,"span");$.className="spotpatch-agent-model";let k=g(e,"span");k.className="spotpatch-agent-status",Ee.append($,k);let He=g(e,"p");He.className="spotpatch-agent-phase";let de=g(e,"p");de.className="spotpatch-agent-error",de.hidden=!0;let $e=g(e,"ul");$e.className="spotpatch-agent-activity";let Ae=g(e,"div");Ae.className="spotpatch-agent-result",Ae.hidden=!0;let ht=g(e,"p");ht.className="spotpatch-agent-summary";let le=g(e,"ul");le.className="spotpatch-agent-files";let We=g(e,"div");We.className="spotpatch-agent-checks";let xe=g(e,"pre");xe.className="spotpatch-agent-diff",xe.tabIndex=0,xe.setAttribute("aria-label",n.agent.diffAriaLabel),Ae.append(ht,le,We,xe),te.append(Ee,He,de,$e,Ae),s.append(d,A,te);let be=oe(e,n.agent.testConnection),Re=oe(e,n.agent.run,"spotpatch-run"),Y=oe(e,n.agent.cancel),_e=oe(e,n.agent.apply,"spotpatch-primary"),Ke=oe(e,n.agent.revert),Je=oe(e,n.agent.revise),Qe=t.enabled?t.providers:[],Xe=t.enabled&&t.applyMode==="trusted-auto",ne=t.enabled?t.applyMode:"review",xt=new Map(Qe.map(y=>[y.id,y])),et=!1,tt=!0,Be=!1,ze=!1,j=!1,Ce=!1,Te,nt,st=[],yt,fe="idle",je=n.agent.connectionNotTested,ot,ve="idle",rt,Le;for(let y of Qe)Vt(e,I,y.id,y.label);t.enabled&&(I.value=t.defaultProvider);let P,ct,re;ne==="auto"?re=Vt(e,r,"auto",n.agent.autoGated):(P=Vt(e,r,"review",n.agent.review),Xe&&(ct=Vt(e,r,"trusted-auto",n.agent.trustedFast)));let Z=Xe?"review":ne;r.value=Z,T.hidden=!Xe;let Ge=()=>r.value==="trusted-auto"?"trusted-auto":Z,qe=()=>Ge()==="trusted-auto",me=()=>xt.get(I.value),bt=y=>y===void 0?n.agent.providerUnavailable:qe()?n.agent.trustedFastConsent(y.label):n.agent.consent(y.label),Pe=()=>qe()?G.checked:O.checked,Ie=()=>{let y=qe();J.classList.toggle("spotpatch-trusted-consent",y),l.textContent=y?n.agent.trustedFast:ne==="auto"?n.agent.autoGated:n.agent.review,h.textContent=bt(me()),R.hidden=y||ve!=="consent-required"},Ye=()=>{let y=me();if(K.replaceChildren(),y===void 0){h.textContent=bt(y);return}for(let W of y.models)Vt(e,K,W.id,W.label);K.value=y.defaultModel,h.textContent=bt(y)},Q=()=>{let y=t.enabled&&Be&&!ze;Re.textContent=j?n.agent.verifying:n.agent.run,Re.classList.toggle("spotpatch-primary",Ce),be.hidden=!y,Re.hidden=!y,be.disabled=!tt||j||me()===void 0,Re.disabled=!tt||j||!et||!G.checked||ve==="idle"||ve==="checking"||ve==="blocked"||ve==="consent-required"&&!Pe()||me()===void 0||K.value.length===0,(!ze||!Be)&&(Y.hidden=!0,_e.hidden=!0,Ke.hidden=!0,Je.hidden=!0)},Ue=()=>{if(ve==="idle")v.textContent=n.agent.workspaceNotChecked;else if(ve==="checking")v.textContent=n.agent.checkingWorkspace;else if(ve==="ready")v.textContent=n.agent.workspaceReady;else if(ve==="consent-required"){let y=rt?.changes;v.textContent=n.agent.workspaceDirty(y?.staged??0,y?.unstaged??0,y?.untracked??0)}else v.textContent=Le===void 0?n.errors.INTERNAL_ERROR:n.errors[Le]};function c(){Ye(),G.checked=!1,L.dataset.state="idle",L.textContent=n.agent.connectionNotTested,fe="idle",je=n.agent.connectionNotTested,ot=void 0,Ce=!1,Q()}function u(){L.dataset.state="idle",L.textContent=n.agent.connectionNotTested,fe="idle",je=n.agent.connectionNotTested,ot=void 0,Ce=!1,Q()}function E(){G.checked=!1,O.checked=!1,Ie(),Q()}Ye(),r.addEventListener("change",E),I.addEventListener("change",c),K.addEventListener("change",u),G.addEventListener("change",Q),O.addEventListener("change",Q);function H(){if(Te===void 0)return;let y=Te,W=nt;$.textContent=`${y.providerLabel} · ${y.modelLabel}`,k.textContent=n.agent.status(y.status),He.textContent=y.phaseMessage;let pe=yt??y.errorCode;de.hidden=pe===void 0,de.textContent=pe===void 0?"":n.errors[pe],$e.replaceChildren();for(let se of st.slice(-8)){let Ne=g(e,"li");Ne.dataset.state=se.state,Ne.textContent=se.label,$e.append(Ne)}Ae.hidden=W===void 0,ht.textContent=W?.summary??"",le.replaceChildren(),We.replaceChildren(),xe.textContent=W?.diff??"";for(let se of W?.files??[]){let Ne=g(e,"li");Ne.textContent=`${se.kind} ${se.relativePath} (+${String(se.additions)} / -${String(se.deletions)})`,le.append(Ne)}for(let se of W?.checks??[]){let Ne=g(e,"details"),_t=g(e,"summary");_t.textContent=`${se.label}: ${se.status} · ${String(se.durationMs)} ms`;let Lt=g(e,"pre");Lt.textContent=se.output.length===0?n.agent.noOutput:se.output,Ne.append(_t,Lt),We.append(Ne)}be.hidden=!0,Re.hidden=!0,Y.hidden=!Be||!y.canCancel,Y.textContent=y.status==="awaiting-review"?n.agent.discard:n.agent.cancel,_e.hidden=!Be||!y.canApply,Ke.hidden=!Be||!y.canRevert,Je.hidden=!Be||!["completed","cancelled","reverted","failed"].includes(y.status)}function V(){n=o.messages(),i.textContent=n.agent.title,N.textContent=n.agent.mode,P!==void 0&&(P.textContent=n.agent.review),ct!==void 0&&(ct.textContent=n.agent.trustedFast),re!==void 0&&(re.textContent=n.agent.autoGated),M.textContent=n.agent.provider,x.textContent=n.agent.model,I.setAttribute("aria-label",n.agent.providerAriaLabel),K.setAttribute("aria-label",n.agent.modelAriaLabel),U.textContent=n.agent.includeLocalChanges,S.textContent=n.agent.includeLocalChangesHelp,xe.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,_e.textContent=n.agent.apply,Ke.textContent=n.agent.revert,Je.textContent=n.agent.revise,Ie(),fe==="idle"?L.textContent=n.agent.connectionNotTested:fe==="probing"?L.textContent=n.agent.testingCapability:fe==="ready"?L.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ot!==void 0?L.textContent=n.errors[ot]:me()===void 0?L.textContent=n.agent.providerUnavailable:L.textContent=je,Ue(),Q(),H()}let ie=o.subscribe(V);return V(),Object.freeze({root:s,modeSelect:r,providerSelect:I,modelSelect:K,consentCheckbox:G,workspaceConsentCheckbox:O,testButton:be,runButton:Re,cancelButton:Y,applyButton:_e,revertButton:Ke,resetButton:Je,consentGranted(){return G.checked},workspaceConsentGranted(){return Pe()},readSelection(){let y=me(),W=y?.models.find(pe=>pe.id===K.value);return y===void 0||W===void 0?void 0:Object.freeze({applyMode:Ge(),providerProfileId:y.id,modelProfileId:W.id})},renderCapability(y,W,pe,se){fe=y,je=W,ot=se,j=y==="probing",Ce=y==="ready"&&pe?.state==="agent-ready",L.dataset.state=y,L.textContent=pe?.state==="agent-ready"?`${W} · ${n.agent.toolsReady}`:W,Q()},renderWorkspaceHealth(y,W,pe){ve=y,rt=W,Le=pe??W?.errorCode,v.dataset.state=y,y!=="checking"&&(R.hidden=qe()||y!=="consent-required"),(y==="idle"||y==="ready"||y==="blocked")&&(O.checked=!1),Ue(),Q()},renderJob(y,W,pe,se){ze=!0,A.hidden=!0,te.hidden=!1,I.disabled=!0,K.disabled=!0,r.disabled=!0,G.disabled=!0,O.disabled=!0,Te=y,nt=W,st=pe,yt=se,H()},resetJob(){ze=!1,Te=void 0,nt=void 0,st=[],yt=void 0,A.hidden=!1,te.hidden=!0,I.disabled=!1,K.disabled=!1,r.disabled=!1,G.disabled=!1,O.disabled=!1,$e.replaceChildren(),le.replaceChildren(),We.replaceChildren(),xe.textContent="",de.textContent="",de.hidden=!0,Q()},setContextReady(y){et=y,Q()},setEditingEnabled(y){tt=y,I.disabled=!y||ze,K.disabled=!y||ze,r.disabled=!y||ze,G.disabled=!y||ze,O.disabled=!y||ze,Q()},setProviderConsent(y){G.checked=y,Q()},setSelectionVisible(y){Be=y,Q(),y||(Y.hidden=!0,_e.hidden=!0,Ke.hidden=!0,Je.hidden=!0)},dispose(){ie(),I.removeEventListener("change",c),K.removeEventListener("change",u),r.removeEventListener("change",E),G.removeEventListener("change",Q),O.removeEventListener("change",Q)}})}var er="http://www.w3.org/2000/svg",hi="";function yi(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:hi,viewBox:"0 0 1 1"}}function bi(e,t,o){let n=e.createElementNS(er,t);for(let[s,d]of Object.entries(o))n.setAttribute(s,d);return n}function Si(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/gu,"-"),n=new Map;for(let s of e.querySelectorAll("[id]")){let d=s.id,i=`${o}-${d}`;n.set(d,i),s.id=i}for(let s of[e,...e.querySelectorAll("*")])for(let d of[...s.attributes]){let i=d.value;for(let[l,A]of n)i=i.replaceAll(`url(#${l})`,`url(#${A})`),i===`#${l}`&&(i=`#${A}`);i!==d.value&&s.setAttribute(d.name,i)}}function In(e,t,o){let n=yi(t),s=bi(e,"svg",{xmlns:er,class:"spotpatch-brand-mark",viewBox:n.viewBox,"aria-hidden":"true",focusable:"false"});return s.innerHTML=n.content,o!==void 0&&Si(s,o),s}var Ei=Symbol.for("spotpatch.data-flow.extension.v1");function Wt(e=globalThis){return e[Ei]}var Ai=Symbol.for("spotpatch.external-handoff.v1");function dn(){return globalThis[Ai]}var xi=Symbol.for("spotpatch.motion.v1");function tr(){return globalThis[xi]}var Ri=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"}),Ci=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ti=Object.freeze({prepare:"Preparing context",dispatch:"Dispatching context",discover:"Discovering project files",search:"Searching source",read:"Reading",patch:"Generating a minimal patch",check:"Running",audit:"Auditing proposed changes",apply:"Applying verified changes",sync:"Returning results to SpotPatch",unknown:"Processing the current task"}),vi=Object.freeze({prepare:"正在准备上下文",dispatch:"正在派发上下文",discover:"正在查找项目文件",search:"正在搜索源码",read:"正在读取",patch:"正在生成最小修改补丁",check:"正在运行",audit:"正在审计候选修改",apply:"正在应用已验证修改",sync:"正在将结果回流 SpotPatch",unknown:"正在处理当前任务"}),nr=Object.freeze({prepare:"prepare",dispatch:"dispatch",discover:"list",search:"search",read:"read",patch:"patch",check:"check",audit:"audit",apply:"apply",sync:"sync",unknown:"agent"});function or(e,t,o){return o===void 0||o.length===0?e[t]:`${e[t]} ${o}`}function rr(e,t){return t===void 0||t.length===0?nr[e]:`${nr[e]} · ${t}`}var he="The external Agent handoff request failed.",ye="外部 Agent 交接请求失败。",wi=Object.freeze({[p.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[p.INVALID_TOKEN]:"The local SpotPatch session expired.",[p.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[p.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[p.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[p.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[p.EDITOR_OPEN_FAILED]:"The editor request failed.",[p.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[p.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[p.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[p.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[p.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[p.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[p.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[p.AGENT_BUSY]:"Another write Agent job is still active.",[p.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[p.AGENT_CANCELLED]:"The Agent job was cancelled.",[p.EXTERNAL_HANDOFF_DISABLED]:he,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:he,[p.HANDOFF_VALIDATION_FAILED]:he,[p.HANDOFF_SOURCE_STALE]:he,[p.HANDOFF_NOT_FOUND]:he,[p.HANDOFF_EXPIRED]:he,[p.HANDOFF_CURSOR_INVALID]:he,[p.HANDOFF_RESPONSE_TOO_LARGE]:he,[p.BRIDGE_UNAUTHORIZED]:he,[p.BRIDGE_PROTOCOL_MISMATCH]:he,[p.BRIDGE_BUSY]:he,[p.EXTERNAL_AGENT_BUSY]:he,[p.ACTIVE_ADAPTER_CONFLICT]:he,[p.ACTIVE_ADAPTER_LEASE_INVALID]:he,[p.ACTIVE_DISPATCH_INVALID]:he,[p.SESSION_NOT_FOUND]:he,[p.SESSION_AMBIGUOUS]:he,[p.SESSION_CLOSED]:he,[p.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[p.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[p.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[p.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[p.TOOL_DENIED]:"A tool request violated local safety policy.",[p.TOOL_INPUT_INVALID]:"Invalid tool request.",[p.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[p.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[p.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[p.PATCH_REJECTED]:"The patch violated local policy.",[p.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[p.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[p.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Oi=Object.freeze({[p.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[p.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[p.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[p.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[p.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[p.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[p.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[p.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[p.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[p.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[p.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[p.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[p.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[p.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[p.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[p.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[p.AGENT_CANCELLED]:"Agent 任务已取消。",[p.EXTERNAL_HANDOFF_DISABLED]:ye,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:ye,[p.HANDOFF_VALIDATION_FAILED]:ye,[p.HANDOFF_SOURCE_STALE]:ye,[p.HANDOFF_NOT_FOUND]:ye,[p.HANDOFF_EXPIRED]:ye,[p.HANDOFF_CURSOR_INVALID]:ye,[p.HANDOFF_RESPONSE_TOO_LARGE]:ye,[p.BRIDGE_UNAUTHORIZED]:ye,[p.BRIDGE_PROTOCOL_MISMATCH]:ye,[p.BRIDGE_BUSY]:ye,[p.EXTERNAL_AGENT_BUSY]:ye,[p.ACTIVE_ADAPTER_CONFLICT]:ye,[p.ACTIVE_ADAPTER_LEASE_INVALID]:ye,[p.ACTIVE_DISPATCH_INVALID]:ye,[p.SESSION_NOT_FOUND]:ye,[p.SESSION_AMBIGUOUS]:ye,[p.SESSION_CLOSED]:ye,[p.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[p.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[p.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[p.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[p.TOOL_DENIED]:"工具请求违反本地安全策略。",[p.TOOL_INPUT_INVALID]:"工具请求无效。",[p.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[p.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[p.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[p.PATCH_REJECTED]:"补丁违反本地策略。",[p.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[p.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[p.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),_i=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"}),Li=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:"警告"}),Pi=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."}),floatingSurface:Object.freeze({dragHandle:"Drag to move the SpotPatch workbench",resetPosition:"Reset workbench position",positionReset:"SpotPatch position reset to the lower-right corner."}),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:_i,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted direct",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,trustedFastConsent:e=>`Enable trusted direct mode for ${e}: send allowed project context, include current local changes, skip project validation checks, and immediately apply AI changes, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Ri[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"Receiving context",dispatchingTitle:e=>`Handing off to ${e}`,runningTitle:e=>`Modifying ${e}`,expandedRunningTitle:e=>`${e} is making changes`,completedTitle:"Change complete",expandedCompletedTitle:"Changes complete",failedTitle:"Execution failed",receivingStatus:"Receiving",dispatchingStatus:"Dispatching",runningStatus:"Running",checkingStatus:"Checking",completedStatus:"Done",failedStatus:"Failed",resultReturned:"The result is back in SpotPatch",resultSummary:e=>`${String(e)} ${e===1?"file":"files"}`,activityAction:(e,t)=>or(Ti,e,t),activityLane:rr}),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:wi}),"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 前,请核对完整上下文与每项目标说明。"}),floatingSurface:Object.freeze({dragHandle:"拖拽以移动 SpotPatch 工作台",resetPosition:"重置工作台位置",positionReset:"SpotPatch 已恢复到右下角。"}),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:Li,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",mode:"执行方式",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信极速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信极速模式:发送获准的项目上下文、纳入当前本地修改、跳过项目验证检查,并立即应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Ci[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"正在接收上下文",dispatchingTitle:e=>`正在交接给 ${e}`,runningTitle:e=>`正在修改 ${e}`,expandedRunningTitle:e=>`${e} 正在执行修改`,completedTitle:"修改完成",expandedCompletedTitle:"修改已完成",failedTitle:"执行失败",receivingStatus:"接收中",dispatchingStatus:"派发中",runningStatus:"执行中",checkingStatus:"检查中",completedStatus:"完成",failedStatus:"失败",resultReturned:"结果已回流 SpotPatch",resultSummary:e=>`${String(e)} 个文件`,activityAction:(e,t)=>or(vi,e,t),activityLane:rr}),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:Oi})});function ar(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 Ii(e,t){if(e!=="auto")return e;let o=ar(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(ar).find(s=>s!==void 0)??"en-US"}function ir(e,t="auto"){let o=Ii(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>Pi[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 Ni="spotpatch:floating-surface:";function ki(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function sr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function cr(e){return e==="start"||e==="end"}function Di(e){let t=ki(e);if(!(t?.version!==1||!cr(t.horizontal)||!cr(t.vertical)||!sr(t.xRatio)||!sr(t.yRatio)))return Object.freeze({horizontal:t.horizontal,vertical:t.vertical,xRatio:t.xRatio,yRatio:t.yRatio})}function dr(e,t){let o=`${Ni}${t}`,n;try{n=e.sessionStorage}catch{n=void 0}return Object.freeze({clear(){try{n?.removeItem(o)}catch{}},load(){let s;try{s=n?.getItem(o)??null}catch{return}if(!(s===null||s.length>1024))try{return Di(JSON.parse(s))}catch{return}},save(s){try{n?.setItem(o,JSON.stringify({version:1,...s}))}catch{}}})}var ln=Object.freeze({horizontal:"end",vertical:"end",xRatio:1,yRatio:1});function Gt(e,t,o){return Math.min(Math.max(e,t),o)}function At(e){return Number.isFinite(e)?Math.max(0,e):0}function Nn(e){return Number.isFinite(e)?Gt(e,0,1):.5}function pr(e){return Object.freeze({height:At(e.height),left:Number.isFinite(e.left)?e.left:0,top:Number.isFinite(e.top)?e.top:0,width:At(e.width)})}function Fi(e,t){return t==="end"?e.left+e.width:e.left}function Mi(e,t){return t==="end"?e.top+e.height:e.top}function lr(e,t,o){return o<=0?.5:Nn((e-t)/o)}function kn(e,t,o,n){return Object.freeze({horizontal:o,vertical:n,xRatio:lr(e.x,t.left,t.width),yRatio:lr(e.y,t.top,t.height)})}function ur(e,t,o){let n=At(t.width),s=At(t.height),d=pr(o),i=d.width,l=d.height,A=d.left,w=d.top,T=A+i,N=w+l,r=A+Nn(e.xRatio)*i,F=w+Nn(e.yRatio)*l,M=e.horizontal==="end"?r-n:r,I=e.vertical==="end"?F-s:F,b=Math.max(A,T-n),x=Math.max(w,N-s);return Object.freeze({height:s,left:Gt(M,A,b),top:Gt(I,w,x),width:n})}function Dn(e,t,o){let n=At(o),s=At(e.width),d=At(e.height),i=pr(t),l=i.left+i.width,A=i.top+i.height,w=Math.max(i.left,l-s),T=Math.max(i.top,A-d),N=Gt(e.left,i.left,w),r=Gt(e.top,i.top,T),F=Math.abs(N-i.left),M=Math.abs(l-(N+s)),I=Math.abs(r-i.top),b=Math.abs(A-(r+d)),x=Math.min(F,M)<=n?F<=M?i.left:l-s:N,K=Math.min(I,b)<=n?I<=b?i.top:A-d:r;return Object.freeze({height:d,left:x,top:K,width:s})}function gr(e,t,o){let n=Dn(e,t,0),s=n.left+n.width/2,d=n.top+n.height/2,i=t.left+At(t.width)/2,l=t.top+At(t.height)/2,A=s===i?o.horizontal:s<i?"start":"end",w=d===l?o.vertical:d<l?"start":"end";return kn({x:Fi(n,A),y:Mi(n,w)},t,A,w)}function Mt(e,t=0){return Number.isFinite(e)?e:t}function Hi(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function $i(e){return e.button===0&&e.isPrimary}function Bi(e){let t=e.getBoundingClientRect();return Object.freeze({height:Math.max(0,Mt(t.height)),width:Math.max(0,Mt(t.width))})}function zi(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(()=>{t(Date.now())},0)}function fr(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function mr(e,t,o){let n=t.load()??ln,s,d,i,l,A=!1,w=new Set,T=new Set;function N(){let S=e.visualViewport,C=Math.max(0,Mt(S?.width??e.innerWidth)),v=Math.max(0,Mt(S?.height??e.innerHeight)),L=C<=o.compactViewportWidth?o.compactInset:o.desktopInset;return Object.freeze({height:Math.max(0,v-L*2),left:Mt(S?.offsetLeft??0)+L,top:Mt(S?.offsetTop??0)+L,width:Math.max(0,C-L*2)})}function r(){return N().width+o.compactInset*2<=o.compactViewportWidth}function F(S){if(S.hidden||S.dataset.motionMorphing==="true"&&S.dataset.floatingPositioned==="true")return;let C=Bi(S);if(C.width===0||C.height===0)return;let v=ur(n,C,N());return S.style.left=`${String(v.left)}px`,S.style.top=`${String(v.top)}px`,S.style.right="auto",S.style.bottom="auto",S.dataset.floatingPositioned="true",v}function M(){if(!A){d!==void 0&&(fr(e,d),d=void 0);for(let S of w)F(S)}}function I(){A||d!==void 0||(d=zi(e,()=>{d=void 0,M()}))}function b(S){n=S,t.save(n)}function x(S){let C=s;if(C!==void 0){s=void 0,C.handle.dataset.dragging="false",C.surface.dataset.dragging="false";try{C.handle.hasPointerCapture(C.pointerId)&&C.handle.releasePointerCapture(C.pointerId)}catch{}if(S){let v=F(C.surface);if(v!==void 0){let L=Dn(v,N(),o.edgeSnapDistance);b(gr(L,N(),n)),F(C.surface)}}else n=t.load()??ln,M()}}function K(S){let C=s;if(C===void 0||S.pointerId!==C.pointerId)return;let v=Object.freeze({x:S.clientX,y:S.clientY}),L=Object.freeze({x:C.startX,y:C.startY});C.handle.dataset.dragging!=="true"&&Hi(v,L)<o.dragActivationDistance||(C.handle.dataset.dragging!=="true"&&C.onDragStart?.(),C.handle.dataset.dragging="true",C.surface.dataset.dragging="true",n=kn({x:v.x+C.anchorOffsetX,y:v.y+C.anchorOffsetY},N(),n.horizontal,n.vertical),I(),S.preventDefault())}function J(S,C,v,L){S.addEventListener(C,v,L),T.add(()=>{S.removeEventListener(C,v,L)})}function G(S,C,v={}){let L=$=>{if(A||s!==void 0||!$i($)||v.canStartDrag?.($)===!1)return;let k=F(C)??C.getBoundingClientRect(),He=n.horizontal==="end"?k.left+k.width:k.left,de=n.vertical==="end"?k.top+k.height:k.top;s=Object.freeze({anchorOffsetX:He-$.clientX,anchorOffsetY:de-$.clientY,handle:S,...v.onDragStart===void 0?{}:{onDragStart:v.onDragStart},pointerId:$.pointerId,startX:$.clientX,startY:$.clientY,suppressClickOnDrag:v.suppressClickOnDrag??!1,surface:C});try{S.setPointerCapture($.pointerId)}catch{}},te=$=>{s?.pointerId===$.pointerId&&x(S.dataset.dragging==="true")},Ee=$=>{i===S&&(i=void 0,l!==void 0&&(e.clearTimeout(l),l=void 0),$.preventDefault(),$.stopImmediatePropagation())};J(S,"pointerdown",$=>{L($)}),J(S,"lostpointercapture",$=>{te($)}),J(S,"click",$=>{Ee($)},!0)}function h(){x(!1),n=ln,t.clear(),M()}function R(){x(!1)}function O(S){S.key!=="Escape"||s===void 0||(x(!1),S.preventDefault(),S.stopImmediatePropagation())}function _(S){if(s?.pointerId!==S.pointerId)return;let C=s,v=C.handle.dataset.dragging==="true";x(v),v&&C.suppressClickOnDrag&&(i=C.handle,l=e.setTimeout(()=>{i=void 0,l=void 0},0))}function U(S){s?.pointerId===S.pointerId&&x(!1)}return J(e,"pointermove",S=>{K(S)}),J(e,"pointerup",S=>{_(S)}),J(e,"pointercancel",S=>{U(S)}),J(e,"resize",I),J(e,"blur",R),J(e,"keydown",S=>{O(S)},!0),e.visualViewport?.addEventListener("resize",I),e.visualViewport?.addEventListener("scroll",I),T.add(()=>e.visualViewport?.removeEventListener("resize",I)),T.add(()=>e.visualViewport?.removeEventListener("scroll",I)),Object.freeze({attachDraggable:G,dispose(){if(!A){A=!0,x(!1),d!==void 0&&(fr(e,d),d=void 0),l!==void 0&&(e.clearTimeout(l),l=void 0),i=void 0;for(let S of T)S();T.clear(),w.clear()}},isCompact:r,reconcile:M,registerSurface(S){w.add(S)},requestReconcile:I,reset:h})}var ji=1500;function Ui(e){let t=new Set([...e.querySelectorAll("script[nonce]")].map(o=>o.nonce?.trim()??"").filter(Boolean));if(t.size===1)return t.values().next().value}function Vi(e){let t=e.createElement("style");return t.textContent=`
256
+ `;function Wt(e,t,o,n){let s=e.createElement("option");return s.value=o,s.textContent=n,t.append(s),s}function ar(e,t,o){let n=o.messages(),s=g(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let l=g(e,"div");l.className="spotpatch-agent-head",l.setAttribute("data-spotpatch-agent-identity","");let a=g(e,"span");a.className="spotpatch-agent-title";let d=g(e,"span");d.className="spotpatch-agent-badge",l.append(a,d);let C=g(e,"div");C.className="spotpatch-agent-setup";let x=g(e,"div");x.className="spotpatch-agent-selectors";let w=g(e,"label");w.className="spotpatch-agent-mode";let V=g(e,"span"),b=g(e,"select");w.append(V,b);let i=g(e,"label"),W=g(e,"span"),H=g(e,"select");i.append(W,H);let A=g(e,"label"),v=g(e,"span"),q=g(e,"select");A.append(v,q),x.append(w,i,A);let B=g(e,"label");B.className="spotpatch-consent";let I=g(e,"input");I.type="checkbox";let y=g(e,"span");B.append(I,y);let R=g(e,"label");R.className="spotpatch-consent spotpatch-workspace-consent",R.hidden=!0;let L=g(e,"input");L.type="checkbox";let M=g(e,"span"),K=g(e,"strong"),E=g(e,"small");M.append(K,E),R.append(L,M);let T=g(e,"div");T.className="spotpatch-agent-health-list";let O=g(e,"p");O.className="spotpatch-agent-workspace",O.dataset.state="idle";let _=g(e,"p");_.className="spotpatch-agent-capability",_.dataset.state="idle",T.append(O,_),C.append(x,B,R,T);let pe=g(e,"div");pe.className="spotpatch-agent-job",pe.hidden=!0;let ve=g(e,"div");ve.className="spotpatch-agent-job-meta";let D=g(e,"span");D.className="spotpatch-agent-model";let N=g(e,"span");N.className="spotpatch-agent-status",ve.append(D,N);let le=g(e,"p");le.className="spotpatch-agent-phase";let ye=g(e,"p");ye.className="spotpatch-agent-error",ye.hidden=!0;let be=g(e,"ul");be.className="spotpatch-agent-activity";let te=g(e,"div");te.className="spotpatch-agent-result",te.hidden=!0;let st=g(e,"p");st.className="spotpatch-agent-summary";let se=g(e,"ul");se.className="spotpatch-agent-files";let Ue=g(e,"div");Ue.className="spotpatch-agent-checks";let xe=g(e,"pre");xe.className="spotpatch-agent-diff",xe.tabIndex=0,xe.setAttribute("aria-label",n.agent.diffAriaLabel),te.append(st,se,Ue,xe),pe.append(ve,le,ye,be,te),s.append(l,C,pe);let tt=ie(e,n.agent.testConnection),qe=ie(e,n.agent.run,"spotpatch-run"),Ge=ie(e,n.agent.cancel),ee=ie(e,n.agent.apply,"spotpatch-primary"),de=ie(e,n.agent.revert),Ne=ie(e,n.agent.revise),nt=t.enabled?t.providers:[],Ke=t.enabled&&t.applyMode==="trusted-auto",ct=t.enabled?t.applyMode:"review",ot=new Map(nt.map(m=>[m.id,m])),lt=!1,De=!0,ne=!1,Re=!1,Je=!1,U=!1,je,Ce,St=[],Xe,fe="idle",Ye=n.agent.connectionNotTested,Ze,Se="idle",we,ze;for(let m of nt)Wt(e,H,m.id,m.label);t.enabled&&(H.value=t.defaultProvider);let Rt,Ve,We;ct==="auto"?We=Wt(e,b,"auto",n.agent.autoGated):(Rt=Wt(e,b,"review",n.agent.review),Ke&&(Ve=Wt(e,b,"trusted-auto",n.agent.trustedFast)));let dt=Ke?"review":ct;b.value=dt,w.hidden=!Ke;let P=()=>b.value==="trusted-auto"?"trusted-auto":dt,rt=()=>P()==="trusted-auto",Z=()=>ot.get(H.value),Y=m=>m===void 0?n.agent.providerUnavailable:rt()?n.agent.trustedFastConsent(m.label):n.agent.consent(m.label),Me=()=>rt()?I.checked:L.checked,pt=()=>{let m=rt();B.classList.toggle("spotpatch-trusted-consent",m),d.textContent=m?n.agent.trustedFast:ct==="auto"?n.agent.autoGated:n.agent.review,y.textContent=Y(Z()),R.hidden=m||Se!=="consent-required"},Fe=()=>{let m=Z();if(q.replaceChildren(),m===void 0){y.textContent=Y(m);return}for(let F of m.models)Wt(e,q,F.id,F.label);q.value=m.defaultModel,y.textContent=Y(m)},re=()=>{let m=t.enabled&&ne&&!Re;qe.textContent=Je?n.agent.verifying:n.agent.run,qe.classList.toggle("spotpatch-primary",U),tt.hidden=!m,qe.hidden=!m,tt.disabled=!De||Je||Z()===void 0,qe.disabled=!De||Je||!lt||!I.checked||Se==="idle"||Se==="checking"||Se==="blocked"||Se==="consent-required"&&!Me()||Z()===void 0||q.value.length===0,(!Re||!ne)&&(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},Oe=()=>{if(Se==="idle")O.textContent=n.agent.workspaceNotChecked;else if(Se==="checking")O.textContent=n.agent.checkingWorkspace;else if(Se==="ready")O.textContent=n.agent.workspaceReady;else if(Se==="consent-required"){let m=we?.changes;O.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else O.textContent=ze===void 0?n.errors.INTERNAL_ERROR:n.errors[ze]};function He(){Fe(),I.checked=!1,_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function at(){_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function c(){I.checked=!1,L.checked=!1,pt(),re()}Fe(),b.addEventListener("change",c),H.addEventListener("change",He),q.addEventListener("change",at),I.addEventListener("change",re),L.addEventListener("change",re);function u(){if(je===void 0)return;let m=je,F=Ce;D.textContent=`${m.providerLabel} · ${m.modelLabel}`,N.textContent=n.agent.status(m.status),le.textContent=m.phaseMessage;let G=Xe??m.errorCode;ye.hidden=G===void 0,ye.textContent=G===void 0?"":n.errors[G],be.replaceChildren();for(let Q of St.slice(-8)){let _e=g(e,"li");_e.dataset.state=Q.state,_e.textContent=Q.label,be.append(_e)}te.hidden=F===void 0,st.textContent=F?.summary??"",se.replaceChildren(),Ue.replaceChildren(),xe.textContent=F?.diff??"";for(let Q of F?.files??[]){let _e=g(e,"li");_e.textContent=`${Q.kind} ${Q.relativePath} (+${String(Q.additions)} / -${String(Q.deletions)})`,se.append(_e)}for(let Q of F?.checks??[]){let _e=g(e,"details"),Ft=g(e,"summary");Ft.textContent=`${Q.label}: ${Q.status} · ${String(Q.durationMs)} ms`;let Qe=g(e,"pre");Qe.textContent=Q.output.length===0?n.agent.noOutput:Q.output,_e.append(Ft,Qe),Ue.append(_e)}tt.hidden=!0,qe.hidden=!0,Ge.hidden=!ne||!m.canCancel,Ge.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ee.hidden=!ne||!m.canApply,de.hidden=!ne||!m.canRevert,Ne.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function S(){n=o.messages(),a.textContent=n.agent.title,V.textContent=n.agent.mode,Rt!==void 0&&(Rt.textContent=n.agent.review),Ve!==void 0&&(Ve.textContent=n.agent.trustedFast),We!==void 0&&(We.textContent=n.agent.autoGated),W.textContent=n.agent.provider,v.textContent=n.agent.model,H.setAttribute("aria-label",n.agent.providerAriaLabel),q.setAttribute("aria-label",n.agent.modelAriaLabel),K.textContent=n.agent.includeLocalChanges,E.textContent=n.agent.includeLocalChangesHelp,xe.setAttribute("aria-label",n.agent.diffAriaLabel),tt.textContent=n.agent.testConnection,ee.textContent=n.agent.apply,de.textContent=n.agent.revert,Ne.textContent=n.agent.revise,pt(),fe==="idle"?_.textContent=n.agent.connectionNotTested:fe==="probing"?_.textContent=n.agent.testingCapability:fe==="ready"?_.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ze!==void 0?_.textContent=n.errors[Ze]:Z()===void 0?_.textContent=n.agent.providerUnavailable:_.textContent=Ye,Oe(),re(),u()}let $=o.subscribe(S);return S(),Object.freeze({root:s,modeSelect:b,providerSelect:H,modelSelect:q,consentCheckbox:I,workspaceConsentCheckbox:L,testButton:tt,runButton:qe,cancelButton:Ge,applyButton:ee,revertButton:de,resetButton:Ne,consentGranted(){return I.checked},workspaceConsentGranted(){return Me()},readSelection(){let m=Z(),F=m?.models.find(G=>G.id===q.value);return m===void 0||F===void 0?void 0:Object.freeze({applyMode:P(),providerProfileId:m.id,modelProfileId:F.id})},renderCapability(m,F,G,Q){fe=m,Ye=F,Ze=Q,Je=m==="probing",U=m==="ready"&&G?.state==="agent-ready",_.dataset.state=m,_.textContent=G?.state==="agent-ready"?`${F} · ${n.agent.toolsReady}`:F,re()},renderWorkspaceHealth(m,F,G){Se=m,we=F,ze=G??F?.errorCode,O.dataset.state=m,m!=="checking"&&(R.hidden=rt()||m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(L.checked=!1),Oe(),re()},renderJob(m,F,G,Q){Re=!0,C.hidden=!0,pe.hidden=!1,H.disabled=!0,q.disabled=!0,b.disabled=!0,I.disabled=!0,L.disabled=!0,je=m,Ce=F,St=G,Xe=Q,u()},resetJob(){Re=!1,je=void 0,Ce=void 0,St=[],Xe=void 0,C.hidden=!1,pe.hidden=!0,H.disabled=!1,q.disabled=!1,b.disabled=!1,I.disabled=!1,L.disabled=!1,be.replaceChildren(),se.replaceChildren(),Ue.replaceChildren(),xe.textContent="",ye.textContent="",ye.hidden=!0,re()},setContextReady(m){lt=m,re()},setEditingEnabled(m){De=m,H.disabled=!m||Re,q.disabled=!m||Re,b.disabled=!m||Re,I.disabled=!m||Re,L.disabled=!m||Re,re()},setProviderConsent(m){I.checked=m,re()},setSelectionVisible(m){ne=m,re(),m||(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},dispose(){$(),H.removeEventListener("change",He),q.removeEventListener("change",at),b.removeEventListener("change",c),I.removeEventListener("change",re),L.removeEventListener("change",re)}})}var ir="http://www.w3.org/2000/svg",Ri="";function Ci(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:Ri,viewBox:"0 0 1 1"}}function Ti(e,t,o){let n=e.createElementNS(ir,t);for(let[s,l]of Object.entries(o))n.setAttribute(s,l);return n}function vi(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/gu,"-"),n=new Map;for(let s of e.querySelectorAll("[id]")){let l=s.id,a=`${o}-${l}`;n.set(l,a),s.id=a}for(let s of[e,...e.querySelectorAll("*")])for(let l of[...s.attributes]){let a=l.value;for(let[d,C]of n)a=a.replaceAll(`url(#${d})`,`url(#${C})`),a===`#${d}`&&(a=`#${C}`);a!==l.value&&s.setAttribute(l.name,a)}}function $n(e,t,o){let n=Ci(t),s=Ti(e,"svg",{xmlns:ir,class:"spotpatch-brand-mark",viewBox:n.viewBox,"aria-hidden":"true",focusable:"false"});return s.innerHTML=n.content,o!==void 0&&vi(s,o),s}var wi=Symbol.for("spotpatch.data-flow.extension.v1");function qt(e=globalThis){return e[wi]}var Oi=Symbol.for("spotpatch.external-handoff.v1");function gn(){return globalThis[Oi]}var _i=Symbol.for("spotpatch.contextual-ask.v1");function fn(){return globalThis[_i]}var Li=Symbol.for("spotpatch.motion.v1");function sr(){return globalThis[Li]}var ki=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"}),Pi=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ii=Object.freeze({prepare:"Preparing context",dispatch:"Dispatching context",discover:"Discovering project files",search:"Searching source",read:"Reading",patch:"Generating a minimal patch",check:"Running",audit:"Auditing proposed changes",apply:"Applying verified changes",sync:"Returning results to SpotPatch",unknown:"Processing the current task"}),Ni=Object.freeze({prepare:"正在准备上下文",dispatch:"正在派发上下文",discover:"正在查找项目文件",search:"正在搜索源码",read:"正在读取",patch:"正在生成最小修改补丁",check:"正在运行",audit:"正在审计候选修改",apply:"正在应用已验证修改",sync:"正在将结果回流 SpotPatch",unknown:"正在处理当前任务"}),cr=Object.freeze({prepare:"prepare",dispatch:"dispatch",discover:"list",search:"search",read:"read",patch:"patch",check:"check",audit:"audit",apply:"apply",sync:"sync",unknown:"agent"});function lr(e,t,o){return o===void 0||o.length===0?e[t]:`${e[t]} ${o}`}function dr(e,t){return t===void 0||t.length===0?cr[e]:`${cr[e]} · ${t}`}var me="The external Agent handoff request failed.",he="外部 Agent 交接请求失败。",Di=Object.freeze({[p.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[p.INVALID_TOKEN]:"The local SpotPatch session expired.",[p.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[p.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[p.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[p.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[p.EDITOR_OPEN_FAILED]:"The editor request failed.",[p.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[p.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[p.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[p.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[p.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[p.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[p.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[p.AGENT_BUSY]:"Another write Agent job is still active.",[p.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[p.AGENT_CANCELLED]:"The Agent job was cancelled.",[p.EXTERNAL_HANDOFF_DISABLED]:me,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:me,[p.HANDOFF_VALIDATION_FAILED]:me,[p.HANDOFF_SOURCE_STALE]:me,[p.HANDOFF_NOT_FOUND]:me,[p.HANDOFF_EXPIRED]:me,[p.HANDOFF_CURSOR_INVALID]:me,[p.HANDOFF_RESPONSE_TOO_LARGE]:me,[p.BRIDGE_UNAUTHORIZED]:me,[p.BRIDGE_PROTOCOL_MISMATCH]:me,[p.BRIDGE_BUSY]:me,[p.EXTERNAL_AGENT_BUSY]:me,[p.ACTIVE_ADAPTER_CONFLICT]:me,[p.ACTIVE_ADAPTER_LEASE_INVALID]:me,[p.ACTIVE_DISPATCH_INVALID]:me,[p.SESSION_NOT_FOUND]:me,[p.SESSION_AMBIGUOUS]:me,[p.SESSION_CLOSED]:me,[p.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[p.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[p.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[p.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[p.TOOL_DENIED]:"A tool request violated local safety policy.",[p.TOOL_INPUT_INVALID]:"Invalid tool request.",[p.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[p.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[p.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[p.PATCH_REJECTED]:"The patch violated local policy.",[p.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[p.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[p.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Mi=Object.freeze({[p.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[p.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[p.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[p.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[p.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[p.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[p.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[p.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[p.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[p.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[p.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[p.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[p.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[p.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[p.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[p.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[p.AGENT_CANCELLED]:"Agent 任务已取消。",[p.EXTERNAL_HANDOFF_DISABLED]:he,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:he,[p.HANDOFF_VALIDATION_FAILED]:he,[p.HANDOFF_SOURCE_STALE]:he,[p.HANDOFF_NOT_FOUND]:he,[p.HANDOFF_EXPIRED]:he,[p.HANDOFF_CURSOR_INVALID]:he,[p.HANDOFF_RESPONSE_TOO_LARGE]:he,[p.BRIDGE_UNAUTHORIZED]:he,[p.BRIDGE_PROTOCOL_MISMATCH]:he,[p.BRIDGE_BUSY]:he,[p.EXTERNAL_AGENT_BUSY]:he,[p.ACTIVE_ADAPTER_CONFLICT]:he,[p.ACTIVE_ADAPTER_LEASE_INVALID]:he,[p.ACTIVE_DISPATCH_INVALID]:he,[p.SESSION_NOT_FOUND]:he,[p.SESSION_AMBIGUOUS]:he,[p.SESSION_CLOSED]:he,[p.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[p.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[p.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[p.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[p.TOOL_DENIED]:"工具请求违反本地安全策略。",[p.TOOL_INPUT_INVALID]:"工具请求无效。",[p.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[p.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[p.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[p.PATCH_REJECTED]:"补丁违反本地策略。",[p.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[p.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[p.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Fi=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"}),Hi=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:"警告"}),$i=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."}),floatingSurface:Object.freeze({dragHandle:"Drag to move the SpotPatch workbench",resetPosition:"Reset workbench position",positionReset:"SpotPatch position reset to the lower-right corner."}),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:Fi,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted direct",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,trustedFastConsent:e=>`Enable trusted direct mode for ${e}: send allowed project context, include current local changes, skip project validation checks, and immediately apply AI changes, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>ki[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"Receiving context",dispatchingTitle:e=>`Handing off to ${e}`,runningTitle:e=>`Modifying ${e}`,expandedRunningTitle:e=>`${e} is making changes`,completedTitle:"Change complete",expandedCompletedTitle:"Changes complete",failedTitle:"Execution failed",receivingStatus:"Receiving",dispatchingStatus:"Dispatching",runningStatus:"Running",checkingStatus:"Checking",completedStatus:"Done",failedStatus:"Failed",resultReturned:"The result is back in SpotPatch",resultSummary:e=>`${String(e)} ${e===1?"file":"files"}`,activityAction:(e,t)=>lr(Ii,e,t),activityLane:dr}),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:Di}),"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 前,请核对完整上下文与每项目标说明。"}),floatingSurface:Object.freeze({dragHandle:"拖拽以移动 SpotPatch 工作台",resetPosition:"重置工作台位置",positionReset:"SpotPatch 已恢复到右下角。"}),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:Hi,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",mode:"执行方式",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信极速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信极速模式:发送获准的项目上下文、纳入当前本地修改、跳过项目验证检查,并立即应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Pi[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"正在接收上下文",dispatchingTitle:e=>`正在交接给 ${e}`,runningTitle:e=>`正在修改 ${e}`,expandedRunningTitle:e=>`${e} 正在执行修改`,completedTitle:"修改完成",expandedCompletedTitle:"修改已完成",failedTitle:"执行失败",receivingStatus:"接收中",dispatchingStatus:"派发中",runningStatus:"执行中",checkingStatus:"检查中",completedStatus:"完成",failedStatus:"失败",resultReturned:"结果已回流 SpotPatch",resultSummary:e=>`${String(e)} 个文件`,activityAction:(e,t)=>lr(Ni,e,t),activityLane:dr}),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:Mi})});function pr(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 Bi(e,t){if(e!=="auto")return e;let o=pr(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(pr).find(s=>s!==void 0)??"en-US"}function ur(e,t="auto"){let o=Bi(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>$i[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 Ui="spotpatch:floating-surface:";function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function gr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function fr(e){return e==="start"||e==="end"}function zi(e){let t=ji(e);if(!(t?.version!==1||!fr(t.horizontal)||!fr(t.vertical)||!gr(t.xRatio)||!gr(t.yRatio)))return Object.freeze({horizontal:t.horizontal,vertical:t.vertical,xRatio:t.xRatio,yRatio:t.yRatio})}function mr(e,t){let o=`${Ui}${t}`,n;try{n=e.sessionStorage}catch{n=void 0}return Object.freeze({clear(){try{n?.removeItem(o)}catch{}},load(){let s;try{s=n?.getItem(o)??null}catch{return}if(!(s===null||s.length>1024))try{return zi(JSON.parse(s))}catch{return}},save(s){try{n?.setItem(o,JSON.stringify({version:1,...s}))}catch{}}})}var mn=Object.freeze({horizontal:"end",vertical:"end",xRatio:1,yRatio:1});function Gt(e,t,o){return Math.min(Math.max(e,t),o)}function xt(e){return Number.isFinite(e)?Math.max(0,e):0}function Bn(e){return Number.isFinite(e)?Gt(e,0,1):.5}function yr(e){return Object.freeze({height:xt(e.height),left:Number.isFinite(e.left)?e.left:0,top:Number.isFinite(e.top)?e.top:0,width:xt(e.width)})}function Vi(e,t){return t==="end"?e.left+e.width:e.left}function Wi(e,t){return t==="end"?e.top+e.height:e.top}function hr(e,t,o){return o<=0?.5:Bn((e-t)/o)}function Un(e,t,o,n){return Object.freeze({horizontal:o,vertical:n,xRatio:hr(e.x,t.left,t.width),yRatio:hr(e.y,t.top,t.height)})}function br(e,t,o){let n=xt(t.width),s=xt(t.height),l=yr(o),a=l.width,d=l.height,C=l.left,x=l.top,w=C+a,V=x+d,b=C+Bn(e.xRatio)*a,i=x+Bn(e.yRatio)*d,W=e.horizontal==="end"?b-n:b,H=e.vertical==="end"?i-s:i,A=Math.max(C,w-n),v=Math.max(x,V-s);return Object.freeze({height:s,left:Gt(W,C,A),top:Gt(H,x,v),width:n})}function jn(e,t,o){let n=xt(o),s=xt(e.width),l=xt(e.height),a=yr(t),d=a.left+a.width,C=a.top+a.height,x=Math.max(a.left,d-s),w=Math.max(a.top,C-l),V=Gt(e.left,a.left,x),b=Gt(e.top,a.top,w),i=Math.abs(V-a.left),W=Math.abs(d-(V+s)),H=Math.abs(b-a.top),A=Math.abs(C-(b+l)),v=Math.min(i,W)<=n?i<=W?a.left:d-s:V,q=Math.min(H,A)<=n?H<=A?a.top:C-l:b;return Object.freeze({height:l,left:v,top:q,width:s})}function Sr(e,t,o){let n=jn(e,t,0),s=n.left+n.width/2,l=n.top+n.height/2,a=t.left+xt(t.width)/2,d=t.top+xt(t.height)/2,C=s===a?o.horizontal:s<a?"start":"end",x=l===d?o.vertical:l<d?"start":"end";return Un({x:Vi(n,C),y:Wi(n,x)},t,C,x)}function Mt(e,t=0){return Number.isFinite(e)?e:t}function qi(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Gi(e){return e.button===0&&e.isPrimary}function Ki(e){let t=e.getBoundingClientRect();return Object.freeze({height:Math.max(0,Mt(t.height)),width:Math.max(0,Mt(t.width))})}function Ji(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(()=>{t(Date.now())},0)}function Er(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Ar(e,t,o){let n=t.load()??mn,s,l,a,d,C=!1,x=new Set,w=new Set;function V(){let E=e.visualViewport,T=Math.max(0,Mt(E?.width??e.innerWidth)),O=Math.max(0,Mt(E?.height??e.innerHeight)),_=T<=o.compactViewportWidth?o.compactInset:o.desktopInset;return Object.freeze({height:Math.max(0,O-_*2),left:Mt(E?.offsetLeft??0)+_,top:Mt(E?.offsetTop??0)+_,width:Math.max(0,T-_*2)})}function b(){return V().width+o.compactInset*2<=o.compactViewportWidth}function i(E){if(E.hidden||E.dataset.motionMorphing==="true"&&E.dataset.floatingPositioned==="true")return;let T=Ki(E);if(T.width===0||T.height===0)return;let O=br(n,T,V());return E.style.left=`${String(O.left)}px`,E.style.top=`${String(O.top)}px`,E.style.right="auto",E.style.bottom="auto",E.dataset.floatingPositioned="true",O}function W(){if(!C){l!==void 0&&(Er(e,l),l=void 0);for(let E of x)i(E)}}function H(){C||l!==void 0||(l=Ji(e,()=>{l=void 0,W()}))}function A(E){n=E,t.save(n)}function v(E){let T=s;if(T!==void 0){s=void 0,T.handle.dataset.dragging="false",T.surface.dataset.dragging="false";try{T.handle.hasPointerCapture(T.pointerId)&&T.handle.releasePointerCapture(T.pointerId)}catch{}if(E){let O=i(T.surface);if(O!==void 0){let _=jn(O,V(),o.edgeSnapDistance);A(Sr(_,V(),n)),i(T.surface)}}else n=t.load()??mn,W()}}function q(E){let T=s;if(T===void 0||E.pointerId!==T.pointerId)return;let O=Object.freeze({x:E.clientX,y:E.clientY}),_=Object.freeze({x:T.startX,y:T.startY});T.handle.dataset.dragging!=="true"&&qi(O,_)<o.dragActivationDistance||(T.handle.dataset.dragging!=="true"&&T.onDragStart?.(),T.handle.dataset.dragging="true",T.surface.dataset.dragging="true",n=Un({x:O.x+T.anchorOffsetX,y:O.y+T.anchorOffsetY},V(),n.horizontal,n.vertical),H(),E.preventDefault())}function B(E,T,O,_){E.addEventListener(T,O,_),w.add(()=>{E.removeEventListener(T,O,_)})}function I(E,T,O={}){let _=D=>{if(C||s!==void 0||!Gi(D)||O.canStartDrag?.(D)===!1)return;let N=i(T)??T.getBoundingClientRect(),le=n.horizontal==="end"?N.left+N.width:N.left,ye=n.vertical==="end"?N.top+N.height:N.top;s=Object.freeze({anchorOffsetX:le-D.clientX,anchorOffsetY:ye-D.clientY,handle:E,...O.onDragStart===void 0?{}:{onDragStart:O.onDragStart},pointerId:D.pointerId,startX:D.clientX,startY:D.clientY,suppressClickOnDrag:O.suppressClickOnDrag??!1,surface:T});try{E.setPointerCapture(D.pointerId)}catch{}},pe=D=>{s?.pointerId===D.pointerId&&v(E.dataset.dragging==="true")},ve=D=>{a===E&&(a=void 0,d!==void 0&&(e.clearTimeout(d),d=void 0),D.preventDefault(),D.stopImmediatePropagation())};B(E,"pointerdown",D=>{_(D)}),B(E,"lostpointercapture",D=>{pe(D)}),B(E,"click",D=>{ve(D)},!0)}function y(){v(!1),n=mn,t.clear(),W()}function R(){v(!1)}function L(E){E.key!=="Escape"||s===void 0||(v(!1),E.preventDefault(),E.stopImmediatePropagation())}function M(E){if(s?.pointerId!==E.pointerId)return;let T=s,O=T.handle.dataset.dragging==="true";v(O),O&&T.suppressClickOnDrag&&(a=T.handle,d=e.setTimeout(()=>{a=void 0,d=void 0},0))}function K(E){s?.pointerId===E.pointerId&&v(!1)}return B(e,"pointermove",E=>{q(E)}),B(e,"pointerup",E=>{M(E)}),B(e,"pointercancel",E=>{K(E)}),B(e,"resize",H),B(e,"blur",R),B(e,"keydown",E=>{L(E)},!0),e.visualViewport?.addEventListener("resize",H),e.visualViewport?.addEventListener("scroll",H),w.add(()=>e.visualViewport?.removeEventListener("resize",H)),w.add(()=>e.visualViewport?.removeEventListener("scroll",H)),Object.freeze({attachDraggable:I,dispose(){if(!C){C=!0,v(!1),l!==void 0&&(Er(e,l),l=void 0),d!==void 0&&(e.clearTimeout(d),d=void 0),a=void 0;for(let E of w)E();w.clear(),x.clear()}},isCompact:b,reconcile:W,registerSurface(E){x.add(E)},requestReconcile:H,reset:y})}var Xi=1500;function Yi(e){let t=new Set([...e.querySelectorAll("script[nonce]")].map(o=>o.nonce?.trim()??"").filter(Boolean));if(t.size===1)return t.values().next().value}function Zi(e){let t=e.createElement("style");return t.textContent=`
257
257
  :host {
258
258
  all: initial;
259
259
  --spotpatch-bg: #0e0e12;
@@ -282,16 +282,16 @@ ${cn(e.code.language,ee(t.codeLines.join(`
282
282
  button, textarea, select { font: inherit; }
283
283
  .spotpatch-floating-surface {
284
284
  position: fixed;
285
- right: ${String(Ot.desktopInset)}px;
286
- bottom: ${String(Ot.desktopInset)}px;
287
- z-index: ${String(sn.controls)};
285
+ right: ${String(_t.desktopInset)}px;
286
+ bottom: ${String(_t.desktopInset)}px;
287
+ z-index: ${String(pn.controls)};
288
288
  isolation: isolate;
289
289
  }
290
290
  .spotpatch-highlight {
291
291
  position: fixed;
292
292
  top: 0;
293
293
  left: 0;
294
- z-index: ${String(sn.highlight)};
294
+ z-index: ${String(pn.highlight)};
295
295
  box-sizing: border-box;
296
296
  border: 2px solid var(--spotpatch-accent);
297
297
  border-radius: 6px;
@@ -318,7 +318,7 @@ ${cn(e.code.language,ee(t.codeLines.join(`
318
318
  .spotpatch-selection-highlights {
319
319
  position: fixed;
320
320
  inset: 0;
321
- z-index: ${String(sn.highlight)};
321
+ z-index: ${String(pn.highlight)};
322
322
  pointer-events: none;
323
323
  }
324
324
  .spotpatch-selection-highlight {
@@ -356,7 +356,7 @@ ${cn(e.code.language,ee(t.codeLines.join(`
356
356
  .spotpatch-dialog {
357
357
  position: relative;
358
358
  box-sizing: border-box;
359
- width: min(${String(Ot.workbenchMaxWidth)}px, calc(100vw - ${String(Ot.desktopInset*2)}px));
359
+ width: min(${String(_t.workbenchMaxWidth)}px, calc(100vw - ${String(_t.desktopInset*2)}px));
360
360
  outline: none;
361
361
  }
362
362
  .spotpatch-shell {
@@ -364,7 +364,7 @@ ${cn(e.code.language,ee(t.codeLines.join(`
364
364
  z-index: 1;
365
365
  display: flex;
366
366
  box-sizing: border-box;
367
- max-height: min(${String(Ot.workbenchMaxHeight)}px, calc(100vh - ${String(Ot.desktopInset*2)}px));
367
+ max-height: min(${String(_t.workbenchMaxHeight)}px, calc(100vh - ${String(_t.desktopInset*2)}px));
368
368
  overflow: hidden;
369
369
  flex-direction: column;
370
370
  }
@@ -853,10 +853,10 @@ ${cn(e.code.language,ee(t.codeLines.join(`
853
853
  .spotpatch-target-state { display: none; }
854
854
  .spotpatch-repository { display: none; }
855
855
  }
856
- ${Zo}
857
- `,t}function Wi(e,t){return e.split(`
858
- `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Gi(e){let t=e.target;return t instanceof Element&&t.closest("a, button, input, select, textarea, summary, [contenteditable='true']")!==null}function qi(e){let t=oe(e,"","spotpatch-execution-island");t.hidden=!0,t.setAttribute("aria-hidden","true");let o=In(e,void 0,"spotpatch-fallback-execution-island");o.classList.add("spotpatch-execution-logo");let n=g(e,"span");return t.append(o,n),Object.freeze({canExpand:()=>!1,isExpanded:()=>!1,root:t,setExpanded:()=>{},render(s){let d=[s.headline,s.action,s.meta].filter(i=>i.length>0).join(" · ");n.textContent=d,t.setAttribute("aria-label",d)},dispose(){}})}function Ki(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:oe(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function hr(e,t,o=Object.freeze({enabled:!1}),n="auto",s=!1,d=!1,i="vite",l=""){let A=ir(e,n),w=e.defaultView;if(w===null)throw new Error("SpotPatch requires a document with an associated window.");let T=w,N=mr(T,dr(T,l),Ot),r=A.messages(),F="idle",M=!1,I=!1,b,x,K,J,G,h,R=e.createElement("spotpatch-root");R.setAttribute(kt,"");let O=R.attachShadow({mode:"open"}),_=g(e,"div");_.className="spotpatch-floating-surface",_.dataset.scene="pill",_.dataset.tone="neutral";let U=oe(e,r.trigger.select,"spotpatch-trigger");U.title=r.trigger.title(t),U.setAttribute("aria-pressed","false");let S=tr(),C=S?.createExecutionIsland(e),v=C??qi(e),L=v.root,te=g(e,"div");te.className="spotpatch-highlight",te.hidden=!0;let Ee=g(e,"span");Ee.className="spotpatch-highlight-label",te.append(Ee);let $=g(e,"div");$.className="spotpatch-selection-highlights",$.setAttribute("aria-hidden","true");let k=g(e,"section");k.className="spotpatch-dialog",k.hidden=!0,k.tabIndex=-1,k.setAttribute("role","dialog"),k.setAttribute("aria-labelledby","spotpatch-selection-title");let He=g(e,"div");He.className="spotpatch-shell";let de=g(e,"header");de.className="spotpatch-header",de.setAttribute("data-spotpatch-drag-handle","");let $e=g(e,"div");$e.className="spotpatch-brand-row";let Ae=g(e,"div");Ae.className="spotpatch-brand";let ht=g(e,"span");ht.className="spotpatch-brand-copy";let le=g(e,"span");le.className="spotpatch-brand-name";let We=g(e,"span");We.className="spotpatch-brand-context",ht.append(le,We),Ae.append(In(e),ht);let xe=g(e,"span");xe.className="spotpatch-header-controls";let be=g(e,"a");be.className="spotpatch-repository",be.href=Tn,be.target="_blank",be.rel="noopener noreferrer";let Re=oe(e,"","spotpatch-locale"),Y=oe(e,"⌖","spotpatch-reset-position"),_e=oe(e,"×","spotpatch-close");xe.append(be,Re,Y,_e),$e.append(Ae,xe);let Ke=g(e,"h2");Ke.id="spotpatch-selection-title",Ke.className="spotpatch-title";let Je=g(e,"p");Je.className="spotpatch-subtitle";let Qe=g(e,"div");Qe.className="spotpatch-target-row";let Xe=g(e,"span");Xe.className="spotpatch-target-label";let ne=g(e,"span");ne.className="spotpatch-context-state",ne.dataset.state="loading",ne.textContent=r.context.collecting,Qe.append(Xe,ne),de.append($e,Ke,Je,Qe);let xt=g(e,"div");xt.className="spotpatch-body";let et=g(e,"div");et.className="spotpatch-selection-panel";let tt=g(e,"section");tt.className="spotpatch-targets";let Be=g(e,"div");Be.className="spotpatch-targets-heading";let ze=g(e,"span"),j=g(e,"span");j.className="spotpatch-targets-meta";let Ce=g(e,"span");Ce.className="spotpatch-target-complete";let Te=g(e,"span");Te.className="spotpatch-target-budget",Te.setAttribute("aria-live","polite");let nt=g(e,"span");nt.className="spotpatch-target-count",j.append(Ce,Te),Qe.append(nt),Be.append(ze,j);let st=g(e,"div");st.className="spotpatch-target-progress",st.setAttribute("aria-hidden","true");let yt=g(e,"div");yt.className="spotpatch-target-progress-fill",st.append(yt);let fe=g(e,"div");fe.className="spotpatch-target-list",tt.append(Be,st,fe);let je=g(e,"details");je.className="spotpatch-diagnostics";let ot=g(e,"summary"),ve=g(e,"span"),rt=g(e,"span");rt.className="spotpatch-source-peek",rt.textContent=r.diagnostics.resolving,ot.append(ve,rt);let Le=g(e,"pre");Le.className="spotpatch-summary",je.append(ot,Le);let P=Qo(e,o,A),ct=g(e,"div");function re(){M&&N.requestReconcile()}let Z=d?dn()?.createPanel(e,i,A.locale,l,A.subscribe,re,Tr,vr):void 0;ct.append(tt,P.root,...Z===void 0?[]:[Z.root]);let Ge=Wt()?.createPanel(e,s,A.locale,ct,je,re)??Ki(e,ct,je);et.append(Ge.root);let qe=g(e,"div");qe.className="spotpatch-preview-panel",qe.hidden=!0;let me=g(e,"pre");me.className="spotpatch-prompt",me.tabIndex=0,me.setAttribute("aria-label",r.diagnostics.promptAriaLabel),qe.append(me),xt.append(et,qe);let bt=g(e,"footer");bt.className="spotpatch-actions";let Pe=g(e,"div");Pe.className="spotpatch-context-state spotpatch-editor-feedback",Pe.dataset.state="idle",Pe.setAttribute("role","status"),Pe.setAttribute("aria-live","polite"),Pe.hidden=!0;let Ie=oe(e,r.actions.addElement),Ye=oe(e,r.actions.reselect),Q=oe(e,r.actions.openEditor),Ue=oe(e,r.actions.preview,"spotpatch-primary"),c=oe(e,r.actions.copy,"spotpatch-primary"),u=oe(e,r.actions.back),E=g(e,"div");E.className="spotpatch-secondary-actions";let H=g(e,"div");H.className="spotpatch-primary-actions",Ie.classList.add("spotpatch-icon-action"),Ie.dataset.compactIcon="+",P.testButton.classList.add("spotpatch-icon-action"),P.testButton.dataset.compactIcon="✓",Q.classList.add("spotpatch-secondary-action"),Ye.classList.add("spotpatch-secondary-action"),E.append(Q,Ye),H.append(P.testButton,Ie,P.runButton,...Z===void 0?[]:[Z.sendButton],Ue,P.cancelButton,P.applyButton,P.revertButton,P.resetButton,c,u),bt.append(Pe,E,H),He.append(de,xt,bt),k.append(He);let V=g(e,"div");V.className="spotpatch-live",V.setAttribute("aria-live","polite"),V.setAttribute("aria-atomic","true");let ie=[Vi(e),...S===void 0?[]:[S.createStyles(e)],Ge.styles,...Z===void 0?[]:[Z.styles]],y=Ui(e);if(y!==void 0)for(let a of ie)a.nonce=y;O.append(...ie,$,te,_,V),_.append(U,k,L),e.documentElement.append(R),N.registerSurface(_);let W=S===void 0||C===void 0?void 0:S.createController(e,Object.freeze({execution:C.elements,pill:U,planner:k,surface:_}),N.reconcile),pe=()=>{W?.cancel()};N.attachDraggable(U,_,{onDragStart:pe,suppressClickOnDrag:!0}),N.attachDraggable(de,_,{canStartDrag:a=>!N.isCompact()&&!Gi(a),onDragStart:pe}),N.attachDraggable(L,_,{onDragStart:pe,suppressClickOnDrag:!0}),N.reconcile();let se=!1,Ne=!1,_t="",Lt=!0,at=[],qt=0,$n="idle",Bn=Object.freeze({component:Object.freeze({status:s?"idle":"disabled"}),page:Object.freeze({status:s?"idle":"disabled"}),observationCount:0});function Kt(){let a=at.find(f=>f.active);return Object.freeze(a===void 0?{label:r.context.selectedElement,source:""}:{label:a.label,source:a.source})}function Pt(){let a=Kt();return a.source.length===0?a.label:`${a.label} · ${a.source}`}function zn(){return h=new Date().toISOString(),h}function jn(){return h??zn()}function Jt(a){G!==void 0&&(T.clearTimeout(G),G=void 0),a&&(K=void 0,J=void 0)}function pn(a){return J===a?!1:(K===a||(Jt(!1),K=a,G=T.setTimeout(()=>{G=void 0,R.isConnected&&(J=a,b=void 0,h=void 0,I=!1,M=!1,we())},ji)),!0)}function Cr(a){return a.startsWith("claude")?r.execution.claude:a.startsWith("codex")?r.execution.codex:a}function Un(a){return Object.freeze({...a.detail===void 0?{}:{detail:a.detail},key:a.key,kind:a.kind,label:r.execution.activityLane(a.kind,a.detail),state:a.state})}function Dt(a,f,m,D="active"){return Object.freeze({...m===void 0?{}:{detail:m},key:a,kind:f,label:r.execution.activityLane(f,m),state:D})}function we(){let a=F==="inspecting",f=!M||a,m=f?{scene:a?"capturing":"pill",tone:a?"capturing":"neutral",headline:U.textContent,action:"",meta:"",recentActivities:Object.freeze([])}:!I&&b!==void 0?b:{scene:"planner",tone:"ready",headline:r.dialog.editTitle,action:r.dialog.editSubtitle,meta:r.context.ready,recentActivities:Object.freeze([])};if(W!==void 0){W.render(m,()=>{v.render(m)});return}v.render(m),_.dataset.scene=m.scene,_.dataset.tone=m.tone;let D=m.scene==="planner";U.hidden=!f,U.inert=!f,k.hidden=!D,k.inert=!D,k.setAttribute("aria-hidden",String(!D)),L.hidden=f||D,L.inert=f||D,L.setAttribute("aria-hidden",String(f||D)),N.reconcile()}function Tr(a){if(a===null?(x=void 0,h=void 0):x!==void 0&&a.phase!=="failed"&&a.phase!=="delivery-unknown"?un():(a.phase==="failed"||a.phase==="delivery-unknown")&&(x=void 0),a!==null&&!I){let f=a.phase==="failed"||a.phase==="delivery-unknown",m=a.phase==="completed",D=f||m?void 0:jn();(f||m)&&(h=void 0);let B=`dispatch:${String(a.revision)}`;if(m&&!pn(B)){b=void 0,we();return}let ae=Cr(a.adapterKind),ke=Kt(),ue=a.phase==="queued"||a.phase==="dispatching"||a.phase==="dispatched"?"dispatch":m?"sync":"unknown",De=Dt(`dispatch:${String(a.revision)}:${a.phase}`,ue,a.phase,f?"failure":m?"success":"active"),z=f?"failed":m?"success":a.phase==="working"?"running":"handoff";b={scene:z,tone:f?"danger":m?"success":"running",headline:m?r.execution.completedTitle:f?r.execution.failedTitle:z==="running"?r.execution.runningTitle(ke.label):r.execution.dispatchingTitle(ae),action:m?r.execution.resultReturned:ke.source,expandedHeadline:m?r.execution.expandedCompletedTitle:f?r.execution.failedTitle:z==="running"?r.execution.expandedRunningTitle(ae):r.execution.dispatchingTitle(ae),expandedAction:m?r.execution.resultReturned:Pt(),meta:f?r.execution.failedStatus:m?r.execution.completedStatus:z==="running"?r.execution.runningStatus:r.execution.dispatchingStatus,activity:De,recentActivities:Object.freeze([De]),...D===void 0?{}:{startedAt:D}}}else a===null&&(b=void 0);we()}function vr(a){let f=a?.task;if(a===void 0||f===void 0||I)return;let m=f.managedPhase,D=m==="failed"||m==="cleanup-warning",B=m==="completed"||m==="review-required",ae=m==="cancelled";if(D||ae?x=void 0:x!==void 0&&un(),ae){b=void 0,h=void 0,we();return}let ke=D||B?void 0:jn();if((D||B)&&(h=void 0),m==="completed"&&!pn(`managed:${String(f.revision)}`)){b=void 0,we();return}let ue=D?"failed":B?"success":m==="preparing"?"handoff":"running",De=D?"danger":B?"success":"running",z=r.execution.codex,X=Kt(),Ze=m==="preparing"?"prepare":m==="auditing"?"audit":m==="validating"?"check":m==="applying"?"apply":B?"sync":"unknown",dt=f.checks.at(-1),lt=f.files.at(-1),pt=m==="validating"?dt?.id:m==="auditing"||m==="applying"?lt?.path:void 0,Rt=Dt(`managed:${String(f.revision)}:${m}:${pt??""}`,Ze,pt,D?"failure":B?"success":"active"),Ht=Object.freeze([...f.files.slice(-2).map(ut=>Dt(`managed-file:${String(f.revision)}:${ut.path}`,"patch",ut.path,"success")),...f.checks.slice(-2).map(ut=>Dt(`managed-check:${String(f.revision)}:${ut.id}`,"check",ut.id,ut.outcome==="passed"?"success":"failure")),Rt]);b={scene:ue,tone:De,headline:B?r.execution.completedTitle:D?r.execution.failedTitle:ue==="handoff"?r.execution.dispatchingTitle(z):m==="validating"?r.execution.activityAction("check",pt):r.execution.runningTitle(X.label),action:B?f.files.length===0?r.execution.resultReturned:r.execution.resultSummary(f.files.length):X.source,expandedHeadline:B?r.execution.expandedCompletedTitle:D?r.execution.failedTitle:ue==="handoff"?r.execution.dispatchingTitle(z):r.execution.expandedRunningTitle(z),expandedAction:B?r.execution.resultReturned:Pt(),meta:D?r.execution.failedStatus:B?r.execution.completedStatus:m==="validating"?r.execution.checkingStatus:ue==="handoff"?r.execution.dispatchingStatus:r.execution.runningStatus,activity:Rt,recentActivities:Ht,...ke===void 0?{}:{startedAt:ke}},we()}function wr(a,f){if(!M)return;Jt(!0);let m=zn();I=!1;let D=Dt(`dispatch-start:${Pt()}`,"dispatch",Pt());b={scene:"agent-charging",tone:"running",headline:r.execution.receivingTitle,action:Pt(),expandedHeadline:r.execution.receivingTitle,expandedAction:Pt(),meta:r.execution.receivingStatus,activity:D,recentActivities:Object.freeze([D]),startedAt:m},we(),W?.dispatch(a,f)}function Vn(a,f){!M||a.disabled||(x=Object.freeze({source:a,target:f}))}function un(){let a=x;x=void 0,!(a===void 0||!a.source.isConnected||!a.target.isConnected)&&wr(a.source,a.target)}function gn(a){$n=a,Pe.dataset.state=a,Pe.hidden=a==="idle",Pe.textContent=a==="opening"?r.announcements.editorOpening:a==="success"?r.announcements.editorOpened:a==="error"?r.announcements.editorFailed:"",re()}function Or(a){return a.status==="ready"?r.targets.statusReady:a.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function Xt(a,f){let m=f===0?0:a/f;yt.style.width=`${String(m*100)}%`}function Wn(a){let f=fe.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(f).find(m=>a===void 0||m.dataset.targetInstructionId===a)}function Gn(a,f){let m=O.activeElement?.closest("textarea[data-target-instruction-id]"),D=m?.dataset.targetInstructionId,B=m?.selectionStart,ae=m?.selectionEnd;at=a.map(z=>Object.freeze({...z})),qt=f,fe.replaceChildren();let ke=a.filter(z=>z.instruction.trim().length>0).length,ue=a.reduce((z,X)=>z+X.instruction.trim().length,0);Xt(ke,a.length),nt.textContent=r.targets.count(a.length,f),Ce.textContent=r.targets.complete(ke,a.length);let De=ue>4e3;Te.dataset.state=De?"over":"ready",Te.textContent=De?r.targets.instructionBudgetExceeded(ue,4e3):r.targets.instructionBudget(ue,4e3),Ie.disabled=!Lt||a.length>=f,Ie.title=a.length>=f?r.targets.limitTitle(f):r.targets.addTitle,Xe.textContent=a.length===1?a[0]?.label??r.context.selectedElement:r.context.selectedCount(a.length);for(let[z,X]of a.entries()){let Ze=g(e,"div");Ze.className="spotpatch-target-item",Ze.dataset.active=String(X.active),Ze.dataset.status=X.status,Ze.dataset.targetId=X.id;let dt=g(e,"div");dt.className="spotpatch-target-summary";let lt=oe(e,"","spotpatch-target-select");lt.dataset.activateTargetId=X.id,lt.setAttribute("aria-label",r.targets.activate(z+1)),lt.setAttribute("aria-expanded",String(X.active));let pt=g(e,"span");pt.className="spotpatch-target-index",pt.textContent=String(z+1);let Rt=g(e,"span");Rt.className="spotpatch-target-copy";let Ht=g(e,"span");Ht.className="spotpatch-target-name",Ht.textContent=X.label;let ut=g(e,"span");ut.className="spotpatch-target-source",ut.textContent=`${Or(X)} · ${X.source}`,Rt.append(Ht,ut);let no=X.instruction.trim().length>0,Yt=g(e,"span");Yt.className="spotpatch-target-state",Yt.dataset.complete=String(no),Yt.textContent=no?r.targets.instructionReady:r.targets.instructionMissing,lt.append(pt,Rt,Yt);let $t=oe(e,"↗","spotpatch-target-open");$t.dataset.openTargetId=X.id,$t.disabled=!X.canOpenEditor,$t.setAttribute("aria-label",r.actions.openTarget(z+1)),$t.title=r.actions.openTarget(z+1);let Bt=oe(e,"×","spotpatch-target-remove");if(Bt.dataset.removeTargetId=X.id,Bt.disabled=!Lt,Bt.setAttribute("aria-label",r.targets.remove(z+1)),Bt.title=r.targets.removeTitle,dt.append(lt,$t,Bt),Ze.append(dt),X.active){let mn=g(e,"label");mn.className="spotpatch-target-editor";let hn=g(e,"span");hn.className="spotpatch-target-editor-head";let yn=g(e,"span");yn.className="spotpatch-target-editor-label",yn.textContent=r.targets.instructionLabel(X.label);let bn=g(e,"span");bn.className="spotpatch-target-editor-count",bn.textContent=r.targets.instructionCount(X.instruction.length,2e3),hn.append(yn,bn);let Ct=g(e,"textarea");Ct.rows=4,Ct.maxLength=2e3,Ct.value=X.instruction,Ct.placeholder=r.targets.instructionPlaceholder,Ct.disabled=!Lt,Ct.dataset.targetInstructionId=X.id,Ct.setAttribute("aria-label",r.targets.instructionLabel(X.label)),mn.append(hn,Ct),Ze.append(mn)}fe.append(Ze)}if(D!==void 0){let z=Wn(D);z?.focus({preventScroll:!0}),B!==void 0&&ae!==void 0&&z?.setSelectionRange(B,ae)}re()}function _r(a,f){at=at.map(z=>z.id===a?Object.freeze({...z,instruction:f}):z);let m=Array.from(fe.querySelectorAll(".spotpatch-target-item")).find(z=>z.dataset.targetId===a);if(m===void 0)return;let D=f.trim().length>0,B=m.querySelector(".spotpatch-target-state"),ae=m.querySelector(".spotpatch-target-editor-count");B!==null&&(B.dataset.complete=String(D),B.textContent=D?r.targets.instructionReady:r.targets.instructionMissing),ae!==null&&(ae.textContent=r.targets.instructionCount(f.length,2e3));let ke=at.filter(z=>z.instruction.trim().length>0).length;Ce.textContent=r.targets.complete(ke,at.length),Xt(ke,at.length);let ue=at.reduce((z,X)=>z+X.instruction.trim().length,0),De=ue>4e3;Te.dataset.state=De?"over":"ready",Te.textContent=De?r.targets.instructionBudgetExceeded(ue,4e3):r.targets.instructionBudget(ue,4e3)}function Lr(a){$.replaceChildren();for(let[f,m]of a.entries()){let D=g(e,"div");D.className="spotpatch-selection-highlight",D.dataset.targetId=m.id,D.dataset.active=String(m.active),D.style.transform=`translate(${String(m.rect.x)}px, ${String(m.rect.y)}px)`,D.style.width=`${String(m.rect.width)}px`,D.style.height=`${String(m.rect.height)}px`;let B=g(e,"span");B.textContent=`${String(f+1)} · ${m.label}`,D.append(B),$.append(D)}}function qn(a){let f=r.summary,m=Wi(a,f.source);rt.textContent=m??r.diagnostics.noExactSource;let D=`${f.browserContext}: ${f.collectionStatuses.ready}`,B=`${f.browserContext}: ${f.collectionStatuses.loading}`,ae=`${f.browserContext}: ${f.collectionStatuses.failed}`,ke=`${f.api}: ${f.apiStatuses.loading}`,ue=`${f.api}: ${f.apiStatuses.failed}`;a.includes(D)&&!a.includes(B)&&!a.includes(ke)&&!a.includes(ae)&&!a.includes(ue)?(ne.dataset.state="ready",ne.textContent=r.context.ready):a.includes(ae)||a.includes(ue)?(ne.dataset.state="warning",ne.textContent=r.context.partial):(ne.dataset.state="loading",ne.textContent=r.context.collecting)}function Kn(a,f,m){se=f,Ne=m,_t=a,Le.textContent=a,Q.disabled=!f,Ue.disabled=!m,P.setContextReady(m),Z?.setContextReady(m),qn(a),re()}function fn(a){F=a;let f=a==="selected",m=a==="previewing";et.hidden=!f,qe.hidden=!m,Ye.hidden=!f,Ie.hidden=!f,Q.hidden=!f,Ue.hidden=!f,E.hidden=!f,P.setSelectionVisible(f),Z?.setSelectionVisible(f),c.hidden=!m,u.hidden=!m,Ke.textContent=m?r.dialog.previewTitle:r.dialog.editTitle,Je.textContent=m?r.dialog.previewSubtitle:r.dialog.editSubtitle,we()}function Jn(){r=A.messages(),le.textContent=r.brand.name,We.textContent=r.brand.context,be.textContent=r.brand.repository,be.title=r.brand.repositoryTitle,be.setAttribute("aria-label",r.brand.repositoryTitle),Re.textContent=r.alternateLocaleName,Re.title=r.switchLocale,Re.setAttribute("aria-label",r.switchLocale),Y.title=r.floatingSurface.resetPosition,Y.setAttribute("aria-label",r.floatingSurface.resetPosition),_e.setAttribute("aria-label",r.dialog.close),_e.title=r.dialog.close,de.title=r.floatingSurface.dragHandle,tt.setAttribute("aria-label",r.targets.ariaLabel),ze.textContent=r.targets.title,ve.textContent=r.diagnostics.title,me.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Ie.textContent=r.actions.addElement,Ye.textContent=r.actions.reselect,Q.textContent=r.actions.openEditor,Ue.textContent=r.actions.preview,c.textContent=r.actions.copy,u.textContent=r.actions.back,Ge.render(Bn),U.title=r.trigger.title(t),U.textContent=F==="inspecting"?r.trigger.stop:r.trigger.select,fn(F),gn($n),at.length>0?Gn(at,qt):(nt.textContent=r.targets.count(0,qt),Ce.textContent=r.targets.complete(0,0),Xt(0,0),Te.dataset.state="ready",Te.textContent=r.targets.instructionBudget(0,4e3),Xe.textContent=r.context.selectedElement),_t.length>0?qn(_t):(rt.textContent=r.diagnostics.resolving,ne.textContent=r.context.collecting)}function Xn(a){V.textContent="",V.textContent=a}function Yn(){N.reset(),Xn(r.floatingSurface.positionReset)}je.addEventListener("toggle",re),Re.addEventListener("click",A.toggle),Y.addEventListener("click",Yn);let Zn=()=>{Vn(P.runButton,P.root)},Qn=()=>{Z!==void 0&&Vn(Z.sendButton,Z.root)},eo=()=>{if(v.canExpand()&&!v.isExpanded()){W===void 0?(v.setExpanded(!0),N.reconcile()):W.updateLayout(()=>{v.setExpanded(!0)});return}Jt(!1),I=!0,we()},to=a=>{a.key!=="Escape"||!v.isExpanded()||(a.preventDefault(),a.stopPropagation(),W===void 0?(v.setExpanded(!1),N.reconcile()):W.updateLayout(()=>{v.setExpanded(!1)}))};P.runButton.addEventListener("click",Zn),Z?.sendButton.addEventListener("click",Qn),L.addEventListener("click",eo),L.addEventListener("keydown",to);let Pr=A.subscribe(Jn);return Jn(),Object.freeze({host:R,triggerButton:U,addTargetButton:Ie,targetList:fe,reselectButton:Ye,openEditorButton:Q,repositoryLink:be,previewButton:Ue,copyButton:c,dataFlowRefreshButton:Ge.refreshButton,backButton:u,closeButton:_e,agentProviderSelect:P.providerSelect,agentModelSelect:P.modelSelect,agentModeSelect:P.modeSelect,agentConsentCheckbox:P.consentCheckbox,agentWorkspaceConsentCheckbox:P.workspaceConsentCheckbox,agentTestButton:P.testButton,agentRunButton:P.runButton,agentCancelButton:P.cancelButton,agentApplyButton:P.applyButton,agentRevertButton:P.revertButton,agentResetButton:P.resetButton,...Z===void 0?{}:{externalHandoffPanel:Z},renderStatus(a){let f=a==="inspecting";a==="idle"||f?M=!1:M=!0,U.setAttribute("aria-pressed",String(f)),U.textContent=f?r.trigger.stop:r.trigger.select,fn(a)},renderEditorStatus:gn,renderDataFlow(a){Bn=a,Ge.render(a),re()},showHighlight(a,f){te.hidden=!1,te.style.transform=`translate(${String(a.x)}px, ${String(a.y)}px)`,te.style.width=`${String(a.width)}px`,te.style.height=`${String(a.height)}px`,Ee.textContent=f,Xe.textContent=f},hideHighlight(){te.hidden=!0,Ee.textContent=""},showSelectionHighlights:Lr,hideSelectionHighlights(){$.replaceChildren()},showSelection(a,f,m){Kn(a,f,m),M=!0,fn(F==="previewing"?"previewing":"selected")},updateSelection:Kn,renderTargets:Gn,updateTargetInstruction:_r,setPreviewEnabled(a){Ne=a,Ue.disabled=!a,P.setContextReady(a),Z?.setContextReady(a)},hideSelection(){M=!1,I=!1,b=void 0,fe.replaceChildren(),at=[],qt=0,_t="",gn("idle"),nt.textContent=r.targets.count(0,0),Ce.textContent=r.targets.complete(0,0),Xt(0,0),Xe.textContent=r.context.selectedElement,Le.textContent="",me.textContent="",rt.textContent=r.diagnostics.resolving,ne.dataset.state="loading",ne.textContent=r.context.collecting,Q.disabled=!0,Ue.disabled=!0,se=!1,Ne=!1,P.setContextReady(!1),P.setSelectionVisible(!1),Z?.setContextReady(!1),Z?.setSelectionVisible(!1),P.setEditingEnabled(!0),P.resetJob(),Ge.resetView(),we()},hideSelectionTemporarily(){M=!1,I=!1,b=void 0,we()},showPreview(a){me.textContent=a,re()},readAgentSelection(){return P.readSelection()},agentConsentGranted(){return P.consentGranted()},setAgentProviderConsent(a){P.setProviderConsent(a)},setAgentEditingEnabled(a){Lt=a,Ie.disabled=!a,Ye.disabled=!a,fe.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(f=>{f.disabled=!a}),Q.disabled=!se,Ue.disabled=!a||!Ne,Z?.setContextReady(a&&Ne),P.setEditingEnabled(a),re()},renderAgentCapability(a,f,m,D){P.renderCapability(a,f,m,D),a==="error"&&(x=void 0,we());let B=a==="ready"&&m?.state==="agent-ready";Ue.classList.toggle("spotpatch-primary",!B),re()},renderAgentWorkspaceHealth(a,f,m){P.renderWorkspaceHealth(a,f,m),a==="blocked"&&(x=void 0,we()),re()},renderAgentJob(a,f,m,D){P.renderJob(a,f,m,D),x!==void 0&&a.status!=="failed"&&a.status!=="cancelled"&&un(),(a.status==="failed"||a.status==="cancelled")&&(x=void 0);let B=a.status==="awaiting-review"||a.status==="applied"||a.status==="completed"||a.status==="reverted",ae=a.status==="failed",ke=a.status==="cancelled",ue=a.status==="applied"||a.status==="completed"||a.status==="reverted",De=B?"success":ae?"failed":a.status==="queued"||a.status==="preparing"?"handoff":"running";if(!I){if(ue&&!pn(`job:${a.jobId}:${a.status}`)){b=void 0,we(),re();return}let z=a.providerLabel,X=Kt(),Ze=Object.freeze(m.map(Un)),dt=m.at(-1),lt=a.status==="queued"||a.status==="preparing"?"prepare":a.status==="validating"?"check":a.status==="applying"||a.status==="reverting"?"apply":a.status==="awaiting-review"||B?"sync":"unknown",pt=Dt(`job-phase:${a.jobId}:${a.status}:${a.updatedAt}`,lt,void 0,B?"success":ae?"failure":"active"),Rt=a.status==="running"&&dt!==void 0?Un(dt):pt;b=ke?void 0:{scene:De,tone:B?"success":ae?"danger":"running",headline:B?r.execution.completedTitle:ae?r.execution.failedTitle:De==="handoff"?r.execution.dispatchingTitle(z):a.status==="validating"?r.execution.activityAction("check",dt?.detail):a.status==="applying"||a.status==="reverting"?r.execution.activityAction(lt):r.execution.runningTitle(X.label),action:B?f===void 0||f.files.length===0?r.execution.resultReturned:r.execution.resultSummary(f.files.length):dt?.detail??X.source,expandedHeadline:B?r.execution.expandedCompletedTitle:ae?r.execution.failedTitle:De==="handoff"?r.execution.dispatchingTitle(z):r.execution.expandedRunningTitle(z),expandedAction:B?f===void 0||f.files.length===0?r.execution.resultReturned:r.execution.resultSummary(f.files.length):Pt(),meta:B?r.execution.completedStatus:ae?r.execution.failedStatus:a.status==="validating"?r.execution.checkingStatus:De==="handoff"?r.execution.dispatchingStatus:r.execution.runningStatus,activity:Rt,recentActivities:Ze.length===0?Object.freeze([pt]):Ze,startedAt:a.createdAt}}we(),re()},resetAgentJob(){P.resetJob(),h=void 0,b!==void 0&&(b=void 0,I=!1,we()),re()},focusTargetInstruction(a){Wn(a)?.focus({preventScroll:!0})},focusPrompt(){me.focus({preventScroll:!0})},announce:Xn,locale:A.locale,messages:A.messages,agentWorkspaceConsentGranted:P.workspaceConsentGranted,subscribeLocale:A.subscribe,dispose(){je.removeEventListener("toggle",re),Re.removeEventListener("click",A.toggle),Y.removeEventListener("click",Yn),P.runButton.removeEventListener("click",Zn),Z?.sendButton.removeEventListener("click",Qn),L.removeEventListener("click",eo),L.removeEventListener("keydown",to),Pr(),Ge.dispose(),Z?.dispose(),P.dispose(),W?.dispose(),v.dispose(),Jt(!0),N.dispose(),R.remove()}})}function Ji(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,d=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${d===void 0?"":`:${String(d)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,d):o.unavailable}function yr(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${Ji(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(`
859
- `)}function br(e,t){return`${e}:${t}`}var Xi=Object.freeze({list_files:"discover",search_text:"search",read_file:"read",replace_text:"patch",apply_patch:"patch",run_check:"check"});function Yi(e){return Xi[e]??"unknown"}function Zi(e){if(e.type==="tool"){let t=e.data.relativePath??e.data.checkLabel;return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,kind:Yi(e.data.toolName),...t===void 0?{}:{detail:t},label:`${e.data.toolName}${t===void 0?"":` · ${t}`} · ${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)}`,kind:"check",detail:e.data.result.label,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 Sr(e){let t=h=>Eo(h)??p.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,s=new Set,d=new Map,i=0,l,A,w=!1,T=!1,N=()=>e.view.readAgentSelection(),r=h=>`${h.providerProfileId}:${h.applyMode}`,F=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let R=await e.api.agentWorkspaceHealth();return h!==i||e.view.renderAgentWorkspaceHealth(R.state,R,R.errorCode),R}catch(R){throw h===i&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(R)),R}},M=h=>{l!==void 0&&e.view.renderAgentJob(l,A,Object.freeze([...d.values()]),h??l.errorCode)},I=()=>{let h=N();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(r(h)));let R=n.get(br(h.providerProfileId,h.modelProfileId));R===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,R)},b=async h=>{let R=N();if(R===void 0)throw new Error("Agent provider selection is unavailable.");let O=br(R.providerProfileId,R.modelProfileId),_=n.get(O);if(_!==void 0)return _;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let U=await e.api.agentCapability(R);if(h!==i)return U;if(U.state!=="agent-ready")throw new q(U.errorCode??p.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(O,U),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,U),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),U},x=async(h,R)=>{try{let O=await e.api.agentResult(h);if(R!==i||O.snapshot.jobId!==h)return;l=O.snapshot,A=O.result,M()}catch(O){R===i&&M(t(O))}},K=async(h,R)=>{try{await e.api.agentEvents(h,O=>{if(R!==i||O.jobId!==h)return;O.type==="snapshot"&&(l=O.data.snapshot,l.status==="applied"&&!w&&(w=!0,e.onApplied()));let _=Zi(O);_!==void 0&&d.set(_.key,_),M()}),R===i&&await x(h,R)}catch(O){R===i&&!(O instanceof DOMException&&O.name==="AbortError")&&M(t(O))}},J=async h=>{let R=l;if(R===void 0||T)return;T=!0;let O=i;l=Object.freeze({...R,status:h==="apply"?"applying":h==="cancel"?"cancelling":"reverting",phaseMessage:h==="apply"?e.view.messages().agent.applying:h==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),M();try{let _=h==="apply"?await e.api.applyAgentJob(R.jobId):h==="cancel"?await e.api.cancelAgentJob(R.jobId):await e.api.revertAgentJob(R.jobId);if(O!==i)return;l=_,_.status==="applied"&&!w&&(w=!0,e.onApplied()),await x(_.jobId,O)}catch(_){if(O!==i)return;l=R,await x(R.jobId,O),M(t(_)),e.view.announce(o(_))}finally{O===i&&(T=!1)}},G=()=>{i+=1,l=void 0,A=void 0,d.clear(),w=!1,T=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),I()};return Object.freeze({apply(){l?.canApply===!0&&J("apply")},beginSelection(){G();let h=i;e.ai.enabled&&F(h).catch(()=>{})},cancel(){l?.canCancel===!0&&J("cancel")},consentChanged(){let h=N();h!==void 0&&(e.view.agentConsentGranted()?s.add(r(h)):s.delete(r(h)))},disposeSelection(){let h=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;i+=1,l=void 0,A=void 0,d.clear(),w=!1,T=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){i+=1,I(),F(i).catch(()=>{})},reset(){let h=w;G(),h?e.onReselectRequired():e.ai.enabled&&F(i).catch(()=>{})},revert(){l?.canRevert===!0&&J("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let h=N(),R=e.getAnnotation();if(h===void 0||R===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(r(h));let O=++i;e.view.setAgentEditingEnabled(!1),F(O).then(async _=>{if(O!==i)return;if(_.state==="blocked")throw new q(_.errorCode??p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(_.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new q(p.WORKTREE_DIRTY);let U=await e.api.createAgentJob({annotation:R,applyMode:h.applyMode,providerProfileId:h.providerProfileId,modelProfileId:h.modelProfileId,providerDataConsent:!0,...h.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:_.state==="consent-required"?"include-local-changes":"require-clean"});O===i&&(l=U,A=void 0,d.clear(),M(),K(U.jobId,O))}).catch(_=>{O===i&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(_),void 0,t(_)),e.view.announce(o(_)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let h=++i;Promise.all([b(h),F(h)]).catch(R=>{h===i&&(e.view.renderAgentCapability("error",o(R),void 0,t(R)),e.view.announce(o(R)))})}})}function Er(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 Fn(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 Ar(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var es=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Mn(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 ts(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 ns(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function os(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 xr(e,t={}){let o=os(t),n=t.view??hr(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId),s=t.api??Ao({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),d=t.promptComposer??Uo({maxCharacters:e.budget.totalCharacters}),i=t.clipboard??Ar(o.window.navigator),l=t.createId??(()=>Er(o.window)),A=t.now??(()=>new Date().toISOString()),w=t.selectionSession??qo(o.window,e.sessionId,e.maxTargets),T=w.load(),N=Yo({adapter:t.reactAdapter??Qi({...e.dataFlow.enabled?{getComponentRegistration:c=>Wt()?.getComponentRegistration(c)}:{},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.")}}),r=_n,F=!1,M,I,b=T?.targets.map(c=>{let u=Pn(c.source);return{id:c.id,resolution:Object.freeze({source:c.source,react:c.react}),apiStatus:u===void 0?"not-required":c.code===void 0?"failed":"connected",code:c.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:c.element,instruction:c.instruction,marker:u,page:c.page,styles:c.styles}})??[],x=T?.activeTargetId,K=T?.sequence??0,J=T?.open??!1,G=!1,h=0,R=0,O=0,_,U="idle",S=!1,C="",v,L,te,Ee,$=new Map;function k(c){r=Vo(r,c),n.renderStatus(r.status)}function He(){return b.find(c=>c.id===x)??b.at(-1)}function de(c){let u=c.resolution.react;if(u.componentSourceId!==void 0&&u.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:u.componentSourceId,sourceVersion:u.sourceVersion});let E=c.marker;return E===void 0?void 0:Object.freeze({schemaVersion:1,fileId:E.fileId,line:E.line,column:E.column})}function $e(){let c=Wt(),u=c?.observations(o.window.location.pathname)??[],E=He();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?E?.dataFlowStatus??"idle":"disabled",...E?.dataFlowReport===void 0?{}:{report:c?.mergeComponentReport(E.dataFlowReport,u)??E.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?U:"disabled",..._===void 0?{}:{report:c?.mergePageReport(_,u)??_}}),observationCount:u.length})}async function Ae(){if(!e.dataFlow.enabled){$e();return}let c=He(),u=c===void 0?void 0:de(c),E=b.flatMap(W=>{let pe=de(W);return pe===void 0?[]:[pe]}),H=++O,V=h;c!==void 0&&(c.dataFlowStatus="loading"),U=E.length===0?"idle":"loading",$e();let[ie,y]=await Promise.allSettled([u===void 0?Promise.resolve(void 0):s.componentDataFlowReport(u),E.length===0?Promise.resolve(void 0):s.pageDataFlowReport({schemaVersion:1,targets:E})]);!F||H!==O||V!==h||(c!==void 0&&b.includes(c)&&(ie.status==="fulfilled"?(c.dataFlowReport=ie.value,c.dataFlowStatus=ie.value===void 0?"idle":"ready"):(c.dataFlowReport=void 0,c.dataFlowStatus="error")),y.status==="fulfilled"?(_=y.value,U=y.value===void 0?"idle":"ready"):(_=void 0,U="error"),$e())}function ht(c){if(!(c.elementContext===void 0||c.styles===void 0))return{id:c.id,instruction:c.instruction,page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code}}}function le(){let c=b.flatMap(E=>{let H=ht(E);return H===void 0?[]:[H]});if(c.length===0){w.clear();return}let u=new Set(c.map(({id:E})=>E));w.save({...x!==void 0&&u.has(x)?{activeTargetId:x}:{},open:J,sequence:K,targets:c})}function We(c,u){return F&&u===h&&r.status!=="idle"&&b.includes(c)}function xe(){let c=b.reduce((u,E)=>u+E.instruction.trim().length,0);return b.length>0&&c<=4e3&&b.every(u=>u.instruction.trim().length>0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function be(){let c=n.messages().summary;return b.map((u,E)=>{let H=yr({resolution:u.resolution,...u.code===void 0?{}:{code:u.code},...u.styles===void 0?{}:{styles:u.styles},apiStatus:u.apiStatus,collectionStatus:u.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},c);return`${c.target(E+1,u.id===x)}
860
- ${H}`}).join(`
856
+ ${rr}
857
+ `,t}function Qi(e,t){return e.split(`
858
+ `).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function es(e){let t=e.target;return t instanceof Element&&t.closest("a, button, input, select, textarea, summary, [contenteditable='true']")!==null}function ts(e){let t=ie(e,"","spotpatch-execution-island");t.hidden=!0,t.setAttribute("aria-hidden","true");let o=$n(e,void 0,"spotpatch-fallback-execution-island");o.classList.add("spotpatch-execution-logo");let n=g(e,"span");return t.append(o,n),Object.freeze({canExpand:()=>!1,isExpanded:()=>!1,root:t,setExpanded:()=>{},render(s){let l=[s.headline,s.action,s.meta].filter(a=>a.length>0).join(" · ");n.textContent=l,t.setAttribute("aria-label",l)},dispose(){}})}function ns(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:ie(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function xr(e,t,o=Object.freeze({enabled:!1}),n="auto",s=!1,l=!1,a="vite",d="",C=!1){let x=ur(e,n),w=e.defaultView;if(w===null)throw new Error("SpotPatch requires a document with an associated window.");let V=w,b=Ar(V,mr(V,d),_t),i=x.messages(),W="idle",H="change",A="",v="",q=!1,B=!1,I,y,R,L,M,K,E=e.createElement("spotpatch-root");E.setAttribute(Nt,"");let T=E.attachShadow({mode:"open"}),O=g(e,"div");O.className="spotpatch-floating-surface",O.dataset.scene="pill",O.dataset.tone="neutral";let _=ie(e,i.trigger.select,"spotpatch-trigger");_.title=i.trigger.title(t),_.setAttribute("aria-pressed","false");let pe=sr(),ve=pe?.createExecutionIsland(e),D=ve??ts(e),N=D.root,le=g(e,"div");le.className="spotpatch-highlight",le.hidden=!0;let ye=g(e,"span");ye.className="spotpatch-highlight-label",le.append(ye);let be=g(e,"div");be.className="spotpatch-selection-highlights",be.setAttribute("aria-hidden","true");let te=g(e,"section");te.className="spotpatch-dialog",te.hidden=!0,te.tabIndex=-1,te.setAttribute("role","dialog"),te.setAttribute("aria-labelledby","spotpatch-selection-title");let st=g(e,"div");st.className="spotpatch-shell";let se=g(e,"header");se.className="spotpatch-header",se.setAttribute("data-spotpatch-drag-handle","");let Ue=g(e,"div");Ue.className="spotpatch-brand-row";let xe=g(e,"div");xe.className="spotpatch-brand";let tt=g(e,"span");tt.className="spotpatch-brand-copy";let qe=g(e,"span");qe.className="spotpatch-brand-name";let Ge=g(e,"span");Ge.className="spotpatch-brand-context",tt.append(qe,Ge),xe.append($n(e),tt);let ee=g(e,"span");ee.className="spotpatch-header-controls";let de=g(e,"a");de.className="spotpatch-repository",de.href=Pn,de.target="_blank",de.rel="noopener noreferrer";let Ne=ie(e,"","spotpatch-locale"),nt=ie(e,"⌖","spotpatch-reset-position"),Ke=ie(e,"×","spotpatch-close");ee.append(de,Ne,nt,Ke),Ue.append(xe,ee);let ct=g(e,"h2");ct.id="spotpatch-selection-title",ct.className="spotpatch-title";let ot=g(e,"p");ot.className="spotpatch-subtitle";let lt=g(e,"div");lt.className="spotpatch-target-row";let De=g(e,"span");De.className="spotpatch-target-label";let ne=g(e,"span");ne.className="spotpatch-context-state",ne.dataset.state="loading",ne.textContent=i.context.collecting,lt.append(De,ne),se.append(Ue,ct,ot,lt);let Re=g(e,"div");Re.className="spotpatch-body";let Je=g(e,"div");Je.className="spotpatch-selection-panel";let U=g(e,"section");U.className="spotpatch-targets";let je=g(e,"div");je.className="spotpatch-targets-heading";let Ce=g(e,"span"),St=g(e,"span");St.className="spotpatch-targets-meta";let Xe=g(e,"span");Xe.className="spotpatch-target-complete";let fe=g(e,"span");fe.className="spotpatch-target-budget",fe.setAttribute("aria-live","polite");let Ye=g(e,"span");Ye.className="spotpatch-target-count",St.append(Xe,fe),lt.append(Ye),je.append(Ce,St);let Ze=g(e,"div");Ze.className="spotpatch-target-progress",Ze.setAttribute("aria-hidden","true");let Se=g(e,"div");Se.className="spotpatch-target-progress-fill",Ze.append(Se);let we=g(e,"div");we.className="spotpatch-target-list",U.append(je,Ze,we);let ze=g(e,"details");ze.className="spotpatch-diagnostics";let Rt=g(e,"summary"),Ve=g(e,"span"),We=g(e,"span");We.className="spotpatch-source-peek",We.textContent=i.diagnostics.resolving,Rt.append(Ve,We);let dt=g(e,"pre");dt.className="spotpatch-summary",ze.append(Rt,dt);let P=ar(e,o,x),rt=g(e,"div");function Z(){q&&b.requestReconcile()}let Y=l?gn()?.createPanel(e,a,x.locale,d,x.subscribe,Z,kr,Pr):void 0;rt.append(U,P.root,...Y===void 0?[]:[Y.root]);let Me=qt()?.createPanel(e,s,x.locale,rt,ze,Z)??ns(e,rt,ze);Je.append(Me.root);let pt=g(e,"div");pt.className="spotpatch-preview-panel",pt.hidden=!0;let Fe=g(e,"pre");Fe.className="spotpatch-prompt",Fe.tabIndex=0,Fe.setAttribute("aria-label",i.diagnostics.promptAriaLabel),pt.append(Fe),Re.append(Je,pt);let re=g(e,"footer");re.className="spotpatch-actions";let Oe=g(e,"div");Oe.className="spotpatch-context-state spotpatch-editor-feedback",Oe.dataset.state="idle",Oe.setAttribute("role","status"),Oe.setAttribute("aria-live","polite"),Oe.hidden=!0;let He=ie(e,i.actions.addElement),at=ie(e,i.actions.reselect),c=ie(e,i.actions.openEditor),u=ie(e,i.actions.preview,"spotpatch-primary"),S=ie(e,i.actions.copy,"spotpatch-primary"),$=ie(e,i.actions.back),m=g(e,"div");m.className="spotpatch-secondary-actions";let F=g(e,"div");F.className="spotpatch-primary-actions",He.classList.add("spotpatch-icon-action"),He.dataset.compactIcon="+",P.testButton.classList.add("spotpatch-icon-action"),P.testButton.dataset.compactIcon="✓",c.classList.add("spotpatch-secondary-action"),at.classList.add("spotpatch-secondary-action"),m.append(c,at),F.append(P.testButton,He,P.runButton,...Y===void 0?[]:[Y.sendButton],u,P.cancelButton,P.applyButton,P.revertButton,P.resetButton,S,$),re.append(Oe,m,F);let G=C?fn()?.createPanel({document:e,locale:x.locale,subscribeLocale:x.subscribe,changeRoot:Me.root,changeActions:re,announce:An,onModeChange(r,f,h){H=r,A=f,v=h,E.isConnected&&en(W)},onExecutionChange(r){I=r,B=!1,Ee()},onViewChange:Z}):void 0;G!==void 0&&Je.prepend(G.root),st.append(se,Re,re),te.append(st);let Q=g(e,"div");Q.className="spotpatch-live",Q.setAttribute("aria-live","polite"),Q.setAttribute("aria-atomic","true");let _e=[Zi(e),...pe===void 0?[]:[pe.createStyles(e)],Me.styles,...G===void 0?[]:[G.styles],...Y===void 0?[]:[Y.styles]],Ft=Yi(e);if(Ft!==void 0)for(let r of _e)r.nonce=Ft;T.append(..._e,be,le,O,Q),O.append(_,te,N),e.documentElement.append(E),b.registerSurface(O);let Qe=pe===void 0||ve===void 0?void 0:pe.createController(e,Object.freeze({execution:ve.elements,pill:_,planner:te,surface:O}),b.reconcile),hn=()=>{Qe?.cancel()};b.attachDraggable(_,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.attachDraggable(se,O,{canStartDrag:r=>!b.isCompact()&&!es(r),onDragStart:hn}),b.attachDraggable(N,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.reconcile();let yn=!1,Ht=!1,Kt="",Jt=!0,$e=[],Xt=0,qn="idle",Gn=Object.freeze({component:Object.freeze({status:s?"idle":"disabled"}),page:Object.freeze({status:s?"idle":"disabled"}),observationCount:0});function Yt(){let r=$e.find(f=>f.active);return Object.freeze(r===void 0?{label:i.context.selectedElement,source:""}:{label:r.label,source:r.source})}function Lt(){let r=Yt();return r.source.length===0?r.label:`${r.label} · ${r.source}`}function Kn(){return K=new Date().toISOString(),K}function Jn(){return K??Kn()}function Zt(r){M!==void 0&&(V.clearTimeout(M),M=void 0),r&&(R=void 0,L=void 0)}function bn(r){return L===r?!1:(R===r||(Zt(!1),R=r,M=V.setTimeout(()=>{M=void 0,E.isConnected&&(L=r,I=void 0,K=void 0,B=!1,q=!1,Ee())},Xi)),!0)}function Lr(r){return r.startsWith("claude")?i.execution.claude:r.startsWith("codex")?i.execution.codex:r}function Xn(r){return Object.freeze({...r.detail===void 0?{}:{detail:r.detail},key:r.key,kind:r.kind,label:i.execution.activityLane(r.kind,r.detail),state:r.state})}function Dt(r,f,h,k="active"){return Object.freeze({...h===void 0?{}:{detail:h},key:r,kind:f,label:i.execution.activityLane(f,h),state:k})}function Ee(){let r=W==="inspecting",f=!q||r,h=f?{scene:r?"capturing":"pill",tone:r?"capturing":"neutral",headline:_.textContent,action:"",meta:"",recentActivities:Object.freeze([])}:!B&&I!==void 0?I:{scene:"planner",tone:"ready",headline:i.dialog.editTitle,action:i.dialog.editSubtitle,meta:i.context.ready,recentActivities:Object.freeze([])};if(Qe!==void 0){Qe.render(h,()=>{D.render(h)});return}D.render(h),O.dataset.scene=h.scene,O.dataset.tone=h.tone;let k=h.scene==="planner";_.hidden=!f,_.inert=!f,te.hidden=!k,te.inert=!k,te.setAttribute("aria-hidden",String(!k)),N.hidden=f||k,N.inert=f||k,N.setAttribute("aria-hidden",String(f||k)),b.reconcile()}function kr(r){if(r===null?(y=void 0,K=void 0):y!==void 0&&r.phase!=="failed"&&r.phase!=="delivery-unknown"?Sn():(r.phase==="failed"||r.phase==="delivery-unknown")&&(y=void 0),r!==null&&!B){let f=r.phase==="failed"||r.phase==="delivery-unknown",h=r.phase==="completed",k=f||h?void 0:Jn();(f||h)&&(K=void 0);let j=`dispatch:${String(r.revision)}`;if(h&&!bn(j)){I=void 0,Ee();return}let ce=Lr(r.adapterKind),Le=Yt(),ue=r.phase==="queued"||r.phase==="dispatching"||r.phase==="dispatched"?"dispatch":h?"sync":"unknown",ke=Dt(`dispatch:${String(r.revision)}:${r.phase}`,ue,r.phase,f?"failure":h?"success":"active"),z=f?"failed":h?"success":r.phase==="working"?"running":"handoff";I={scene:z,tone:f?"danger":h?"success":"running",headline:h?i.execution.completedTitle:f?i.execution.failedTitle:z==="running"?i.execution.runningTitle(Le.label):i.execution.dispatchingTitle(ce),action:h?i.execution.resultReturned:Le.source,expandedHeadline:h?i.execution.expandedCompletedTitle:f?i.execution.failedTitle:z==="running"?i.execution.expandedRunningTitle(ce):i.execution.dispatchingTitle(ce),expandedAction:h?i.execution.resultReturned:Lt(),meta:f?i.execution.failedStatus:h?i.execution.completedStatus:z==="running"?i.execution.runningStatus:i.execution.dispatchingStatus,activity:ke,recentActivities:Object.freeze([ke]),...k===void 0?{}:{startedAt:k}}}else r===null&&(I=void 0);Ee()}function Pr(r){let f=r?.task;if(r===void 0||f===void 0||B)return;let h=f.managedPhase,k=h==="failed"||h==="cleanup-warning",j=h==="completed"||h==="review-required",ce=h==="cancelled";if(k||ce?y=void 0:y!==void 0&&Sn(),ce){I=void 0,K=void 0,Ee();return}let Le=k||j?void 0:Jn();if((k||j)&&(K=void 0),h==="completed"&&!bn(`managed:${String(f.revision)}`)){I=void 0,Ee();return}let ue=k?"failed":j?"success":h==="preparing"?"handoff":"running",ke=k?"danger":j?"success":"running",z=i.execution.codex,X=Yt(),et=h==="preparing"?"prepare":h==="auditing"?"audit":h==="validating"?"check":h==="applying"?"apply":j?"sync":"unknown",ut=f.checks.at(-1),gt=f.files.at(-1),ft=h==="validating"?ut?.id:h==="auditing"||h==="applying"?gt?.path:void 0,Ct=Dt(`managed:${String(f.revision)}:${h}:${ft??""}`,et,ft,k?"failure":j?"success":"active"),$t=Object.freeze([...f.files.slice(-2).map(mt=>Dt(`managed-file:${String(f.revision)}:${mt.path}`,"patch",mt.path,"success")),...f.checks.slice(-2).map(mt=>Dt(`managed-check:${String(f.revision)}:${mt.id}`,"check",mt.id,mt.outcome==="passed"?"success":"failure")),Ct]);I={scene:ue,tone:ke,headline:j?i.execution.completedTitle:k?i.execution.failedTitle:ue==="handoff"?i.execution.dispatchingTitle(z):h==="validating"?i.execution.activityAction("check",ft):i.execution.runningTitle(X.label),action:j?f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):X.source,expandedHeadline:j?i.execution.expandedCompletedTitle:k?i.execution.failedTitle:ue==="handoff"?i.execution.dispatchingTitle(z):i.execution.expandedRunningTitle(z),expandedAction:j?i.execution.resultReturned:Lt(),meta:k?i.execution.failedStatus:j?i.execution.completedStatus:h==="validating"?i.execution.checkingStatus:ue==="handoff"?i.execution.dispatchingStatus:i.execution.runningStatus,activity:Ct,recentActivities:$t,...Le===void 0?{}:{startedAt:Le}},Ee()}function Ir(r,f){if(!q)return;Zt(!0);let h=Kn();B=!1;let k=Dt(`dispatch-start:${Lt()}`,"dispatch",Lt());I={scene:"agent-charging",tone:"running",headline:i.execution.receivingTitle,action:Lt(),expandedHeadline:i.execution.receivingTitle,expandedAction:Lt(),meta:i.execution.receivingStatus,activity:k,recentActivities:Object.freeze([k]),startedAt:h},Ee(),Qe?.dispatch(r,f)}function Yn(r,f){!q||r.disabled||(y=Object.freeze({source:r,target:f}))}function Sn(){let r=y;y=void 0,!(r===void 0||!r.source.isConnected||!r.target.isConnected)&&Ir(r.source,r.target)}function En(r){qn=r,Oe.dataset.state=r,Oe.hidden=r==="idle",Oe.textContent=r==="opening"?i.announcements.editorOpening:r==="success"?i.announcements.editorOpened:r==="error"?i.announcements.editorFailed:"",Z()}function Nr(r){return r.status==="ready"?i.targets.statusReady:r.status==="warning"?i.targets.statusPartial:i.targets.statusCollecting}function Qt(r,f){let h=f===0?0:r/f;Se.style.width=`${String(h*100)}%`}function Zn(r){let f=we.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(f).find(h=>r===void 0||h.dataset.targetInstructionId===r)}function Qn(r,f){let h=T.activeElement?.closest("textarea[data-target-instruction-id]"),k=h?.dataset.targetInstructionId,j=h?.selectionStart,ce=h?.selectionEnd;$e=r.map(z=>Object.freeze({...z})),Xt=f,we.replaceChildren();let Le=r.filter(z=>z.instruction.trim().length>0).length,ue=r.reduce((z,X)=>z+X.instruction.trim().length,0);Qt(Le,r.length),Ye.textContent=i.targets.count(r.length,f),Xe.textContent=i.targets.complete(Le,r.length);let ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?i.targets.instructionBudgetExceeded(ue,4e3):i.targets.instructionBudget(ue,4e3),He.disabled=!Jt||r.length>=f,He.title=r.length>=f?i.targets.limitTitle(f):i.targets.addTitle,De.textContent=r.length===1?r[0]?.label??i.context.selectedElement:i.context.selectedCount(r.length);for(let[z,X]of r.entries()){let et=g(e,"div");et.className="spotpatch-target-item",et.dataset.active=String(X.active),et.dataset.status=X.status,et.dataset.targetId=X.id;let ut=g(e,"div");ut.className="spotpatch-target-summary";let gt=ie(e,"","spotpatch-target-select");gt.dataset.activateTargetId=X.id,gt.setAttribute("aria-label",i.targets.activate(z+1)),gt.setAttribute("aria-expanded",String(X.active));let ft=g(e,"span");ft.className="spotpatch-target-index",ft.textContent=String(z+1);let Ct=g(e,"span");Ct.className="spotpatch-target-copy";let $t=g(e,"span");$t.className="spotpatch-target-name",$t.textContent=X.label;let mt=g(e,"span");mt.className="spotpatch-target-source",mt.textContent=`${Nr(X)} · ${X.source}`,Ct.append($t,mt);let co=X.instruction.trim().length>0,tn=g(e,"span");tn.className="spotpatch-target-state",tn.dataset.complete=String(co),tn.textContent=co?i.targets.instructionReady:i.targets.instructionMissing,gt.append(ft,Ct,tn);let Bt=ie(e,"↗","spotpatch-target-open");Bt.dataset.openTargetId=X.id,Bt.disabled=!X.canOpenEditor,Bt.setAttribute("aria-label",i.actions.openTarget(z+1)),Bt.title=i.actions.openTarget(z+1);let Ut=ie(e,"×","spotpatch-target-remove");if(Ut.dataset.removeTargetId=X.id,Ut.disabled=!Jt,Ut.setAttribute("aria-label",i.targets.remove(z+1)),Ut.title=i.targets.removeTitle,ut.append(gt,Bt,Ut),et.append(ut),X.active){let xn=g(e,"label");xn.className="spotpatch-target-editor";let Rn=g(e,"span");Rn.className="spotpatch-target-editor-head";let Cn=g(e,"span");Cn.className="spotpatch-target-editor-label",Cn.textContent=i.targets.instructionLabel(X.label);let Tn=g(e,"span");Tn.className="spotpatch-target-editor-count",Tn.textContent=i.targets.instructionCount(X.instruction.length,2e3),Rn.append(Cn,Tn);let Tt=g(e,"textarea");Tt.rows=4,Tt.maxLength=2e3,Tt.value=X.instruction,Tt.placeholder=i.targets.instructionPlaceholder,Tt.disabled=!Jt,Tt.dataset.targetInstructionId=X.id,Tt.setAttribute("aria-label",i.targets.instructionLabel(X.label)),xn.append(Rn,Tt),et.append(xn)}we.append(et)}if(k!==void 0){let z=Zn(k);z?.focus({preventScroll:!0}),j!==void 0&&ce!==void 0&&z?.setSelectionRange(j,ce)}Z()}function Dr(r,f){$e=$e.map(z=>z.id===r?Object.freeze({...z,instruction:f}):z);let h=Array.from(we.querySelectorAll(".spotpatch-target-item")).find(z=>z.dataset.targetId===r);if(h===void 0)return;let k=f.trim().length>0,j=h.querySelector(".spotpatch-target-state"),ce=h.querySelector(".spotpatch-target-editor-count");j!==null&&(j.dataset.complete=String(k),j.textContent=k?i.targets.instructionReady:i.targets.instructionMissing),ce!==null&&(ce.textContent=i.targets.instructionCount(f.length,2e3));let Le=$e.filter(z=>z.instruction.trim().length>0).length;Xe.textContent=i.targets.complete(Le,$e.length),Qt(Le,$e.length);let ue=$e.reduce((z,X)=>z+X.instruction.trim().length,0),ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?i.targets.instructionBudgetExceeded(ue,4e3):i.targets.instructionBudget(ue,4e3)}function Mr(r){be.replaceChildren();for(let[f,h]of r.entries()){let k=g(e,"div");k.className="spotpatch-selection-highlight",k.dataset.targetId=h.id,k.dataset.active=String(h.active),k.style.transform=`translate(${String(h.rect.x)}px, ${String(h.rect.y)}px)`,k.style.width=`${String(h.rect.width)}px`,k.style.height=`${String(h.rect.height)}px`;let j=g(e,"span");j.textContent=`${String(f+1)} · ${h.label}`,k.append(j),be.append(k)}}function eo(r){let f=i.summary,h=Qi(r,f.source);We.textContent=h??i.diagnostics.noExactSource;let k=`${f.browserContext}: ${f.collectionStatuses.ready}`,j=`${f.browserContext}: ${f.collectionStatuses.loading}`,ce=`${f.browserContext}: ${f.collectionStatuses.failed}`,Le=`${f.api}: ${f.apiStatuses.loading}`,ue=`${f.api}: ${f.apiStatuses.failed}`;r.includes(k)&&!r.includes(j)&&!r.includes(Le)&&!r.includes(ce)&&!r.includes(ue)?(ne.dataset.state="ready",ne.textContent=i.context.ready):r.includes(ce)||r.includes(ue)?(ne.dataset.state="warning",ne.textContent=i.context.partial):(ne.dataset.state="loading",ne.textContent=i.context.collecting)}function to(r,f,h){yn=f,Ht=h,Kt=r,dt.textContent=r,c.disabled=!f,u.disabled=!h,P.setContextReady(h),Y?.setContextReady(h),G?.setSelectionPreview({contextReady:$e.every(k=>k.status!=="loading"),targetCount:$e.length,sourceCount:$e.filter(k=>k.canOpenEditor).length}),eo(r),Z()}function en(r){W=r;let f=r==="selected",h=r==="previewing";Je.hidden=!f,pt.hidden=!h,at.hidden=!f,He.hidden=!f,c.hidden=!f,u.hidden=!f,m.hidden=!f,P.setSelectionVisible(f),Y?.setSelectionVisible(f),G?.setSelectionVisible(f),S.hidden=!h,$.hidden=!h,ct.textContent=h?i.dialog.previewTitle:H==="ask"&&A.length>0?A:i.dialog.editTitle,ot.textContent=h?i.dialog.previewSubtitle:H==="ask"&&v.length>0?v:i.dialog.editSubtitle,Ee()}function no(){i=x.messages(),qe.textContent=i.brand.name,Ge.textContent=i.brand.context,de.textContent=i.brand.repository,de.title=i.brand.repositoryTitle,de.setAttribute("aria-label",i.brand.repositoryTitle),Ne.textContent=i.alternateLocaleName,Ne.title=i.switchLocale,Ne.setAttribute("aria-label",i.switchLocale),nt.title=i.floatingSurface.resetPosition,nt.setAttribute("aria-label",i.floatingSurface.resetPosition),Ke.setAttribute("aria-label",i.dialog.close),Ke.title=i.dialog.close,se.title=i.floatingSurface.dragHandle,U.setAttribute("aria-label",i.targets.ariaLabel),Ce.textContent=i.targets.title,Ve.textContent=i.diagnostics.title,Fe.setAttribute("aria-label",i.diagnostics.promptAriaLabel),He.textContent=i.actions.addElement,at.textContent=i.actions.reselect,c.textContent=i.actions.openEditor,u.textContent=i.actions.preview,S.textContent=i.actions.copy,$.textContent=i.actions.back,Me.render(Gn),_.title=i.trigger.title(t),_.textContent=W==="inspecting"?i.trigger.stop:i.trigger.select,en(W),En(qn),$e.length>0?Qn($e,Xt):(Ye.textContent=i.targets.count(0,Xt),Xe.textContent=i.targets.complete(0,0),Qt(0,0),fe.dataset.state="ready",fe.textContent=i.targets.instructionBudget(0,4e3),De.textContent=i.context.selectedElement),Kt.length>0?eo(Kt):(We.textContent=i.diagnostics.resolving,ne.textContent=i.context.collecting)}function An(r){Q.textContent="",Q.textContent=r}function oo(){b.reset(),An(i.floatingSurface.positionReset)}ze.addEventListener("toggle",Z),Ne.addEventListener("click",x.toggle),nt.addEventListener("click",oo);let ro=()=>{Yn(P.runButton,P.root)},ao=()=>{Y!==void 0&&Yn(Y.sendButton,Y.root)},io=()=>{if(D.canExpand()&&!D.isExpanded()){Qe===void 0?(D.setExpanded(!0),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!0)});return}Zt(!1),B=!0,Ee()},so=r=>{r.key!=="Escape"||!D.isExpanded()||(r.preventDefault(),r.stopPropagation(),Qe===void 0?(D.setExpanded(!1),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!1)}))};P.runButton.addEventListener("click",ro),Y?.sendButton.addEventListener("click",ao),N.addEventListener("click",io),N.addEventListener("keydown",so);let Fr=x.subscribe(no);return no(),Object.freeze({host:E,triggerButton:_,addTargetButton:He,targetList:we,reselectButton:at,openEditorButton:c,repositoryLink:de,previewButton:u,copyButton:S,dataFlowRefreshButton:Me.refreshButton,backButton:$,closeButton:Ke,agentProviderSelect:P.providerSelect,agentModelSelect:P.modelSelect,agentModeSelect:P.modeSelect,agentConsentCheckbox:P.consentCheckbox,agentWorkspaceConsentCheckbox:P.workspaceConsentCheckbox,agentTestButton:P.testButton,agentRunButton:P.runButton,agentCancelButton:P.cancelButton,agentApplyButton:P.applyButton,agentRevertButton:P.revertButton,agentResetButton:P.resetButton,...Y===void 0?{}:{externalHandoffPanel:Y},...G===void 0?{}:{contextualAskPanel:G},renderStatus(r){let f=r==="inspecting";r==="idle"||f?q=!1:q=!0,_.setAttribute("aria-pressed",String(f)),_.textContent=f?i.trigger.stop:i.trigger.select,en(r)},renderEditorStatus:En,renderDataFlow(r){Gn=r,Me.render(r),Z()},showHighlight(r,f){le.hidden=!1,le.style.transform=`translate(${String(r.x)}px, ${String(r.y)}px)`,le.style.width=`${String(r.width)}px`,le.style.height=`${String(r.height)}px`,ye.textContent=f,De.textContent=f},hideHighlight(){le.hidden=!0,ye.textContent=""},showSelectionHighlights:Mr,hideSelectionHighlights(){be.replaceChildren()},showSelection(r,f,h){to(r,f,h),q=!0,en(W==="previewing"?"previewing":"selected")},updateSelection:to,renderTargets:Qn,updateTargetInstruction:Dr,setPreviewEnabled(r){Ht=r,u.disabled=!r,P.setContextReady(r),Y?.setContextReady(r)},hideSelection(){q=!1,B=!1,I=void 0,we.replaceChildren(),$e=[],Xt=0,Kt="",En("idle"),Ye.textContent=i.targets.count(0,0),Xe.textContent=i.targets.complete(0,0),Qt(0,0),De.textContent=i.context.selectedElement,dt.textContent="",Fe.textContent="",We.textContent=i.diagnostics.resolving,ne.dataset.state="loading",ne.textContent=i.context.collecting,c.disabled=!0,u.disabled=!0,yn=!1,Ht=!1,P.setContextReady(!1),P.setSelectionVisible(!1),Y?.setContextReady(!1),Y?.setSelectionVisible(!1),G?.setSelectionVisible(!1),P.setEditingEnabled(!0),P.resetJob(),Me.resetView(),Ee()},hideSelectionTemporarily(){q=!1,B=!1,I=void 0,Ee()},showPreview(r){Fe.textContent=r,Z()},readAgentSelection(){return P.readSelection()},agentConsentGranted(){return P.consentGranted()},setAgentProviderConsent(r){P.setProviderConsent(r)},setAgentEditingEnabled(r){Jt=r,He.disabled=!r,at.disabled=!r,we.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(f=>{f.disabled=!r}),c.disabled=!yn,u.disabled=!r||!Ht,Y?.setContextReady(r&&Ht),P.setEditingEnabled(r),Z()},renderAgentCapability(r,f,h,k){P.renderCapability(r,f,h,k),r==="error"&&(y=void 0,Ee());let j=r==="ready"&&h?.state==="agent-ready";u.classList.toggle("spotpatch-primary",!j),Z()},renderAgentWorkspaceHealth(r,f,h){P.renderWorkspaceHealth(r,f,h),r==="blocked"&&(y=void 0,Ee()),Z()},renderAgentJob(r,f,h,k){P.renderJob(r,f,h,k),y!==void 0&&r.status!=="failed"&&r.status!=="cancelled"&&Sn(),(r.status==="failed"||r.status==="cancelled")&&(y=void 0);let j=r.status==="awaiting-review"||r.status==="applied"||r.status==="completed"||r.status==="reverted",ce=r.status==="failed",Le=r.status==="cancelled",ue=r.status==="applied"||r.status==="completed"||r.status==="reverted",ke=j?"success":ce?"failed":r.status==="queued"||r.status==="preparing"?"handoff":"running";if(!B){if(ue&&!bn(`job:${r.jobId}:${r.status}`)){I=void 0,Ee(),Z();return}let z=r.providerLabel,X=Yt(),et=Object.freeze(h.map(Xn)),ut=h.at(-1),gt=r.status==="queued"||r.status==="preparing"?"prepare":r.status==="validating"?"check":r.status==="applying"||r.status==="reverting"?"apply":r.status==="awaiting-review"||j?"sync":"unknown",ft=Dt(`job-phase:${r.jobId}:${r.status}:${r.updatedAt}`,gt,void 0,j?"success":ce?"failure":"active"),Ct=r.status==="running"&&ut!==void 0?Xn(ut):ft;I=Le?void 0:{scene:ke,tone:j?"success":ce?"danger":"running",headline:j?i.execution.completedTitle:ce?i.execution.failedTitle:ke==="handoff"?i.execution.dispatchingTitle(z):r.status==="validating"?i.execution.activityAction("check",ut?.detail):r.status==="applying"||r.status==="reverting"?i.execution.activityAction(gt):i.execution.runningTitle(X.label),action:j?f===void 0||f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):ut?.detail??X.source,expandedHeadline:j?i.execution.expandedCompletedTitle:ce?i.execution.failedTitle:ke==="handoff"?i.execution.dispatchingTitle(z):i.execution.expandedRunningTitle(z),expandedAction:j?f===void 0||f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):Lt(),meta:j?i.execution.completedStatus:ce?i.execution.failedStatus:r.status==="validating"?i.execution.checkingStatus:ke==="handoff"?i.execution.dispatchingStatus:i.execution.runningStatus,activity:Ct,recentActivities:et.length===0?Object.freeze([ft]):et,startedAt:r.createdAt}}Ee(),Z()},resetAgentJob(){P.resetJob(),K=void 0,I!==void 0&&(I=void 0,B=!1,Ee()),Z()},focusTargetInstruction(r){Zn(r)?.focus({preventScroll:!0})},focusPrompt(){Fe.focus({preventScroll:!0})},announce:An,locale:x.locale,messages:x.messages,agentWorkspaceConsentGranted:P.workspaceConsentGranted,subscribeLocale:x.subscribe,dispose(){ze.removeEventListener("toggle",Z),Ne.removeEventListener("click",x.toggle),nt.removeEventListener("click",oo),P.runButton.removeEventListener("click",ro),Y?.sendButton.removeEventListener("click",ao),N.removeEventListener("click",io),N.removeEventListener("keydown",so),Fr(),Me.dispose(),Y?.dispose(),G?.dispose(),P.dispose(),Qe?.dispose(),D.dispose(),Zt(!0),b.dispose(),E.remove()}})}function os(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,l=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${l===void 0?"":`:${String(l)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,l):o.unavailable}function Rr(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${os(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(`
859
+ `)}function Cr(e,t){return`${e}:${t}`}var rs=Object.freeze({list_files:"discover",search_text:"search",read_file:"read",replace_text:"patch",apply_patch:"patch",run_check:"check"});function as(e){return rs[e]??"unknown"}function is(e){if(e.type==="tool"){let t=e.data.relativePath??e.data.checkLabel;return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,kind:as(e.data.toolName),...t===void 0?{}:{detail:t},label:`${e.data.toolName}${t===void 0?"":` · ${t}`} · ${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)}`,kind:"check",detail:e.data.result.label,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 Tr(e){let t=y=>vo(y)??p.INTERNAL_ERROR,o=y=>e.view.messages().errors[t(y)],n=new Map,s=new Set,l=new Map,a=0,d,C,x=!1,w=!1,V=()=>e.view.readAgentSelection(),b=y=>`${y.providerProfileId}:${y.applyMode}`,i=async y=>{e.view.renderAgentWorkspaceHealth("checking");try{let R=await e.api.agentWorkspaceHealth();return y!==a||e.view.renderAgentWorkspaceHealth(R.state,R,R.errorCode),R}catch(R){throw y===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(R)),R}},W=y=>{d!==void 0&&e.view.renderAgentJob(d,C,Object.freeze([...l.values()]),y??d.errorCode)},H=()=>{let y=V();if(y===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(b(y)));let R=n.get(Cr(y.providerProfileId,y.modelProfileId));R===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,R)},A=async y=>{let R=V();if(R===void 0)throw new Error("Agent provider selection is unavailable.");let L=Cr(R.providerProfileId,R.modelProfileId),M=n.get(L);if(M!==void 0)return M;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let K=await e.api.agentCapability(R);if(y!==a)return K;if(K.state!=="agent-ready")throw new J(K.errorCode??p.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(L,K),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,K),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),K},v=async(y,R)=>{try{let L=await e.api.agentResult(y);if(R!==a||L.snapshot.jobId!==y)return;d=L.snapshot,C=L.result,W()}catch(L){R===a&&W(t(L))}},q=async(y,R)=>{try{await e.api.agentEvents(y,L=>{if(R!==a||L.jobId!==y)return;L.type==="snapshot"&&(d=L.data.snapshot,d.status==="applied"&&!x&&(x=!0,e.onApplied()));let M=is(L);M!==void 0&&l.set(M.key,M),W()}),R===a&&await v(y,R)}catch(L){R===a&&!(L instanceof DOMException&&L.name==="AbortError")&&W(t(L))}},B=async y=>{let R=d;if(R===void 0||w)return;w=!0;let L=a;d=Object.freeze({...R,status:y==="apply"?"applying":y==="cancel"?"cancelling":"reverting",phaseMessage:y==="apply"?e.view.messages().agent.applying:y==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),W();try{let M=y==="apply"?await e.api.applyAgentJob(R.jobId):y==="cancel"?await e.api.cancelAgentJob(R.jobId):await e.api.revertAgentJob(R.jobId);if(L!==a)return;d=M,M.status==="applied"&&!x&&(x=!0,e.onApplied()),await v(M.jobId,L)}catch(M){if(L!==a)return;d=R,await v(R.jobId,L),W(t(M)),e.view.announce(o(M))}finally{L===a&&(w=!1)}},I=()=>{a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),H()};return Object.freeze({apply(){d?.canApply===!0&&B("apply")},beginSelection(){I();let y=a;e.ai.enabled&&i(y).catch(()=>{})},cancel(){d?.canCancel===!0&&B("cancel")},consentChanged(){let y=V();y!==void 0&&(e.view.agentConsentGranted()?s.add(b(y)):s.delete(b(y)))},disposeSelection(){let y=d?.canCancel===!0||d?.status==="cancelling"?d.jobId:void 0;a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,y!==void 0&&e.api.cancelAgentJob(y).catch(()=>{})},providerOrModelChanged(){a+=1,H(),i(a).catch(()=>{})},reset(){let y=x;I(),y?e.onReselectRequired():e.ai.enabled&&i(a).catch(()=>{})},revert(){d?.canRevert===!0&&B("revert")},run(){if(!e.ai.enabled||d!==void 0)return;let y=V(),R=e.getAnnotation();if(y===void 0||R===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(b(y));let L=++a;e.view.setAgentEditingEnabled(!1),i(L).then(async M=>{if(L!==a)return;if(M.state==="blocked")throw new J(M.errorCode??p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(M.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new J(p.WORKTREE_DIRTY);let K=await e.api.createAgentJob({annotation:R,applyMode:y.applyMode,providerProfileId:y.providerProfileId,modelProfileId:y.modelProfileId,providerDataConsent:!0,...y.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:M.state==="consent-required"?"include-local-changes":"require-clean"});L===a&&(d=K,C=void 0,l.clear(),W(),q(K.jobId,L))}).catch(M=>{L===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(M),void 0,t(M)),e.view.announce(o(M)))})},testCapability(){if(!e.ai.enabled||d!==void 0)return;let y=++a;Promise.all([A(y),i(y)]).catch(R=>{y===a&&(e.view.renderAgentCapability("error",o(R),void 0,t(R)),e.view.announce(o(R)))})}})}function vr(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 zn(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 wr(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var cs=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Vn(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 ls(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 ds(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ps(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 Or(e,t={}){let o=ps(t),n=t.view??xr(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId,e.contextualAsk.enabled),s=t.api??wo({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),l=t.promptComposer??Jo({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??wr(o.window.navigator),d=t.createId??(()=>vr(o.window)),C=t.now??(()=>new Date().toISOString()),x=t.selectionSession??Qo(o.window,e.sessionId,e.maxTargets),w=x.load(),V=or({adapter:t.reactAdapter??ss({...e.dataFlow.enabled?{getComponentRegistration:c=>qt()?.getComponentRegistration(c)}:{},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.")}}),b=Mn,i=!1,W,H,A=w?.targets.map(c=>{let u=Hn(c.source);return{id:c.id,resolution:Object.freeze({source:c.source,react:c.react}),apiStatus:u===void 0?"not-required":c.code===void 0?"failed":"connected",code:c.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:c.element,instruction:c.instruction,marker:u,page:c.page,styles:c.styles}})??[],v=w?.activeTargetId,q=w?.sequence??0,B=w?.open??!1,I=!1,y=0,R=0,L=0,M,K="idle",E=!1,T="",O,_,pe,ve,D=new Map;function N(c){b=Xo(b,c),n.renderStatus(b.status)}function le(){return A.find(c=>c.id===v)??A.at(-1)}function ye(c){let u=c.resolution.react;if(u.componentSourceId!==void 0&&u.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:u.componentSourceId,sourceVersion:u.sourceVersion});let S=c.marker;return S===void 0?void 0:Object.freeze({schemaVersion:1,fileId:S.fileId,line:S.line,column:S.column})}function be(){let c=qt(),u=c?.observations(o.window.location.pathname)??[],S=le();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?S?.dataFlowStatus??"idle":"disabled",...S?.dataFlowReport===void 0?{}:{report:c?.mergeComponentReport(S.dataFlowReport,u)??S.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?K:"disabled",...M===void 0?{}:{report:c?.mergePageReport(M,u)??M}}),observationCount:u.length})}async function te(){if(!e.dataFlow.enabled){be();return}let c=le(),u=c===void 0?void 0:ye(c),S=A.flatMap(Q=>{let _e=ye(Q);return _e===void 0?[]:[_e]}),$=++L,m=y;c!==void 0&&(c.dataFlowStatus="loading"),K=S.length===0?"idle":"loading",be();let[F,G]=await Promise.allSettled([u===void 0?Promise.resolve(void 0):s.componentDataFlowReport(u),S.length===0?Promise.resolve(void 0):s.pageDataFlowReport({schemaVersion:1,targets:S})]);!i||$!==L||m!==y||(c!==void 0&&A.includes(c)&&(F.status==="fulfilled"?(c.dataFlowReport=F.value,c.dataFlowStatus=F.value===void 0?"idle":"ready"):(c.dataFlowReport=void 0,c.dataFlowStatus="error")),G.status==="fulfilled"?(M=G.value,K=G.value===void 0?"idle":"ready"):(M=void 0,K="error"),be())}function st(c){if(!(c.elementContext===void 0||c.styles===void 0))return{id:c.id,instruction:c.instruction,page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code}}}function se(){let c=A.flatMap(S=>{let $=st(S);return $===void 0?[]:[$]});if(c.length===0){x.clear();return}let u=new Set(c.map(({id:S})=>S));x.save({...v!==void 0&&u.has(v)?{activeTargetId:v}:{},open:B,sequence:q,targets:c})}function Ue(c,u){return i&&u===y&&b.status!=="idle"&&A.includes(c)}function xe(){let c=A.reduce((u,S)=>u+S.instruction.trim().length,0);return A.length>0&&c<=4e3&&A.every(u=>u.instruction.trim().length>0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function tt(){let c=A.flatMap(u=>{let S=st(u);return S===void 0?[]:[S]});if(!(c.length===0||c.length!==A.length))return Object.freeze({locale:n.locale(),targets:c})}function qe(){let c=n.messages().summary;return A.map((u,S)=>{let $=Rr({resolution:u.resolution,...u.code===void 0?{}:{code:u.code},...u.styles===void 0?{}:{styles:u.styles},apiStatus:u.apiStatus,collectionStatus:u.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},c);return`${c.target(S+1,u.id===v)}
860
+ ${$}`}).join(`
861
861
 
862
- `)}function Re(){let c=b.flatMap(u=>{if(!u.element?.isConnected)return[];let E=an(u.element,o.window);return E===void 0?[]:[{id:u.id,label:Mn(u.element),rect:E,active:u.id===x}]});c.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(c)}function Y(c=!1){if(b.length===0)return;n.renderTargets(b.map(V=>({id:V.id,label:V.resolution.react.componentName??(V.element===void 0?V.elementContext?.tagName??"Element":Mn(V.element)),source:ts(V,n.messages().context.sourceUnavailable),canOpenEditor:V.marker!==void 0,status:ns(V),active:V.id===x,instruction:V.instruction})),e.maxTargets),Re();let u=He(),E=be(),H=u?.marker!==void 0;c?n.showSelection(E,H,xe()):n.updateSelection(E,H,xe())}function _e(){if(!xe())return;let c=b.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let E=[...u.apiStatus==="failed"?["Source context could not be loaded."]:[],...u.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:u.instruction.trim(),page:u.page,source:u.resolution.source,react:u.resolution.react,element:u.elementContext,styles:u.styles,...u.code===void 0?{}:{code:u.code},warnings:E}});return ro({id:l(),locale:n.locale(),createdAt:A(),page:Fn(o.document,o.window),targets:c})}function Ke(c){n.showHighlight(Mo(c,o.window),Mn(c))}function Je(){v?.isConnected===!0&&v.focus({preventScroll:!0}),v=void 0}function Qe(){for(let c of $.values())o.window.clearTimeout(c);$.clear()}function Xe(){h+=1,s.cancelPending(),j.disposeSelection(),Ce?.cancelPending(),Qe(),L?.disconnect(),b=[],x=void 0,O+=1,_=void 0,U="idle",J=!1,G=!1,S=!1,C="",n.hideSelection(),n.hideSelectionHighlights(),w.clear(),Je()}function ne(){r.status==="inspecting"?k({type:"CANCEL"}):r.status==="selected"?k({type:"CLOSE"}):r.status==="previewing"&&(k({type:"BACK"}),k({type:"CLOSE"})),J=!1,le(),n.hideSelection(),n.hideSelectionHighlights(),Je(),n.hideHighlight()}function xt(){if(r.status!=="inspecting"||!S||b.length===0){ne();return}S=!1,k({type:"SELECT"}),n.hideHighlight(),Y(!0),n.focusTargetInstruction(x),n.announce(n.messages().announcements.addCancelled)}function et(){if(r.status==="inspecting"&&S){xt();return}if(r.status!=="idle"){ne();return}if(b.length>0){J=!0,k({type:"RESTORE"}),G||(j.beginSelection(),G=!0),Y(!0),Ae(),n.focusTargetInstruction(x),le();return}k({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function tt(c=n.messages().announcements.chooseAnother){r.status==="selected"&&(k({type:"RESELECT"}),Xe(),n.hideHighlight(),n.announce(c))}function Be(){if(r.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}S=!0,k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function ze(){h+=1,Qe(),L?.disconnect();for(let c of b)c.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),Y(),w.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let j=Sr({ai:e.ai,api:s,getAnnotation:_e,onApplied:ze,onReselectRequired(){tt(n.messages().announcements.reselectAfterChange)},view:n}),Ce=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?dn()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,_e,e.sessionToken,o.window):void 0;async function Te(c,u){let E=c.marker;if(E!==void 0)try{let H=await s.sourceContext({fileId:E.fileId,line:E.line,column:E.column,maxLines:e.budget.maxCodeLines});We(c,u)&&(c.code=H,c.apiStatus="connected",le(),Y(),n.announce(n.messages().announcements.sourceLoaded))}catch(H){We(c,u)&&(c.code=void 0,c.apiStatus="failed",le(),Y(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(H instanceof DOMException&&H.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function nt(c,u){let E=c.element;if(E===void 0)return;let H=o.window.setTimeout(()=>{if($.delete(c.id),!We(c,u))return;let V=!1;try{c.elementContext=Io({element:E,maxCharacters:e.budget.domCharacters})}catch{c.elementContext=void 0,V=!0}try{c.styles=vo({document:o.document,element:E,maxCharacters:e.budget.cssCharacters})}catch{c.styles=es,V=!0}c.collectionStatus=V?"failed":"ready",le(),Y(),n.announce(V?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&c.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(c.styles.warnings.length)} warning(s).`)},0);$.set(c.id,H)}function st(c,u){return u!==void 0?b.find(E=>E.marker?.fileId===u.fileId&&E.marker.line===u.line&&E.marker.column===u.column):b.find(E=>E.element===c)}function yt(c){let u=N.resolve(c),E=Pn(u.source),H=st(c,E);if(H!==void 0){x=H.id,S=!1,k({type:"SELECT"}),n.hideHighlight(),Y(!0),Ae(),n.focusTargetInstruction(H.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){S=!1,k({type:"SELECT"}),n.hideHighlight(),Y(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(v=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,C="",j.beginSelection(),G=!0),K+=1;let ie={id:`target-${String(K)}`,element:c,resolution:u,marker:E,page:Fn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:E===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};b.push(ie),x=ie.id,S=!1;let y=h;k({type:"SELECT"}),n.hideHighlight(),L?.observe(c),Y(!0),Ae(),J=!0,n.focusTargetInstruction(ie.id),nt(ie,y),E!==void 0?Te(ie,y):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function fe(){if(M=void 0,r.status!=="inspecting"||I===void 0)return;let c=wn(o.document,o.window,I.x,I.y);if(k({type:"HOVER"}),c===void 0){n.hideHighlight();return}Ke(c)}function je(c){r.status==="inspecting"&&(I={x:c.clientX,y:c.clientY},M??=o.window.requestAnimationFrame(fe))}function ot(c){if(r.status!=="inspecting"||$o(c.target))return;c.preventDefault(),c.stopPropagation(),c.stopImmediatePropagation();let u=wn(o.document,o.window,c.clientX,c.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}yt(u)}function ve(c){if(c.key==="Escape"&&r.status!=="idle"){c.preventDefault(),r.status==="inspecting"&&S?xt():r.status==="inspecting"||r.status==="selected"?ne():(k({type:"BACK"}),n.focusTargetInstruction(x));return}ko(c.target)||!Do(c,e.shortcut,o.window.navigator.userAgent)||(c.preventDefault(),et())}function rt(c){if(r.status!=="selected"&&r.status!=="inspecting")return;let u=b.findIndex(V=>V.id===c);if(u<0)return;let[E]=b.splice(u,1);if(E===void 0)return;let H=$.get(E.id);if(H!==void 0&&(o.window.clearTimeout(H),$.delete(E.id)),E.element!==void 0&&L?.unobserve(E.element),x===E.id&&(x=b.at(-1)?.id),b.length===0){S=!0,r.status==="selected"&&k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),_=void 0,U="idle",$e(),w.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}Y(),Ae(),le(),n.announce(n.messages().announcements.targetRemoved)}function Le(){if(r.status==="idle"||b.length===0)return;let c=b.filter(u=>u.element!==void 0&&!u.element.isConnected);if(c.length>0){for(let u of c)u.element!==void 0&&(L?.unobserve(u.element),u.element=void 0);Y(),le(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Re()}function P(c){let u=c===void 0?He():b.find(ie=>ie.id===c);if(r.status!=="selected"||u?.marker===void 0)return;x!==u.id&&(x=u.id,Y());let E=u.marker,H=h,V=++R;k({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:E.fileId,line:E.line,column:E.column}).then(()=>{F&&r.status==="selected"&&H===h&&V===R&&x===u.id&&b.includes(u)&&n.renderEditorStatus("success")}).catch(()=>{F&&r.status==="selected"&&H===h&&V===R&&x===u.id&&b.includes(u)&&n.renderEditorStatus("error")})}function ct(c){if(r.status!=="selected"||!(c.target instanceof HTMLTextAreaElement))return;let u=c.target.dataset.targetInstructionId,E=b.find(H=>H.id===u);E!==void 0&&(E.instruction=c.target.value,n.updateTargetInstruction(E.id,E.instruction),n.setPreviewEnabled(xe()),le())}function re(){P()}function Z(c){e.ai.enabled&&r.status==="selected"&&c.key==="Enter"&&(c.metaKey||c.ctrlKey)&&(c.preventDefault(),j.run())}function Ge(){if(r.status!=="selected")return;let c=_e();if(c===void 0){n.announce(n.messages().announcements.completeInstructions);return}C=d.compose(c),k({type:"PREVIEW"}),n.showPreview(C),n.focusPrompt()}function qe(){if(r.status!=="previewing"||C.length===0)return;if(i===void 0){k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let c=h;i.writeText(C).then(()=>{F&&c===h&&r.status==="previewing"&&(k({type:"COPY_SUCCESS"}),n.focusTargetInstruction(x),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{F&&c===h&&r.status==="previewing"&&(k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function me(){r.status==="previewing"&&(k({type:"BACK"}),n.focusTargetInstruction(x))}function bt(){if(!(!F||b.length===0)&&(Y(),r.status==="previewing")){let c=_e();c!==void 0&&(C=d.compose(c),n.showPreview(C))}}function Pe(c){let u=c.target;if(!(u instanceof Element))return;let E=u.closest("button[data-remove-target-id]");if(E?.dataset.removeTargetId!==void 0){rt(E.dataset.removeTargetId);return}let H=u.closest("button[data-open-target-id]");if(H?.dataset.openTargetId!==void 0){P(H.dataset.openTargetId);return}let ie=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;r.status!=="selected"||ie===void 0||!b.some(y=>y.id===ie)||(x=ie,Y(),Ae(),n.focusTargetInstruction(ie))}function Ie(){tt()}function Ye(){Ae()}function Q(){F||(F=!0,Ce?.mount(),n.renderStatus(r.status),o.document.addEventListener("pointermove",je,!0),o.document.addEventListener("click",ot,!0),o.document.addEventListener("keydown",ve,!0),o.window.addEventListener("scroll",Le,!0),o.window.addEventListener("resize",Le),n.triggerButton.addEventListener("click",et),n.addTargetButton.addEventListener("click",Be),n.reselectButton.addEventListener("click",Ie),n.targetList.addEventListener("click",Pe),n.targetList.addEventListener("input",ct),n.targetList.addEventListener("keydown",Z),n.openEditorButton.addEventListener("click",re),n.dataFlowRefreshButton.addEventListener("click",Ye),n.previewButton.addEventListener("click",Ge),n.copyButton.addEventListener("click",qe),n.backButton.addEventListener("click",me),n.closeButton.addEventListener("click",ne),n.agentProviderSelect.addEventListener("change",j.providerOrModelChanged),n.agentModelSelect.addEventListener("change",j.providerOrModelChanged),n.agentModeSelect.addEventListener("change",j.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",j.consentChanged),n.agentTestButton.addEventListener("click",j.testCapability),n.agentRunButton.addEventListener("click",j.run),n.agentCancelButton.addEventListener("click",j.cancel),n.agentApplyButton.addEventListener("click",j.apply),n.agentRevertButton.addEventListener("click",j.revert),n.agentResetButton.addEventListener("click",j.reset),Ee=n.subscribeLocale(bt),o.resizeObserver!==void 0&&(L=new o.resizeObserver(Le)),o.mutationObserver!==void 0&&(te=new o.mutationObserver(Le),te.observe(o.document.documentElement,{childList:!0,subtree:!0})),J&&b.length>0&&(k({type:"RESTORE"}),j.beginSelection(),G=!0,Y(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function Ue(){if(!F){Ee?.(),Ee=void 0,n.dispose(),s.cancelPending(),s.dispose(),j.disposeSelection(),Ce?.dispose(),N.dispose();return}F=!1,Ee?.(),Ee=void 0,o.document.removeEventListener("pointermove",je,!0),o.document.removeEventListener("click",ot,!0),o.document.removeEventListener("keydown",ve,!0),o.window.removeEventListener("scroll",Le,!0),o.window.removeEventListener("resize",Le),n.triggerButton.removeEventListener("click",et),n.addTargetButton.removeEventListener("click",Be),n.reselectButton.removeEventListener("click",Ie),n.targetList.removeEventListener("click",Pe),n.targetList.removeEventListener("input",ct),n.targetList.removeEventListener("keydown",Z),n.openEditorButton.removeEventListener("click",re),n.dataFlowRefreshButton.removeEventListener("click",Ye),n.previewButton.removeEventListener("click",Ge),n.copyButton.removeEventListener("click",qe),n.backButton.removeEventListener("click",me),n.closeButton.removeEventListener("click",ne),n.agentProviderSelect.removeEventListener("change",j.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",j.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",j.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",j.consentChanged),n.agentTestButton.removeEventListener("click",j.testCapability),n.agentRunButton.removeEventListener("click",j.run),n.agentCancelButton.removeEventListener("click",j.cancel),n.agentApplyButton.removeEventListener("click",j.apply),n.agentRevertButton.removeEventListener("click",j.revert),n.agentResetButton.removeEventListener("click",j.reset),M!==void 0&&(o.window.cancelAnimationFrame(M),M=void 0),Qe(),le(),L?.disconnect(),te?.disconnect(),L=void 0,te=void 0,b=[],x=void 0,C="",I=void 0,v=void 0,s.cancelPending(),s.dispose(),j.disposeSelection(),Ce?.dispose(),N.dispose(),n.dispose(),r=_n}return Object.freeze({mount:Q,dispose:Ue,getState:()=>r})}var Rr="__spotpatchRuntime__";function Hn(e){let t=globalThis;t[Rr]?.dispose();let o=xr(e);t[Rr]=o,o.mount()}Hn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:ce});
862
+ `)}function Ge(){let c=A.flatMap(u=>{if(!u.element?.isConnected)return[];let S=dn(u.element,o.window);return S===void 0?[]:[{id:u.id,label:Vn(u.element),rect:S,active:u.id===v}]});c.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(c)}function ee(c=!1){if(A.length===0)return;n.renderTargets(A.map(m=>({id:m.id,label:m.resolution.react.componentName??(m.element===void 0?m.elementContext?.tagName??"Element":Vn(m.element)),source:ls(m,n.messages().context.sourceUnavailable),canOpenEditor:m.marker!==void 0,status:ds(m),active:m.id===v,instruction:m.instruction})),e.maxTargets),Ge();let u=le(),S=qe(),$=u?.marker!==void 0;c?n.showSelection(S,$,xe()):n.updateSelection(S,$,xe())}function de(){if(!xe())return;let c=A.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let S=[...u.apiStatus==="failed"?["Source context could not be loaded."]:[],...u.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:u.instruction.trim(),page:u.page,source:u.resolution.source,react:u.resolution.react,element:u.elementContext,styles:u.styles,...u.code===void 0?{}:{code:u.code},warnings:S}});return po({id:d(),locale:n.locale(),createdAt:C(),page:zn(o.document,o.window),targets:c})}function Ne(c){n.showHighlight(zo(c,o.window),Vn(c))}function nt(){O?.isConnected===!0&&O.focus({preventScroll:!0}),O=void 0}function Ke(){for(let c of D.values())o.window.clearTimeout(c);D.clear()}function ct(){y+=1,s.cancelPending(),U.disposeSelection(),je?.cancelPending(),Ce?.cancelPending(),Ke(),_?.disconnect(),A=[],v=void 0,L+=1,M=void 0,K="idle",B=!1,I=!1,E=!1,T="",n.hideSelection(),n.hideSelectionHighlights(),x.clear(),nt()}function ot(){b.status==="inspecting"?N({type:"CANCEL"}):b.status==="selected"?N({type:"CLOSE"}):b.status==="previewing"&&(N({type:"BACK"}),N({type:"CLOSE"})),B=!1,se(),n.hideSelection(),n.hideSelectionHighlights(),nt(),n.hideHighlight()}function lt(){if(b.status!=="inspecting"||!E||A.length===0){ot();return}E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.focusTargetInstruction(v),n.announce(n.messages().announcements.addCancelled)}function De(){if(b.status==="inspecting"&&E){lt();return}if(b.status!=="idle"){ot();return}if(A.length>0){B=!0,N({type:"RESTORE"}),I||(U.beginSelection(),I=!0),ee(!0),te(),n.focusTargetInstruction(v),se();return}N({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function ne(c=n.messages().announcements.chooseAnother){b.status==="selected"&&(N({type:"RESELECT"}),ct(),n.hideHighlight(),n.announce(c))}function Re(){if(b.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}E=!0,N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function Je(){y+=1,Ke(),_?.disconnect();for(let c of A)c.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),ee(),x.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let U=Tr({ai:e.ai,api:s,getAnnotation:de,onApplied:Je,onReselectRequired(){ne(n.messages().announcements.reselectAfterChange)},view:n}),je=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?gn()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,de,e.sessionToken,o.window):void 0,Ce=e.contextualAsk.enabled&&n.contextualAskPanel!==void 0?fn()?.createWorkflow({...a===void 0?{}:{clipboard:a},createId:d,fetch:o.window.fetch.bind(o.window),getSelection:tt,onBusyChange(c){n.setAgentEditingEnabled(!c)},onConvert(){n.focusTargetInstruction(v)},async onOpenSource(c){await s.openEditor({fileId:c.fileId,line:c.startLine,column:1})},panel:n.contextualAskPanel,sessionToken:e.sessionToken}):void 0;async function St(c,u){let S=c.marker;if(S!==void 0)try{let $=await s.sourceContext({fileId:S.fileId,line:S.line,column:S.column,maxLines:e.budget.maxCodeLines});Ue(c,u)&&(c.code=$,c.apiStatus="connected",se(),ee(),n.announce(n.messages().announcements.sourceLoaded))}catch($){Ue(c,u)&&(c.code=void 0,c.apiStatus="failed",se(),ee(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!($ instanceof DOMException&&$.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Xe(c,u){let S=c.element;if(S===void 0)return;let $=o.window.setTimeout(()=>{if(D.delete(c.id),!Ue(c,u))return;let m=!1;try{c.elementContext=Ho({element:S,maxCharacters:e.budget.domCharacters})}catch{c.elementContext=void 0,m=!0}try{c.styles=Po({document:o.document,element:S,maxCharacters:e.budget.cssCharacters})}catch{c.styles=cs,m=!0}c.collectionStatus=m?"failed":"ready",se(),ee(),n.announce(m?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&c.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(c.styles.warnings.length)} warning(s).`)},0);D.set(c.id,$)}function fe(c,u){return u!==void 0?A.find(S=>S.marker?.fileId===u.fileId&&S.marker.line===u.line&&S.marker.column===u.column):A.find(S=>S.element===c)}function Ye(c){let u=V.resolve(c),S=Hn(u.source),$=fe(c,S);if($!==void 0){v=$.id,E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),te(),n.focusTargetInstruction($.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}let m=A.length===0;m&&(O=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,T="",U.beginSelection(),I=!0,Ce?.beginSelection()),q+=1;let F={id:`target-${String(q)}`,element:c,resolution:u,marker:S,page:zn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:S===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};A.push(F),m||Ce?.selectionChanged(),v=F.id,E=!1;let G=y;N({type:"SELECT"}),n.hideHighlight(),_?.observe(c),ee(!0),te(),B=!0,n.focusTargetInstruction(F.id),Xe(F,G),S!==void 0?St(F,G):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Ze(){if(W=void 0,b.status!=="inspecting"||H===void 0)return;let c=Nn(o.document,o.window,H.x,H.y);if(N({type:"HOVER"}),c===void 0){n.hideHighlight();return}Ne(c)}function Se(c){b.status==="inspecting"&&(H={x:c.clientX,y:c.clientY},W??=o.window.requestAnimationFrame(Ze))}function we(c){if(b.status!=="inspecting"||Wo(c.target))return;c.preventDefault(),c.stopPropagation(),c.stopImmediatePropagation();let u=Nn(o.document,o.window,c.clientX,c.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}Ye(u)}function ze(c){if(c.key==="Escape"&&b.status!=="idle"){c.preventDefault(),b.status==="inspecting"&&E?lt():b.status==="inspecting"||b.status==="selected"?ot():(N({type:"BACK"}),n.focusTargetInstruction(v));return}Bo(c.target)||!Uo(c,e.shortcut,o.window.navigator.userAgent)||(c.preventDefault(),De())}function Rt(c){if(b.status!=="selected"&&b.status!=="inspecting")return;let u=A.findIndex(m=>m.id===c);if(u<0)return;let[S]=A.splice(u,1);if(S===void 0)return;let $=D.get(S.id);if($!==void 0&&(o.window.clearTimeout($),D.delete(S.id)),S.element!==void 0&&_?.unobserve(S.element),v===S.id&&(v=A.at(-1)?.id),A.length===0){E=!0,b.status==="selected"&&N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),M=void 0,K="idle",be(),x.clear(),Ce?.selectionChanged(),n.announce(n.messages().announcements.allTargetsRemoved);return}ee(),Ce?.selectionChanged(),te(),se(),n.announce(n.messages().announcements.targetRemoved)}function Ve(){if(b.status==="idle"||A.length===0)return;let c=A.filter(u=>u.element!==void 0&&!u.element.isConnected);if(c.length>0){for(let u of c)u.element!==void 0&&(_?.unobserve(u.element),u.element=void 0);ee(),se(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Ge()}function We(c){let u=c===void 0?le():A.find(F=>F.id===c);if(b.status!=="selected"||u?.marker===void 0)return;v!==u.id&&(v=u.id,ee());let S=u.marker,$=y,m=++R;N({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:S.fileId,line:S.line,column:S.column}).then(()=>{i&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("success")}).catch(()=>{i&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("error")})}function dt(c){if(b.status!=="selected"||!(c.target instanceof HTMLTextAreaElement))return;let u=c.target.dataset.targetInstructionId,S=A.find($=>$.id===u);S!==void 0&&(S.instruction=c.target.value,n.updateTargetInstruction(S.id,S.instruction),n.setPreviewEnabled(xe()),se())}function P(){We()}function rt(c){e.ai.enabled&&b.status==="selected"&&c.key==="Enter"&&(c.metaKey||c.ctrlKey)&&(c.preventDefault(),U.run())}function Z(){if(b.status!=="selected")return;let c=de();if(c===void 0){n.announce(n.messages().announcements.completeInstructions);return}T=l.compose(c),N({type:"PREVIEW"}),n.showPreview(T),n.focusPrompt()}function Y(){if(b.status!=="previewing"||T.length===0)return;if(a===void 0){N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let c=y;a.writeText(T).then(()=>{i&&c===y&&b.status==="previewing"&&(N({type:"COPY_SUCCESS"}),n.focusTargetInstruction(v),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{i&&c===y&&b.status==="previewing"&&(N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Me(){b.status==="previewing"&&(N({type:"BACK"}),n.focusTargetInstruction(v))}function pt(){if(!(!i||A.length===0)&&(ee(),b.status==="previewing")){let c=de();c!==void 0&&(T=l.compose(c),n.showPreview(T))}}function Fe(c){let u=c.target;if(!(u instanceof Element))return;let S=u.closest("button[data-remove-target-id]");if(S?.dataset.removeTargetId!==void 0){Rt(S.dataset.removeTargetId);return}let $=u.closest("button[data-open-target-id]");if($?.dataset.openTargetId!==void 0){We($.dataset.openTargetId);return}let F=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;b.status!=="selected"||F===void 0||!A.some(G=>G.id===F)||(v=F,ee(),te(),n.focusTargetInstruction(F))}function re(){ne()}function Oe(){te()}function He(){i||(i=!0,je?.mount(),Ce?.mount(),n.renderStatus(b.status),o.document.addEventListener("pointermove",Se,!0),o.document.addEventListener("click",we,!0),o.document.addEventListener("keydown",ze,!0),o.window.addEventListener("scroll",Ve,!0),o.window.addEventListener("resize",Ve),n.triggerButton.addEventListener("click",De),n.addTargetButton.addEventListener("click",Re),n.reselectButton.addEventListener("click",re),n.targetList.addEventListener("click",Fe),n.targetList.addEventListener("input",dt),n.targetList.addEventListener("keydown",rt),n.openEditorButton.addEventListener("click",P),n.dataFlowRefreshButton.addEventListener("click",Oe),n.previewButton.addEventListener("click",Z),n.copyButton.addEventListener("click",Y),n.backButton.addEventListener("click",Me),n.closeButton.addEventListener("click",ot),n.agentProviderSelect.addEventListener("change",U.providerOrModelChanged),n.agentModelSelect.addEventListener("change",U.providerOrModelChanged),n.agentModeSelect.addEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",U.consentChanged),n.agentTestButton.addEventListener("click",U.testCapability),n.agentRunButton.addEventListener("click",U.run),n.agentCancelButton.addEventListener("click",U.cancel),n.agentApplyButton.addEventListener("click",U.apply),n.agentRevertButton.addEventListener("click",U.revert),n.agentResetButton.addEventListener("click",U.reset),ve=n.subscribeLocale(pt),o.resizeObserver!==void 0&&(_=new o.resizeObserver(Ve)),o.mutationObserver!==void 0&&(pe=new o.mutationObserver(Ve),pe.observe(o.document.documentElement,{childList:!0,subtree:!0})),B&&A.length>0&&(N({type:"RESTORE"}),U.beginSelection(),Ce?.beginSelection(),I=!0,ee(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function at(){if(!i){ve?.(),ve=void 0,n.dispose(),s.cancelPending(),s.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose();return}i=!1,ve?.(),ve=void 0,o.document.removeEventListener("pointermove",Se,!0),o.document.removeEventListener("click",we,!0),o.document.removeEventListener("keydown",ze,!0),o.window.removeEventListener("scroll",Ve,!0),o.window.removeEventListener("resize",Ve),n.triggerButton.removeEventListener("click",De),n.addTargetButton.removeEventListener("click",Re),n.reselectButton.removeEventListener("click",re),n.targetList.removeEventListener("click",Fe),n.targetList.removeEventListener("input",dt),n.targetList.removeEventListener("keydown",rt),n.openEditorButton.removeEventListener("click",P),n.dataFlowRefreshButton.removeEventListener("click",Oe),n.previewButton.removeEventListener("click",Z),n.copyButton.removeEventListener("click",Y),n.backButton.removeEventListener("click",Me),n.closeButton.removeEventListener("click",ot),n.agentProviderSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",U.consentChanged),n.agentTestButton.removeEventListener("click",U.testCapability),n.agentRunButton.removeEventListener("click",U.run),n.agentCancelButton.removeEventListener("click",U.cancel),n.agentApplyButton.removeEventListener("click",U.apply),n.agentRevertButton.removeEventListener("click",U.revert),n.agentResetButton.removeEventListener("click",U.reset),W!==void 0&&(o.window.cancelAnimationFrame(W),W=void 0),Ke(),se(),_?.disconnect(),pe?.disconnect(),_=void 0,pe=void 0,A=[],v=void 0,T="",H=void 0,O=void 0,s.cancelPending(),s.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose(),n.dispose(),b=Mn}return Object.freeze({mount:He,dispose:at,getState:()=>b})}var _r="__spotpatchRuntime__";function Wn(e){let t=globalThis;t[_r]?.dispose();let o=Or(e);t[_r]=o,o.mount()}Wn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:ae});