@spotpatch/vite 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/cli.js +8 -8
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +22 -95
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +23 -103
- package/dist/index.js.map +1 -1
- package/dist/runtime-client.js +15 -15
- package/dist/runtime-contextual-ask-panel.js +12 -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 +5 -5
- package/package.json +6 -6
package/dist/runtime-client.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{createReact18Adapter as ss}from"@spotpatch/react-adapter";var p={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",DATA_FLOW_DISABLED:"DATA_FLOW_DISABLED",DATA_FLOW_SOURCE_STALE:"DATA_FLOW_SOURCE_STALE",DATA_FLOW_ANALYSIS_CANCELLED:"DATA_FLOW_ANALYSIS_CANCELLED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",EXTERNAL_HANDOFF_DISABLED:"EXTERNAL_HANDOFF_DISABLED",EXTERNAL_HANDOFF_UNAVAILABLE:"EXTERNAL_HANDOFF_UNAVAILABLE",HANDOFF_VALIDATION_FAILED:"HANDOFF_VALIDATION_FAILED",HANDOFF_SOURCE_STALE:"HANDOFF_SOURCE_STALE",HANDOFF_NOT_FOUND:"HANDOFF_NOT_FOUND",HANDOFF_EXPIRED:"HANDOFF_EXPIRED",HANDOFF_CURSOR_INVALID:"HANDOFF_CURSOR_INVALID",HANDOFF_RESPONSE_TOO_LARGE:"HANDOFF_RESPONSE_TOO_LARGE",BRIDGE_UNAUTHORIZED:"BRIDGE_UNAUTHORIZED",BRIDGE_PROTOCOL_MISMATCH:"BRIDGE_PROTOCOL_MISMATCH",BRIDGE_BUSY:"BRIDGE_BUSY",EXTERNAL_AGENT_BUSY:"EXTERNAL_AGENT_BUSY",ACTIVE_ADAPTER_CONFLICT:"ACTIVE_ADAPTER_CONFLICT",ACTIVE_ADAPTER_LEASE_INVALID:"ACTIVE_ADAPTER_LEASE_INVALID",ACTIVE_DISPATCH_INVALID:"ACTIVE_DISPATCH_INVALID",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_AMBIGUOUS:"SESSION_AMBIGUOUS",SESSION_CLOSED:"SESSION_CLOSED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"},Hr=Object.freeze(["ASK_DISABLED","ASK_SELECTION_REQUIRED","ASK_SELECTION_STALE","ASK_QUESTION_INVALID","ASK_EXECUTOR_UNAVAILABLE","ASK_TIMEOUT","ASK_CONSENT_REQUIRED","ASK_BUSY","ASK_IDEMPOTENCY_CONFLICT","ASK_SOURCE_SCOPE_DENIED","ASK_LIMIT_EXCEEDED","ASK_ANSWER_INVALID","ASK_WRITE_ATTEMPTED","ASK_CANCELLED","ASK_RESULT_EXPIRED","ASK_PROTOCOL_INCOMPATIBLE"]),$r=Object.freeze(Object.values(p));var Br=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Ur=/blob:[^\s"'<>]+/giu,jr=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,zr=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Vr=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,Wr=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),qr=500;function Gr(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Kr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nn(e){let t=Gr(e);return Wr.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function oe(e){return e.replace(Br,"[redacted inline data]").replace(Ur,"[redacted blob URL]").replace(jr,"Bearer [redacted]").replace(zr,"$1[redacted]@").replace(Vr,(t,o,n,s)=>{let l=s.at(0),a=l==='"'||l==="'"||l==="`";return`${o}${n}${a?l:""}[redacted]${a?l:""}`})}function Jr(e){e.username="",e.password="";for(let[t,o]of e.searchParams)nn(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,oe(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function vt(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=oe(o);try{let s=new URL(n,t),l=Jr(s),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===a.origin?`${s.pathname}${s.search}${s.hash}`:l}catch{return Kr(n,qr)}}var ae="/__spotpatch/v1",on="X-SpotPatch-Token",ht=Object.freeze({bootstrap:`${ae}/bootstrap`,sourceContext:`${ae}/source-context`,openEditor:`${ae}/open-editor`,dataFlowComponentReport:`${ae}/data-flow/component-report`,dataFlowPageReport:`${ae}/data-flow/page-report`,agentCapability:`${ae}/agent/capability`,agentWorkspaceHealth:`${ae}/agent/workspace-health`,agentJobs:`${ae}/agent/jobs`,askCapability:`${ae}/ask/capability`,askJobs:`${ae}/ask/jobs`,externalHandoffCapability:`${ae}/external-handoff/capability`,externalHandoffPublish:`${ae}/external-handoff/publish`,externalHandoffStatus:`${ae}/external-handoff/status`,externalHandoffResolveDelivery:`${ae}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${ae}/external-agent/control/status`,externalAgentControlConnect:`${ae}/external-agent/control/connect`,externalAgentControlDisconnect:`${ae}/external-agent/control/disconnect`,externalAgentControlCancel:`${ae}/external-agent/control/cancel`,externalAgentEvents:`${ae}/external-agent/events`,externalAgentResult:`${ae}/external-agent/result`});function kt(e,t){return`${ht.agentJobs}/${encodeURIComponent(e)}/${t}`}var Xr=Object.freeze(["review","auto","trusted-auto"]),Yr=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),vn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),wn=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Zr=Object.freeze(["ready","consent-required","blocked"]),Qr=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),On=Object.freeze(["added","modified","deleted"]),_n=Object.freeze(["passed","failed","cancelled","timed-out"]);var Ln="data-spotpatch-source",ea=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function kn(e){if(e===null)return;let t=ea.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),s=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)))return Object.freeze({fileId:o,line:n,column:s})}var Pn="https://github.com/huanglvjing/spotpatch";function lo(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function na(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:lo(e.source)}})}function oa(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function ra(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function aa(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:lo(e.source,e.code),react:na(e.react),element:oa(e.element),styles:ra(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function po(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(aa)),createdAt:e.createdAt})}var ia=new Set(Object.values(p)),sa=new Set(wn),ca=new Set(_n),la=new Set(On),go=new Set(vn),da=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,pa=/^[A-Za-z0-9_-]+$/,ua=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){return Object.keys(e).every(o=>t.includes(o))}function Ae(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function jt(e){return Ae(e,64,1)&&typeof e=="string"&&da.test(e)}function In(e){return Ae(e,128,22)&&typeof e=="string"&&pa.test(e)}function zt(e){return typeof e=="string"&&ua.test(e)&&Number.isFinite(Date.parse(e))}function wt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function fo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function uo(e,t){return e===void 0||Ae(e,t)}function Pt(e){return typeof e=="string"&&ia.has(e)}function mo(e){return!yt(e)||!Pe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&sa.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||zt(e.checkedAt))&&(e.errorCode===void 0||Pt(e.errorCode))}function ho(e){if(!yt(e)||!Pe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!zt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Pt(e.errorCode)||!yt(e.changes)||!Pe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:l,total:a}=t;return!wt(o)||!wt(n)||!wt(s)||!wt(l)||!wt(a)||a<o||a<n||a<s||a<l||a>o+n+s?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&l===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function an(e){return!yt(e)||!Pe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&Ae(e.phaseMessage,1024)&&zt(e.createdAt)&&zt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Pt(e.errorCode))}function ga(e){return yt(e)&&Pe(e,["relativePath","kind","additions","deletions"])&&Ae(e.relativePath,1024)&&typeof e.kind=="string"&&la.has(e.kind)&&wt(e.additions)&&wt(e.deletions)}function yo(e){return yt(e)&&Pe(e,["checkId","label","status","durationMs","output"])&&jt(e.checkId)&&Ae(e.label,100)&&typeof e.status=="string"&&ca.has(e.status)&&wt(e.durationMs)&&Ae(e.output,8e4)}function fa(e){return yt(e)&&Pe(e,["jobId","summary","diff","files","checks"])&&In(e.jobId)&&Ae(e.summary,8e4)&&Ae(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ga)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(yo)}function bo(e){return yt(e)&&Pe(e,["snapshot","result"])&&an(e.snapshot)&&(e.result===void 0||fa(e.result)&&e.result.jobId===e.snapshot.jobId)}function ma(e){return yt(e)&&Pe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&fo(e.sequence)&&In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&zt(e.timestamp)&&typeof e.type=="string"&&yt(e.data)}function So(e){if(!ma(e))return!1;let t=e.data;switch(e.type){case"snapshot":return Pe(t,["snapshot"])&&an(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Pe(t,["message"])&&Ae(t.message,1024);case"tool":return Pe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&fo(t.turn)&&Ae(t.toolCallId,256)&&Ae(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&uo(t.relativePath,1024)&&uo(t.checkLabel,100);case"check":return Pe(t,["result"])&&yo(t.result);case"result-ready":return Pe(t,["hasResult"])&&t.hasResult===!0;case"error":return Pe(t,["code","message"])&&Pt(t.code)&&Ae(t.message,1024);default:return!1}}var xo=2e6,Eo=1e5,ha=4e6,J=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ya(e){if(!(!Ie(e)||e.ok!==!1||!Ie(e.error)))return Pt(e.error.code)?e.error.code:void 0}function ba(e){if(!Ie(e)||e.ok!==!0||!("data"in e))throw new J;return e.data}function Sa(e){return Ie(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function Ro(e){if(!(!Ie(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Ro(t);Object.freeze(e)}}function It(e){return Ro(e),e}async function Ea(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new J;if(e.body===null)throw new J;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),l=0,a="";try{for(;;){let d=await n.read();if(d.done)return a+=s.decode(),a;if(l+=d.value.byteLength,l>t)throw await n.cancel(),new J;a+=s.decode(d.value,{stream:!0})}}catch(d){throw d instanceof J?d:new J}finally{n.releaseLock()}}function Co(e){try{return JSON.parse(e)}catch{throw new J}}async function Ao(e,t=xo){let o=Co(await Ea(e,t));if(!e.ok)throw new J(ya(o));return ba(o)}function cn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Aa(e){return Ie(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function xa(e){return Ie(e)&&typeof e.enabled=="boolean"&&(e.staticAnalysis==="available"||e.staticAnalysis==="partial"||e.staticAnalysis==="unavailable")&&e.runtimeObservation==="dispatch-only"&&e.responseShape==="consumed-fields-only"&&e.aiAssistance==="disabled"&&Array.isArray(e.reasons)}function Ra(e){return Ie(e)&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.direction=="string"&&typeof e.execution=="string"&&typeof e.proof=="string"&&typeof e.association=="string"&&Array.isArray(e.parameters)&&Ie(e.response)&&cn(e.response.consumedFields)&&cn(e.evidenceIds)&&cn(e.observationIds)}function To(e){return Ie(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Ie(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&cn(e.baseline.analyzedSourceVersions)&&xa(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(Ra)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&Aa(e.completeness)}function Ca(e){return To(e)&&Ie(e)&&Ie(e.component)&&Ie(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function Ta(e){return To(e)}function va(e,t){if(!mo(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new J;return It(e)}function sn(e,t){if(!an(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new J;return It(e)}function wa(e,t){if(!bo(e)||e.snapshot.jobId!==t)throw new J;return It(e)}function Oa(e){if(!So(e))throw new J;return It(e)}function _a(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function vo(e){return e instanceof J&&Pt(e.code)?e.code:void 0}function wo(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,d,C,x=xo){let w=new AbortController;t.add(w);try{let V=await e.fetch(a,{method:d,headers:{...C===void 0?{}:{"Content-Type":"application/json"},[on]:e.sessionToken},...C===void 0?{}:{body:JSON.stringify(C)},signal:w.signal});return await Ao(V,x)}finally{t.delete(w)}}async function s(a,d){let C=new AbortController;t.add(C);try{let x=await e.fetch(kt(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[on]:e.sessionToken},body:JSON.stringify({}),signal:C.signal});if(!x.ok){await Ao(x);return}if(x.body===null)throw new J;let w=x.body.getReader(),V=new TextDecoder("utf-8",{fatal:!0}),b="",i=0,W=0,H=A=>{if(A.trim().length===0)return;if(new TextEncoder().encode(A).byteLength>Eo)throw new J;let v=Oa(Co(A));if(v.jobId!==a||v.sequence<=W)throw new J;W=v.sequence,d(v)};try{for(;;){let A=await w.read();if(A.done){b+=V.decode(),H(b);return}if(i+=A.value.byteLength,i>ha)throw await w.cancel(),new J;b+=V.decode(A.value,{stream:!0});let v=b.split(`
|
|
2
|
-
`);if(b=v.pop()??"",new TextEncoder().encode(b).byteLength>Eo)throw await w.cancel(),new J;for(let q of v)H(q)}}catch(A){throw A instanceof J||A instanceof DOMException&&A.name==="AbortError"?A:new J}finally{w.releaseLock()}}finally{t.delete(C)}}let l=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let d=await n(ht.sourceContext,"POST",a);if(!Sa(d))throw new J;return Object.freeze({...d})},async componentDataFlowReport(a){let d=await n(ht.dataFlowComponentReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ca(d))throw new J;return It(d)},async pageDataFlowReport(a){let d=await n(ht.dataFlowPageReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ta(d))throw new J;return It(d)},async openEditor(a){let d=await n(ht.openEditor,"POST",a);if(!Ie(d)||d.editor!=="auto"&&d.editor!=="vscode"&&d.editor!=="cursor")throw new J;return Object.freeze({editor:d.editor})},async agentCapability(a){return va(await n(ht.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(ht.agentWorkspaceHealth,"POST",l);if(!ho(a))throw new J;return It(a)},async createAgentJob(a){let d=_a(a);return sn(await n(ht.agentJobs,"POST",d),a)},agentEvents:
|
|
3
|
-
`).length}function Fa(e,t){return e.href===null?void 0:vt(e.href,t)}function ko(e,t,o,n,
|
|
4
|
-
`),e.maxCharacters),...
|
|
1
|
+
import{createReact18Adapter as ss}from"@spotpatch/react-adapter";var p={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",DATA_FLOW_DISABLED:"DATA_FLOW_DISABLED",DATA_FLOW_SOURCE_STALE:"DATA_FLOW_SOURCE_STALE",DATA_FLOW_ANALYSIS_CANCELLED:"DATA_FLOW_ANALYSIS_CANCELLED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",EXTERNAL_HANDOFF_DISABLED:"EXTERNAL_HANDOFF_DISABLED",EXTERNAL_HANDOFF_UNAVAILABLE:"EXTERNAL_HANDOFF_UNAVAILABLE",HANDOFF_VALIDATION_FAILED:"HANDOFF_VALIDATION_FAILED",HANDOFF_SOURCE_STALE:"HANDOFF_SOURCE_STALE",HANDOFF_NOT_FOUND:"HANDOFF_NOT_FOUND",HANDOFF_EXPIRED:"HANDOFF_EXPIRED",HANDOFF_CURSOR_INVALID:"HANDOFF_CURSOR_INVALID",HANDOFF_RESPONSE_TOO_LARGE:"HANDOFF_RESPONSE_TOO_LARGE",BRIDGE_UNAUTHORIZED:"BRIDGE_UNAUTHORIZED",BRIDGE_PROTOCOL_MISMATCH:"BRIDGE_PROTOCOL_MISMATCH",BRIDGE_BUSY:"BRIDGE_BUSY",EXTERNAL_AGENT_BUSY:"EXTERNAL_AGENT_BUSY",ACTIVE_ADAPTER_CONFLICT:"ACTIVE_ADAPTER_CONFLICT",ACTIVE_ADAPTER_LEASE_INVALID:"ACTIVE_ADAPTER_LEASE_INVALID",ACTIVE_DISPATCH_INVALID:"ACTIVE_DISPATCH_INVALID",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_AMBIGUOUS:"SESSION_AMBIGUOUS",SESSION_CLOSED:"SESSION_CLOSED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"},Hr=Object.freeze(["ASK_DISABLED","ASK_SELECTION_REQUIRED","ASK_SELECTION_STALE","ASK_QUESTION_INVALID","ASK_EXECUTOR_UNAVAILABLE","ASK_TIMEOUT","ASK_CONSENT_REQUIRED","ASK_BUSY","ASK_IDEMPOTENCY_CONFLICT","ASK_SOURCE_SCOPE_DENIED","ASK_LIMIT_EXCEEDED","ASK_ANSWER_INVALID","ASK_WRITE_ATTEMPTED","ASK_CANCELLED","ASK_RESULT_EXPIRED","ASK_PROTOCOL_INCOMPATIBLE"]),$r=Object.freeze(Object.values(p));var Br=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,Ur=/blob:[^\s"'<>]+/giu,jr=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,zr=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,Vr=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,Wr=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),qr=500;function Gr(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Kr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nn(e){let t=Gr(e);return Wr.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function oe(e){return e.replace(Br,"[redacted inline data]").replace(Ur,"[redacted blob URL]").replace(jr,"Bearer [redacted]").replace(zr,"$1[redacted]@").replace(Vr,(t,o,n,i)=>{let l=i.at(0),a=l==='"'||l==="'"||l==="`";return`${o}${n}${a?l:""}[redacted]${a?l:""}`})}function Jr(e){e.username="",e.password="";for(let[t,o]of e.searchParams)nn(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,oe(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function vt(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=oe(o);try{let i=new URL(n,t),l=Jr(i),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===a.origin?`${i.pathname}${i.search}${i.hash}`:l}catch{return Kr(n,qr)}}var ae="/__spotpatch/v1",on="X-SpotPatch-Token",ht=Object.freeze({bootstrap:`${ae}/bootstrap`,sourceContext:`${ae}/source-context`,openEditor:`${ae}/open-editor`,dataFlowComponentReport:`${ae}/data-flow/component-report`,dataFlowPageReport:`${ae}/data-flow/page-report`,agentCapability:`${ae}/agent/capability`,agentWorkspaceHealth:`${ae}/agent/workspace-health`,agentJobs:`${ae}/agent/jobs`,askCapability:`${ae}/ask/capability`,askJobs:`${ae}/ask/jobs`,externalHandoffCapability:`${ae}/external-handoff/capability`,externalHandoffPublish:`${ae}/external-handoff/publish`,externalHandoffStatus:`${ae}/external-handoff/status`,externalHandoffResolveDelivery:`${ae}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${ae}/external-agent/control/status`,externalAgentControlConnect:`${ae}/external-agent/control/connect`,externalAgentControlDisconnect:`${ae}/external-agent/control/disconnect`,externalAgentControlCancel:`${ae}/external-agent/control/cancel`,externalAgentEvents:`${ae}/external-agent/events`,externalAgentResult:`${ae}/external-agent/result`});function kt(e,t){return`${ht.agentJobs}/${encodeURIComponent(e)}/${t}`}var Xr=Object.freeze(["review","auto","trusted-auto"]),Yr=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),vn=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),wn=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),Zr=Object.freeze(["ready","consent-required","blocked"]),Qr=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),On=Object.freeze(["added","modified","deleted"]),_n=Object.freeze(["passed","failed","cancelled","timed-out"]);var Ln="data-spotpatch-source",ea=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)(:astro)?$/;function kn(e){if(e===null)return;let t=ea.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,...t[4]===void 0?{}:{kind:"astro"}})}var Pn="https://github.com/huanglvjing/spotpatch";function lo(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function na(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:lo(e.source)}})}function oa(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function ra(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function aa(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:lo(e.source,e.code),react:na(e.react),element:oa(e.element),styles:ra(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function po(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(aa)),createdAt:e.createdAt})}var ia=new Set(Object.values(p)),sa=new Set(wn),ca=new Set(_n),la=new Set(On),go=new Set(vn),da=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,pa=/^[A-Za-z0-9_-]+$/,ua=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){return Object.keys(e).every(o=>t.includes(o))}function Ae(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function jt(e){return Ae(e,64,1)&&typeof e=="string"&&da.test(e)}function In(e){return Ae(e,128,22)&&typeof e=="string"&&pa.test(e)}function zt(e){return typeof e=="string"&&ua.test(e)&&Number.isFinite(Date.parse(e))}function wt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function fo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function uo(e,t){return e===void 0||Ae(e,t)}function Pt(e){return typeof e=="string"&&ia.has(e)}function mo(e){return!yt(e)||!Pe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&sa.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||zt(e.checkedAt))&&(e.errorCode===void 0||Pt(e.errorCode))}function ho(e){if(!yt(e)||!Pe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!zt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!Pt(e.errorCode)||!yt(e.changes)||!Pe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:l,total:a}=t;return!wt(o)||!wt(n)||!wt(i)||!wt(l)||!wt(a)||a<o||a<n||a<i||a<l||a>o+n+i?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&l===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function an(e){return!yt(e)||!Pe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&jt(e.providerProfileId)&&Ae(e.providerLabel,100)&&jt(e.modelProfileId)&&Ae(e.modelLabel,100)&&Ae(e.phaseMessage,1024)&&zt(e.createdAt)&&zt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||Pt(e.errorCode))}function ga(e){return yt(e)&&Pe(e,["relativePath","kind","additions","deletions"])&&Ae(e.relativePath,1024)&&typeof e.kind=="string"&&la.has(e.kind)&&wt(e.additions)&&wt(e.deletions)}function yo(e){return yt(e)&&Pe(e,["checkId","label","status","durationMs","output"])&&jt(e.checkId)&&Ae(e.label,100)&&typeof e.status=="string"&&ca.has(e.status)&&wt(e.durationMs)&&Ae(e.output,8e4)}function fa(e){return yt(e)&&Pe(e,["jobId","summary","diff","files","checks"])&&In(e.jobId)&&Ae(e.summary,8e4)&&Ae(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(ga)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(yo)}function bo(e){return yt(e)&&Pe(e,["snapshot","result"])&&an(e.snapshot)&&(e.result===void 0||fa(e.result)&&e.result.jobId===e.snapshot.jobId)}function ma(e){return yt(e)&&Pe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&fo(e.sequence)&&In(e.jobId)&&typeof e.status=="string"&&go.has(e.status)&&zt(e.timestamp)&&typeof e.type=="string"&&yt(e.data)}function So(e){if(!ma(e))return!1;let t=e.data;switch(e.type){case"snapshot":return Pe(t,["snapshot"])&&an(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return Pe(t,["message"])&&Ae(t.message,1024);case"tool":return Pe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&fo(t.turn)&&Ae(t.toolCallId,256)&&Ae(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&uo(t.relativePath,1024)&&uo(t.checkLabel,100);case"check":return Pe(t,["result"])&&yo(t.result);case"result-ready":return Pe(t,["hasResult"])&&t.hasResult===!0;case"error":return Pe(t,["code","message"])&&Pt(t.code)&&Ae(t.message,1024);default:return!1}}var xo=2e6,Eo=1e5,ha=4e6,J=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ya(e){if(!(!Ie(e)||e.ok!==!1||!Ie(e.error)))return Pt(e.error.code)?e.error.code:void 0}function ba(e){if(!Ie(e)||e.ok!==!0||!("data"in e))throw new J;return e.data}function Sa(e){return Ie(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx"||e.language==="astro")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function Ro(e){if(!(!Ie(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))Ro(t);Object.freeze(e)}}function It(e){return Ro(e),e}async function Ea(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new J;if(e.body===null)throw new J;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),l=0,a="";try{for(;;){let d=await n.read();if(d.done)return a+=i.decode(),a;if(l+=d.value.byteLength,l>t)throw await n.cancel(),new J;a+=i.decode(d.value,{stream:!0})}}catch(d){throw d instanceof J?d:new J}finally{n.releaseLock()}}function Co(e){try{return JSON.parse(e)}catch{throw new J}}async function Ao(e,t=xo){let o=Co(await Ea(e,t));if(!e.ok)throw new J(ya(o));return ba(o)}function cn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Aa(e){return Ie(e)&&typeof e.complete=="boolean"&&typeof e.visitedModules=="number"&&typeof e.visitedCallsites=="number"&&typeof e.frontierCount=="number"}function xa(e){return Ie(e)&&typeof e.enabled=="boolean"&&(e.staticAnalysis==="available"||e.staticAnalysis==="partial"||e.staticAnalysis==="unavailable")&&e.runtimeObservation==="dispatch-only"&&e.responseShape==="consumed-fields-only"&&e.aiAssistance==="disabled"&&Array.isArray(e.reasons)}function Ra(e){return Ie(e)&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.direction=="string"&&typeof e.execution=="string"&&typeof e.proof=="string"&&typeof e.association=="string"&&Array.isArray(e.parameters)&&Ie(e.response)&&cn(e.response.consumedFields)&&cn(e.evidenceIds)&&cn(e.observationIds)}function To(e){return Ie(e)&&e.schemaVersion===1&&typeof e.reportId=="string"&&Ie(e.baseline)&&typeof e.baseline.registryEpoch=="string"&&typeof e.baseline.analyzerVersion=="string"&&cn(e.baseline.analyzedSourceVersions)&&xa(e.capability)&&Array.isArray(e.dependencies)&&e.dependencies.every(Ra)&&Array.isArray(e.evidence)&&Array.isArray(e.diagnostics)&&Aa(e.completeness)}function Ca(e){return To(e)&&Ie(e)&&Ie(e.component)&&Ie(e.component.source)&&typeof e.component.source.fileId=="string"&&typeof e.component.source.sourceVersion=="string"}function Ta(e){return To(e)}function va(e,t){if(!mo(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new J;return It(e)}function sn(e,t){if(!an(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new J;return It(e)}function wa(e,t){if(!bo(e)||e.snapshot.jobId!==t)throw new J;return It(e)}function Oa(e){if(!So(e))throw new J;return It(e)}function _a(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function vo(e){return e instanceof J&&Pt(e.code)?e.code:void 0}function wo(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,d,C,x=xo){let w=new AbortController;t.add(w);try{let V=await e.fetch(a,{method:d,headers:{...C===void 0?{}:{"Content-Type":"application/json"},[on]:e.sessionToken},...C===void 0?{}:{body:JSON.stringify(C)},signal:w.signal});return await Ao(V,x)}finally{t.delete(w)}}async function i(a,d){let C=new AbortController;t.add(C);try{let x=await e.fetch(kt(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[on]:e.sessionToken},body:JSON.stringify({}),signal:C.signal});if(!x.ok){await Ao(x);return}if(x.body===null)throw new J;let w=x.body.getReader(),V=new TextDecoder("utf-8",{fatal:!0}),b="",s=0,W=0,H=A=>{if(A.trim().length===0)return;if(new TextEncoder().encode(A).byteLength>Eo)throw new J;let v=Oa(Co(A));if(v.jobId!==a||v.sequence<=W)throw new J;W=v.sequence,d(v)};try{for(;;){let A=await w.read();if(A.done){b+=V.decode(),H(b);return}if(s+=A.value.byteLength,s>ha)throw await w.cancel(),new J;b+=V.decode(A.value,{stream:!0});let v=b.split(`
|
|
2
|
+
`);if(b=v.pop()??"",new TextEncoder().encode(b).byteLength>Eo)throw await w.cancel(),new J;for(let q of v)H(q)}}catch(A){throw A instanceof J||A instanceof DOMException&&A.name==="AbortError"?A:new J}finally{w.releaseLock()}}finally{t.delete(C)}}let l=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let d=await n(ht.sourceContext,"POST",a);if(!Sa(d))throw new J;return Object.freeze({...d})},async componentDataFlowReport(a){let d=await n(ht.dataFlowComponentReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ca(d))throw new J;return It(d)},async pageDataFlowReport(a){let d=await n(ht.dataFlowPageReport,"POST",a,e.dataFlowReportMaxBytes);if(!Ta(d))throw new J;return It(d)},async openEditor(a){let d=await n(ht.openEditor,"POST",a);if(!Ie(d)||d.editor!=="auto"&&d.editor!=="vscode"&&d.editor!=="cursor")throw new J;return Object.freeze({editor:d.editor})},async agentCapability(a){return va(await n(ht.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(ht.agentWorkspaceHealth,"POST",l);if(!ho(a))throw new J;return It(a)},async createAgentJob(a){let d=_a(a);return sn(await n(ht.agentJobs,"POST",d),a)},agentEvents:i,async agentResult(a){return wa(await n(kt(a,"result"),"POST",l),a)},async cancelAgentJob(a){return sn(await n(kt(a,"cancel"),"POST",l),{jobId:a})},async applyAgentJob(a){return sn(await n(kt(a,"apply"),"POST",l),{jobId:a})},async revertAgentJob(a){return sn(await n(kt(a,"revert"),"POST",l),{jobId:a})},dispose(){o()}})}var La=500,Oo=256;function ka(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Pa(e){return nn(e)}function _o(e,t,o){if(!Pa(e))return e==="href"||e==="src"?vt(t,o):e==="d"&&t.length>Oo?`${t.slice(0,Oo)}…`:ka(oe(t),La)}function Be(e){return oe(e)}var Lo=Object.freeze(["display","position","inset","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height","margin","padding","box-sizing","overflow","overflow-x","overflow-y","flex","flex-direction","flex-wrap","align-items","align-content","justify-content","gap","grid-template-columns","grid-template-rows","font-family","font-size","font-weight","line-height","text-align","white-space","color","background-color","border","border-radius","opacity","visibility","z-index","transform"]);var Vt=Object.freeze({cascade:"CSS shorthand and longhand cascade resolution is not available in v1.",cssInJs:"Runtime CSS-in-JS rules may not include original TypeScript source locations.",inaccessibleStylesheet:"A stylesheet could not be inspected because browser security denied access.",selector:"A stylesheet selector could not be evaluated and was skipped.",state:"Dynamic pseudo-class and pseudo-element rules may be unavailable in the current state."});function Ia(e){return"selectorText"in e&&"style"in e}function Na(e){return"cssRules"in e}function Da(e){if(typeof e.conditionText=="string"&&e.conditionText.length>0)return e.conditionText;let t=e.cssText.indexOf("{"),o=t<0?"":e.cssText.slice(0,t).trim();return o.length===0?void 0:o}function Ma(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((l,a)=>l+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((l,[a,d])=>l+a.length+d.length,0)+i.join(`
|
|
3
|
+
`).length}function Fa(e,t){return e.href===null?void 0:vt(e.href,t)}function ko(e,t,o,n,i,l){for(let a of t){if(Ia(a)){let d=!1;try{d=e.matches(a.selectorText)}catch{l.add(Vt.selector);continue}d&&i.push(Object.freeze({selector:Be(a.selectorText),declarations:Be(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(Na(a)){let d=Da(a);ko(e,a.cssRules,o,d===void 0?n:[...n,d],i,l)}}}function Ha(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of Lo){let l=Be(o.getPropertyValue(i).trim());l.length>0&&(n[i]=l)}return n}function Po(e){let t=new Set([Vt.state,Vt.cssInJs,Vt.cascade]),o=[],n=e.readCssRules??(w=>w.cssRules);for(let w of e.document.styleSheets){let V;try{V=n(w)}catch{t.add(Vt.inaccessibleStylesheet);continue}ko(e.element,V,Fa(w,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),l=e.element.getAttribute("style"),a=l===null?void 0:Be(l),d=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),C=Object.entries(Ha(e.element,d)),x=Array.from(t);for(;Ma(i,a,o,Object.fromEntries(C),x)>e.maxCharacters;){if(C.length>0){C.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(C)),warnings:Object.freeze(x)})}var Ot=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),$a=new Set(["alt","autocomplete","checked","class","colspan","contenteditable","d","disabled","download","draggable","for","height","hidden","href","id","max","maxlength","min","minlength","multiple","name","open","pattern","placeholder","readonly","rel","required","role","rowspan","selected","src","step","style","tabindex","target","title","type","width"]),Ba=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function No(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function Ua(e){return $a.has(e)||e.startsWith("aria-")||e==="data-testid"}function Do(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let l=i.name.toLowerCase();if(!Ua(l))continue;let a=_o(l,i.value,n);a!==void 0&&o.push(`${l}="${No(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Mo(e){return oe(e).replaceAll(/\s+/gu," ").trim()}function Fo(e,t,o,n){if(o.nodeCount>=Ot.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),l=e.tagName.toLowerCase();if(n.push(`${i}${Do(e)}`),!Ba.has(l)){for(let a of e.childNodes){if(o.nodeCount>=Ot.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let d=Mo(a.textContent??"");if(d.length>0){o.nodeCount+=1;let C=d.length<=Ot.maxTextCharacters?d:`${d.slice(0,Ot.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${No(C)}`)}continue}if(a.nodeType===1){if(t>=Ot.maxDepth){o.truncated=!0;continue}Fo(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${l}>`)}}function ja(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<Ot.maxParentDepth;)t.push(Do(o)),o=o.parentElement;return t}function za(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Io(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function Va(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Wa(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Io(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${Va(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(d=>`.${Io(d)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(d=>d.tagName===e.tagName),l=i.indexOf(e),a=i.length>1&&l>=0?`:nth-of-type(${String(l+1)})`:"";return`${t}${n}${a}`}function qa(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=Wa(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function Ho(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};Fo(e.element,0,o,t);let n=ja(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=Mo(e.element.textContent),l=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:qa(e.element),sanitizedHtml:za(t.join(`
|
|
4
|
+
`),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=Ot.maxTextCharacters?i:`${i.slice(0,Ot.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:l.x,y:l.y,width:l.width,height:l.height})})}function $o(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function Ga(e){return e.toLowerCase()}function Bo(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Uo(e,t,o){let n=t.split("+").map(w=>w.trim().toLowerCase()).filter(w=>w.length>0),i=n.find(w=>w!=="mod"&&w!=="meta"&&w!=="ctrl"&&w!=="control"&&w!=="alt"&&w!=="option"&&w!=="shift");if(i===void 0||Ga(e.key)!==i)return!1;let l=n.includes("mod"),a=n.includes("meta")||l&&$o(o),d=n.includes("ctrl")||n.includes("control")||l&&!$o(o),C=n.includes("alt")||n.includes("option"),x=n.includes("shift");return e.metaKey===a&&e.ctrlKey===d&&e.altKey===C&&e.shiftKey===x}function Ka(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function Ja(e){let t=e.filter(d=>d.width>0&&d.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,l=o.right,a=o.bottom;for(let d of t.slice(1))n=Math.min(n,d.left),i=Math.min(i,d.top),l=Math.max(l,d.right),a=Math.max(a,d.bottom);return Object.freeze({x:n,y:i,width:l-n,height:a-i})}function jo(e,t){if(t.startsWith("inline")){let o=Ja(Array.from(e.getClientRects()));if(o!==void 0)return o}return Ka(e.getBoundingClientRect())}function zo(e,t){return jo(e,t.getComputedStyle(e).display)}function dn(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=jo(e,o.display);return n.width>0&&n.height>0?n:void 0}var Nt="data-spotpatch-ui",pn=Object.freeze({highlight:2147483646,controls:2147483647}),_t=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function Vo(e){if(e.closest(`[${Nt}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(Nt)}function Xa(e,t){return dn(e,t)!==void 0}function Ya(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Nn(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(l=>!Vo(l)&&Xa(l,t));return i.find(l=>!Ya(l))??i[0]}function Wo(e){return e instanceof Element&&Vo(e)}var Dn=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function Za(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function un(e,t){let o="`".repeat(Math.max(3,Za(t)+1));return`${o}${e}
|
|
5
5
|
${t}
|
|
6
|
-
${o}`}function Go(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,
|
|
6
|
+
${o}`}function Go(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${oe(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function Ko(e,t){return e.split(`
|
|
7
7
|
`).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Qa(e){let t=[e.source===void 0?void 0:`/* source: ${Be(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Be(e.media)} */`].filter(n=>n!==void 0),o=`${Be(e.selector)} {
|
|
8
8
|
${Be(e.declarations)}
|
|
9
9
|
}`;return[...t,o].join(`
|
|
10
|
-
`)}function ei(e,t,o){let
|
|
10
|
+
`)}function ei(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Be).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Be(e.styles.inlineStyle)} */`].filter(l=>l!==void 0),...t.map(Qa)];return i.length===0?o.unavailable:un("css",i.join(`
|
|
11
11
|
|
|
12
12
|
`))}function ti(e,t){return e.length===0?t.unavailable:un("css",e.map(([o,n])=>`${Be(o)}: ${Be(n)};`).join(`
|
|
13
|
-
`))}function ni(e,t,o,n){let
|
|
13
|
+
`))}function ni(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${oe(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${oe(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(oe).join(" > ")}`]],l=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
|
|
14
14
|
|
|
15
15
|
${un(e.code.language,oe(t.codeLines.join(`
|
|
16
16
|
`)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${vt(e.page.url,e.page.url)}>
|
|
17
17
|
- ${n.pathname}: ${oe(e.page.pathname)}
|
|
18
|
-
- ${n.title}: ${oe(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,
|
|
18
|
+
- ${n.title}: ${oe(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,i.join(`
|
|
19
19
|
`),`#### ${n.source}`,`- ${n.file}: ${Go(e,n)}
|
|
20
20
|
- ${n.origin}: ${e.source.origin}
|
|
21
21
|
- ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,un("html",oe(t.dom)),`#### ${n.styles}`,ei(e,t.matchedRules,n),`#### ${n.computedStyles}`,ti(t.computedEntries,n),`#### ${n.code}`,l,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${oe(a)}`).join(`
|
|
@@ -25,16 +25,16 @@ ${un(e.code.language,oe(t.codeLines.join(`
|
|
|
25
25
|
- ${n.pathname}: ${oe(e.page.pathname)}
|
|
26
26
|
- ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
|
|
27
27
|
- ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
|
|
28
|
-
- ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((
|
|
28
|
+
- ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((i,l)=>{let a=t.targets[l];if(a===void 0)throw new RangeError("Prompt target draft is missing.");return ni(i,a,l,n)}).join(`
|
|
29
29
|
|
|
30
30
|
`),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
|
|
31
31
|
|
|
32
|
-
`)}function oi(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let a=t.codeLines[0]??"";return a.length<=120?t.codeLines=[]:t.codeLines=[`${a.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),
|
|
32
|
+
`)}function oi(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let a=t.codeLines[0]??"";return a.length<=120?t.codeLines=[]:t.codeLines=[`${a.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function ri(e){return{instruction:oe(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function ai(e){return{pageTitle:oe(e.page.title),targets:e.targets.map(ri)}}function ii(e,t,o){let n=Dn[e.locale],i=[(l,a)=>a.computedEntries.pop()!==void 0,(l,a)=>a.reactStack.pop()!==void 0,(l,a)=>{let d=Ko(a.dom,n.unavailable);return a.dom===d?!1:(a.dom=d,!0)},(l,a)=>a.matchedRules.shift()!==void 0,oi,(l,a)=>a.warnings.pop()!==void 0];for(let l of i)for(let a=0;a<e.targets.length;a+=1){let d=(o+a)%e.targets.length,C=e.targets[d],x=t.targets[d];if(C!==void 0&&x!==void 0&&l(C,x))return(d+1)%e.targets.length}}function si(e,t){let o=Dn[e.locale],n=e.targets.map((i,l)=>{let a=t.targets[l],d=i.react.componentName;return[`### ${o.target(l+1)}`,`- ${o.requestedChange}: ${a?.instruction??oe(i.instruction)}`,`- ${o.file}: ${Go(i,o)}`,...d===void 0?[]:[`- ${o.component}: ${oe(d)}`],`- ${o.element}: ${oe(Ko(a?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
|
|
33
33
|
`)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
|
|
34
34
|
|
|
35
35
|
`),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
|
|
36
36
|
|
|
37
|
-
`)}function ci(e,t){let o=ai(e),n=qo(e,o),
|
|
37
|
+
`)}function ci(e,t){let o=ai(e),n=qo(e,o),i=0;for(;n.length>t;){let a=ii(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=qo(e,o)}if(n.length<=t)return n;let l=si(e,o);if(l.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return l}function Jo(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return ci(t,e.maxCharacters)}})}var Te=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Mn=Te.idle;function li(e){return e.type==="ACTIVATE"?Te.inspecting:e.type==="RESTORE"?Te.selected:Te.idle}function di(e){switch(e.type){case"HOVER":return Te.inspecting;case"SELECT":return Te.selected;case"CANCEL":return Te.idle;default:return Te.inspecting}}function pi(e){switch(e.type){case"RESELECT":return Te.inspecting;case"CLOSE":return Te.idle;case"PREVIEW":return Te.previewing;case"OPEN_EDITOR":return Te.selected;default:return Te.selected}}function ui(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return Te.selected;case"COPY_FAILURE":return Te.previewing;default:return Te.previewing}}function Xo(e,t){switch(e.status){case"idle":return li(t);case"inspecting":return di(t);case"selected":return pi(t);case"previewing":return ui(t)}}var gi="spotpatch:selection:";function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ge(e){return typeof e=="string"}function At(e){return e===void 0||ge(e)}function Fn(e){return Array.isArray(e)&&e.length<=256&&e.every(ge)}function bt(e){return typeof e=="number"&&Number.isFinite(e)}function Yo(e){return e===void 0||bt(e)}function Zo(e){let t=it(e);return t!==void 0&&ge(t.origin)&&ge(t.confidence)&&At(t.fileId)&&At(t.relativePath)&&Yo(t.line)&&Yo(t.column)}function fi(e){let t=it(e);return t!==void 0&&typeof t.supported=="boolean"&&At(t.version)&&At(t.componentName)&&Fn(t.componentStack)&&(t.source===void 0||Zo(t.source))}function mi(e){let t=it(e);return t!==void 0&&ge(t.url)&&ge(t.pathname)&&ge(t.title)&&bt(t.viewportWidth)&&bt(t.viewportHeight)&&bt(t.devicePixelRatio)}function hi(e){let t=it(e),o=it(t?.rect);return t!==void 0&&ge(t.tagName)&&ge(t.selector)&&ge(t.sanitizedHtml)&&At(t.textPreview)&&At(t.role)&&o!==void 0&&bt(o.x)&&bt(o.y)&&bt(o.width)&&bt(o.height)}function yi(e){let t=it(e),o=it(t?.computed);return t!==void 0&&Fn(t.classNames)&&At(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let i=it(n);return i!==void 0&&ge(i.selector)&&ge(i.declarations)&&At(i.source)&&At(i.media)})&&o!==void 0&&Object.values(o).every(ge)&&Fn(t.warnings)}function bi(e){let t=it(e);return t!==void 0&&ge(t.relativePath)&&ge(t.language)&&bt(t.startLine)&&bt(t.endLine)&&ge(t.excerpt)&&ge(t.boundary)}function Si(e){let t=it(e);return t!==void 0&&ge(t.id)&&ge(t.instruction)&&mi(t.page)&&Zo(t.source)&&fi(t.react)&&hi(t.element)&&yi(t.styles)&&(t.code===void 0||bi(t.code))}function Ei(e,t){let o=it(e);if(o?.version!==1||typeof o.open!="boolean"||!Number.isSafeInteger(o.sequence)||Number(o.sequence)<0||o.activeTargetId!==void 0&&typeof o.activeTargetId!="string"||!Array.isArray(o.targets)||o.targets.length===0||o.targets.length>t||!o.targets.every(Si))return;let n=o.targets,i=n.map(({id:l})=>l);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 Qo(e,t,o){let n=`${gi}${t}`,i;try{i=e.sessionStorage}catch{i=void 0}return Object.freeze({clear(){try{i?.removeItem(n)}catch{}},load(){let l;try{l=i?.getItem(n)??null}catch{return}if(!(l===null||l.length>1e6))try{return Ei(JSON.parse(l),o)}catch{return}},save(l){try{i?.setItem(n,JSON.stringify({version:1,...l}))}catch{}}})}var er=Object.freeze({supported:!1,componentStack:Object.freeze([])});function nr(e){return kn(e.getAttribute(Ln))}function Ai(e){let t=e.parentElement;for(;t!==null;){let o=nr(t);if(o!==void 0)return o;t=t.parentElement}}function tr(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function xi(){return Object.freeze({origin:"none",confidence:"unknown"})}function Hn(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function or(e){let t=!0;function o(n){if(!t)return er;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),er}}return Object.freeze({resolve(n){let i=nr(n),l=o(n);if(i!==void 0)return Object.freeze({react:l,source:tr(i,i.kind==="astro"?"astro-host":"jsx-host","exact")});if(l.source!==void 0)return Object.freeze({react:l,source:l.source});let a=Ai(n);return Object.freeze(a!==void 0?{react:l,source:tr(a,"dom-ancestor","approximate")}:{react:l,source:xi()})},dispose(){t=!1,e.adapter.dispose()}})}function g(e,t){let o=e.createElement(t);return o.setAttribute(Nt,""),o}function ie(e,t,o=""){let n=g(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var rr=`
|
|
38
38
|
.spotpatch-agent {
|
|
39
39
|
margin-top: 10px;
|
|
40
40
|
overflow: hidden;
|
|
@@ -253,7 +253,7 @@ ${un(e.code.language,oe(t.codeLines.join(`
|
|
|
253
253
|
.spotpatch-agent-selectors { grid-template-columns: 1fr; }
|
|
254
254
|
.spotpatch-agent-mode { grid-column: auto; }
|
|
255
255
|
}
|
|
256
|
-
`;function Wt(e,t,o,n){let s=e.createElement("option");return s.value=o,s.textContent=n,t.append(s),s}function ar(e,t,o){let n=o.messages(),s=g(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let l=g(e,"div");l.className="spotpatch-agent-head",l.setAttribute("data-spotpatch-agent-identity","");let a=g(e,"span");a.className="spotpatch-agent-title";let d=g(e,"span");d.className="spotpatch-agent-badge",l.append(a,d);let C=g(e,"div");C.className="spotpatch-agent-setup";let x=g(e,"div");x.className="spotpatch-agent-selectors";let w=g(e,"label");w.className="spotpatch-agent-mode";let V=g(e,"span"),b=g(e,"select");w.append(V,b);let i=g(e,"label"),W=g(e,"span"),H=g(e,"select");i.append(W,H);let A=g(e,"label"),v=g(e,"span"),q=g(e,"select");A.append(v,q),x.append(w,i,A);let B=g(e,"label");B.className="spotpatch-consent";let I=g(e,"input");I.type="checkbox";let y=g(e,"span");B.append(I,y);let R=g(e,"label");R.className="spotpatch-consent spotpatch-workspace-consent",R.hidden=!0;let L=g(e,"input");L.type="checkbox";let M=g(e,"span"),K=g(e,"strong"),E=g(e,"small");M.append(K,E),R.append(L,M);let T=g(e,"div");T.className="spotpatch-agent-health-list";let O=g(e,"p");O.className="spotpatch-agent-workspace",O.dataset.state="idle";let _=g(e,"p");_.className="spotpatch-agent-capability",_.dataset.state="idle",T.append(O,_),C.append(x,B,R,T);let pe=g(e,"div");pe.className="spotpatch-agent-job",pe.hidden=!0;let ve=g(e,"div");ve.className="spotpatch-agent-job-meta";let D=g(e,"span");D.className="spotpatch-agent-model";let N=g(e,"span");N.className="spotpatch-agent-status",ve.append(D,N);let le=g(e,"p");le.className="spotpatch-agent-phase";let ye=g(e,"p");ye.className="spotpatch-agent-error",ye.hidden=!0;let be=g(e,"ul");be.className="spotpatch-agent-activity";let te=g(e,"div");te.className="spotpatch-agent-result",te.hidden=!0;let st=g(e,"p");st.className="spotpatch-agent-summary";let se=g(e,"ul");se.className="spotpatch-agent-files";let Ue=g(e,"div");Ue.className="spotpatch-agent-checks";let xe=g(e,"pre");xe.className="spotpatch-agent-diff",xe.tabIndex=0,xe.setAttribute("aria-label",n.agent.diffAriaLabel),te.append(st,se,Ue,xe),pe.append(ve,le,ye,be,te),s.append(l,C,pe);let tt=ie(e,n.agent.testConnection),qe=ie(e,n.agent.run,"spotpatch-run"),Ge=ie(e,n.agent.cancel),ee=ie(e,n.agent.apply,"spotpatch-primary"),de=ie(e,n.agent.revert),Ne=ie(e,n.agent.revise),nt=t.enabled?t.providers:[],Ke=t.enabled&&t.applyMode==="trusted-auto",ct=t.enabled?t.applyMode:"review",ot=new Map(nt.map(m=>[m.id,m])),lt=!1,De=!0,ne=!1,Re=!1,Je=!1,U=!1,je,Ce,St=[],Xe,fe="idle",Ye=n.agent.connectionNotTested,Ze,Se="idle",we,ze;for(let m of nt)Wt(e,H,m.id,m.label);t.enabled&&(H.value=t.defaultProvider);let Rt,Ve,We;ct==="auto"?We=Wt(e,b,"auto",n.agent.autoGated):(Rt=Wt(e,b,"review",n.agent.review),Ke&&(Ve=Wt(e,b,"trusted-auto",n.agent.trustedFast)));let dt=Ke?"review":ct;b.value=dt,w.hidden=!Ke;let P=()=>b.value==="trusted-auto"?"trusted-auto":dt,rt=()=>P()==="trusted-auto",Z=()=>ot.get(H.value),Y=m=>m===void 0?n.agent.providerUnavailable:rt()?n.agent.trustedFastConsent(m.label):n.agent.consent(m.label),Me=()=>rt()?I.checked:L.checked,pt=()=>{let m=rt();B.classList.toggle("spotpatch-trusted-consent",m),d.textContent=m?n.agent.trustedFast:ct==="auto"?n.agent.autoGated:n.agent.review,y.textContent=Y(Z()),R.hidden=m||Se!=="consent-required"},Fe=()=>{let m=Z();if(q.replaceChildren(),m===void 0){y.textContent=Y(m);return}for(let F of m.models)Wt(e,q,F.id,F.label);q.value=m.defaultModel,y.textContent=Y(m)},re=()=>{let m=t.enabled&&ne&&!Re;qe.textContent=Je?n.agent.verifying:n.agent.run,qe.classList.toggle("spotpatch-primary",U),tt.hidden=!m,qe.hidden=!m,tt.disabled=!De||Je||Z()===void 0,qe.disabled=!De||Je||!lt||!I.checked||Se==="idle"||Se==="checking"||Se==="blocked"||Se==="consent-required"&&!Me()||Z()===void 0||q.value.length===0,(!Re||!ne)&&(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},Oe=()=>{if(Se==="idle")O.textContent=n.agent.workspaceNotChecked;else if(Se==="checking")O.textContent=n.agent.checkingWorkspace;else if(Se==="ready")O.textContent=n.agent.workspaceReady;else if(Se==="consent-required"){let m=we?.changes;O.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else O.textContent=ze===void 0?n.errors.INTERNAL_ERROR:n.errors[ze]};function He(){Fe(),I.checked=!1,_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function at(){_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function c(){I.checked=!1,L.checked=!1,pt(),re()}Fe(),b.addEventListener("change",c),H.addEventListener("change",He),q.addEventListener("change",at),I.addEventListener("change",re),L.addEventListener("change",re);function u(){if(je===void 0)return;let m=je,F=Ce;D.textContent=`${m.providerLabel} · ${m.modelLabel}`,N.textContent=n.agent.status(m.status),le.textContent=m.phaseMessage;let G=Xe??m.errorCode;ye.hidden=G===void 0,ye.textContent=G===void 0?"":n.errors[G],be.replaceChildren();for(let Q of St.slice(-8)){let _e=g(e,"li");_e.dataset.state=Q.state,_e.textContent=Q.label,be.append(_e)}te.hidden=F===void 0,st.textContent=F?.summary??"",se.replaceChildren(),Ue.replaceChildren(),xe.textContent=F?.diff??"";for(let Q of F?.files??[]){let _e=g(e,"li");_e.textContent=`${Q.kind} ${Q.relativePath} (+${String(Q.additions)} / -${String(Q.deletions)})`,se.append(_e)}for(let Q of F?.checks??[]){let _e=g(e,"details"),Ft=g(e,"summary");Ft.textContent=`${Q.label}: ${Q.status} · ${String(Q.durationMs)} ms`;let Qe=g(e,"pre");Qe.textContent=Q.output.length===0?n.agent.noOutput:Q.output,_e.append(Ft,Qe),Ue.append(_e)}tt.hidden=!0,qe.hidden=!0,Ge.hidden=!ne||!m.canCancel,Ge.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ee.hidden=!ne||!m.canApply,de.hidden=!ne||!m.canRevert,Ne.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function S(){n=o.messages(),a.textContent=n.agent.title,V.textContent=n.agent.mode,Rt!==void 0&&(Rt.textContent=n.agent.review),Ve!==void 0&&(Ve.textContent=n.agent.trustedFast),We!==void 0&&(We.textContent=n.agent.autoGated),W.textContent=n.agent.provider,v.textContent=n.agent.model,H.setAttribute("aria-label",n.agent.providerAriaLabel),q.setAttribute("aria-label",n.agent.modelAriaLabel),K.textContent=n.agent.includeLocalChanges,E.textContent=n.agent.includeLocalChangesHelp,xe.setAttribute("aria-label",n.agent.diffAriaLabel),tt.textContent=n.agent.testConnection,ee.textContent=n.agent.apply,de.textContent=n.agent.revert,Ne.textContent=n.agent.revise,pt(),fe==="idle"?_.textContent=n.agent.connectionNotTested:fe==="probing"?_.textContent=n.agent.testingCapability:fe==="ready"?_.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ze!==void 0?_.textContent=n.errors[Ze]:Z()===void 0?_.textContent=n.agent.providerUnavailable:_.textContent=Ye,Oe(),re(),u()}let $=o.subscribe(S);return S(),Object.freeze({root:s,modeSelect:b,providerSelect:H,modelSelect:q,consentCheckbox:I,workspaceConsentCheckbox:L,testButton:tt,runButton:qe,cancelButton:Ge,applyButton:ee,revertButton:de,resetButton:Ne,consentGranted(){return I.checked},workspaceConsentGranted(){return Me()},readSelection(){let m=Z(),F=m?.models.find(G=>G.id===q.value);return m===void 0||F===void 0?void 0:Object.freeze({applyMode:P(),providerProfileId:m.id,modelProfileId:F.id})},renderCapability(m,F,G,Q){fe=m,Ye=F,Ze=Q,Je=m==="probing",U=m==="ready"&&G?.state==="agent-ready",_.dataset.state=m,_.textContent=G?.state==="agent-ready"?`${F} · ${n.agent.toolsReady}`:F,re()},renderWorkspaceHealth(m,F,G){Se=m,we=F,ze=G??F?.errorCode,O.dataset.state=m,m!=="checking"&&(R.hidden=rt()||m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(L.checked=!1),Oe(),re()},renderJob(m,F,G,Q){Re=!0,C.hidden=!0,pe.hidden=!1,H.disabled=!0,q.disabled=!0,b.disabled=!0,I.disabled=!0,L.disabled=!0,je=m,Ce=F,St=G,Xe=Q,u()},resetJob(){Re=!1,je=void 0,Ce=void 0,St=[],Xe=void 0,C.hidden=!1,pe.hidden=!0,H.disabled=!1,q.disabled=!1,b.disabled=!1,I.disabled=!1,L.disabled=!1,be.replaceChildren(),se.replaceChildren(),Ue.replaceChildren(),xe.textContent="",ye.textContent="",ye.hidden=!0,re()},setContextReady(m){lt=m,re()},setEditingEnabled(m){De=m,H.disabled=!m||Re,q.disabled=!m||Re,b.disabled=!m||Re,I.disabled=!m||Re,L.disabled=!m||Re,re()},setProviderConsent(m){I.checked=m,re()},setSelectionVisible(m){ne=m,re(),m||(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},dispose(){$(),H.removeEventListener("change",He),q.removeEventListener("change",at),b.removeEventListener("change",c),I.removeEventListener("change",re),L.removeEventListener("change",re)}})}var ir="http://www.w3.org/2000/svg",Ri="";function Ci(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Ri,viewBox:"0 0 1 1"}}function Ti(e,t,o){let n=e.createElementNS(ir,t);for(let[s,l]of Object.entries(o))n.setAttribute(s,l);return n}function vi(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/gu,"-"),n=new Map;for(let s of e.querySelectorAll("[id]")){let l=s.id,a=`${o}-${l}`;n.set(l,a),s.id=a}for(let s of[e,...e.querySelectorAll("*")])for(let l of[...s.attributes]){let a=l.value;for(let[d,C]of n)a=a.replaceAll(`url(#${d})`,`url(#${C})`),a===`#${d}`&&(a=`#${C}`);a!==l.value&&s.setAttribute(l.name,a)}}function $n(e,t,o){let n=Ci(t),s=Ti(e,"svg",{xmlns:ir,class:"spotpatch-brand-mark",viewBox:n.viewBox,"aria-hidden":"true",focusable:"false"});return s.innerHTML=n.content,o!==void 0&&vi(s,o),s}var wi=Symbol.for("spotpatch.data-flow.extension.v1");function qt(e=globalThis){return e[wi]}var Oi=Symbol.for("spotpatch.external-handoff.v1");function gn(){return globalThis[Oi]}var _i=Symbol.for("spotpatch.contextual-ask.v1");function fn(){return globalThis[_i]}var Li=Symbol.for("spotpatch.motion.v1");function sr(){return globalThis[Li]}var ki=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Pi=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ii=Object.freeze({prepare:"Preparing context",dispatch:"Dispatching context",discover:"Discovering project files",search:"Searching source",read:"Reading",patch:"Generating a minimal patch",check:"Running",audit:"Auditing proposed changes",apply:"Applying verified changes",sync:"Returning results to SpotPatch",unknown:"Processing the current task"}),Ni=Object.freeze({prepare:"正在准备上下文",dispatch:"正在派发上下文",discover:"正在查找项目文件",search:"正在搜索源码",read:"正在读取",patch:"正在生成最小修改补丁",check:"正在运行",audit:"正在审计候选修改",apply:"正在应用已验证修改",sync:"正在将结果回流 SpotPatch",unknown:"正在处理当前任务"}),cr=Object.freeze({prepare:"prepare",dispatch:"dispatch",discover:"list",search:"search",read:"read",patch:"patch",check:"check",audit:"audit",apply:"apply",sync:"sync",unknown:"agent"});function lr(e,t,o){return o===void 0||o.length===0?e[t]:`${e[t]} ${o}`}function dr(e,t){return t===void 0||t.length===0?cr[e]:`${cr[e]} · ${t}`}var me="The external Agent handoff request failed.",he="外部 Agent 交接请求失败。",Di=Object.freeze({[p.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[p.INVALID_TOKEN]:"The local SpotPatch session expired.",[p.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[p.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[p.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[p.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[p.EDITOR_OPEN_FAILED]:"The editor request failed.",[p.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[p.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[p.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[p.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[p.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[p.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[p.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[p.AGENT_BUSY]:"Another write Agent job is still active.",[p.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[p.AGENT_CANCELLED]:"The Agent job was cancelled.",[p.EXTERNAL_HANDOFF_DISABLED]:me,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:me,[p.HANDOFF_VALIDATION_FAILED]:me,[p.HANDOFF_SOURCE_STALE]:me,[p.HANDOFF_NOT_FOUND]:me,[p.HANDOFF_EXPIRED]:me,[p.HANDOFF_CURSOR_INVALID]:me,[p.HANDOFF_RESPONSE_TOO_LARGE]:me,[p.BRIDGE_UNAUTHORIZED]:me,[p.BRIDGE_PROTOCOL_MISMATCH]:me,[p.BRIDGE_BUSY]:me,[p.EXTERNAL_AGENT_BUSY]:me,[p.ACTIVE_ADAPTER_CONFLICT]:me,[p.ACTIVE_ADAPTER_LEASE_INVALID]:me,[p.ACTIVE_DISPATCH_INVALID]:me,[p.SESSION_NOT_FOUND]:me,[p.SESSION_AMBIGUOUS]:me,[p.SESSION_CLOSED]:me,[p.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[p.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[p.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[p.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[p.TOOL_DENIED]:"A tool request violated local safety policy.",[p.TOOL_INPUT_INVALID]:"Invalid tool request.",[p.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[p.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[p.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[p.PATCH_REJECTED]:"The patch violated local policy.",[p.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[p.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[p.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Mi=Object.freeze({[p.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[p.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[p.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[p.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[p.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[p.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[p.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[p.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[p.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[p.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[p.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[p.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[p.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[p.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[p.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[p.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[p.AGENT_CANCELLED]:"Agent 任务已取消。",[p.EXTERNAL_HANDOFF_DISABLED]:he,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:he,[p.HANDOFF_VALIDATION_FAILED]:he,[p.HANDOFF_SOURCE_STALE]:he,[p.HANDOFF_NOT_FOUND]:he,[p.HANDOFF_EXPIRED]:he,[p.HANDOFF_CURSOR_INVALID]:he,[p.HANDOFF_RESPONSE_TOO_LARGE]:he,[p.BRIDGE_UNAUTHORIZED]:he,[p.BRIDGE_PROTOCOL_MISMATCH]:he,[p.BRIDGE_BUSY]:he,[p.EXTERNAL_AGENT_BUSY]:he,[p.ACTIVE_ADAPTER_CONFLICT]:he,[p.ACTIVE_ADAPTER_LEASE_INVALID]:he,[p.ACTIVE_DISPATCH_INVALID]:he,[p.SESSION_NOT_FOUND]:he,[p.SESSION_AMBIGUOUS]:he,[p.SESSION_CLOSED]:he,[p.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[p.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[p.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[p.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[p.TOOL_DENIED]:"工具请求违反本地安全策略。",[p.TOOL_INPUT_INVALID]:"工具请求无效。",[p.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[p.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[p.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[p.PATCH_REJECTED]:"补丁违反本地策略。",[p.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[p.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[p.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Fi=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),Hi=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),$i=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),floatingSurface:Object.freeze({dragHandle:"Drag to move the SpotPatch workbench",resetPosition:"Reset workbench position",positionReset:"SpotPatch position reset to the lower-right corner."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Fi,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted direct",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,trustedFastConsent:e=>`Enable trusted direct mode for ${e}: send allowed project context, include current local changes, skip project validation checks, and immediately apply AI changes, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>ki[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"Receiving context",dispatchingTitle:e=>`Handing off to ${e}`,runningTitle:e=>`Modifying ${e}`,expandedRunningTitle:e=>`${e} is making changes`,completedTitle:"Change complete",expandedCompletedTitle:"Changes complete",failedTitle:"Execution failed",receivingStatus:"Receiving",dispatchingStatus:"Dispatching",runningStatus:"Running",checkingStatus:"Checking",completedStatus:"Done",failedStatus:"Failed",resultReturned:"The result is back in SpotPatch",resultSummary:e=>`${String(e)} ${e===1?"file":"files"}`,activityAction:(e,t)=>lr(Ii,e,t),activityLane:dr}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Di}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),floatingSurface:Object.freeze({dragHandle:"拖拽以移动 SpotPatch 工作台",resetPosition:"重置工作台位置",positionReset:"SpotPatch 已恢复到右下角。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:Hi,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",mode:"执行方式",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信极速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信极速模式:发送获准的项目上下文、纳入当前本地修改、跳过项目验证检查,并立即应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Pi[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"正在接收上下文",dispatchingTitle:e=>`正在交接给 ${e}`,runningTitle:e=>`正在修改 ${e}`,expandedRunningTitle:e=>`${e} 正在执行修改`,completedTitle:"修改完成",expandedCompletedTitle:"修改已完成",failedTitle:"执行失败",receivingStatus:"接收中",dispatchingStatus:"派发中",runningStatus:"执行中",checkingStatus:"检查中",completedStatus:"完成",failedStatus:"失败",resultReturned:"结果已回流 SpotPatch",resultSummary:e=>`${String(e)} 个文件`,activityAction:(e,t)=>lr(Ni,e,t),activityLane:dr}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Mi})});function pr(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function Bi(e,t){if(e!=="auto")return e;let o=pr(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(pr).find(s=>s!==void 0)??"en-US"}function ur(e,t="auto"){let o=Bi(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>$i[o],subscribe(s){return n.add(s),()=>{n.delete(s)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let s of n)s()}})}var Ui="spotpatch:floating-surface:";function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function gr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function fr(e){return e==="start"||e==="end"}function zi(e){let t=ji(e);if(!(t?.version!==1||!fr(t.horizontal)||!fr(t.vertical)||!gr(t.xRatio)||!gr(t.yRatio)))return Object.freeze({horizontal:t.horizontal,vertical:t.vertical,xRatio:t.xRatio,yRatio:t.yRatio})}function mr(e,t){let o=`${Ui}${t}`,n;try{n=e.sessionStorage}catch{n=void 0}return Object.freeze({clear(){try{n?.removeItem(o)}catch{}},load(){let s;try{s=n?.getItem(o)??null}catch{return}if(!(s===null||s.length>1024))try{return zi(JSON.parse(s))}catch{return}},save(s){try{n?.setItem(o,JSON.stringify({version:1,...s}))}catch{}}})}var mn=Object.freeze({horizontal:"end",vertical:"end",xRatio:1,yRatio:1});function Gt(e,t,o){return Math.min(Math.max(e,t),o)}function xt(e){return Number.isFinite(e)?Math.max(0,e):0}function Bn(e){return Number.isFinite(e)?Gt(e,0,1):.5}function yr(e){return Object.freeze({height:xt(e.height),left:Number.isFinite(e.left)?e.left:0,top:Number.isFinite(e.top)?e.top:0,width:xt(e.width)})}function Vi(e,t){return t==="end"?e.left+e.width:e.left}function Wi(e,t){return t==="end"?e.top+e.height:e.top}function hr(e,t,o){return o<=0?.5:Bn((e-t)/o)}function Un(e,t,o,n){return Object.freeze({horizontal:o,vertical:n,xRatio:hr(e.x,t.left,t.width),yRatio:hr(e.y,t.top,t.height)})}function br(e,t,o){let n=xt(t.width),s=xt(t.height),l=yr(o),a=l.width,d=l.height,C=l.left,x=l.top,w=C+a,V=x+d,b=C+Bn(e.xRatio)*a,i=x+Bn(e.yRatio)*d,W=e.horizontal==="end"?b-n:b,H=e.vertical==="end"?i-s:i,A=Math.max(C,w-n),v=Math.max(x,V-s);return Object.freeze({height:s,left:Gt(W,C,A),top:Gt(H,x,v),width:n})}function jn(e,t,o){let n=xt(o),s=xt(e.width),l=xt(e.height),a=yr(t),d=a.left+a.width,C=a.top+a.height,x=Math.max(a.left,d-s),w=Math.max(a.top,C-l),V=Gt(e.left,a.left,x),b=Gt(e.top,a.top,w),i=Math.abs(V-a.left),W=Math.abs(d-(V+s)),H=Math.abs(b-a.top),A=Math.abs(C-(b+l)),v=Math.min(i,W)<=n?i<=W?a.left:d-s:V,q=Math.min(H,A)<=n?H<=A?a.top:C-l:b;return Object.freeze({height:l,left:v,top:q,width:s})}function Sr(e,t,o){let n=jn(e,t,0),s=n.left+n.width/2,l=n.top+n.height/2,a=t.left+xt(t.width)/2,d=t.top+xt(t.height)/2,C=s===a?o.horizontal:s<a?"start":"end",x=l===d?o.vertical:l<d?"start":"end";return Un({x:Vi(n,C),y:Wi(n,x)},t,C,x)}function Mt(e,t=0){return Number.isFinite(e)?e:t}function qi(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Gi(e){return e.button===0&&e.isPrimary}function Ki(e){let t=e.getBoundingClientRect();return Object.freeze({height:Math.max(0,Mt(t.height)),width:Math.max(0,Mt(t.width))})}function Ji(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(()=>{t(Date.now())},0)}function Er(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Ar(e,t,o){let n=t.load()??mn,s,l,a,d,C=!1,x=new Set,w=new Set;function V(){let E=e.visualViewport,T=Math.max(0,Mt(E?.width??e.innerWidth)),O=Math.max(0,Mt(E?.height??e.innerHeight)),_=T<=o.compactViewportWidth?o.compactInset:o.desktopInset;return Object.freeze({height:Math.max(0,O-_*2),left:Mt(E?.offsetLeft??0)+_,top:Mt(E?.offsetTop??0)+_,width:Math.max(0,T-_*2)})}function b(){return V().width+o.compactInset*2<=o.compactViewportWidth}function i(E){if(E.hidden||E.dataset.motionMorphing==="true"&&E.dataset.floatingPositioned==="true")return;let T=Ki(E);if(T.width===0||T.height===0)return;let O=br(n,T,V());return E.style.left=`${String(O.left)}px`,E.style.top=`${String(O.top)}px`,E.style.right="auto",E.style.bottom="auto",E.dataset.floatingPositioned="true",O}function W(){if(!C){l!==void 0&&(Er(e,l),l=void 0);for(let E of x)i(E)}}function H(){C||l!==void 0||(l=Ji(e,()=>{l=void 0,W()}))}function A(E){n=E,t.save(n)}function v(E){let T=s;if(T!==void 0){s=void 0,T.handle.dataset.dragging="false",T.surface.dataset.dragging="false";try{T.handle.hasPointerCapture(T.pointerId)&&T.handle.releasePointerCapture(T.pointerId)}catch{}if(E){let O=i(T.surface);if(O!==void 0){let _=jn(O,V(),o.edgeSnapDistance);A(Sr(_,V(),n)),i(T.surface)}}else n=t.load()??mn,W()}}function q(E){let T=s;if(T===void 0||E.pointerId!==T.pointerId)return;let O=Object.freeze({x:E.clientX,y:E.clientY}),_=Object.freeze({x:T.startX,y:T.startY});T.handle.dataset.dragging!=="true"&&qi(O,_)<o.dragActivationDistance||(T.handle.dataset.dragging!=="true"&&T.onDragStart?.(),T.handle.dataset.dragging="true",T.surface.dataset.dragging="true",n=Un({x:O.x+T.anchorOffsetX,y:O.y+T.anchorOffsetY},V(),n.horizontal,n.vertical),H(),E.preventDefault())}function B(E,T,O,_){E.addEventListener(T,O,_),w.add(()=>{E.removeEventListener(T,O,_)})}function I(E,T,O={}){let _=D=>{if(C||s!==void 0||!Gi(D)||O.canStartDrag?.(D)===!1)return;let N=i(T)??T.getBoundingClientRect(),le=n.horizontal==="end"?N.left+N.width:N.left,ye=n.vertical==="end"?N.top+N.height:N.top;s=Object.freeze({anchorOffsetX:le-D.clientX,anchorOffsetY:ye-D.clientY,handle:E,...O.onDragStart===void 0?{}:{onDragStart:O.onDragStart},pointerId:D.pointerId,startX:D.clientX,startY:D.clientY,suppressClickOnDrag:O.suppressClickOnDrag??!1,surface:T});try{E.setPointerCapture(D.pointerId)}catch{}},pe=D=>{s?.pointerId===D.pointerId&&v(E.dataset.dragging==="true")},ve=D=>{a===E&&(a=void 0,d!==void 0&&(e.clearTimeout(d),d=void 0),D.preventDefault(),D.stopImmediatePropagation())};B(E,"pointerdown",D=>{_(D)}),B(E,"lostpointercapture",D=>{pe(D)}),B(E,"click",D=>{ve(D)},!0)}function y(){v(!1),n=mn,t.clear(),W()}function R(){v(!1)}function L(E){E.key!=="Escape"||s===void 0||(v(!1),E.preventDefault(),E.stopImmediatePropagation())}function M(E){if(s?.pointerId!==E.pointerId)return;let T=s,O=T.handle.dataset.dragging==="true";v(O),O&&T.suppressClickOnDrag&&(a=T.handle,d=e.setTimeout(()=>{a=void 0,d=void 0},0))}function K(E){s?.pointerId===E.pointerId&&v(!1)}return B(e,"pointermove",E=>{q(E)}),B(e,"pointerup",E=>{M(E)}),B(e,"pointercancel",E=>{K(E)}),B(e,"resize",H),B(e,"blur",R),B(e,"keydown",E=>{L(E)},!0),e.visualViewport?.addEventListener("resize",H),e.visualViewport?.addEventListener("scroll",H),w.add(()=>e.visualViewport?.removeEventListener("resize",H)),w.add(()=>e.visualViewport?.removeEventListener("scroll",H)),Object.freeze({attachDraggable:I,dispose(){if(!C){C=!0,v(!1),l!==void 0&&(Er(e,l),l=void 0),d!==void 0&&(e.clearTimeout(d),d=void 0),a=void 0;for(let E of w)E();w.clear(),x.clear()}},isCompact:b,reconcile:W,registerSurface(E){x.add(E)},requestReconcile:H,reset:y})}var Xi=1500;function Yi(e){let t=new Set([...e.querySelectorAll("script[nonce]")].map(o=>o.nonce?.trim()??"").filter(Boolean));if(t.size===1)return t.values().next().value}function Zi(e){let t=e.createElement("style");return t.textContent=`
|
|
256
|
+
`;function Wt(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function ar(e,t,o){let n=o.messages(),i=g(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let l=g(e,"div");l.className="spotpatch-agent-head",l.setAttribute("data-spotpatch-agent-identity","");let a=g(e,"span");a.className="spotpatch-agent-title";let d=g(e,"span");d.className="spotpatch-agent-badge",l.append(a,d);let C=g(e,"div");C.className="spotpatch-agent-setup";let x=g(e,"div");x.className="spotpatch-agent-selectors";let w=g(e,"label");w.className="spotpatch-agent-mode";let V=g(e,"span"),b=g(e,"select");w.append(V,b);let s=g(e,"label"),W=g(e,"span"),H=g(e,"select");s.append(W,H);let A=g(e,"label"),v=g(e,"span"),q=g(e,"select");A.append(v,q),x.append(w,s,A);let B=g(e,"label");B.className="spotpatch-consent";let I=g(e,"input");I.type="checkbox";let y=g(e,"span");B.append(I,y);let R=g(e,"label");R.className="spotpatch-consent spotpatch-workspace-consent",R.hidden=!0;let L=g(e,"input");L.type="checkbox";let M=g(e,"span"),K=g(e,"strong"),E=g(e,"small");M.append(K,E),R.append(L,M);let T=g(e,"div");T.className="spotpatch-agent-health-list";let O=g(e,"p");O.className="spotpatch-agent-workspace",O.dataset.state="idle";let _=g(e,"p");_.className="spotpatch-agent-capability",_.dataset.state="idle",T.append(O,_),C.append(x,B,R,T);let pe=g(e,"div");pe.className="spotpatch-agent-job",pe.hidden=!0;let ve=g(e,"div");ve.className="spotpatch-agent-job-meta";let D=g(e,"span");D.className="spotpatch-agent-model";let N=g(e,"span");N.className="spotpatch-agent-status",ve.append(D,N);let le=g(e,"p");le.className="spotpatch-agent-phase";let ye=g(e,"p");ye.className="spotpatch-agent-error",ye.hidden=!0;let be=g(e,"ul");be.className="spotpatch-agent-activity";let te=g(e,"div");te.className="spotpatch-agent-result",te.hidden=!0;let st=g(e,"p");st.className="spotpatch-agent-summary";let se=g(e,"ul");se.className="spotpatch-agent-files";let Ue=g(e,"div");Ue.className="spotpatch-agent-checks";let xe=g(e,"pre");xe.className="spotpatch-agent-diff",xe.tabIndex=0,xe.setAttribute("aria-label",n.agent.diffAriaLabel),te.append(st,se,Ue,xe),pe.append(ve,le,ye,be,te),i.append(l,C,pe);let tt=ie(e,n.agent.testConnection),qe=ie(e,n.agent.run,"spotpatch-run"),Ge=ie(e,n.agent.cancel),ee=ie(e,n.agent.apply,"spotpatch-primary"),de=ie(e,n.agent.revert),Ne=ie(e,n.agent.revise),nt=t.enabled?t.providers:[],Ke=t.enabled&&t.applyMode==="trusted-auto",ct=t.enabled?t.applyMode:"review",ot=new Map(nt.map(m=>[m.id,m])),lt=!1,De=!0,ne=!1,Re=!1,Je=!1,U=!1,je,Ce,St=[],Xe,fe="idle",Ye=n.agent.connectionNotTested,Ze,Se="idle",we,ze;for(let m of nt)Wt(e,H,m.id,m.label);t.enabled&&(H.value=t.defaultProvider);let Rt,Ve,We;ct==="auto"?We=Wt(e,b,"auto",n.agent.autoGated):(Rt=Wt(e,b,"review",n.agent.review),Ke&&(Ve=Wt(e,b,"trusted-auto",n.agent.trustedFast)));let dt=Ke?"review":ct;b.value=dt,w.hidden=!Ke;let P=()=>b.value==="trusted-auto"?"trusted-auto":dt,rt=()=>P()==="trusted-auto",Z=()=>ot.get(H.value),Y=m=>m===void 0?n.agent.providerUnavailable:rt()?n.agent.trustedFastConsent(m.label):n.agent.consent(m.label),Me=()=>rt()?I.checked:L.checked,pt=()=>{let m=rt();B.classList.toggle("spotpatch-trusted-consent",m),d.textContent=m?n.agent.trustedFast:ct==="auto"?n.agent.autoGated:n.agent.review,y.textContent=Y(Z()),R.hidden=m||Se!=="consent-required"},Fe=()=>{let m=Z();if(q.replaceChildren(),m===void 0){y.textContent=Y(m);return}for(let F of m.models)Wt(e,q,F.id,F.label);q.value=m.defaultModel,y.textContent=Y(m)},re=()=>{let m=t.enabled&&ne&&!Re;qe.textContent=Je?n.agent.verifying:n.agent.run,qe.classList.toggle("spotpatch-primary",U),tt.hidden=!m,qe.hidden=!m,tt.disabled=!De||Je||Z()===void 0,qe.disabled=!De||Je||!lt||!I.checked||Se==="idle"||Se==="checking"||Se==="blocked"||Se==="consent-required"&&!Me()||Z()===void 0||q.value.length===0,(!Re||!ne)&&(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},Oe=()=>{if(Se==="idle")O.textContent=n.agent.workspaceNotChecked;else if(Se==="checking")O.textContent=n.agent.checkingWorkspace;else if(Se==="ready")O.textContent=n.agent.workspaceReady;else if(Se==="consent-required"){let m=we?.changes;O.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else O.textContent=ze===void 0?n.errors.INTERNAL_ERROR:n.errors[ze]};function He(){Fe(),I.checked=!1,_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function at(){_.dataset.state="idle",_.textContent=n.agent.connectionNotTested,fe="idle",Ye=n.agent.connectionNotTested,Ze=void 0,U=!1,re()}function c(){I.checked=!1,L.checked=!1,pt(),re()}Fe(),b.addEventListener("change",c),H.addEventListener("change",He),q.addEventListener("change",at),I.addEventListener("change",re),L.addEventListener("change",re);function u(){if(je===void 0)return;let m=je,F=Ce;D.textContent=`${m.providerLabel} · ${m.modelLabel}`,N.textContent=n.agent.status(m.status),le.textContent=m.phaseMessage;let G=Xe??m.errorCode;ye.hidden=G===void 0,ye.textContent=G===void 0?"":n.errors[G],be.replaceChildren();for(let Q of St.slice(-8)){let _e=g(e,"li");_e.dataset.state=Q.state,_e.textContent=Q.label,be.append(_e)}te.hidden=F===void 0,st.textContent=F?.summary??"",se.replaceChildren(),Ue.replaceChildren(),xe.textContent=F?.diff??"";for(let Q of F?.files??[]){let _e=g(e,"li");_e.textContent=`${Q.kind} ${Q.relativePath} (+${String(Q.additions)} / -${String(Q.deletions)})`,se.append(_e)}for(let Q of F?.checks??[]){let _e=g(e,"details"),Ft=g(e,"summary");Ft.textContent=`${Q.label}: ${Q.status} · ${String(Q.durationMs)} ms`;let Qe=g(e,"pre");Qe.textContent=Q.output.length===0?n.agent.noOutput:Q.output,_e.append(Ft,Qe),Ue.append(_e)}tt.hidden=!0,qe.hidden=!0,Ge.hidden=!ne||!m.canCancel,Ge.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,ee.hidden=!ne||!m.canApply,de.hidden=!ne||!m.canRevert,Ne.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function S(){n=o.messages(),a.textContent=n.agent.title,V.textContent=n.agent.mode,Rt!==void 0&&(Rt.textContent=n.agent.review),Ve!==void 0&&(Ve.textContent=n.agent.trustedFast),We!==void 0&&(We.textContent=n.agent.autoGated),W.textContent=n.agent.provider,v.textContent=n.agent.model,H.setAttribute("aria-label",n.agent.providerAriaLabel),q.setAttribute("aria-label",n.agent.modelAriaLabel),K.textContent=n.agent.includeLocalChanges,E.textContent=n.agent.includeLocalChangesHelp,xe.setAttribute("aria-label",n.agent.diffAriaLabel),tt.textContent=n.agent.testConnection,ee.textContent=n.agent.apply,de.textContent=n.agent.revert,Ne.textContent=n.agent.revise,pt(),fe==="idle"?_.textContent=n.agent.connectionNotTested:fe==="probing"?_.textContent=n.agent.testingCapability:fe==="ready"?_.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ze!==void 0?_.textContent=n.errors[Ze]:Z()===void 0?_.textContent=n.agent.providerUnavailable:_.textContent=Ye,Oe(),re(),u()}let $=o.subscribe(S);return S(),Object.freeze({root:i,modeSelect:b,providerSelect:H,modelSelect:q,consentCheckbox:I,workspaceConsentCheckbox:L,testButton:tt,runButton:qe,cancelButton:Ge,applyButton:ee,revertButton:de,resetButton:Ne,consentGranted(){return I.checked},workspaceConsentGranted(){return Me()},readSelection(){let m=Z(),F=m?.models.find(G=>G.id===q.value);return m===void 0||F===void 0?void 0:Object.freeze({applyMode:P(),providerProfileId:m.id,modelProfileId:F.id})},renderCapability(m,F,G,Q){fe=m,Ye=F,Ze=Q,Je=m==="probing",U=m==="ready"&&G?.state==="agent-ready",_.dataset.state=m,_.textContent=G?.state==="agent-ready"?`${F} · ${n.agent.toolsReady}`:F,re()},renderWorkspaceHealth(m,F,G){Se=m,we=F,ze=G??F?.errorCode,O.dataset.state=m,m!=="checking"&&(R.hidden=rt()||m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(L.checked=!1),Oe(),re()},renderJob(m,F,G,Q){Re=!0,C.hidden=!0,pe.hidden=!1,H.disabled=!0,q.disabled=!0,b.disabled=!0,I.disabled=!0,L.disabled=!0,je=m,Ce=F,St=G,Xe=Q,u()},resetJob(){Re=!1,je=void 0,Ce=void 0,St=[],Xe=void 0,C.hidden=!1,pe.hidden=!0,H.disabled=!1,q.disabled=!1,b.disabled=!1,I.disabled=!1,L.disabled=!1,be.replaceChildren(),se.replaceChildren(),Ue.replaceChildren(),xe.textContent="",ye.textContent="",ye.hidden=!0,re()},setContextReady(m){lt=m,re()},setEditingEnabled(m){De=m,H.disabled=!m||Re,q.disabled=!m||Re,b.disabled=!m||Re,I.disabled=!m||Re,L.disabled=!m||Re,re()},setProviderConsent(m){I.checked=m,re()},setSelectionVisible(m){ne=m,re(),m||(Ge.hidden=!0,ee.hidden=!0,de.hidden=!0,Ne.hidden=!0)},dispose(){$(),H.removeEventListener("change",He),q.removeEventListener("change",at),b.removeEventListener("change",c),I.removeEventListener("change",re),L.removeEventListener("change",re)}})}var ir="http://www.w3.org/2000/svg",Ri="";function Ci(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Ri,viewBox:"0 0 1 1"}}function Ti(e,t,o){let n=e.createElementNS(ir,t);for(let[i,l]of Object.entries(o))n.setAttribute(i,l);return n}function vi(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/gu,"-"),n=new Map;for(let i of e.querySelectorAll("[id]")){let l=i.id,a=`${o}-${l}`;n.set(l,a),i.id=a}for(let i of[e,...e.querySelectorAll("*")])for(let l of[...i.attributes]){let a=l.value;for(let[d,C]of n)a=a.replaceAll(`url(#${d})`,`url(#${C})`),a===`#${d}`&&(a=`#${C}`);a!==l.value&&i.setAttribute(l.name,a)}}function $n(e,t,o){let n=Ci(t),i=Ti(e,"svg",{xmlns:ir,class:"spotpatch-brand-mark",viewBox:n.viewBox,"aria-hidden":"true",focusable:"false"});return i.innerHTML=n.content,o!==void 0&&vi(i,o),i}var wi=Symbol.for("spotpatch.data-flow.extension.v1");function qt(e=globalThis){return e[wi]}var Oi=Symbol.for("spotpatch.external-handoff.v1");function gn(){return globalThis[Oi]}var _i=Symbol.for("spotpatch.contextual-ask.v1");function fn(){return globalThis[_i]}var Li=Symbol.for("spotpatch.motion.v1");function sr(){return globalThis[Li]}var ki=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Pi=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Ii=Object.freeze({prepare:"Preparing context",dispatch:"Dispatching context",discover:"Discovering project files",search:"Searching source",read:"Reading",patch:"Generating a minimal patch",check:"Running",audit:"Auditing proposed changes",apply:"Applying verified changes",sync:"Returning results to SpotPatch",unknown:"Processing the current task"}),Ni=Object.freeze({prepare:"正在准备上下文",dispatch:"正在派发上下文",discover:"正在查找项目文件",search:"正在搜索源码",read:"正在读取",patch:"正在生成最小修改补丁",check:"正在运行",audit:"正在审计候选修改",apply:"正在应用已验证修改",sync:"正在将结果回流 SpotPatch",unknown:"正在处理当前任务"}),cr=Object.freeze({prepare:"prepare",dispatch:"dispatch",discover:"list",search:"search",read:"read",patch:"patch",check:"check",audit:"audit",apply:"apply",sync:"sync",unknown:"agent"});function lr(e,t,o){return o===void 0||o.length===0?e[t]:`${e[t]} ${o}`}function dr(e,t){return t===void 0||t.length===0?cr[e]:`${cr[e]} · ${t}`}var me="The external Agent handoff request failed.",he="外部 Agent 交接请求失败。",Di=Object.freeze({[p.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[p.INVALID_TOKEN]:"The local SpotPatch session expired.",[p.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[p.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[p.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[p.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[p.EDITOR_OPEN_FAILED]:"The editor request failed.",[p.DATA_FLOW_DISABLED]:"Component data-flow analysis is disabled.",[p.DATA_FLOW_SOURCE_STALE]:"The selected source changed. Select the component again.",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"Component data-flow analysis was cancelled.",[p.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[p.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[p.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[p.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[p.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[p.AGENT_BUSY]:"Another write Agent job is still active.",[p.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[p.AGENT_CANCELLED]:"The Agent job was cancelled.",[p.EXTERNAL_HANDOFF_DISABLED]:me,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:me,[p.HANDOFF_VALIDATION_FAILED]:me,[p.HANDOFF_SOURCE_STALE]:me,[p.HANDOFF_NOT_FOUND]:me,[p.HANDOFF_EXPIRED]:me,[p.HANDOFF_CURSOR_INVALID]:me,[p.HANDOFF_RESPONSE_TOO_LARGE]:me,[p.BRIDGE_UNAUTHORIZED]:me,[p.BRIDGE_PROTOCOL_MISMATCH]:me,[p.BRIDGE_BUSY]:me,[p.EXTERNAL_AGENT_BUSY]:me,[p.ACTIVE_ADAPTER_CONFLICT]:me,[p.ACTIVE_ADAPTER_LEASE_INVALID]:me,[p.ACTIVE_DISPATCH_INVALID]:me,[p.SESSION_NOT_FOUND]:me,[p.SESSION_AMBIGUOUS]:me,[p.SESSION_CLOSED]:me,[p.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[p.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[p.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[p.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[p.TOOL_DENIED]:"A tool request violated local safety policy.",[p.TOOL_INPUT_INVALID]:"Invalid tool request.",[p.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[p.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[p.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[p.PATCH_REJECTED]:"The patch violated local policy.",[p.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[p.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[p.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Mi=Object.freeze({[p.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[p.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[p.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[p.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[p.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[p.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[p.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[p.DATA_FLOW_DISABLED]:"组件数据链路分析未启用。",[p.DATA_FLOW_SOURCE_STALE]:"选中源码已经变化,请重新选择组件。",[p.DATA_FLOW_ANALYSIS_CANCELLED]:"组件数据链路分析已取消。",[p.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[p.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[p.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[p.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[p.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[p.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[p.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[p.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[p.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[p.AGENT_CANCELLED]:"Agent 任务已取消。",[p.EXTERNAL_HANDOFF_DISABLED]:he,[p.EXTERNAL_HANDOFF_UNAVAILABLE]:he,[p.HANDOFF_VALIDATION_FAILED]:he,[p.HANDOFF_SOURCE_STALE]:he,[p.HANDOFF_NOT_FOUND]:he,[p.HANDOFF_EXPIRED]:he,[p.HANDOFF_CURSOR_INVALID]:he,[p.HANDOFF_RESPONSE_TOO_LARGE]:he,[p.BRIDGE_UNAUTHORIZED]:he,[p.BRIDGE_PROTOCOL_MISMATCH]:he,[p.BRIDGE_BUSY]:he,[p.EXTERNAL_AGENT_BUSY]:he,[p.ACTIVE_ADAPTER_CONFLICT]:he,[p.ACTIVE_ADAPTER_LEASE_INVALID]:he,[p.ACTIVE_DISPATCH_INVALID]:he,[p.SESSION_NOT_FOUND]:he,[p.SESSION_AMBIGUOUS]:he,[p.SESSION_CLOSED]:he,[p.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[p.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[p.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[p.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[p.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[p.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[p.TOOL_DENIED]:"工具请求违反本地安全策略。",[p.TOOL_INPUT_INVALID]:"工具请求无效。",[p.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[p.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[p.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[p.PATCH_REJECTED]:"补丁违反本地策略。",[p.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[p.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[p.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Fi=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),Hi=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),$i=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),floatingSurface:Object.freeze({dragHandle:"Drag to move the SpotPatch workbench",resetPosition:"Reset workbench position",positionReset:"SpotPatch position reset to the lower-right corner."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Fi,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted direct",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,trustedFastConsent:e=>`Enable trusted direct mode for ${e}: send allowed project context, include current local changes, skip project validation checks, and immediately apply AI changes, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>ki[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"Receiving context",dispatchingTitle:e=>`Handing off to ${e}`,runningTitle:e=>`Modifying ${e}`,expandedRunningTitle:e=>`${e} is making changes`,completedTitle:"Change complete",expandedCompletedTitle:"Changes complete",failedTitle:"Execution failed",receivingStatus:"Receiving",dispatchingStatus:"Dispatching",runningStatus:"Running",checkingStatus:"Checking",completedStatus:"Done",failedStatus:"Failed",resultReturned:"The result is back in SpotPatch",resultSummary:e=>`${String(e)} ${e===1?"file":"files"}`,activityAction:(e,t)=>lr(Ii,e,t),activityLane:dr}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Di}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),floatingSurface:Object.freeze({dragHandle:"拖拽以移动 SpotPatch 工作台",resetPosition:"重置工作台位置",positionReset:"SpotPatch 已恢复到右下角。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:Hi,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",mode:"执行方式",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信极速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信极速模式:发送获准的项目上下文、纳入当前本地修改、跳过项目验证检查,并立即应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Pi[e]}),execution:Object.freeze({claude:"Claude",codex:"Codex",receivingTitle:"正在接收上下文",dispatchingTitle:e=>`正在交接给 ${e}`,runningTitle:e=>`正在修改 ${e}`,expandedRunningTitle:e=>`${e} 正在执行修改`,completedTitle:"修改完成",expandedCompletedTitle:"修改已完成",failedTitle:"执行失败",receivingStatus:"接收中",dispatchingStatus:"派发中",runningStatus:"执行中",checkingStatus:"检查中",completedStatus:"完成",failedStatus:"失败",resultReturned:"结果已回流 SpotPatch",resultSummary:e=>`${String(e)} 个文件`,activityAction:(e,t)=>lr(Ni,e,t),activityLane:dr}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Mi})});function pr(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function Bi(e,t){if(e!=="auto")return e;let o=pr(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(pr).find(i=>i!==void 0)??"en-US"}function ur(e,t="auto"){let o=Bi(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>$i[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var Ui="spotpatch:floating-surface:";function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function gr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function fr(e){return e==="start"||e==="end"}function zi(e){let t=ji(e);if(!(t?.version!==1||!fr(t.horizontal)||!fr(t.vertical)||!gr(t.xRatio)||!gr(t.yRatio)))return Object.freeze({horizontal:t.horizontal,vertical:t.vertical,xRatio:t.xRatio,yRatio:t.yRatio})}function mr(e,t){let o=`${Ui}${t}`,n;try{n=e.sessionStorage}catch{n=void 0}return Object.freeze({clear(){try{n?.removeItem(o)}catch{}},load(){let i;try{i=n?.getItem(o)??null}catch{return}if(!(i===null||i.length>1024))try{return zi(JSON.parse(i))}catch{return}},save(i){try{n?.setItem(o,JSON.stringify({version:1,...i}))}catch{}}})}var mn=Object.freeze({horizontal:"end",vertical:"end",xRatio:1,yRatio:1});function Gt(e,t,o){return Math.min(Math.max(e,t),o)}function xt(e){return Number.isFinite(e)?Math.max(0,e):0}function Bn(e){return Number.isFinite(e)?Gt(e,0,1):.5}function yr(e){return Object.freeze({height:xt(e.height),left:Number.isFinite(e.left)?e.left:0,top:Number.isFinite(e.top)?e.top:0,width:xt(e.width)})}function Vi(e,t){return t==="end"?e.left+e.width:e.left}function Wi(e,t){return t==="end"?e.top+e.height:e.top}function hr(e,t,o){return o<=0?.5:Bn((e-t)/o)}function Un(e,t,o,n){return Object.freeze({horizontal:o,vertical:n,xRatio:hr(e.x,t.left,t.width),yRatio:hr(e.y,t.top,t.height)})}function br(e,t,o){let n=xt(t.width),i=xt(t.height),l=yr(o),a=l.width,d=l.height,C=l.left,x=l.top,w=C+a,V=x+d,b=C+Bn(e.xRatio)*a,s=x+Bn(e.yRatio)*d,W=e.horizontal==="end"?b-n:b,H=e.vertical==="end"?s-i:s,A=Math.max(C,w-n),v=Math.max(x,V-i);return Object.freeze({height:i,left:Gt(W,C,A),top:Gt(H,x,v),width:n})}function jn(e,t,o){let n=xt(o),i=xt(e.width),l=xt(e.height),a=yr(t),d=a.left+a.width,C=a.top+a.height,x=Math.max(a.left,d-i),w=Math.max(a.top,C-l),V=Gt(e.left,a.left,x),b=Gt(e.top,a.top,w),s=Math.abs(V-a.left),W=Math.abs(d-(V+i)),H=Math.abs(b-a.top),A=Math.abs(C-(b+l)),v=Math.min(s,W)<=n?s<=W?a.left:d-i:V,q=Math.min(H,A)<=n?H<=A?a.top:C-l:b;return Object.freeze({height:l,left:v,top:q,width:i})}function Sr(e,t,o){let n=jn(e,t,0),i=n.left+n.width/2,l=n.top+n.height/2,a=t.left+xt(t.width)/2,d=t.top+xt(t.height)/2,C=i===a?o.horizontal:i<a?"start":"end",x=l===d?o.vertical:l<d?"start":"end";return Un({x:Vi(n,C),y:Wi(n,x)},t,C,x)}function Mt(e,t=0){return Number.isFinite(e)?e:t}function qi(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Gi(e){return e.button===0&&e.isPrimary}function Ki(e){let t=e.getBoundingClientRect();return Object.freeze({height:Math.max(0,Mt(t.height)),width:Math.max(0,Mt(t.width))})}function Ji(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(()=>{t(Date.now())},0)}function Er(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Ar(e,t,o){let n=t.load()??mn,i,l,a,d,C=!1,x=new Set,w=new Set;function V(){let E=e.visualViewport,T=Math.max(0,Mt(E?.width??e.innerWidth)),O=Math.max(0,Mt(E?.height??e.innerHeight)),_=T<=o.compactViewportWidth?o.compactInset:o.desktopInset;return Object.freeze({height:Math.max(0,O-_*2),left:Mt(E?.offsetLeft??0)+_,top:Mt(E?.offsetTop??0)+_,width:Math.max(0,T-_*2)})}function b(){return V().width+o.compactInset*2<=o.compactViewportWidth}function s(E){if(E.hidden||E.dataset.motionMorphing==="true"&&E.dataset.floatingPositioned==="true")return;let T=Ki(E);if(T.width===0||T.height===0)return;let O=br(n,T,V());return E.style.left=`${String(O.left)}px`,E.style.top=`${String(O.top)}px`,E.style.right="auto",E.style.bottom="auto",E.dataset.floatingPositioned="true",O}function W(){if(!C){l!==void 0&&(Er(e,l),l=void 0);for(let E of x)s(E)}}function H(){C||l!==void 0||(l=Ji(e,()=>{l=void 0,W()}))}function A(E){n=E,t.save(n)}function v(E){let T=i;if(T!==void 0){i=void 0,T.handle.dataset.dragging="false",T.surface.dataset.dragging="false";try{T.handle.hasPointerCapture(T.pointerId)&&T.handle.releasePointerCapture(T.pointerId)}catch{}if(E){let O=s(T.surface);if(O!==void 0){let _=jn(O,V(),o.edgeSnapDistance);A(Sr(_,V(),n)),s(T.surface)}}else n=t.load()??mn,W()}}function q(E){let T=i;if(T===void 0||E.pointerId!==T.pointerId)return;let O=Object.freeze({x:E.clientX,y:E.clientY}),_=Object.freeze({x:T.startX,y:T.startY});T.handle.dataset.dragging!=="true"&&qi(O,_)<o.dragActivationDistance||(T.handle.dataset.dragging!=="true"&&T.onDragStart?.(),T.handle.dataset.dragging="true",T.surface.dataset.dragging="true",n=Un({x:O.x+T.anchorOffsetX,y:O.y+T.anchorOffsetY},V(),n.horizontal,n.vertical),H(),E.preventDefault())}function B(E,T,O,_){E.addEventListener(T,O,_),w.add(()=>{E.removeEventListener(T,O,_)})}function I(E,T,O={}){let _=D=>{if(C||i!==void 0||!Gi(D)||O.canStartDrag?.(D)===!1)return;let N=s(T)??T.getBoundingClientRect(),le=n.horizontal==="end"?N.left+N.width:N.left,ye=n.vertical==="end"?N.top+N.height:N.top;i=Object.freeze({anchorOffsetX:le-D.clientX,anchorOffsetY:ye-D.clientY,handle:E,...O.onDragStart===void 0?{}:{onDragStart:O.onDragStart},pointerId:D.pointerId,startX:D.clientX,startY:D.clientY,suppressClickOnDrag:O.suppressClickOnDrag??!1,surface:T});try{E.setPointerCapture(D.pointerId)}catch{}},pe=D=>{i?.pointerId===D.pointerId&&v(E.dataset.dragging==="true")},ve=D=>{a===E&&(a=void 0,d!==void 0&&(e.clearTimeout(d),d=void 0),D.preventDefault(),D.stopImmediatePropagation())};B(E,"pointerdown",D=>{_(D)}),B(E,"lostpointercapture",D=>{pe(D)}),B(E,"click",D=>{ve(D)},!0)}function y(){v(!1),n=mn,t.clear(),W()}function R(){v(!1)}function L(E){E.key!=="Escape"||i===void 0||(v(!1),E.preventDefault(),E.stopImmediatePropagation())}function M(E){if(i?.pointerId!==E.pointerId)return;let T=i,O=T.handle.dataset.dragging==="true";v(O),O&&T.suppressClickOnDrag&&(a=T.handle,d=e.setTimeout(()=>{a=void 0,d=void 0},0))}function K(E){i?.pointerId===E.pointerId&&v(!1)}return B(e,"pointermove",E=>{q(E)}),B(e,"pointerup",E=>{M(E)}),B(e,"pointercancel",E=>{K(E)}),B(e,"resize",H),B(e,"blur",R),B(e,"keydown",E=>{L(E)},!0),e.visualViewport?.addEventListener("resize",H),e.visualViewport?.addEventListener("scroll",H),w.add(()=>e.visualViewport?.removeEventListener("resize",H)),w.add(()=>e.visualViewport?.removeEventListener("scroll",H)),Object.freeze({attachDraggable:I,dispose(){if(!C){C=!0,v(!1),l!==void 0&&(Er(e,l),l=void 0),d!==void 0&&(e.clearTimeout(d),d=void 0),a=void 0;for(let E of w)E();w.clear(),x.clear()}},isCompact:b,reconcile:W,registerSurface(E){x.add(E)},requestReconcile:H,reset:y})}var Xi=1500;function Yi(e){let t=new Set([...e.querySelectorAll("script[nonce]")].map(o=>o.nonce?.trim()??"").filter(Boolean));if(t.size===1)return t.values().next().value}function Zi(e){let t=e.createElement("style");return t.textContent=`
|
|
257
257
|
:host {
|
|
258
258
|
all: initial;
|
|
259
259
|
--spotpatch-bg: #0e0e12;
|
|
@@ -855,8 +855,8 @@ ${un(e.code.language,oe(t.codeLines.join(`
|
|
|
855
855
|
}
|
|
856
856
|
${rr}
|
|
857
857
|
`,t}function Qi(e,t){return e.split(`
|
|
858
|
-
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function es(e){let t=e.target;return t instanceof Element&&t.closest("a, button, input, select, textarea, summary, [contenteditable='true']")!==null}function ts(e){let t=ie(e,"","spotpatch-execution-island");t.hidden=!0,t.setAttribute("aria-hidden","true");let o=$n(e,void 0,"spotpatch-fallback-execution-island");o.classList.add("spotpatch-execution-logo");let n=g(e,"span");return t.append(o,n),Object.freeze({canExpand:()=>!1,isExpanded:()=>!1,root:t,setExpanded:()=>{},render(s){let l=[s.headline,s.action,s.meta].filter(a=>a.length>0).join(" · ");n.textContent=l,t.setAttribute("aria-label",l)},dispose(){}})}function ns(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:ie(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function xr(e,t,o=Object.freeze({enabled:!1}),n="auto",s=!1,l=!1,a="vite",d="",C=!1){let x=ur(e,n),w=e.defaultView;if(w===null)throw new Error("SpotPatch requires a document with an associated window.");let V=w,b=Ar(V,mr(V,d),_t),i=x.messages(),W="idle",H="change",A="",v="",q=!1,B=!1,I,y,R,L,M,K,E=e.createElement("spotpatch-root");E.setAttribute(Nt,"");let T=E.attachShadow({mode:"open"}),O=g(e,"div");O.className="spotpatch-floating-surface",O.dataset.scene="pill",O.dataset.tone="neutral";let _=ie(e,i.trigger.select,"spotpatch-trigger");_.title=i.trigger.title(t),_.setAttribute("aria-pressed","false");let pe=sr(),ve=pe?.createExecutionIsland(e),D=ve??ts(e),N=D.root,le=g(e,"div");le.className="spotpatch-highlight",le.hidden=!0;let ye=g(e,"span");ye.className="spotpatch-highlight-label",le.append(ye);let be=g(e,"div");be.className="spotpatch-selection-highlights",be.setAttribute("aria-hidden","true");let te=g(e,"section");te.className="spotpatch-dialog",te.hidden=!0,te.tabIndex=-1,te.setAttribute("role","dialog"),te.setAttribute("aria-labelledby","spotpatch-selection-title");let st=g(e,"div");st.className="spotpatch-shell";let se=g(e,"header");se.className="spotpatch-header",se.setAttribute("data-spotpatch-drag-handle","");let Ue=g(e,"div");Ue.className="spotpatch-brand-row";let xe=g(e,"div");xe.className="spotpatch-brand";let tt=g(e,"span");tt.className="spotpatch-brand-copy";let qe=g(e,"span");qe.className="spotpatch-brand-name";let Ge=g(e,"span");Ge.className="spotpatch-brand-context",tt.append(qe,Ge),xe.append($n(e),tt);let ee=g(e,"span");ee.className="spotpatch-header-controls";let de=g(e,"a");de.className="spotpatch-repository",de.href=Pn,de.target="_blank",de.rel="noopener noreferrer";let Ne=ie(e,"","spotpatch-locale"),nt=ie(e,"⌖","spotpatch-reset-position"),Ke=ie(e,"×","spotpatch-close");ee.append(de,Ne,nt,Ke),Ue.append(xe,ee);let ct=g(e,"h2");ct.id="spotpatch-selection-title",ct.className="spotpatch-title";let ot=g(e,"p");ot.className="spotpatch-subtitle";let lt=g(e,"div");lt.className="spotpatch-target-row";let De=g(e,"span");De.className="spotpatch-target-label";let ne=g(e,"span");ne.className="spotpatch-context-state",ne.dataset.state="loading",ne.textContent=i.context.collecting,lt.append(De,ne),se.append(Ue,ct,ot,lt);let Re=g(e,"div");Re.className="spotpatch-body";let Je=g(e,"div");Je.className="spotpatch-selection-panel";let U=g(e,"section");U.className="spotpatch-targets";let je=g(e,"div");je.className="spotpatch-targets-heading";let Ce=g(e,"span"),St=g(e,"span");St.className="spotpatch-targets-meta";let Xe=g(e,"span");Xe.className="spotpatch-target-complete";let fe=g(e,"span");fe.className="spotpatch-target-budget",fe.setAttribute("aria-live","polite");let Ye=g(e,"span");Ye.className="spotpatch-target-count",St.append(Xe,fe),lt.append(Ye),je.append(Ce,St);let Ze=g(e,"div");Ze.className="spotpatch-target-progress",Ze.setAttribute("aria-hidden","true");let Se=g(e,"div");Se.className="spotpatch-target-progress-fill",Ze.append(Se);let we=g(e,"div");we.className="spotpatch-target-list",U.append(je,Ze,we);let ze=g(e,"details");ze.className="spotpatch-diagnostics";let Rt=g(e,"summary"),Ve=g(e,"span"),We=g(e,"span");We.className="spotpatch-source-peek",We.textContent=i.diagnostics.resolving,Rt.append(Ve,We);let dt=g(e,"pre");dt.className="spotpatch-summary",ze.append(Rt,dt);let P=ar(e,o,x),rt=g(e,"div");function Z(){q&&b.requestReconcile()}let Y=l?gn()?.createPanel(e,a,x.locale,d,x.subscribe,Z,kr,Pr):void 0;rt.append(U,P.root,...Y===void 0?[]:[Y.root]);let Me=qt()?.createPanel(e,s,x.locale,rt,ze,Z)??ns(e,rt,ze);Je.append(Me.root);let pt=g(e,"div");pt.className="spotpatch-preview-panel",pt.hidden=!0;let Fe=g(e,"pre");Fe.className="spotpatch-prompt",Fe.tabIndex=0,Fe.setAttribute("aria-label",i.diagnostics.promptAriaLabel),pt.append(Fe),Re.append(Je,pt);let re=g(e,"footer");re.className="spotpatch-actions";let Oe=g(e,"div");Oe.className="spotpatch-context-state spotpatch-editor-feedback",Oe.dataset.state="idle",Oe.setAttribute("role","status"),Oe.setAttribute("aria-live","polite"),Oe.hidden=!0;let He=ie(e,i.actions.addElement),at=ie(e,i.actions.reselect),c=ie(e,i.actions.openEditor),u=ie(e,i.actions.preview,"spotpatch-primary"),S=ie(e,i.actions.copy,"spotpatch-primary"),$=ie(e,i.actions.back),m=g(e,"div");m.className="spotpatch-secondary-actions";let F=g(e,"div");F.className="spotpatch-primary-actions",He.classList.add("spotpatch-icon-action"),He.dataset.compactIcon="+",P.testButton.classList.add("spotpatch-icon-action"),P.testButton.dataset.compactIcon="✓",c.classList.add("spotpatch-secondary-action"),at.classList.add("spotpatch-secondary-action"),m.append(c,at),F.append(P.testButton,He,P.runButton,...Y===void 0?[]:[Y.sendButton],u,P.cancelButton,P.applyButton,P.revertButton,P.resetButton,S,$),re.append(Oe,m,F);let G=C?fn()?.createPanel({document:e,locale:x.locale,subscribeLocale:x.subscribe,changeRoot:Me.root,changeActions:re,announce:An,onModeChange(r,f,h){H=r,A=f,v=h,E.isConnected&&en(W)},onExecutionChange(r){I=r,B=!1,Ee()},onViewChange:Z}):void 0;G!==void 0&&Je.prepend(G.root),st.append(se,Re,re),te.append(st);let Q=g(e,"div");Q.className="spotpatch-live",Q.setAttribute("aria-live","polite"),Q.setAttribute("aria-atomic","true");let _e=[Zi(e),...pe===void 0?[]:[pe.createStyles(e)],Me.styles,...G===void 0?[]:[G.styles],...Y===void 0?[]:[Y.styles]],Ft=Yi(e);if(Ft!==void 0)for(let r of _e)r.nonce=Ft;T.append(..._e,be,le,O,Q),O.append(_,te,N),e.documentElement.append(E),b.registerSurface(O);let Qe=pe===void 0||ve===void 0?void 0:pe.createController(e,Object.freeze({execution:ve.elements,pill:_,planner:te,surface:O}),b.reconcile),hn=()=>{Qe?.cancel()};b.attachDraggable(_,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.attachDraggable(se,O,{canStartDrag:r=>!b.isCompact()&&!es(r),onDragStart:hn}),b.attachDraggable(N,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.reconcile();let yn=!1,Ht=!1,Kt="",Jt=!0,$e=[],Xt=0,qn="idle",Gn=Object.freeze({component:Object.freeze({status:s?"idle":"disabled"}),page:Object.freeze({status:s?"idle":"disabled"}),observationCount:0});function Yt(){let r=$e.find(f=>f.active);return Object.freeze(r===void 0?{label:i.context.selectedElement,source:""}:{label:r.label,source:r.source})}function Lt(){let r=Yt();return r.source.length===0?r.label:`${r.label} · ${r.source}`}function Kn(){return K=new Date().toISOString(),K}function Jn(){return K??Kn()}function Zt(r){M!==void 0&&(V.clearTimeout(M),M=void 0),r&&(R=void 0,L=void 0)}function bn(r){return L===r?!1:(R===r||(Zt(!1),R=r,M=V.setTimeout(()=>{M=void 0,E.isConnected&&(L=r,I=void 0,K=void 0,B=!1,q=!1,Ee())},Xi)),!0)}function Lr(r){return r.startsWith("claude")?i.execution.claude:r.startsWith("codex")?i.execution.codex:r}function Xn(r){return Object.freeze({...r.detail===void 0?{}:{detail:r.detail},key:r.key,kind:r.kind,label:i.execution.activityLane(r.kind,r.detail),state:r.state})}function Dt(r,f,h,k="active"){return Object.freeze({...h===void 0?{}:{detail:h},key:r,kind:f,label:i.execution.activityLane(f,h),state:k})}function Ee(){let r=W==="inspecting",f=!q||r,h=f?{scene:r?"capturing":"pill",tone:r?"capturing":"neutral",headline:_.textContent,action:"",meta:"",recentActivities:Object.freeze([])}:!B&&I!==void 0?I:{scene:"planner",tone:"ready",headline:i.dialog.editTitle,action:i.dialog.editSubtitle,meta:i.context.ready,recentActivities:Object.freeze([])};if(Qe!==void 0){Qe.render(h,()=>{D.render(h)});return}D.render(h),O.dataset.scene=h.scene,O.dataset.tone=h.tone;let k=h.scene==="planner";_.hidden=!f,_.inert=!f,te.hidden=!k,te.inert=!k,te.setAttribute("aria-hidden",String(!k)),N.hidden=f||k,N.inert=f||k,N.setAttribute("aria-hidden",String(f||k)),b.reconcile()}function kr(r){if(r===null?(y=void 0,K=void 0):y!==void 0&&r.phase!=="failed"&&r.phase!=="delivery-unknown"?Sn():(r.phase==="failed"||r.phase==="delivery-unknown")&&(y=void 0),r!==null&&!B){let f=r.phase==="failed"||r.phase==="delivery-unknown",h=r.phase==="completed",k=f||h?void 0:Jn();(f||h)&&(K=void 0);let j=`dispatch:${String(r.revision)}`;if(h&&!bn(j)){I=void 0,Ee();return}let ce=Lr(r.adapterKind),Le=Yt(),ue=r.phase==="queued"||r.phase==="dispatching"||r.phase==="dispatched"?"dispatch":h?"sync":"unknown",ke=Dt(`dispatch:${String(r.revision)}:${r.phase}`,ue,r.phase,f?"failure":h?"success":"active"),z=f?"failed":h?"success":r.phase==="working"?"running":"handoff";I={scene:z,tone:f?"danger":h?"success":"running",headline:h?i.execution.completedTitle:f?i.execution.failedTitle:z==="running"?i.execution.runningTitle(Le.label):i.execution.dispatchingTitle(ce),action:h?i.execution.resultReturned:Le.source,expandedHeadline:h?i.execution.expandedCompletedTitle:f?i.execution.failedTitle:z==="running"?i.execution.expandedRunningTitle(ce):i.execution.dispatchingTitle(ce),expandedAction:h?i.execution.resultReturned:Lt(),meta:f?i.execution.failedStatus:h?i.execution.completedStatus:z==="running"?i.execution.runningStatus:i.execution.dispatchingStatus,activity:ke,recentActivities:Object.freeze([ke]),...k===void 0?{}:{startedAt:k}}}else r===null&&(I=void 0);Ee()}function Pr(r){let f=r?.task;if(r===void 0||f===void 0||B)return;let h=f.managedPhase,k=h==="failed"||h==="cleanup-warning",j=h==="completed"||h==="review-required",ce=h==="cancelled";if(k||ce?y=void 0:y!==void 0&&Sn(),ce){I=void 0,K=void 0,Ee();return}let Le=k||j?void 0:Jn();if((k||j)&&(K=void 0),h==="completed"&&!bn(`managed:${String(f.revision)}`)){I=void 0,Ee();return}let ue=k?"failed":j?"success":h==="preparing"?"handoff":"running",ke=k?"danger":j?"success":"running",z=i.execution.codex,X=Yt(),et=h==="preparing"?"prepare":h==="auditing"?"audit":h==="validating"?"check":h==="applying"?"apply":j?"sync":"unknown",ut=f.checks.at(-1),gt=f.files.at(-1),ft=h==="validating"?ut?.id:h==="auditing"||h==="applying"?gt?.path:void 0,Ct=Dt(`managed:${String(f.revision)}:${h}:${ft??""}`,et,ft,k?"failure":j?"success":"active"),$t=Object.freeze([...f.files.slice(-2).map(mt=>Dt(`managed-file:${String(f.revision)}:${mt.path}`,"patch",mt.path,"success")),...f.checks.slice(-2).map(mt=>Dt(`managed-check:${String(f.revision)}:${mt.id}`,"check",mt.id,mt.outcome==="passed"?"success":"failure")),Ct]);I={scene:ue,tone:ke,headline:j?i.execution.completedTitle:k?i.execution.failedTitle:ue==="handoff"?i.execution.dispatchingTitle(z):h==="validating"?i.execution.activityAction("check",ft):i.execution.runningTitle(X.label),action:j?f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):X.source,expandedHeadline:j?i.execution.expandedCompletedTitle:k?i.execution.failedTitle:ue==="handoff"?i.execution.dispatchingTitle(z):i.execution.expandedRunningTitle(z),expandedAction:j?i.execution.resultReturned:Lt(),meta:k?i.execution.failedStatus:j?i.execution.completedStatus:h==="validating"?i.execution.checkingStatus:ue==="handoff"?i.execution.dispatchingStatus:i.execution.runningStatus,activity:Ct,recentActivities:$t,...Le===void 0?{}:{startedAt:Le}},Ee()}function Ir(r,f){if(!q)return;Zt(!0);let h=Kn();B=!1;let k=Dt(`dispatch-start:${Lt()}`,"dispatch",Lt());I={scene:"agent-charging",tone:"running",headline:i.execution.receivingTitle,action:Lt(),expandedHeadline:i.execution.receivingTitle,expandedAction:Lt(),meta:i.execution.receivingStatus,activity:k,recentActivities:Object.freeze([k]),startedAt:h},Ee(),Qe?.dispatch(r,f)}function Yn(r,f){!q||r.disabled||(y=Object.freeze({source:r,target:f}))}function Sn(){let r=y;y=void 0,!(r===void 0||!r.source.isConnected||!r.target.isConnected)&&Ir(r.source,r.target)}function En(r){qn=r,Oe.dataset.state=r,Oe.hidden=r==="idle",Oe.textContent=r==="opening"?i.announcements.editorOpening:r==="success"?i.announcements.editorOpened:r==="error"?i.announcements.editorFailed:"",Z()}function Nr(r){return r.status==="ready"?i.targets.statusReady:r.status==="warning"?i.targets.statusPartial:i.targets.statusCollecting}function Qt(r,f){let h=f===0?0:r/f;Se.style.width=`${String(h*100)}%`}function Zn(r){let f=we.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(f).find(h=>r===void 0||h.dataset.targetInstructionId===r)}function Qn(r,f){let h=T.activeElement?.closest("textarea[data-target-instruction-id]"),k=h?.dataset.targetInstructionId,j=h?.selectionStart,ce=h?.selectionEnd;$e=r.map(z=>Object.freeze({...z})),Xt=f,we.replaceChildren();let Le=r.filter(z=>z.instruction.trim().length>0).length,ue=r.reduce((z,X)=>z+X.instruction.trim().length,0);Qt(Le,r.length),Ye.textContent=i.targets.count(r.length,f),Xe.textContent=i.targets.complete(Le,r.length);let ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?i.targets.instructionBudgetExceeded(ue,4e3):i.targets.instructionBudget(ue,4e3),He.disabled=!Jt||r.length>=f,He.title=r.length>=f?i.targets.limitTitle(f):i.targets.addTitle,De.textContent=r.length===1?r[0]?.label??i.context.selectedElement:i.context.selectedCount(r.length);for(let[z,X]of r.entries()){let et=g(e,"div");et.className="spotpatch-target-item",et.dataset.active=String(X.active),et.dataset.status=X.status,et.dataset.targetId=X.id;let ut=g(e,"div");ut.className="spotpatch-target-summary";let gt=ie(e,"","spotpatch-target-select");gt.dataset.activateTargetId=X.id,gt.setAttribute("aria-label",i.targets.activate(z+1)),gt.setAttribute("aria-expanded",String(X.active));let ft=g(e,"span");ft.className="spotpatch-target-index",ft.textContent=String(z+1);let Ct=g(e,"span");Ct.className="spotpatch-target-copy";let $t=g(e,"span");$t.className="spotpatch-target-name",$t.textContent=X.label;let mt=g(e,"span");mt.className="spotpatch-target-source",mt.textContent=`${Nr(X)} · ${X.source}`,Ct.append($t,mt);let co=X.instruction.trim().length>0,tn=g(e,"span");tn.className="spotpatch-target-state",tn.dataset.complete=String(co),tn.textContent=co?i.targets.instructionReady:i.targets.instructionMissing,gt.append(ft,Ct,tn);let Bt=ie(e,"↗","spotpatch-target-open");Bt.dataset.openTargetId=X.id,Bt.disabled=!X.canOpenEditor,Bt.setAttribute("aria-label",i.actions.openTarget(z+1)),Bt.title=i.actions.openTarget(z+1);let Ut=ie(e,"×","spotpatch-target-remove");if(Ut.dataset.removeTargetId=X.id,Ut.disabled=!Jt,Ut.setAttribute("aria-label",i.targets.remove(z+1)),Ut.title=i.targets.removeTitle,ut.append(gt,Bt,Ut),et.append(ut),X.active){let xn=g(e,"label");xn.className="spotpatch-target-editor";let Rn=g(e,"span");Rn.className="spotpatch-target-editor-head";let Cn=g(e,"span");Cn.className="spotpatch-target-editor-label",Cn.textContent=i.targets.instructionLabel(X.label);let Tn=g(e,"span");Tn.className="spotpatch-target-editor-count",Tn.textContent=i.targets.instructionCount(X.instruction.length,2e3),Rn.append(Cn,Tn);let Tt=g(e,"textarea");Tt.rows=4,Tt.maxLength=2e3,Tt.value=X.instruction,Tt.placeholder=i.targets.instructionPlaceholder,Tt.disabled=!Jt,Tt.dataset.targetInstructionId=X.id,Tt.setAttribute("aria-label",i.targets.instructionLabel(X.label)),xn.append(Rn,Tt),et.append(xn)}we.append(et)}if(k!==void 0){let z=Zn(k);z?.focus({preventScroll:!0}),j!==void 0&&ce!==void 0&&z?.setSelectionRange(j,ce)}Z()}function Dr(r,f){$e=$e.map(z=>z.id===r?Object.freeze({...z,instruction:f}):z);let h=Array.from(we.querySelectorAll(".spotpatch-target-item")).find(z=>z.dataset.targetId===r);if(h===void 0)return;let k=f.trim().length>0,j=h.querySelector(".spotpatch-target-state"),ce=h.querySelector(".spotpatch-target-editor-count");j!==null&&(j.dataset.complete=String(k),j.textContent=k?i.targets.instructionReady:i.targets.instructionMissing),ce!==null&&(ce.textContent=i.targets.instructionCount(f.length,2e3));let Le=$e.filter(z=>z.instruction.trim().length>0).length;Xe.textContent=i.targets.complete(Le,$e.length),Qt(Le,$e.length);let ue=$e.reduce((z,X)=>z+X.instruction.trim().length,0),ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?i.targets.instructionBudgetExceeded(ue,4e3):i.targets.instructionBudget(ue,4e3)}function Mr(r){be.replaceChildren();for(let[f,h]of r.entries()){let k=g(e,"div");k.className="spotpatch-selection-highlight",k.dataset.targetId=h.id,k.dataset.active=String(h.active),k.style.transform=`translate(${String(h.rect.x)}px, ${String(h.rect.y)}px)`,k.style.width=`${String(h.rect.width)}px`,k.style.height=`${String(h.rect.height)}px`;let j=g(e,"span");j.textContent=`${String(f+1)} · ${h.label}`,k.append(j),be.append(k)}}function eo(r){let f=i.summary,h=Qi(r,f.source);We.textContent=h??i.diagnostics.noExactSource;let k=`${f.browserContext}: ${f.collectionStatuses.ready}`,j=`${f.browserContext}: ${f.collectionStatuses.loading}`,ce=`${f.browserContext}: ${f.collectionStatuses.failed}`,Le=`${f.api}: ${f.apiStatuses.loading}`,ue=`${f.api}: ${f.apiStatuses.failed}`;r.includes(k)&&!r.includes(j)&&!r.includes(Le)&&!r.includes(ce)&&!r.includes(ue)?(ne.dataset.state="ready",ne.textContent=i.context.ready):r.includes(ce)||r.includes(ue)?(ne.dataset.state="warning",ne.textContent=i.context.partial):(ne.dataset.state="loading",ne.textContent=i.context.collecting)}function to(r,f,h){yn=f,Ht=h,Kt=r,dt.textContent=r,c.disabled=!f,u.disabled=!h,P.setContextReady(h),Y?.setContextReady(h),G?.setSelectionPreview({contextReady:$e.every(k=>k.status!=="loading"),targetCount:$e.length,sourceCount:$e.filter(k=>k.canOpenEditor).length}),eo(r),Z()}function en(r){W=r;let f=r==="selected",h=r==="previewing";Je.hidden=!f,pt.hidden=!h,at.hidden=!f,He.hidden=!f,c.hidden=!f,u.hidden=!f,m.hidden=!f,P.setSelectionVisible(f),Y?.setSelectionVisible(f),G?.setSelectionVisible(f),S.hidden=!h,$.hidden=!h,ct.textContent=h?i.dialog.previewTitle:H==="ask"&&A.length>0?A:i.dialog.editTitle,ot.textContent=h?i.dialog.previewSubtitle:H==="ask"&&v.length>0?v:i.dialog.editSubtitle,Ee()}function no(){i=x.messages(),qe.textContent=i.brand.name,Ge.textContent=i.brand.context,de.textContent=i.brand.repository,de.title=i.brand.repositoryTitle,de.setAttribute("aria-label",i.brand.repositoryTitle),Ne.textContent=i.alternateLocaleName,Ne.title=i.switchLocale,Ne.setAttribute("aria-label",i.switchLocale),nt.title=i.floatingSurface.resetPosition,nt.setAttribute("aria-label",i.floatingSurface.resetPosition),Ke.setAttribute("aria-label",i.dialog.close),Ke.title=i.dialog.close,se.title=i.floatingSurface.dragHandle,U.setAttribute("aria-label",i.targets.ariaLabel),Ce.textContent=i.targets.title,Ve.textContent=i.diagnostics.title,Fe.setAttribute("aria-label",i.diagnostics.promptAriaLabel),He.textContent=i.actions.addElement,at.textContent=i.actions.reselect,c.textContent=i.actions.openEditor,u.textContent=i.actions.preview,S.textContent=i.actions.copy,$.textContent=i.actions.back,Me.render(Gn),_.title=i.trigger.title(t),_.textContent=W==="inspecting"?i.trigger.stop:i.trigger.select,en(W),En(qn),$e.length>0?Qn($e,Xt):(Ye.textContent=i.targets.count(0,Xt),Xe.textContent=i.targets.complete(0,0),Qt(0,0),fe.dataset.state="ready",fe.textContent=i.targets.instructionBudget(0,4e3),De.textContent=i.context.selectedElement),Kt.length>0?eo(Kt):(We.textContent=i.diagnostics.resolving,ne.textContent=i.context.collecting)}function An(r){Q.textContent="",Q.textContent=r}function oo(){b.reset(),An(i.floatingSurface.positionReset)}ze.addEventListener("toggle",Z),Ne.addEventListener("click",x.toggle),nt.addEventListener("click",oo);let ro=()=>{Yn(P.runButton,P.root)},ao=()=>{Y!==void 0&&Yn(Y.sendButton,Y.root)},io=()=>{if(D.canExpand()&&!D.isExpanded()){Qe===void 0?(D.setExpanded(!0),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!0)});return}Zt(!1),B=!0,Ee()},so=r=>{r.key!=="Escape"||!D.isExpanded()||(r.preventDefault(),r.stopPropagation(),Qe===void 0?(D.setExpanded(!1),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!1)}))};P.runButton.addEventListener("click",ro),Y?.sendButton.addEventListener("click",ao),N.addEventListener("click",io),N.addEventListener("keydown",so);let Fr=x.subscribe(no);return no(),Object.freeze({host:E,triggerButton:_,addTargetButton:He,targetList:we,reselectButton:at,openEditorButton:c,repositoryLink:de,previewButton:u,copyButton:S,dataFlowRefreshButton:Me.refreshButton,backButton:$,closeButton:Ke,agentProviderSelect:P.providerSelect,agentModelSelect:P.modelSelect,agentModeSelect:P.modeSelect,agentConsentCheckbox:P.consentCheckbox,agentWorkspaceConsentCheckbox:P.workspaceConsentCheckbox,agentTestButton:P.testButton,agentRunButton:P.runButton,agentCancelButton:P.cancelButton,agentApplyButton:P.applyButton,agentRevertButton:P.revertButton,agentResetButton:P.resetButton,...Y===void 0?{}:{externalHandoffPanel:Y},...G===void 0?{}:{contextualAskPanel:G},renderStatus(r){let f=r==="inspecting";r==="idle"||f?q=!1:q=!0,_.setAttribute("aria-pressed",String(f)),_.textContent=f?i.trigger.stop:i.trigger.select,en(r)},renderEditorStatus:En,renderDataFlow(r){Gn=r,Me.render(r),Z()},showHighlight(r,f){le.hidden=!1,le.style.transform=`translate(${String(r.x)}px, ${String(r.y)}px)`,le.style.width=`${String(r.width)}px`,le.style.height=`${String(r.height)}px`,ye.textContent=f,De.textContent=f},hideHighlight(){le.hidden=!0,ye.textContent=""},showSelectionHighlights:Mr,hideSelectionHighlights(){be.replaceChildren()},showSelection(r,f,h){to(r,f,h),q=!0,en(W==="previewing"?"previewing":"selected")},updateSelection:to,renderTargets:Qn,updateTargetInstruction:Dr,setPreviewEnabled(r){Ht=r,u.disabled=!r,P.setContextReady(r),Y?.setContextReady(r)},hideSelection(){q=!1,B=!1,I=void 0,we.replaceChildren(),$e=[],Xt=0,Kt="",En("idle"),Ye.textContent=i.targets.count(0,0),Xe.textContent=i.targets.complete(0,0),Qt(0,0),De.textContent=i.context.selectedElement,dt.textContent="",Fe.textContent="",We.textContent=i.diagnostics.resolving,ne.dataset.state="loading",ne.textContent=i.context.collecting,c.disabled=!0,u.disabled=!0,yn=!1,Ht=!1,P.setContextReady(!1),P.setSelectionVisible(!1),Y?.setContextReady(!1),Y?.setSelectionVisible(!1),G?.setSelectionVisible(!1),P.setEditingEnabled(!0),P.resetJob(),Me.resetView(),Ee()},hideSelectionTemporarily(){q=!1,B=!1,I=void 0,Ee()},showPreview(r){Fe.textContent=r,Z()},readAgentSelection(){return P.readSelection()},agentConsentGranted(){return P.consentGranted()},setAgentProviderConsent(r){P.setProviderConsent(r)},setAgentEditingEnabled(r){Jt=r,He.disabled=!r,at.disabled=!r,we.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(f=>{f.disabled=!r}),c.disabled=!yn,u.disabled=!r||!Ht,Y?.setContextReady(r&&Ht),P.setEditingEnabled(r),Z()},renderAgentCapability(r,f,h,k){P.renderCapability(r,f,h,k),r==="error"&&(y=void 0,Ee());let j=r==="ready"&&h?.state==="agent-ready";u.classList.toggle("spotpatch-primary",!j),Z()},renderAgentWorkspaceHealth(r,f,h){P.renderWorkspaceHealth(r,f,h),r==="blocked"&&(y=void 0,Ee()),Z()},renderAgentJob(r,f,h,k){P.renderJob(r,f,h,k),y!==void 0&&r.status!=="failed"&&r.status!=="cancelled"&&Sn(),(r.status==="failed"||r.status==="cancelled")&&(y=void 0);let j=r.status==="awaiting-review"||r.status==="applied"||r.status==="completed"||r.status==="reverted",ce=r.status==="failed",Le=r.status==="cancelled",ue=r.status==="applied"||r.status==="completed"||r.status==="reverted",ke=j?"success":ce?"failed":r.status==="queued"||r.status==="preparing"?"handoff":"running";if(!B){if(ue&&!bn(`job:${r.jobId}:${r.status}`)){I=void 0,Ee(),Z();return}let z=r.providerLabel,X=Yt(),et=Object.freeze(h.map(Xn)),ut=h.at(-1),gt=r.status==="queued"||r.status==="preparing"?"prepare":r.status==="validating"?"check":r.status==="applying"||r.status==="reverting"?"apply":r.status==="awaiting-review"||j?"sync":"unknown",ft=Dt(`job-phase:${r.jobId}:${r.status}:${r.updatedAt}`,gt,void 0,j?"success":ce?"failure":"active"),Ct=r.status==="running"&&ut!==void 0?Xn(ut):ft;I=Le?void 0:{scene:ke,tone:j?"success":ce?"danger":"running",headline:j?i.execution.completedTitle:ce?i.execution.failedTitle:ke==="handoff"?i.execution.dispatchingTitle(z):r.status==="validating"?i.execution.activityAction("check",ut?.detail):r.status==="applying"||r.status==="reverting"?i.execution.activityAction(gt):i.execution.runningTitle(X.label),action:j?f===void 0||f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):ut?.detail??X.source,expandedHeadline:j?i.execution.expandedCompletedTitle:ce?i.execution.failedTitle:ke==="handoff"?i.execution.dispatchingTitle(z):i.execution.expandedRunningTitle(z),expandedAction:j?f===void 0||f.files.length===0?i.execution.resultReturned:i.execution.resultSummary(f.files.length):Lt(),meta:j?i.execution.completedStatus:ce?i.execution.failedStatus:r.status==="validating"?i.execution.checkingStatus:ke==="handoff"?i.execution.dispatchingStatus:i.execution.runningStatus,activity:Ct,recentActivities:et.length===0?Object.freeze([ft]):et,startedAt:r.createdAt}}Ee(),Z()},resetAgentJob(){P.resetJob(),K=void 0,I!==void 0&&(I=void 0,B=!1,Ee()),Z()},focusTargetInstruction(r){Zn(r)?.focus({preventScroll:!0})},focusPrompt(){Fe.focus({preventScroll:!0})},announce:An,locale:x.locale,messages:x.messages,agentWorkspaceConsentGranted:P.workspaceConsentGranted,subscribeLocale:x.subscribe,dispose(){ze.removeEventListener("toggle",Z),Ne.removeEventListener("click",x.toggle),nt.removeEventListener("click",oo),P.runButton.removeEventListener("click",ro),Y?.sendButton.removeEventListener("click",ao),N.removeEventListener("click",io),N.removeEventListener("keydown",so),Fr(),Me.dispose(),Y?.dispose(),G?.dispose(),P.dispose(),Qe?.dispose(),D.dispose(),Zt(!0),b.dispose(),E.remove()}})}function os(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,l=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${l===void 0?"":`:${String(l)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,l):o.unavailable}function Rr(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${os(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
859
|
-
`)}function Cr(e,t){return`${e}:${t}`}var rs=Object.freeze({list_files:"discover",search_text:"search",read_file:"read",replace_text:"patch",apply_patch:"patch",run_check:"check"});function as(e){return rs[e]??"unknown"}function is(e){if(e.type==="tool"){let t=e.data.relativePath??e.data.checkLabel;return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,kind:as(e.data.toolName),...t===void 0?{}:{detail:t},label:`${e.data.toolName}${t===void 0?"":` · ${t}`} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"})}if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,kind:"check",detail:e.data.result.label,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function Tr(e){let t=y=>vo(y)??p.INTERNAL_ERROR,o=y=>e.view.messages().errors[t(y)],n=new Map,s=new Set,l=new Map,a=0,d,C,x=!1,w=!1,V=()=>e.view.readAgentSelection(),b=y=>`${y.providerProfileId}:${y.applyMode}`,i=async y=>{e.view.renderAgentWorkspaceHealth("checking");try{let R=await e.api.agentWorkspaceHealth();return y!==a||e.view.renderAgentWorkspaceHealth(R.state,R,R.errorCode),R}catch(R){throw y===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(R)),R}},W=y=>{d!==void 0&&e.view.renderAgentJob(d,C,Object.freeze([...l.values()]),y??d.errorCode)},H=()=>{let y=V();if(y===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(s.has(b(y)));let R=n.get(Cr(y.providerProfileId,y.modelProfileId));R===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,R)},A=async y=>{let R=V();if(R===void 0)throw new Error("Agent provider selection is unavailable.");let L=Cr(R.providerProfileId,R.modelProfileId),M=n.get(L);if(M!==void 0)return M;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let K=await e.api.agentCapability(R);if(y!==a)return K;if(K.state!=="agent-ready")throw new J(K.errorCode??p.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(L,K),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,K),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),K},v=async(y,R)=>{try{let L=await e.api.agentResult(y);if(R!==a||L.snapshot.jobId!==y)return;d=L.snapshot,C=L.result,W()}catch(L){R===a&&W(t(L))}},q=async(y,R)=>{try{await e.api.agentEvents(y,L=>{if(R!==a||L.jobId!==y)return;L.type==="snapshot"&&(d=L.data.snapshot,d.status==="applied"&&!x&&(x=!0,e.onApplied()));let M=is(L);M!==void 0&&l.set(M.key,M),W()}),R===a&&await v(y,R)}catch(L){R===a&&!(L instanceof DOMException&&L.name==="AbortError")&&W(t(L))}},B=async y=>{let R=d;if(R===void 0||w)return;w=!0;let L=a;d=Object.freeze({...R,status:y==="apply"?"applying":y==="cancel"?"cancelling":"reverting",phaseMessage:y==="apply"?e.view.messages().agent.applying:y==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),W();try{let M=y==="apply"?await e.api.applyAgentJob(R.jobId):y==="cancel"?await e.api.cancelAgentJob(R.jobId):await e.api.revertAgentJob(R.jobId);if(L!==a)return;d=M,M.status==="applied"&&!x&&(x=!0,e.onApplied()),await v(M.jobId,L)}catch(M){if(L!==a)return;d=R,await v(R.jobId,L),W(t(M)),e.view.announce(o(M))}finally{L===a&&(w=!1)}},I=()=>{a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),H()};return Object.freeze({apply(){d?.canApply===!0&&B("apply")},beginSelection(){I();let y=a;e.ai.enabled&&i(y).catch(()=>{})},cancel(){d?.canCancel===!0&&B("cancel")},consentChanged(){let y=V();y!==void 0&&(e.view.agentConsentGranted()?s.add(b(y)):s.delete(b(y)))},disposeSelection(){let y=d?.canCancel===!0||d?.status==="cancelling"?d.jobId:void 0;a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,y!==void 0&&e.api.cancelAgentJob(y).catch(()=>{})},providerOrModelChanged(){a+=1,H(),i(a).catch(()=>{})},reset(){let y=x;I(),y?e.onReselectRequired():e.ai.enabled&&i(a).catch(()=>{})},revert(){d?.canRevert===!0&&B("revert")},run(){if(!e.ai.enabled||d!==void 0)return;let y=V(),R=e.getAnnotation();if(y===void 0||R===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}s.add(b(y));let L=++a;e.view.setAgentEditingEnabled(!1),i(L).then(async M=>{if(L!==a)return;if(M.state==="blocked")throw new J(M.errorCode??p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(M.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new J(p.WORKTREE_DIRTY);let K=await e.api.createAgentJob({annotation:R,applyMode:y.applyMode,providerProfileId:y.providerProfileId,modelProfileId:y.modelProfileId,providerDataConsent:!0,...y.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:M.state==="consent-required"?"include-local-changes":"require-clean"});L===a&&(d=K,C=void 0,l.clear(),W(),q(K.jobId,L))}).catch(M=>{L===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(M),void 0,t(M)),e.view.announce(o(M)))})},testCapability(){if(!e.ai.enabled||d!==void 0)return;let y=++a;Promise.all([A(y),i(y)]).catch(R=>{y===a&&(e.view.renderAgentCapability("error",o(R),void 0,t(R)),e.view.announce(o(R)))})}})}function vr(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function zn(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function wr(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var cs=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Vn(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function ls(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,s=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${s===void 0?"":`:${String(s)}`}`}function ds(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ps(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function Or(e,t={}){let o=ps(t),n=t.view??xr(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId,e.contextualAsk.enabled),s=t.api??wo({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),l=t.promptComposer??Jo({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??wr(o.window.navigator),d=t.createId??(()=>vr(o.window)),C=t.now??(()=>new Date().toISOString()),x=t.selectionSession??Qo(o.window,e.sessionId,e.maxTargets),w=x.load(),V=or({adapter:t.reactAdapter??ss({...e.dataFlow.enabled?{getComponentRegistration:c=>qt()?.getComponentRegistration(c)}:{},maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),b=Mn,i=!1,W,H,A=w?.targets.map(c=>{let u=Hn(c.source);return{id:c.id,resolution:Object.freeze({source:c.source,react:c.react}),apiStatus:u===void 0?"not-required":c.code===void 0?"failed":"connected",code:c.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:c.element,instruction:c.instruction,marker:u,page:c.page,styles:c.styles}})??[],v=w?.activeTargetId,q=w?.sequence??0,B=w?.open??!1,I=!1,y=0,R=0,L=0,M,K="idle",E=!1,T="",O,_,pe,ve,D=new Map;function N(c){b=Xo(b,c),n.renderStatus(b.status)}function le(){return A.find(c=>c.id===v)??A.at(-1)}function ye(c){let u=c.resolution.react;if(u.componentSourceId!==void 0&&u.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:u.componentSourceId,sourceVersion:u.sourceVersion});let S=c.marker;return S===void 0?void 0:Object.freeze({schemaVersion:1,fileId:S.fileId,line:S.line,column:S.column})}function be(){let c=qt(),u=c?.observations(o.window.location.pathname)??[],S=le();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?S?.dataFlowStatus??"idle":"disabled",...S?.dataFlowReport===void 0?{}:{report:c?.mergeComponentReport(S.dataFlowReport,u)??S.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?K:"disabled",...M===void 0?{}:{report:c?.mergePageReport(M,u)??M}}),observationCount:u.length})}async function te(){if(!e.dataFlow.enabled){be();return}let c=le(),u=c===void 0?void 0:ye(c),S=A.flatMap(Q=>{let _e=ye(Q);return _e===void 0?[]:[_e]}),$=++L,m=y;c!==void 0&&(c.dataFlowStatus="loading"),K=S.length===0?"idle":"loading",be();let[F,G]=await Promise.allSettled([u===void 0?Promise.resolve(void 0):s.componentDataFlowReport(u),S.length===0?Promise.resolve(void 0):s.pageDataFlowReport({schemaVersion:1,targets:S})]);!i||$!==L||m!==y||(c!==void 0&&A.includes(c)&&(F.status==="fulfilled"?(c.dataFlowReport=F.value,c.dataFlowStatus=F.value===void 0?"idle":"ready"):(c.dataFlowReport=void 0,c.dataFlowStatus="error")),G.status==="fulfilled"?(M=G.value,K=G.value===void 0?"idle":"ready"):(M=void 0,K="error"),be())}function st(c){if(!(c.elementContext===void 0||c.styles===void 0))return{id:c.id,instruction:c.instruction,page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code}}}function se(){let c=A.flatMap(S=>{let $=st(S);return $===void 0?[]:[$]});if(c.length===0){x.clear();return}let u=new Set(c.map(({id:S})=>S));x.save({...v!==void 0&&u.has(v)?{activeTargetId:v}:{},open:B,sequence:q,targets:c})}function Ue(c,u){return i&&u===y&&b.status!=="idle"&&A.includes(c)}function xe(){let c=A.reduce((u,S)=>u+S.instruction.trim().length,0);return A.length>0&&c<=4e3&&A.every(u=>u.instruction.trim().length>0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function tt(){let c=A.flatMap(u=>{let S=st(u);return S===void 0?[]:[S]});if(!(c.length===0||c.length!==A.length))return Object.freeze({locale:n.locale(),targets:c})}function qe(){let c=n.messages().summary;return A.map((u,S)=>{let $=Rr({resolution:u.resolution,...u.code===void 0?{}:{code:u.code},...u.styles===void 0?{}:{styles:u.styles},apiStatus:u.apiStatus,collectionStatus:u.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},c);return`${c.target(S+1,u.id===v)}
|
|
858
|
+
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function es(e){let t=e.target;return t instanceof Element&&t.closest("a, button, input, select, textarea, summary, [contenteditable='true']")!==null}function ts(e){let t=ie(e,"","spotpatch-execution-island");t.hidden=!0,t.setAttribute("aria-hidden","true");let o=$n(e,void 0,"spotpatch-fallback-execution-island");o.classList.add("spotpatch-execution-logo");let n=g(e,"span");return t.append(o,n),Object.freeze({canExpand:()=>!1,isExpanded:()=>!1,root:t,setExpanded:()=>{},render(i){let l=[i.headline,i.action,i.meta].filter(a=>a.length>0).join(" · ");n.textContent=l,t.setAttribute("aria-label",l)},dispose(){}})}function ns(e,t,o){return t.append(o),Object.freeze({root:t,refreshButton:ie(e,""),styles:e.createElement("style"),dispose:()=>{},render:()=>{},resetView:()=>{}})}function xr(e,t,o=Object.freeze({enabled:!1}),n="auto",i=!1,l=!1,a="vite",d="",C=!1){let x=ur(e,n),w=e.defaultView;if(w===null)throw new Error("SpotPatch requires a document with an associated window.");let V=w,b=Ar(V,mr(V,d),_t),s=x.messages(),W="idle",H="change",A="",v="",q=!1,B=!1,I,y,R,L,M,K,E=e.createElement("spotpatch-root");E.setAttribute(Nt,"");let T=E.attachShadow({mode:"open"}),O=g(e,"div");O.className="spotpatch-floating-surface",O.dataset.scene="pill",O.dataset.tone="neutral";let _=ie(e,s.trigger.select,"spotpatch-trigger");_.title=s.trigger.title(t),_.setAttribute("aria-pressed","false");let pe=sr(),ve=pe?.createExecutionIsland(e),D=ve??ts(e),N=D.root,le=g(e,"div");le.className="spotpatch-highlight",le.hidden=!0;let ye=g(e,"span");ye.className="spotpatch-highlight-label",le.append(ye);let be=g(e,"div");be.className="spotpatch-selection-highlights",be.setAttribute("aria-hidden","true");let te=g(e,"section");te.className="spotpatch-dialog",te.hidden=!0,te.tabIndex=-1,te.setAttribute("role","dialog"),te.setAttribute("aria-labelledby","spotpatch-selection-title");let st=g(e,"div");st.className="spotpatch-shell";let se=g(e,"header");se.className="spotpatch-header",se.setAttribute("data-spotpatch-drag-handle","");let Ue=g(e,"div");Ue.className="spotpatch-brand-row";let xe=g(e,"div");xe.className="spotpatch-brand";let tt=g(e,"span");tt.className="spotpatch-brand-copy";let qe=g(e,"span");qe.className="spotpatch-brand-name";let Ge=g(e,"span");Ge.className="spotpatch-brand-context",tt.append(qe,Ge),xe.append($n(e),tt);let ee=g(e,"span");ee.className="spotpatch-header-controls";let de=g(e,"a");de.className="spotpatch-repository",de.href=Pn,de.target="_blank",de.rel="noopener noreferrer";let Ne=ie(e,"","spotpatch-locale"),nt=ie(e,"⌖","spotpatch-reset-position"),Ke=ie(e,"×","spotpatch-close");ee.append(de,Ne,nt,Ke),Ue.append(xe,ee);let ct=g(e,"h2");ct.id="spotpatch-selection-title",ct.className="spotpatch-title";let ot=g(e,"p");ot.className="spotpatch-subtitle";let lt=g(e,"div");lt.className="spotpatch-target-row";let De=g(e,"span");De.className="spotpatch-target-label";let ne=g(e,"span");ne.className="spotpatch-context-state",ne.dataset.state="loading",ne.textContent=s.context.collecting,lt.append(De,ne),se.append(Ue,ct,ot,lt);let Re=g(e,"div");Re.className="spotpatch-body";let Je=g(e,"div");Je.className="spotpatch-selection-panel";let U=g(e,"section");U.className="spotpatch-targets";let je=g(e,"div");je.className="spotpatch-targets-heading";let Ce=g(e,"span"),St=g(e,"span");St.className="spotpatch-targets-meta";let Xe=g(e,"span");Xe.className="spotpatch-target-complete";let fe=g(e,"span");fe.className="spotpatch-target-budget",fe.setAttribute("aria-live","polite");let Ye=g(e,"span");Ye.className="spotpatch-target-count",St.append(Xe,fe),lt.append(Ye),je.append(Ce,St);let Ze=g(e,"div");Ze.className="spotpatch-target-progress",Ze.setAttribute("aria-hidden","true");let Se=g(e,"div");Se.className="spotpatch-target-progress-fill",Ze.append(Se);let we=g(e,"div");we.className="spotpatch-target-list",U.append(je,Ze,we);let ze=g(e,"details");ze.className="spotpatch-diagnostics";let Rt=g(e,"summary"),Ve=g(e,"span"),We=g(e,"span");We.className="spotpatch-source-peek",We.textContent=s.diagnostics.resolving,Rt.append(Ve,We);let dt=g(e,"pre");dt.className="spotpatch-summary",ze.append(Rt,dt);let P=ar(e,o,x),rt=g(e,"div");function Z(){q&&b.requestReconcile()}let Y=l?gn()?.createPanel(e,a,x.locale,d,x.subscribe,Z,kr,Pr):void 0;rt.append(U,P.root,...Y===void 0?[]:[Y.root]);let Me=qt()?.createPanel(e,i,x.locale,rt,ze,Z)??ns(e,rt,ze);Je.append(Me.root);let pt=g(e,"div");pt.className="spotpatch-preview-panel",pt.hidden=!0;let Fe=g(e,"pre");Fe.className="spotpatch-prompt",Fe.tabIndex=0,Fe.setAttribute("aria-label",s.diagnostics.promptAriaLabel),pt.append(Fe),Re.append(Je,pt);let re=g(e,"footer");re.className="spotpatch-actions";let Oe=g(e,"div");Oe.className="spotpatch-context-state spotpatch-editor-feedback",Oe.dataset.state="idle",Oe.setAttribute("role","status"),Oe.setAttribute("aria-live","polite"),Oe.hidden=!0;let He=ie(e,s.actions.addElement),at=ie(e,s.actions.reselect),c=ie(e,s.actions.openEditor),u=ie(e,s.actions.preview,"spotpatch-primary"),S=ie(e,s.actions.copy,"spotpatch-primary"),$=ie(e,s.actions.back),m=g(e,"div");m.className="spotpatch-secondary-actions";let F=g(e,"div");F.className="spotpatch-primary-actions",He.classList.add("spotpatch-icon-action"),He.dataset.compactIcon="+",P.testButton.classList.add("spotpatch-icon-action"),P.testButton.dataset.compactIcon="✓",c.classList.add("spotpatch-secondary-action"),at.classList.add("spotpatch-secondary-action"),m.append(c,at),F.append(P.testButton,He,P.runButton,...Y===void 0?[]:[Y.sendButton],u,P.cancelButton,P.applyButton,P.revertButton,P.resetButton,S,$),re.append(Oe,m,F);let G=C?fn()?.createPanel({document:e,locale:x.locale,subscribeLocale:x.subscribe,changeRoot:Me.root,changeActions:re,announce:An,onModeChange(r,f,h){H=r,A=f,v=h,E.isConnected&&en(W)},onExecutionChange(r){I=r,B=!1,Ee()},onViewChange:Z}):void 0;G!==void 0&&Je.prepend(G.root),st.append(se,Re,re),te.append(st);let Q=g(e,"div");Q.className="spotpatch-live",Q.setAttribute("aria-live","polite"),Q.setAttribute("aria-atomic","true");let _e=[Zi(e),...pe===void 0?[]:[pe.createStyles(e)],Me.styles,...G===void 0?[]:[G.styles],...Y===void 0?[]:[Y.styles]],Ft=Yi(e);if(Ft!==void 0)for(let r of _e)r.nonce=Ft;T.append(..._e,be,le,O,Q),O.append(_,te,N),e.documentElement.append(E),b.registerSurface(O);let Qe=pe===void 0||ve===void 0?void 0:pe.createController(e,Object.freeze({execution:ve.elements,pill:_,planner:te,surface:O}),b.reconcile),hn=()=>{Qe?.cancel()};b.attachDraggable(_,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.attachDraggable(se,O,{canStartDrag:r=>!b.isCompact()&&!es(r),onDragStart:hn}),b.attachDraggable(N,O,{onDragStart:hn,suppressClickOnDrag:!0}),b.reconcile();let yn=!1,Ht=!1,Kt="",Jt=!0,$e=[],Xt=0,qn="idle",Gn=Object.freeze({component:Object.freeze({status:i?"idle":"disabled"}),page:Object.freeze({status:i?"idle":"disabled"}),observationCount:0});function Yt(){let r=$e.find(f=>f.active);return Object.freeze(r===void 0?{label:s.context.selectedElement,source:""}:{label:r.label,source:r.source})}function Lt(){let r=Yt();return r.source.length===0?r.label:`${r.label} · ${r.source}`}function Kn(){return K=new Date().toISOString(),K}function Jn(){return K??Kn()}function Zt(r){M!==void 0&&(V.clearTimeout(M),M=void 0),r&&(R=void 0,L=void 0)}function bn(r){return L===r?!1:(R===r||(Zt(!1),R=r,M=V.setTimeout(()=>{M=void 0,E.isConnected&&(L=r,I=void 0,K=void 0,B=!1,q=!1,Ee())},Xi)),!0)}function Lr(r){return r.startsWith("claude")?s.execution.claude:r.startsWith("codex")?s.execution.codex:r}function Xn(r){return Object.freeze({...r.detail===void 0?{}:{detail:r.detail},key:r.key,kind:r.kind,label:s.execution.activityLane(r.kind,r.detail),state:r.state})}function Dt(r,f,h,k="active"){return Object.freeze({...h===void 0?{}:{detail:h},key:r,kind:f,label:s.execution.activityLane(f,h),state:k})}function Ee(){let r=W==="inspecting",f=!q||r,h=f?{scene:r?"capturing":"pill",tone:r?"capturing":"neutral",headline:_.textContent,action:"",meta:"",recentActivities:Object.freeze([])}:!B&&I!==void 0?I:{scene:"planner",tone:"ready",headline:s.dialog.editTitle,action:s.dialog.editSubtitle,meta:s.context.ready,recentActivities:Object.freeze([])};if(Qe!==void 0){Qe.render(h,()=>{D.render(h)});return}D.render(h),O.dataset.scene=h.scene,O.dataset.tone=h.tone;let k=h.scene==="planner";_.hidden=!f,_.inert=!f,te.hidden=!k,te.inert=!k,te.setAttribute("aria-hidden",String(!k)),N.hidden=f||k,N.inert=f||k,N.setAttribute("aria-hidden",String(f||k)),b.reconcile()}function kr(r){if(r===null?(y=void 0,K=void 0):y!==void 0&&r.phase!=="failed"&&r.phase!=="delivery-unknown"?Sn():(r.phase==="failed"||r.phase==="delivery-unknown")&&(y=void 0),r!==null&&!B){let f=r.phase==="failed"||r.phase==="delivery-unknown",h=r.phase==="completed",k=f||h?void 0:Jn();(f||h)&&(K=void 0);let j=`dispatch:${String(r.revision)}`;if(h&&!bn(j)){I=void 0,Ee();return}let ce=Lr(r.adapterKind),Le=Yt(),ue=r.phase==="queued"||r.phase==="dispatching"||r.phase==="dispatched"?"dispatch":h?"sync":"unknown",ke=Dt(`dispatch:${String(r.revision)}:${r.phase}`,ue,r.phase,f?"failure":h?"success":"active"),z=f?"failed":h?"success":r.phase==="working"?"running":"handoff";I={scene:z,tone:f?"danger":h?"success":"running",headline:h?s.execution.completedTitle:f?s.execution.failedTitle:z==="running"?s.execution.runningTitle(Le.label):s.execution.dispatchingTitle(ce),action:h?s.execution.resultReturned:Le.source,expandedHeadline:h?s.execution.expandedCompletedTitle:f?s.execution.failedTitle:z==="running"?s.execution.expandedRunningTitle(ce):s.execution.dispatchingTitle(ce),expandedAction:h?s.execution.resultReturned:Lt(),meta:f?s.execution.failedStatus:h?s.execution.completedStatus:z==="running"?s.execution.runningStatus:s.execution.dispatchingStatus,activity:ke,recentActivities:Object.freeze([ke]),...k===void 0?{}:{startedAt:k}}}else r===null&&(I=void 0);Ee()}function Pr(r){let f=r?.task;if(r===void 0||f===void 0||B)return;let h=f.managedPhase,k=h==="failed"||h==="cleanup-warning",j=h==="completed"||h==="review-required",ce=h==="cancelled";if(k||ce?y=void 0:y!==void 0&&Sn(),ce){I=void 0,K=void 0,Ee();return}let Le=k||j?void 0:Jn();if((k||j)&&(K=void 0),h==="completed"&&!bn(`managed:${String(f.revision)}`)){I=void 0,Ee();return}let ue=k?"failed":j?"success":h==="preparing"?"handoff":"running",ke=k?"danger":j?"success":"running",z=s.execution.codex,X=Yt(),et=h==="preparing"?"prepare":h==="auditing"?"audit":h==="validating"?"check":h==="applying"?"apply":j?"sync":"unknown",ut=f.checks.at(-1),gt=f.files.at(-1),ft=h==="validating"?ut?.id:h==="auditing"||h==="applying"?gt?.path:void 0,Ct=Dt(`managed:${String(f.revision)}:${h}:${ft??""}`,et,ft,k?"failure":j?"success":"active"),$t=Object.freeze([...f.files.slice(-2).map(mt=>Dt(`managed-file:${String(f.revision)}:${mt.path}`,"patch",mt.path,"success")),...f.checks.slice(-2).map(mt=>Dt(`managed-check:${String(f.revision)}:${mt.id}`,"check",mt.id,mt.outcome==="passed"?"success":"failure")),Ct]);I={scene:ue,tone:ke,headline:j?s.execution.completedTitle:k?s.execution.failedTitle:ue==="handoff"?s.execution.dispatchingTitle(z):h==="validating"?s.execution.activityAction("check",ft):s.execution.runningTitle(X.label),action:j?f.files.length===0?s.execution.resultReturned:s.execution.resultSummary(f.files.length):X.source,expandedHeadline:j?s.execution.expandedCompletedTitle:k?s.execution.failedTitle:ue==="handoff"?s.execution.dispatchingTitle(z):s.execution.expandedRunningTitle(z),expandedAction:j?s.execution.resultReturned:Lt(),meta:k?s.execution.failedStatus:j?s.execution.completedStatus:h==="validating"?s.execution.checkingStatus:ue==="handoff"?s.execution.dispatchingStatus:s.execution.runningStatus,activity:Ct,recentActivities:$t,...Le===void 0?{}:{startedAt:Le}},Ee()}function Ir(r,f){if(!q)return;Zt(!0);let h=Kn();B=!1;let k=Dt(`dispatch-start:${Lt()}`,"dispatch",Lt());I={scene:"agent-charging",tone:"running",headline:s.execution.receivingTitle,action:Lt(),expandedHeadline:s.execution.receivingTitle,expandedAction:Lt(),meta:s.execution.receivingStatus,activity:k,recentActivities:Object.freeze([k]),startedAt:h},Ee(),Qe?.dispatch(r,f)}function Yn(r,f){!q||r.disabled||(y=Object.freeze({source:r,target:f}))}function Sn(){let r=y;y=void 0,!(r===void 0||!r.source.isConnected||!r.target.isConnected)&&Ir(r.source,r.target)}function En(r){qn=r,Oe.dataset.state=r,Oe.hidden=r==="idle",Oe.textContent=r==="opening"?s.announcements.editorOpening:r==="success"?s.announcements.editorOpened:r==="error"?s.announcements.editorFailed:"",Z()}function Nr(r){return r.status==="ready"?s.targets.statusReady:r.status==="warning"?s.targets.statusPartial:s.targets.statusCollecting}function Qt(r,f){let h=f===0?0:r/f;Se.style.width=`${String(h*100)}%`}function Zn(r){let f=we.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(f).find(h=>r===void 0||h.dataset.targetInstructionId===r)}function Qn(r,f){let h=T.activeElement?.closest("textarea[data-target-instruction-id]"),k=h?.dataset.targetInstructionId,j=h?.selectionStart,ce=h?.selectionEnd;$e=r.map(z=>Object.freeze({...z})),Xt=f,we.replaceChildren();let Le=r.filter(z=>z.instruction.trim().length>0).length,ue=r.reduce((z,X)=>z+X.instruction.trim().length,0);Qt(Le,r.length),Ye.textContent=s.targets.count(r.length,f),Xe.textContent=s.targets.complete(Le,r.length);let ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?s.targets.instructionBudgetExceeded(ue,4e3):s.targets.instructionBudget(ue,4e3),He.disabled=!Jt||r.length>=f,He.title=r.length>=f?s.targets.limitTitle(f):s.targets.addTitle,De.textContent=r.length===1?r[0]?.label??s.context.selectedElement:s.context.selectedCount(r.length);for(let[z,X]of r.entries()){let et=g(e,"div");et.className="spotpatch-target-item",et.dataset.active=String(X.active),et.dataset.status=X.status,et.dataset.targetId=X.id;let ut=g(e,"div");ut.className="spotpatch-target-summary";let gt=ie(e,"","spotpatch-target-select");gt.dataset.activateTargetId=X.id,gt.setAttribute("aria-label",s.targets.activate(z+1)),gt.setAttribute("aria-expanded",String(X.active));let ft=g(e,"span");ft.className="spotpatch-target-index",ft.textContent=String(z+1);let Ct=g(e,"span");Ct.className="spotpatch-target-copy";let $t=g(e,"span");$t.className="spotpatch-target-name",$t.textContent=X.label;let mt=g(e,"span");mt.className="spotpatch-target-source",mt.textContent=`${Nr(X)} · ${X.source}`,Ct.append($t,mt);let co=X.instruction.trim().length>0,tn=g(e,"span");tn.className="spotpatch-target-state",tn.dataset.complete=String(co),tn.textContent=co?s.targets.instructionReady:s.targets.instructionMissing,gt.append(ft,Ct,tn);let Bt=ie(e,"↗","spotpatch-target-open");Bt.dataset.openTargetId=X.id,Bt.disabled=!X.canOpenEditor,Bt.setAttribute("aria-label",s.actions.openTarget(z+1)),Bt.title=s.actions.openTarget(z+1);let Ut=ie(e,"×","spotpatch-target-remove");if(Ut.dataset.removeTargetId=X.id,Ut.disabled=!Jt,Ut.setAttribute("aria-label",s.targets.remove(z+1)),Ut.title=s.targets.removeTitle,ut.append(gt,Bt,Ut),et.append(ut),X.active){let xn=g(e,"label");xn.className="spotpatch-target-editor";let Rn=g(e,"span");Rn.className="spotpatch-target-editor-head";let Cn=g(e,"span");Cn.className="spotpatch-target-editor-label",Cn.textContent=s.targets.instructionLabel(X.label);let Tn=g(e,"span");Tn.className="spotpatch-target-editor-count",Tn.textContent=s.targets.instructionCount(X.instruction.length,2e3),Rn.append(Cn,Tn);let Tt=g(e,"textarea");Tt.rows=4,Tt.maxLength=2e3,Tt.value=X.instruction,Tt.placeholder=s.targets.instructionPlaceholder,Tt.disabled=!Jt,Tt.dataset.targetInstructionId=X.id,Tt.setAttribute("aria-label",s.targets.instructionLabel(X.label)),xn.append(Rn,Tt),et.append(xn)}we.append(et)}if(k!==void 0){let z=Zn(k);z?.focus({preventScroll:!0}),j!==void 0&&ce!==void 0&&z?.setSelectionRange(j,ce)}Z()}function Dr(r,f){$e=$e.map(z=>z.id===r?Object.freeze({...z,instruction:f}):z);let h=Array.from(we.querySelectorAll(".spotpatch-target-item")).find(z=>z.dataset.targetId===r);if(h===void 0)return;let k=f.trim().length>0,j=h.querySelector(".spotpatch-target-state"),ce=h.querySelector(".spotpatch-target-editor-count");j!==null&&(j.dataset.complete=String(k),j.textContent=k?s.targets.instructionReady:s.targets.instructionMissing),ce!==null&&(ce.textContent=s.targets.instructionCount(f.length,2e3));let Le=$e.filter(z=>z.instruction.trim().length>0).length;Xe.textContent=s.targets.complete(Le,$e.length),Qt(Le,$e.length);let ue=$e.reduce((z,X)=>z+X.instruction.trim().length,0),ke=ue>4e3;fe.dataset.state=ke?"over":"ready",fe.textContent=ke?s.targets.instructionBudgetExceeded(ue,4e3):s.targets.instructionBudget(ue,4e3)}function Mr(r){be.replaceChildren();for(let[f,h]of r.entries()){let k=g(e,"div");k.className="spotpatch-selection-highlight",k.dataset.targetId=h.id,k.dataset.active=String(h.active),k.style.transform=`translate(${String(h.rect.x)}px, ${String(h.rect.y)}px)`,k.style.width=`${String(h.rect.width)}px`,k.style.height=`${String(h.rect.height)}px`;let j=g(e,"span");j.textContent=`${String(f+1)} · ${h.label}`,k.append(j),be.append(k)}}function eo(r){let f=s.summary,h=Qi(r,f.source);We.textContent=h??s.diagnostics.noExactSource;let k=`${f.browserContext}: ${f.collectionStatuses.ready}`,j=`${f.browserContext}: ${f.collectionStatuses.loading}`,ce=`${f.browserContext}: ${f.collectionStatuses.failed}`,Le=`${f.api}: ${f.apiStatuses.loading}`,ue=`${f.api}: ${f.apiStatuses.failed}`;r.includes(k)&&!r.includes(j)&&!r.includes(Le)&&!r.includes(ce)&&!r.includes(ue)?(ne.dataset.state="ready",ne.textContent=s.context.ready):r.includes(ce)||r.includes(ue)?(ne.dataset.state="warning",ne.textContent=s.context.partial):(ne.dataset.state="loading",ne.textContent=s.context.collecting)}function to(r,f,h){yn=f,Ht=h,Kt=r,dt.textContent=r,c.disabled=!f,u.disabled=!h,P.setContextReady(h),Y?.setContextReady(h),G?.setSelectionPreview({contextReady:$e.every(k=>k.status!=="loading"),targetCount:$e.length,sourceCount:$e.filter(k=>k.canOpenEditor).length}),eo(r),Z()}function en(r){W=r;let f=r==="selected",h=r==="previewing";Je.hidden=!f,pt.hidden=!h,at.hidden=!f,He.hidden=!f,c.hidden=!f,u.hidden=!f,m.hidden=!f,P.setSelectionVisible(f),Y?.setSelectionVisible(f),G?.setSelectionVisible(f),S.hidden=!h,$.hidden=!h,ct.textContent=h?s.dialog.previewTitle:H==="ask"&&A.length>0?A:s.dialog.editTitle,ot.textContent=h?s.dialog.previewSubtitle:H==="ask"&&v.length>0?v:s.dialog.editSubtitle,Ee()}function no(){s=x.messages(),qe.textContent=s.brand.name,Ge.textContent=s.brand.context,de.textContent=s.brand.repository,de.title=s.brand.repositoryTitle,de.setAttribute("aria-label",s.brand.repositoryTitle),Ne.textContent=s.alternateLocaleName,Ne.title=s.switchLocale,Ne.setAttribute("aria-label",s.switchLocale),nt.title=s.floatingSurface.resetPosition,nt.setAttribute("aria-label",s.floatingSurface.resetPosition),Ke.setAttribute("aria-label",s.dialog.close),Ke.title=s.dialog.close,se.title=s.floatingSurface.dragHandle,U.setAttribute("aria-label",s.targets.ariaLabel),Ce.textContent=s.targets.title,Ve.textContent=s.diagnostics.title,Fe.setAttribute("aria-label",s.diagnostics.promptAriaLabel),He.textContent=s.actions.addElement,at.textContent=s.actions.reselect,c.textContent=s.actions.openEditor,u.textContent=s.actions.preview,S.textContent=s.actions.copy,$.textContent=s.actions.back,Me.render(Gn),_.title=s.trigger.title(t),_.textContent=W==="inspecting"?s.trigger.stop:s.trigger.select,en(W),En(qn),$e.length>0?Qn($e,Xt):(Ye.textContent=s.targets.count(0,Xt),Xe.textContent=s.targets.complete(0,0),Qt(0,0),fe.dataset.state="ready",fe.textContent=s.targets.instructionBudget(0,4e3),De.textContent=s.context.selectedElement),Kt.length>0?eo(Kt):(We.textContent=s.diagnostics.resolving,ne.textContent=s.context.collecting)}function An(r){Q.textContent="",Q.textContent=r}function oo(){b.reset(),An(s.floatingSurface.positionReset)}ze.addEventListener("toggle",Z),Ne.addEventListener("click",x.toggle),nt.addEventListener("click",oo);let ro=()=>{Yn(P.runButton,P.root)},ao=()=>{Y!==void 0&&Yn(Y.sendButton,Y.root)},io=()=>{if(D.canExpand()&&!D.isExpanded()){Qe===void 0?(D.setExpanded(!0),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!0)});return}Zt(!1),B=!0,Ee()},so=r=>{r.key!=="Escape"||!D.isExpanded()||(r.preventDefault(),r.stopPropagation(),Qe===void 0?(D.setExpanded(!1),b.reconcile()):Qe.updateLayout(()=>{D.setExpanded(!1)}))};P.runButton.addEventListener("click",ro),Y?.sendButton.addEventListener("click",ao),N.addEventListener("click",io),N.addEventListener("keydown",so);let Fr=x.subscribe(no);return no(),Object.freeze({host:E,triggerButton:_,addTargetButton:He,targetList:we,reselectButton:at,openEditorButton:c,repositoryLink:de,previewButton:u,copyButton:S,dataFlowRefreshButton:Me.refreshButton,backButton:$,closeButton:Ke,agentProviderSelect:P.providerSelect,agentModelSelect:P.modelSelect,agentModeSelect:P.modeSelect,agentConsentCheckbox:P.consentCheckbox,agentWorkspaceConsentCheckbox:P.workspaceConsentCheckbox,agentTestButton:P.testButton,agentRunButton:P.runButton,agentCancelButton:P.cancelButton,agentApplyButton:P.applyButton,agentRevertButton:P.revertButton,agentResetButton:P.resetButton,...Y===void 0?{}:{externalHandoffPanel:Y},...G===void 0?{}:{contextualAskPanel:G},renderStatus(r){let f=r==="inspecting";r==="idle"||f?q=!1:q=!0,_.setAttribute("aria-pressed",String(f)),_.textContent=f?s.trigger.stop:s.trigger.select,en(r)},renderEditorStatus:En,renderDataFlow(r){Gn=r,Me.render(r),Z()},showHighlight(r,f){le.hidden=!1,le.style.transform=`translate(${String(r.x)}px, ${String(r.y)}px)`,le.style.width=`${String(r.width)}px`,le.style.height=`${String(r.height)}px`,ye.textContent=f,De.textContent=f},hideHighlight(){le.hidden=!0,ye.textContent=""},showSelectionHighlights:Mr,hideSelectionHighlights(){be.replaceChildren()},showSelection(r,f,h){to(r,f,h),q=!0,en(W==="previewing"?"previewing":"selected")},updateSelection:to,renderTargets:Qn,updateTargetInstruction:Dr,setPreviewEnabled(r){Ht=r,u.disabled=!r,P.setContextReady(r),Y?.setContextReady(r)},hideSelection(){q=!1,B=!1,I=void 0,we.replaceChildren(),$e=[],Xt=0,Kt="",En("idle"),Ye.textContent=s.targets.count(0,0),Xe.textContent=s.targets.complete(0,0),Qt(0,0),De.textContent=s.context.selectedElement,dt.textContent="",Fe.textContent="",We.textContent=s.diagnostics.resolving,ne.dataset.state="loading",ne.textContent=s.context.collecting,c.disabled=!0,u.disabled=!0,yn=!1,Ht=!1,P.setContextReady(!1),P.setSelectionVisible(!1),Y?.setContextReady(!1),Y?.setSelectionVisible(!1),G?.setSelectionVisible(!1),P.setEditingEnabled(!0),P.resetJob(),Me.resetView(),Ee()},hideSelectionTemporarily(){q=!1,B=!1,I=void 0,Ee()},showPreview(r){Fe.textContent=r,Z()},readAgentSelection(){return P.readSelection()},agentConsentGranted(){return P.consentGranted()},setAgentProviderConsent(r){P.setProviderConsent(r)},setAgentEditingEnabled(r){Jt=r,He.disabled=!r,at.disabled=!r,we.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(f=>{f.disabled=!r}),c.disabled=!yn,u.disabled=!r||!Ht,Y?.setContextReady(r&&Ht),P.setEditingEnabled(r),Z()},renderAgentCapability(r,f,h,k){P.renderCapability(r,f,h,k),r==="error"&&(y=void 0,Ee());let j=r==="ready"&&h?.state==="agent-ready";u.classList.toggle("spotpatch-primary",!j),Z()},renderAgentWorkspaceHealth(r,f,h){P.renderWorkspaceHealth(r,f,h),r==="blocked"&&(y=void 0,Ee()),Z()},renderAgentJob(r,f,h,k){P.renderJob(r,f,h,k),y!==void 0&&r.status!=="failed"&&r.status!=="cancelled"&&Sn(),(r.status==="failed"||r.status==="cancelled")&&(y=void 0);let j=r.status==="awaiting-review"||r.status==="applied"||r.status==="completed"||r.status==="reverted",ce=r.status==="failed",Le=r.status==="cancelled",ue=r.status==="applied"||r.status==="completed"||r.status==="reverted",ke=j?"success":ce?"failed":r.status==="queued"||r.status==="preparing"?"handoff":"running";if(!B){if(ue&&!bn(`job:${r.jobId}:${r.status}`)){I=void 0,Ee(),Z();return}let z=r.providerLabel,X=Yt(),et=Object.freeze(h.map(Xn)),ut=h.at(-1),gt=r.status==="queued"||r.status==="preparing"?"prepare":r.status==="validating"?"check":r.status==="applying"||r.status==="reverting"?"apply":r.status==="awaiting-review"||j?"sync":"unknown",ft=Dt(`job-phase:${r.jobId}:${r.status}:${r.updatedAt}`,gt,void 0,j?"success":ce?"failure":"active"),Ct=r.status==="running"&&ut!==void 0?Xn(ut):ft;I=Le?void 0:{scene:ke,tone:j?"success":ce?"danger":"running",headline:j?s.execution.completedTitle:ce?s.execution.failedTitle:ke==="handoff"?s.execution.dispatchingTitle(z):r.status==="validating"?s.execution.activityAction("check",ut?.detail):r.status==="applying"||r.status==="reverting"?s.execution.activityAction(gt):s.execution.runningTitle(X.label),action:j?f===void 0||f.files.length===0?s.execution.resultReturned:s.execution.resultSummary(f.files.length):ut?.detail??X.source,expandedHeadline:j?s.execution.expandedCompletedTitle:ce?s.execution.failedTitle:ke==="handoff"?s.execution.dispatchingTitle(z):s.execution.expandedRunningTitle(z),expandedAction:j?f===void 0||f.files.length===0?s.execution.resultReturned:s.execution.resultSummary(f.files.length):Lt(),meta:j?s.execution.completedStatus:ce?s.execution.failedStatus:r.status==="validating"?s.execution.checkingStatus:ke==="handoff"?s.execution.dispatchingStatus:s.execution.runningStatus,activity:Ct,recentActivities:et.length===0?Object.freeze([ft]):et,startedAt:r.createdAt}}Ee(),Z()},resetAgentJob(){P.resetJob(),K=void 0,I!==void 0&&(I=void 0,B=!1,Ee()),Z()},focusTargetInstruction(r){Zn(r)?.focus({preventScroll:!0})},focusPrompt(){Fe.focus({preventScroll:!0})},announce:An,locale:x.locale,messages:x.messages,agentWorkspaceConsentGranted:P.workspaceConsentGranted,subscribeLocale:x.subscribe,dispose(){ze.removeEventListener("toggle",Z),Ne.removeEventListener("click",x.toggle),nt.removeEventListener("click",oo),P.runButton.removeEventListener("click",ro),Y?.sendButton.removeEventListener("click",ao),N.removeEventListener("click",io),N.removeEventListener("keydown",so),Fr(),Me.dispose(),Y?.dispose(),G?.dispose(),P.dispose(),Qe?.dispose(),D.dispose(),Zt(!0),b.dispose(),E.remove()}})}function os(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,l=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${l===void 0?"":`:${String(l)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,l):o.unavailable}function Rr(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${{next:"Next.js",vite:"Vite",astro:"Astro"}[e.framework]}: ${e.frameworkVersion}`,`${t.source}: ${os(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
859
|
+
`)}function Cr(e,t){return`${e}:${t}`}var rs=Object.freeze({list_files:"discover",search_text:"search",read_file:"read",replace_text:"patch",apply_patch:"patch",run_check:"check"});function as(e){return rs[e]??"unknown"}function is(e){if(e.type==="tool"){let t=e.data.relativePath??e.data.checkLabel;return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,kind:as(e.data.toolName),...t===void 0?{}:{detail:t},label:`${e.data.toolName}${t===void 0?"":` · ${t}`} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"})}if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,kind:"check",detail:e.data.result.label,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function Tr(e){let t=y=>vo(y)??p.INTERNAL_ERROR,o=y=>e.view.messages().errors[t(y)],n=new Map,i=new Set,l=new Map,a=0,d,C,x=!1,w=!1,V=()=>e.view.readAgentSelection(),b=y=>`${y.providerProfileId}:${y.applyMode}`,s=async y=>{e.view.renderAgentWorkspaceHealth("checking");try{let R=await e.api.agentWorkspaceHealth();return y!==a||e.view.renderAgentWorkspaceHealth(R.state,R,R.errorCode),R}catch(R){throw y===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(R)),R}},W=y=>{d!==void 0&&e.view.renderAgentJob(d,C,Object.freeze([...l.values()]),y??d.errorCode)},H=()=>{let y=V();if(y===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(b(y)));let R=n.get(Cr(y.providerProfileId,y.modelProfileId));R===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,R)},A=async y=>{let R=V();if(R===void 0)throw new Error("Agent provider selection is unavailable.");let L=Cr(R.providerProfileId,R.modelProfileId),M=n.get(L);if(M!==void 0)return M;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let K=await e.api.agentCapability(R);if(y!==a)return K;if(K.state!=="agent-ready")throw new J(K.errorCode??p.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(L,K),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,K),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),K},v=async(y,R)=>{try{let L=await e.api.agentResult(y);if(R!==a||L.snapshot.jobId!==y)return;d=L.snapshot,C=L.result,W()}catch(L){R===a&&W(t(L))}},q=async(y,R)=>{try{await e.api.agentEvents(y,L=>{if(R!==a||L.jobId!==y)return;L.type==="snapshot"&&(d=L.data.snapshot,d.status==="applied"&&!x&&(x=!0,e.onApplied()));let M=is(L);M!==void 0&&l.set(M.key,M),W()}),R===a&&await v(y,R)}catch(L){R===a&&!(L instanceof DOMException&&L.name==="AbortError")&&W(t(L))}},B=async y=>{let R=d;if(R===void 0||w)return;w=!0;let L=a;d=Object.freeze({...R,status:y==="apply"?"applying":y==="cancel"?"cancelling":"reverting",phaseMessage:y==="apply"?e.view.messages().agent.applying:y==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),W();try{let M=y==="apply"?await e.api.applyAgentJob(R.jobId):y==="cancel"?await e.api.cancelAgentJob(R.jobId):await e.api.revertAgentJob(R.jobId);if(L!==a)return;d=M,M.status==="applied"&&!x&&(x=!0,e.onApplied()),await v(M.jobId,L)}catch(M){if(L!==a)return;d=R,await v(R.jobId,L),W(t(M)),e.view.announce(o(M))}finally{L===a&&(w=!1)}},I=()=>{a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),H()};return Object.freeze({apply(){d?.canApply===!0&&B("apply")},beginSelection(){I();let y=a;e.ai.enabled&&s(y).catch(()=>{})},cancel(){d?.canCancel===!0&&B("cancel")},consentChanged(){let y=V();y!==void 0&&(e.view.agentConsentGranted()?i.add(b(y)):i.delete(b(y)))},disposeSelection(){let y=d?.canCancel===!0||d?.status==="cancelling"?d.jobId:void 0;a+=1,d=void 0,C=void 0,l.clear(),x=!1,w=!1,y!==void 0&&e.api.cancelAgentJob(y).catch(()=>{})},providerOrModelChanged(){a+=1,H(),s(a).catch(()=>{})},reset(){let y=x;I(),y?e.onReselectRequired():e.ai.enabled&&s(a).catch(()=>{})},revert(){d?.canRevert===!0&&B("revert")},run(){if(!e.ai.enabled||d!==void 0)return;let y=V(),R=e.getAnnotation();if(y===void 0||R===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(b(y));let L=++a;e.view.setAgentEditingEnabled(!1),s(L).then(async M=>{if(L!==a)return;if(M.state==="blocked")throw new J(M.errorCode??p.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(M.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new J(p.WORKTREE_DIRTY);let K=await e.api.createAgentJob({annotation:R,applyMode:y.applyMode,providerProfileId:y.providerProfileId,modelProfileId:y.modelProfileId,providerDataConsent:!0,...y.applyMode==="trusted-auto"?{trustedFastModeConsent:!0}:{},workingTreeMode:M.state==="consent-required"?"include-local-changes":"require-clean"});L===a&&(d=K,C=void 0,l.clear(),W(),q(K.jobId,L))}).catch(M=>{L===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(M),void 0,t(M)),e.view.announce(o(M)))})},testCapability(){if(!e.ai.enabled||d!==void 0)return;let y=++a;Promise.all([A(y),s(y)]).catch(R=>{y===a&&(e.view.renderAgentCapability("error",o(R),void 0,t(R)),e.view.announce(o(R)))})}})}function vr(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function zn(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function wr(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var cs=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Vn(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function ls(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function ds(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ps(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function Or(e,t={}){let o=ps(t),n=t.view??xr(o.document,e.shortcut,e.ai,e.locale,e.dataFlow.enabled,e.externalAgent.enabled,e.framework,e.sessionId,e.contextualAsk.enabled),i=t.api??wo({apiBase:e.apiBase,dataFlowReportMaxBytes:e.dataFlow.limits.reportMaxBytes,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),l=t.promptComposer??Jo({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??wr(o.window.navigator),d=t.createId??(()=>vr(o.window)),C=t.now??(()=>new Date().toISOString()),x=t.selectionSession??Qo(o.window,e.sessionId,e.maxTargets),w=x.load(),V=or({adapter:t.reactAdapter??ss({...e.dataFlow.enabled?{getComponentRegistration:c=>qt()?.getComponentRegistration(c)}:{},maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),b=Mn,s=!1,W,H,A=w?.targets.map(c=>{let u=Hn(c.source);return{id:c.id,resolution:Object.freeze({source:c.source,react:c.react}),apiStatus:u===void 0?"not-required":c.code===void 0?"failed":"connected",code:c.code,collectionStatus:"ready",dataFlowReport:void 0,dataFlowStatus:"idle",element:void 0,elementContext:c.element,instruction:c.instruction,marker:u,page:c.page,styles:c.styles}})??[],v=w?.activeTargetId,q=w?.sequence??0,B=w?.open??!1,I=!1,y=0,R=0,L=0,M,K="idle",E=!1,T="",O,_,pe,ve,D=new Map;function N(c){b=Xo(b,c),n.renderStatus(b.status)}function le(){return A.find(c=>c.id===v)??A.at(-1)}function ye(c){let u=c.resolution.react;if(u.componentSourceId!==void 0&&u.sourceVersion!==void 0)return Object.freeze({schemaVersion:1,componentSourceId:u.componentSourceId,sourceVersion:u.sourceVersion});let S=c.marker;return S===void 0?void 0:Object.freeze({schemaVersion:1,fileId:S.fileId,line:S.line,column:S.column})}function be(){let c=qt(),u=c?.observations(o.window.location.pathname)??[],S=le();n.renderDataFlow({component:Object.freeze({status:e.dataFlow.enabled?S?.dataFlowStatus??"idle":"disabled",...S?.dataFlowReport===void 0?{}:{report:c?.mergeComponentReport(S.dataFlowReport,u)??S.dataFlowReport}}),page:Object.freeze({status:e.dataFlow.enabled?K:"disabled",...M===void 0?{}:{report:c?.mergePageReport(M,u)??M}}),observationCount:u.length})}async function te(){if(!e.dataFlow.enabled){be();return}let c=le(),u=c===void 0?void 0:ye(c),S=A.flatMap(Q=>{let _e=ye(Q);return _e===void 0?[]:[_e]}),$=++L,m=y;c!==void 0&&(c.dataFlowStatus="loading"),K=S.length===0?"idle":"loading",be();let[F,G]=await Promise.allSettled([u===void 0?Promise.resolve(void 0):i.componentDataFlowReport(u),S.length===0?Promise.resolve(void 0):i.pageDataFlowReport({schemaVersion:1,targets:S})]);!s||$!==L||m!==y||(c!==void 0&&A.includes(c)&&(F.status==="fulfilled"?(c.dataFlowReport=F.value,c.dataFlowStatus=F.value===void 0?"idle":"ready"):(c.dataFlowReport=void 0,c.dataFlowStatus="error")),G.status==="fulfilled"?(M=G.value,K=G.value===void 0?"idle":"ready"):(M=void 0,K="error"),be())}function st(c){if(!(c.elementContext===void 0||c.styles===void 0))return{id:c.id,instruction:c.instruction,page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code}}}function se(){let c=A.flatMap(S=>{let $=st(S);return $===void 0?[]:[$]});if(c.length===0){x.clear();return}let u=new Set(c.map(({id:S})=>S));x.save({...v!==void 0&&u.has(v)?{activeTargetId:v}:{},open:B,sequence:q,targets:c})}function Ue(c,u){return s&&u===y&&b.status!=="idle"&&A.includes(c)}function xe(){let c=A.reduce((u,S)=>u+S.instruction.trim().length,0);return A.length>0&&c<=4e3&&A.every(u=>u.instruction.trim().length>0&&u.elementContext!==void 0&&u.styles!==void 0&&u.apiStatus!=="loading")}function tt(){let c=A.flatMap(u=>{let S=st(u);return S===void 0?[]:[S]});if(!(c.length===0||c.length!==A.length))return Object.freeze({locale:n.locale(),targets:c})}function qe(){let c=n.messages().summary;return A.map((u,S)=>{let $=Rr({resolution:u.resolution,...u.code===void 0?{}:{code:u.code},...u.styles===void 0?{}:{styles:u.styles},apiStatus:u.apiStatus,collectionStatus:u.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},c);return`${c.target(S+1,u.id===v)}
|
|
860
860
|
${$}`}).join(`
|
|
861
861
|
|
|
862
|
-
`)}function Ge(){let c=A.flatMap(u=>{if(!u.element?.isConnected)return[];let S=dn(u.element,o.window);return S===void 0?[]:[{id:u.id,label:Vn(u.element),rect:S,active:u.id===v}]});c.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(c)}function ee(c=!1){if(A.length===0)return;n.renderTargets(A.map(m=>({id:m.id,label:m.resolution.react.componentName??(m.element===void 0?m.elementContext?.tagName??"Element":Vn(m.element)),source:ls(m,n.messages().context.sourceUnavailable),canOpenEditor:m.marker!==void 0,status:ds(m),active:m.id===v,instruction:m.instruction})),e.maxTargets),Ge();let u=le(),S=qe(),$=u?.marker!==void 0;c?n.showSelection(S,$,xe()):n.updateSelection(S,$,xe())}function de(){if(!xe())return;let c=A.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let S=[...u.apiStatus==="failed"?["Source context could not be loaded."]:[],...u.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:u.instruction.trim(),page:u.page,source:u.resolution.source,react:u.resolution.react,element:u.elementContext,styles:u.styles,...u.code===void 0?{}:{code:u.code},warnings:S}});return po({id:d(),locale:n.locale(),createdAt:C(),page:zn(o.document,o.window),targets:c})}function Ne(c){n.showHighlight(zo(c,o.window),Vn(c))}function nt(){O?.isConnected===!0&&O.focus({preventScroll:!0}),O=void 0}function Ke(){for(let c of D.values())o.window.clearTimeout(c);D.clear()}function ct(){y+=1,s.cancelPending(),U.disposeSelection(),je?.cancelPending(),Ce?.cancelPending(),Ke(),_?.disconnect(),A=[],v=void 0,L+=1,M=void 0,K="idle",B=!1,I=!1,E=!1,T="",n.hideSelection(),n.hideSelectionHighlights(),x.clear(),nt()}function ot(){b.status==="inspecting"?N({type:"CANCEL"}):b.status==="selected"?N({type:"CLOSE"}):b.status==="previewing"&&(N({type:"BACK"}),N({type:"CLOSE"})),B=!1,se(),n.hideSelection(),n.hideSelectionHighlights(),nt(),n.hideHighlight()}function lt(){if(b.status!=="inspecting"||!E||A.length===0){ot();return}E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.focusTargetInstruction(v),n.announce(n.messages().announcements.addCancelled)}function De(){if(b.status==="inspecting"&&E){lt();return}if(b.status!=="idle"){ot();return}if(A.length>0){B=!0,N({type:"RESTORE"}),I||(U.beginSelection(),I=!0),ee(!0),te(),n.focusTargetInstruction(v),se();return}N({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function ne(c=n.messages().announcements.chooseAnother){b.status==="selected"&&(N({type:"RESELECT"}),ct(),n.hideHighlight(),n.announce(c))}function Re(){if(b.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}E=!0,N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function Je(){y+=1,Ke(),_?.disconnect();for(let c of A)c.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),ee(),x.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let U=Tr({ai:e.ai,api:s,getAnnotation:de,onApplied:Je,onReselectRequired(){ne(n.messages().announcements.reselectAfterChange)},view:n}),je=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?gn()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,de,e.sessionToken,o.window):void 0,Ce=e.contextualAsk.enabled&&n.contextualAskPanel!==void 0?fn()?.createWorkflow({...a===void 0?{}:{clipboard:a},createId:d,fetch:o.window.fetch.bind(o.window),getSelection:tt,onBusyChange(c){n.setAgentEditingEnabled(!c)},onConvert(){n.focusTargetInstruction(v)},async onOpenSource(c){await s.openEditor({fileId:c.fileId,line:c.startLine,column:1})},panel:n.contextualAskPanel,sessionToken:e.sessionToken}):void 0;async function St(c,u){let S=c.marker;if(S!==void 0)try{let $=await s.sourceContext({fileId:S.fileId,line:S.line,column:S.column,maxLines:e.budget.maxCodeLines});Ue(c,u)&&(c.code=$,c.apiStatus="connected",se(),ee(),n.announce(n.messages().announcements.sourceLoaded))}catch($){Ue(c,u)&&(c.code=void 0,c.apiStatus="failed",se(),ee(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!($ instanceof DOMException&&$.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Xe(c,u){let S=c.element;if(S===void 0)return;let $=o.window.setTimeout(()=>{if(D.delete(c.id),!Ue(c,u))return;let m=!1;try{c.elementContext=Ho({element:S,maxCharacters:e.budget.domCharacters})}catch{c.elementContext=void 0,m=!0}try{c.styles=Po({document:o.document,element:S,maxCharacters:e.budget.cssCharacters})}catch{c.styles=cs,m=!0}c.collectionStatus=m?"failed":"ready",se(),ee(),n.announce(m?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&c.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(c.styles.warnings.length)} warning(s).`)},0);D.set(c.id,$)}function fe(c,u){return u!==void 0?A.find(S=>S.marker?.fileId===u.fileId&&S.marker.line===u.line&&S.marker.column===u.column):A.find(S=>S.element===c)}function Ye(c){let u=V.resolve(c),S=Hn(u.source),$=fe(c,S);if($!==void 0){v=$.id,E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),te(),n.focusTargetInstruction($.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}let m=A.length===0;m&&(O=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,T="",U.beginSelection(),I=!0,Ce?.beginSelection()),q+=1;let F={id:`target-${String(q)}`,element:c,resolution:u,marker:S,page:zn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:S===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};A.push(F),m||Ce?.selectionChanged(),v=F.id,E=!1;let G=y;N({type:"SELECT"}),n.hideHighlight(),_?.observe(c),ee(!0),te(),B=!0,n.focusTargetInstruction(F.id),Xe(F,G),S!==void 0?St(F,G):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function Ze(){if(W=void 0,b.status!=="inspecting"||H===void 0)return;let c=Nn(o.document,o.window,H.x,H.y);if(N({type:"HOVER"}),c===void 0){n.hideHighlight();return}Ne(c)}function Se(c){b.status==="inspecting"&&(H={x:c.clientX,y:c.clientY},W??=o.window.requestAnimationFrame(Ze))}function we(c){if(b.status!=="inspecting"||Wo(c.target))return;c.preventDefault(),c.stopPropagation(),c.stopImmediatePropagation();let u=Nn(o.document,o.window,c.clientX,c.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}Ye(u)}function ze(c){if(c.key==="Escape"&&b.status!=="idle"){c.preventDefault(),b.status==="inspecting"&&E?lt():b.status==="inspecting"||b.status==="selected"?ot():(N({type:"BACK"}),n.focusTargetInstruction(v));return}Bo(c.target)||!Uo(c,e.shortcut,o.window.navigator.userAgent)||(c.preventDefault(),De())}function Rt(c){if(b.status!=="selected"&&b.status!=="inspecting")return;let u=A.findIndex(m=>m.id===c);if(u<0)return;let[S]=A.splice(u,1);if(S===void 0)return;let $=D.get(S.id);if($!==void 0&&(o.window.clearTimeout($),D.delete(S.id)),S.element!==void 0&&_?.unobserve(S.element),v===S.id&&(v=A.at(-1)?.id),A.length===0){E=!0,b.status==="selected"&&N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),M=void 0,K="idle",be(),x.clear(),Ce?.selectionChanged(),n.announce(n.messages().announcements.allTargetsRemoved);return}ee(),Ce?.selectionChanged(),te(),se(),n.announce(n.messages().announcements.targetRemoved)}function Ve(){if(b.status==="idle"||A.length===0)return;let c=A.filter(u=>u.element!==void 0&&!u.element.isConnected);if(c.length>0){for(let u of c)u.element!==void 0&&(_?.unobserve(u.element),u.element=void 0);ee(),se(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Ge()}function We(c){let u=c===void 0?le():A.find(F=>F.id===c);if(b.status!=="selected"||u?.marker===void 0)return;v!==u.id&&(v=u.id,ee());let S=u.marker,$=y,m=++R;N({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:S.fileId,line:S.line,column:S.column}).then(()=>{i&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("success")}).catch(()=>{i&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("error")})}function dt(c){if(b.status!=="selected"||!(c.target instanceof HTMLTextAreaElement))return;let u=c.target.dataset.targetInstructionId,S=A.find($=>$.id===u);S!==void 0&&(S.instruction=c.target.value,n.updateTargetInstruction(S.id,S.instruction),n.setPreviewEnabled(xe()),se())}function P(){We()}function rt(c){e.ai.enabled&&b.status==="selected"&&c.key==="Enter"&&(c.metaKey||c.ctrlKey)&&(c.preventDefault(),U.run())}function Z(){if(b.status!=="selected")return;let c=de();if(c===void 0){n.announce(n.messages().announcements.completeInstructions);return}T=l.compose(c),N({type:"PREVIEW"}),n.showPreview(T),n.focusPrompt()}function Y(){if(b.status!=="previewing"||T.length===0)return;if(a===void 0){N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let c=y;a.writeText(T).then(()=>{i&&c===y&&b.status==="previewing"&&(N({type:"COPY_SUCCESS"}),n.focusTargetInstruction(v),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{i&&c===y&&b.status==="previewing"&&(N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Me(){b.status==="previewing"&&(N({type:"BACK"}),n.focusTargetInstruction(v))}function pt(){if(!(!i||A.length===0)&&(ee(),b.status==="previewing")){let c=de();c!==void 0&&(T=l.compose(c),n.showPreview(T))}}function Fe(c){let u=c.target;if(!(u instanceof Element))return;let S=u.closest("button[data-remove-target-id]");if(S?.dataset.removeTargetId!==void 0){Rt(S.dataset.removeTargetId);return}let $=u.closest("button[data-open-target-id]");if($?.dataset.openTargetId!==void 0){We($.dataset.openTargetId);return}let F=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;b.status!=="selected"||F===void 0||!A.some(G=>G.id===F)||(v=F,ee(),te(),n.focusTargetInstruction(F))}function re(){ne()}function Oe(){te()}function He(){i||(i=!0,je?.mount(),Ce?.mount(),n.renderStatus(b.status),o.document.addEventListener("pointermove",Se,!0),o.document.addEventListener("click",we,!0),o.document.addEventListener("keydown",ze,!0),o.window.addEventListener("scroll",Ve,!0),o.window.addEventListener("resize",Ve),n.triggerButton.addEventListener("click",De),n.addTargetButton.addEventListener("click",Re),n.reselectButton.addEventListener("click",re),n.targetList.addEventListener("click",Fe),n.targetList.addEventListener("input",dt),n.targetList.addEventListener("keydown",rt),n.openEditorButton.addEventListener("click",P),n.dataFlowRefreshButton.addEventListener("click",Oe),n.previewButton.addEventListener("click",Z),n.copyButton.addEventListener("click",Y),n.backButton.addEventListener("click",Me),n.closeButton.addEventListener("click",ot),n.agentProviderSelect.addEventListener("change",U.providerOrModelChanged),n.agentModelSelect.addEventListener("change",U.providerOrModelChanged),n.agentModeSelect.addEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",U.consentChanged),n.agentTestButton.addEventListener("click",U.testCapability),n.agentRunButton.addEventListener("click",U.run),n.agentCancelButton.addEventListener("click",U.cancel),n.agentApplyButton.addEventListener("click",U.apply),n.agentRevertButton.addEventListener("click",U.revert),n.agentResetButton.addEventListener("click",U.reset),ve=n.subscribeLocale(pt),o.resizeObserver!==void 0&&(_=new o.resizeObserver(Ve)),o.mutationObserver!==void 0&&(pe=new o.mutationObserver(Ve),pe.observe(o.document.documentElement,{childList:!0,subtree:!0})),B&&A.length>0&&(N({type:"RESTORE"}),U.beginSelection(),Ce?.beginSelection(),I=!0,ee(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function at(){if(!i){ve?.(),ve=void 0,n.dispose(),s.cancelPending(),s.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose();return}i=!1,ve?.(),ve=void 0,o.document.removeEventListener("pointermove",Se,!0),o.document.removeEventListener("click",we,!0),o.document.removeEventListener("keydown",ze,!0),o.window.removeEventListener("scroll",Ve,!0),o.window.removeEventListener("resize",Ve),n.triggerButton.removeEventListener("click",De),n.addTargetButton.removeEventListener("click",Re),n.reselectButton.removeEventListener("click",re),n.targetList.removeEventListener("click",Fe),n.targetList.removeEventListener("input",dt),n.targetList.removeEventListener("keydown",rt),n.openEditorButton.removeEventListener("click",P),n.dataFlowRefreshButton.removeEventListener("click",Oe),n.previewButton.removeEventListener("click",Z),n.copyButton.removeEventListener("click",Y),n.backButton.removeEventListener("click",Me),n.closeButton.removeEventListener("click",ot),n.agentProviderSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",U.consentChanged),n.agentTestButton.removeEventListener("click",U.testCapability),n.agentRunButton.removeEventListener("click",U.run),n.agentCancelButton.removeEventListener("click",U.cancel),n.agentApplyButton.removeEventListener("click",U.apply),n.agentRevertButton.removeEventListener("click",U.revert),n.agentResetButton.removeEventListener("click",U.reset),W!==void 0&&(o.window.cancelAnimationFrame(W),W=void 0),Ke(),se(),_?.disconnect(),pe?.disconnect(),_=void 0,pe=void 0,A=[],v=void 0,T="",H=void 0,O=void 0,s.cancelPending(),s.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose(),n.dispose(),b=Mn}return Object.freeze({mount:He,dispose:at,getState:()=>b})}var _r="__spotpatchRuntime__";function Wn(e){let t=globalThis;t[_r]?.dispose();let o=Or(e);t[_r]=o,o.mount()}Wn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:ae});
|
|
862
|
+
`)}function Ge(){let c=A.flatMap(u=>{if(!u.element?.isConnected)return[];let S=dn(u.element,o.window);return S===void 0?[]:[{id:u.id,label:Vn(u.element),rect:S,active:u.id===v}]});c.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(c)}function ee(c=!1){if(A.length===0)return;n.renderTargets(A.map(m=>({id:m.id,label:m.resolution.react.componentName??(m.element===void 0?m.elementContext?.tagName??"Element":Vn(m.element)),source:ls(m,n.messages().context.sourceUnavailable),canOpenEditor:m.marker!==void 0,status:ds(m),active:m.id===v,instruction:m.instruction})),e.maxTargets),Ge();let u=le(),S=qe(),$=u?.marker!==void 0;c?n.showSelection(S,$,xe()):n.updateSelection(S,$,xe())}function de(){if(!xe())return;let c=A.map(u=>{if(u.elementContext===void 0||u.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let S=[...u.apiStatus==="failed"?["Source context could not be loaded."]:[],...u.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:u.instruction.trim(),page:u.page,source:u.resolution.source,react:u.resolution.react,element:u.elementContext,styles:u.styles,...u.code===void 0?{}:{code:u.code},warnings:S}});return po({id:d(),locale:n.locale(),createdAt:C(),page:zn(o.document,o.window),targets:c})}function Ne(c){n.showHighlight(zo(c,o.window),Vn(c))}function nt(){O?.isConnected===!0&&O.focus({preventScroll:!0}),O=void 0}function Ke(){for(let c of D.values())o.window.clearTimeout(c);D.clear()}function ct(){y+=1,i.cancelPending(),U.disposeSelection(),je?.cancelPending(),Ce?.cancelPending(),Ke(),_?.disconnect(),A=[],v=void 0,L+=1,M=void 0,K="idle",B=!1,I=!1,E=!1,T="",n.hideSelection(),n.hideSelectionHighlights(),x.clear(),nt()}function ot(){b.status==="inspecting"?N({type:"CANCEL"}):b.status==="selected"?N({type:"CLOSE"}):b.status==="previewing"&&(N({type:"BACK"}),N({type:"CLOSE"})),B=!1,se(),n.hideSelection(),n.hideSelectionHighlights(),nt(),n.hideHighlight()}function lt(){if(b.status!=="inspecting"||!E||A.length===0){ot();return}E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.focusTargetInstruction(v),n.announce(n.messages().announcements.addCancelled)}function De(){if(b.status==="inspecting"&&E){lt();return}if(b.status!=="idle"){ot();return}if(A.length>0){B=!0,N({type:"RESTORE"}),I||(U.beginSelection(),I=!0),ee(!0),te(),n.focusTargetInstruction(v),se();return}N({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function ne(c=n.messages().announcements.chooseAnother){b.status==="selected"&&(N({type:"RESELECT"}),ct(),n.hideHighlight(),n.announce(c))}function Re(){if(b.status==="selected"){if(A.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}E=!0,N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(A.length,e.maxTargets))}}function Je(){y+=1,Ke(),_?.disconnect();for(let c of A)c.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),ee(),x.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let U=Tr({ai:e.ai,api:i,getAnnotation:de,onApplied:Je,onReselectRequired(){ne(n.messages().announcements.reselectAfterChange)},view:n}),je=e.externalAgent.enabled&&n.externalHandoffPanel!==void 0?gn()?.createWorkflow(o.window.fetch.bind(o.window),n.externalHandoffPanel,de,e.sessionToken,o.window):void 0,Ce=e.contextualAsk.enabled&&n.contextualAskPanel!==void 0?fn()?.createWorkflow({...a===void 0?{}:{clipboard:a},createId:d,fetch:o.window.fetch.bind(o.window),getSelection:tt,onBusyChange(c){n.setAgentEditingEnabled(!c)},onConvert(){n.focusTargetInstruction(v)},async onOpenSource(c){await i.openEditor({fileId:c.fileId,line:c.startLine,column:1})},panel:n.contextualAskPanel,sessionToken:e.sessionToken}):void 0;async function St(c,u){let S=c.marker;if(S!==void 0)try{let $=await i.sourceContext({fileId:S.fileId,line:S.line,column:S.column,maxLines:e.budget.maxCodeLines});Ue(c,u)&&(c.code=$,c.apiStatus="connected",se(),ee(),n.announce(n.messages().announcements.sourceLoaded))}catch($){Ue(c,u)&&(c.code=void 0,c.apiStatus="failed",se(),ee(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!($ instanceof DOMException&&$.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function Xe(c,u){let S=c.element;if(S===void 0)return;let $=o.window.setTimeout(()=>{if(D.delete(c.id),!Ue(c,u))return;let m=!1;try{c.elementContext=Ho({element:S,maxCharacters:e.budget.domCharacters})}catch{c.elementContext=void 0,m=!0}try{c.styles=Po({document:o.document,element:S,maxCharacters:e.budget.cssCharacters})}catch{c.styles=cs,m=!0}c.collectionStatus=m?"failed":"ready",se(),ee(),n.announce(m?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&c.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(c.styles.warnings.length)} warning(s).`)},0);D.set(c.id,$)}function fe(c,u){return u!==void 0?A.find(S=>S.marker?.fileId===u.fileId&&S.marker.line===u.line&&S.marker.column===u.column):A.find(S=>S.element===c)}function Ye(c){let u=V.resolve(c),S=Hn(u.source),$=fe(c,S);if($!==void 0){v=$.id,E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),te(),n.focusTargetInstruction($.id),n.announce(n.messages().announcements.duplicate);return}if(A.length>=e.maxTargets){E=!1,N({type:"SELECT"}),n.hideHighlight(),ee(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}let m=A.length===0;m&&(O=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,T="",U.beginSelection(),I=!0,Ce?.beginSelection()),q+=1;let F={id:`target-${String(q)}`,element:c,resolution:u,marker:S,page:zn(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:S===void 0?"not-required":"loading",collectionStatus:"loading",dataFlowReport:void 0,dataFlowStatus:"idle"};A.push(F),m||Ce?.selectionChanged(),v=F.id,E=!1;let G=y;N({type:"SELECT"}),n.hideHighlight(),_?.observe(c),ee(!0),B=!0,n.focusTargetInstruction(F.id),Xe(F,G),S!==void 0?St(F,G):n.announce(u.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing),te()}function Ze(){if(W=void 0,b.status!=="inspecting"||H===void 0)return;let c=Nn(o.document,o.window,H.x,H.y);if(N({type:"HOVER"}),c===void 0){n.hideHighlight();return}Ne(c)}function Se(c){b.status==="inspecting"&&(H={x:c.clientX,y:c.clientY},W??=o.window.requestAnimationFrame(Ze))}function we(c){if(b.status!=="inspecting"||Wo(c.target))return;c.preventDefault(),c.stopPropagation(),c.stopImmediatePropagation();let u=Nn(o.document,o.window,c.clientX,c.clientY);if(u===void 0){n.announce(n.messages().announcements.noSelectable);return}Ye(u)}function ze(c){if(c.key==="Escape"&&b.status!=="idle"){c.preventDefault(),b.status==="inspecting"&&E?lt():b.status==="inspecting"||b.status==="selected"?ot():(N({type:"BACK"}),n.focusTargetInstruction(v));return}Bo(c.target)||!Uo(c,e.shortcut,o.window.navigator.userAgent)||(c.preventDefault(),De())}function Rt(c){if(b.status!=="selected"&&b.status!=="inspecting")return;let u=A.findIndex(m=>m.id===c);if(u<0)return;let[S]=A.splice(u,1);if(S===void 0)return;let $=D.get(S.id);if($!==void 0&&(o.window.clearTimeout($),D.delete(S.id)),S.element!==void 0&&_?.unobserve(S.element),v===S.id&&(v=A.at(-1)?.id),A.length===0){E=!0,b.status==="selected"&&N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),M=void 0,K="idle",be(),x.clear(),Ce?.selectionChanged(),n.announce(n.messages().announcements.allTargetsRemoved);return}ee(),Ce?.selectionChanged(),te(),se(),n.announce(n.messages().announcements.targetRemoved)}function Ve(){if(b.status==="idle"||A.length===0)return;let c=A.filter(u=>u.element!==void 0&&!u.element.isConnected);if(c.length>0){for(let u of c)u.element!==void 0&&(_?.unobserve(u.element),u.element=void 0);ee(),se(),n.announce(n.messages().announcements.detachedTargetPreserved);return}Ge()}function We(c){let u=c===void 0?le():A.find(F=>F.id===c);if(b.status!=="selected"||u?.marker===void 0)return;v!==u.id&&(v=u.id,ee());let S=u.marker,$=y,m=++R;N({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:S.fileId,line:S.line,column:S.column}).then(()=>{s&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("success")}).catch(()=>{s&&b.status==="selected"&&$===y&&m===R&&v===u.id&&A.includes(u)&&n.renderEditorStatus("error")})}function dt(c){if(b.status!=="selected"||!(c.target instanceof HTMLTextAreaElement))return;let u=c.target.dataset.targetInstructionId,S=A.find($=>$.id===u);S!==void 0&&(S.instruction=c.target.value,n.updateTargetInstruction(S.id,S.instruction),n.setPreviewEnabled(xe()),se())}function P(){We()}function rt(c){e.ai.enabled&&b.status==="selected"&&c.key==="Enter"&&(c.metaKey||c.ctrlKey)&&(c.preventDefault(),U.run())}function Z(){if(b.status!=="selected")return;let c=de();if(c===void 0){n.announce(n.messages().announcements.completeInstructions);return}T=l.compose(c),N({type:"PREVIEW"}),n.showPreview(T),n.focusPrompt()}function Y(){if(b.status!=="previewing"||T.length===0)return;if(a===void 0){N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let c=y;a.writeText(T).then(()=>{s&&c===y&&b.status==="previewing"&&(N({type:"COPY_SUCCESS"}),n.focusTargetInstruction(v),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{s&&c===y&&b.status==="previewing"&&(N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function Me(){b.status==="previewing"&&(N({type:"BACK"}),n.focusTargetInstruction(v))}function pt(){if(!(!s||A.length===0)&&(ee(),b.status==="previewing")){let c=de();c!==void 0&&(T=l.compose(c),n.showPreview(T))}}function Fe(c){let u=c.target;if(!(u instanceof Element))return;let S=u.closest("button[data-remove-target-id]");if(S?.dataset.removeTargetId!==void 0){Rt(S.dataset.removeTargetId);return}let $=u.closest("button[data-open-target-id]");if($?.dataset.openTargetId!==void 0){We($.dataset.openTargetId);return}let F=u.closest("button[data-activate-target-id]")?.dataset.activateTargetId;b.status!=="selected"||F===void 0||!A.some(G=>G.id===F)||(v=F,ee(),te(),n.focusTargetInstruction(F))}function re(){ne()}function Oe(){te()}function He(){s||(s=!0,je?.mount(),Ce?.mount(),n.renderStatus(b.status),o.document.addEventListener("pointermove",Se,!0),o.document.addEventListener("click",we,!0),o.document.addEventListener("keydown",ze,!0),o.window.addEventListener("scroll",Ve,!0),o.window.addEventListener("resize",Ve),n.triggerButton.addEventListener("click",De),n.addTargetButton.addEventListener("click",Re),n.reselectButton.addEventListener("click",re),n.targetList.addEventListener("click",Fe),n.targetList.addEventListener("input",dt),n.targetList.addEventListener("keydown",rt),n.openEditorButton.addEventListener("click",P),n.dataFlowRefreshButton.addEventListener("click",Oe),n.previewButton.addEventListener("click",Z),n.copyButton.addEventListener("click",Y),n.backButton.addEventListener("click",Me),n.closeButton.addEventListener("click",ot),n.agentProviderSelect.addEventListener("change",U.providerOrModelChanged),n.agentModelSelect.addEventListener("change",U.providerOrModelChanged),n.agentModeSelect.addEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",U.consentChanged),n.agentTestButton.addEventListener("click",U.testCapability),n.agentRunButton.addEventListener("click",U.run),n.agentCancelButton.addEventListener("click",U.cancel),n.agentApplyButton.addEventListener("click",U.apply),n.agentRevertButton.addEventListener("click",U.revert),n.agentResetButton.addEventListener("click",U.reset),ve=n.subscribeLocale(pt),o.resizeObserver!==void 0&&(_=new o.resizeObserver(Ve)),o.mutationObserver!==void 0&&(pe=new o.mutationObserver(Ve),pe.observe(o.document.documentElement,{childList:!0,subtree:!0})),B&&A.length>0&&(N({type:"RESTORE"}),U.beginSelection(),Ce?.beginSelection(),I=!0,ee(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function at(){if(!s){ve?.(),ve=void 0,n.dispose(),i.cancelPending(),i.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose();return}s=!1,ve?.(),ve=void 0,o.document.removeEventListener("pointermove",Se,!0),o.document.removeEventListener("click",we,!0),o.document.removeEventListener("keydown",ze,!0),o.window.removeEventListener("scroll",Ve,!0),o.window.removeEventListener("resize",Ve),n.triggerButton.removeEventListener("click",De),n.addTargetButton.removeEventListener("click",Re),n.reselectButton.removeEventListener("click",re),n.targetList.removeEventListener("click",Fe),n.targetList.removeEventListener("input",dt),n.targetList.removeEventListener("keydown",rt),n.openEditorButton.removeEventListener("click",P),n.dataFlowRefreshButton.removeEventListener("click",Oe),n.previewButton.removeEventListener("click",Z),n.copyButton.removeEventListener("click",Y),n.backButton.removeEventListener("click",Me),n.closeButton.removeEventListener("click",ot),n.agentProviderSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",U.providerOrModelChanged),n.agentModeSelect.removeEventListener("change",U.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",U.consentChanged),n.agentTestButton.removeEventListener("click",U.testCapability),n.agentRunButton.removeEventListener("click",U.run),n.agentCancelButton.removeEventListener("click",U.cancel),n.agentApplyButton.removeEventListener("click",U.apply),n.agentRevertButton.removeEventListener("click",U.revert),n.agentResetButton.removeEventListener("click",U.reset),W!==void 0&&(o.window.cancelAnimationFrame(W),W=void 0),Ke(),se(),_?.disconnect(),pe?.disconnect(),_=void 0,pe=void 0,A=[],v=void 0,T="",H=void 0,O=void 0,i.cancelPending(),i.dispose(),U.disposeSelection(),je?.dispose(),Ce?.dispose(),V.dispose(),n.dispose(),b=Mn}return Object.freeze({mount:He,dispose:at,getState:()=>b})}var _r="__spotpatchRuntime__";function Wn(e){let t=globalThis;t[_r]?.dispose();let o=Or(e);return t[_r]=o,o.mount(),o}Wn({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:ae});
|