@spotpatch/vite 1.10.0 → 1.11.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.
- package/dist/cli.js +13 -0
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +39 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +43 -13
- package/dist/index.js.map +1 -1
- package/dist/runtime-client.js +11 -11
- package/dist/runtime-data-flow-panel.js +3 -3
- package/dist/runtime-data-flow-prelude.js +1 -1
- package/dist/runtime-external-handoff-panel.js +14 -4
- package/package.json +5 -5
package/dist/runtime-client.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createReact18Adapter as Ma}from"@spotpatch/react-adapter";var l={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"},Io=Object.freeze(Object.values(l));var No=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ko=/blob:[^\s"'<>]+/giu,Do=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Mo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Fo=/\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,Ho=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),$o=500;function Bo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Uo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ft(e){let t=Bo(e);return Ho.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function V(e){return e.replace(No,"[redacted inline data]").replace(ko,"[redacted blob URL]").replace(Do,"Bearer [redacted]").replace(Mo,"$1[redacted]@").replace(Fo,(t,o,n,i)=>{let c=i.at(0),r=c==='"'||c==="'"||c==="`";return`${o}${n}${r?c:""}[redacted]${r?c:""}`})}function zo(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Ft(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,V(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function ft(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=V(o);try{let i=new URL(n,t),c=zo(i),r=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===r.origin?`${i.pathname}${i.search}${i.hash}`:c}catch{return Uo(n,$o)}}var Oe="/__spotpatch/v1",Ht="X-SpotPatch-Token",nt=Object.freeze({bootstrap:`${Oe}/bootstrap`,sourceContext:`${Oe}/source-context`,openEditor:`${Oe}/open-editor`,dataFlowComponentReport:`${Oe}/data-flow/component-report`,dataFlowPageReport:`${Oe}/data-flow/page-report`,agentCapability:`${Oe}/agent/capability`,agentWorkspaceHealth:`${Oe}/agent/workspace-health`,agentJobs:`${Oe}/agent/jobs`,externalHandoffCapability:`${Oe}/external-handoff/capability`,externalHandoffPublish:`${Oe}/external-handoff/publish`,externalHandoffStatus:`${Oe}/external-handoff/status`,externalHandoffResolveDelivery:`${Oe}/external-handoff/resolve-delivery`});function Et(e,t){return`${nt.agentJobs}/${encodeURIComponent(e)}/${t}`}var jo=Object.freeze(["review","auto","trusted-auto"]),Vo=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),nn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),on=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Go=Object.freeze(["ready","consent-required","blocked"]),Wo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),rn=Object.freeze(["added","modified","deleted"]),an=Object.freeze(["passed","failed","cancelled","timed-out"]);var sn="data-spotpatch-source",qo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function cn(e){if(e===null)return;let t=qo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var ln="https://github.com/huanglvjing/spotpatch";function En(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function Ko(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:En(e.source)}})}function Yo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Xo(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 Zo(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:En(e.source,e.code),react:Ko(e.react),element:Yo(e.element),styles:Xo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function An(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(Zo)),createdAt:e.createdAt})}var Qo=new Set(Object.values(l)),er=new Set(on),tr=new Set(an),nr=new Set(rn),Rn=new Set(nn),or=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,rr=/^[A-Za-z0-9_-]+$/,ar=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e,t){return Object.keys(e).every(o=>t.includes(o))}function me(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function _t(e){return me(e,64,1)&&typeof e=="string"&&or.test(e)}function dn(e){return me(e,128,22)&&typeof e=="string"&&rr.test(e)}function Lt(e){return typeof e=="string"&&ar.test(e)&&Number.isFinite(Date.parse(e))}function mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Cn(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function xn(e,t){return e===void 0||me(e,t)}function Rt(e){return typeof e=="string"&&Qo.has(e)}function Tn(e){return!ot(e)||!_e(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:_t(e.providerProfileId)&&me(e.providerLabel,100)&&_t(e.modelProfileId)&&me(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&er.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||Lt(e.checkedAt))&&(e.errorCode===void 0||Rt(e.errorCode))}function vn(e){if(!ot(e)||!_e(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!Lt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Rt(e.errorCode)||!ot(e.changes)||!_e(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:c,total:r}=t;return!mt(o)||!mt(n)||!mt(i)||!mt(c)||!mt(r)||r<o||r<n||r<i||r<c||r>o+n+i?!1:e.state==="ready"?r===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?r>0&&c===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function Bt(e){return!ot(e)||!_e(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:dn(e.jobId)&&typeof e.status=="string"&&Rn.has(e.status)&&_t(e.providerProfileId)&&me(e.providerLabel,100)&&_t(e.modelProfileId)&&me(e.modelLabel,100)&&me(e.phaseMessage,1024)&&Lt(e.createdAt)&&Lt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Rt(e.errorCode))}function ir(e){return ot(e)&&_e(e,["relativePath","kind","additions","deletions"])&&me(e.relativePath,1024)&&typeof e.kind=="string"&&nr.has(e.kind)&&mt(e.additions)&&mt(e.deletions)}function wn(e){return ot(e)&&_e(e,["checkId","label","status","durationMs","output"])&&_t(e.checkId)&&me(e.label,100)&&typeof e.status=="string"&&tr.has(e.status)&&mt(e.durationMs)&&me(e.output,8e4)}function sr(e){return ot(e)&&_e(e,["jobId","summary","diff","files","checks"])&&dn(e.jobId)&&me(e.summary,8e4)&&me(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ir)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(wn)}function On(e){return ot(e)&&_e(e,["snapshot","result"])&&Bt(e.snapshot)&&(e.result===void 0||sr(e.result)&&e.result.jobId===e.snapshot.jobId)}function cr(e){return ot(e)&&_e(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&Cn(e.sequence)&&dn(e.jobId)&&typeof e.status=="string"&&Rn.has(e.status)&&Lt(e.timestamp)&&typeof e.type=="string"&&ot(e.data)}function _n(e){if(!cr(e))return!1;let t=e.data;switch(e.type){case"snapshot":return _e(t,["snapshot"])&&Bt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return _e(t,["message"])&&me(t.message,1024);case"tool":return _e(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&Cn(t.turn)&&me(t.toolCallId,256)&&me(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&xn(t.relativePath,1024)&&xn(t.checkLabel,100);case"check":return _e(t,["result"])&&wn(t.result);case"result-ready":return _e(t,["hasResult"])&&t.hasResult===!0;case"error":return _e(t,["code","message"])&&Rt(t.code)&&me(t.message,1024);default:return!1}}var In=2e6,Ln=1e5,lr=4e6,k=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dr(e){if(!(!Le(e)||e.ok!==!1||!Le(e.error)))return Rt(e.error.code)?e.error.code:void 0}function pr(e){if(!Le(e)||e.ok!==!0||!("data"in e))throw new k;return e.data}function ur(e){return Le(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function Nn(e){if(!(!Le(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Nn(t);Object.freeze(e)}}function At(e){return Nn(e),e}async function gr(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new k;if(e.body===null)throw new k;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),c=0,r="";try{for(;;){let u=await n.read();if(u.done)return r+=i.decode(),r;if(c+=u.value.byteLength,c>t)throw await n.cancel(),new k;r+=i.decode(u.value,{stream:!0})}}catch(u){throw u instanceof k?u:new k}finally{n.releaseLock()}}function kn(e){try{return JSON.parse(e)}catch{throw new k}}async function Pn(e,t=In){let o=kn(await gr(e,t));if(!e.ok)throw new k(dr(o));return pr(o)}function zt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function fr(e){return Le(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function mr(e){return Le(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 hr(e){return Le(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)&&Le(e.response)&&zt(e.response.consumedFields)&&zt(e.evidenceIds)&&zt(e.observationIds)}function Dn(e){return Le(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Le(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&zt(e.baseline.analyzedSourceVersions)&&mr(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(hr)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&fr(e.completeness)}function br(e){return Dn(e)&&Le(e)&&Le(e.component)&&Le(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function yr(e){return Dn(e)}function Sr(e,t){if(!Tn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new k;return At(e)}function Ut(e,t){if(!Bt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new k;return At(e)}function Er(e,t){if(!On(e)||e.snapshot.jobId!==t)throw new k;return At(e)}function Ar(e){if(!_n(e))throw new k;return At(e)}function xr(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function Mn(e){return e instanceof k?e.code:void 0}function Fn(e){let t=new Set;function o(){for(let r of t)r.abort();t.clear()}async function n(r,u,R,s=In){let A=new AbortController;t.add(A);try{let z=await e.fetch(r,{method:u,headers:{...R===void 0?{}:{"Content-Type":"application/json"},[Ht]:e.sessionToken},...R===void 0?{}:{body:JSON.stringify(R)},signal:A.signal});return await Pn(z,s)}finally{t.delete(A)}}async function i(r,u){let R=new AbortController;t.add(R);try{let s=await e.fetch(Et(r,"events"),{method:"POST",headers:{"Content-Type":"application/json",[Ht]:e.sessionToken},body:JSON.stringify({}),signal:R.signal});if(!s.ok){await Pn(s);return}if(s.body===null)throw new k;let A=s.body.getReader(),z=new TextDecoder("utf-8",{fatal:!0}),m="",L=0,M=0,P=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>Ln)throw new k;let T=Ar(kn(b));if(T.jobId!==r||T.sequence<=M)throw new k;M=T.sequence,u(T)};try{for(;;){let b=await A.read();if(b.done){m+=z.decode(),P(m);return}if(L+=b.value.byteLength,L>lr)throw await A.cancel(),new k;m+=z.decode(b.value,{stream:!0});let T=m.split(`
|
|
2
|
-
`);if(m=T.pop()??"",new TextEncoder().encode(m).byteLength>Ln)throw await A.cancel(),new
|
|
3
|
-
`).length}function Lr(e,t){return e.href===null?void 0:ft(e.href,t)}function Un(e,t,o,n,i,c){for(let r of t){if(vr(r)){let u=!1;try{u=e.matches(r.selectorText)}catch{c.add(
|
|
4
|
-
`),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=ht.maxTextCharacters?i:`${i.slice(0,ht.maxTextCharacters)}…`},...r===null?{}:{role:r},rect:Object.freeze({x:c.x,y:c.y,width:c.width,height:c.height})})}function Kn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Br(e){return e.toLowerCase()}function
|
|
1
|
+
import{createReact18Adapter as Ma}from"@spotpatch/react-adapter";var l={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"},Io=Object.freeze(Object.values(l));var Po=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Do=/blob:[^\s"'<>]+/giu,ko=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,Mo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Fo=/\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,Ho=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),$o=500;function Bo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Uo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ft(e){let t=Bo(e);return Ho.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function V(e){return e.replace(Po,"[redacted inline data]").replace(Do,"[redacted blob URL]").replace(ko,"Bearer [redacted]").replace(Mo,"$1[redacted]@").replace(Fo,(t,o,n,i)=>{let c=i.at(0),r=c==='"'||c==="'"||c==="`";return`${o}${n}${r?c:""}[redacted]${r?c:""}`})}function zo(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Ft(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,V(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function ft(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=V(o);try{let i=new URL(n,t),c=zo(i),r=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===r.origin?`${i.pathname}${i.search}${i.hash}`:c}catch{return Uo(n,$o)}}var X="/__spotpatch/v1",Ht="X-SpotPatch-Token",nt=Object.freeze({bootstrap:`${X}/bootstrap`,sourceContext:`${X}/source-context`,openEditor:`${X}/open-editor`,dataFlowComponentReport:`${X}/data-flow/component-report`,dataFlowPageReport:`${X}/data-flow/page-report`,agentCapability:`${X}/agent/capability`,agentWorkspaceHealth:`${X}/agent/workspace-health`,agentJobs:`${X}/agent/jobs`,externalHandoffCapability:`${X}/external-handoff/capability`,externalHandoffPublish:`${X}/external-handoff/publish`,externalHandoffStatus:`${X}/external-handoff/status`,externalHandoffResolveDelivery:`${X}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${X}/external-agent/control/status`,externalAgentControlConnect:`${X}/external-agent/control/connect`,externalAgentControlDisconnect:`${X}/external-agent/control/disconnect`,externalAgentControlCancel:`${X}/external-agent/control/cancel`,externalAgentEvents:`${X}/external-agent/events`,externalAgentResult:`${X}/external-agent/result`});function St(e,t){return`${nt.agentJobs}/${encodeURIComponent(e)}/${t}`}var jo=Object.freeze(["review","auto","trusted-auto"]),Vo=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),nn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),on=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Go=Object.freeze(["ready","consent-required","blocked"]),Wo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),rn=Object.freeze(["added","modified","deleted"]),an=Object.freeze(["passed","failed","cancelled","timed-out"]);var sn="data-spotpatch-source",qo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function cn(e){if(e===null)return;let t=qo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var ln="https://github.com/huanglvjing/spotpatch";function Sn(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function Ko(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:Sn(e.source)}})}function Xo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Yo(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 Zo(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:Sn(e.source,e.code),react:Ko(e.react),element:Xo(e.element),styles:Yo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function An(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(Zo)),createdAt:e.createdAt})}var Qo=new Set(Object.values(l)),er=new Set(on),tr=new Set(an),nr=new Set(rn),Rn=new Set(nn),or=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,rr=/^[A-Za-z0-9_-]+$/,ar=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e,t){return Object.keys(e).every(o=>t.includes(o))}function he(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function _t(e){return he(e,64,1)&&typeof e=="string"&&or.test(e)}function dn(e){return he(e,128,22)&&typeof e=="string"&&rr.test(e)}function Lt(e){return typeof e=="string"&&ar.test(e)&&Number.isFinite(Date.parse(e))}function mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Cn(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function xn(e,t){return e===void 0||he(e,t)}function Rt(e){return typeof e=="string"&&Qo.has(e)}function Tn(e){return!ot(e)||!_e(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:_t(e.providerProfileId)&&he(e.providerLabel,100)&&_t(e.modelProfileId)&&he(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&er.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||Lt(e.checkedAt))&&(e.errorCode===void 0||Rt(e.errorCode))}function vn(e){if(!ot(e)||!_e(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!Lt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Rt(e.errorCode)||!ot(e.changes)||!_e(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:c,total:r}=t;return!mt(o)||!mt(n)||!mt(i)||!mt(c)||!mt(r)||r<o||r<n||r<i||r<c||r>o+n+i?!1:e.state==="ready"?r===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?r>0&&c===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function Bt(e){return!ot(e)||!_e(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:dn(e.jobId)&&typeof e.status=="string"&&Rn.has(e.status)&&_t(e.providerProfileId)&&he(e.providerLabel,100)&&_t(e.modelProfileId)&&he(e.modelLabel,100)&&he(e.phaseMessage,1024)&&Lt(e.createdAt)&&Lt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Rt(e.errorCode))}function ir(e){return ot(e)&&_e(e,["relativePath","kind","additions","deletions"])&&he(e.relativePath,1024)&&typeof e.kind=="string"&&nr.has(e.kind)&&mt(e.additions)&&mt(e.deletions)}function wn(e){return ot(e)&&_e(e,["checkId","label","status","durationMs","output"])&&_t(e.checkId)&&he(e.label,100)&&typeof e.status=="string"&&tr.has(e.status)&&mt(e.durationMs)&&he(e.output,8e4)}function sr(e){return ot(e)&&_e(e,["jobId","summary","diff","files","checks"])&&dn(e.jobId)&&he(e.summary,8e4)&&he(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ir)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(wn)}function On(e){return ot(e)&&_e(e,["snapshot","result"])&&Bt(e.snapshot)&&(e.result===void 0||sr(e.result)&&e.result.jobId===e.snapshot.jobId)}function cr(e){return ot(e)&&_e(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&Cn(e.sequence)&&dn(e.jobId)&&typeof e.status=="string"&&Rn.has(e.status)&&Lt(e.timestamp)&&typeof e.type=="string"&&ot(e.data)}function _n(e){if(!cr(e))return!1;let t=e.data;switch(e.type){case"snapshot":return _e(t,["snapshot"])&&Bt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return _e(t,["message"])&&he(t.message,1024);case"tool":return _e(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&Cn(t.turn)&&he(t.toolCallId,256)&&he(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&xn(t.relativePath,1024)&&xn(t.checkLabel,100);case"check":return _e(t,["result"])&&wn(t.result);case"result-ready":return _e(t,["hasResult"])&&t.hasResult===!0;case"error":return _e(t,["code","message"])&&Rt(t.code)&&he(t.message,1024);default:return!1}}var In=2e6,Ln=1e5,lr=4e6,D=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dr(e){if(!(!Le(e)||e.ok!==!1||!Le(e.error)))return Rt(e.error.code)?e.error.code:void 0}function pr(e){if(!Le(e)||e.ok!==!0||!("data"in e))throw new D;return e.data}function ur(e){return Le(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 Pn(e){if(!(!Le(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Pn(t);Object.freeze(e)}}function At(e){return Pn(e),e}async function gr(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new D;if(e.body===null)throw new D;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),c=0,r="";try{for(;;){let u=await n.read();if(u.done)return r+=i.decode(),r;if(c+=u.value.byteLength,c>t)throw await n.cancel(),new D;r+=i.decode(u.value,{stream:!0})}}catch(u){throw u instanceof D?u:new D}finally{n.releaseLock()}}function Dn(e){try{return JSON.parse(e)}catch{throw new D}}async function Nn(e,t=In){let o=Dn(await gr(e,t));if(!e.ok)throw new D(dr(o));return pr(o)}function zt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function fr(e){return Le(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function mr(e){return Le(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 hr(e){return Le(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)&&Le(e.response)&&zt(e.response.consumedFields)&&zt(e.evidenceIds)&&zt(e.observationIds)}function kn(e){return Le(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Le(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&zt(e.baseline.analyzedSourceVersions)&&mr(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(hr)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&fr(e.completeness)}function br(e){return kn(e)&&Le(e)&&Le(e.component)&&Le(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function yr(e){return kn(e)}function Er(e,t){if(!Tn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new D;return At(e)}function Ut(e,t){if(!Bt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new D;return At(e)}function Sr(e,t){if(!On(e)||e.snapshot.jobId!==t)throw new D;return At(e)}function Ar(e){if(!_n(e))throw new D;return At(e)}function xr(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function Mn(e){return e instanceof D?e.code:void 0}function Fn(e){let t=new Set;function o(){for(let r of t)r.abort();t.clear()}async function n(r,u,R,s=In){let A=new AbortController;t.add(A);try{let z=await e.fetch(r,{method:u,headers:{...R===void 0?{}:{"Content-Type":"application/json"},[Ht]:e.sessionToken},...R===void 0?{}:{body:JSON.stringify(R)},signal:A.signal});return await Nn(z,s)}finally{t.delete(A)}}async function i(r,u){let R=new AbortController;t.add(R);try{let s=await e.fetch(St(r,"events"),{method:"POST",headers:{"Content-Type":"application/json",[Ht]:e.sessionToken},body:JSON.stringify({}),signal:R.signal});if(!s.ok){await Nn(s);return}if(s.body===null)throw new D;let A=s.body.getReader(),z=new TextDecoder("utf-8",{fatal:!0}),m="",L=0,M=0,N=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>Ln)throw new D;let T=Ar(Dn(b));if(T.jobId!==r||T.sequence<=M)throw new D;M=T.sequence,u(T)};try{for(;;){let b=await A.read();if(b.done){m+=z.decode(),N(m);return}if(L+=b.value.byteLength,L>lr)throw await A.cancel(),new D;m+=z.decode(b.value,{stream:!0});let T=m.split(`
|
|
2
|
+
`);if(m=T.pop()??"",new TextEncoder().encode(m).byteLength>Ln)throw await A.cancel(),new D;for(let $ of T)N($)}}catch(b){throw b instanceof D||b instanceof DOMException&&b.name==="AbortError"?b:new D}finally{A.releaseLock()}}finally{t.delete(R)}}let c=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(r){let u=await n(nt.sourceContext,"POST",r);if(!ur(u))throw new D;return Object.freeze({...u})},async componentDataFlowReport(r){let u=await n(nt.dataFlowComponentReport,"POST",r,e.dataFlowReportMaxBytes);if(!br(u))throw new D;return At(u)},async pageDataFlowReport(r){let u=await n(nt.dataFlowPageReport,"POST",r,e.dataFlowReportMaxBytes);if(!yr(u))throw new D;return At(u)},async openEditor(r){let u=await n(nt.openEditor,"POST",r);if(!Le(u)||u.editor!=="auto"&&u.editor!=="vscode"&&u.editor!=="cursor")throw new D;return Object.freeze({editor:u.editor})},async agentCapability(r){return Er(await n(nt.agentCapability,"POST",r),r)},async agentWorkspaceHealth(){let r=await n(nt.agentWorkspaceHealth,"POST",c);if(!vn(r))throw new D;return At(r)},async createAgentJob(r){let u=xr(r);return Ut(await n(nt.agentJobs,"POST",u),r)},agentEvents:i,async agentResult(r){return Sr(await n(St(r,"result"),"POST",c),r)},async cancelAgentJob(r){return Ut(await n(St(r,"cancel"),"POST",c),{jobId:r})},async applyAgentJob(r){return Ut(await n(St(r,"apply"),"POST",c),{jobId:r})},async revertAgentJob(r){return Ut(await n(St(r,"revert"),"POST",c),{jobId:r})},dispose(){o()}})}var Rr=500,Hn=256;function Cr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Tr(e){return Ft(e)}function $n(e,t,o){if(!Tr(e))return e==="href"||e==="src"?ft(t,o):e==="d"&&t.length>Hn?`${t.slice(0,Hn)}…`:Cr(V(t),Rr)}function Me(e){return V(e)}var Bn=Object.freeze(["display","position","inset","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height","margin","padding","box-sizing","overflow","overflow-x","overflow-y","flex","flex-direction","flex-wrap","align-items","align-content","justify-content","gap","grid-template-columns","grid-template-rows","font-family","font-size","font-weight","line-height","text-align","white-space","color","background-color","border","border-radius","opacity","visibility","z-index","transform"]);var Nt=Object.freeze({cascade:"CSS shorthand and longhand cascade resolution is not available in v1.",cssInJs:"Runtime CSS-in-JS rules may not include original TypeScript source locations.",inaccessibleStylesheet:"A stylesheet could not be inspected because browser security denied access.",selector:"A stylesheet selector could not be evaluated and was skipped.",state:"Dynamic pseudo-class and pseudo-element rules may be unavailable in the current state."});function vr(e){return"selectorText"in e&&"style"in e}function wr(e){return"cssRules"in e}function Or(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 _r(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((c,r)=>c+r.selector.length+r.declarations.length+(r.source?.length??0)+(r.media?.length??0),0)+Object.entries(n).reduce((c,[r,u])=>c+r.length+u.length,0)+i.join(`
|
|
3
|
+
`).length}function Lr(e,t){return e.href===null?void 0:ft(e.href,t)}function Un(e,t,o,n,i,c){for(let r of t){if(vr(r)){let u=!1;try{u=e.matches(r.selectorText)}catch{c.add(Nt.selector);continue}u&&i.push(Object.freeze({selector:Me(r.selectorText),declarations:Me(r.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(wr(r)){let u=Or(r);Un(e,r.cssRules,o,u===void 0?n:[...n,u],i,c)}}}function Nr(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of Bn){let c=Me(o.getPropertyValue(i).trim());c.length>0&&(n[i]=c)}return n}function zn(e){let t=new Set([Nt.state,Nt.cssInJs,Nt.cascade]),o=[],n=e.readCssRules??(A=>A.cssRules);for(let A of e.document.styleSheets){let z;try{z=n(A)}catch{t.add(Nt.inaccessibleStylesheet);continue}Un(e.element,z,Lr(A,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),c=e.element.getAttribute("style"),r=c===null?void 0:Me(c),u=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),R=Object.entries(Nr(e.element,u)),s=Array.from(t);for(;_r(i,r,o,Object.fromEntries(R),s)>e.maxCharacters;){if(R.length>0){R.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...r===void 0?{}:{inlineStyle:r},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(R)),warnings:Object.freeze(s)})}var ht=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),Ir=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"]),Pr=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Vn(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function Dr(e){return Ir.has(e)||e.startsWith("aria-")||e==="data-testid"}function Gn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let c=i.name.toLowerCase();if(!Dr(c))continue;let r=$n(c,i.value,n);r!==void 0&&o.push(`${c}="${Vn(r)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Wn(e){return V(e).replaceAll(/\s+/gu," ").trim()}function qn(e,t,o,n){if(o.nodeCount>=ht.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),c=e.tagName.toLowerCase();if(n.push(`${i}${Gn(e)}`),!Pr.has(c)){for(let r of e.childNodes){if(o.nodeCount>=ht.maxNodes){o.truncated=!0;break}if(r.nodeType===3){let u=Wn(r.textContent??"");if(u.length>0){o.nodeCount+=1;let R=u.length<=ht.maxTextCharacters?u:`${u.slice(0,ht.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Vn(R)}`)}continue}if(r.nodeType===1){if(t>=ht.maxDepth){o.truncated=!0;continue}qn(r,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${c}>`)}}function kr(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<ht.maxParentDepth;)t.push(Gn(o)),o=o.parentElement;return t}function Mr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function jn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Fr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Hr(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${jn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Fr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(u=>`.${jn(u)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(u=>u.tagName===e.tagName),c=i.indexOf(e),r=i.length>1&&c>=0?`:nth-of-type(${String(c+1)})`:"";return`${t}${n}${r}`}function $r(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Hr(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Jn(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};qn(e.element,0,o,t);let n=kr(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=Wn(e.element.textContent),c=e.element.getBoundingClientRect(),r=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:$r(e.element),sanitizedHtml:Mr(t.join(`
|
|
4
|
+
`),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=ht.maxTextCharacters?i:`${i.slice(0,ht.maxTextCharacters)}…`},...r===null?{}:{role:r},rect:Object.freeze({x:c.x,y:c.y,width:c.width,height:c.height})})}function Kn(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Br(e){return e.toLowerCase()}function Xn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Yn(e,t,o){let n=t.split("+").map(A=>A.trim().toLowerCase()).filter(A=>A.length>0),i=n.find(A=>A!=="mod"&&A!=="meta"&&A!=="ctrl"&&A!=="control"&&A!=="alt"&&A!=="option"&&A!=="shift");if(i===void 0||Br(e.key)!==i)return!1;let c=n.includes("mod"),r=n.includes("meta")||c&&Kn(o),u=n.includes("ctrl")||n.includes("control")||c&&!Kn(o),R=n.includes("alt")||n.includes("option"),s=n.includes("shift");return e.metaKey===r&&e.ctrlKey===u&&e.altKey===R&&e.shiftKey===s}function Ur(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function zr(e){let t=e.filter(u=>u.width>0&&u.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,c=o.right,r=o.bottom;for(let u of t.slice(1))n=Math.min(n,u.left),i=Math.min(i,u.top),c=Math.max(c,u.right),r=Math.max(r,u.bottom);return Object.freeze({x:n,y:i,width:c-n,height:r-i})}function Zn(e,t){if(t.startsWith("inline")){let o=zr(Array.from(e.getClientRects()));if(o!==void 0)return o}return Ur(e.getBoundingClientRect())}function Qn(e,t){return Zn(e,t.getComputedStyle(e).display)}function Vt(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=Zn(e,o.display);return n.width>0&&n.height>0?n:void 0}var xt="data-spotpatch-ui",It=Object.freeze({highlight:2147483646,controls:2147483647});function eo(e){if(e.closest(`[${xt}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(xt)}function jr(e,t){return Vt(e,t)!==void 0}function Vr(e){return e.tagName==="HTML"||e.tagName==="BODY"}function pn(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(c=>!eo(c)&&jr(c,t));return i.find(c=>!Vr(c))??i[0]}function to(e){return e instanceof Element&&eo(e)}var un=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 Gr(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function Gt(e,t){let o="`".repeat(Math.max(3,Gr(t)+1));return`${o}${e}
|
|
5
5
|
${t}
|
|
6
6
|
${o}`}function oo(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${V(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function ro(e,t){return e.split(`
|
|
7
7
|
`).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Wr(e){let t=[e.source===void 0?void 0:`/* source: ${Me(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Me(e.media)} */`].filter(n=>n!==void 0),o=`${Me(e.selector)} {
|
|
@@ -29,12 +29,12 @@ ${Gt(e.code.language,V(t.codeLines.join(`
|
|
|
29
29
|
|
|
30
30
|
`),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
|
|
31
31
|
|
|
32
|
-
`)}function
|
|
32
|
+
`)}function Xr(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let r=t.codeLines[0]??"";return r.length<=120?t.codeLines=[]:t.codeLines=[`${r.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function Yr(e){return{instruction:V(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 Zr(e){return{pageTitle:V(e.page.title),targets:e.targets.map(Yr)}}function Qr(e,t,o){let n=un[e.locale],i=[(c,r)=>r.computedEntries.pop()!==void 0,(c,r)=>r.reactStack.pop()!==void 0,(c,r)=>{let u=ro(r.dom,n.unavailable);return r.dom===u?!1:(r.dom=u,!0)},(c,r)=>r.matchedRules.shift()!==void 0,Xr,(c,r)=>r.warnings.pop()!==void 0];for(let c of i)for(let r=0;r<e.targets.length;r+=1){let u=(o+r)%e.targets.length,R=e.targets[u],s=t.targets[u];if(R!==void 0&&s!==void 0&&c(R,s))return(u+1)%e.targets.length}}function ea(e,t){let o=un[e.locale],n=e.targets.map((i,c)=>{let r=t.targets[c],u=i.react.componentName;return[`### ${o.target(c+1)}`,`- ${o.requestedChange}: ${r?.instruction??V(i.instruction)}`,`- ${o.file}: ${oo(i,o)}`,...u===void 0?[]:[`- ${o.component}: ${V(u)}`],`- ${o.element}: ${V(ro(r?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
|
|
33
33
|
`)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
|
|
34
34
|
|
|
35
35
|
`),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
|
|
36
36
|
|
|
37
|
-
`)}function ta(e,t){let o=Zr(e),n=no(e,o),i=0;for(;n.length>t;){let r=Qr(e,o,i);if(r===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=r;n=no(e,o)}if(n.length<=t)return n;let c=ea(e,o);if(c.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return c}function ao(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 ta(t,e.maxCharacters)}})}var
|
|
37
|
+
`)}function ta(e,t){let o=Zr(e),n=no(e,o),i=0;for(;n.length>t;){let r=Qr(e,o,i);if(r===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=r;n=no(e,o)}if(n.length<=t)return n;let c=ea(e,o);if(c.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return c}function ao(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 ta(t,e.maxCharacters)}})}var xe=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),gn=xe.idle;function na(e){return e.type==="ACTIVATE"?xe.inspecting:e.type==="RESTORE"?xe.selected:xe.idle}function oa(e){switch(e.type){case"HOVER":return xe.inspecting;case"SELECT":return xe.selected;case"CANCEL":return xe.idle;default:return xe.inspecting}}function ra(e){switch(e.type){case"RESELECT":return xe.inspecting;case"CLOSE":return xe.idle;case"PREVIEW":return xe.previewing;case"OPEN_EDITOR":return xe.selected;default:return xe.selected}}function aa(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return xe.selected;case"COPY_FAILURE":return xe.previewing;default:return xe.previewing}}function io(e,t){switch(e.status){case"idle":return na(t);case"inspecting":return oa(t);case"selected":return ra(t);case"previewing":return aa(t)}}var ia="spotpatch:selection:";function Je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ie(e){return typeof e=="string"}function dt(e){return e===void 0||ie(e)}function fn(e){return Array.isArray(e)&&e.length<=256&&e.every(ie)}function rt(e){return typeof e=="number"&&Number.isFinite(e)}function so(e){return e===void 0||rt(e)}function co(e){let t=Je(e);return t!==void 0&&ie(t.origin)&&ie(t.confidence)&&dt(t.fileId)&&dt(t.relativePath)&&so(t.line)&&so(t.column)}function sa(e){let t=Je(e);return t!==void 0&&typeof t.supported=="boolean"&&dt(t.version)&&dt(t.componentName)&&fn(t.componentStack)&&(t.source===void 0||co(t.source))}function ca(e){let t=Je(e);return t!==void 0&&ie(t.url)&&ie(t.pathname)&&ie(t.title)&&rt(t.viewportWidth)&&rt(t.viewportHeight)&&rt(t.devicePixelRatio)}function la(e){let t=Je(e),o=Je(t?.rect);return t!==void 0&&ie(t.tagName)&&ie(t.selector)&&ie(t.sanitizedHtml)&&dt(t.textPreview)&&dt(t.role)&&o!==void 0&&rt(o.x)&&rt(o.y)&&rt(o.width)&&rt(o.height)}function da(e){let t=Je(e),o=Je(t?.computed);return t!==void 0&&fn(t.classNames)&&dt(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let i=Je(n);return i!==void 0&&ie(i.selector)&&ie(i.declarations)&&dt(i.source)&&dt(i.media)})&&o!==void 0&&Object.values(o).every(ie)&&fn(t.warnings)}function pa(e){let t=Je(e);return t!==void 0&&ie(t.relativePath)&&ie(t.language)&&rt(t.startLine)&&rt(t.endLine)&&ie(t.excerpt)&&ie(t.boundary)}function ua(e){let t=Je(e);return t!==void 0&&ie(t.id)&&ie(t.instruction)&&ca(t.page)&&co(t.source)&&sa(t.react)&&la(t.element)&&da(t.styles)&&(t.code===void 0||pa(t.code))}function ga(e,t){let o=Je(e);if(o?.version!==1||typeof o.open!="boolean"||!Number.isSafeInteger(o.sequence)||Number(o.sequence)<0||o.activeTargetId!==void 0&&typeof o.activeTargetId!="string"||!Array.isArray(o.targets)||o.targets.length===0||o.targets.length>t||!o.targets.every(ua))return;let n=o.targets,i=n.map(({id:c})=>c);if(!(new Set(i).size!==i.length||o.activeTargetId!==void 0&&!i.includes(o.activeTargetId)))return{...o.activeTargetId===void 0?{}:{activeTargetId:o.activeTargetId},open:o.open,sequence:Number(o.sequence),targets:n}}function lo(e,t,o){let n=`${ia}${t}`,i;try{i=e.sessionStorage}catch{i=void 0}return Object.freeze({clear(){try{i?.removeItem(n)}catch{}},load(){let c;try{c=i?.getItem(n)??null}catch{return}if(!(c===null||c.length>1e6))try{return ga(JSON.parse(c),o)}catch{return}},save(c){try{i?.setItem(n,JSON.stringify({version:1,...c}))}catch{}}})}var po=Object.freeze({supported:!1,componentStack:Object.freeze([])});function go(e){return cn(e.getAttribute(sn))}function fa(e){let t=e.parentElement;for(;t!==null;){let o=go(t);if(o!==void 0)return o;t=t.parentElement}}function uo(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function ma(){return Object.freeze({origin:"none",confidence:"unknown"})}function mn(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 fo(e){let t=!0;function o(n){if(!t)return po;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),po}}return Object.freeze({resolve(n){let i=go(n),c=o(n);if(i!==void 0)return Object.freeze({react:c,source:uo(i,"jsx-host","exact")});if(c.source!==void 0)return Object.freeze({react:c,source:c.source});let r=fa(n);return Object.freeze(r!==void 0?{react:c,source:uo(r,"dom-ancestor","approximate")}:{react:c,source:ma()})},dispose(){t=!1,e.adapter.dispose()}})}function d(e,t){let o=e.createElement(t);return o.setAttribute(xt,""),o}function Y(e,t,o=""){let n=d(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var mo=`
|
|
38
38
|
.spotpatch-agent {
|
|
39
39
|
margin-top: 10px;
|
|
40
40
|
overflow: hidden;
|
|
@@ -253,7 +253,7 @@ ${Gt(e.code.language,V(t.codeLines.join(`
|
|
|
253
253
|
.spotpatch-agent-selectors { grid-template-columns: 1fr; }
|
|
254
254
|
.spotpatch-agent-mode { grid-column: auto; }
|
|
255
255
|
}
|
|
256
|
-
`;function Nt(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function ho(e,t,o){let n=o.messages(),i=d(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let c=d(e,"div");c.className="spotpatch-agent-head";let r=d(e,"span");r.className="spotpatch-agent-title";let u=d(e,"span");u.className="spotpatch-agent-badge",c.append(r,u);let R=d(e,"div");R.className="spotpatch-agent-setup";let s=d(e,"div");s.className="spotpatch-agent-selectors";let A=d(e,"label");A.className="spotpatch-agent-mode";let z=d(e,"span"),m=d(e,"select");A.append(z,m);let L=d(e,"label"),M=d(e,"span"),P=d(e,"select");L.append(M,P);let b=d(e,"label"),T=d(e,"span"),$=d(e,"select");b.append(T,$),s.append(A,L,b);let oe=d(e,"label");oe.className="spotpatch-consent";let H=d(e,"input");H.type="checkbox";let h=d(e,"span");oe.append(H,h);let E=d(e,"label");E.className="spotpatch-consent spotpatch-workspace-consent",E.hidden=!0;let x=d(e,"input");x.type="checkbox";let I=d(e,"span"),G=d(e,"strong"),W=d(e,"small");I.append(G,W),E.append(x,I);let X=d(e,"div");X.className="spotpatch-agent-health-list";let Z=d(e,"p");Z.className="spotpatch-agent-workspace",Z.dataset.state="idle";let F=d(e,"p");F.className="spotpatch-agent-capability",F.dataset.state="idle",X.append(Z,F),R.append(s,oe,E,X);let xe=d(e,"div");xe.className="spotpatch-agent-job",xe.hidden=!0;let Pe=d(e,"div");Pe.className="spotpatch-agent-job-meta";let ue=d(e,"span");ue.className="spotpatch-agent-model";let _=d(e,"span");_.className="spotpatch-agent-status",Pe.append(ue,_);let Ue=d(e,"p");Ue.className="spotpatch-agent-phase";let Re=d(e,"p");Re.className="spotpatch-agent-error",Re.hidden=!0;let Ce=d(e,"ul");Ce.className="spotpatch-agent-activity";let he=d(e,"div");he.className="spotpatch-agent-result",he.hidden=!0;let pt=d(e,"p");pt.className="spotpatch-agent-summary";let re=d(e,"ul");re.className="spotpatch-agent-files";let be=d(e,"div");be.className="spotpatch-agent-checks";let q=d(e,"pre");q.className="spotpatch-agent-diff",q.tabIndex=0,q.setAttribute("aria-label",n.agent.diffAriaLabel),he.append(pt,re,be,q),xe.append(Pe,Ue,Re,Ce,he),i.append(c,R,xe);let Fe=Y(e,n.agent.testConnection),Ie=Y(e,n.agent.run,"spotpatch-run"),B=Y(e,n.agent.cancel),Q=Y(e,n.agent.apply,"spotpatch-primary"),Ne=Y(e,n.agent.revert),We=Y(e,n.agent.revise),at=t.enabled?t.providers:[],ze=t.enabled&&t.applyMode==="trusted-auto",ke=t.enabled?t.applyMode:"review",v=new Map(at.map(f=>[f.id,f])),Ke=!1,J=!0,ie=!1,ge=!1,O=!1,He=!1,ye,Te,je=[],De,se="idle",Ve=n.agent.connectionNotTested,$e,ce="idle",ut,fe;for(let f of at)Nt(e,P,f.id,f.label);t.enabled&&(P.value=t.defaultProvider);let it,st,Be;ke==="auto"?Be=Nt(e,m,"auto",n.agent.autoGated):(it=Nt(e,m,"review",n.agent.review),ze&&(st=Nt(e,m,"trusted-auto",n.agent.trustedFast)));let Ye=ze?"review":ke;m.value=Ye,A.hidden=!ze;let Xe=()=>m.value==="trusted-auto"?"trusted-auto":Ye,qe=()=>Xe()==="trusted-auto",ve=()=>v.get(P.value),Ze=f=>f===void 0?n.agent.providerUnavailable:qe()?n.agent.trustedFastConsent(f.label):n.agent.consent(f.label),Qe=()=>qe()?H.checked:x.checked,Se=()=>{let f=qe();oe.classList.toggle("spotpatch-trusted-consent",f),u.textContent=f?n.agent.trustedFast:ke==="auto"?n.agent.autoGated:n.agent.review,h.textContent=Ze(ve()),E.hidden=f||ce!=="consent-required"},et=()=>{let f=ve();if($.replaceChildren(),f===void 0){h.textContent=Ze(f);return}for(let w of f.models)Nt(e,$,w.id,w.label);$.value=f.defaultModel,h.textContent=Ze(f)},ee=()=>{let f=t.enabled&&ie&&!ge;Ie.textContent=O?n.agent.verifying:n.agent.run,Ie.classList.toggle("spotpatch-primary",He),Fe.hidden=!f,Ie.hidden=!f,Fe.disabled=!J||O||ve()===void 0,Ie.disabled=!J||O||!Ke||!H.checked||ce==="idle"||ce==="checking"||ce==="blocked"||ce==="consent-required"&&!Qe()||ve()===void 0||$.value.length===0,(!ge||!ie)&&(B.hidden=!0,Q.hidden=!0,Ne.hidden=!0,We.hidden=!0)},yt=()=>{if(ce==="idle")Z.textContent=n.agent.workspaceNotChecked;else if(ce==="checking")Z.textContent=n.agent.checkingWorkspace;else if(ce==="ready")Z.textContent=n.agent.workspaceReady;else if(ce==="consent-required"){let f=ut?.changes;Z.textContent=n.agent.workspaceDirty(f?.staged??0,f?.unstaged??0,f?.untracked??0)}else Z.textContent=fe===void 0?n.errors.INTERNAL_ERROR:n.errors[fe]};function a(){et(),H.checked=!1,F.dataset.state="idle",F.textContent=n.agent.connectionNotTested,se="idle",Ve=n.agent.connectionNotTested,$e=void 0,He=!1,ee()}function p(){F.dataset.state="idle",F.textContent=n.agent.connectionNotTested,se="idle",Ve=n.agent.connectionNotTested,$e=void 0,He=!1,ee()}function y(){H.checked=!1,x.checked=!1,Se(),ee()}et(),m.addEventListener("change",y),P.addEventListener("change",a),$.addEventListener("change",p),H.addEventListener("change",ee),x.addEventListener("change",ee);function N(){if(ye===void 0)return;let f=ye,w=Te;ue.textContent=`${f.providerLabel} · ${f.modelLabel}`,_.textContent=n.agent.status(f.status),Ue.textContent=f.phaseMessage;let le=De??f.errorCode;Re.hidden=le===void 0,Re.textContent=le===void 0?"":n.errors[le],Ce.replaceChildren();for(let ne of je.slice(-8)){let Ge=d(e,"li");Ge.dataset.state=ne.state,Ge.textContent=ne.label,Ce.append(Ge)}he.hidden=w===void 0,pt.textContent=w?.summary??"",re.replaceChildren(),be.replaceChildren(),q.textContent=w?.diff??"";for(let ne of w?.files??[]){let Ge=d(e,"li");Ge.textContent=`${ne.kind} ${ne.relativePath} (+${String(ne.additions)} / -${String(ne.deletions)})`,re.append(Ge)}for(let ne of w?.checks??[]){let Ge=d(e,"details"),Ct=d(e,"summary");Ct.textContent=`${ne.label}: ${ne.status} · ${String(ne.durationMs)} ms`;let Dt=d(e,"pre");Dt.textContent=ne.output.length===0?n.agent.noOutput:ne.output,Ge.append(Ct,Dt),be.append(Ge)}Fe.hidden=!0,Ie.hidden=!0,B.hidden=!ie||!f.canCancel,B.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,Q.hidden=!ie||!f.canApply,Ne.hidden=!ie||!f.canRevert,We.hidden=!ie||!["completed","cancelled","reverted","failed"].includes(f.status)}function D(){n=o.messages(),r.textContent=n.agent.title,z.textContent=n.agent.mode,it!==void 0&&(it.textContent=n.agent.review),st!==void 0&&(st.textContent=n.agent.trustedFast),Be!==void 0&&(Be.textContent=n.agent.autoGated),M.textContent=n.agent.provider,T.textContent=n.agent.model,P.setAttribute("aria-label",n.agent.providerAriaLabel),$.setAttribute("aria-label",n.agent.modelAriaLabel),G.textContent=n.agent.includeLocalChanges,W.textContent=n.agent.includeLocalChangesHelp,q.setAttribute("aria-label",n.agent.diffAriaLabel),Fe.textContent=n.agent.testConnection,Q.textContent=n.agent.apply,Ne.textContent=n.agent.revert,We.textContent=n.agent.revise,Se(),se==="idle"?F.textContent=n.agent.connectionNotTested:se==="probing"?F.textContent=n.agent.testingCapability:se==="ready"?F.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:$e!==void 0?F.textContent=n.errors[$e]:ve()===void 0?F.textContent=n.agent.providerUnavailable:F.textContent=Ve,yt(),ee(),N()}let te=o.subscribe(D);return D(),Object.freeze({root:i,modeSelect:m,providerSelect:P,modelSelect:$,consentCheckbox:H,workspaceConsentCheckbox:x,testButton:Fe,runButton:Ie,cancelButton:B,applyButton:Q,revertButton:Ne,resetButton:We,consentGranted(){return H.checked},workspaceConsentGranted(){return Qe()},readSelection(){let f=ve(),w=f?.models.find(le=>le.id===$.value);return f===void 0||w===void 0?void 0:Object.freeze({applyMode:Xe(),providerProfileId:f.id,modelProfileId:w.id})},renderCapability(f,w,le,ne){se=f,Ve=w,$e=ne,O=f==="probing",He=f==="ready"&&le?.state==="agent-ready",F.dataset.state=f,F.textContent=le?.state==="agent-ready"?`${w} · ${n.agent.toolsReady}`:w,ee()},renderWorkspaceHealth(f,w,le){ce=f,ut=w,fe=le??w?.errorCode,Z.dataset.state=f,f!=="checking"&&(E.hidden=qe()||f!=="consent-required"),(f==="idle"||f==="ready"||f==="blocked")&&(x.checked=!1),yt(),ee()},renderJob(f,w,le,ne){ge=!0,R.hidden=!0,xe.hidden=!1,P.disabled=!0,$.disabled=!0,m.disabled=!0,H.disabled=!0,x.disabled=!0,ye=f,Te=w,je=le,De=ne,N()},resetJob(){ge=!1,ye=void 0,Te=void 0,je=[],De=void 0,R.hidden=!1,xe.hidden=!0,P.disabled=!1,$.disabled=!1,m.disabled=!1,H.disabled=!1,x.disabled=!1,Ce.replaceChildren(),re.replaceChildren(),be.replaceChildren(),q.textContent="",Re.textContent="",Re.hidden=!0,ee()},setContextReady(f){Ke=f,ee()},setEditingEnabled(f){J=f,P.disabled=!f||ge,$.disabled=!f||ge,m.disabled=!f||ge,H.disabled=!f||ge,x.disabled=!f||ge,ee()},setProviderConsent(f){H.checked=f,ee()},setSelectionVisible(f){ie=f,ee(),f||(B.hidden=!0,Q.hidden=!0,Ne.hidden=!0,We.hidden=!0)},dispose(){te(),P.removeEventListener("change",a),$.removeEventListener("change",p),m.removeEventListener("change",y),H.removeEventListener("change",ee),x.removeEventListener("change",ee)}})}var bo="http://www.w3.org/2000/svg",ha="";function ba(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:ha,viewBox:"0 0 1 1"}}function ya(e,t,o){let n=e.createElementNS(bo,t);for(let[i,c]of Object.entries(o))n.setAttribute(i,c);return n}function yo(e,t){let o=ba(t),n=ya(e,"svg",{xmlns:bo,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}var Sa=Symbol.for("spotpatch.data-flow.extension.v1");function kt(e=globalThis){return e[Sa]}function bt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function So({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let c=i-t-16,r=n-e-16,u=bt((i-t)/2,16,c),R=bt((n-e)/2,16,r);if(o===void 0)return Object.freeze({anchorX:bt(t/2,22,t-22),anchorY:bt(e/2,22,e-22),left:u,mode:"viewport",top:R});let s=o.x+o.width/2,A=o.y+o.height/2,z=bt(s-t/2,16,c),m=bt(A-e/2,16,r),L=z,M=m,P="viewport";return o.width>=t+48&&o.height>=e+48?P="center":o.y-e-14>=16?(M=o.y-e-14,P="above"):o.y+o.height+14+e<=n-16?(M=o.y+o.height+14,P="below"):o.x+o.width+14+t<=i-16?(L=o.x+o.width+14,P="right"):o.x-t-14>=16&&(L=o.x-t-14,P="left"),Object.freeze({anchorX:bt(s-L,22,t-22),anchorY:bt(A-M,22,e-22),left:L,mode:P,top:M})}var Ea=Symbol.for("spotpatch.external-handoff.v1");function Wt(){return globalThis[Ea]}var Aa=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"}),xa=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),de="The external Agent handoff request failed.",pe="外部 Agent 交接请求失败。",Ra=Object.freeze({[l.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[l.INVALID_TOKEN]:"The local SpotPatch session expired.",[l.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[l.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[l.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[l.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[l.EDITOR_OPEN_FAILED]:"The editor request failed.",[l.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[l.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[l.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[l.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[l.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[l.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[l.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[l.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[l.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[l.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[l.AGENT_BUSY]:"Another write Agent job is still active.",[l.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[l.AGENT_CANCELLED]:"The Agent job was cancelled.",[l.EXTERNAL_HANDOFF_DISABLED]:de,[l.EXTERNAL_HANDOFF_UNAVAILABLE]:de,[l.HANDOFF_VALIDATION_FAILED]:de,[l.HANDOFF_SOURCE_STALE]:de,[l.HANDOFF_NOT_FOUND]:de,[l.HANDOFF_EXPIRED]:de,[l.HANDOFF_CURSOR_INVALID]:de,[l.HANDOFF_RESPONSE_TOO_LARGE]:de,[l.BRIDGE_UNAUTHORIZED]:de,[l.BRIDGE_PROTOCOL_MISMATCH]:de,[l.BRIDGE_BUSY]:de,[l.EXTERNAL_AGENT_BUSY]:de,[l.ACTIVE_ADAPTER_CONFLICT]:de,[l.ACTIVE_ADAPTER_LEASE_INVALID]:de,[l.ACTIVE_DISPATCH_INVALID]:de,[l.SESSION_NOT_FOUND]:de,[l.SESSION_AMBIGUOUS]:de,[l.SESSION_CLOSED]:de,[l.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[l.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[l.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[l.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[l.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[l.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[l.TOOL_DENIED]:"A tool request violated local safety policy.",[l.TOOL_INPUT_INVALID]:"Invalid tool request.",[l.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[l.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[l.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[l.PATCH_REJECTED]:"The patch violated local policy.",[l.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[l.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[l.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Ca=Object.freeze({[l.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[l.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[l.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[l.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[l.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[l.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[l.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[l.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[l.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[l.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[l.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[l.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[l.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[l.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[l.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[l.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[l.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[l.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[l.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[l.AGENT_CANCELLED]:"Agent 任务已取消。",[l.EXTERNAL_HANDOFF_DISABLED]:pe,[l.EXTERNAL_HANDOFF_UNAVAILABLE]:pe,[l.HANDOFF_VALIDATION_FAILED]:pe,[l.HANDOFF_SOURCE_STALE]:pe,[l.HANDOFF_NOT_FOUND]:pe,[l.HANDOFF_EXPIRED]:pe,[l.HANDOFF_CURSOR_INVALID]:pe,[l.HANDOFF_RESPONSE_TOO_LARGE]:pe,[l.BRIDGE_UNAUTHORIZED]:pe,[l.BRIDGE_PROTOCOL_MISMATCH]:pe,[l.BRIDGE_BUSY]:pe,[l.EXTERNAL_AGENT_BUSY]:pe,[l.ACTIVE_ADAPTER_CONFLICT]:pe,[l.ACTIVE_ADAPTER_LEASE_INVALID]:pe,[l.ACTIVE_DISPATCH_INVALID]:pe,[l.SESSION_NOT_FOUND]:pe,[l.SESSION_AMBIGUOUS]:pe,[l.SESSION_CLOSED]:pe,[l.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[l.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[l.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[l.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[l.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[l.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[l.TOOL_DENIED]:"工具请求违反本地安全策略。",[l.TOOL_INPUT_INVALID]:"工具请求无效。",[l.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[l.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[l.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[l.PATCH_REJECTED]:"补丁违反本地策略。",[l.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[l.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[l.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Ta=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"}),va=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:"警告"}),wa=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Ta,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=>Aa[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Ra}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:va,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=>xa[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Ca})});function Eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function Oa(e,t){if(e!=="auto")return e;let o=Eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(Eo).find(i=>i!==void 0)??"en-US"}function Ao(e,t="auto"){let o=Oa(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>wa[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var xo=460,Ro=620,_a=Object.freeze({previewing:560,selected:Ro});function La(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 Pa(e){let t=e.createElement("style");return t.textContent=`
|
|
256
|
+
`;function Pt(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function ho(e,t,o){let n=o.messages(),i=d(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let c=d(e,"div");c.className="spotpatch-agent-head";let r=d(e,"span");r.className="spotpatch-agent-title";let u=d(e,"span");u.className="spotpatch-agent-badge",c.append(r,u);let R=d(e,"div");R.className="spotpatch-agent-setup";let s=d(e,"div");s.className="spotpatch-agent-selectors";let A=d(e,"label");A.className="spotpatch-agent-mode";let z=d(e,"span"),m=d(e,"select");A.append(z,m);let L=d(e,"label"),M=d(e,"span"),N=d(e,"select");L.append(M,N);let b=d(e,"label"),T=d(e,"span"),$=d(e,"select");b.append(T,$),s.append(A,L,b);let re=d(e,"label");re.className="spotpatch-consent";let H=d(e,"input");H.type="checkbox";let h=d(e,"span");re.append(H,h);let S=d(e,"label");S.className="spotpatch-consent spotpatch-workspace-consent",S.hidden=!0;let x=d(e,"input");x.type="checkbox";let I=d(e,"span"),G=d(e,"strong"),W=d(e,"small");I.append(G,W),S.append(x,I);let Z=d(e,"div");Z.className="spotpatch-agent-health-list";let Q=d(e,"p");Q.className="spotpatch-agent-workspace",Q.dataset.state="idle";let F=d(e,"p");F.className="spotpatch-agent-capability",F.dataset.state="idle",Z.append(Q,F),R.append(s,re,S,Z);let Re=d(e,"div");Re.className="spotpatch-agent-job",Re.hidden=!0;let Ne=d(e,"div");Ne.className="spotpatch-agent-job-meta";let ge=d(e,"span");ge.className="spotpatch-agent-model";let _=d(e,"span");_.className="spotpatch-agent-status",Ne.append(ge,_);let Ue=d(e,"p");Ue.className="spotpatch-agent-phase";let Ce=d(e,"p");Ce.className="spotpatch-agent-error",Ce.hidden=!0;let Te=d(e,"ul");Te.className="spotpatch-agent-activity";let be=d(e,"div");be.className="spotpatch-agent-result",be.hidden=!0;let pt=d(e,"p");pt.className="spotpatch-agent-summary";let ae=d(e,"ul");ae.className="spotpatch-agent-files";let ye=d(e,"div");ye.className="spotpatch-agent-checks";let q=d(e,"pre");q.className="spotpatch-agent-diff",q.tabIndex=0,q.setAttribute("aria-label",n.agent.diffAriaLabel),be.append(pt,ae,ye,q),Re.append(Ne,Ue,Ce,Te,be),i.append(c,R,Re);let Fe=Y(e,n.agent.testConnection),Ie=Y(e,n.agent.run,"spotpatch-run"),B=Y(e,n.agent.cancel),ee=Y(e,n.agent.apply,"spotpatch-primary"),Pe=Y(e,n.agent.revert),We=Y(e,n.agent.revise),at=t.enabled?t.providers:[],ze=t.enabled&&t.applyMode==="trusted-auto",De=t.enabled?t.applyMode:"review",v=new Map(at.map(f=>[f.id,f])),Ke=!1,J=!0,se=!1,fe=!1,O=!1,He=!1,Ee,ve,je=[],ke,ce="idle",Ve=n.agent.connectionNotTested,$e,le="idle",ut,me;for(let f of at)Pt(e,N,f.id,f.label);t.enabled&&(N.value=t.defaultProvider);let it,st,Be;De==="auto"?Be=Pt(e,m,"auto",n.agent.autoGated):(it=Pt(e,m,"review",n.agent.review),ze&&(st=Pt(e,m,"trusted-auto",n.agent.trustedFast)));let Xe=ze?"review":De;m.value=Xe,A.hidden=!ze;let Ye=()=>m.value==="trusted-auto"?"trusted-auto":Xe,qe=()=>Ye()==="trusted-auto",we=()=>v.get(N.value),Ze=f=>f===void 0?n.agent.providerUnavailable:qe()?n.agent.trustedFastConsent(f.label):n.agent.consent(f.label),Qe=()=>qe()?H.checked:x.checked,Se=()=>{let f=qe();re.classList.toggle("spotpatch-trusted-consent",f),u.textContent=f?n.agent.trustedFast:De==="auto"?n.agent.autoGated:n.agent.review,h.textContent=Ze(we()),S.hidden=f||le!=="consent-required"},et=()=>{let f=we();if($.replaceChildren(),f===void 0){h.textContent=Ze(f);return}for(let w of f.models)Pt(e,$,w.id,w.label);$.value=f.defaultModel,h.textContent=Ze(f)},te=()=>{let f=t.enabled&&se&&!fe;Ie.textContent=O?n.agent.verifying:n.agent.run,Ie.classList.toggle("spotpatch-primary",He),Fe.hidden=!f,Ie.hidden=!f,Fe.disabled=!J||O||we()===void 0,Ie.disabled=!J||O||!Ke||!H.checked||le==="idle"||le==="checking"||le==="blocked"||le==="consent-required"&&!Qe()||we()===void 0||$.value.length===0,(!fe||!se)&&(B.hidden=!0,ee.hidden=!0,Pe.hidden=!0,We.hidden=!0)},yt=()=>{if(le==="idle")Q.textContent=n.agent.workspaceNotChecked;else if(le==="checking")Q.textContent=n.agent.checkingWorkspace;else if(le==="ready")Q.textContent=n.agent.workspaceReady;else if(le==="consent-required"){let f=ut?.changes;Q.textContent=n.agent.workspaceDirty(f?.staged??0,f?.unstaged??0,f?.untracked??0)}else Q.textContent=me===void 0?n.errors.INTERNAL_ERROR:n.errors[me]};function a(){et(),H.checked=!1,F.dataset.state="idle",F.textContent=n.agent.connectionNotTested,ce="idle",Ve=n.agent.connectionNotTested,$e=void 0,He=!1,te()}function p(){F.dataset.state="idle",F.textContent=n.agent.connectionNotTested,ce="idle",Ve=n.agent.connectionNotTested,$e=void 0,He=!1,te()}function y(){H.checked=!1,x.checked=!1,Se(),te()}et(),m.addEventListener("change",y),N.addEventListener("change",a),$.addEventListener("change",p),H.addEventListener("change",te),x.addEventListener("change",te);function P(){if(Ee===void 0)return;let f=Ee,w=ve;ge.textContent=`${f.providerLabel} · ${f.modelLabel}`,_.textContent=n.agent.status(f.status),Ue.textContent=f.phaseMessage;let de=ke??f.errorCode;Ce.hidden=de===void 0,Ce.textContent=de===void 0?"":n.errors[de],Te.replaceChildren();for(let oe of je.slice(-8)){let Ge=d(e,"li");Ge.dataset.state=oe.state,Ge.textContent=oe.label,Te.append(Ge)}be.hidden=w===void 0,pt.textContent=w?.summary??"",ae.replaceChildren(),ye.replaceChildren(),q.textContent=w?.diff??"";for(let oe of w?.files??[]){let Ge=d(e,"li");Ge.textContent=`${oe.kind} ${oe.relativePath} (+${String(oe.additions)} / -${String(oe.deletions)})`,ae.append(Ge)}for(let oe of w?.checks??[]){let Ge=d(e,"details"),Ct=d(e,"summary");Ct.textContent=`${oe.label}: ${oe.status} · ${String(oe.durationMs)} ms`;let kt=d(e,"pre");kt.textContent=oe.output.length===0?n.agent.noOutput:oe.output,Ge.append(Ct,kt),ye.append(Ge)}Fe.hidden=!0,Ie.hidden=!0,B.hidden=!se||!f.canCancel,B.textContent=f.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ee.hidden=!se||!f.canApply,Pe.hidden=!se||!f.canRevert,We.hidden=!se||!["completed","cancelled","reverted","failed"].includes(f.status)}function k(){n=o.messages(),r.textContent=n.agent.title,z.textContent=n.agent.mode,it!==void 0&&(it.textContent=n.agent.review),st!==void 0&&(st.textContent=n.agent.trustedFast),Be!==void 0&&(Be.textContent=n.agent.autoGated),M.textContent=n.agent.provider,T.textContent=n.agent.model,N.setAttribute("aria-label",n.agent.providerAriaLabel),$.setAttribute("aria-label",n.agent.modelAriaLabel),G.textContent=n.agent.includeLocalChanges,W.textContent=n.agent.includeLocalChangesHelp,q.setAttribute("aria-label",n.agent.diffAriaLabel),Fe.textContent=n.agent.testConnection,ee.textContent=n.agent.apply,Pe.textContent=n.agent.revert,We.textContent=n.agent.revise,Se(),ce==="idle"?F.textContent=n.agent.connectionNotTested:ce==="probing"?F.textContent=n.agent.testingCapability:ce==="ready"?F.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:$e!==void 0?F.textContent=n.errors[$e]:we()===void 0?F.textContent=n.agent.providerUnavailable:F.textContent=Ve,yt(),te(),P()}let ne=o.subscribe(k);return k(),Object.freeze({root:i,modeSelect:m,providerSelect:N,modelSelect:$,consentCheckbox:H,workspaceConsentCheckbox:x,testButton:Fe,runButton:Ie,cancelButton:B,applyButton:ee,revertButton:Pe,resetButton:We,consentGranted(){return H.checked},workspaceConsentGranted(){return Qe()},readSelection(){let f=we(),w=f?.models.find(de=>de.id===$.value);return f===void 0||w===void 0?void 0:Object.freeze({applyMode:Ye(),providerProfileId:f.id,modelProfileId:w.id})},renderCapability(f,w,de,oe){ce=f,Ve=w,$e=oe,O=f==="probing",He=f==="ready"&&de?.state==="agent-ready",F.dataset.state=f,F.textContent=de?.state==="agent-ready"?`${w} · ${n.agent.toolsReady}`:w,te()},renderWorkspaceHealth(f,w,de){le=f,ut=w,me=de??w?.errorCode,Q.dataset.state=f,f!=="checking"&&(S.hidden=qe()||f!=="consent-required"),(f==="idle"||f==="ready"||f==="blocked")&&(x.checked=!1),yt(),te()},renderJob(f,w,de,oe){fe=!0,R.hidden=!0,Re.hidden=!1,N.disabled=!0,$.disabled=!0,m.disabled=!0,H.disabled=!0,x.disabled=!0,Ee=f,ve=w,je=de,ke=oe,P()},resetJob(){fe=!1,Ee=void 0,ve=void 0,je=[],ke=void 0,R.hidden=!1,Re.hidden=!0,N.disabled=!1,$.disabled=!1,m.disabled=!1,H.disabled=!1,x.disabled=!1,Te.replaceChildren(),ae.replaceChildren(),ye.replaceChildren(),q.textContent="",Ce.textContent="",Ce.hidden=!0,te()},setContextReady(f){Ke=f,te()},setEditingEnabled(f){J=f,N.disabled=!f||fe,$.disabled=!f||fe,m.disabled=!f||fe,H.disabled=!f||fe,x.disabled=!f||fe,te()},setProviderConsent(f){H.checked=f,te()},setSelectionVisible(f){se=f,te(),f||(B.hidden=!0,ee.hidden=!0,Pe.hidden=!0,We.hidden=!0)},dispose(){ne(),N.removeEventListener("change",a),$.removeEventListener("change",p),m.removeEventListener("change",y),H.removeEventListener("change",te),x.removeEventListener("change",te)}})}var bo="http://www.w3.org/2000/svg",ha="";function ba(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:ha,viewBox:"0 0 1 1"}}function ya(e,t,o){let n=e.createElementNS(bo,t);for(let[i,c]of Object.entries(o))n.setAttribute(i,c);return n}function yo(e,t){let o=ba(t),n=ya(e,"svg",{xmlns:bo,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}var Ea=Symbol.for("spotpatch.data-flow.extension.v1");function Dt(e=globalThis){return e[Ea]}function bt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Eo({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let c=i-t-16,r=n-e-16,u=bt((i-t)/2,16,c),R=bt((n-e)/2,16,r);if(o===void 0)return Object.freeze({anchorX:bt(t/2,22,t-22),anchorY:bt(e/2,22,e-22),left:u,mode:"viewport",top:R});let s=o.x+o.width/2,A=o.y+o.height/2,z=bt(s-t/2,16,c),m=bt(A-e/2,16,r),L=z,M=m,N="viewport";return o.width>=t+48&&o.height>=e+48?N="center":o.y-e-14>=16?(M=o.y-e-14,N="above"):o.y+o.height+14+e<=n-16?(M=o.y+o.height+14,N="below"):o.x+o.width+14+t<=i-16?(L=o.x+o.width+14,N="right"):o.x-t-14>=16&&(L=o.x-t-14,N="left"),Object.freeze({anchorX:bt(s-L,22,t-22),anchorY:bt(A-M,22,e-22),left:L,mode:N,top:M})}var Sa=Symbol.for("spotpatch.external-handoff.v1");function Wt(){return globalThis[Sa]}var Aa=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"}),xa=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),pe="The external Agent handoff request failed.",ue="外部 Agent 交接请求失败。",Ra=Object.freeze({[l.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[l.INVALID_TOKEN]:"The local SpotPatch session expired.",[l.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[l.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[l.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[l.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[l.EDITOR_OPEN_FAILED]:"The editor request failed.",[l.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[l.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[l.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[l.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[l.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[l.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[l.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[l.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[l.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[l.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[l.AGENT_BUSY]:"Another write Agent job is still active.",[l.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[l.AGENT_CANCELLED]:"The Agent job was cancelled.",[l.EXTERNAL_HANDOFF_DISABLED]:pe,[l.EXTERNAL_HANDOFF_UNAVAILABLE]:pe,[l.HANDOFF_VALIDATION_FAILED]:pe,[l.HANDOFF_SOURCE_STALE]:pe,[l.HANDOFF_NOT_FOUND]:pe,[l.HANDOFF_EXPIRED]:pe,[l.HANDOFF_CURSOR_INVALID]:pe,[l.HANDOFF_RESPONSE_TOO_LARGE]:pe,[l.BRIDGE_UNAUTHORIZED]:pe,[l.BRIDGE_PROTOCOL_MISMATCH]:pe,[l.BRIDGE_BUSY]:pe,[l.EXTERNAL_AGENT_BUSY]:pe,[l.ACTIVE_ADAPTER_CONFLICT]:pe,[l.ACTIVE_ADAPTER_LEASE_INVALID]:pe,[l.ACTIVE_DISPATCH_INVALID]:pe,[l.SESSION_NOT_FOUND]:pe,[l.SESSION_AMBIGUOUS]:pe,[l.SESSION_CLOSED]:pe,[l.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[l.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[l.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[l.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[l.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[l.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[l.TOOL_DENIED]:"A tool request violated local safety policy.",[l.TOOL_INPUT_INVALID]:"Invalid tool request.",[l.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[l.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[l.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[l.PATCH_REJECTED]:"The patch violated local policy.",[l.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[l.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[l.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Ca=Object.freeze({[l.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[l.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[l.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[l.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[l.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[l.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[l.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[l.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[l.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[l.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[l.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[l.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[l.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[l.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[l.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[l.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[l.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[l.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[l.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[l.AGENT_CANCELLED]:"Agent 任务已取消。",[l.EXTERNAL_HANDOFF_DISABLED]:ue,[l.EXTERNAL_HANDOFF_UNAVAILABLE]:ue,[l.HANDOFF_VALIDATION_FAILED]:ue,[l.HANDOFF_SOURCE_STALE]:ue,[l.HANDOFF_NOT_FOUND]:ue,[l.HANDOFF_EXPIRED]:ue,[l.HANDOFF_CURSOR_INVALID]:ue,[l.HANDOFF_RESPONSE_TOO_LARGE]:ue,[l.BRIDGE_UNAUTHORIZED]:ue,[l.BRIDGE_PROTOCOL_MISMATCH]:ue,[l.BRIDGE_BUSY]:ue,[l.EXTERNAL_AGENT_BUSY]:ue,[l.ACTIVE_ADAPTER_CONFLICT]:ue,[l.ACTIVE_ADAPTER_LEASE_INVALID]:ue,[l.ACTIVE_DISPATCH_INVALID]:ue,[l.SESSION_NOT_FOUND]:ue,[l.SESSION_AMBIGUOUS]:ue,[l.SESSION_CLOSED]:ue,[l.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[l.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[l.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[l.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[l.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[l.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[l.TOOL_DENIED]:"工具请求违反本地安全策略。",[l.TOOL_INPUT_INVALID]:"工具请求无效。",[l.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[l.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[l.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[l.PATCH_REJECTED]:"补丁违反本地策略。",[l.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[l.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[l.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Ta=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"}),va=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:"警告"}),wa=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Ta,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=>Aa[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Ra}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:va,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=>xa[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Ca})});function So(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function Oa(e,t){if(e!=="auto")return e;let o=So(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(So).find(i=>i!==void 0)??"en-US"}function Ao(e,t="auto"){let o=Oa(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>wa[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var xo=460,Ro=620,_a=Object.freeze({previewing:560,selected:Ro});function La(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 Na(e){let t=e.createElement("style");return t.textContent=`
|
|
257
257
|
:host {
|
|
258
258
|
all: initial;
|
|
259
259
|
--spotpatch-bg: #0e0e12;
|
|
@@ -955,8 +955,8 @@ ${Gt(e.code.language,V(t.codeLines.join(`
|
|
|
955
955
|
}
|
|
956
956
|
${mo}
|
|
957
957
|
`,t}function Ia(e,t){return e.split(`
|
|
958
|
-
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Na(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:Y(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function Co(e,t,o=Object.freeze({enabled:!1}),n="auto",i=!1,c=!1,r="vite",u=""){let R=Ao(e,n),s=R.messages(),A=e.createElement("spotpatch-root");A.setAttribute(xt,"");let z=A.attachShadow({mode:"open"}),m=Y(e,s.trigger.select,"spotpatch-trigger");m.title=s.trigger.title(t),m.setAttribute("aria-pressed","false");let L=d(e,"div");L.className="spotpatch-highlight",L.hidden=!0;let M=d(e,"span");M.className="spotpatch-highlight-label",L.append(M);let P=d(e,"div");P.className="spotpatch-selection-highlights",P.setAttribute("aria-hidden","true");let b=d(e,"section");b.className="spotpatch-dialog",b.hidden=!0,b.tabIndex=-1,b.dataset.placement="viewport",b.setAttribute("role","dialog"),b.setAttribute("aria-labelledby","spotpatch-selection-title");let T=d(e,"span");T.className="spotpatch-anchor",T.setAttribute("aria-hidden","true");let $=d(e,"div");$.className="spotpatch-shell";let oe=d(e,"header");oe.className="spotpatch-header";let H=d(e,"div");H.className="spotpatch-brand-row";let h=d(e,"div");h.className="spotpatch-brand";let E=d(e,"span");E.className="spotpatch-brand-copy";let x=d(e,"span");x.className="spotpatch-brand-name";let I=d(e,"span");I.className="spotpatch-brand-context",E.append(x,I),h.append(yo(e),E);let G=d(e,"span");G.className="spotpatch-header-controls";let W=d(e,"a");W.className="spotpatch-repository",W.href=ln,W.target="_blank",W.rel="noopener noreferrer";let X=Y(e,"","spotpatch-locale"),Z=Y(e,"×","spotpatch-close");G.append(W,X,Z),H.append(h,G);let F=d(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let xe=d(e,"p");xe.className="spotpatch-subtitle";let Pe=d(e,"div");Pe.className="spotpatch-target-row";let ue=d(e,"span");ue.className="spotpatch-target-label";let _=d(e,"span");_.className="spotpatch-context-state",_.dataset.state="loading",_.textContent=s.context.collecting,Pe.append(ue,_),oe.append(H,F,xe,Pe);let Ue=d(e,"div");Ue.className="spotpatch-body";let Re=d(e,"div");Re.className="spotpatch-selection-panel";let Ce=d(e,"section");Ce.className="spotpatch-targets";let he=d(e,"div");he.className="spotpatch-targets-heading";let pt=d(e,"span"),re=d(e,"span");re.className="spotpatch-targets-meta";let be=d(e,"span");be.className="spotpatch-target-complete";let q=d(e,"span");q.className="spotpatch-target-budget",q.setAttribute("aria-live","polite");let Fe=d(e,"span");Fe.className="spotpatch-target-count",re.append(be,q),Pe.append(Fe),he.append(pt,re);let Ie=d(e,"div");Ie.className="spotpatch-target-progress",Ie.setAttribute("aria-hidden","true");let B=d(e,"div");B.className="spotpatch-target-progress-fill",Ie.append(B);let Q=d(e,"div");Q.className="spotpatch-target-list",Ce.append(he,Ie,Q);let Ne=d(e,"details");Ne.className="spotpatch-diagnostics";let We=d(e,"summary"),at=d(e,"span"),ze=d(e,"span");ze.className="spotpatch-source-peek",ze.textContent=s.diagnostics.resolving,We.append(at,ze);let ke=d(e,"pre");ke.className="spotpatch-summary",Ne.append(We,ke);let v=ho(e,o,R),Ke=d(e,"div"),J=c?Wt()?.createPanel(e,r,R.locale,u,R.subscribe,w):void 0;Ke.append(Ce,v.root,...J===void 0?[]:[J.root]);let ie=kt()?.createPanel(e,i,R.locale,Ke,Ne,w)??Na(e,Ke,Ne);Re.append(ie.root);let ge=d(e,"div");ge.className="spotpatch-preview-panel",ge.hidden=!0;let O=d(e,"pre");O.className="spotpatch-prompt",O.tabIndex=0,O.setAttribute("aria-label",s.diagnostics.promptAriaLabel),ge.append(O),Ue.append(Re,ge);let He=d(e,"footer");He.className="spotpatch-actions";let ye=d(e,"div");ye.className="spotpatch-context-state spotpatch-editor-feedback",ye.dataset.state="idle",ye.setAttribute("role","status"),ye.setAttribute("aria-live","polite"),ye.hidden=!0;let Te=Y(e,s.actions.addElement),je=Y(e,s.actions.reselect),De=Y(e,s.actions.openEditor),se=Y(e,s.actions.preview,"spotpatch-primary"),Ve=Y(e,s.actions.copy,"spotpatch-primary"),$e=Y(e,s.actions.back),ce=d(e,"div");ce.className="spotpatch-secondary-actions";let ut=d(e,"div");ut.className="spotpatch-primary-actions",Te.classList.add("spotpatch-icon-action"),Te.dataset.compactIcon="+",v.testButton.classList.add("spotpatch-icon-action"),v.testButton.dataset.compactIcon="✓",De.classList.add("spotpatch-secondary-action"),je.classList.add("spotpatch-secondary-action"),ce.append(De,je),ut.append(v.testButton,Te,v.runButton,...J===void 0?[]:[J.sendButton],se,v.cancelButton,v.applyButton,v.revertButton,v.resetButton,Ve,$e),He.append(ye,ce,ut),$.append(oe,Ue,He),b.append(T,$);let fe=d(e,"div");fe.className="spotpatch-live",fe.setAttribute("aria-live","polite"),fe.setAttribute("aria-atomic","true");let it=[Pa(e),ie.styles,...J===void 0?[]:[J.styles]],st=La(e);if(st!==void 0)for(let g of it)g.nonce=st;z.append(...it,P,L,b,m,fe),e.documentElement.append(A);let Be,Ye,Xe="idle",qe=!1,ve=!1,Ze="",Qe=!0,Se=[],et=0,ee="idle",yt=Object.freeze({component:Object.freeze({status:i?"idle":"disabled"}),page:Object.freeze({status:i?"idle":"disabled"}),observationCount:0});function a(g){ee=g,ye.dataset.state=g,ye.hidden=g==="idle",ye.textContent=g==="opening"?s.announcements.editorOpening:g==="success"?s.announcements.editorOpened:g==="error"?s.announcements.editorFailed:"",w()}function p(g){return g.status==="ready"?s.targets.statusReady:g.status==="warning"?s.targets.statusPartial:s.targets.statusCollecting}function y(g,S){let C=S===0?0:g/S;B.style.width=`${String(C*100)}%`}function N(g){let S=Q.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(S).find(C=>g===void 0||C.dataset.targetInstructionId===g)}function D(g,S){let C=z.activeElement?.closest("textarea[data-target-instruction-id]"),U=C?.dataset.targetInstructionId,we=C?.selectionStart,tt=C?.selectionEnd;Se=g.map(j=>Object.freeze({...j})),et=S,Q.replaceChildren();let ct=g.filter(j=>j.instruction.trim().length>0).length,Ee=g.reduce((j,K)=>j+K.instruction.trim().length,0);y(ct,g.length),Fe.textContent=s.targets.count(g.length,S),be.textContent=s.targets.complete(ct,g.length);let Tt=Ee>4e3;q.dataset.state=Tt?"over":"ready",q.textContent=Tt?s.targets.instructionBudgetExceeded(Ee,4e3):s.targets.instructionBudget(Ee,4e3),Te.disabled=!Qe||g.length>=S,Te.title=g.length>=S?s.targets.limitTitle(S):s.targets.addTitle,ue.textContent=g.length===1?g[0]?.label??s.context.selectedElement:s.context.selectedCount(g.length);for(let[j,K]of g.entries()){let St=d(e,"div");St.className="spotpatch-target-item",St.dataset.active=String(K.active),St.dataset.status=K.status,St.dataset.targetId=K.id;let qt=d(e,"div");qt.className="spotpatch-target-summary";let vt=Y(e,"","spotpatch-target-select");vt.dataset.activateTargetId=K.id,vt.setAttribute("aria-label",s.targets.activate(j+1)),vt.setAttribute("aria-expanded",String(K.active));let Jt=d(e,"span");Jt.className="spotpatch-target-index",Jt.textContent=String(j+1);let Kt=d(e,"span");Kt.className="spotpatch-target-copy";let Yt=d(e,"span");Yt.className="spotpatch-target-name",Yt.textContent=K.label;let Xt=d(e,"span");Xt.className="spotpatch-target-source",Xt.textContent=`${p(K)} · ${K.source}`,Kt.append(Yt,Xt);let Sn=K.instruction.trim().length>0,Mt=d(e,"span");Mt.className="spotpatch-target-state",Mt.dataset.complete=String(Sn),Mt.textContent=Sn?s.targets.instructionReady:s.targets.instructionMissing,vt.append(Jt,Kt,Mt);let wt=Y(e,"↗","spotpatch-target-open");wt.dataset.openTargetId=K.id,wt.disabled=!K.canOpenEditor,wt.setAttribute("aria-label",s.actions.openTarget(j+1)),wt.title=s.actions.openTarget(j+1);let Ot=Y(e,"×","spotpatch-target-remove");if(Ot.dataset.removeTargetId=K.id,Ot.disabled=!Qe,Ot.setAttribute("aria-label",s.targets.remove(j+1)),Ot.title=s.targets.removeTitle,qt.append(vt,wt,Ot),St.append(qt),K.active){let Zt=d(e,"label");Zt.className="spotpatch-target-editor";let Qt=d(e,"span");Qt.className="spotpatch-target-editor-head";let en=d(e,"span");en.className="spotpatch-target-editor-label",en.textContent=s.targets.instructionLabel(K.label);let tn=d(e,"span");tn.className="spotpatch-target-editor-count",tn.textContent=s.targets.instructionCount(K.instruction.length,2e3),Qt.append(en,tn);let gt=d(e,"textarea");gt.rows=4,gt.maxLength=2e3,gt.value=K.instruction,gt.placeholder=s.targets.instructionPlaceholder,gt.disabled=!Qe,gt.dataset.targetInstructionId=K.id,gt.setAttribute("aria-label",s.targets.instructionLabel(K.label)),Zt.append(Qt,gt),St.append(Zt)}Q.append(St)}if(U!==void 0){let j=N(U);j?.focus({preventScroll:!0}),we!==void 0&&tt!==void 0&&j?.setSelectionRange(we,tt)}}function te(g,S){Se=Se.map(j=>j.id===g?Object.freeze({...j,instruction:S}):j);let C=Array.from(Q.querySelectorAll(".spotpatch-target-item")).find(j=>j.dataset.targetId===g);if(C===void 0)return;let U=S.trim().length>0,we=C.querySelector(".spotpatch-target-state"),tt=C.querySelector(".spotpatch-target-editor-count");we!==null&&(we.dataset.complete=String(U),we.textContent=U?s.targets.instructionReady:s.targets.instructionMissing),tt!==null&&(tt.textContent=s.targets.instructionCount(S.length,2e3));let ct=Se.filter(j=>j.instruction.trim().length>0).length;be.textContent=s.targets.complete(ct,Se.length),y(ct,Se.length);let Ee=Se.reduce((j,K)=>j+K.instruction.trim().length,0),Tt=Ee>4e3;q.dataset.state=Tt?"over":"ready",q.textContent=Tt?s.targets.instructionBudgetExceeded(Ee,4e3):s.targets.instructionBudget(Ee,4e3)}function f(g){P.replaceChildren(),Ye=g.find(S=>S.active)?.rect,Be=Ye;for(let[S,C]of g.entries()){let U=d(e,"div");U.className="spotpatch-selection-highlight",U.dataset.targetId=C.id,U.dataset.active=String(C.active),U.style.transform=`translate(${String(C.rect.x)}px, ${String(C.rect.y)}px)`,U.style.width=`${String(C.rect.width)}px`,U.style.height=`${String(C.rect.height)}px`;let we=d(e,"span");we.textContent=`${String(S+1)} · ${C.label}`,U.append(we),P.append(U)}w()}function w(){if(b.hidden)return;let g=e.defaultView,S=g?.innerWidth??e.documentElement.clientWidth,C=g?.innerHeight??e.documentElement.clientHeight,U=b.getBoundingClientRect(),we=Xe==="previewing"?"previewing":"selected",tt=U.width>0?U.width:Math.min(xo,S-32),ct=U.height>0?U.height:Math.min(_a[we],C-32),Ee=So({dialogWidth:tt,dialogHeight:ct,viewportWidth:S,viewportHeight:C,...Be===void 0?{}:{target:Be}});b.style.left=`${String(Ee.left)}px`,b.style.top=`${String(Ee.top)}px`,b.style.setProperty("--spotpatch-anchor-x",`${String(Ee.anchorX)}px`),b.style.setProperty("--spotpatch-anchor-y",`${String(Ee.anchorY)}px`),b.dataset.placement=Ee.mode}function le(g){let S=s.summary,C=Ia(g,S.source);ze.textContent=C??s.diagnostics.noExactSource;let U=`${S.browserContext}: ${S.collectionStatuses.ready}`,we=`${S.browserContext}: ${S.collectionStatuses.loading}`,tt=`${S.browserContext}: ${S.collectionStatuses.failed}`,ct=`${S.api}: ${S.apiStatuses.loading}`,Ee=`${S.api}: ${S.apiStatuses.failed}`;g.includes(U)&&!g.includes(we)&&!g.includes(ct)&&!g.includes(tt)&&!g.includes(Ee)?(_.dataset.state="ready",_.textContent=s.context.ready):g.includes(tt)||g.includes(Ee)?(_.dataset.state="warning",_.textContent=s.context.partial):(_.dataset.state="loading",_.textContent=s.context.collecting)}function ne(g,S,C){qe=S,ve=C,Ze=g,ke.textContent=g,De.disabled=!S,se.disabled=!C,v.setContextReady(C),J?.setContextReady(C),le(g),w()}function Ge(g){Xe=g;let S=g==="selected",C=g==="previewing";m.hidden=S||C,Re.hidden=!S,ge.hidden=!C,je.hidden=!S,Te.hidden=!S,De.hidden=!S,se.hidden=!S,ce.hidden=!S,v.setSelectionVisible(S),J?.setSelectionVisible(S),Ve.hidden=!C,$e.hidden=!C,F.textContent=C?s.dialog.previewTitle:s.dialog.editTitle,xe.textContent=C?s.dialog.previewSubtitle:s.dialog.editSubtitle,w()}function Ct(){s=R.messages(),x.textContent=s.brand.name,I.textContent=s.brand.context,W.textContent=s.brand.repository,W.title=s.brand.repositoryTitle,W.setAttribute("aria-label",s.brand.repositoryTitle),X.textContent=s.alternateLocaleName,X.title=s.switchLocale,X.setAttribute("aria-label",s.switchLocale),Z.setAttribute("aria-label",s.dialog.close),Z.title=s.dialog.close,Ce.setAttribute("aria-label",s.targets.ariaLabel),pt.textContent=s.targets.title,at.textContent=s.diagnostics.title,O.setAttribute("aria-label",s.diagnostics.promptAriaLabel),Te.textContent=s.actions.addElement,je.textContent=s.actions.reselect,De.textContent=s.actions.openEditor,se.textContent=s.actions.preview,Ve.textContent=s.actions.copy,$e.textContent=s.actions.back,ie.render(yt),m.title=s.trigger.title(t),m.textContent=Xe==="inspecting"?s.trigger.stop:s.trigger.select,Ge(Xe),a(ee),Se.length>0?D(Se,et):(Fe.textContent=s.targets.count(0,et),be.textContent=s.targets.complete(0,0),y(0,0),q.dataset.state="ready",q.textContent=s.targets.instructionBudget(0,4e3),ue.textContent=s.context.selectedElement),Ze.length>0?le(Ze):(ze.textContent=s.diagnostics.resolving,_.textContent=s.context.collecting)}Ne.addEventListener("toggle",w),X.addEventListener("click",R.toggle);let Dt=R.subscribe(Ct);return Ct(),Object.freeze({host:A,triggerButton:m,addTargetButton:Te,targetList:Q,reselectButton:je,openEditorButton:De,repositoryLink:W,previewButton:se,copyButton:Ve,dataFlowRefreshButton:ie.refreshButton,backButton:$e,closeButton:Z,agentProviderSelect:v.providerSelect,agentModelSelect:v.modelSelect,agentModeSelect:v.modeSelect,agentConsentCheckbox:v.consentCheckbox,agentWorkspaceConsentCheckbox:v.workspaceConsentCheckbox,agentTestButton:v.testButton,agentRunButton:v.runButton,agentCancelButton:v.cancelButton,agentApplyButton:v.applyButton,agentRevertButton:v.revertButton,agentResetButton:v.resetButton,...J===void 0?{}:{externalHandoffPanel:J},renderStatus(g){let S=g==="inspecting";m.setAttribute("aria-pressed",String(S)),m.textContent=S?s.trigger.stop:s.trigger.select,Ge(g)},renderEditorStatus:a,renderDataFlow(g){yt=g,ie.render(g),w()},showHighlight(g,S){Be=g,L.hidden=!1,L.style.transform=`translate(${String(g.x)}px, ${String(g.y)}px)`,L.style.width=`${String(g.width)}px`,L.style.height=`${String(g.height)}px`,M.textContent=S,ue.textContent=S,w()},hideHighlight(){Be=Ye,L.hidden=!0,M.textContent="",w()},showSelectionHighlights:f,hideSelectionHighlights(){P.replaceChildren(),Ye=void 0,Be=void 0,w()},showSelection(g,S,C){ne(g,S,C),m.hidden=!0,b.hidden=!1,w()},updateSelection:ne,renderTargets:D,updateTargetInstruction:te,setPreviewEnabled(g){ve=g,se.disabled=!g,v.setContextReady(g),J?.setContextReady(g)},hideSelection(){b.hidden=!0,m.hidden=!1,Q.replaceChildren(),Se=[],et=0,Ze="",a("idle"),Fe.textContent=s.targets.count(0,0),be.textContent=s.targets.complete(0,0),y(0,0),ue.textContent=s.context.selectedElement,ke.textContent="",O.textContent="",ze.textContent=s.diagnostics.resolving,_.dataset.state="loading",_.textContent=s.context.collecting,De.disabled=!0,se.disabled=!0,qe=!1,ve=!1,v.setContextReady(!1),v.setSelectionVisible(!1),J?.setContextReady(!1),J?.setSelectionVisible(!1),v.setEditingEnabled(!0),v.resetJob(),ie.resetView()},hideSelectionTemporarily(){b.hidden=!0,m.hidden=!1},showPreview(g){O.textContent=g,w()},readAgentSelection(){return v.readSelection()},agentConsentGranted(){return v.consentGranted()},setAgentProviderConsent(g){v.setProviderConsent(g)},setAgentEditingEnabled(g){Qe=g,Te.disabled=!g,je.disabled=!g,Q.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(S=>{S.disabled=!g}),De.disabled=!qe,se.disabled=!g||!ve,J?.setContextReady(g&&ve),v.setEditingEnabled(g),w()},renderAgentCapability(g,S,C,U){v.renderCapability(g,S,C,U);let we=g==="ready"&&C?.state==="agent-ready";se.classList.toggle("spotpatch-primary",!we),w()},renderAgentWorkspaceHealth(g,S,C){v.renderWorkspaceHealth(g,S,C),w()},renderAgentJob(g,S,C,U){v.renderJob(g,S,C,U),w()},resetAgentJob(){v.resetJob(),w()},focusTargetInstruction(g){N(g)?.focus({preventScroll:!0})},focusPrompt(){O.focus({preventScroll:!0})},announce(g){fe.textContent="",fe.textContent=g},locale:R.locale,messages:R.messages,agentWorkspaceConsentGranted:v.workspaceConsentGranted,subscribeLocale:R.subscribe,dispose(){Ne.removeEventListener("toggle",w),X.removeEventListener("click",R.toggle),Dt(),ie.dispose(),J?.dispose(),v.dispose(),A.remove()}})}function ka(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,c=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${c===void 0?"":`:${String(c)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,c):o.unavailable}function To(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${ka(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
959
|
-
`)}function vo(e,t){return`${e}:${t}`}function Da(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function wo(e){let t=h=>Mn(h)??l.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,i=new Set,c=new Map,r=0,u,R,s=!1,A=!1,z=()=>e.view.readAgentSelection(),m=h=>`${h.providerProfileId}:${h.applyMode}`,L=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let E=await e.api.agentWorkspaceHealth();return h!==r||e.view.renderAgentWorkspaceHealth(E.state,E,E.errorCode),E}catch(E){throw h===r&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(E)),E}},M=h=>{u!==void 0&&e.view.renderAgentJob(u,R,Object.freeze([...c.values()]),h??u.errorCode)},P=()=>{let h=z();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(m(h)));let E=n.get(vo(h.providerProfileId,h.modelProfileId));E===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,E)},b=async h=>{let E=z();if(E===void 0)throw new Error("Agent provider selection is unavailable.");let x=vo(E.providerProfileId,E.modelProfileId),I=n.get(x);if(I!==void 0)return I;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let G=await e.api.agentCapability(E);if(h!==r)return G;if(G.state!=="agent-ready")throw new k(G.errorCode??l.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(x,G),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,G),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),G},T=async(h,E)=>{try{let x=await e.api.agentResult(h);if(E!==r||x.snapshot.jobId!==h)return;u=x.snapshot,R=x.result,M()}catch(x){E===r&&M(t(x))}},$=async(h,E)=>{try{await e.api.agentEvents(h,x=>{if(E!==r||x.jobId!==h)return;x.type==="snapshot"&&(u=x.data.snapshot,u.status==="applied"&&!s&&(s=!0,e.onApplied()));let I=Da(x);I!==void 0&&c.set(I.key,I),M()}),E===r&&await T(h,E)}catch(x){E===r&&!(x instanceof DOMException&&x.name==="AbortError")&&M(t(x))}},oe=async h=>{let E=u;if(E===void 0||A)return;A=!0;let x=r;u=Object.freeze({...E,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 I=h==="apply"?await e.api.applyAgentJob(E.jobId):h==="cancel"?await e.api.cancelAgentJob(E.jobId):await e.api.revertAgentJob(E.jobId);if(x!==r)return;u=I,I.status==="applied"&&!s&&(s=!0,e.onApplied()),await T(I.jobId,x)}catch(I){if(x!==r)return;u=E,await T(E.jobId,x),M(t(I)),e.view.announce(o(I))}finally{x===r&&(A=!1)}},H=()=>{r+=1,u=void 0,R=void 0,c.clear(),s=!1,A=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),P()};return Object.freeze({apply(){u?.canApply===!0&&oe("apply")},beginSelection(){H();let h=r;e.ai.enabled&&L(h).catch(()=>{})},cancel(){u?.canCancel===!0&&oe("cancel")},consentChanged(){let h=z();h!==void 0&&(e.view.agentConsentGranted()?i.add(m(h)):i.delete(m(h)))},disposeSelection(){let h=u?.canCancel===!0||u?.status==="cancelling"?u.jobId:void 0;r+=1,u=void 0,R=void 0,c.clear(),s=!1,A=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){r+=1,P(),L(r).catch(()=>{})},reset(){let h=s;H(),h?e.onReselectRequired():e.ai.enabled&&L(r).catch(()=>{})},revert(){u?.canRevert===!0&&oe("revert")},run(){if(!e.ai.enabled||u!==void 0)return;let h=z(),E=e.getAnnotation();if(h===void 0||E===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(m(h));let x=++r;e.view.setAgentEditingEnabled(!1),L(x).then(async I=>{if(x!==r)return;if(I.state==="blocked")throw new k(I.errorCode??l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(I.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new k(l.WORKTREE_DIRTY);let G=await e.api.createAgentJob({annotation:E,applyMode:h.applyMode,providerProfileId:h.providerProfileId,modelProfileId:h.modelProfileId,providerDataConsent:!0,...h.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:I.state==="consent-required"?"include-local-changes":"require-clean"});x===r&&(u=G,R=void 0,c.clear(),M(),$(G.jobId,x))}).catch(I=>{x===r&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(I),void 0,t(I)),e.view.announce(o(I)))})},testCapability(){if(!e.ai.enabled||u!==void 0)return;let h=++r;Promise.all([b(h),L(h)]).catch(E=>{h===r&&(e.view.renderAgentCapability("error",o(E),void 0,t(E)),e.view.announce(o(E)))})}})}function Oo(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 hn(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 _o(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var Fa=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function bn(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 Ha(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function $a(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Ba(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 Lo(e,t={}){let o=Ba(t),n=t.view??Co(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId),i=t.api??Fn({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),c=t.promptComposer??ao({maxCharacters:e.budget.totalCharacters}),r=t.clipboard??_o(o.window.navigator),u=t.createId??(()=>Oo(o.window)),R=t.now??(()=>new Date().toISOString()),s=t.selectionSession??lo(o.window,e.sessionId,e.maxTargets),A=s.load(),z=fo({adapter:t.reactAdapter??Ma({...e.dataFlow.enabled?{getComponentRegistration:a=>kt()?.getComponentRegistration(a)}:{},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.")}}),m=gn,L=!1,M,P,b=A?.targets.map(a=>{let p=mn(a.source);return{id:a.id,resolution:Object.freeze({source:a.source,react:a.react}),apiStatus:p===void 0?"not-required":a.code===void 0?"failed":"connected",code:a.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:a.element,instruction:a.instruction,marker:p,page:a.page,styles:a.styles}})??[],T=A?.activeTargetId,$=A?.sequence??0,oe=A?.open??!1,H=!1,h=0,E=0,x=0,I,G="idle",W=!1,X="",Z,F,xe,Pe,ue=new Map;function _(a){m=io(m,a),n.renderStatus(m.status)}function Ue(){return b.find(a=>a.id===T)??b.at(-1)}function Re(a){let p=a.resolution.react;if(p.componentSourceId!==void 0&&p.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:p.componentSourceId,sourceVersion:p.sourceVersion});let y=a.marker;return y===void 0?void 0:Object.freeze({schemaVersion:1,fileId:y.fileId,line:y.line,column:y.column})}function Ce(){let a=kt(),p=a?.observations(o.window.location.pathname)??[],y=Ue();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?y?.dataFlowStatus??"idle":"disabled",...y?.dataFlowReport===void 0?{}:{report:a?.mergeComponentReport(y.dataFlowReport,p)??y.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?G:"disabled",...I===void 0?{}:{report:a?.mergePageReport(I,p)??I}}),observationCount:p.length})}async function he(){if(!e.dataFlow.enabled){Ce();return}let a=Ue(),p=a===void 0?void 0:Re(a),y=b.flatMap(w=>{let le=Re(w);return le===void 0?[]:[le]}),N=++x,D=h;a!==void 0&&(a.dataFlowStatus="loading"),G=y.length===0?"idle":"loading",Ce();let[te,f]=await Promise.allSettled([p===void 0?Promise.resolve(void 0):i.componentDataFlowReport(p),y.length===0?Promise.resolve(void 0):i.pageDataFlowReport({schemaVersion:1,targets:y})]);!L||N!==x||D!==h||(a!==void 0&&b.includes(a)&&(te.status==="fulfilled"?(a.dataFlowReport=te.value,a.dataFlowStatus=te.value===void 0?"idle":"ready"):(a.dataFlowReport=void 0,a.dataFlowStatus="error")),f.status==="fulfilled"?(I=f.value,G=f.value===void 0?"idle":"ready"):(I=void 0,G="error"),Ce())}function pt(a){if(!(a.elementContext===void 0||a.styles===void 0))return{id:a.id,instruction:a.instruction,page:a.page,source:a.resolution.source,react:a.resolution.react,element:a.elementContext,styles:a.styles,...a.code===void 0?{}:{code:a.code}}}function re(){let a=b.flatMap(y=>{let N=pt(y);return N===void 0?[]:[N]});if(a.length===0){s.clear();return}let p=new Set(a.map(({id:y})=>y));s.save({...T!==void 0&&p.has(T)?{activeTargetId:T}:{},open:oe,sequence:$,targets:a})}function be(a,p){return L&&p===h&&m.status!=="idle"&&b.includes(a)}function q(){let a=b.reduce((p,y)=>p+y.instruction.trim().length,0);return b.length>0&&a<=4e3&&b.every(p=>p.instruction.trim().length>0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function Fe(){let a=n.messages().summary;return b.map((p,y)=>{let N=To({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},a);return`${a.target(y+1,p.id===T)}
|
|
960
|
-
${
|
|
958
|
+
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function Pa(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:Y(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function Co(e,t,o=Object.freeze({enabled:!1}),n="auto",i=!1,c=!1,r="vite",u=""){let R=Ao(e,n),s=R.messages(),A=e.createElement("spotpatch-root");A.setAttribute(xt,"");let z=A.attachShadow({mode:"open"}),m=Y(e,s.trigger.select,"spotpatch-trigger");m.title=s.trigger.title(t),m.setAttribute("aria-pressed","false");let L=d(e,"div");L.className="spotpatch-highlight",L.hidden=!0;let M=d(e,"span");M.className="spotpatch-highlight-label",L.append(M);let N=d(e,"div");N.className="spotpatch-selection-highlights",N.setAttribute("aria-hidden","true");let b=d(e,"section");b.className="spotpatch-dialog",b.hidden=!0,b.tabIndex=-1,b.dataset.placement="viewport",b.setAttribute("role","dialog"),b.setAttribute("aria-labelledby","spotpatch-selection-title");let T=d(e,"span");T.className="spotpatch-anchor",T.setAttribute("aria-hidden","true");let $=d(e,"div");$.className="spotpatch-shell";let re=d(e,"header");re.className="spotpatch-header";let H=d(e,"div");H.className="spotpatch-brand-row";let h=d(e,"div");h.className="spotpatch-brand";let S=d(e,"span");S.className="spotpatch-brand-copy";let x=d(e,"span");x.className="spotpatch-brand-name";let I=d(e,"span");I.className="spotpatch-brand-context",S.append(x,I),h.append(yo(e),S);let G=d(e,"span");G.className="spotpatch-header-controls";let W=d(e,"a");W.className="spotpatch-repository",W.href=ln,W.target="_blank",W.rel="noopener noreferrer";let Z=Y(e,"","spotpatch-locale"),Q=Y(e,"×","spotpatch-close");G.append(W,Z,Q),H.append(h,G);let F=d(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let Re=d(e,"p");Re.className="spotpatch-subtitle";let Ne=d(e,"div");Ne.className="spotpatch-target-row";let ge=d(e,"span");ge.className="spotpatch-target-label";let _=d(e,"span");_.className="spotpatch-context-state",_.dataset.state="loading",_.textContent=s.context.collecting,Ne.append(ge,_),re.append(H,F,Re,Ne);let Ue=d(e,"div");Ue.className="spotpatch-body";let Ce=d(e,"div");Ce.className="spotpatch-selection-panel";let Te=d(e,"section");Te.className="spotpatch-targets";let be=d(e,"div");be.className="spotpatch-targets-heading";let pt=d(e,"span"),ae=d(e,"span");ae.className="spotpatch-targets-meta";let ye=d(e,"span");ye.className="spotpatch-target-complete";let q=d(e,"span");q.className="spotpatch-target-budget",q.setAttribute("aria-live","polite");let Fe=d(e,"span");Fe.className="spotpatch-target-count",ae.append(ye,q),Ne.append(Fe),be.append(pt,ae);let Ie=d(e,"div");Ie.className="spotpatch-target-progress",Ie.setAttribute("aria-hidden","true");let B=d(e,"div");B.className="spotpatch-target-progress-fill",Ie.append(B);let ee=d(e,"div");ee.className="spotpatch-target-list",Te.append(be,Ie,ee);let Pe=d(e,"details");Pe.className="spotpatch-diagnostics";let We=d(e,"summary"),at=d(e,"span"),ze=d(e,"span");ze.className="spotpatch-source-peek",ze.textContent=s.diagnostics.resolving,We.append(at,ze);let De=d(e,"pre");De.className="spotpatch-summary",Pe.append(We,De);let v=ho(e,o,R),Ke=d(e,"div"),J=c?Wt()?.createPanel(e,r,R.locale,u,R.subscribe,w):void 0;Ke.append(Te,v.root,...J===void 0?[]:[J.root]);let se=Dt()?.createPanel(e,i,R.locale,Ke,Pe,w)??Pa(e,Ke,Pe);Ce.append(se.root);let fe=d(e,"div");fe.className="spotpatch-preview-panel",fe.hidden=!0;let O=d(e,"pre");O.className="spotpatch-prompt",O.tabIndex=0,O.setAttribute("aria-label",s.diagnostics.promptAriaLabel),fe.append(O),Ue.append(Ce,fe);let He=d(e,"footer");He.className="spotpatch-actions";let Ee=d(e,"div");Ee.className="spotpatch-context-state spotpatch-editor-feedback",Ee.dataset.state="idle",Ee.setAttribute("role","status"),Ee.setAttribute("aria-live","polite"),Ee.hidden=!0;let ve=Y(e,s.actions.addElement),je=Y(e,s.actions.reselect),ke=Y(e,s.actions.openEditor),ce=Y(e,s.actions.preview,"spotpatch-primary"),Ve=Y(e,s.actions.copy,"spotpatch-primary"),$e=Y(e,s.actions.back),le=d(e,"div");le.className="spotpatch-secondary-actions";let ut=d(e,"div");ut.className="spotpatch-primary-actions",ve.classList.add("spotpatch-icon-action"),ve.dataset.compactIcon="+",v.testButton.classList.add("spotpatch-icon-action"),v.testButton.dataset.compactIcon="✓",ke.classList.add("spotpatch-secondary-action"),je.classList.add("spotpatch-secondary-action"),le.append(ke,je),ut.append(v.testButton,ve,v.runButton,...J===void 0?[]:[J.sendButton],ce,v.cancelButton,v.applyButton,v.revertButton,v.resetButton,Ve,$e),He.append(Ee,le,ut),$.append(re,Ue,He),b.append(T,$);let me=d(e,"div");me.className="spotpatch-live",me.setAttribute("aria-live","polite"),me.setAttribute("aria-atomic","true");let it=[Na(e),se.styles,...J===void 0?[]:[J.styles]],st=La(e);if(st!==void 0)for(let g of it)g.nonce=st;z.append(...it,N,L,b,m,me),e.documentElement.append(A);let Be,Xe,Ye="idle",qe=!1,we=!1,Ze="",Qe=!0,Se=[],et=0,te="idle",yt=Object.freeze({component:Object.freeze({status:i?"idle":"disabled"}),page:Object.freeze({status:i?"idle":"disabled"}),observationCount:0});function a(g){te=g,Ee.dataset.state=g,Ee.hidden=g==="idle",Ee.textContent=g==="opening"?s.announcements.editorOpening:g==="success"?s.announcements.editorOpened:g==="error"?s.announcements.editorFailed:"",w()}function p(g){return g.status==="ready"?s.targets.statusReady:g.status==="warning"?s.targets.statusPartial:s.targets.statusCollecting}function y(g,E){let C=E===0?0:g/E;B.style.width=`${String(C*100)}%`}function P(g){let E=ee.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(E).find(C=>g===void 0||C.dataset.targetInstructionId===g)}function k(g,E){let C=z.activeElement?.closest("textarea[data-target-instruction-id]"),U=C?.dataset.targetInstructionId,Oe=C?.selectionStart,tt=C?.selectionEnd;Se=g.map(j=>Object.freeze({...j})),et=E,ee.replaceChildren();let ct=g.filter(j=>j.instruction.trim().length>0).length,Ae=g.reduce((j,K)=>j+K.instruction.trim().length,0);y(ct,g.length),Fe.textContent=s.targets.count(g.length,E),ye.textContent=s.targets.complete(ct,g.length);let Tt=Ae>4e3;q.dataset.state=Tt?"over":"ready",q.textContent=Tt?s.targets.instructionBudgetExceeded(Ae,4e3):s.targets.instructionBudget(Ae,4e3),ve.disabled=!Qe||g.length>=E,ve.title=g.length>=E?s.targets.limitTitle(E):s.targets.addTitle,ge.textContent=g.length===1?g[0]?.label??s.context.selectedElement:s.context.selectedCount(g.length);for(let[j,K]of g.entries()){let Et=d(e,"div");Et.className="spotpatch-target-item",Et.dataset.active=String(K.active),Et.dataset.status=K.status,Et.dataset.targetId=K.id;let qt=d(e,"div");qt.className="spotpatch-target-summary";let vt=Y(e,"","spotpatch-target-select");vt.dataset.activateTargetId=K.id,vt.setAttribute("aria-label",s.targets.activate(j+1)),vt.setAttribute("aria-expanded",String(K.active));let Jt=d(e,"span");Jt.className="spotpatch-target-index",Jt.textContent=String(j+1);let Kt=d(e,"span");Kt.className="spotpatch-target-copy";let Xt=d(e,"span");Xt.className="spotpatch-target-name",Xt.textContent=K.label;let Yt=d(e,"span");Yt.className="spotpatch-target-source",Yt.textContent=`${p(K)} · ${K.source}`,Kt.append(Xt,Yt);let En=K.instruction.trim().length>0,Mt=d(e,"span");Mt.className="spotpatch-target-state",Mt.dataset.complete=String(En),Mt.textContent=En?s.targets.instructionReady:s.targets.instructionMissing,vt.append(Jt,Kt,Mt);let wt=Y(e,"↗","spotpatch-target-open");wt.dataset.openTargetId=K.id,wt.disabled=!K.canOpenEditor,wt.setAttribute("aria-label",s.actions.openTarget(j+1)),wt.title=s.actions.openTarget(j+1);let Ot=Y(e,"×","spotpatch-target-remove");if(Ot.dataset.removeTargetId=K.id,Ot.disabled=!Qe,Ot.setAttribute("aria-label",s.targets.remove(j+1)),Ot.title=s.targets.removeTitle,qt.append(vt,wt,Ot),Et.append(qt),K.active){let Zt=d(e,"label");Zt.className="spotpatch-target-editor";let Qt=d(e,"span");Qt.className="spotpatch-target-editor-head";let en=d(e,"span");en.className="spotpatch-target-editor-label",en.textContent=s.targets.instructionLabel(K.label);let tn=d(e,"span");tn.className="spotpatch-target-editor-count",tn.textContent=s.targets.instructionCount(K.instruction.length,2e3),Qt.append(en,tn);let gt=d(e,"textarea");gt.rows=4,gt.maxLength=2e3,gt.value=K.instruction,gt.placeholder=s.targets.instructionPlaceholder,gt.disabled=!Qe,gt.dataset.targetInstructionId=K.id,gt.setAttribute("aria-label",s.targets.instructionLabel(K.label)),Zt.append(Qt,gt),Et.append(Zt)}ee.append(Et)}if(U!==void 0){let j=P(U);j?.focus({preventScroll:!0}),Oe!==void 0&&tt!==void 0&&j?.setSelectionRange(Oe,tt)}}function ne(g,E){Se=Se.map(j=>j.id===g?Object.freeze({...j,instruction:E}):j);let C=Array.from(ee.querySelectorAll(".spotpatch-target-item")).find(j=>j.dataset.targetId===g);if(C===void 0)return;let U=E.trim().length>0,Oe=C.querySelector(".spotpatch-target-state"),tt=C.querySelector(".spotpatch-target-editor-count");Oe!==null&&(Oe.dataset.complete=String(U),Oe.textContent=U?s.targets.instructionReady:s.targets.instructionMissing),tt!==null&&(tt.textContent=s.targets.instructionCount(E.length,2e3));let ct=Se.filter(j=>j.instruction.trim().length>0).length;ye.textContent=s.targets.complete(ct,Se.length),y(ct,Se.length);let Ae=Se.reduce((j,K)=>j+K.instruction.trim().length,0),Tt=Ae>4e3;q.dataset.state=Tt?"over":"ready",q.textContent=Tt?s.targets.instructionBudgetExceeded(Ae,4e3):s.targets.instructionBudget(Ae,4e3)}function f(g){N.replaceChildren(),Xe=g.find(E=>E.active)?.rect,Be=Xe;for(let[E,C]of g.entries()){let U=d(e,"div");U.className="spotpatch-selection-highlight",U.dataset.targetId=C.id,U.dataset.active=String(C.active),U.style.transform=`translate(${String(C.rect.x)}px, ${String(C.rect.y)}px)`,U.style.width=`${String(C.rect.width)}px`,U.style.height=`${String(C.rect.height)}px`;let Oe=d(e,"span");Oe.textContent=`${String(E+1)} · ${C.label}`,U.append(Oe),N.append(U)}w()}function w(){if(b.hidden)return;let g=e.defaultView,E=g?.innerWidth??e.documentElement.clientWidth,C=g?.innerHeight??e.documentElement.clientHeight,U=b.getBoundingClientRect(),Oe=Ye==="previewing"?"previewing":"selected",tt=U.width>0?U.width:Math.min(xo,E-32),ct=U.height>0?U.height:Math.min(_a[Oe],C-32),Ae=Eo({dialogWidth:tt,dialogHeight:ct,viewportWidth:E,viewportHeight:C,...Be===void 0?{}:{target:Be}});b.style.left=`${String(Ae.left)}px`,b.style.top=`${String(Ae.top)}px`,b.style.setProperty("--spotpatch-anchor-x",`${String(Ae.anchorX)}px`),b.style.setProperty("--spotpatch-anchor-y",`${String(Ae.anchorY)}px`),b.dataset.placement=Ae.mode}function de(g){let E=s.summary,C=Ia(g,E.source);ze.textContent=C??s.diagnostics.noExactSource;let U=`${E.browserContext}: ${E.collectionStatuses.ready}`,Oe=`${E.browserContext}: ${E.collectionStatuses.loading}`,tt=`${E.browserContext}: ${E.collectionStatuses.failed}`,ct=`${E.api}: ${E.apiStatuses.loading}`,Ae=`${E.api}: ${E.apiStatuses.failed}`;g.includes(U)&&!g.includes(Oe)&&!g.includes(ct)&&!g.includes(tt)&&!g.includes(Ae)?(_.dataset.state="ready",_.textContent=s.context.ready):g.includes(tt)||g.includes(Ae)?(_.dataset.state="warning",_.textContent=s.context.partial):(_.dataset.state="loading",_.textContent=s.context.collecting)}function oe(g,E,C){qe=E,we=C,Ze=g,De.textContent=g,ke.disabled=!E,ce.disabled=!C,v.setContextReady(C),J?.setContextReady(C),de(g),w()}function Ge(g){Ye=g;let E=g==="selected",C=g==="previewing";m.hidden=E||C,Ce.hidden=!E,fe.hidden=!C,je.hidden=!E,ve.hidden=!E,ke.hidden=!E,ce.hidden=!E,le.hidden=!E,v.setSelectionVisible(E),J?.setSelectionVisible(E),Ve.hidden=!C,$e.hidden=!C,F.textContent=C?s.dialog.previewTitle:s.dialog.editTitle,Re.textContent=C?s.dialog.previewSubtitle:s.dialog.editSubtitle,w()}function Ct(){s=R.messages(),x.textContent=s.brand.name,I.textContent=s.brand.context,W.textContent=s.brand.repository,W.title=s.brand.repositoryTitle,W.setAttribute("aria-label",s.brand.repositoryTitle),Z.textContent=s.alternateLocaleName,Z.title=s.switchLocale,Z.setAttribute("aria-label",s.switchLocale),Q.setAttribute("aria-label",s.dialog.close),Q.title=s.dialog.close,Te.setAttribute("aria-label",s.targets.ariaLabel),pt.textContent=s.targets.title,at.textContent=s.diagnostics.title,O.setAttribute("aria-label",s.diagnostics.promptAriaLabel),ve.textContent=s.actions.addElement,je.textContent=s.actions.reselect,ke.textContent=s.actions.openEditor,ce.textContent=s.actions.preview,Ve.textContent=s.actions.copy,$e.textContent=s.actions.back,se.render(yt),m.title=s.trigger.title(t),m.textContent=Ye==="inspecting"?s.trigger.stop:s.trigger.select,Ge(Ye),a(te),Se.length>0?k(Se,et):(Fe.textContent=s.targets.count(0,et),ye.textContent=s.targets.complete(0,0),y(0,0),q.dataset.state="ready",q.textContent=s.targets.instructionBudget(0,4e3),ge.textContent=s.context.selectedElement),Ze.length>0?de(Ze):(ze.textContent=s.diagnostics.resolving,_.textContent=s.context.collecting)}Pe.addEventListener("toggle",w),Z.addEventListener("click",R.toggle);let kt=R.subscribe(Ct);return Ct(),Object.freeze({host:A,triggerButton:m,addTargetButton:ve,targetList:ee,reselectButton:je,openEditorButton:ke,repositoryLink:W,previewButton:ce,copyButton:Ve,dataFlowRefreshButton:se.refreshButton,backButton:$e,closeButton:Q,agentProviderSelect:v.providerSelect,agentModelSelect:v.modelSelect,agentModeSelect:v.modeSelect,agentConsentCheckbox:v.consentCheckbox,agentWorkspaceConsentCheckbox:v.workspaceConsentCheckbox,agentTestButton:v.testButton,agentRunButton:v.runButton,agentCancelButton:v.cancelButton,agentApplyButton:v.applyButton,agentRevertButton:v.revertButton,agentResetButton:v.resetButton,...J===void 0?{}:{externalHandoffPanel:J},renderStatus(g){let E=g==="inspecting";m.setAttribute("aria-pressed",String(E)),m.textContent=E?s.trigger.stop:s.trigger.select,Ge(g)},renderEditorStatus:a,renderDataFlow(g){yt=g,se.render(g),w()},showHighlight(g,E){Be=g,L.hidden=!1,L.style.transform=`translate(${String(g.x)}px, ${String(g.y)}px)`,L.style.width=`${String(g.width)}px`,L.style.height=`${String(g.height)}px`,M.textContent=E,ge.textContent=E,w()},hideHighlight(){Be=Xe,L.hidden=!0,M.textContent="",w()},showSelectionHighlights:f,hideSelectionHighlights(){N.replaceChildren(),Xe=void 0,Be=void 0,w()},showSelection(g,E,C){oe(g,E,C),m.hidden=!0,b.hidden=!1,w()},updateSelection:oe,renderTargets:k,updateTargetInstruction:ne,setPreviewEnabled(g){we=g,ce.disabled=!g,v.setContextReady(g),J?.setContextReady(g)},hideSelection(){b.hidden=!0,m.hidden=!1,ee.replaceChildren(),Se=[],et=0,Ze="",a("idle"),Fe.textContent=s.targets.count(0,0),ye.textContent=s.targets.complete(0,0),y(0,0),ge.textContent=s.context.selectedElement,De.textContent="",O.textContent="",ze.textContent=s.diagnostics.resolving,_.dataset.state="loading",_.textContent=s.context.collecting,ke.disabled=!0,ce.disabled=!0,qe=!1,we=!1,v.setContextReady(!1),v.setSelectionVisible(!1),J?.setContextReady(!1),J?.setSelectionVisible(!1),v.setEditingEnabled(!0),v.resetJob(),se.resetView()},hideSelectionTemporarily(){b.hidden=!0,m.hidden=!1},showPreview(g){O.textContent=g,w()},readAgentSelection(){return v.readSelection()},agentConsentGranted(){return v.consentGranted()},setAgentProviderConsent(g){v.setProviderConsent(g)},setAgentEditingEnabled(g){Qe=g,ve.disabled=!g,je.disabled=!g,ee.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(E=>{E.disabled=!g}),ke.disabled=!qe,ce.disabled=!g||!we,J?.setContextReady(g&&we),v.setEditingEnabled(g),w()},renderAgentCapability(g,E,C,U){v.renderCapability(g,E,C,U);let Oe=g==="ready"&&C?.state==="agent-ready";ce.classList.toggle("spotpatch-primary",!Oe),w()},renderAgentWorkspaceHealth(g,E,C){v.renderWorkspaceHealth(g,E,C),w()},renderAgentJob(g,E,C,U){v.renderJob(g,E,C,U),w()},resetAgentJob(){v.resetJob(),w()},focusTargetInstruction(g){P(g)?.focus({preventScroll:!0})},focusPrompt(){O.focus({preventScroll:!0})},announce(g){me.textContent="",me.textContent=g},locale:R.locale,messages:R.messages,agentWorkspaceConsentGranted:v.workspaceConsentGranted,subscribeLocale:R.subscribe,dispose(){Pe.removeEventListener("toggle",w),Z.removeEventListener("click",R.toggle),kt(),se.dispose(),J?.dispose(),v.dispose(),A.remove()}})}function Da(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,c=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${c===void 0?"":`:${String(c)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,c):o.unavailable}function To(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${Da(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
959
|
+
`)}function vo(e,t){return`${e}:${t}`}function ka(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function wo(e){let t=h=>Mn(h)??l.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,i=new Set,c=new Map,r=0,u,R,s=!1,A=!1,z=()=>e.view.readAgentSelection(),m=h=>`${h.providerProfileId}:${h.applyMode}`,L=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let S=await e.api.agentWorkspaceHealth();return h!==r||e.view.renderAgentWorkspaceHealth(S.state,S,S.errorCode),S}catch(S){throw h===r&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(S)),S}},M=h=>{u!==void 0&&e.view.renderAgentJob(u,R,Object.freeze([...c.values()]),h??u.errorCode)},N=()=>{let h=z();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(m(h)));let S=n.get(vo(h.providerProfileId,h.modelProfileId));S===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,S)},b=async h=>{let S=z();if(S===void 0)throw new Error("Agent provider selection is unavailable.");let x=vo(S.providerProfileId,S.modelProfileId),I=n.get(x);if(I!==void 0)return I;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let G=await e.api.agentCapability(S);if(h!==r)return G;if(G.state!=="agent-ready")throw new D(G.errorCode??l.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(x,G),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,G),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),G},T=async(h,S)=>{try{let x=await e.api.agentResult(h);if(S!==r||x.snapshot.jobId!==h)return;u=x.snapshot,R=x.result,M()}catch(x){S===r&&M(t(x))}},$=async(h,S)=>{try{await e.api.agentEvents(h,x=>{if(S!==r||x.jobId!==h)return;x.type==="snapshot"&&(u=x.data.snapshot,u.status==="applied"&&!s&&(s=!0,e.onApplied()));let I=ka(x);I!==void 0&&c.set(I.key,I),M()}),S===r&&await T(h,S)}catch(x){S===r&&!(x instanceof DOMException&&x.name==="AbortError")&&M(t(x))}},re=async h=>{let S=u;if(S===void 0||A)return;A=!0;let x=r;u=Object.freeze({...S,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 I=h==="apply"?await e.api.applyAgentJob(S.jobId):h==="cancel"?await e.api.cancelAgentJob(S.jobId):await e.api.revertAgentJob(S.jobId);if(x!==r)return;u=I,I.status==="applied"&&!s&&(s=!0,e.onApplied()),await T(I.jobId,x)}catch(I){if(x!==r)return;u=S,await T(S.jobId,x),M(t(I)),e.view.announce(o(I))}finally{x===r&&(A=!1)}},H=()=>{r+=1,u=void 0,R=void 0,c.clear(),s=!1,A=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),N()};return Object.freeze({apply(){u?.canApply===!0&&re("apply")},beginSelection(){H();let h=r;e.ai.enabled&&L(h).catch(()=>{})},cancel(){u?.canCancel===!0&&re("cancel")},consentChanged(){let h=z();h!==void 0&&(e.view.agentConsentGranted()?i.add(m(h)):i.delete(m(h)))},disposeSelection(){let h=u?.canCancel===!0||u?.status==="cancelling"?u.jobId:void 0;r+=1,u=void 0,R=void 0,c.clear(),s=!1,A=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){r+=1,N(),L(r).catch(()=>{})},reset(){let h=s;H(),h?e.onReselectRequired():e.ai.enabled&&L(r).catch(()=>{})},revert(){u?.canRevert===!0&&re("revert")},run(){if(!e.ai.enabled||u!==void 0)return;let h=z(),S=e.getAnnotation();if(h===void 0||S===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(m(h));let x=++r;e.view.setAgentEditingEnabled(!1),L(x).then(async I=>{if(x!==r)return;if(I.state==="blocked")throw new D(I.errorCode??l.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(I.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new D(l.WORKTREE_DIRTY);let G=await e.api.createAgentJob({annotation:S,applyMode:h.applyMode,providerProfileId:h.providerProfileId,modelProfileId:h.modelProfileId,providerDataConsent:!0,...h.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:I.state==="consent-required"?"include-local-changes":"require-clean"});x===r&&(u=G,R=void 0,c.clear(),M(),$(G.jobId,x))}).catch(I=>{x===r&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(I),void 0,t(I)),e.view.announce(o(I)))})},testCapability(){if(!e.ai.enabled||u!==void 0)return;let h=++r;Promise.all([b(h),L(h)]).catch(S=>{h===r&&(e.view.renderAgentCapability("error",o(S),void 0,t(S)),e.view.announce(o(S)))})}})}function Oo(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 hn(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 _o(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var Fa=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function bn(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 Ha(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function $a(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function Ba(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 Lo(e,t={}){let o=Ba(t),n=t.view??Co(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId),i=t.api??Fn({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),c=t.promptComposer??ao({maxCharacters:e.budget.totalCharacters}),r=t.clipboard??_o(o.window.navigator),u=t.createId??(()=>Oo(o.window)),R=t.now??(()=>new Date().toISOString()),s=t.selectionSession??lo(o.window,e.sessionId,e.maxTargets),A=s.load(),z=fo({adapter:t.reactAdapter??Ma({...e.dataFlow.enabled?{getComponentRegistration:a=>Dt()?.getComponentRegistration(a)}:{},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.")}}),m=gn,L=!1,M,N,b=A?.targets.map(a=>{let p=mn(a.source);return{id:a.id,resolution:Object.freeze({source:a.source,react:a.react}),apiStatus:p===void 0?"not-required":a.code===void 0?"failed":"connected",code:a.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:a.element,instruction:a.instruction,marker:p,page:a.page,styles:a.styles}})??[],T=A?.activeTargetId,$=A?.sequence??0,re=A?.open??!1,H=!1,h=0,S=0,x=0,I,G="idle",W=!1,Z="",Q,F,Re,Ne,ge=new Map;function _(a){m=io(m,a),n.renderStatus(m.status)}function Ue(){return b.find(a=>a.id===T)??b.at(-1)}function Ce(a){let p=a.resolution.react;if(p.componentSourceId!==void 0&&p.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:p.componentSourceId,sourceVersion:p.sourceVersion});let y=a.marker;return y===void 0?void 0:Object.freeze({schemaVersion:1,fileId:y.fileId,line:y.line,column:y.column})}function Te(){let a=Dt(),p=a?.observations(o.window.location.pathname)??[],y=Ue();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?y?.dataFlowStatus??"idle":"disabled",...y?.dataFlowReport===void 0?{}:{report:a?.mergeComponentReport(y.dataFlowReport,p)??y.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?G:"disabled",...I===void 0?{}:{report:a?.mergePageReport(I,p)??I}}),observationCount:p.length})}async function be(){if(!e.dataFlow.enabled){Te();return}let a=Ue(),p=a===void 0?void 0:Ce(a),y=b.flatMap(w=>{let de=Ce(w);return de===void 0?[]:[de]}),P=++x,k=h;a!==void 0&&(a.dataFlowStatus="loading"),G=y.length===0?"idle":"loading",Te();let[ne,f]=await Promise.allSettled([p===void 0?Promise.resolve(void 0):i.componentDataFlowReport(p),y.length===0?Promise.resolve(void 0):i.pageDataFlowReport({schemaVersion:1,targets:y})]);!L||P!==x||k!==h||(a!==void 0&&b.includes(a)&&(ne.status==="fulfilled"?(a.dataFlowReport=ne.value,a.dataFlowStatus=ne.value===void 0?"idle":"ready"):(a.dataFlowReport=void 0,a.dataFlowStatus="error")),f.status==="fulfilled"?(I=f.value,G=f.value===void 0?"idle":"ready"):(I=void 0,G="error"),Te())}function pt(a){if(!(a.elementContext===void 0||a.styles===void 0))return{id:a.id,instruction:a.instruction,page:a.page,source:a.resolution.source,react:a.resolution.react,element:a.elementContext,styles:a.styles,...a.code===void 0?{}:{code:a.code}}}function ae(){let a=b.flatMap(y=>{let P=pt(y);return P===void 0?[]:[P]});if(a.length===0){s.clear();return}let p=new Set(a.map(({id:y})=>y));s.save({...T!==void 0&&p.has(T)?{activeTargetId:T}:{},open:re,sequence:$,targets:a})}function ye(a,p){return L&&p===h&&m.status!=="idle"&&b.includes(a)}function q(){let a=b.reduce((p,y)=>p+y.instruction.trim().length,0);return b.length>0&&a<=4e3&&b.every(p=>p.instruction.trim().length>0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function Fe(){let a=n.messages().summary;return b.map((p,y)=>{let P=To({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},a);return`${a.target(y+1,p.id===T)}
|
|
960
|
+
${P}`}).join(`
|
|
961
961
|
|
|
962
|
-
`)}function Ie(){let a=b.flatMap(p=>{if(!p.element?.isConnected)return[];let y=Vt(p.element,o.window);return y===void 0?[]:[{id:p.id,label:bn(p.element),rect:y,active:p.id===T}]});a.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(a)}function B(a=!1){if(b.length===0)return;n.renderTargets(b.map(D=>({id:D.id,label:D.resolution.react.componentName??(D.element===void 0?D.elementContext?.tagName??"Element":bn(D.element)),source:Ha(D,n.messages().context.sourceUnavailable),canOpenEditor:D.marker!==void 0,status:$a(D),active:D.id===T,instruction:D.instruction})),e.maxTargets),Ie();let p=Ue(),y=Fe(),N=p?.marker!==void 0;a?n.showSelection(y,N,q()):n.updateSelection(y,N,q())}function Q(){if(!q())return;let a=b.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let y=[...p.apiStatus==="failed"?["Source context could not be loaded."]:[],...p.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:p.instruction.trim(),page:p.page,source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:y}});return An({id:u(),locale:n.locale(),createdAt:R(),page:hn(o.document,o.window),targets:a})}function Ne(a){n.showHighlight(Qn(a,o.window),bn(a))}function We(){Z?.isConnected===!0&&Z.focus({preventScroll:!0}),Z=void 0}function at(){for(let a of ue.values())o.window.clearTimeout(a);ue.clear()}function ze(){h+=1,i.cancelPending(),O.disposeSelection(),He?.cancelPending(),at(),F?.disconnect(),b=[],T=void 0,x+=1,I=void 0,G="idle",oe=!1,H=!1,W=!1,X="",n.hideSelection(),n.hideSelectionHighlights(),s.clear(),We()}function ke(){m.status==="inspecting"?_({type:"CANCEL"}):m.status==="selected"?_({type:"CLOSE"}):m.status==="previewing"&&(_({type:"BACK"}),_({type:"CLOSE"})),oe=!1,re(),n.hideSelection(),n.hideSelectionHighlights(),We(),n.hideHighlight()}function v(){if(m.status!=="inspecting"||!W||b.length===0){ke();return}W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),n.focusTargetInstruction(T),n.announce(n.messages().announcements.addCancelled)}function Ke(){if(m.status==="inspecting"&&W){v();return}if(m.status!=="idle"){ke();return}if(b.length>0){oe=!0,_({type:"RESTORE"}),H||(O.beginSelection(),H=!0),B(!0),he(),n.focusTargetInstruction(T),re();return}_({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function J(a=n.messages().announcements.chooseAnother){m.status==="selected"&&(_({type:"RESELECT"}),ze(),n.hideHighlight(),n.announce(a))}function ie(){if(m.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}W=!0,_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function ge(){h+=1,at(),F?.disconnect();for(let a of b)a.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),B(),s.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let O=wo({ai:e.ai,api:i,getAnnotation:Q,onApplied:ge,onReselectRequired(){J(n.messages().announcements.reselectAfterChange)},view:n}),He=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?Wt()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,Q,e.sessionToken,o.window):void 0;async function ye(a,p){let y=a.marker;if(y!==void 0)try{let N=await i.sourceContext({fileId:y.fileId,line:y.line,column:y.column,maxLines:e.budget.maxCodeLines});be(a,p)&&(a.code=N,a.apiStatus="connected",re(),B(),n.announce(n.messages().announcements.sourceLoaded))}catch(N){be(a,p)&&(a.code=void 0,a.apiStatus="failed",re(),B(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(N instanceof DOMException&&N.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Te(a,p){let y=a.element;if(y===void 0)return;let N=o.window.setTimeout(()=>{if(ue.delete(a.id),!be(a,p))return;let D=!1;try{a.elementContext=Jn({element:y,maxCharacters:e.budget.domCharacters})}catch{a.elementContext=void 0,D=!0}try{a.styles=zn({document:o.document,element:y,maxCharacters:e.budget.cssCharacters})}catch{a.styles=Fa,D=!0}a.collectionStatus=D?"failed":"ready",re(),B(),n.announce(D?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&a.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(a.styles.warnings.length)} warning(s).`)},0);ue.set(a.id,N)}function je(a,p){return p!==void 0?b.find(y=>y.marker?.fileId===p.fileId&&y.marker.line===p.line&&y.marker.column===p.column):b.find(y=>y.element===a)}function De(a){let p=z.resolve(a),y=mn(p.source),N=je(a,y);if(N!==void 0){T=N.id,W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),he(),n.focusTargetInstruction(N.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(Z=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,X="",O.beginSelection(),H=!0),$+=1;let te={id:`target-${String($)}`,element:a,resolution:p,marker:y,page:hn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:y===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};b.push(te),T=te.id,W=!1;let f=h;_({type:"SELECT"}),n.hideHighlight(),F?.observe(a),B(!0),he(),oe=!0,n.focusTargetInstruction(te.id),Te(te,f),y!==void 0?ye(te,f):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function se(){if(M=void 0,m.status!=="inspecting"||P===void 0)return;let a=pn(o.document,o.window,P.x,P.y);if(_({type:"HOVER"}),a===void 0){n.hideHighlight();return}Ne(a)}function Ve(a){m.status==="inspecting"&&(P={x:a.clientX,y:a.clientY},M??=o.window.requestAnimationFrame(se))}function $e(a){if(m.status!=="inspecting"||to(a.target))return;a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation();let p=pn(o.document,o.window,a.clientX,a.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}De(p)}function ce(a){if(a.key==="Escape"&&m.status!=="idle"){a.preventDefault(),m.status==="inspecting"&&W?v():m.status==="inspecting"||m.status==="selected"?ke():(_({type:"BACK"}),n.focusTargetInstruction(T));return}Yn(a.target)||!Xn(a,e.shortcut,o.window.navigator.userAgent)||(a.preventDefault(),Ke())}function ut(a){if(m.status!=="selected"&&m.status!=="inspecting")return;let p=b.findIndex(D=>D.id===a);if(p<0)return;let[y]=b.splice(p,1);if(y===void 0)return;let N=ue.get(y.id);if(N!==void 0&&(o.window.clearTimeout(N),ue.delete(y.id)),y.element!==void 0&&F?.unobserve(y.element),T===y.id&&(T=b.at(-1)?.id),b.length===0){W=!0,m.status==="selected"&&_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),I=void 0,G="idle",Ce(),s.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}B(),he(),re(),n.announce(n.messages().announcements.targetRemoved)}function fe(){if(m.status==="idle"||b.length===0)return;let a=b.filter(p=>p.element!==void 0&&!p.element.isConnected);if(a.length>0){for(let p of a)p.element!==void 0&&(F?.unobserve(p.element),p.element=void 0);B(),re(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Ie()}function it(a){let p=a===void 0?Ue():b.find(te=>te.id===a);if(m.status!=="selected"||p?.marker===void 0)return;T!==p.id&&(T=p.id,B());let y=p.marker,N=h,D=++E;_({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:y.fileId,line:y.line,column:y.column}).then(()=>{L&&m.status==="selected"&&N===h&&D===E&&T===p.id&&b.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{L&&m.status==="selected"&&N===h&&D===E&&T===p.id&&b.includes(p)&&n.renderEditorStatus("error")})}function st(a){if(m.status!=="selected"||!(a.target instanceof HTMLTextAreaElement))return;let p=a.target.dataset.targetInstructionId,y=b.find(N=>N.id===p);y!==void 0&&(y.instruction=a.target.value,n.updateTargetInstruction(y.id,y.instruction),n.setPreviewEnabled(q()),re())}function Be(){it()}function Ye(a){e.ai.enabled&&m.status==="selected"&&a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),O.run())}function Xe(){if(m.status!=="selected")return;let a=Q();if(a===void 0){n.announce(n.messages().announcements.completeInstructions);return}X=c.compose(a),_({type:"PREVIEW"}),n.showPreview(X),n.focusPrompt()}function qe(){if(m.status!=="previewing"||X.length===0)return;if(r===void 0){_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let a=h;r.writeText(X).then(()=>{L&&a===h&&m.status==="previewing"&&(_({type:"COPY_SUCCESS"}),n.focusTargetInstruction(T),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{L&&a===h&&m.status==="previewing"&&(_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function ve(){m.status==="previewing"&&(_({type:"BACK"}),n.focusTargetInstruction(T))}function Ze(){if(!(!L||b.length===0)&&(B(),m.status==="previewing")){let a=Q();a!==void 0&&(X=c.compose(a),n.showPreview(X))}}function Qe(a){let p=a.target;if(!(p instanceof Element))return;let y=p.closest("button[data-remove-target-id]");if(y?.dataset.removeTargetId!==void 0){ut(y.dataset.removeTargetId);return}let N=p.closest("button[data-open-target-id]");if(N?.dataset.openTargetId!==void 0){it(N.dataset.openTargetId);return}let te=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;m.status!=="selected"||te===void 0||!b.some(f=>f.id===te)||(T=te,B(),he(),n.focusTargetInstruction(te))}function Se(){J()}function et(){he()}function ee(){L||(L=!0,He?.mount(),n.renderStatus(m.status),o.document.addEventListener("pointermove",Ve,!0),o.document.addEventListener("click",$e,!0),o.document.addEventListener("keydown",ce,!0),o.window.addEventListener("scroll",fe,!0),o.window.addEventListener("resize",fe),n.triggerButton.addEventListener("click",Ke),n.addTargetButton.addEventListener("click",ie),n.reselectButton.addEventListener("click",Se),n.targetList.addEventListener("click",Qe),n.targetList.addEventListener("input",st),n.targetList.addEventListener("keydown",Ye),n.openEditorButton.addEventListener("click",Be),n.dataFlowRefreshButton.addEventListener("click",et),n.previewButton.addEventListener("click",Xe),n.copyButton.addEventListener("click",qe),n.backButton.addEventListener("click",ve),n.closeButton.addEventListener("click",ke),n.agentProviderSelect.addEventListener("change",O.providerOrModelChanged),n.agentModelSelect.addEventListener("change",O.providerOrModelChanged),n.agentModeSelect.addEventListener("change",O.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",O.consentChanged),n.agentTestButton.addEventListener("click",O.testCapability),n.agentRunButton.addEventListener("click",O.run),n.agentCancelButton.addEventListener("click",O.cancel),n.agentApplyButton.addEventListener("click",O.apply),n.agentRevertButton.addEventListener("click",O.revert),n.agentResetButton.addEventListener("click",O.reset),Pe=n.subscribeLocale(Ze),o.resizeObserver!==void 0&&(F=new o.resizeObserver(fe)),o.mutationObserver!==void 0&&(xe=new o.mutationObserver(fe),xe.observe(o.document.documentElement,{childList:!0,subtree:!0})),oe&&b.length>0&&(_({type:"RESTORE"}),O.beginSelection(),H=!0,B(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function yt(){if(!L){Pe?.(),Pe=void 0,n.dispose(),i.cancelPending(),i.dispose(),O.disposeSelection(),He?.dispose(),z.dispose();return}L=!1,Pe?.(),Pe=void 0,o.document.removeEventListener("pointermove",Ve,!0),o.document.removeEventListener("click",$e,!0),o.document.removeEventListener("keydown",ce,!0),o.window.removeEventListener("scroll",fe,!0),o.window.removeEventListener("resize",fe),n.triggerButton.removeEventListener("click",Ke),n.addTargetButton.removeEventListener("click",ie),n.reselectButton.removeEventListener("click",Se),n.targetList.removeEventListener("click",Qe),n.targetList.removeEventListener("input",st),n.targetList.removeEventListener("keydown",Ye),n.openEditorButton.removeEventListener("click",Be),n.dataFlowRefreshButton.removeEventListener("click",et),n.previewButton.removeEventListener("click",Xe),n.copyButton.removeEventListener("click",qe),n.backButton.removeEventListener("click",ve),n.closeButton.removeEventListener("click",ke),n.agentProviderSelect.removeEventListener("change",O.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",O.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",O.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",O.consentChanged),n.agentTestButton.removeEventListener("click",O.testCapability),n.agentRunButton.removeEventListener("click",O.run),n.agentCancelButton.removeEventListener("click",O.cancel),n.agentApplyButton.removeEventListener("click",O.apply),n.agentRevertButton.removeEventListener("click",O.revert),n.agentResetButton.removeEventListener("click",O.reset),M!==void 0&&(o.window.cancelAnimationFrame(M),M=void 0),at(),re(),F?.disconnect(),xe?.disconnect(),F=void 0,xe=void 0,b=[],T=void 0,X="",P=void 0,Z=void 0,i.cancelPending(),i.dispose(),O.disposeSelection(),He?.dispose(),z.dispose(),n.dispose(),m=gn}return Object.freeze({mount:ee,dispose:yt,getState:()=>m})}var Po="__spotpatchRuntime__";function yn(e){let t=globalThis;t[Po]?.dispose();let o=Lo(e);t[Po]=o,o.mount()}yn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Oe});
|
|
962
|
+
`)}function Ie(){let a=b.flatMap(p=>{if(!p.element?.isConnected)return[];let y=Vt(p.element,o.window);return y===void 0?[]:[{id:p.id,label:bn(p.element),rect:y,active:p.id===T}]});a.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(a)}function B(a=!1){if(b.length===0)return;n.renderTargets(b.map(k=>({id:k.id,label:k.resolution.react.componentName??(k.element===void 0?k.elementContext?.tagName??"Element":bn(k.element)),source:Ha(k,n.messages().context.sourceUnavailable),canOpenEditor:k.marker!==void 0,status:$a(k),active:k.id===T,instruction:k.instruction})),e.maxTargets),Ie();let p=Ue(),y=Fe(),P=p?.marker!==void 0;a?n.showSelection(y,P,q()):n.updateSelection(y,P,q())}function ee(){if(!q())return;let a=b.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let y=[...p.apiStatus==="failed"?["Source context could not be loaded."]:[],...p.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:p.instruction.trim(),page:p.page,source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:y}});return An({id:u(),locale:n.locale(),createdAt:R(),page:hn(o.document,o.window),targets:a})}function Pe(a){n.showHighlight(Qn(a,o.window),bn(a))}function We(){Q?.isConnected===!0&&Q.focus({preventScroll:!0}),Q=void 0}function at(){for(let a of ge.values())o.window.clearTimeout(a);ge.clear()}function ze(){h+=1,i.cancelPending(),O.disposeSelection(),He?.cancelPending(),at(),F?.disconnect(),b=[],T=void 0,x+=1,I=void 0,G="idle",re=!1,H=!1,W=!1,Z="",n.hideSelection(),n.hideSelectionHighlights(),s.clear(),We()}function De(){m.status==="inspecting"?_({type:"CANCEL"}):m.status==="selected"?_({type:"CLOSE"}):m.status==="previewing"&&(_({type:"BACK"}),_({type:"CLOSE"})),re=!1,ae(),n.hideSelection(),n.hideSelectionHighlights(),We(),n.hideHighlight()}function v(){if(m.status!=="inspecting"||!W||b.length===0){De();return}W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),n.focusTargetInstruction(T),n.announce(n.messages().announcements.addCancelled)}function Ke(){if(m.status==="inspecting"&&W){v();return}if(m.status!=="idle"){De();return}if(b.length>0){re=!0,_({type:"RESTORE"}),H||(O.beginSelection(),H=!0),B(!0),be(),n.focusTargetInstruction(T),ae();return}_({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function J(a=n.messages().announcements.chooseAnother){m.status==="selected"&&(_({type:"RESELECT"}),ze(),n.hideHighlight(),n.announce(a))}function se(){if(m.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}W=!0,_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function fe(){h+=1,at(),F?.disconnect();for(let a of b)a.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),B(),s.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let O=wo({ai:e.ai,api:i,getAnnotation:ee,onApplied:fe,onReselectRequired(){J(n.messages().announcements.reselectAfterChange)},view:n}),He=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?Wt()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,ee,e.sessionToken,o.window):void 0;async function Ee(a,p){let y=a.marker;if(y!==void 0)try{let P=await i.sourceContext({fileId:y.fileId,line:y.line,column:y.column,maxLines:e.budget.maxCodeLines});ye(a,p)&&(a.code=P,a.apiStatus="connected",ae(),B(),n.announce(n.messages().announcements.sourceLoaded))}catch(P){ye(a,p)&&(a.code=void 0,a.apiStatus="failed",ae(),B(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(P instanceof DOMException&&P.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function ve(a,p){let y=a.element;if(y===void 0)return;let P=o.window.setTimeout(()=>{if(ge.delete(a.id),!ye(a,p))return;let k=!1;try{a.elementContext=Jn({element:y,maxCharacters:e.budget.domCharacters})}catch{a.elementContext=void 0,k=!0}try{a.styles=zn({document:o.document,element:y,maxCharacters:e.budget.cssCharacters})}catch{a.styles=Fa,k=!0}a.collectionStatus=k?"failed":"ready",ae(),B(),n.announce(k?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&a.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(a.styles.warnings.length)} warning(s).`)},0);ge.set(a.id,P)}function je(a,p){return p!==void 0?b.find(y=>y.marker?.fileId===p.fileId&&y.marker.line===p.line&&y.marker.column===p.column):b.find(y=>y.element===a)}function ke(a){let p=z.resolve(a),y=mn(p.source),P=je(a,y);if(P!==void 0){T=P.id,W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),be(),n.focusTargetInstruction(P.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){W=!1,_({type:"SELECT"}),n.hideHighlight(),B(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(Q=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,Z="",O.beginSelection(),H=!0),$+=1;let ne={id:`target-${String($)}`,element:a,resolution:p,marker:y,page:hn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:y===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};b.push(ne),T=ne.id,W=!1;let f=h;_({type:"SELECT"}),n.hideHighlight(),F?.observe(a),B(!0),be(),re=!0,n.focusTargetInstruction(ne.id),ve(ne,f),y!==void 0?Ee(ne,f):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function ce(){if(M=void 0,m.status!=="inspecting"||N===void 0)return;let a=pn(o.document,o.window,N.x,N.y);if(_({type:"HOVER"}),a===void 0){n.hideHighlight();return}Pe(a)}function Ve(a){m.status==="inspecting"&&(N={x:a.clientX,y:a.clientY},M??=o.window.requestAnimationFrame(ce))}function $e(a){if(m.status!=="inspecting"||to(a.target))return;a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation();let p=pn(o.document,o.window,a.clientX,a.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}ke(p)}function le(a){if(a.key==="Escape"&&m.status!=="idle"){a.preventDefault(),m.status==="inspecting"&&W?v():m.status==="inspecting"||m.status==="selected"?De():(_({type:"BACK"}),n.focusTargetInstruction(T));return}Xn(a.target)||!Yn(a,e.shortcut,o.window.navigator.userAgent)||(a.preventDefault(),Ke())}function ut(a){if(m.status!=="selected"&&m.status!=="inspecting")return;let p=b.findIndex(k=>k.id===a);if(p<0)return;let[y]=b.splice(p,1);if(y===void 0)return;let P=ge.get(y.id);if(P!==void 0&&(o.window.clearTimeout(P),ge.delete(y.id)),y.element!==void 0&&F?.unobserve(y.element),T===y.id&&(T=b.at(-1)?.id),b.length===0){W=!0,m.status==="selected"&&_({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),I=void 0,G="idle",Te(),s.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}B(),be(),ae(),n.announce(n.messages().announcements.targetRemoved)}function me(){if(m.status==="idle"||b.length===0)return;let a=b.filter(p=>p.element!==void 0&&!p.element.isConnected);if(a.length>0){for(let p of a)p.element!==void 0&&(F?.unobserve(p.element),p.element=void 0);B(),ae(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Ie()}function it(a){let p=a===void 0?Ue():b.find(ne=>ne.id===a);if(m.status!=="selected"||p?.marker===void 0)return;T!==p.id&&(T=p.id,B());let y=p.marker,P=h,k=++S;_({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:y.fileId,line:y.line,column:y.column}).then(()=>{L&&m.status==="selected"&&P===h&&k===S&&T===p.id&&b.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{L&&m.status==="selected"&&P===h&&k===S&&T===p.id&&b.includes(p)&&n.renderEditorStatus("error")})}function st(a){if(m.status!=="selected"||!(a.target instanceof HTMLTextAreaElement))return;let p=a.target.dataset.targetInstructionId,y=b.find(P=>P.id===p);y!==void 0&&(y.instruction=a.target.value,n.updateTargetInstruction(y.id,y.instruction),n.setPreviewEnabled(q()),ae())}function Be(){it()}function Xe(a){e.ai.enabled&&m.status==="selected"&&a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),O.run())}function Ye(){if(m.status!=="selected")return;let a=ee();if(a===void 0){n.announce(n.messages().announcements.completeInstructions);return}Z=c.compose(a),_({type:"PREVIEW"}),n.showPreview(Z),n.focusPrompt()}function qe(){if(m.status!=="previewing"||Z.length===0)return;if(r===void 0){_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let a=h;r.writeText(Z).then(()=>{L&&a===h&&m.status==="previewing"&&(_({type:"COPY_SUCCESS"}),n.focusTargetInstruction(T),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{L&&a===h&&m.status==="previewing"&&(_({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function we(){m.status==="previewing"&&(_({type:"BACK"}),n.focusTargetInstruction(T))}function Ze(){if(!(!L||b.length===0)&&(B(),m.status==="previewing")){let a=ee();a!==void 0&&(Z=c.compose(a),n.showPreview(Z))}}function Qe(a){let p=a.target;if(!(p instanceof Element))return;let y=p.closest("button[data-remove-target-id]");if(y?.dataset.removeTargetId!==void 0){ut(y.dataset.removeTargetId);return}let P=p.closest("button[data-open-target-id]");if(P?.dataset.openTargetId!==void 0){it(P.dataset.openTargetId);return}let ne=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;m.status!=="selected"||ne===void 0||!b.some(f=>f.id===ne)||(T=ne,B(),be(),n.focusTargetInstruction(ne))}function Se(){J()}function et(){be()}function te(){L||(L=!0,He?.mount(),n.renderStatus(m.status),o.document.addEventListener("pointermove",Ve,!0),o.document.addEventListener("click",$e,!0),o.document.addEventListener("keydown",le,!0),o.window.addEventListener("scroll",me,!0),o.window.addEventListener("resize",me),n.triggerButton.addEventListener("click",Ke),n.addTargetButton.addEventListener("click",se),n.reselectButton.addEventListener("click",Se),n.targetList.addEventListener("click",Qe),n.targetList.addEventListener("input",st),n.targetList.addEventListener("keydown",Xe),n.openEditorButton.addEventListener("click",Be),n.dataFlowRefreshButton.addEventListener("click",et),n.previewButton.addEventListener("click",Ye),n.copyButton.addEventListener("click",qe),n.backButton.addEventListener("click",we),n.closeButton.addEventListener("click",De),n.agentProviderSelect.addEventListener("change",O.providerOrModelChanged),n.agentModelSelect.addEventListener("change",O.providerOrModelChanged),n.agentModeSelect.addEventListener("change",O.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",O.consentChanged),n.agentTestButton.addEventListener("click",O.testCapability),n.agentRunButton.addEventListener("click",O.run),n.agentCancelButton.addEventListener("click",O.cancel),n.agentApplyButton.addEventListener("click",O.apply),n.agentRevertButton.addEventListener("click",O.revert),n.agentResetButton.addEventListener("click",O.reset),Ne=n.subscribeLocale(Ze),o.resizeObserver!==void 0&&(F=new o.resizeObserver(me)),o.mutationObserver!==void 0&&(Re=new o.mutationObserver(me),Re.observe(o.document.documentElement,{childList:!0,subtree:!0})),re&&b.length>0&&(_({type:"RESTORE"}),O.beginSelection(),H=!0,B(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function yt(){if(!L){Ne?.(),Ne=void 0,n.dispose(),i.cancelPending(),i.dispose(),O.disposeSelection(),He?.dispose(),z.dispose();return}L=!1,Ne?.(),Ne=void 0,o.document.removeEventListener("pointermove",Ve,!0),o.document.removeEventListener("click",$e,!0),o.document.removeEventListener("keydown",le,!0),o.window.removeEventListener("scroll",me,!0),o.window.removeEventListener("resize",me),n.triggerButton.removeEventListener("click",Ke),n.addTargetButton.removeEventListener("click",se),n.reselectButton.removeEventListener("click",Se),n.targetList.removeEventListener("click",Qe),n.targetList.removeEventListener("input",st),n.targetList.removeEventListener("keydown",Xe),n.openEditorButton.removeEventListener("click",Be),n.dataFlowRefreshButton.removeEventListener("click",et),n.previewButton.removeEventListener("click",Ye),n.copyButton.removeEventListener("click",qe),n.backButton.removeEventListener("click",we),n.closeButton.removeEventListener("click",De),n.agentProviderSelect.removeEventListener("change",O.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",O.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",O.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",O.consentChanged),n.agentTestButton.removeEventListener("click",O.testCapability),n.agentRunButton.removeEventListener("click",O.run),n.agentCancelButton.removeEventListener("click",O.cancel),n.agentApplyButton.removeEventListener("click",O.apply),n.agentRevertButton.removeEventListener("click",O.revert),n.agentResetButton.removeEventListener("click",O.reset),M!==void 0&&(o.window.cancelAnimationFrame(M),M=void 0),at(),ae(),F?.disconnect(),Re?.disconnect(),F=void 0,Re=void 0,b=[],T=void 0,Z="",N=void 0,Q=void 0,i.cancelPending(),i.dispose(),O.disposeSelection(),He?.dispose(),z.dispose(),n.dispose(),m=gn}return Object.freeze({mount:te,dispose:yt,getState:()=>m})}var No="__spotpatchRuntime__";function yn(e){let t=globalThis;t[No]?.dispose();let o=Lo(e);t[No]=o,o.mount()}yn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:X});
|