@scene-glass/devtools 0.0.0-stage → 0.1.32

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.
@@ -0,0 +1,1637 @@
1
+ var SceneGlassLoader=(function(Ut){"use strict";const Er=Number.MAX_SAFE_INTEGER,Sr=2147483647,kr=70,Cr=15;class N extends Error{code;constructor(e,i){super(i),this.name="SceneGlassContractError",this.code=e,Object.setPrototypeOf(this,new.target.prototype)}}const Ir={httpBodyBytes:1*1024*1024,canonicalIdentityBytes:2048,routeBytes:2048,memoBytes:16*1024,surroundingTextCodePoints:500,surroundingTextBytes:4*1024,locatorFieldBytes:512,locatorSerializedBytes:16*1024,annotationsPerPage:1e3,pageFileBytes:8*1024*1024,replayLedgerBytes:2*1024*1024,replayResultBytes:64*1024,pagesPerProject:2e3,exportScanBytes:64*1024*1024,exportRenderBytes:16*1024*1024,concurrentRequestsPerProject:16,concurrentRequestsGlobal:64,normalSessionsPerProject:32,normalSessionsGlobal:128,sessionMaxAgeMs:1800*1e3,sessionIdleMs:300*1e3,diagnosticActiveRunsPerProject:4,diagnosticActiveRunsGlobal:16,diagnosticRunsPerProjectPerMinute:5,requestTimeoutMs:30*1e3,exportTimeoutMs:60*1e3,workRequestAnnotations:1e3,workRequestEvents:32,historyTaskCount:32,historyBudgetBytes:256*1024*1024,historyScanFiles:2e4,historyScanBytes:512*1024*1024,historyFileBytes:16*1024*1024,historyDiffRenderBytes:8*1024*1024,historyHashConcurrency:16},D=Object.freeze(Ir),Ar=["httpBodyBytes","concurrentRequestsGlobal","normalSessionsGlobal","diagnosticActiveRunsGlobal","historyHashConcurrency"],Or=new Set(Ar),_r=Object.freeze(Object.keys(D));Object.freeze(_r.filter(t=>!Or.has(t)));function Tr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function he(t,e="revision"){return qi(t,0,Er,e)}function Rr(t,e="domOrder"){return qi(t,0,Sr,e)}function qi(t,e,i,n="value"){if(typeof t!="number"||!Number.isSafeInteger(t)||t<e||t>i)throw new N("SCG_SCALAR_INVALID",`${n} must be a safe integer from ${e} through ${i}`);return t}function zi(t,e="value"){if(typeof t!="string")throw new N("SCG_SCALAR_INVALID",`${e} must be a string`);return ji(t,e),t}function ye(t,e,i="value"){const n=zi(t,i);if(_e(n)>e)throw new N("SCG_SCALAR_INVALID",`${i} exceeds its UTF-8 byte limit`);return n}function te(t,e="id"){if(typeof t!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t))throw new N("SCG_ID_INVALID",`${e} must be a lowercase UUID v4`);return t}function _e(t){let e=0;for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);if(n<=127)e+=1;else if(n<=2047)e+=2;else if(n>=55296&&n<=56319){const s=t.charCodeAt(i+1);if(i+1>=t.length||s<56320||s>57343)throw new N("SCG_SCALAR_INVALID","value contains an unpaired surrogate");e+=4,i+=1}else{if(n>=56320&&n<=57343)throw new N("SCG_SCALAR_INVALID","value contains an unpaired surrogate");e+=3}}return e}function Gi(t){ji(t,"value");let e=0;for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);n>=55296&&n<=56319&&(i+=1),e+=1}return e}function ji(t,e){for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);if(n>=55296&&n<=56319){const s=t.charCodeAt(i+1);if(i+1>=t.length||s<56320||s>57343)throw new N("SCG_SCALAR_INVALID",`${e} contains an unpaired surrogate`);i+=1}else if(n>=56320&&n<=57343)throw new N("SCG_SCALAR_INVALID",`${e} contains an unpaired surrogate`)}}const xr=/^p_[0-9a-f]{64}$/,Nr=/^sha256:[0-9a-f]{64}$/,Pr=/^[a-z][a-z0-9:-]*$/,Lr=/^[a-z][a-z0-9:_-]*$/,Mr=4,Wi=new Set(["policyVersion","canonicalIdentity","route","pageId"]),Dr=new Set(["dataScgId","fingerprint"]),Ui=new Set(["tag","stableAttributes","ancestorSignatures","textDigest"]),qr=new Set(["status","reason"]),zr=new Set(["id","locator","memo","surroundingText","domOrder","resolution","context","createdAt","updatedAt"]),Gr=new Set(["viewport","rect","tag","classes","cssPath","selectedText","sourceFile","componentTrail"]),jr=new Set(["viewport","rect","tag","classes","cssPath","selectedText"]),Wr=64,Ur=64,Vr=4096,Br=16*1024,Fr=new Set(["id","locator","memo","surroundingText","domOrder","resolution","createdAt","updatedAt"]);function Vt(t){const e=xe(t,"annotation context");Ne(e,Gr,"annotation context"),ct(e,jr,"annotation context");const i={viewport:$r(e.viewport),rect:Kr(e.rect),tag:Fi(e.tag,"annotation context tag"),classes:Vi(e.classes,Wr,"annotation context class"),cssPath:Bi(e.cssPath,"annotation context cssPath",Vr),selectedText:Hr(e.selectedText)};ge(e,"sourceFile")&&(i.sourceFile=Bi(e.sourceFile,"annotation context sourceFile",D.locatorFieldBytes)),ge(e,"componentTrail")&&(i.componentTrail=Vi(e.componentTrail,Ur,"annotation context component"));const n=Object.freeze(i);if(_e(JSON.stringify(n))>Br)throw q("annotation context exceeds its serialized byte limit");return n}function Te(t,e,i){if(typeof t!="number"||!Number.isSafeInteger(t)||!i&&t<0)throw new N("SCG_SCALAR_INVALID",`${e} must be a ${i?"safe":"non-negative safe"} integer`);return t}function $r(t){if(!Array.isArray(t)||t.length!==2)throw q("annotation context viewport must be a two-number tuple");return Object.freeze([Te(t[0],"annotation context viewport width",!1),Te(t[1],"annotation context viewport height",!1)])}function Kr(t){if(!Array.isArray(t)||t.length!==4)throw q("annotation context rect must be a four-number tuple");return Object.freeze([Te(t[0],"annotation context rect x",!0),Te(t[1],"annotation context rect y",!0),Te(t[2],"annotation context rect width",!1),Te(t[3],"annotation context rect height",!1)])}function Vi(t,e,i){if(!Array.isArray(t))throw q(`${i} list must be an array`);if(t.length>e)throw q(`${i} list exceeds its limit`);return Object.freeze(t.map(n=>Ke(n,i)))}function Bi(t,e,i){const n=ye(t,i,e);if($t(n))throw new N("SCG_SCALAR_INVALID",`${e} must be free of control characters`);return n}function Hr(t){const e=ye(t,D.surroundingTextBytes,"annotation context selectedText");if(Gi(e)>D.surroundingTextCodePoints)throw new N("SCG_SCALAR_INVALID","annotation context selectedText exceeds its code point limit");return e}function Bt(t){const e=xe(t,"element annotation");Ne(e,zr,"element annotation"),ct(e,Fr,"element annotation");const i=Ki(e.createdAt,"createdAt"),n=Ki(e.updatedAt,"updatedAt");if(Date.parse(n)<Date.parse(i))throw q("updatedAt must not precede createdAt");return Object.freeze({id:te(e.id,"annotation id"),locator:Yr(e.locator),memo:Jr(e.memo),surroundingText:eo(e.surroundingText),domOrder:Rr(e.domOrder),resolution:Qr(e.resolution),...ge(e,"context")?{context:Vt(e.context)}:{},createdAt:i,updatedAt:n})}function $e(t){const e=xe(t,"page identity");if(Ne(e,Wi,"page identity"),ct(e,Wi,"page identity"),e.policyVersion!==1)throw q("page identity policyVersion must be 1");const i=$i(e.canonicalIdentity,"canonicalIdentity",D.canonicalIdentityBytes);if(i.normalize("NFC")!==i)throw q("canonicalIdentity must be NFC normalized");return Object.freeze({policyVersion:1,canonicalIdentity:i,route:$i(e.route,"route",D.routeBytes),pageId:Ft(e.pageId)})}function Ft(t){if(typeof t!="string"||!xr.test(t))throw new N("SCG_ID_INVALID","pageId must be p_ followed by 64 lowercase hexadecimal characters");return t}function Re(t){if(typeof t!="string"||!Nr.test(t))throw new N("SCG_ID_INVALID","digest must be a lowercase sha256 digest");return t}function Yr(t){const e=xe(t,"locator");if(Ne(e,Dr,"locator"),!ge(e,"dataScgId")&&!ge(e,"fingerprint"))throw q("locator requires dataScgId or fingerprint");const i=ge(e,"dataScgId")?Ke(e.dataScgId,"dataScgId"):void 0,n=ge(e,"fingerprint")?Xr(e.fingerprint):void 0,s={...i===void 0?{}:{dataScgId:i},...n===void 0?{}:{fingerprint:n}};return no(s),Object.freeze(s)}function Xr(t){const e=xe(t,"locator fingerprint");if(Ne(e,Ui,"locator fingerprint"),ct(e,Ui,"locator fingerprint"),!Array.isArray(e.stableAttributes)||!Array.isArray(e.ancestorSignatures))throw q("locator fingerprint stableAttributes and ancestorSignatures must be arrays");if(e.ancestorSignatures.length>Mr)throw q("locator fingerprint may contain at most four ancestor signatures");const i=e.stableAttributes.map(s=>Zr(s));so(i,"locator fingerprint stableAttributes");const n=e.ancestorSignatures.map(s=>Ke(s,"locator ancestor signature"));return Object.freeze({tag:Fi(e.tag,"locator fingerprint tag"),stableAttributes:Object.freeze(i),ancestorSignatures:Object.freeze(n),textDigest:Re(e.textDigest)})}function Qr(t){const e=xe(t,"resolution");if(Ne(e,qr,"resolution"),e.status!=="resolved"&&e.status!=="not-found"&&e.status!=="ambiguous")throw q("resolution status is invalid");if(e.status==="resolved"){if(e.reason!==null)throw q("resolved resolution reason must be null");return Object.freeze({status:"resolved",reason:null})}if(e.status==="not-found"){if(e.reason!=="not-found")throw q("not-found resolution reason is invalid");return Object.freeze({status:"not-found",reason:"not-found"})}if(e.reason!=="ambiguous")throw q("ambiguous resolution reason is invalid");return Object.freeze({status:"ambiguous",reason:"ambiguous"})}function Zr(t){if(!Array.isArray(t)||t.length!==2)throw q("locator stable attribute must be a two-item name and value tuple");const[e,i]=t,n=Ke(e,"locator stable attribute name");if(!Lr.test(n))throw q("locator stable attribute name must be lowercase ASCII");const s=to(i,"locator stable attribute value");return Object.freeze([n,s])}function Fi(t,e){const i=Ke(t,e);if(!Pr.test(i))throw q(`${e} must be lowercase ASCII`);return i}function Jr(t){const e=ye(t,D.memoBytes,"memo");if(e.trim().length===0)throw new N("SCG_MEMO_BLANK","memo must not be blank");return e}function eo(t){const e=ye(t,D.surroundingTextBytes,"surroundingText");if(Gi(e)>D.surroundingTextCodePoints)throw new N("SCG_SCALAR_INVALID","surroundingText exceeds its code point limit");return e}function $i(t,e,i){const n=ye(t,i,e);if(n.length===0||$t(n))throw new N("SCG_SCALAR_INVALID",`${e} contains an empty or control value`);return n}function Ke(t,e){const i=ye(t,D.locatorFieldBytes,e);if(i.trim().length===0||$t(i))throw new N("SCG_SCALAR_INVALID",`${e} must be non-blank and free of control characters`);return i}function to(t,e){const i=ye(t,D.locatorFieldBytes,e);if(io(i))throw new N("SCG_SCALAR_INVALID",`${e} must be free of null and delete characters`);return i}function $t(t){for(let e=0;e<t.length;e+=1){const i=t.charCodeAt(e);if(i<=31||i===127)return!0}return!1}function io(t){for(let e=0;e<t.length;e+=1){const i=t.charCodeAt(e);if(i===0||i===127)return!0}return!1}function Ki(t,e){const i=zi(t,e);if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(i)||Number.isNaN(Date.parse(i)))throw new N("SCG_SCALAR_INVALID",`${e} must be an exact UTC ISO timestamp`);return i}function no(t){const e=JSON.stringify(t);if(_e(e)>D.locatorSerializedBytes)throw new N("SCG_SCALAR_INVALID","locator exceeds its serialized byte limit")}function so(t,e){let i;for(const[n,s]of t){const r=`${n}\0${s}`;if(i!==void 0&&i>=r)throw q(`${e} must be strictly sorted and unique`);i=r}}function xe(t,e){if(!Tr(t))throw q(`${e} must be an object`);return t}function Ne(t,e,i){for(const n of Object.keys(t))if(!e.has(n))throw q(`${i} contains an unknown field`)}function ct(t,e,i){for(const n of e)if(!ge(t,n))throw q(`${i} is missing ${n}`)}function ge(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function q(t){return new N("SCG_ANNOTATION_INVALID",t)}function Hi(t){if(!Array.isArray(t)||t.length>D.annotationsPerPage)throw new N("SCG_ANNOTATION_INVALID","annotationIds is invalid");const e=Array.from(t,i=>te(i,"annotationIds"));if(new Set(e).size!==e.length)throw new N("SCG_ANNOTATION_INVALID","annotationIds contains duplicates");return Object.freeze(e)}function ro(t){return typeof t=="string"&&/^[a-z0-9][a-z0-9_-]{0,127}$/.test(t)}function lt(t){return oo(t)}function oo(t,e){if(!ro(t))throw ao("projectId must contain 1 through 128 lowercase ASCII letters, digits, underscores, or hyphens");return t}function ao(t,e){return co("SCG_CONFIG_INVALID",t)}function co(t,e,i){return new N(t,e)}const Pe="scene-glass-premium-measurement-v1",dt=1,Yi=256*1024,Xi=64*1024,Kt="premium/measurement-v1.js",Ht="premium/measurement-v1.css",Qi="application/javascript; charset=utf-8",Zi="text/css; charset=utf-8";function lo(t){const e=wo(t),i=e.activate;if(e.namespace!==Pe||e.abiVersion!==dt||!uo(i))throw J("measurement capability namespace or ABI is invalid");return Object.freeze({namespace:Pe,abiVersion:dt,activate:i})}function uo(t){return typeof t=="function"}function Ji(t){return ho(t)}function ho(t){const e=tn(t,["moduleId","namespace","abiVersion","module","stylesheet"],"premium measurement artifact");if(e.moduleId!==Pe||e.namespace!==Pe||e.abiVersion!==dt)throw J("premium measurement artifact identity or ABI is invalid");return Object.freeze({moduleId:Pe,namespace:Pe,abiVersion:dt,module:go(e.module),stylesheet:fo(e.stylesheet)})}function go(t){const e=en(t,"premium measurement module");if(e.path!==Kt||e.maxBytes!==Yi||e.mediaType!==Qi)throw J("premium measurement module authority is invalid");return Object.freeze({path:Kt,maxBytes:Yi,mediaType:Qi,sha256:e.sha256})}function fo(t){const e=en(t,"premium measurement stylesheet");if(e.path!==Ht||e.maxBytes!==Xi||e.mediaType!==Zi)throw J("premium measurement stylesheet authority is invalid");return Object.freeze({path:Ht,maxBytes:Xi,mediaType:Zi,sha256:e.sha256})}function en(t,e){const i=tn(t,["path","maxBytes","mediaType","sha256"],e),n=po(i.path,e);if(typeof i.maxBytes!="number"||!Number.isSafeInteger(i.maxBytes)||i.maxBytes<1||typeof i.mediaType!="string")throw J(`${e} media type or size bound is invalid`);return Object.freeze({path:n,maxBytes:i.maxBytes,mediaType:i.mediaType,sha256:mo(i.sha256,e)})}function po(t,e){if(typeof t!="string"||t.length===0||t.length>256||t.startsWith("/")||t.endsWith("/")||t.includes("\\")||t.includes("\0")||t.includes("?")||t.includes("#"))throw J(`${e} path is not package-relative`);if(t.split("/").some(n=>n.length===0||n==="."||n===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(n)))throw J(`${e} path is not package-relative`);return t}function mo(t,e){if(typeof t!="string"||!/^sha256:[0-9a-f]{64}$/u.test(t))throw J(`${e} SHA-256 is invalid`);return t}function wo(t){if(!nn(t))throw J("measurement capability must be an object");const e=["namespace","abiVersion","activate"],i=Reflect.ownKeys(t),n=i.filter(r=>typeof r=="string"),s=i.filter(r=>typeof r=="symbol");if(n.length!==e.length||n.some(r=>!e.includes(r))||s.some(r=>r!==Symbol.toStringTag))throw J("measurement capability contains missing or unknown fields");return t}function tn(t,e,i){if(!nn(t))throw J(`${i} must be an object`);const n=Reflect.ownKeys(t);if(n.length!==e.length||n.some(s=>typeof s!="string"||!e.includes(s)))throw J(`${i} contains missing or unknown fields`);return t}function nn(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function J(t){return new TypeError(t)}const vo=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/,bo=D.routeBytes;function ie(t){const e=n=>new N(t,n),i=(n,s)=>{try{return s()}catch(r){throw r instanceof N?e(n):r}};return Object.freeze({fail:e,mapped:i,record:(n,s)=>{if(typeof n!="object"||n===null||Array.isArray(n))throw e(`${s} must be an object`);const r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw e(`${s} must be a plain object`);return n},field:(n,s)=>Reflect.get(n,s),exactKeys:(n,s,r)=>{for(const o of Reflect.ownKeys(n))if(typeof o!="string"||!s.has(o))throw e(`${r} contains an unknown field`);for(const o of s)if(!Object.prototype.hasOwnProperty.call(n,o))throw e(`${r} is missing ${o}`)},denseArray:(n,s)=>{if(!Array.isArray(n))throw e(`${s} must be an array`);for(let r=0;r<n.length;r+=1)if(!Object.prototype.hasOwnProperty.call(n,r))throw e(`${s} must not be sparse`);return Object.freeze(Array.from(n,r=>r))},unique:(n,s)=>{if(new Set(n).size!==n.length)throw e(`${s} must not contain duplicates`)},member:(n,s,r)=>{for(const o of s)if(n===o)return o;throw e(`${r} is invalid`)},uuid:(n,s)=>i(`${s} must be a lowercase UUID v4`,()=>te(n,s)),digest:(n,s)=>i(`${s} must be a lowercase sha256 digest`,()=>Re(n)),integer:(n,s)=>i(`${s} must be a non-negative safe integer`,()=>he(n,s)),flag:(n,s)=>{if(typeof n!="boolean")throw e(`${s} must be a boolean`);return n},text:(n,s)=>{if(typeof n!="string")throw e(`${s} must be a string`);return n},timestamp:(n,s)=>{if(typeof n!="string")throw e(`${s} must be an exact UTC ISO timestamp`);const r=vo.exec(n),o=r?.[1],a=r?.[2]??"";if(o===void 0)throw e(`${s} must be an exact UTC ISO timestamp`);const c=new Date(n),l=`${o}.${a.padEnd(3,"0")}Z`;if(Number.isNaN(c.valueOf())||c.toISOString()!==l)throw e(`${s} must be an exact UTC ISO timestamp`);return n},schemaVersion:(n,s)=>{if(n!==1)throw e(`${s} schemaVersion must be 1`)}})}function Yt(t){return new N("SCG_WORK_LIMIT_EXCEEDED",t)}function yo(t,e){if(typeof t!="string"||t.length===0)throw e.fail("work path must be a non-empty string");if(e.mapped("work path is invalid",()=>_e(t))>bo)throw e.fail("work path exceeds its byte limit");if(t.startsWith("/")||t.includes("\\")||t.includes("\0"))throw e.fail("work path must be project-relative and free of null bytes");if(t.split("/").some(n=>n===""||n==="."||n===".."))throw e.fail("work path must not contain empty or relative segments");return t}const sn=Object.freeze({model:null,reasoningEffort:null}),Eo=new Set(["model","reasoningEffort"]),So=new RegExp("\\p{Cc}","u"),ne=ie("SCG_WORK_EXECUTION_SETTINGS_INVALID");function ko(t){const e=ne.record(t,"execution settings");ne.exactKeys(e,Eo,"execution settings");const i=on(ne.field(e,"model"),512),n=on(ne.field(e,"reasoningEffort"),128);if(i===null&&n!==null)throw ne.fail("SCG_WORK_EXECUTION_SETTINGS_INVALID");return Object.freeze({model:i,reasoningEffort:n})}function rn(t,e){return Object.hasOwn(t,"executionSettings")?new Set([...e,"executionSettings"]):e}function ut(t){if(!Object.hasOwn(t,"executionSettings"))return Object.freeze({});const e=ko(ne.field(t,"executionSettings"));if(ne.field(t,"provider")==="none"&&!ht(e,void 0))throw ne.fail("SCG_WORK_EXECUTION_SETTINGS_INVALID");return Object.freeze({executionSettings:e})}function Co(t){return Object.freeze(t===void 0?{}:{executionSettings:Object.freeze({model:t.model,reasoningEffort:t.reasoningEffort})})}function ht(t,e){return(t?.model??null)===(e?.model??null)&&(t?.reasoningEffort??null)===(e?.reasoningEffort??null)}function on(t,e){if(t===null)return null;if(typeof t!="string"||!/\S/u.test(t)||[...t].length>e||So.test(t))throw ne.fail("SCG_WORK_EXECUTION_SETTINGS_INVALID");return t}const an=["SCG_OMO_RUNTIME_AUTHORITY_ABSENT","SCG_OMO_RUNTIME_UNSUPPORTED","SCG_OMO_RUNTIME_MISSING","SCG_OMO_RUNTIME_INTEGRITY"],cn=["SCG_RUNTIME_AUTHORITY_ABSENT","SCG_RUNTIME_UNSUPPORTED","SCG_RUNTIME_MISSING","SCG_RUNTIME_INTEGRITY","SCG_RUNTIME_VERSION_MISMATCH","SCG_RUNTIME_CONVERSATION_UNQUALIFIED","SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED"],Io=[...an,...cn],Xt="scene-glass omo install",ln=Object.freeze({"claude-code":"scene-glass runtime install --provider claude","codex-cli":"scene-glass runtime install --provider codex"}),Ao=Object.freeze({SCG_OMO_RUNTIME_AUTHORITY_ABSENT:"unavailable",SCG_OMO_RUNTIME_UNSUPPORTED:"incompatible",SCG_OMO_RUNTIME_MISSING:"missing",SCG_OMO_RUNTIME_INTEGRITY:"unavailable",SCG_RUNTIME_AUTHORITY_ABSENT:"unavailable",SCG_RUNTIME_UNSUPPORTED:"incompatible",SCG_RUNTIME_MISSING:"missing",SCG_RUNTIME_INTEGRITY:"unavailable",SCG_RUNTIME_VERSION_MISMATCH:"incompatible",SCG_RUNTIME_CONVERSATION_UNQUALIFIED:"unavailable",SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED:"unavailable"}),dn=new Set(["code","action"]),Y=ie("SCG_WORK_PROVIDER_INVALID"),Qt=an,un=cn;function Oo(t,e,i,n){return hn(t,n)&&Ao[n.code]===e&&(n.code==="SCG_OMO_RUNTIME_UNSUPPORTED"||n.code==="SCG_RUNTIME_UNSUPPORTED"?i==="select-provider":e!=="incompatible"||i==="update-provider")}function hn(t,e){return"provider"in e?e.provider===t:t==="omo-native"}function _o(t){return Object.freeze({code:t,action:t==="SCG_OMO_RUNTIME_MISSING"?Xt:null})}function To(t,e,i){if(i!==null&&!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(i))throw Y.fail("work provider runtime version is invalid");return Object.freeze({code:t,provider:e,version:i,action:t==="SCG_RUNTIME_MISSING"?ln[e]:t==="SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED"?"start-new-session":null})}function gn(t){const e=Y.record(t,"work provider runtime diagnostic"),i=Y.member(Y.field(e,"code"),Io,"work provider runtime code"),n=un.find(o=>o===i);Y.exactKeys(e,n===void 0?dn:new Set([...dn,"provider","version"]),"work provider runtime diagnostic");const s=Qt.find(o=>o===i);if(n===void 0&&s===void 0)throw Y.fail("invalid runtime code");const r=n!==void 0?To(n,Y.member(Y.field(e,"provider"),["claude-code","codex-cli"],"work provider runtime provider"),Y.field(e,"version")===null?null:Y.text(Y.field(e,"version"),"work provider runtime version")):_o(Y.member(s,Qt,"work provider runtime code"));if(Y.field(e,"action")!==r.action)throw Y.fail("work provider runtime action is inconsistent");return r}Object.freeze({oneOf:[{type:"object",additionalProperties:!1,required:["code","action"],properties:{code:{enum:Qt},action:{anyOf:[{const:Xt},{type:"null"}]}}},{type:"object",additionalProperties:!1,required:["code","action","provider","version"],properties:{code:{enum:un},action:{anyOf:[{enum:[...Object.values(ln),"start-new-session"]},{type:"null"}]},provider:{enum:["claude-code","codex-cli"]},version:{anyOf:[{type:"string"},{type:"null"}]}}}]});const $=ie("SCG_WORK_PROVIDER_INVALID"),fn=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,gt=["provider","releaseVersion","tuple","version","runtimeId","binarySha256"];function ft(t){if(typeof t!="string"||!fn.test(t))throw $.fail("runtime identity version must be exact");return t}function pn(t){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t)||/^0+$/u.test(t))throw $.fail("runtime identity digest must be nonzero lowercase hex");return t}function mn(t){const e=$.record(t,"runtime identity");for(const s of Object.values(Object.getOwnPropertyDescriptors(e)))if(s.enumerable!==!0||!Object.hasOwn(s,"value"))throw $.fail("runtime identity must contain only data fields");const i=$.member($.field(e,"provider"),["omo-native","claude-code","codex-cli"],"runtime identity provider");$.exactKeys(e,new Set(i==="omo-native"?[...gt,"nodeVersion","senpiVersion"]:gt),"runtime identity");const n={releaseVersion:ft($.field(e,"releaseVersion")),tuple:$.member($.field(e,"tuple"),["darwin-arm64","darwin-x64","linux-x64-gnu"],"runtime identity tuple"),version:ft($.field(e,"version")),runtimeId:pn($.field(e,"runtimeId")),binarySha256:pn($.field(e,"binarySha256"))};return Object.freeze(i==="omo-native"?{...n,provider:i,nodeVersion:ft($.field(e,"nodeVersion")),senpiVersion:ft($.field(e,"senpiVersion"))}:{...n,provider:i})}const Le={type:"string",pattern:fn.source},pt={type:"string",pattern:"^(?!0{64}$)[a-f0-9]{64}$"};Object.freeze({oneOf:[{type:"object",additionalProperties:!1,required:[...gt,"nodeVersion","senpiVersion"],properties:{provider:{const:"omo-native"},releaseVersion:Le,tuple:{enum:["darwin-arm64","darwin-x64","linux-x64-gnu"]},version:Le,runtimeId:pt,binarySha256:pt,nodeVersion:Le,senpiVersion:Le}},{type:"object",additionalProperties:!1,required:gt,properties:{provider:{enum:["claude-code","codex-cli"]},releaseVersion:Le,tuple:{enum:["darwin-arm64","darwin-x64","linux-x64-gnu"]},version:Le,runtimeId:pt,binarySha256:pt}}]});const Zt=["none","omo-native","codex-cli","claude-code"],Ro=["none","ready","missing","auth-required","incompatible","unavailable"],xo=["none","select-provider","install-provider","authenticate-provider","update-provider","retry-provider"],No=new Set(["provider","status","remediation"]),X=ie("SCG_WORK_PROVIDER_INVALID");function mt(t){return X.member(t,Zt,"work provider")}function Me(t){const e=mt(t);if(e==="none")throw X.fail("work provider must not be none");return e}function Po(t){const e=X.record(t,"work provider readiness"),i=Object.hasOwn(e,"runtime"),n=Object.hasOwn(e,"identity");X.exactKeys(e,new Set([...No,...i?["runtime"]:[],...n?["identity"]:[]]),"work provider readiness");const s=mt(X.field(e,"provider")),r=X.member(X.field(e,"status"),Ro,"work provider readiness status"),o=X.member(X.field(e,"remediation"),xo,"work provider remediation");if(s==="none"!=(r==="none")||r==="ready"&&o!=="none"||r==="none"&&o!=="select-provider"||r==="missing"&&o!=="install-provider"||r==="auth-required"&&o!=="authenticate-provider"||r==="incompatible"&&o!=="update-provider"&&!i||r==="unavailable"&&o!=="retry-provider")throw X.fail("work provider readiness fields are inconsistent");const a=n?mn(X.field(e,"identity")):void 0;if(a!==void 0&&(a.provider!==s||i||r!=="ready"&&r!=="auth-required"))throw X.fail("work provider runtime identity is inconsistent");if(!i)return Object.freeze({provider:s,status:r,remediation:o,...a===void 0?{}:{identity:a}});const c=gn(X.field(e,"runtime"));if(!Oo(s,r,o,c))throw X.fail("work provider runtime diagnostic is inconsistent");return Object.freeze({provider:s,status:r,remediation:o,runtime:c})}const Lo=["SCG_WORK_PRIOR_EXECUTION_UNCONFIRMED","SCG_WORK_LEGACY_EXECUTION_UNCONFIRMED"],Mo=32,Do=new Set(["code","requestId","remainingCount","unknownCount"]),qo=new Set(["code","requestIds","requestCount"]),W=ie("SCG_WORK_PROVIDER_INVALID");function zo(t){const e=W.record(t,"work provider session warning"),i=W.member(W.field(e,"code"),Lo,"work provider session warning code");if(i==="SCG_WORK_PRIOR_EXECUTION_UNCONFIRMED")return W.exactKeys(e,Do,"work provider session warning"),Object.freeze({code:i,requestId:W.uuid(W.field(e,"requestId"),"work provider session warning requestId"),remainingCount:W.integer(W.field(e,"remainingCount"),"work provider session warning remainingCount"),unknownCount:W.integer(W.field(e,"unknownCount"),"work provider session warning unknownCount")});W.exactKeys(e,qo,"work provider session warning");const n=W.denseArray(W.field(e,"requestIds"),"work provider session warning requestIds").map(r=>W.uuid(r,"work provider session warning requestId"));W.unique(n,"work provider session warning requestIds");const s=W.integer(W.field(e,"requestCount"),"work provider session warning requestCount");if(s===0||n.length===0||n.length>Math.min(s,Mo))throw W.fail("work provider legacy warning request list is inconsistent");return Object.freeze({code:i,requestIds:Object.freeze(n),requestCount:s})}const De="v1",Go=["bound","new-session-pending","restart-required"],jo=new Set(["schemaVersion","provider","generation","warningAcknowledgments"]),Wo=new Set(["provider","contractVersion","acknowledgedAt"]),wn=new Set(["schemaVersion","selection","readiness","warningContractVersion"]),Uo=new Set(["provider","state","nextRequestStartsNewConversation","warnings"]),A=ie("SCG_WORK_PROVIDER_INVALID");function Vo(t){const e=A.record(t,"work provider tool result");if(A.exactKeys(e,Object.hasOwn(e,"session")?new Set([...wn,"session"]):wn,"work provider tool result"),A.schemaVersion(A.field(e,"schemaVersion"),"work provider tool result"),A.field(e,"warningContractVersion")!==De)throw A.fail("work provider tool warningContractVersion is invalid");const i=Fo(A.field(e,"selection")),n=Po(A.field(e,"readiness"));if(n.provider!==i.provider)throw A.fail("work provider readiness does not match selection");const s=Object.hasOwn(e,"session")?{session:Bo(A.field(e,"session"))}:{};if(s.session!==void 0&&s.session.provider!==i.provider)throw A.fail("work provider session status does not match selection");return Object.freeze({schemaVersion:1,selection:i,readiness:n,warningContractVersion:De,...s})}function Bo(t){const e=A.record(t,"work provider session status");A.exactKeys(e,Uo,"work provider session status");const i=A.member(A.field(e,"state"),Go,"work provider session state"),n=A.flag(A.field(e,"nextRequestStartsNewConversation"),"work provider session nextRequestStartsNewConversation");if(i==="new-session-pending"&&!n||i==="restart-required"&&n)throw A.fail("work provider session status fields are inconsistent");const s=A.denseArray(A.field(e,"warnings"),"work provider session warnings").map(zo);return A.unique(s.map(r=>r.code),"work provider session warnings"),Object.freeze({provider:Me(A.field(e,"provider")),state:i,nextRequestStartsNewConversation:n,warnings:Object.freeze(s)})}function Fo(t){const e=A.record(t,"work provider selection");A.exactKeys(e,rn(e,jo),"work provider selection"),A.schemaVersion(A.field(e,"schemaVersion"),"work provider selection");const i=A.denseArray(A.field(e,"warningAcknowledgments"),"work provider warningAcknowledgments").map($o);return A.unique(i.map(n=>n.provider),"work provider warningAcknowledgments"),Object.freeze({schemaVersion:1,provider:mt(A.field(e,"provider")),generation:A.integer(A.field(e,"generation"),"work provider generation"),warningAcknowledgments:Object.freeze(i),...ut(e)})}function $o(t){const e=A.record(t,"work warning acknowledgment");if(A.exactKeys(e,Wo,"work warning acknowledgment"),A.field(e,"contractVersion")!==De)throw A.fail("work warning acknowledgment must match the warning contract");return Object.freeze({provider:Me(A.field(e,"provider")),contractVersion:De,acknowledgedAt:A.timestamp(A.field(e,"acknowledgedAt"),"work warning acknowledgedAt")})}const P=ie("SCG_WORK_CAPABILITIES_UNAVAILABLE"),Ko=new Set(["schemaVersion","provider","status","reason","models"]),Ho=new Set(["model","displayName","reasoningEfforts","defaultReasoningEffort"]),Yo=["available","unsupported","unavailable"],Xo=["unsupported-protocol","daemon-not-running","authentication-required","invalid-response","limit-exceeded","discovery-failed"];function Qo(t){const e=P.record(t,"model capability");P.exactKeys(e,Ho,"model capability");const i=wt(P.field(e,"model"),512,!1),n=wt(P.field(e,"displayName"),256,!0),s=P.field(e,"reasoningEfforts"),r=s===null?null:P.denseArray(s,"reasoning efforts").map(c=>wt(c,128,!1));if(r!==null){if(r.length>32)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");P.unique(r,"reasoning efforts")}const o=P.field(e,"defaultReasoningEffort"),a=o===null?null:wt(o,128,!1);if(a!==null&&r?.includes(a)!==!0)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");return Object.freeze({model:i,displayName:n,reasoningEfforts:r===null?null:Object.freeze(r),defaultReasoningEffort:a})}function Zo(t){const e=P.record(t,"provider capabilities"),i=Object.hasOwn(e,"runtime"),n=Object.hasOwn(e,"identity");P.exactKeys(e,new Set([...Ko,...i?["runtime"]:[],...n?["identity"]:[]]),"provider capabilities"),P.schemaVersion(P.field(e,"schemaVersion"),"provider capabilities");const s=Me(P.field(e,"provider")),r=P.member(P.field(e,"status"),Yo,"capability status"),o=P.field(e,"reason"),a=o===null?null:P.member(o,Xo,"capability reason"),c=P.denseArray(P.field(e,"models"),"capability models");if(c.length>1e3)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");const l=c.map(Qo);switch(P.unique(l.map(h=>h.model),"capability models"),r){case"available":if(a!==null)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");break;case"unsupported":if(a!=="unsupported-protocol"||l.length!==0)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");break;case"unavailable":if(a===null||l.length!==0)throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");break;default:throw r}const d=i?gn(P.field(e,"runtime")):void 0;if(d!==void 0&&(!hn(s,d)||r!=="unavailable"||a!=="discovery-failed"))throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");const u=n?mn(P.field(e,"identity")):void 0;if(u!==void 0&&(u.provider!==s||i))throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");return Object.freeze({schemaVersion:1,provider:s,status:r,reason:a,models:Object.freeze(l),...d===void 0?{}:{runtime:d},...u===void 0?{}:{identity:u}})}function wt(t,e,i){if(typeof t!="string"||[...t].length>e||new RegExp("\\p{Cc}","u").test(t)||!i&&!/\S/u.test(t))throw P.fail("SCG_WORK_CAPABILITIES_UNAVAILABLE");return t}const Jo=["added","modified","deleted","mode-only","binary","metadata-only"],ea=["exact","post-late","unavailable"],ta=["complete","truncated","unavailable"],ia=["context","added","deleted"],na=new Set(["schemaVersion","requestId","state","fidelity","files"]),sa=new Set(["path","status","preContent","postContent","hunks"]),ra=new Set(["digest","mode","sizeBytes"]),oa=new Set(["oldStart","oldLines","newStart","newLines","lines"]),aa=new Set(["kind","oldLine","newLine","text"]),ca=4095,m=ie("SCG_WORK_DIFF_INVALID");function la(t,e=D){const i=m.record(t,"work task patch");m.exactKeys(i,na,"work task patch"),m.schemaVersion(m.field(i,"schemaVersion"),"work task patch");const n=m.member(m.field(i,"state"),ta,"work diff state"),s=m.denseArray(m.field(i,"files"),"work diff files").map(o=>da(o,e));if(n==="unavailable"&&s.length>0)throw m.fail("unavailable work diff must not carry files");if(fa(s),s.reduce((o,a)=>o+a.hunks.reduce((c,l)=>c+l.lines.reduce((d,u)=>d+_e(u.text),0),0),0)>e.historyDiffRenderBytes)throw Yt("work diff text exceeds its effective render limit");return Object.freeze({schemaVersion:1,requestId:m.uuid(m.field(i,"requestId"),"work diff requestId"),state:n,fidelity:m.member(m.field(i,"fidelity"),ea,"work diff fidelity"),files:Object.freeze(s)})}function da(t,e){const i=m.record(t,"work diff file");m.exactKeys(i,sa,"work diff file");const n=m.member(m.field(i,"status"),Jo,"work diff file status"),s=vn(m.field(i,"preContent"),e),r=vn(m.field(i,"postContent"),e);ga(n,s,r);const o=m.denseArray(m.field(i,"hunks"),"work diff hunks").map(ua);if((n==="mode-only"||n==="binary"||n==="metadata-only")&&o.length>0)throw m.fail("non-text work diff files must not carry text hunks");return Object.freeze({path:yo(m.field(i,"path"),m),status:n,preContent:s,postContent:r,hunks:Object.freeze(o)})}function vn(t,e){if(t===null)return null;const i=m.record(t,"work diff content identity");m.exactKeys(i,ra,"work diff content identity");const n=m.integer(m.field(i,"mode"),"work diff content mode"),s=m.integer(m.field(i,"sizeBytes"),"work diff content sizeBytes");if(n>ca)throw m.fail("work diff content mode must be a POSIX permission value");if(s>e.historyFileBytes)throw Yt("work diff content exceeds its effective file limit");return Object.freeze({digest:m.digest(m.field(i,"digest"),"work diff content digest"),mode:n,sizeBytes:s})}function ua(t){const e=m.record(t,"work diff hunk");return m.exactKeys(e,oa,"work diff hunk"),Object.freeze({oldStart:m.integer(m.field(e,"oldStart"),"work diff hunk oldStart"),oldLines:m.integer(m.field(e,"oldLines"),"work diff hunk oldLines"),newStart:m.integer(m.field(e,"newStart"),"work diff hunk newStart"),newLines:m.integer(m.field(e,"newLines"),"work diff hunk newLines"),lines:Object.freeze(m.denseArray(m.field(e,"lines"),"work diff lines").map(ha))})}function ha(t){const e=m.record(t,"work diff line");m.exactKeys(e,aa,"work diff line");const i=m.member(m.field(e,"kind"),ia,"work diff line kind"),n=bn(m.field(e,"oldLine"),"oldLine"),s=bn(m.field(e,"newLine"),"newLine");if(i==="added"&&n!==null||i==="deleted"&&s!==null)throw m.fail("work diff line identity does not match its kind");if(i==="context"&&(n===null||s===null))throw m.fail("work diff context line requires pre and post line numbers");return Object.freeze({kind:i,oldLine:n,newLine:s,text:m.text(m.field(e,"text"),"work diff line text")})}function bn(t,e){if(t===null)return null;const i=m.integer(t,`work diff line ${e}`);if(i===0)throw m.fail(`work diff line ${e} must be positive`);return i}function ga(t,e,i){switch(t){case"added":if(e!==null||i===null)throw m.fail("added work diff requires only a post identity");return;case"modified":case"mode-only":if(e===null||i===null)throw m.fail(`${t} work diff requires pre and post identities`);return;case"deleted":if(e===null||i!==null)throw m.fail("deleted work diff requires only a pre identity");return;case"binary":case"metadata-only":if(e===null&&i===null)throw m.fail(`${t} work diff requires at least one content identity`);return}}function fa(t){let e;for(const i of t){if(e!==void 0&&e>=i.path)throw m.fail("work diff files must be strictly sorted by path");e=i.path}}const Jt=["queued","preparing","dispatching","delivered","running","cancelling","completed","failed","cancelled","indeterminate"],pa=["completed","failed","cancelled","indeterminate"],ma=["none","pending","acknowledged"],yn=["SCG_OMO_CONVERSATION_INCOMPATIBLE","SCG_OMO_RUNTIME_AUTHORITY_ABSENT","SCG_OMO_RUNTIME_UNSUPPORTED","SCG_OMO_RUNTIME_MISSING","SCG_OMO_RUNTIME_INTEGRITY","SCG_RUNTIME_AUTHORITY_ABSENT","SCG_RUNTIME_UNSUPPORTED","SCG_RUNTIME_MISSING","SCG_RUNTIME_INTEGRITY","SCG_RUNTIME_VERSION_MISMATCH","SCG_RUNTIME_CONVERSATION_UNQUALIFIED","SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED"],En=["SCG_WORK_REQUEST_INVALID","SCG_WORK_PROVIDER_INVALID","SCG_WORK_EXECUTION_SETTINGS_INVALID","SCG_WORK_CAPABILITIES_UNAVAILABLE","SCG_WORK_HISTORY_INVALID","SCG_WORK_DIFF_INVALID","SCG_WORK_LIMIT_EXCEEDED","SCG_WORK_PROVIDER_NONE","SCG_WORK_PROVIDER_UNREADY","SCG_WORK_WARNING_REQUIRED","SCG_WORK_GENERATION_CONFLICT","SCG_WORK_ACTIVE","SCG_WORK_STALE_PREVIEW","SCG_WORK_NO_ELIGIBLE","SCG_WORK_NOT_FOUND","SCG_WORK_CANCELLED","SCG_WORK_INDETERMINATE",...yn];function wa(t){return yn.find(e=>e===t)??null}const va=new Set(["schemaVersion","requestId","projectId","page","pageRevision","provider","providerGeneration","warningContractVersion","promptDigest","snapshotDigest","annotationDigests","createdAt"]),ba=new Set(["schemaVersion","requestId","state","reviewState","mayHaveModifiedWorkspace","errorCode","eventSequence","updatedAt"]),ya=new Set(["requestId","fromState","toState","expectedEventSequence","occurredAt","mayHaveModifiedWorkspace"]),Ea=new Set(["failed","indeterminate"]),Sa=new Set(pa),p=ie("SCG_WORK_REQUEST_INVALID");function Ee(t){return Sa.has(t)}function ka(t){return p.member(t,En,"work error code")}function Ca(t,e=D){const i=p.record(t,"work request");if(p.exactKeys(i,rn(i,va),"work request"),p.schemaVersion(p.field(i,"schemaVersion"),"work request"),p.field(i,"warningContractVersion")!==De)throw p.fail("work request warningContractVersion must match the warning contract");const n=p.denseArray(p.field(i,"annotationDigests"),"work request annotationDigests").map(s=>p.digest(s,"work request annotation digest"));if(n.length===0)throw p.fail("work request must include at least one annotation digest");if(n.length>e.workRequestAnnotations)throw Yt("work request annotation count exceeds its effective limit");return p.unique(n,"work request annotationDigests"),Object.freeze({schemaVersion:1,requestId:p.uuid(p.field(i,"requestId"),"work request requestId"),projectId:p.mapped("work request projectId is invalid",()=>lt(p.field(i,"projectId"))),page:p.mapped("work request page is invalid",()=>$e(p.field(i,"page"))),pageRevision:p.integer(p.field(i,"pageRevision"),"work request pageRevision"),provider:p.mapped("work request provider is invalid",()=>Me(p.field(i,"provider"))),providerGeneration:p.integer(p.field(i,"providerGeneration"),"work request providerGeneration"),warningContractVersion:De,promptDigest:p.digest(p.field(i,"promptDigest"),"work request promptDigest"),snapshotDigest:p.digest(p.field(i,"snapshotDigest"),"work request snapshotDigest"),annotationDigests:Object.freeze(n),createdAt:p.timestamp(p.field(i,"createdAt"),"work request createdAt"),...ut(i)})}function Sn(t){const e=p.record(t,"work result");p.exactKeys(e,ba,"work result"),p.schemaVersion(p.field(e,"schemaVersion"),"work result");const i=p.member(p.field(e,"state"),Jt,"work result state"),n=p.member(p.field(e,"reviewState"),ma,"work result review");if(n!=="none"&&i!=="completed")throw p.fail("work review state requires a completed request");return Object.freeze({schemaVersion:1,requestId:p.uuid(p.field(e,"requestId"),"work result requestId"),state:i,reviewState:n,mayHaveModifiedWorkspace:p.flag(p.field(e,"mayHaveModifiedWorkspace"),"work result mayHaveModifiedWorkspace"),errorCode:Aa(p.field(e,"errorCode"),i),eventSequence:p.integer(p.field(e,"eventSequence"),"work result eventSequence"),updatedAt:p.timestamp(p.field(e,"updatedAt"),"work result updatedAt")})}function Ia(t){const e=p.record(t,"work transition input");return p.exactKeys(e,ya,"work transition input"),Object.freeze({requestId:p.uuid(p.field(e,"requestId"),"work transition requestId"),fromState:p.member(p.field(e,"fromState"),Jt,"work transition fromState"),toState:p.member(p.field(e,"toState"),Jt,"work transition toState"),expectedEventSequence:p.integer(p.field(e,"expectedEventSequence"),"work transition expectedEventSequence"),occurredAt:p.timestamp(p.field(e,"occurredAt"),"work transition occurredAt"),mayHaveModifiedWorkspace:p.flag(p.field(e,"mayHaveModifiedWorkspace"),"work transition mayHaveModifiedWorkspace")})}function Aa(t,e){if(Ea.has(e))return ka(t);if(t!==null)throw p.fail("work result errorCode is only defined for failed or indeterminate work");return null}async function kn(t){const e=await t.fetch(t.url,{cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:t.signal});try{Oa(e,t);const i=await _a(e,t.artifact.maxBytes,t.signal);try{return await Ta(i,t.artifact.sha256,t.crypto),t.kind==="module"?Ra(i):xa(i),i}catch(n){throw i.fill(0),n}}catch(i){throw await Na(e),i}}function Oa(t,e){const i=t.headers.get("content-length");if(e.signal.aborted||t.status!==200||!t.ok||t.redirected||t.type==="opaque"||t.url!==e.url||t.headers.get("content-type")!==e.artifact.mediaType||t.headers.get("cache-control")!=="private, no-store"||t.headers.get("x-content-type-options")!=="nosniff"||t.headers.get("x-scene-glass-artifact-path")!==e.artifact.path||t.headers.get("x-scene-glass-module-id")!==e.premium.moduleId||t.headers.get("x-scene-glass-module-abi")!==String(e.premium.abiVersion)||t.headers.get("x-scene-glass-module-namespace")!==e.premium.namespace||t.headers.get("x-scene-glass-content-sha256")!==e.artifact.sha256||!/^sha256:[0-9a-f]{64}$/u.test(t.headers.get("x-scene-glass-release-manifest-sha256")??"")||i===null||!/^[1-9][0-9]*$/u.test(i)||Number(i)>e.artifact.maxBytes)throw new Error("premium artifact response is invalid")}async function _a(t,e,i){const n=Number(t.headers.get("content-length"));if(!Number.isSafeInteger(n)||n<1||n>e||t.body===null)throw new Error("premium artifact body is invalid");const s=t.body.getReader(),r=new Uint8Array(n);let o=0;const a=()=>{s.cancel().catch(()=>{})};i.addEventListener("abort",a,{once:!0});try{for(;;){const c=await s.read();if(i.aborted)throw new Error("premium artifact fetch aborted");if(c.done)break;const l=c.value;try{if(l.byteLength===0||o+l.byteLength>n)throw new Error("premium artifact body is invalid");r.set(l,o),o+=l.byteLength}finally{l.fill(0)}}if(o!==n)throw new Error("premium artifact body is invalid");return r}catch(c){throw r.fill(0),c}finally{i.removeEventListener("abort",a);try{await s.cancel()}catch{}s.releaseLock()}}async function Ta(t,e,i){const n=new Uint8Array(await i.subtle.digest("SHA-256",t));try{let s="sha256:";for(const r of n)s+=r.toString(16).padStart(2,"0");if(s!==e)throw new Error("premium artifact digest mismatch")}finally{n.fill(0)}}function Cn(t){const e=t.toLowerCase();let i=e.indexOf("source");for(;i!==-1;){if(e.startsWith("url=",i+6)||e.charCodeAt(i+6)===109&&e.startsWith("appingurl",i+7))return!0;i=e.indexOf("source",i+1)}return!1}function Ra(t){const e=new TextDecoder("utf-8",{fatal:!0}).decode(t);if(e.length===0||e.includes("\0")||/\bimport(?![A-Za-z0-9_$])/u.test(e)||/\bexport\b[^;]{0,1024}\bfrom\s*["']/u.test(e)||Cn(e)||/(?:https?:|blob:|data:)/iu.test(e)||/scg-premium-measurement-styles|\[data-scg-premium-measurement|createElement\(["']style["']/u.test(e))throw new Error("premium module source is invalid")}function xa(t){const e=new TextDecoder("utf-8",{fatal:!0}).decode(t);if(e.length===0||e.includes("\0")||e.split(`
2
+ `).filter(i=>i.length>0).length>1||Cn(e)||/@import|url\s*\(|(?:https?:|blob:|data:)/iu.test(e)||!e.includes("[data-scg-premium-measurement=true]")||!/\.scg-meas(?:ure)-layer/u.test(e)||!/\.scg-si(?:ze)-layer/u.test(e))throw new Error("premium stylesheet source is invalid")}async function Na(t){try{await t.body?.cancel()}catch{}}function Pa(t,e,i,n){let s=!1;return Object.freeze({generation:t,remove(){if(s)return;s=!0;let r;try{e.remove()}catch(o){r=o}try{n(i)}catch(o){r===void 0&&(r=o)}if(r!==void 0)throw r}})}function La(t){return(e,i)=>new Promise((n,s)=>{const r=t.createElement("link");let o=!1,a=!1;const c=()=>{a||(a=!0,r.remove())},l=()=>{i.removeEventListener("abort",u),r.removeEventListener("load",f),r.removeEventListener("error",h)},d=()=>{o||(o=!0,l(),c(),s(new Error("premium stylesheet attachment failed")))},u=()=>d(),h=()=>d(),f=()=>{o||(o=!0,l(),n(Object.freeze({remove:c})))};if(r.rel="stylesheet",r.href=e,r.referrerPolicy="no-referrer",r.className="scg-premium-measurement-styles",r.addEventListener("load",f,{once:!0}),r.addEventListener("error",h,{once:!0}),i.addEventListener("abort",u,{once:!0}),i.aborted)return u();t.head.append(r)})}function Ma(t){let e;try{e=new URL(t)}catch{throw new TypeError("local premium origin must be the active Vite authority")}const i=Number(e.port);if(e.protocol!=="http:"||e.hostname!=="127.0.0.1"||e.username!==""||e.password!==""||e.pathname!=="/"||e.search!==""||e.hash!==""||!Number.isInteger(i)||i<1024||i>65535||i===4175||e.origin!==t)throw new TypeError("local premium origin must be the active Vite authority");return e.origin}function Da(){if(typeof globalThis.document?.createElement!="function")throw new TypeError("document premium artifact loading is unavailable");return globalThis.document}function qa(){if(typeof globalThis.fetch!="function")throw new TypeError("premium fetch is unavailable");return globalThis.fetch.bind(globalThis)}function za(){if(globalThis.crypto?.subtle===void 0)throw new TypeError("Web Crypto is unavailable");return globalThis.crypto}function Ga(t){try{t?.remove()}catch{}}function ja(t,e){try{e(t)}catch{}}function Wa(t,e,i){return e.aborted?Promise.reject(i()):new Promise((n,s)=>{const r=()=>s(i());e.addEventListener("abort",r,{once:!0}),t.then(o=>{e.removeEventListener("abort",r),e.aborted?s(i()):n(o)},()=>{e.removeEventListener("abort",r),s(i())})})}function Ua(t){return import(t)}const Va=`/@scene-glass/${Kt}`,Ba=`/@scene-glass/${Ht}`,Fa="local-premium";class $a extends Error{name="LocalPremiumProviderError";constructor(){super("local premium artifact validation failed")}}class Ka{provider=Fa;#e;#t;#i;#s;#n;#o;#r;#a;#l;#c=null;#d=!1;#u=0;#h=null;#g=null;constructor(e){const i=Ma(e.origin);this.#e=Ji(e.releaseArtifact),this.#r=new URL(Va,`${i}/`).href,this.#l=new URL(Ba,`${i}/`).href,this.#n=e.fetch??qa(),this.#s=e.crypto??za(),this.#i=e.createObjectURL??URL.createObjectURL.bind(URL),this.#a=e.revokeObjectURL??URL.revokeObjectURL.bind(URL),this.#t=e.attachStylesheet??La(e.document??Da()),this.#o=e.importModule??Ua}load(e){if(e.signal.aborted||this.#d)return Promise.reject(Se());const i=this.#c;if(i!==null&&i.generation===this.#u&&this.#g?.generation===this.#u)return Wa(Promise.resolve(i.value),e.signal,Se);let n=this.#h;if(n===null||n.generation!==this.#u){const s=new AbortController;n={controller:s,generation:this.#u,promise:null,settled:!1,waiters:0};const r=n;n.promise=this.loadGeneration(r.generation,s).finally(()=>{r.settled=!0,this.#h===r&&(this.#h=null)}),this.#h=n}return this.join(n,e.signal)}invalidate(){this.#d||(this.#u+=1,this.#c=null,this.#h?.controller.abort(),this.#h=null,this.releaseStylesheet())}destroy(){if(!this.#d)try{this.invalidate()}finally{this.#d=!0}}join(e,i){const n=e.promise;return n===null?Promise.reject(Se()):(e.waiters+=1,new Promise((s,r)=>{let o=!1;const a=l=>{o||(o=!0,i.removeEventListener("abort",c),e.waiters-=1,l())},c=()=>{a(()=>r(Se())),!e.settled&&e.waiters===0&&e.controller.abort()};if(i.addEventListener("abort",c,{once:!0}),i.aborted)return c();n.then(l=>a(()=>s(l)),()=>a(()=>r(Se())))}))}async loadGeneration(e,i){let n=null,s=!1;try{this.assertCurrent(e,i),n=await this.loadStylesheet(e,i),this.assertCurrent(e,i);const r=await this.loadModule(i);this.assertCurrent(e,i);const o=lo(r);return this.assertCurrent(e,i),this.releaseStylesheet(),this.#g=n,this.#c=Object.freeze({generation:e,value:o}),s=!0,o}catch{throw Se()}finally{s||Ga(n)}}async loadStylesheet(e,i){const n=await kn({artifact:this.#e.stylesheet,crypto:this.#s,fetch:this.#n,kind:"stylesheet",premium:this.#e,signal:i.signal,url:this.#l});let s=null;try{this.assertCurrent(e,i),s=this.#i(new Blob([n],{type:this.#e.stylesheet.mediaType}))}finally{n.fill(0)}try{const r=await this.#t(s,i.signal);return Pa(e,r,s,this.#a)}catch(r){throw ja(s,this.#a),r}}async loadModule(e){const i=await kn({artifact:this.#e.module,crypto:this.#s,fetch:this.#n,kind:"module",premium:this.#e,signal:e.signal,url:this.#r});let n=null;try{n=this.#i(new Blob([i],{type:this.#e.module.mediaType}))}finally{i.fill(0)}try{return await this.#o(n)}finally{this.#a(n)}}assertCurrent(e,i){if(this.#d||e!==this.#u||i.signal.aborted)throw Se()}releaseStylesheet(){const e=this.#g;this.#g=null,e?.remove()}}function Se(){return new $a}const Ha=kr,Ya=Cr,Xa=25,Qa=35,Za=20,Ja=20;function ec(t,e){const i=t.fingerprint;if(t.dataScgId!==void 0){const o=e.filter(c=>c.dataScgId===t.dataScgId),a=o[0];if(o.length===1&&a!==void 0)return In(a,"data-scg-id",100,100);if(i===void 0)return o.length===0?ei():An(100,0)}if(i===void 0||e.length===0)return ei();const n=e.map((o,a)=>({candidate:o,index:a,score:tc(i,o)})).sort(ic),s=n[0];if(s===void 0)return ei();const r=s.score-(n[1]?.score??0);return s.score<Ha||r<Ya?An(s.score,r):In(s.candidate,"fingerprint",s.score,r)}function tc(t,e){const i=e.fingerprint;if(i===void 0)return 0;const n=t.tag===i.tag?Xa:0,s=On(t.stableAttributes.length,t.stableAttributes.filter(([a,c])=>i.stableAttributes.some(([l,d])=>l===a&&d===c)).length,Qa),r=On(t.ancestorSignatures.length,t.ancestorSignatures.filter((a,c)=>a===i.ancestorSignatures[c]).length,Za),o=t.textDigest===i.textDigest?Ja:0;return n+s+r+o}function In(t,e,i,n){return Object.freeze({status:"resolved",candidate:t.value,strategy:e,score:i,gap:n,resolution:Object.freeze({status:"resolved",reason:null})})}function ei(){return Object.freeze({status:"not-found",resolution:Object.freeze({status:"not-found",reason:"not-found"})})}function An(t,e){return Object.freeze({status:"ambiguous",score:t,gap:e,resolution:Object.freeze({status:"ambiguous",reason:"ambiguous"})})}function On(t,e,i){return t===0?i:Math.floor(e*i/t)}function ic(t,e){return e.score-t.score||t.index-e.index}const nc=4,sc=12,rc=128,oc=512,ac=64,cc=new Set(["alt","for","href","id","name","rel","role","title","type"]);async function lc(t){Tn(t);const e=dc(t);return Object.freeze(e!==void 0?{dataScgId:e}:{fingerprint:await _n(t)})}async function _n(t){Tn(t);const e={tag:xn(t),stableAttributes:Rn(t),ancestorSignatures:uc(t),textDigest:await mc(pc(t))};return bc(e)}function ti(t){const e=t.ownerDocument;return e.documentElement!==null&&e.documentElement.contains(t)&&t.getRootNode()===e}function Tn(t){if(!ti(t))throw new Error("Scene Glass can capture locators only for mounted light-DOM elements")}function dc(t){const e=t.getAttribute("data-scg-id");if(e===null||!Pn(e))return;let i=0;for(const n of t.ownerDocument.querySelectorAll("[data-scg-id]"))if(n.getAttribute("data-scg-id")===e&&ti(n)&&(i+=1,i>1))return;return i===1?e:void 0}function Rn(t){const e=[];for(const i of t.attributes){const n=i.name.toLowerCase(),s=fc(i.value);gc(n,s)&&e.push(Object.freeze([n,s]))}return e.sort(vc),Object.freeze(e.slice(0,sc))}function uc(t){const e=[];let i=t.parentElement;for(;i!==null&&e.length<nc;)e.push(hc(i)),i=i.parentElement;return Object.freeze(e)}function hc(t){return JSON.stringify([xn(t),Rn(t)])}function xn(t){return t.localName.toLowerCase()}function gc(t,e){return!/^[a-z][a-z0-9:_-]*$/u.test(t)||Array.from(t).length>ac||!Pn(e)||t==="class"||t==="data-scg-id"||t==="slot"||t==="style"||t.startsWith("on")?!1:cc.has(t)||t.startsWith("aria-")||t.startsWith("data-")}function fc(t){return Nn(t.trim(),rc)}function pc(t){const e="innerText"in t?t.innerText:void 0,i=typeof e=="string"?e:t.textContent;return Nn((i??"").replace(/\s+/gu," ").trim(),oc)}async function mc(t){const e=globalThis.crypto?.subtle;if(e===void 0)throw new Error("Scene Glass requires Web Crypto to capture a locator");const i=new TextEncoder().encode(t),n=await e.digest("SHA-256",i);return`sha256:${[...new Uint8Array(n)].map(r=>r.toString(16).padStart(2,"0")).join("")}`}function Nn(t,e){const i=Array.from(t);return i.length<=e?t:i.slice(0,e).join("")}function Pn(t){return t.trim().length>0&&!wc(t)&&new TextEncoder().encode(t).byteLength<=512}function wc(t){for(let e=0;e<t.length;e+=1){const i=t.charCodeAt(e);if(i<=31||i===127)return!0}return!1}function vc(t,e){const[i,n]=t,[s,r]=e;return i!==s?i<s?-1:1:n===r?0:n<r?-1:1}function bc(t){return Object.freeze({tag:t.tag,stableAttributes:Object.freeze(t.stableAttributes.map(([e,i])=>Object.freeze([e,i]))),ancestorSignatures:Object.freeze([...t.ancestorSignatures]),textDigest:t.textDigest})}async function yc(t,e=kc()){const i=Ec(e);if(i.length===0)return He();const n=t.dataScgId===void 0?[]:i.filter(s=>s.getAttribute("data-scg-id")===t.dataScgId);if(n.length===1){const s=n[0];if(s!==void 0)return Mn(s,"data-scg-id",100,100)}if(t.dataScgId!==void 0&&t.fingerprint===void 0)return n.length===0?He():Dn(100,0);if(t.fingerprint===void 0)return He();try{const s=await Promise.all(i.map(async r=>{const o=r.getAttribute("data-scg-id");return Object.freeze({value:r,...o===null?{}:{dataScgId:o},fingerprint:await _n(r)})}));return Sc(ec(t,s))}catch{return He()}}function Ec(t){if(t===void 0)return[];const e=[];Cc(t)&&Ln(t)&&e.push(t);for(const i of t.querySelectorAll("*"))Ln(i)&&e.push(i);return e}function Ln(t){return t.getAttribute("data-scg-selector-overlay")!=="true"&&ti(t)}function Sc(t){return t.status==="resolved"?Mn(t.candidate,t.strategy,t.score,t.gap):t.status==="ambiguous"?Dn(t.score,t.gap):He()}function Mn(t,e,i,n){return Object.freeze({status:"resolved",element:t,strategy:e,score:i,gap:n,resolution:Object.freeze({status:"resolved",reason:null})})}function Dn(t,e){return Object.freeze({status:"unresolved",reason:"ambiguous",score:t,gap:e,resolution:Object.freeze({status:"ambiguous",reason:"ambiguous"})})}function He(){return Object.freeze({status:"unresolved",reason:"not-found",resolution:Object.freeze({status:"not-found",reason:"not-found"})})}function kc(){return typeof globalThis.document>"u"?void 0:globalThis.document}function Cc(t){return typeof t=="object"&&t!==null&&t.nodeType===1}class Ic{port;resolve;root;listeners=new Set;state=Ac();sequence=0;destroyed=!1;constructor(e){this.port=e.port,this.resolve=e.resolve??yc,this.root=e.root,e.onStateChange!==void 0&&this.listeners.add(e.onStateChange)}getState(){return this.state}subscribe(e){return this.destroyed?()=>{}:(this.listeners.add(e),()=>{this.listeners.delete(e)})}setPage(e){this.destroyed||(this.sequence+=1,this.commit({generation:this.state.generation+1,page:e,annotations:[],bindings:[],loading:!1}))}async load(){if(this.destroyed||this.state.page===void 0)return this.missingContext();const e=Object.freeze({generation:this.state.generation,page:this.state.page}),i=this.begin(e.generation,!0);try{const n=await this.port.listAnnotations(e.page);return this.isCurrent(i)?(this.commit({generation:e.generation,page:e.page,revision:n.revision,annotations:n.annotations,bindings:[],loading:!0}),await this.reconcileSnapshot(i,n.annotations),this.isCurrent(i)?(this.commit({...this.state,loading:!1}),{status:"applied"}):{status:"ignored"}):{status:"ignored"}}catch(n){return this.fail(i,n)}}async create(e){const i=this.requireContext();if(i===void 0)return this.missingContext();const n=this.begin(i.generation,!0),s={...e,page:i.page,expectedRevision:i.revision};try{const r=await this.port.createAnnotation(s);if(!this.isCurrent(n))return{status:"ignored"};const o=qn(this.state.annotations,r.annotation);return this.commit({generation:i.generation,page:i.page,revision:r.revision,annotations:o,bindings:[],loading:!0}),await this.reconcileSnapshot(n,o),this.isCurrent(n)?(this.commit({...this.state,loading:!1}),{status:"applied"}):{status:"ignored"}}catch(r){return this.fail(n,r)}}async update(e){const i=this.requireContext();if(i===void 0)return this.missingContext();const n=this.begin(i.generation,!0),s={...e,page:i.page,expectedRevision:i.revision};try{const r=await this.port.updateAnnotation(s);if(!this.isCurrent(n))return{status:"ignored"};const o=qn(this.state.annotations,r.annotation);return this.commit({generation:i.generation,page:i.page,revision:r.revision,annotations:o,bindings:[],loading:!0}),await this.reconcileSnapshot(n,o),this.isCurrent(n)?(this.commit({...this.state,loading:!1}),{status:"applied"}):{status:"ignored"}}catch(r){return this.fail(n,r)}}async delete(e){const i=this.requireContext();if(i===void 0)return this.missingContext();const n=this.begin(i.generation,!0),s={...e,page:i.page,expectedRevision:i.revision};try{const r=await this.port.deleteAnnotation(s);if(!this.isCurrent(n))return{status:"ignored"};const o=this.state.annotations.filter(a=>a.id!==r.annotationId);return this.commit({generation:i.generation,page:i.page,revision:r.revision,annotations:o,bindings:[],loading:!0}),await this.reconcileSnapshot(n,o),this.isCurrent(n)?(this.commit({...this.state,loading:!1}),{status:"applied"}):{status:"ignored"}}catch(r){return this.fail(n,r)}}async reconcile(){const e=this.requireContext();if(e===void 0)return this.missingContext();const i=this.begin(e.generation,!1);this.commit({...this.state,bindings:[]});try{return await this.reconcileSnapshot(i,this.state.annotations),this.isCurrent(i)?{status:"applied"}:{status:"ignored"}}catch(n){return this.fail(i,n)}}setManualError(e,i="SCG_MANUAL_ERROR"){this.destroyed||this.commit({...this.state,error:vt({code:i,message:e,source:"manual"})})}clearError(){this.destroyed||this.state.error===void 0||this.commit(Rc(this.state))}destroy(){this.destroyed||(this.destroyed=!0,this.sequence+=1,this.listeners.clear())}begin(e,i){const n=Object.freeze({generation:e,sequence:this.sequence+=1});return this.commit({...this.state,loading:i}),n}requireContext(){if(!(this.destroyed||this.state.page===void 0||this.state.revision===void 0))return Object.freeze({generation:this.state.generation,page:this.state.page,revision:this.state.revision})}missingContext(){const e=vt({code:"SCG_ANNOTATION_STATE",message:"Load annotations for the current page before changing them.",source:"manual"});return this.destroyed||this.commit({...this.state,error:e}),{status:"failed",error:e}}isCurrent(e){return!this.destroyed&&this.state.generation===e.generation&&this.sequence===e.sequence}async reconcileSnapshot(e,i){const n=await Promise.all(i.map(async s=>Object.freeze({annotation:s,resolution:await this.resolve(s.locator,this.root)})));this.isCurrent(e)&&this.commit({...this.state,bindings:Object.freeze(n)})}fail(e,i){if(!this.isCurrent(e))return{status:"ignored"};const n=Oc(i);return this.commit({...this.state,loading:!1,error:n}),{status:"failed",error:n}}commit(e){this.state=zn(e);for(const i of this.listeners)try{i(this.state)}catch{}}}function Ac(){return zn({generation:0,annotations:[],bindings:[],loading:!1})}function qn(t,e){const i=t.findIndex(n=>n.id===e.id);return i<0?Object.freeze([...t,e]):Object.freeze([...t.slice(0,i),e,...t.slice(i+1)])}function Oc(t){const e=_c(t);return vt(e==="SCG_LIMIT_FILE"?{code:e,message:"The annotation file has reached its configured limit. No change was saved.",source:"mcp"}:{code:e,message:Tc(t),source:"mcp"})}function _c(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"SCG_MCP_ERROR"}function Tc(t){return t instanceof Error&&t.message.length>0?t.message:"Scene Glass could not complete the annotation request."}function vt(t){return Object.freeze({...t})}function Rc(t){const e={...t};return delete e.error,e}function zn(t){const e={generation:t.generation,annotations:Object.freeze([...t.annotations]),bindings:Object.freeze([...t.bindings]),loading:t.loading};return t.page!==void 0&&(e.page=t.page),t.revision!==void 0&&(e.revision=t.revision),t.error!==void 0&&(e.error=t.error),Object.freeze(e)}const ii="data-scg-id",xc=["id","data-testid","row-id","col-id"],Nc=6e3;function Pc(t){for(const e of xc){const i=t.getAttribute(e);if(i!==null&&i!==""&&i.length<=64)return`${e}=${i}`}}function Lc(t){let e=1,i=t.previousElementSibling;for(;i!==null;)i.localName===t.localName&&(e+=1),i=i.previousElementSibling;return e}const Gn=new WeakSet;function Mc(t,e){const i=t.getAttribute(ii);return i!==null&&!Gn.has(t)?!1:(i!==e&&t.setAttribute(ii,e),Gn.add(t),!0)}function Dc(t,e){const i=new WeakMap;i.set(t,"");let n=0;for(const s of t.querySelectorAll("*")){if(n>=Nc)return;if(e(s))continue;const r=s.parentElement;if(r===null)continue;const o=i.get(r);if(o===void 0)continue;const a=Pc(s),c=a===void 0?`${s.localName}${Lc(s)}`:`${s.localName}[${a}]`,l=`${o}/${c}`;i.set(s,l),Mc(s,l)&&(n+=1)}}const qe=512,qc=4096,zc=500,Gc=4096,jc=8,ni=64;function Wc(t){const e=Uc(t),i=Vc(t),n=jn(t),s=Wn(t),r=Bc(t),o=Fc(t),a={viewport:e,rect:i,tag:n,classes:s,cssPath:r,selectedText:o},c={viewport:e,rect:i,tag:n,classes:[],cssPath:"",selectedText:""};try{const d=$c(t)??Hc(t);return Vt({...a,...d})}catch{return Vt(c)}}function Uc(t){try{const e=t.ownerDocument.defaultView;return[bt(e?.innerWidth),bt(e?.innerHeight)]}catch{return[0,0]}}function Vc(t){try{const e=t.getBoundingClientRect();return[si(e.x),si(e.y),bt(e.width),bt(e.height)]}catch{return[0,0,0,0]}}function jn(t){try{const e=t.localName.toLowerCase();return/^[a-z][a-z0-9:-]*$/.test(e)?e:"div"}catch{return"div"}}function Wn(t){try{return Array.from(t.classList).filter(e=>ze(e,qe)&&e.trim().length>0).slice(0,ni)}catch{return[]}}function Bc(t){try{const e=[];let i=t;for(let n=0;i!==null&&n<jc;n+=1){const s=jn(i),r=ri(i.id),o=Wn(i);if(e.unshift(`${s}${r.length===0?"":`#${r}`}${o.map(a=>`.${a}`).join("")}`),i===i.ownerDocument.body||i===i.ownerDocument.documentElement)break;i=i.parentElement}return Bn(ri(e.join(" > ")),qc)}catch{return""}}function Fc(t){try{const e=(t.textContent??"").replace(/\s+/g," ").trim();return Bn(Array.from(e).slice(0,zc).join(""),Gc)}catch{return""}}function $c(t){try{let e=t.__vueParentComponent;if(e===void 0)return;let i;const n=[],s=new Set;for(;e!=null&&!s.has(e);){s.add(e);const r=e.type?.__file;if(i===void 0&&typeof r=="string"){const a=Vn(r);a!==void 0&&ze(a,qe)&&(i=a)}const o=Kc(e);o!==void 0&&n.unshift(o),e=e.parent??void 0}return{...i===void 0?{}:{sourceFile:i},...n.length===0?{}:{componentTrail:n.slice(0,ni)}}}catch{return}}function Kc(t){const e=t.type,i=e?.__name??e?.name;if(typeof i=="string"&&ze(i,qe)&&i.trim().length>0)return i;if(typeof e?.__file!="string")return;const n=e.__file.split(/[\\/]/).pop()?.replace(/\.[^.]*$/,"");return n!==void 0&&ze(n,qe)&&n.trim().length>0?n:void 0}function Hc(t){try{const e=Object.getOwnPropertyNames(t).find(o=>o.startsWith("__reactFiber$")||o.startsWith("__reactInternalInstance$"));if(e===void 0)return;let i=t[e],n;const s=[],r=new Set;for(;i!=null&&!r.has(i);){r.add(i);const o=i._debugSource?.fileName;if(n===void 0&&typeof o=="string"){const c=Vn(o);c!==void 0&&ze(c,qe)&&(n=c)}const a=i.type;if(typeof a=="function"){const c=a.displayName??a.name;typeof c=="string"&&ze(c,qe)&&c.trim().length>0&&s.unshift(c)}i=i.return??void 0}return{...n===void 0?{}:{sourceFile:n},...s.length===0?{}:{componentTrail:s.slice(0,ni)}}}catch{return}}function si(t){if(typeof t!="number"||!Number.isFinite(t))return 0;const e=Math.round(t);return Number.isSafeInteger(e)?e:0}function bt(t){const e=si(t);return e<0?0:e}function Un(t){return t<=31||t===127}function ze(t,e){for(let i=0;i<t.length;i+=1)if(Un(t.charCodeAt(i)))return!1;return Fn(t)<=e}function ri(t){let e="";for(const i of t)Un(i.charCodeAt(0))||(e+=i);return e}function Vn(t){const e=ri(t).replace(/\\/g,"/").trim();if(e.length===0)return;const i=e.lastIndexOf("/src/");if(i!==-1)return e.slice(i+1);const n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}function Bn(t,e){let i="",n=0;for(const s of t){const r=Fn(s);if(n+r>e)break;i+=s,n+=r}return i}function Fn(t){return new TextEncoder().encode(t).length}const oi="data-scg-owned",$n="data-scg-selector-overlay",Yc='.scg-ui-overlay, .scg-ui-launcher, .scg-ui-editor, .scg-ui-badges, .scg-ui-work-review-highlights, .scg-ui-styles, .scg-diag-panel, .scg-diag-styles, [data-scg-owned="true"]';function Xc(t,e){if(!ai(t))return Object.freeze({status:"unsupported",reason:"not-element"});if(t.ownerDocument!==e)return tl(t,e);if(fe(t))return;const i=e.documentElement,n=t.getRootNode();if(n!==e){const s=il(n);return s!==void 0?i===null||!i.contains(s)?Object.freeze({status:"unsupported",reason:"unmounted"}):Object.freeze({status:"unsupported",reason:"shadow-child",host:s}):Object.freeze({status:"unsupported",reason:"unmounted"})}return i===null||!i.contains(t)?Object.freeze({status:"unsupported",reason:"unmounted"}):Object.freeze({status:"selected",element:t,rect:t.getBoundingClientRect()})}const Kn=["pointerdown","mousedown","mouseup","touchstart","contextmenu"],Qc="button[disabled], input[disabled], select[disabled], textarea[disabled], optgroup[disabled], option[disabled]";function Zc(t){if(typeof t.closest!="function")return!1;if(t.closest(Qc)!==null)return!0;const e=t.closest("fieldset[disabled]");if(e===null)return!1;const i=typeof e.querySelector=="function"?e.querySelector(":scope > legend"):null;return i===null||typeof i.contains!="function"||!i.contains(t)}function Jc(t){const e=t.document??el();let i=!1,n=!1,s=0,r,o,a=null;const c=[];let l=!1;const d=(v,S)=>{if(c.push(Object.freeze({phase:v,error:S})),!l){l=!0;try{for(let g=0;g<c.length;g+=1){const O=c[g];if(O!==void 0)try{t.onCallbackError(O)}catch{}}}finally{c.length=0,l=!1}}},u=(v,S,g)=>{if(S!==void 0)try{S(g)}catch(O){d(v,O)}},h=v=>{o=v,Hn(r,v),u("selection-change",t.onSelectionChange,v)},f=(v,S)=>{if(e!==void 0)return Xc(e.elementFromPoint(v,S),e)},b=v=>{h(f(v.clientX,v.clientY))},y=v=>{if(!i)return;const S=v.target;S instanceof Element&&fe(S)||(v.preventDefault(),v.stopPropagation())},T=(v,S)=>{S.preventDefault(),S.stopPropagation(),M(),u("select",t.onSelect,v)},E=v=>{const S=s,g=f(v.clientX,v.clientY);if(h(g),!(!i||s!==S)){if(g?.status==="unsupported"){u("unsupported-select",t.onUnsupportedSelect,g);return}g?.status==="selected"&&T(g,v)}},w=v=>{const S=i?f(v.clientX,v.clientY):void 0;a=S?.status==="selected"?S.element:null},R=v=>{const S=a;a=null;const g=s;if(!i||S===null)return;const O=f(v.clientX,v.clientY);O?.status!=="selected"||O.element!==S||!Zc(O.element)||(h(O),!(!i||s!==g)&&T(O,v))},x=()=>{Hn(r,o)},G=()=>{if(e===void 0)return;e.removeEventListener("pointermove",b),e.removeEventListener("pointerdown",w,!0),e.removeEventListener("pointerup",R,!0),e.removeEventListener("click",E,!0);for(const S of Kn)e.removeEventListener(S,y,!0);const v=e.defaultView;v?.removeEventListener("resize",x),v?.removeEventListener("scroll",x,!0)},M=()=>{i&&(i=!1,s+=1,a=null,G(),r?.remove(),r=void 0,o=void 0,u("selection-change",t.onSelectionChange,void 0))};return{get isReviewing(){return i},start(){if(n||i||e===void 0)return;const v=e.body??e.documentElement;if(v===null)return;r=nl(e),v.append(r),s+=1,i=!0,e.addEventListener("pointermove",b,{passive:!0}),e.addEventListener("pointerdown",w,!0),e.addEventListener("pointerup",R,!0),e.addEventListener("click",E,!0);for(const g of Kn)e.addEventListener(g,y,!0);const S=e.defaultView;S?.addEventListener("resize",x),S?.addEventListener("scroll",x,!0)},stop:M,destroy(){n||(n=!0,M())}}}function el(){return typeof globalThis.document>"u"?void 0:globalThis.document}function tl(t,e){const i=t.ownerDocument.defaultView?.frameElement;return!ai(i)||i.ownerDocument!==e||e.documentElement===null||!e.documentElement.contains(i)?Object.freeze({status:"unsupported",reason:"unmounted"}):Object.freeze({status:"unsupported",reason:"iframe-internal",host:i})}function il(t){const e=t.host;return ai(e)?e:void 0}function ai(t){return typeof t=="object"&&t!==null&&t.nodeType===1&&typeof t.getAttribute=="function"}function fe(t){return t.getAttribute(oi)==="true"||t.getAttribute($n)==="true"?!0:typeof t.closest=="function"&&t.closest(Yc)!==null}function nl(t){const e=t.createElement("div");return e.setAttribute(oi,"true"),e.setAttribute($n,"true"),e.setAttribute("aria-hidden","true"),Object.assign(e.style,{display:"none",position:"fixed",pointerEvents:"none",zIndex:"2147483647",boxSizing:"border-box",border:"2px solid #4f8cff",background:"rgba(79, 140, 255, 0.12)"}),e}function Hn(t,e){if(t===void 0||e?.status!=="selected"){t!==void 0&&(t.style.display="none");return}const i=e.element.getBoundingClientRect();if(i.width<=0||i.height<=0){t.style.display="none";return}t.style.display="block",t.style.left=`${i.left}px`,t.style.top=`${i.top}px`,t.style.width=`${i.width}px`,t.style.height=`${i.height}px`}const yt=["test-token","connection","authentication","round-trip"],sl=Object.freeze({"test-token":{code:"SCG_DIAGNOSTIC_TOKEN_FAILED",message:"A diagnostic test token could not be issued.",remediation:"Confirm the local server is running for this project, then try again."},connection:{code:"SCG_DIAGNOSTIC_CONNECTION_FAILED",message:"The diagnostic connection could not be established.",remediation:"Confirm Scene Glass is available on this page, then try again."},authentication:{code:"SCG_DIAGNOSTIC_AUTHENTICATION_FAILED",message:"The diagnostic initialization was not accepted.",remediation:"Reload the page to receive the current project capability, then try again."},"round-trip":{code:"SCG_DIAGNOSTIC_ROUND_TRIP_FAILED",message:"The diagnostic ping did not complete.",remediation:"Confirm the local server is running, then try again."},cleanup:{code:"SCG_DIAGNOSTIC_CLEANUP_FAILED",message:"The diagnostic connection could not be closed.",remediation:"Reload the page before starting another diagnostic."}}),rl=/^SCG_[A-Z0-9_]{1,80}$/;function ol(t){let e=t.projectId,i=t.now,n=t.transport,s=!1,r=!1,o=null,a=null,c=null,l=0,d=null,u="idle",h=null,f={state:"idle",durationMs:0};const b={"test-token":{state:"idle",durationMs:0},connection:{state:"idle",durationMs:0},authentication:{state:"idle",durationMs:0},"round-trip":{state:"idle",durationMs:0}},y=new Set;let T=ci(u,l,b,f,h);const E=()=>{if(T=ci(u,S(),b,f,h),!r)for(const g of y)try{g(T)}catch{}},w=(g,O)=>{const j=g==="cleanup"?f:b[g];j.state=O,j.durationMs=S(),d=O==="running"?g:null,E()},R=()=>{a!==null&&clearInterval(a),a=setInterval(()=>{if(r||d===null)return;const g=d==="cleanup"?f:b[d];g.durationMs=S(),E()},100)},x=()=>{a!==null&&(clearInterval(a),a=null)},G=()=>{l=0,c=Yn(i),d=null,u="running",h=null,f={state:"idle",durationMs:0};for(const g of yt)b[g]={state:"idle",durationMs:0};R(),E()},M=async()=>{const g=n;if(!s||r||g===null)return T;G();let O="",j=null,L=!1;try{if(w("test-token","running"),O=(await g.issueProjectTestToken({projectId:e})).token,O.length===0)throw new Error("missing diagnostic token");w("test-token","passed"),w("connection","running"),j=await g.initialize({projectId:e,token:O}),O="",w("connection","passed"),w("authentication","running"),await g.sendInitializedNotification({connection:j}),w("authentication","passed"),w("round-trip","running"),await g.ping({connection:j}),w("round-trip","passed"),u="passed",E()}catch(U){L=!0;const be=d??"test-token";h=Xn(be,U),w(be,"failed")}finally{if(O="",j===null)w("cleanup","cleaned");else{w("cleanup","running");try{await g.deleteClose({connection:j}),w("cleanup","cleaned")}catch(U){L=!0,h=Xn("cleanup",U),w("cleanup","failed")}}j=null,d=null,u=L?"failed":"cleaned",x(),E()}return T};return{open(){r||(s=!0)},run(){if(o!==null)return o;const g=M();return o=g,g.then(()=>{o===g&&(o=null)},()=>{o===g&&(o=null)}),g},subscribe(g){if(r)return()=>{};y.add(g);try{g(T)}catch{}let O=!0;return()=>{O&&(O=!1,y.delete(g))}},destroy(){if(!r){r=!0,s=!1,x(),y.clear(),n=null,o=null,e="",i=void 0,c=null,d=null,h=null,f={state:"cleaned",durationMs:0};for(const g of yt)b[g]={state:"cleaned",durationMs:0};T=ci("cleaned",0,b,f,null)}}};function S(){if(c===null)return l;const g=Math.max(0,Math.round(Yn(i)-c));return l=Math.max(l,g),l}}function ci(t,e,i,n,s){return Object.freeze({state:t,durationMs:e,steps:Object.freeze({"test-token":Ye(i["test-token"]),connection:Ye(i.connection),authentication:Ye(i.authentication),"round-trip":Ye(i["round-trip"])}),cleanup:Ye(n),failure:s===null?null:Object.freeze({...s})})}function Ye(t){return Object.freeze({state:t.state,durationMs:t.durationMs})}function Yn(t){try{const e=t===void 0?performance.now():t();return Number.isFinite(e)?e:0}catch{return 0}}function Xn(t,e){const i=sl[t];return Object.freeze({step:t,code:al(e,i.code),message:i.message,remediation:i.remediation})}function al(t,e){if(typeof t!="object"||t===null||!("code"in t))return e;const i=t.code;return typeof i=="string"&&rl.test(i)?i:e}function cl(t){const e=gl(t);if(e===null)return fl();let i=t.container??null,n=t.controller;const s=e.createElement("style");s.className="scg-diag-styles",s.textContent=pl;const r=e.createElement("aside");r.className="scg-diag-panel",r.setAttribute(oi,"true"),r.setAttribute("aria-label","Scene Glass 진단");const o=e.createElement("h2");o.className="scg-diag-heading",o.textContent="Scene Glass 진단";const a=e.createElement("p");a.className="scg-diag-description",a.textContent="민감한 값을 표시하지 않고 짧은 진단을 실행합니다.";const c=e.createElement("button");c.className="scg-diag-run",c.type="button",c.textContent="진단 실행";const l=e.createElement("output");l.className="scg-diag-run-state",l.setAttribute("aria-live","polite"),l.setAttribute("aria-atomic","true"),l.setAttribute("role","status");const d=e.createElement("ol");d.className="scg-diag-steps";const u={};for(const L of yt){const U=Qn(e,ll(L));u[L]=U,d.append(U.row)}const h=e.createElement("h3");h.className="scg-diag-cleanup-heading",h.textContent="정리";const f=Qn(e,"DELETE 종료");f.row.classList.add("scg-diag-cleanup");const b=e.createElement("ul");b.className="scg-diag-cleanup-list",b.append(f.row);const y=e.createElement("section");y.className="scg-diag-error",y.setAttribute("role","alert"),y.hidden=!0;const T=e.createElement("strong");T.className="scg-diag-error-code";const E=e.createElement("p");E.className="scg-diag-error-message";const w=e.createElement("p");w.className="scg-diag-remediation",y.append(T,E,w),r.append(o,a,c,l,d,h,b,y);let R=!1,x=!1,G=!1,M,v=null;const S=L=>{if(!R){l.textContent=`${ul(L.state)} ${Jn(L.durationMs)}`,l.dataset.state=L.state,c.disabled=L.state!=="idle";for(const U of yt)Zn(u[U],L.steps[U]);if(Zn(f,L.cleanup),L.failure===null){y.hidden=!0,T.textContent="",E.textContent="",w.textContent="";return}y.hidden=!1,T.textContent=L.failure.code,E.textContent=L.failure.message,w.textContent=L.failure.remediation}},g=()=>{const L=n;L!==null&&L.run().catch(()=>{})};c.addEventListener("click",g);const O=()=>{const L=hl(e,i),U=n;return R||x||L===null||U===null?!1:(L.append(s,r),v=U.subscribe(S),x=!0,e.removeEventListener("DOMContentLoaded",j),M!==void 0&&(clearTimeout(M),M=void 0),!0)},j=()=>{G&&O()};return{open(){if(R||x)return;const L=n;L!==null&&(L.open(),G=!0,O()||(e.addEventListener("DOMContentLoaded",j,{once:!0}),e.readyState==="interactive"&&M===void 0&&(M=setTimeout(j,50))))},destroy(){R||(R=!0,c.removeEventListener("click",g),v?.(),v=null,n=null,i=null,G=!1,e.removeEventListener("DOMContentLoaded",j),M!==void 0&&(clearTimeout(M),M=void 0),T.textContent="",E.textContent="",w.textContent="",l.textContent="",r.replaceChildren(),s.textContent="",s.remove(),r.remove())}}}function Qn(t,e){const i=t.createElement("li");i.className="scg-diag-step";const n=t.createElement("span");n.className="scg-diag-step-label",n.textContent=e;const s=t.createElement("output");s.className="scg-diag-step-state",s.setAttribute("aria-live","polite");const r=t.createElement("span");return r.className="scg-diag-step-duration",i.append(n,s,r),{row:i,state:s,duration:r}}function Zn(t,e){t.row.dataset.state=e.state,t.state.textContent=dl(e.state),t.duration.textContent=Jn(e.durationMs)}function ll(t){switch(t){case"test-token":return"토큰 테스트";case"connection":return"연결";case"authentication":return"인증";case"round-trip":return"왕복 통신"}}function dl(t){switch(t){case"idle":return"시작되지 않음";case"running":return"실행 중";case"passed":return"통과";case"failed":return"실패";case"cleaned":return"정리됨"}}function ul(t){switch(t){case"idle":return"시작되지 않음.";case"running":return"실행 중.";case"passed":return"검사를 통과했습니다. 정리 중입니다.";case"failed":return"진단에 실패했습니다.";case"cleaned":return"진단 정리가 완료되었습니다."}}function Jn(t){return`${Math.max(0,Math.round(t))}밀리초`}function hl(t,e){if(e!==null)return e;const i=t.defaultView,n=i===null?[]:[...t.querySelectorAll("[data-scg-root]")].filter(r=>r instanceof i.HTMLElement),[s]=n;return s!==void 0&&n.length===1?s:n.length>1||t.readyState==="complete"?t.body:null}function gl(t){return t.document!==void 0?t.document:t.container!==void 0?t.container.ownerDocument:typeof globalThis.document>"u"?null:globalThis.document}function fl(){return{open(){},destroy(){}}}const pl=`
3
+ .scg-diag-panel {
4
+ background: #fff;
5
+ border: 1px solid #475569;
6
+ color: #0f172a;
7
+ font: 14px/1.4 system-ui, sans-serif;
8
+ margin: 1rem;
9
+ max-width: 32rem;
10
+ padding: 1rem;
11
+ }
12
+ .scg-diag-heading,
13
+ .scg-diag-cleanup-heading { margin: 0 0 .5rem; }
14
+ .scg-diag-description { margin: 0 0 .75rem; }
15
+ .scg-diag-run { margin: 0 .75rem .75rem 0; }
16
+ .scg-diag-steps { margin: .75rem 0; padding-left: 1.25rem; }
17
+ .scg-diag-cleanup-list { list-style: none; margin: .5rem 0; padding: 0; }
18
+ .scg-diag-step { display: grid; gap: .5rem; grid-template-columns: 1fr auto auto; margin: .25rem 0; }
19
+ .scg-diag-step-state { font-weight: 600; }
20
+ .scg-diag-step-duration { color: #475569; font-variant-numeric: tabular-nums; min-width: 4rem; text-align: right; }
21
+ .scg-diag-error { border-left: 3px solid #b91c1c; margin-top: .75rem; padding-left: .75rem; }
22
+ .scg-diag-error-message,
23
+ .scg-diag-remediation { margin: .25rem 0; }
24
+ `,ml={canonicalIdentityBytes:D.canonicalIdentityBytes,routeBytes:D.routeBytes};async function wl(t,e=ml){const i=bl(t.override??vl(t),e.canonicalIdentityBytes,"canonicalIdentity");return es(i,e.routeBytes,"route"),Object.freeze({policyVersion:1,canonicalIdentity:i,route:i,pageId:await yl(i)})}function vl(t){if(t.pathname===void 0)throw ke("pathname is required when no identity override is supplied");const e=t.policy?.includeQuery===!0,i=t.policy?.includeHash===!0;return`${t.pathname}${e?t.query??"":""}${i?t.hash??"":""}`}function bl(t,e,i){El(t,i);const n=t.normalize("NFC");return es(n,e,i),n}function es(t,e,i){if(t.length===0)throw ke(`${i} must not be empty`);if(Sl(t))throw ke(`${i} must not contain control characters`);if(new TextEncoder().encode(t).byteLength>e)throw ke(`${i} exceeds its UTF-8 byte limit`)}async function yl(t){if(!globalThis.crypto?.subtle)throw ke("Web Crypto SHA-256 is unavailable");const e=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return`p_${Array.from(new Uint8Array(e),n=>n.toString(16).padStart(2,"0")).join("")}`}function El(t,e){for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);if(n>=55296&&n<=56319){const s=t.charCodeAt(i+1);if(i+1>=t.length||s<56320||s>57343)throw ke(`${e} contains an unpaired surrogate`);i+=1}else if(n>=56320&&n<=57343)throw ke(`${e} contains an unpaired surrogate`)}}function Sl(t){for(let e=0;e<t.length;e+=1){const i=t.charCodeAt(e);if(i<=31||i>=127&&i<=159)return!0}return!1}function ke(t){return new N("SCG_SCALAR_INVALID",t)}async function kl(t={}){const e=t.location??globalThis.location,i={pathname:e.pathname,query:e.search,hash:e.hash,...t.override===void 0?{}:{override:t.override},...t.policy===void 0?{}:{policy:t.policy}};return wl(i,t.limits)}class Q extends Error{cleanupErrors=Object.freeze([]);constructor(e){super(e),this.name="McpClientError",Object.setPrototypeOf(this,new.target.prototype)}}class Et extends Q{status;constructor(e){super(`MCP request failed with status ${e}`),this.name="McpHttpError",this.status=e,Object.setPrototypeOf(this,new.target.prototype)}}class _ extends Q{constructor(e){super(e),this.name="McpProtocolError",Object.setPrototypeOf(this,new.target.prototype)}}class li extends _{byteLimit;constructor(e){super("MCP response exceeds the byte limit"),this.name="McpResponseTooLargeError",this.byteLimit=e,Object.setPrototypeOf(this,new.target.prototype)}}class St extends Q{code;rpcCode;data;constructor(e,i,n){super(e),this.name="McpRpcDomainError",this.code=e,this.rpcCode=i,this.data=n,Object.setPrototypeOf(this,new.target.prototype)}}const F=Object.freeze({providerRead:"work.provider.read",providerSet:"work.provider.set",providerWarningAcknowledge:"work.provider.warning.acknowledge",providerCapabilitiesRead:"work.provider.capabilities.read",providerSessionReset:"work.provider.session.reset",preview:"work.preview",submit:"work.submit",read:"work.read",list:"work.list",watch:"work.watch",cancel:"work.cancel",retry:"work.retry",reviewAcknowledge:"work.review.acknowledge",diffRead:"work.diff.read",diffCompare:"work.diff.compare"}),Cl=9e5,ts=32,se=32,di=32,Il="v1",Al=Object.freeze(["pre-checkpoint-unavailable","post-checkpoint-unavailable","scan-file-limit","scan-byte-limit","file-content-limit","history-budget-limit","content-identity-unavailable","content-identity-mismatch","render-byte-limit","diff-complexity-limit"]),Ol=Object.freeze(["complete","truncated"]),_l=Object.freeze(["comparison-column-truncated","comparison-render-byte-limit"]),Tl=Object.freeze(["shared-file","task-a-only","task-b-only"]),is=Object.freeze(["added","modified","deleted","modeOnly","binary","metadataOnly"]),ns=Object.freeze(["scannedInputBytes","scannedBytes","scannedLines","projectedDisplayBytes","projectedMinimumSerializedBytes","currentLineBytes","longestLineBytes","materializedLines","materializedOperations","materializedHunks","retainedDisplayBytes","projectedStructureBytes","rejectedProjectedStructureBytes"]),Rl=Object.freeze(["patch","reason","renderedBytes","summary","resources"]),Xe=Object.freeze(["request","result","events"]),xl=Object.freeze(["cursor","limit","nextCursor"]),ui=Object.freeze(["schemaVersion","provider","providerGeneration","page","pageRevision","entries","previewDigest"]),Nl=Object.freeze(["annotationId","digest","domOrder"]),Qe=Object.freeze({"work.preview":ui,"work.submit":Object.freeze(["duplicate","work"]),"work.read":Xe,"work.list":Object.freeze(["items","pagination"]),"work.watch":Object.freeze(["requestId","events","heartbeat","result"]),"work.cancel":Xe,"work.retry":Xe,"work.review.acknowledge":Xe,"work.diff.read":Object.freeze(["patch","reason","renderedBytes","summary","resources","pagination"]),"work.diff.compare":Object.freeze(["state","reason","renderedBytes","taskA","taskB","paths","pagination"])});class B extends _{code;constructor(e,i){super(i),this.name="WorkClientProtocolError",this.code=e,Object.setPrototypeOf(this,new.target.prototype)}}function C(t){return new B("SCG_WORK_CLIENT_PROTOCOL",t)}function Ge(t){return new B("SCG_WORK_CLIENT_INPUT",t)}const Pl=new Set(["SCG_WORK_LIMIT_EXCEEDED","SCG_WORK_REQUEST_INVALID","SCG_WORK_PROVIDER_INVALID","SCG_WORK_EXECUTION_SETTINGS_INVALID","SCG_WORK_CAPABILITIES_UNAVAILABLE","SCG_WORK_HISTORY_INVALID","SCG_WORK_DIFF_INVALID"]);function K(t,e){try{return e()}catch(i){if(i instanceof B)throw i;const n=i instanceof Error?Reflect.get(i,"code"):void 0;throw typeof n=="string"&&Pl.has(n)?new B(n,t):C(t)}}async function ss(t,e){try{return await e()}catch(i){throw i instanceof li?new B("SCG_WORK_LIMIT_EXCEEDED",`${t} exceeded the bounded response byte ceiling`):i}}function kt(t){return K("work provider tool result is invalid",()=>Vo(t))}function Ll(t,e){const i=kt(t);if(i.selection.provider==="none"||i.session!==void 0&&i.session.state!=="new-session-pending"||i.selection.generation<=e)throw C("work provider session reset result is not a committed rotation");return i}function Ml(t){return K("work provider capabilities are invalid",()=>Zo(t))}const Dl=22e5;async function ql(t,e){const i=K("capability provider is invalid",()=>Me(e)),n=F.providerCapabilitiesRead,s=Ml(await ss(n,()=>t(n,{provider:i},Dl)));if(s.provider!==i)throw C("capability provider does not match the request");return s}function rs(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw C(`${e} must be an object`);const i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw C(`${e} must be a plain object`);return t}function os(t,e,i){const n=new Set(e);for(const s of Reflect.ownKeys(t))if(typeof s!="string"||!n.has(s))throw C(`${i} contains an unknown field`);for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s))throw C(`${i} is missing ${s}`);return t}function ee(t,e,i){return os(rs(t,i),e,i)}function I(t,e){return Reflect.get(t,e)}function Ct(t,e,i){for(const n of e)if(t===n)return n;throw C(`${i} is invalid`)}function as(t,e){if(typeof t!="boolean")throw C(`${e} must be a boolean`);return t}function zl(t,e){if(typeof t!="string")throw C(`${e} must be a string`);return t}function re(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||Object.is(t,-0))throw C(`${e} must be a non-negative safe integer`);return t}function hi(t,e){return t===null?null:e(t)}function It(t,e,i){if(!Array.isArray(t))throw C(`${e} must be an array`);for(let n=0;n<t.length;n+=1)if(!Object.prototype.hasOwnProperty.call(t,n))throw C(`${e} must not be sparse`);if(t.length>i)throw C(`${e} exceeds its bounded item ceiling`);return Object.freeze([...t])}function cs(t,e,i){const n=ee(t,e,i);return Object.freeze(Object.fromEntries(e.map(s=>[s,re(I(n,s),`${i} ${s}`)])))}function At(t,e){if(!t)throw Ge(e)}function oe(t,e){if(typeof t!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(t))throw Ge(`${e} must be a lowercase UUID v4`);return t}function je(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw Ge(`${e} must be a non-negative safe integer`);return t}function ls(t,e){return t.request.requestId===e&&t.result.requestId===e&&t.result.state==="completed"&&t.result.reviewState==="acknowledged"}function gi(t,e){const i=ee(t,[...xl],e),n=re(I(i,"limit"),`${e} limit`);if(n<1||n>se)throw C(`${e} limit is outside its bounded range`);return Object.freeze({cursor:re(I(i,"cursor"),`${e} cursor`),limit:n,nextCursor:hi(I(i,"nextCursor"),s=>re(s,`${e} nextCursor`))})}function Gl(t){const e=rs(t,"work preview");if(os(e,Object.hasOwn(e,"executionSettings")?[...ui,"executionSettings"]:[...ui],"work preview"),I(e,"schemaVersion")!==1)throw C("work preview schemaVersion must be 1");const i=It(I(e,"entries"),"work preview entries",se*32).map(Vl);if(i.length===0)throw C("work preview must contain at least one entry");return Object.freeze({schemaVersion:1,provider:K("work preview provider is invalid",()=>Me(I(e,"provider"))),providerGeneration:re(I(e,"providerGeneration"),"work preview providerGeneration"),page:K("work preview page is invalid",()=>$e(I(e,"page"))),pageRevision:re(I(e,"pageRevision"),"work preview pageRevision"),entries:Object.freeze(i),previewDigest:K("work preview previewDigest is invalid",()=>Re(I(e,"previewDigest"))),...K("work preview execution settings are invalid",()=>ut(e))})}function We(t){const e=ee(t,[...Xe],"work record"),i=K("work record request is invalid",()=>Ca(I(e,"request"))),n=K("work record result is invalid",()=>Sn(I(e,"result")));if(n.requestId!==i.requestId)throw C("work record result does not belong to its request");const s=ds(I(e,"events"),"work record events",i.requestId);return Object.freeze({request:i,result:n,events:s})}function jl(t){const e=ee(t,[...Qe["work.submit"]],"work submit");return Object.freeze({duplicate:as(I(e,"duplicate"),"work submit duplicate"),work:We(I(e,"work"))})}function Wl(t){const e=ee(t,[...Qe["work.list"]],"work list"),i=It(I(e,"items"),"work list items",se).map(We);return Object.freeze({items:Object.freeze(i),pagination:gi(I(e,"pagination"),"work list pagination")})}function Ul(t,e){const i=ee(t,[...Qe["work.watch"]],"work watch"),n=K("work watch requestId is invalid",()=>te(I(i,"requestId"),"work watch requestId"));if(n!==e)throw C("work watch response does not belong to the watched request");const s=K("work watch result is invalid",()=>Sn(I(i,"result")));if(s.requestId!==e)throw C("work watch result does not belong to the watched request");return Object.freeze({requestId:n,events:ds(I(i,"events"),"work watch events",e),heartbeat:as(I(i,"heartbeat"),"work watch heartbeat"),result:s})}function Vl(t){const e=ee(t,[...Nl],"work preview entry");return Object.freeze({annotationId:K("work preview entry annotationId is invalid",()=>te(I(e,"annotationId"),"work preview entry annotationId")),digest:K("work preview entry digest is invalid",()=>Re(I(e,"digest"))),domOrder:re(I(e,"domOrder"),"work preview entry domOrder")})}function ds(t,e,i){const n=It(t,e,ts).map(s=>K(`${e} contains an invalid transition`,()=>Ia(s)));for(const s of n)if(s.requestId!==i)throw C(`${e} contains a transition for another request`);return Object.freeze(n)}function Bl(t){const e=ee(t,[...Qe["work.diff.read"]],"work diff read");return Object.freeze({...hs(e,"work diff read"),pagination:gi(I(e,"pagination"),"work diff read pagination")})}function Fl(t){const e=ee(t,[...Qe["work.diff.compare"]],"work diff compare"),i=us(I(e,"taskA"),"work diff compare taskA"),n=us(I(e,"taskB"),"work diff compare taskB");if(i.patch.requestId===n.patch.requestId)throw C("work diff comparison requires two distinct tasks");return Object.freeze({state:Ct(I(e,"state"),[...Ol],"work diff compare state"),reason:hi(I(e,"reason"),s=>Ct(s,[..._l],"work diff compare reason")),renderedBytes:re(I(e,"renderedBytes"),"work diff compare renderedBytes"),taskA:i,taskB:n,paths:Object.freeze(It(I(e,"paths"),"work diff compare paths",se).map($l)),pagination:gi(I(e,"pagination"),"work diff compare pagination")})}function us(t,e){return Object.freeze(hs(ee(t,[...Rl],e),e))}function hs(t,e){return{patch:K(`${e} patch is invalid`,()=>la(I(t,"patch"))),reason:hi(I(t,"reason"),i=>Ct(i,[...Al],`${e} reason`)),renderedBytes:re(I(t,"renderedBytes"),`${e} renderedBytes`),summary:cs(I(t,"summary"),[...is],`${e} summary`),resources:cs(I(t,"resources"),[...ns],`${e} resources`)}}function $l(t){const e=ee(t,["path","relationship"],"work diff compared path");return Object.freeze({path:zl(I(e,"path"),"work diff compared path"),relationship:Ct(I(e,"relationship"),[...Tl],"work diff compared relationship")})}function fi(t){const e=async(n,s,r)=>r(await ss(n,()=>t(n,s,Cl)));return Object.freeze({readProvider:async()=>e(F.providerRead,{},kt),readCapabilities:n=>ql(t,n),setProvider:async n=>e(F.providerSet,{provider:gs(n.provider),expectedGeneration:je(n.expectedGeneration,"expectedGeneration"),...ut(n)},kt),acknowledgeWarning:async n=>{if(typeof n.remember!="boolean")throw Ge("remember is invalid");return e(F.providerWarningAcknowledge,{provider:Kl(n.provider),contractVersion:Il,remember:n.remember},kt)},resetProviderSession:async n=>{const s=je(n.expectedGeneration,"expectedGeneration");return e(F.providerSessionReset,{expectedGeneration:s},r=>Ll(r,s))},preview:async n=>e(F.preview,{page:fs(n.page)},Gl),submit:async n=>e(F.submit,{requestId:oe(n.requestId,"requestId"),page:fs(n.page),pageRevision:je(n.pageRevision,"pageRevision"),previewDigest:Hl(n.previewDigest)},jl),read:async n=>e(F.read,{requestId:oe(n.requestId,"requestId")},We),list:async n=>e(F.list,pi(n),Wl),watch:async n=>{const s=oe(n.requestId,"requestId");return e(F.watch,{requestId:s,afterEventSequence:je(n.afterEventSequence,"afterEventSequence")},r=>Ul(r,s))},cancel:async n=>e(F.cancel,{requestId:oe(n.requestId,"requestId")},We),retry:async n=>e(F.retry,{requestId:oe(n.requestId,"requestId")},We),acknowledgeReview:async n=>e(F.reviewAcknowledge,{requestId:oe(n.requestId,"requestId")},We),readDiff:async n=>e(F.diffRead,{requestId:oe(n.requestId,"requestId"),...pi(n)},Bl),compareDiff:async n=>{const s=oe(n.requestIdA,"requestIdA"),r=oe(n.requestIdB,"requestIdB");return At(s!==r,"a comparison requires two distinct requests"),e(F.diffCompare,{requestIdA:s,requestIdB:r,...pi(n)},Fl)}})}function pi(t){const e=t?.cursor===void 0?0:je(t.cursor,"cursor"),i=t?.limit===void 0?di:je(t.limit,"limit");return At(i>=1&&i<=se,"limit is outside its range"),{cursor:e,limit:i}}function gs(t){for(const e of Zt)if(t===e)return e;throw Ge("provider is invalid")}function Kl(t){const e=gs(t);if(e==="none")throw Ge("provider must not be none");return e}function fs(t){return At(typeof t=="object"&&t!==null&&!Array.isArray(t),"page identity is invalid"),t}function Hl(t){return At(typeof t=="string"&&/^sha256:[0-9a-f]{64}$/u.test(t),"previewDigest is invalid"),t}const Ot=1048576,Yl=1e4,mi="x-scene-glass-diagnostic-alias",wi=/^scene-glass-vite-diagnostic-v1-[1-9][0-9]*$/u,Xl="/@scene-glass/mcp",Ze="2025-11-25",Je=Object.freeze({listAnnotations:"annotations.list",createAnnotation:"annotations.create",updateAnnotation:"annotations.update",deleteAnnotation:"annotations.delete",exportPrompt:"prompt.export"});class ps{endpoint;diagnosticEndpoint;fetch;now;crypto;clientInfo;diagnosticProxyAlias;token;sessionId=null;sessionEpoch;sessionInitializationTask=null;fullInitializationTask=null;initializedNotificationTask=null;closeTask=null;workClient=null;constructor(e){if(this.endpoint=e.endpoint,this.diagnosticEndpoint=e.diagnosticEndpoint,e.diagnosticProxyAlias!==void 0&&(e.token!==void 0||!wi.test(e.diagnosticProxyAlias)||!bs(e.endpoint)))throw new TypeError("diagnostic proxy authority is invalid");this.diagnosticProxyAlias=e.diagnosticProxyAlias??null,this.token=e.token??"",this.fetch=e.fetch??Ql,this.now=e.now??Date.now,this.crypto=e.crypto??Zl(),this.clientInfo=e.clientInfo??{name:"scene-glass-browser",version:"0.1.0"},this.sessionEpoch=this.createSessionEpoch(e.token??"")}initialize(){try{return this.startInitialization(!0)}catch(e){return Promise.reject(e)}}initializeSession(){try{return this.startInitialization(!1)}catch(e){return Promise.reject(e)}}sendInitializedNotification(){const e=this.sessionEpoch;return this.startInitializedNotification(e,this.requireSessionId(e))}async ping(){const e=this.currentSessionContext(),i=await this.request("ping",{},e);return this.assertCurrentSession(e),i.result}async callTool(e,i,n={}){const s=this.currentSessionContext(),r=await this.request("tools/call",{name:e,arguments:i},s,n.maxResponseBytes??Ot);return this.assertCurrentSession(s),ad(r.result)}async listAnnotations(e){const i=await this.callTool(Je.listAnnotations,{page:e});return cd(i,e)}async createAnnotation(e){const i=await this.callTool(Je.createAnnotation,e);return bi(i,"create",void 0)}async updateAnnotation(e){const i=await this.callTool(Je.updateAnnotation,e);return bi(i,"update",e.annotationId)}async deleteAnnotation(e){const i=await this.callTool(Je.deleteAnnotation,e);return bi(i,"delete",e.annotationId)}async exportPrompt(e){const i=await this.callTool(Je.exportPrompt,e);return dd(i,e)}get work(){return this.workClient??=fi((e,i,n)=>this.callTool(e,i,{maxResponseBytes:n})),this.workClient}issueDiagnosticRun(){return this.issueDiagnosticRunFor(this.sessionEpoch)}getSessionId(){return this.isCurrentEpoch(this.sessionEpoch)?this.sessionId:null}async withDiagnosticRun(e){const i=this.sessionEpoch,n=await this.issueDiagnosticRunFor(i);this.assertCurrentEpoch(i);try{const s=await e(n);return this.assertCurrentEpoch(i),s}catch(s){throw this.assertCurrentEpoch(i),s}}close(){if(this.closeTask!==null)return this.closeTask;const e=et();this.closeTask=e.promise;const i=this.sessionEpoch,n=this.fullInitializationTask??this.sessionInitializationTask,s=n===null&&this.initializedNotificationTask?.epoch===i?this.initializedNotificationTask.task:null,r=this.sessionCleanups(i);return this.invalidateSession(),this.token=null,Promise.resolve().then(()=>this.closeSessionAndInitialization(r,n,s)).then(e.resolve,e.reject),e.promise}dispose(){this.invalidateSession(),this.token=null}startInitialization(e){const i=this.sessionInitializationTask;if(i!==null)return e?this.startFullInitialization(i):i;const n=this.requireCredential(),s=et(),r=s.promise;this.sessionInitializationTask=r;let o=null;try{const a=this.beginSessionEpoch(n);o=a,Promise.resolve().then(()=>this.initializeSessionForEpoch(a)).then(s.resolve,s.reject)}catch(a){s.reject(a)}return r.then(()=>{this.sessionInitializationTask===r&&this.fullInitializationTask===null&&(this.sessionInitializationTask=null)},()=>{this.sessionInitializationTask===r&&this.fullInitializationTask===null&&(this.sessionInitializationTask=null)}),!e||o===null?r:this.startFullInitialization(r)}startFullInitialization(e){if(this.fullInitializationTask!==null)return this.fullInitializationTask;const i=this.sessionEpoch,n=et(),s=n.promise;return this.fullInitializationTask=s,Promise.resolve().then(()=>this.initializeFullyForEpoch(i,e)).then(n.resolve,n.reject),s.then(()=>{this.fullInitializationTask===s&&(this.fullInitializationTask=null,this.sessionInitializationTask===e&&(this.sessionInitializationTask=null))},()=>{this.fullInitializationTask===s&&(this.fullInitializationTask=null,this.sessionInitializationTask===e&&(this.sessionInitializationTask=null))}),s}async initializeSessionForEpoch(e){try{for(const n of e.pendingCleanups)await this.closeSessionCleanup(n),this.assertCurrentEpoch(e);const i=await this.initializeSessionFor(e);return this.assertCurrentEpoch(e),i}catch(i){try{await this.cleanupFailedInitialization(e)}catch(n){_t(i,n)}throw i}}async initializeFullyForEpoch(e,i){const n=await i;try{return this.assertCurrentEpoch(e),await this.startInitializedNotification(e,this.requireSessionId(e)),this.assertCurrentEpoch(e),n}catch(s){try{await this.cleanupFailedInitialization(e)}catch(r){_t(s,r)}throw s}}async issueDiagnosticRunFor(e){this.assertCurrentEpoch(e);const i=this.requireCredential(),n=await this.fetch(this.diagnosticEndpoint,{method:"POST",mode:"cors",credentials:"omit",cache:"no-store",signal:e.controller.signal,headers:{accept:"application/json",...i===""?{}:{authorization:`Bearer ${i}`},...this.diagnosticProxyAlias===null?{}:{[mi]:this.diagnosticProxyAlias},"content-type":"application/json"},body:JSON.stringify({schemaVersion:1})});this.isCurrentEpoch(e)||await pe(n,tt()),this.assertCurrentEpoch(e),n.status!==201&&await pe(n,new Et(n.status)),gd(n.headers.get("cache-control"))||await pe(n,new _("diagnostic response must disable caching"));const s=await ms(n,e.controller.signal);if(this.assertCurrentEpoch(e),!fd(s,this.now()))throw new _("diagnostic response is invalid");if(!vd(s.endpoint,this.endpoint)||!wd(s.token,this.endpoint))throw new _("diagnostic endpoint is invalid");return Object.freeze({runId:s.runId,token:s.token,expiresAt:s.expiresAt,endpoint:s.endpoint})}async initializeSessionFor(e){const i=await this.request("initialize",{protocolVersion:Ze,capabilities:{},clientInfo:this.clientInfo},{epoch:e,sessionId:null});this.assertCurrentEpoch(e);const n=od(i.result),s=hd(i.receivedSessionId);return this.assertCurrentEpoch(e),e.provisionalSessionId=s,this.sessionId=s,n}startInitializedNotification(e,i){const n=this.initializedNotificationTask;if(n!==null&&n.epoch===e)return n.task;const s=et(),r=s.promise;return this.initializedNotificationTask=Object.freeze({epoch:e,task:r}),Promise.resolve().then(()=>this.sendInitializedNotificationFor(e,i)).then(s.resolve,s.reject),r.then(()=>{this.initializedNotificationTask?.task===r&&(this.initializedNotificationTask=null)},()=>{this.initializedNotificationTask?.task===r&&(this.initializedNotificationTask=null)}),r}async sendInitializedNotificationFor(e,i){const n=await this.notify("notifications/initialized",{},{epoch:e,sessionId:i});this.assertCurrentSession({epoch:e,sessionId:i}),n.status!==202&&n.status!==204&&await pe(n,new _("MCP initialized notification was not acknowledged"));const s=await ws(n,e.controller.signal,!0);if(this.assertCurrentSession({epoch:e,sessionId:i}),s.trim().length!==0)throw new _("MCP initialized notification acknowledgement must be empty")}async request(e,i,n,s=Ot){const r=this.createRequestId(),o=await this.post({jsonrpc:"2.0",id:r,method:e,params:i},n);this.assertCurrentSession(n);const a=await ms(o,n.epoch.controller.signal,s);return this.assertCurrentSession(n),Object.freeze({result:nd(a,r),receivedSessionId:o.headers.get("mcp-session-id")})}notify(e,i,n){return this.post({jsonrpc:"2.0",method:e,params:i},n)}async post(e,i){this.assertCurrentSession(i);const n=this.requireCredential(),s={accept:"application/json",...n===""?{}:{authorization:`Bearer ${n}`},...this.diagnosticProxyAlias===null?{}:{[mi]:this.diagnosticProxyAlias},"content-type":"application/json","mcp-protocol-version":Ze};i.sessionId!==null&&(s["mcp-session-id"]=i.sessionId);const r=await this.fetch(this.endpoint,{method:"POST",mode:"cors",credentials:"omit",cache:"no-store",signal:i.epoch.controller.signal,headers:s,body:JSON.stringify(e)});return this.recordProvisionalSession(i,r),this.isCurrentSession(i)||await pe(r,tt()),this.assertCurrentSession(i),(r.status<200||r.status>=300)&&await pe(r,new Et(r.status)),r}async cleanupFailedInitialization(e){const i=this.sessionCleanupFor(e);this.sessionEpoch===e&&this.invalidateSession(),i!==null&&await this.closeSessionCleanup(i)}async closeSessionAndInitialization(e,i,n){const s=[],r=new Set,o=a=>{!r.has(a)&&!s.some(c=>yi(c,a))&&(r.add(a),s.push(a))};if(i!==null)try{await Ue(()=>i)}catch(a){vs(a)||o(a)}if(n!==null)try{await Ue(()=>n)}catch(a){vs(a)||o(a)}for(const a of e)if(!a.completed)try{await this.closeSessionCleanup(a)}catch(c){o(c)}if(s.length===1)throw s[0];if(s.length>1)throw new AggregateError(s,"MCP client cleanup failed")}async closeSession(e,i){const n=new AbortController,s=await Ue(()=>this.fetch(this.endpoint,{method:"DELETE",mode:"cors",credentials:"omit",cache:"no-store",signal:n.signal,headers:{accept:"application/json",...i===""?{}:{authorization:`Bearer ${i}`},...this.diagnosticProxyAlias===null?{}:{[mi]:this.diagnosticProxyAlias},"mcp-protocol-version":Ze,"mcp-session-id":e}}),{onLateFulfilled:r=>ed(()=>vi(r)),onTimeout:r=>n.abort(r)});Rt(n.signal),(s.status<200||s.status>=300)&&await pe(s,new Et(s.status)),await vi(s),Rt(n.signal)}beginSessionEpoch(e){const i=this.sessionEpoch,n=this.createSessionEpoch(e,this.sessionCleanups(i));return this.sessionId=null,this.sessionEpoch=n,this.abortEpoch(i),n}invalidateSession(){const e=this.sessionEpoch,i=this.sessionCleanups(e);return this.sessionId=null,this.sessionEpoch=this.createSessionEpoch(e.credential,i),this.abortEpoch(e),e}createSessionEpoch(e,i=[]){return{controller:new AbortController,credential:e,pendingCleanups:i,provisionalSessionId:null,sessionCleanup:null}}createSessionCleanup(e,i){return{credential:i,sessionId:e,task:null,completed:!1}}sessionCleanupFor(e){if(e.sessionCleanup!==null)return e.sessionCleanup;const i=e.provisionalSessionId??(this.sessionEpoch===e?this.sessionId:null);if(i===null)return null;const n=this.createSessionCleanup(i,e.credential);return e.sessionCleanup=n,n}sessionCleanups(e){const i=e.pendingCleanups.filter(s=>!s.completed),n=this.sessionCleanupFor(e);return Object.freeze(n===null||i.includes(n)?i:[...i,n])}closeSessionCleanup(e){if(e.task!==null)return e.task;const i=et();return e.task=i.promise,Promise.resolve().then(()=>this.closeSession(e.sessionId,e.credential)).then(()=>{e.completed=!0,i.resolve()},i.reject),i.promise}abortEpoch(e){e.controller.signal.aborted||e.controller.abort(tt())}currentSessionContext(){const e=this.sessionEpoch;return Object.freeze({epoch:e,sessionId:this.requireSessionId(e)})}requireSessionId(e){if(this.assertCurrentEpoch(e),this.sessionId===null)throw new Q("MCP session has not been initialized");return this.sessionId}isCurrentEpoch(e){return this.sessionEpoch===e&&!e.controller.signal.aborted}isCurrentSession(e){return this.isCurrentEpoch(e.epoch)&&(e.sessionId===null||this.sessionId===e.sessionId)}assertCurrentEpoch(e){if(!this.isCurrentEpoch(e))throw tt()}assertCurrentSession(e){if(this.assertCurrentEpoch(e.epoch),e.sessionId!==null&&this.sessionId!==e.sessionId)throw tt()}recordProvisionalSession(e,i){if(e.sessionId!==null)return;const n=i.headers.get("mcp-session-id");n!==null&&xt(n)&&n===n.trim()&&(e.epoch.provisionalSessionId=n,e.epoch.sessionCleanup===null&&(e.epoch.sessionCleanup=this.createSessionCleanup(n,e.epoch.credential)))}createRequestId(){const e=new Uint8Array(12);this.crypto.getRandomValues(e);let i="";for(const n of e)i+=n.toString(16).padStart(2,"0");return`${this.now().toString(36)}-${i}`}requireCredential(){if(this.token===null)throw new Q("MCP client has been destroyed");return this.token}}function Ql(t,e){if(typeof globalThis.fetch!="function")throw new Q("browser fetch is unavailable");return globalThis.fetch(t,e)}function Zl(){if(typeof globalThis.crypto?.getRandomValues!="function")throw new Q("browser cryptography is unavailable");return globalThis.crypto}function et(){let t,e;const i=new Promise((n,s)=>{e=n,t=s});if(e===void 0||t===void 0)throw new Q("MCP could not create a deferred task");return Object.freeze({promise:i,resolve:e,reject:t})}async function ms(t,e,i=Ot){id(t.headers.get("content-type"))!=="application/json"&&await pe(t,new _("MCP response uses an unsupported Content-Type"));const n=await ws(t,e,!1,i);return Rt(e),td(n)}async function ws(t,e,i=!1,n=Ot){if(t.body===null){if(i)return"";throw new _("MCP response is empty")}const s=t.body.getReader(),r=new TextDecoder("utf-8",{fatal:!0});let o=!1,a=0,c="";try{for(;;){const l=await Jl(s,e);if(Rt(e),l.done){o=!0;break}if(a+=l.value.byteLength,a>n)throw new li(n);try{c+=r.decode(l.value,{stream:!0})}catch{throw new _("MCP response is not valid UTF-8")}}try{c+=r.decode()}catch{throw new _("MCP response is not valid UTF-8")}if(!i&&c.trim().length===0)throw new _("MCP response is empty");return c}catch(l){if(!o)try{await Ue(()=>s.cancel())}catch(d){_t(l,d)}throw l}finally{s.releaseLock()}}function Jl(t,e){return new Promise((i,n)=>{if(e.aborted){n(Tt(e));return}const s=()=>{e.removeEventListener("abort",s),n(Tt(e))};e.addEventListener("abort",s,{once:!0}),t.read().then(r=>{if(e.removeEventListener("abort",s),e.aborted){n(Tt(e));return}i(r)},r=>{e.removeEventListener("abort",s),n(r)})})}async function vi(t){const e=t.body;e!==null&&await Ue(()=>e.cancel())}async function Ue(t,e={}){let i=!1;const n=new Q("MCP session cleanup timed out"),s=Promise.resolve().then(t),r=new Promise((o,a)=>{const c=globalThis.setTimeout(()=>{i=!0;try{e.onTimeout?.(n)}catch(l){a(new AggregateError([n,l],"MCP cleanup deadline failed"));return}a(n)},Yl);s.then(()=>globalThis.clearTimeout(c),()=>globalThis.clearTimeout(c))});return s.then(o=>{i&&e.onLateFulfilled!==void 0&&e.onLateFulfilled(o)},()=>{}),Promise.race([s,r])}function ed(t){Ue(t).then(()=>{},()=>{})}async function pe(t,e){try{await vi(t)}catch(i){_t(e,i)}throw e}function _t(t,e){throw t instanceof Q?(Object.defineProperty(t,"cleanupErrors",{configurable:!0,enumerable:!0,value:Object.freeze([...t.cleanupErrors,e]),writable:!1}),t):new AggregateError([t,e],"MCP request failed and cleanup failed")}function Tt(t){return t.reason instanceof Error?t.reason:new Q("MCP request was aborted")}function Rt(t){if(t.aborted)throw Tt(t)}function td(t){try{return JSON.parse(t)}catch{throw new _("MCP response is not valid JSON")}}function id(t){if(t===null)return null;const e=t.split(";")[0];if(e===void 0)return null;const i=e.trim().toLowerCase();return i.length===0?null:i}function nd(t,e){if(!ce(t)||t.jsonrpc!=="2.0"||t.id!==e)throw new _("MCP response does not match its request");if(Object.hasOwn(t,"error")){const i=sd(t,e);throw i!==void 0?i:new _("MCP returned an error response")}if(!Object.hasOwn(t,"result"))throw new _("MCP response has no result");return t.result}function sd(t,e){if(!it(t,["jsonrpc","id","error"])||t.jsonrpc!=="2.0"||t.id!==e||!ce(t.error))return;const i=t.error;if(!it(i,["code","message","data"])||typeof i.code!="number"||!Number.isSafeInteger(i.code)||typeof i.message!="string"||!ce(i.data))return;const n=rd(i.data);if(!(n===void 0||typeof n.code!="string"||!/^SCG_[A-Z0-9_]{1,80}$/.test(n.code)))return new St(n.code,i.code,n)}function rd(t){const e=Object.create(null);for(const[i,n]of Object.entries(t)){if(n!==null&&typeof n!="string"&&typeof n!="boolean"&&(typeof n!="number"||!Number.isSafeInteger(n)))return;Object.defineProperty(e,i,{configurable:!1,enumerable:!0,value:n,writable:!1})}return Object.freeze(e)}function od(t){const e=ae(t,["protocolVersion","capabilities","serverInfo"],"MCP initialize response is invalid");if(e.protocolVersion!==Ze)throw new _("MCP server negotiated an unsupported protocol version");const i=e.capabilities;if(!ce(i))throw new _("MCP initialize capabilities are invalid");const n=Object.keys(i);if(n.length!==0){if(n.length!==1||i.tools===void 0||!ce(i.tools)||!it(i.tools,["listChanged"])||i.tools.listChanged!==!1)throw new _("MCP initialize capabilities are invalid")}const s=ae(e.serverInfo,["name","version"],"MCP initialize server information is invalid");if(!xt(s.name)||!xt(s.version))throw new _("MCP initialize server information is invalid");return Object.freeze({protocolVersion:Ze,capabilities:Object.freeze({...i}),serverInfo:Object.freeze({name:s.name,version:s.version})})}function ad(t){if(!ce(t)||!Object.hasOwn(t,"structuredContent"))throw new _("MCP tool response has no structured content");if(!ce(t.structuredContent))throw new _("MCP tool structured content is invalid");return t.structuredContent}function cd(t,e){try{const i=ae(t,["page","revision","annotations"],"MCP annotation list structured content is invalid");if(!Array.isArray(i.annotations))throw new _("MCP annotation list structured content is invalid");const n=$e(i.page);if(!ud(n,e))throw new _("MCP annotation list returned a different page");const s=i.annotations.map(o=>Bt(o)),r=new Set;for(const o of s){if(r.has(o.id))throw new _("MCP annotation list contains duplicate annotation IDs");r.add(o.id)}return Object.freeze({page:n,revision:he(i.revision,"annotation list revision"),annotations:Object.freeze(s)})}catch(i){throw Ei(i,"MCP annotation list structured content is invalid")}}function bi(t,e,i){try{const n=ae(t,["replay","revision"],"MCP annotation mutation structured content is invalid"),s=ld(n.replay,e),r=he(n.revision,"annotation mutation revision");if(s.revision!==r)throw new _("MCP annotation mutation replay revision does not match");if(i!==void 0&&(s.kind==="delete"?s.annotationId:s.annotation.id)!==i)throw new _("MCP annotation mutation replay annotation ID does not match");return Object.freeze({replay:s,revision:r})}catch(n){throw Ei(n,"MCP annotation mutation structured content is invalid")}}function ld(t,e){switch(e){case"create":{const i=ae(t,["kind","revision","annotation"],"MCP annotation replay is invalid");if(i.kind!=="create")throw new _("MCP annotation replay kind does not match");return Object.freeze({kind:"create",revision:he(i.revision,"annotation replay revision"),annotation:Bt(i.annotation)})}case"update":{const i=ae(t,["kind","revision","annotation"],"MCP annotation replay is invalid");if(i.kind!=="update")throw new _("MCP annotation replay kind does not match");return Object.freeze({kind:"update",revision:he(i.revision,"annotation replay revision"),annotation:Bt(i.annotation)})}case"delete":{const i=ae(t,["kind","revision","annotationId"],"MCP annotation replay is invalid");if(i.kind!=="delete")throw new _("MCP annotation replay kind does not match");return Object.freeze({kind:"delete",revision:he(i.revision,"annotation replay revision"),annotationId:te(i.annotationId,"annotation replay annotationId")})}}}function dd(t,e){try{if(e.mode==="project"){const s=ae(t,["mode","markdown"],"MCP prompt export structured content is invalid");if(s.mode!=="project"||typeof s.markdown!="string")throw new _("MCP prompt export structured content is invalid");return Object.freeze({mode:"project",markdown:s.markdown})}const i=ae(t,["mode","pageId","markdown"],"MCP prompt export structured content is invalid");if(i.mode!=="page"||typeof i.markdown!="string")throw new _("MCP prompt export structured content is invalid");const n=Ft(i.pageId);if(e.pageId===void 0||n!==e.pageId)throw new _("MCP prompt export returned a different page");return Object.freeze({mode:"page",pageId:n,markdown:i.markdown})}catch(i){throw Ei(i,"MCP prompt export structured content is invalid")}}function ae(t,e,i){if(!ce(t)||!it(t,e))throw new _(i);return t}function ud(t,e){return t.policyVersion===e.policyVersion&&t.canonicalIdentity===e.canonicalIdentity&&t.route===e.route&&t.pageId===e.pageId}function hd(t){if(t===null||!xt(t)||t!==t.trim())throw new _("MCP initialize response omitted a valid session ID");return t}function tt(){return new Q("MCP session was superseded")}function vs(t){return t instanceof Q&&t.message==="MCP session was superseded"&&t.cleanupErrors.length===0}function yi(t,e,i=new Set){return t===e?!0:typeof t!="object"||t===null||i.has(t)?!1:(i.add(t),t instanceof AggregateError?t.errors.some(n=>yi(n,e,i)):t instanceof Q&&t.cleanupErrors.some(n=>yi(n,e,i)))}function Ei(t,e){return t instanceof _?t:new _(e)}function it(t,e){return Object.keys(t).length===e.length&&e.every(n=>Object.hasOwn(t,n))}function gd(t){return t===null?!1:t.split(",").some(e=>e.trim().toLowerCase()==="no-store")}function fd(t,e){return!ce(t)||!Number.isSafeInteger(e)||!it(t,["runId","token","expiresAt","endpoint"])?!1:typeof t.runId=="string"&&pd(t.runId)&&typeof t.token=="string"&&(Si(t.token,32)||wi.test(t.token))&&typeof t.expiresAt=="string"&&md(t.expiresAt,e)&&typeof t.endpoint=="string"}function pd(t){const e="diagnostic-";return t.startsWith(e)&&Si(t.slice(e.length),16)}function Si(t,e){if(t.length!==Math.ceil(e*4/3)||!/^[A-Za-z0-9_-]+$/.test(t))return!1;const i=e%3;if(i===0)return!0;const n=t.at(-1);if(n===void 0)return!1;const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(n);return i===1?s>=0&&s%16===0:s>=0&&s%4===0}function md(t,e){const i=Date.parse(t);return Number.isSafeInteger(i)&&i>e&&new Date(i).toISOString()===t}function wd(t,e){return bs(e)?wi.test(t):Si(t,32)}function bs(t){try{const e=new URL(t),i=Number(e.port);return e.protocol==="http:"&&e.hostname==="127.0.0.1"&&e.pathname===Xl&&e.username===""&&e.password===""&&e.search===""&&e.hash===""&&Number.isInteger(i)&&i>=1024&&i<=65535&&i!==4175}catch{return!1}}function vd(t,e){const i=/^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})(?:\/|$)/.exec(t);if(i===null||i[1]===void 0||Number(i[1])>65535)return!1;try{const n=new URL(t),s=new URL(e);return n.protocol==="http:"&&n.hostname==="127.0.0.1"&&n.origin===s.origin&&n.pathname===s.pathname&&n.username.length===0&&n.password.length===0&&n.search.length===0&&n.hash.length===0}catch{return!1}}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xt(t){return typeof t=="string"&&t.trim().length>0}class bd{mcp;stateValue="booting";connectTask=null;destroyTask=null;connectTaskEpoch=null;connectionEpoch=Object.freeze({});diagnosticsPanel;stateChangeHandler;hostReadyHandler;constructor(e){this.mcp=new ps({endpoint:e.endpoint,diagnosticEndpoint:e.diagnosticEndpoint,...e.token===void 0?{}:{token:e.token},...e.fetch===void 0?{}:{fetch:e.fetch},...e.now===void 0?{}:{now:e.now},...e.crypto===void 0?{}:{crypto:e.crypto}}),this.diagnosticsPanel=e.openDiagnosticsPanel??null,this.stateChangeHandler=e.onStateChange??null,this.hostReadyHandler=e.onHostReady??null}get state(){return this.stateValue}getSessionId(){return this.stateValue==="ready"?this.mcp.getSessionId():null}start(){return this.stateValue!=="booting"?Promise.resolve():this.connect()}retry(){return this.stateValue!=="unavailable"?Promise.resolve():this.connect()}notifyReady(){if(this.stateValue!=="destroyed"){try{this.hostReadyHandler?.()}catch{}this.stateValue==="ready"&&this.pingAfterHostReady()}}async openDiagnostics(){if(this.stateValue!=="ready")throw new Error("Scene Glass is not ready");const e=this.diagnosticsPanel;if(e===null)throw new Error("Scene Glass diagnostics panel is unavailable");await this.openDiagnosticPanel(e,this.connectionEpoch)}destroy(){if(this.destroyTask!==null)return this.destroyTask;if(this.stateValue==="destroyed")return Promise.resolve();this.invalidateConnection(),this.diagnosticsPanel=null,this.hostReadyHandler=null;const e=this.mcp.close();return this.destroyTask=e,this.transitionTo("destroyed"),this.stateChangeHandler=null,e}listAnnotations(e){return this.perform(i=>i.listAnnotations(e))}createAnnotation(e){return this.perform(i=>i.createAnnotation(e))}updateAnnotation(e){return this.perform(i=>i.updateAnnotation(e))}deleteAnnotation(e){return this.perform(i=>i.deleteAnnotation(e))}exportPrompt(e){return this.perform(i=>i.exportPrompt(e))}callWorkTool(e,i,n){return this.perform(s=>s.callTool(e,i,{maxResponseBytes:n}))}async connect(){if(this.connectTask!==null)return this.connectTask;const e=this.beginConnection(),i=this.initialize(e);this.connectTask=i,this.connectTaskEpoch=e,this.transitionTo("connecting");try{await i}finally{this.clearConnectTask(e,i)}}async initialize(e){if(this.isActiveConnection(e))try{await this.mcp.initialize(),this.isActiveConnection(e)&&this.transitionTo("ready")}catch(i){this.isActiveConnection(e)&&(this.clearConnectTask(e),this.transitionToFailure(i))}}async pingAfterHostReady(){const e=this.connectionEpoch;try{await this.mcp.ping()}catch(i){this.isActiveConnection(e)&&this.transitionToFailure(i)}}async openDiagnosticPanel(e,i){let n;try{n=await this.mcp.issueDiagnosticRun()}catch(s){throw this.isActiveConnection(i)&&this.transitionToFailure(s),s}if(!this.isReadyConnection(i))throw new Error("Scene Glass diagnostics request was superseded");try{if(await e(n),!this.isReadyConnection(i))throw new Error("Scene Glass diagnostics request was superseded")}catch(s){throw this.isReadyConnection(i)?s:new Error("Scene Glass diagnostics request was superseded")}}async perform(e){if(this.stateValue!=="ready")throw new Error("Scene Glass is not ready");const i=this.connectionEpoch;try{const n=await e(this.mcp);if(!this.isReadyConnection(i))throw new Error("Scene Glass operation was superseded");return n}catch(n){throw this.isReadyConnection(i)?(n instanceof St||this.transitionToFailure(n),n):new Error("Scene Glass operation was superseded")}}transitionToFailure(e){if(this.stateValue!=="destroyed"){if(e instanceof Et&&(e.status===401||e.status===403)){this.transitionTo("access-error");return}this.transitionTo("unavailable")}}beginConnection(){const e=Object.freeze({});return this.connectionEpoch=e,e}invalidateConnection(){this.connectionEpoch=Object.freeze({})}isActiveConnection(e){return this.connectionEpoch===e&&this.stateValue!=="destroyed"}isReadyConnection(e){return this.isActiveConnection(e)&&this.stateValue==="ready"}clearConnectTask(e,i){this.connectTaskEpoch===e&&(i===void 0||this.connectTask===i)&&(this.connectTask=null,this.connectTaskEpoch=null)}transitionTo(e){if(this.stateValue!==e){this.stateValue=e;try{this.stateChangeHandler?.(e)}catch{}}}}function ys(t,e){if(e.length>ts)throw C("work event batch exceeds the bounded event ceiling");const i=[];let n=t.nextSequence,s=0,r=null,o=e[0]?.requestId??null;for(const a of e){if(a.requestId!==o)throw C("work event batch mixes request identities");o=a.requestId;const c=a.expectedEventSequence;if(r!==null&&c<=r)throw C("work event batch is not ordered by sequence");if(r=c,c<n){s+=1;continue}if(c>n)throw C("work event batch skips a durable sequence");i.push(a),n+=1}return Object.freeze({events:i.length===0?t.events:Object.freeze([...t.events,...i]),nextSequence:n,applied:Object.freeze(i),suppressed:s})}function nt(t){const e=new Map;for(const i of t){Sd(i);const n=e.get(i.request.requestId);if(n===void 0){e.set(i.request.requestId,i);continue}if(Ss(n)!==Ss(i))throw C("immutable work request changed across durable records");e.set(i.request.requestId,yd(n,i))}return Object.freeze([...e.values()].sort(kd))}function Es(t,e){const i=new Map;for(const n of nt(t)){if(n.request.page.pageId!==e||n.result.state!=="completed"||n.result.reviewState!=="pending"&&n.result.reviewState!=="acknowledged")continue;const s=Object.freeze({requestId:n.request.requestId,phase:n.result.reviewState==="pending"?"review-pending":"reviewed"});for(const r of n.request.annotationDigests)i.has(r)||i.set(r,s)}return i}function yd(t,e){if(e.result.eventSequence<t.result.eventSequence)return t;if(e.result.eventSequence>t.result.eventSequence){if(Ed(t,e),Nt(e.result.reviewState)<Nt(t.result.reviewState))throw C("higher-sequence work review state regressed");return e}if(ks(t)!==ks(e))throw C("equal-sequence work lifecycle records conflict");return Nt(e.result.reviewState)>Nt(t.result.reviewState)?e:t}function Ed(t,e){if(t.events.length!==t.result.eventSequence||e.events.length!==e.result.eventSequence||e.events.length<=t.events.length)throw C("higher-sequence work event history is not a contiguous extension");for(const[i,n]of t.events.entries())if(JSON.stringify(n)!==JSON.stringify(e.events[i]))throw C("higher-sequence work event history prefix changed");if(e.events.at(-1)?.toState!==e.result.state)throw C("higher-sequence work lifecycle disagrees with event history")}function Sd(t){if(t.request.requestId!==t.result.requestId)throw C("work record request and result identities differ")}function Ss(t){return JSON.stringify(t.request)}function ks(t){const e=t.result;return JSON.stringify({result:{schemaVersion:e.schemaVersion,requestId:e.requestId,state:e.state,mayHaveModifiedWorkspace:e.mayHaveModifiedWorkspace,errorCode:e.errorCode,eventSequence:e.eventSequence,updatedAt:e.updatedAt},events:t.events})}function Nt(t){switch(t){case"none":return 0;case"pending":return 1;case"acknowledged":return 2}}function kd(t,e){return Date.parse(e.request.createdAt)-Date.parse(t.request.createdAt)||t.request.requestId.localeCompare(e.request.requestId)}class Cd{epoch=0;value=null;loading=!1;error=null;pending=null;snapshot(){return Object.freeze({providerCapabilities:this.value,providerCapabilitiesLoading:this.loading,providerCapabilitiesError:this.error})}invalidate(){this.epoch+=1,this.pending=null,this.value=null,this.loading=!1,this.error=null}read(e,i){if(this.pending?.provider===e&&this.pending.generation===i.generation)return this.pending.promise;const n=++this.epoch,s=Promise.resolve().then(i.read).then(r=>(this.epoch===n&&(this.value=r),r),r=>{throw this.epoch===n&&(this.value=null,this.error="SCG_WORK_CAPABILITIES_UNAVAILABLE"),r}).finally(()=>{this.epoch===n&&(this.pending=null,this.loading=!1,i.changed())});return this.pending={provider:e,generation:i.generation,promise:s},this.loading=!0,this.error=null,i.changed(),s}}class Id{capabilities=new Cd;selection=null;readiness=null;session=null;warningVersion=null;captured=null;generation=0;request=null;result=null;events=Object.freeze([]);nextSequence=0;history=Object.freeze([]);diff=null;comparison=null;watching=!1;snapshot(){return Object.freeze({...this.capabilities.snapshot(),providerSelection:this.selection,providerReadiness:this.readiness,providerSession:this.session,warningContractVersion:this.warningVersion,preview:this.captured?.view??null,pageGeneration:this.generation,request:this.request,result:this.result,events:this.events,nextEventSequence:this.nextSequence,reviewState:this.result?.reviewState??"none",history:this.history,diff:this.diff,comparison:this.comparison,watching:this.watching})}pageGeneration(){return this.generation}invalidatePage(){this.generation+=1,this.captured=null}applyProvider(e){if(this.selection!==null&&e.selection.generation<this.selection.generation)throw new B("SCG_WORK_GENERATION_CONFLICT","work provider selection generation regressed");const i=this.selection===null||this.selection.provider!==e.selection.provider||this.selection.generation!==e.selection.generation||!ht(this.selection.executionSettings,e.selection.executionSettings);this.selection=e.selection,this.readiness=e.readiness,this.session=e.session??null,this.warningVersion=e.warningContractVersion,i&&(this.captured=null,this.capabilities.invalidate())}setPreview(e,i){if(i!==this.generation||this.selection!==null&&(e.provider!==this.selection.provider||e.providerGeneration!==this.selection.generation||!ht(e.executionSettings,this.selection.executionSettings)))throw new B("SCG_WORK_STALE_PREVIEW","work preview was superseded by navigation");this.captured=Object.freeze({view:e,pageGeneration:i,providerGeneration:e.providerGeneration})}requirePreview(){const e=this.captured;if(e===null)throw new B("SCG_WORK_STALE_PREVIEW","no current work preview exists");if(e.pageGeneration!==this.generation||e.providerGeneration!==this.selection?.generation||e.view.provider!==this.selection?.provider||!ht(e.view.executionSettings,this.selection?.executionSettings))throw new B("SCG_WORK_STALE_PREVIEW","work preview no longer matches the current page or provider generation");return e.view}applyRecord(e){const i=ys(this.matches(e.request.requestId)?{events:this.events,nextSequence:this.nextSequence}:{events:Object.freeze([]),nextSequence:0},e.events);if(e.result.eventSequence<i.nextSequence)throw C("work result sequence regressed behind its applied events");this.request=e.request,this.result=e.result,this.events=i.events,this.nextSequence=i.nextSequence}applyWatch(e){if(!this.matches(e.requestId))throw C("work watch response does not match the tracked request");const i=ys({events:this.events,nextSequence:this.nextSequence},e.events);if(e.result.eventSequence<i.nextSequence)throw C("work result sequence regressed behind its applied events");this.result=e.result,this.events=i.events,this.nextSequence=i.nextSequence,this.projectTrackedRecordIntoHistory()}setHistory(e){const i=this.trackedRecord();if(this.history=nt([...this.history,...e.items,...i===null?[]:[i]]),this.request!==null)return;const n=this.history.find(({result:s})=>!Ee(s.state)||s.state==="completed"&&s.reviewState==="pending");n!==void 0&&this.applyRecord(n)}reviewStateForRequest(e){return this.matches(e)?this.result?.reviewState??null:this.history.find(({request:i})=>i.requestId===e)?.result.reviewState??null}applyHistoricalRecord(e){this.history=nt([...this.history,e]),this.matches(e.request.requestId)&&this.applyRecord(e)}setDiff(e){this.diff=e}setComparison(e){this.comparison=e}setWatching(e){this.watching=e}trackedRequestId(){return this.request?.requestId??null}isTerminal(){return this.result!==null&&Ee(this.result.state)}projectTrackedRecordIntoHistory(){const e=this.trackedRecord();e!==null&&(this.history=nt([...this.history,e]))}trackedRecord(){return this.request===null||this.result===null?null:Object.freeze({request:this.request,result:this.result,events:this.events})}matches(e){return this.request!==null&&this.request.requestId===e}}async function Ad(t,e){const i=[],n=Math.ceil(D.pagesPerProject/se);let s=0;for(let r=0;r<n;r+=1){const o=await t.list({cursor:s,limit:se});if(e(),o.pagination.cursor!==s||o.pagination.limit!==se)throw C("work history pagination does not match the requested page");if(i.length+o.items.length>D.pagesPerProject)throw Cs();i.push(...o.items);const a=o.pagination.nextCursor;if(a===null)return Object.freeze(i);if(a<=s)throw C("work history pagination cursor did not advance");s=a}throw Cs()}function Cs(){return new B("SCG_WORK_LIMIT_EXCEEDED","work history pagination exceeds the project record ceiling")}class Od{constructor(e){this.access=e}access;diffOperationId=0;historyOperationId=0;reviewAcknowledgments=new Map;async refreshProvider(){this.access.assertActive();const e=await this.access.client.readProvider();this.access.assertActive(),this.access.store.applyProvider(e),this.access.emit()}async setProvider(e,i){this.access.assertActive();const n=await this.access.client.setProvider({provider:e,expectedGeneration:this.knownGeneration(),...Co(i)});this.access.assertActive(),this.access.store.applyProvider(n),this.access.emit()}async resetProviderSession(){this.access.assertActive();const e=await this.access.client.resetProviderSession({expectedGeneration:this.knownGeneration()});this.access.assertActive(),this.access.store.applyProvider(e),this.access.emit()}async acknowledgeWarning(e,i){this.access.assertActive();const n=await this.access.client.acknowledgeWarning({provider:e,remember:i});this.access.assertActive(),this.access.store.applyProvider(n),this.access.emit()}async preview(e){this.access.assertActive();const i=this.access.store.pageGeneration(),n=await this.access.client.preview({page:e});if(this.access.assertActive(),!Td(n.page,e))throw C("work preview does not describe the requested page");this.access.store.setPreview(n,i),this.access.emit()}async submit(e){this.access.assertActive();const i=this.access.store.requirePreview(),n=await this.access.client.submit({requestId:e,page:i.page,pageRevision:i.pageRevision,previewDigest:i.previewDigest});if(this.access.assertActive(),n.work.request.requestId!==e)throw C("work submit returned another request identity");this.access.store.applyRecord(n.work),this.access.emit(),this.access.beginWatch(n.work.request.requestId)}async cancelRequest(){this.access.assertActive(),this.access.store.applyRecord(await this.access.client.cancel({requestId:this.requireTracked()})),this.access.emit()}async retryRequest(){this.access.assertActive();const e=await this.access.client.retry({requestId:this.requireTracked()});this.access.assertActive(),this.access.store.applyRecord(e),this.access.emit(),this.access.beginWatch(e.request.requestId)}acknowledgeReview(e){const i=this.reviewAcknowledgments.get(e);if(i!==void 0)return i;const n=this.performReviewAcknowledgment(e).finally(()=>{this.reviewAcknowledgments.delete(e)});return this.reviewAcknowledgments.set(e,n),n}async performReviewAcknowledgment(e){this.access.assertActive();const i=this.access.store.reviewStateForRequest(e);if(i==="acknowledged")return;if(i!=="pending")throw new B("SCG_WORK_GENERATION_CONFLICT","the requested review is not a retained pending request");let n;try{n=await this.access.client.acknowledgeReview({requestId:e})}catch(s){if(!_d(s,"SCG_WORK_REQUEST_INVALID"))throw s;const r=await this.access.client.read({requestId:e});if(this.access.assertActive(),!ls(r,e))throw s;n=r}if(this.access.assertActive(),!ls(n,e))throw C("work review acknowledgment returned an invalid record");this.access.store.applyHistoricalRecord(n),this.access.emit()}async refreshHistory(){this.access.assertActive();const e=++this.historyOperationId,i=this.access.onHistoryRefresh?.(),n=this.access.store.snapshot(),s=new Set([...n.history.map(({request:o})=>o.requestId),...n.request===null?[]:[n.request.requestId]]),r=await Ad(this.access.client,this.access.assertActive);if(this.access.store.setHistory(Object.freeze({items:r,pagination:Object.freeze({cursor:0,limit:se,nextCursor:null})})),e===this.historyOperationId&&i!==void 0){const o=this.access.store.snapshot(),a=new Set([...o.history.map(({request:c})=>c.requestId),...o.request===null?[]:[o.request.requestId]].filter(c=>!s.has(c)));i({retainedRequestIds:new Set(r.map(({request:c})=>c.requestId)),observedAfterStart:a})}this.access.emit()}async readDiff(e){this.access.assertActive();const i=this.diffOperationId+=1,n=await this.access.client.readDiff({requestId:e});this.access.assertActive(),i===this.diffOperationId&&(this.access.store.setDiff(n),this.access.emit())}async compareDiff(e,i){this.access.assertActive();const n=this.diffOperationId+=1,s=await this.access.client.compareDiff({requestIdA:e,requestIdB:i});this.access.assertActive(),n===this.diffOperationId&&(this.access.store.setComparison(s),this.access.emit())}knownGeneration(){const e=this.access.store.snapshot().providerSelection;if(e===null)throw new B("SCG_WORK_GENERATION_CONFLICT","the work provider selection generation is not known yet");return e.generation}requireTracked(){const e=this.access.store.trackedRequestId();if(e===null)throw C("no accepted work request is tracked");return e}}function _d(t,e){return typeof t=="object"&&t!==null&&Reflect.get(t,"code")===e}function Td(t,e){return t.policyVersion===e.policyVersion&&t.canonicalIdentity===e.canonicalIdentity&&t.route===e.route&&t.pageId===e.pageId}function Is(){let t=()=>{};return{promise:new Promise(i=>{t=i}),resolve:t}}function Rd(t){return{requestId:t,issued:Is(),aborted:Is(),cancelled:!1}}async function xd(t,e){const{client:i,store:n,isDestroyed:s,onProgress:r,onFinished:o}=e;try{for(;!t.cancelled&&!s()&&!n.isTerminal();){const a=n.snapshot().nextEventSequence,c=await Promise.race([i.watch({requestId:t.requestId,afterEventSequence:a}).then(l=>({kind:"view",view:l}),l=>({kind:"error",error:l})),t.aborted.promise.then(()=>({kind:"aborted"}))]);if(c.kind==="aborted"||t.cancelled||s())return;if(c.kind==="error")throw c.error;n.applyWatch(c.view),r()}}finally{t.cancelled=!0,t.aborted.resolve(),t.issued.resolve(),o(t)}}function Nd(t){return new Pd(t)}class Pd{store=new Id;client;notify;operations;session=null;watchTask=Promise.resolve();issuedPromise=Promise.resolve();destroyed=!1;constructor(e){this.notify=e.onStateChange??null,this.client=fi((i,n,s)=>{const r=e.callTool(i,n,s);return i===F.watch&&this.session?.issued.resolve(),r}),this.operations=new Od({client:this.client,store:this.store,assertActive:()=>this.assertActive(),emit:()=>this.emit(),beginWatch:i=>this.beginWatch(i),...e.onHistoryRefresh===void 0?{}:{onHistoryRefresh:e.onHistoryRefresh}})}getState(){return this.store.snapshot()}refreshProvider(){return this.operations.refreshProvider()}readCapabilities(e){return this.assertActive(),this.store.capabilities.read(e,{generation:this.store.snapshot().providerSelection?.generation??null,read:()=>this.client.readCapabilities(e),changed:()=>this.emit()})}setProvider(e,i){return this.operations.setProvider(e,i)}acknowledgeWarning(e,i){return this.operations.acknowledgeWarning(e,i)}resetProviderSession(){return this.operations.resetProviderSession()}preview(e){return this.operations.preview(e)}submit(e){return this.operations.submit(e)}cancelRequest(){return this.operations.cancelRequest()}retryRequest(){return this.operations.retryRequest()}acknowledgeReview(e){return this.operations.acknowledgeReview(e)}refreshHistory(){return this.operations.refreshHistory()}readDiff(e){return this.operations.readDiff(e)}compareDiff(e,i){return this.operations.compareDiff(e,i)}watchIssued(){return this.issuedPromise}settled(){return this.watchTask}suspend(){this.store.capabilities.invalidate(),this.emit();const e=this.session;e!==null&&(e.cancelled=!0,this.session=null,e.aborted.resolve(),e.issued.resolve(),this.store.setWatching(!1),this.emit())}async resume(){this.assertActive();const e=this.store.trackedRequestId();e!==null&&(this.store.applyRecord(await this.client.read({requestId:e})),this.assertActive(),this.emit(),this.beginWatch(e))}invalidatePage(){this.store.invalidatePage(),this.emit()}destroy(){this.destroyed=!0,this.suspend()}beginWatch(e){if(this.destroyed||this.session!==null||this.store.isTerminal())return;const i=Rd(e);this.session=i,this.issuedPromise=i.issued.promise,this.store.setWatching(!0),this.emit();const n=xd(i,{client:this.client,store:this.store,isDestroyed:()=>this.destroyed,onProgress:()=>this.emit(),onFinished:s=>this.releaseWatch(s)});this.watchTask=n,n.catch(()=>{})}releaseWatch(e){this.session===e&&(this.session=null,this.store.setWatching(!1),this.emit())}assertActive(){if(this.destroyed)throw new B("SCG_WORK_CLIENT_TORN_DOWN","the work runtime was torn down")}emit(){if(this.notify!==null)try{this.notify(this.store.snapshot())}catch{}}}const Ld=/^SCG_[A-Z0-9_]{1,80}$/u;function Md(t){let e="idle",i=null,n=!1,s=null,r=null;const o=()=>Object.freeze({pending:e,preview:i,stale:n,failureCode:s}),a=()=>t.onChanged(o()),c=u=>e!=="idle"?!1:(e=u,s=null,a(),!0),l=()=>{e="idle",a()},d=async(u,h)=>{if(await t.controller.preview(u),i=t.controller.getState().preview,n=h,i===null)throw new Dd("SCG_WORK_STALE_PREVIEW")};return{snapshot:o,syncContext(u){const h=r;r=u,h!==null&&h.providerGeneration!==u.providerGeneration&&(i=null,n=!1),h!==null&&(h.pageId!==u.pageId||h.revision!==u.revision||h.providerGeneration!==u.providerGeneration)&&s==="SCG_WORK_NO_ELIGIBLE"&&(s=null)},async preview(u){if(c("previewing")){n=!1;try{await d(u,!1)}catch(h){s=Pt(h,"SCG_WORK_REQUEST_INVALID")}finally{l()}}},async submit(u){if(!c("submitting"))return;const h=i?.page??null;try{await t.controller.submit(u),i=null,n=!1}catch(f){const b=Pt(f,"SCG_WORK_REQUEST_INVALID");if(b==="SCG_WORK_STALE_PREVIEW"&&h!==null)try{await d(h,!0)}catch(y){i=null,n=!1,s=Pt(y,"SCG_WORK_STALE_PREVIEW")}else i=null,n=!1,s=b}finally{l()}},async cancel(){if(c("cancelling"))try{await t.controller.cancelRequest()}catch(u){s=Pt(u,"SCG_WORK_REQUEST_INVALID")}finally{l()}},dismissPreview(){i=null,n=!1,s=null,a()},invalidatePage(){i=null,n=!1,s=null,a()}}}class Dd extends Error{constructor(e){super(e),this.code=e}code;name="WorkRequestFlowError"}function Pt(t,e){if(t instanceof Error){const i=Reflect.get(t,"code");if(typeof i=="string"&&Ld.test(i))return i}return e}const qd=/^SCG_[A-Z0-9_]{1,80}$/u,zd=new Set(["SCG_WORK_GENERATION_CONFLICT","SCG_WORK_ACTIVE"]),Gd="SCG_WORK_PROVIDER_INVALID";function jd(t){let e="idle",i=!1,n="pending",s=null;const r=d=>{s=null,e=d,t.onChanged()},o=()=>{e="idle",t.onChanged()},a=async()=>{try{await t.controller.refreshProvider()}catch(d){if(!(d instanceof Error))throw d}},c=async()=>{try{await t.controller.refreshProvider(),await t.controller.refreshHistory()}catch(d){if(!(d instanceof Error))throw d;return}n="settled",t.onChanged()},l=async(d,u="saving")=>{if(e==="idle"){r(u);try{await d(),i=!1}catch(h){const f=As(h);zd.has(f)?(i=!0,await a()):(s=f,t.onFailure(f))}finally{o()}}};return{pending:()=>e,conflict:()=>i,recovery:()=>n,failureCode:()=>s,changeProvider:d=>l(()=>t.controller.setProvider(d)),changeExecutionSettings:d=>l(async()=>{const u=t.controller.getState?.().providerSelection;if(u==null)throw new B("SCG_WORK_GENERATION_CONFLICT","SCG_WORK_GENERATION_CONFLICT");await t.controller.setProvider(u.provider,d)}),async acknowledgeWarning(d){if(e==="idle"){r("acknowledging");try{await t.controller.acknowledgeWarning(d.provider,d.remember),i=!1}catch(u){const h=As(u);s=h,t.onFailure(h)}finally{o()}}},resetSession:()=>l(()=>t.controller.resetProviderSession(),"resetting"),refresh:a,hydrate:c}}function As(t){if(t instanceof Error){const e=Reflect.get(t,"code");if(typeof e=="string"&&qd.test(e))return e}return Gd}class Wd{constructor(e){this.access=e}access;#e=null;async changeProvider(e){await this.access.provider.changeProvider(e.provider),await this.readCapabilities()}async changeExecutionSettings(e){await this.access.provider.changeExecutionSettings(e.executionSettings),await this.readCapabilities()}async open(){this.access.ready()&&(await this.access.provider.refresh(),await this.readCapabilities())}async resetSession(){await this.access.provider.resetSession(),await this.readCapabilities()}refreshAfterSettlement(){const{request:e,result:i}=this.access.work.getState();if(e===null||i===null||!Ee(i.state))return;const n=`${e.requestId}:${i.eventSequence}`;n!==this.#e&&(this.#e=n,this.access.provider.refresh())}async readCapabilities(){if(!this.access.ready())return;const e=this.access.work.getState().providerSelection?.provider;if(!(e===void 0||e==="none"))try{await this.access.work.readCapabilities(e)}catch(i){if(!(i instanceof Error))throw i}}}function Ud(t,e){return t.projectionGeneration===e.projectionGeneration&&e.pageCurrent&&t.pageId===e.pageId&&t.revision===e.revision&&t.recordSignature===e.recordSignature}function Vd(t,e){return async(i,n,s)=>{if(i!=="work.preview"&&i!=="work.submit")return t(i,n,s);const r=n,o=_s(await e());o.assertCurrent(),(!Ts(o.page,$e(r.page))||i==="work.submit"&&o.pageRevision!==r.pageRevision)&&Rs();const a=await t(i,{...r,pageRevision:o.pageRevision,annotationIds:o.annotationIds},s);return i==="work.preview"&&Os(o,await e()),a}}function Os(t,e){t.assertCurrent();const i=_s(e);i.assertCurrent();const n=new Set(i.annotationIds);(!Ts(t.page,i.page)||t.pageRevision!==i.pageRevision||t.annotationIds.length!==n.size||t.annotationIds.some(s=>!n.has(s)))&&Rs()}function _s(t){return{...t,page:$e(t.page),pageRevision:he(t.pageRevision),annotationIds:Hi(t.annotationIds)}}function Ts(t,e){return t.pageId===e.pageId&&t.canonicalIdentity===e.canonicalIdentity&&t.route===e.route&&t.policyVersion===e.policyVersion}function Rs(){throw new B("SCG_WORK_STALE_PREVIEW","live page eligibility changed")}function Bd(t,e,i){if(e.annotationId!==void 0)return{mode:"page",pageId:t,annotationId:te(e.annotationId,"annotationId")};if(i===void 0)throw new TypeError("bulk page copy requires a live annotation snapshot");return{mode:"page",pageId:t,pageRevision:he(i.pageRevision),annotationIds:Hi(i.annotationIds)}}function Fd(t){const e=async()=>{const i=t.capture(),n=await t.controller.reconcile();t.assertCurrent(i);const s=t.controller.getState();if(n.status!=="applied"||s.revision===void 0)throw new B("SCG_WORK_STALE_PREVIEW","live page unavailable");return{page:i.page,pageRevision:s.revision,annotationIds:s.bindings.filter(r=>r.resolution.status==="resolved").map(r=>r.annotation.id),assertCurrent:()=>t.assertCurrent(i)}};return{capture:e,async exportCurrentPage(i){const n=t.capture(),s=i.annotationId===void 0?await e():void 0,r=await t.exportPrompt(Bd(n.page.pageId,i,s));return t.assertCurrent(n),s!==void 0&&Os(s,await e()),r.markdown}}}const ki=4096,$d=ki*512+512,Kd=["schemaVersion","projectId","pageId","requestId","annotationVersionDigest"];function xs(t){return`scg:badge-attention:v1:${lt(t)}`}function Ce(t){return JSON.stringify([t.schemaVersion,t.projectId,t.pageId,t.requestId,t.annotationVersionDigest])}function Ci(t,e){const i=Ns(t,Kd),n=lt(i.projectId);if(i.schemaVersion!==1||n!==e)throw new TypeError("Invalid badge attention identity");return Object.freeze({schemaVersion:1,projectId:n,pageId:Ft(i.pageId),requestId:te(i.requestId),annotationVersionDigest:Re(i.annotationVersionDigest)})}function Hd(t,e){const i=xs(t);let n,s;try{if(n=e(),n===null)return{storage:null,tokens:[],warning:"storage-unavailable"};s=n.getItem(i)}catch{return{storage:null,tokens:[],warning:"storage-unavailable"}}if(s===null)return{storage:n,tokens:[],warning:null};try{return{storage:n,tokens:Xd(s,t),warning:null}}catch{return{storage:n,tokens:[],warning:"invalid-storage"}}}function Yd(t,e,i){if(i.length>ki)return"capacity-exhausted";if(e===null)return"storage-unavailable";try{return e.setItem(xs(t),JSON.stringify({schemaVersion:1,projectId:t,dismissedTokens:i.map(n=>({schemaVersion:n.schemaVersion,projectId:n.projectId,pageId:n.pageId,requestId:n.requestId,annotationVersionDigest:n.annotationVersionDigest}))})),null}catch{return"storage-unavailable"}}function Xd(t,e){if(t.length>$d)throw new TypeError("Badge attention storage exceeds its bound");const i=Ns(JSON.parse(t),["schemaVersion","projectId","dismissedTokens"]);if(i.schemaVersion!==1||i.projectId!==e||!Array.isArray(i.dismissedTokens)||i.dismissedTokens.length>ki)throw new TypeError("Invalid badge attention storage");const n=new Set,s=i.dismissedTokens.map(r=>{const o=Ci(r,e),a=Ce(o);if(n.has(a))throw new TypeError("Duplicate badge attention token");return n.add(a),o});return Object.freeze(s)}function Ns(t,e){if(typeof t!="object"||t===null||Array.isArray(t)||Object.keys(t).length!==e.length||!e.every(i=>Object.prototype.hasOwnProperty.call(t,i)))throw new TypeError("Invalid badge attention object");return t}function Qd(t){return Ci({...t,schemaVersion:1},t.projectId)}function Zd(t){const e=lt(t.projectId),i=Hd(e,t.getStorage),n=new Map(i.tokens.map(l=>[Ce(l),l]));let s=i.warning;function r(){s=Yd(e,i.storage,[...n.values()])}function o(l){return l.projectId===e&&n.has(Ce(l))}function a(l,d){const u=new Map;for(const h of l)h.projectId!==e||h.pageId!==d||o(h)||u.set(Ce(h),Ps(h,e));return Object.freeze([...u.values()])}function c(l){const d=l.filter(h=>h.projectId===e).map(h=>Ps(h,e));let u=!1;for(const h of d){const f=Ce(h);n.has(f)||(n.set(f,h),u=!0)}u&&r()}return Object.freeze({get persistenceWarning(){return s},get reloadDurable(){return s===null},isDismissed:o,pending:a,capturePending:a,dismiss(l){c([l])},dismissSnapshot:c,updateRetainedHistory(l){if(l.projectId!==e||!l.complete)return;let d=!1;for(const[u,h]of n)l.requestIds.has(h.requestId)||(n.delete(u),d=!0);(d||s!==null)&&r()}})}function Ps(t,e){return Ci({schemaVersion:t.schemaVersion,projectId:t.projectId,pageId:t.pageId,requestId:t.requestId,annotationVersionDigest:t.annotationVersionDigest},e)}function Jd(t){const e=new Map,i=[];let n=0;return Object.freeze({read(s){const r=e.get(s);if(r!==void 0)return r;const a=(n<2?(n++,Promise.resolve()):new Promise(c=>i.push(c))).then(()=>eu(t,s)).finally(()=>{e.delete(s);const c=i.shift();c===void 0?n--:c()});return e.set(s,a),a}})}async function eu(t,e){const i=new tu(e);for(;i.cursor!==null;){let n;try{n=await t.readDiff({requestId:e,cursor:i.cursor,limit:di})}catch(r){return nu(r)}const s=i.append(n);if(s!==null)return s}return i.result()}class tu{constructor(e){this.requestId=e}requestId;cursor=0;header=null;previousPath=null;fileCount=0;preBytes=0;postBytes=0;textBytes=0;changed=!1;append(e){const{patch:i,pagination:n}=e,{cursor:s,limit:r,nextCursor:o}=n;if(i.requestId!==this.requestId||s!==this.cursor||r!==di||i.files.length>r||s>0&&i.files.length===0||o!==null&&(o!==s+r||i.files.length!==r))return H("invalid");if(i.state==="unavailable")return H("unavailable");if(i.state==="truncated")return H("truncated");if(i.fidelity!=="exact")return H("not-exact");if(e.reason!==null)return H("incomplete");if(e.renderedBytes>D.historyDiffRenderBytes)return H("limit-exceeded");const a=JSON.stringify([e.renderedBytes,...is.map(c=>e.summary[c]),...ns.map(c=>e.resources[c])]);if(this.header!==null&&this.header!==a)return H("invalid");this.header=a;for(const c of i.files){if(this.previousPath!==null&&this.previousPath>=c.path)return H("invalid");this.previousPath=c.path,this.fileCount++,this.preBytes+=c.preContent?.sizeBytes??0,this.postBytes+=c.postContent?.sizeBytes??0;for(const l of c.hunks)for(const d of l.lines)this.textBytes+=_e(d.text);if(this.fileCount>D.historyScanFiles||this.preBytes>D.historyScanBytes||this.postBytes>D.historyScanBytes||this.textBytes>D.historyDiffRenderBytes)return H("limit-exceeded");this.changed||=iu(c)}return o!==null&&this.fileCount>=D.historyScanFiles?H("limit-exceeded"):(this.cursor=o,null)}result(){return this.cursor!==null?H("incomplete"):Object.freeze({classification:this.changed?"changed":"unchanged",reason:null})}}function iu(t){switch(t.status){case"added":return t.postContent!==null;case"deleted":return t.preContent!==null;case"modified":return t.preContent?.digest!==t.postContent?.digest;case"mode-only":case"binary":case"metadata-only":return!1}}function H(t){return Object.freeze({classification:"unknown",reason:t})}function nu(t){return t instanceof li||(t instanceof B||t instanceof St)&&t.code==="SCG_WORK_LIMIT_EXCEEDED"?H("limit-exceeded"):t instanceof _?H("invalid"):t instanceof St&&t.code==="SCG_WORK_NOT_FOUND"?H("unavailable"):H("read-failed")}function su(t,e){return t!==null&&!Ee(t)?t:ru(e)}function ru(t){for(const e of t)if(!Ee(e.result.state))return e.result.state;return null}function ou(t){return Ii(t,new Set)}function Ii(t,e){switch(typeof t){case"string":return Ls(t),Ai(t);case"number":if(!Number.isFinite(t))throw me("canonical JSON cannot contain a non-finite number");return Ai(t);case"boolean":return t?"true":"false";case"object":if(t===null)return"null";if(e.has(t))throw me("canonical JSON cannot contain a cycle");e.add(t);try{if(Array.isArray(t)){const s=[];for(let r=0;r<t.length;r+=1){if(!Object.prototype.hasOwnProperty.call(t,r))throw me("canonical JSON cannot contain an array hole");s.push(Ii(t[r],e))}return`[${s.join(",")}]`}if(!au(t))throw me("canonical JSON requires plain objects");return`{${Object.keys(t).sort(cu).map(s=>(Ls(s),`${Ai(s)}:${Ii(t[s],e)}`)).join(",")}}`}finally{e.delete(t)}default:throw me("canonical JSON contains an unsupported value")}}function au(t){const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function cu(t,e){return t<e?-1:t>e?1:0}function Ai(t){const e=JSON.stringify(t);if(e===void 0)throw me("canonical JSON stringification failed");return e}function Ls(t){for(let e=0;e<t.length;e+=1){const i=t.charCodeAt(e);if(i>=55296&&i<=56319){const n=t.charCodeAt(e+1);if(e+1>=t.length||n<56320||n>57343)throw me("canonical JSON contains an unpaired surrogate");e+=1}else if(i>=56320&&i<=57343)throw me("canonical JSON contains an unpaired surrogate")}}function me(t){return new N("SCG_PAGE_FILE_INVALID",t)}const lu=1;async function du(t){return uu(gu(t))}async function uu(t){return hu(ou(t))}async function hu(t){if(!globalThis.crypto?.subtle)throw new N("SCG_WORK_REQUEST_INVALID","Web Crypto SHA-256 is unavailable");const e=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=Array.from(new Uint8Array(e),n=>n.toString(16).padStart(2,"0")).join("");return Re(`sha256:${i}`)}function gu(t){return{version:lu,annotationId:t.id,context:t.context??null,domOrder:t.domOrder,locator:t.locator,memo:t.memo,resolution:t.resolution,surroundingText:t.surroundingText}}function fu(t){switch(t.state){case"failed":case"cancelled":return t.mayHaveModifiedWorkspace?"require-new-request":"retry-same-request";case"indeterminate":return"require-new-request";case"queued":case"preparing":case"dispatching":case"delivered":case"running":case"cancelling":case"completed":return"retry-unavailable";default:return pu(t.state)}}function pu(t){throw new N("SCG_WORK_REQUEST_INVALID",`work request state ${String(t)} is unsupported`)}const Oi=t=>Object.freeze({text:t}),Ms=Object.freeze(["이전 실행이 작업 공간을 바꿨을 수 있습니다. 새 요청은 작업을 ",Oi("중복 실행할 수 있습니다"),"."]),le=Object.freeze({previewTitle:"작업 요청 미리보기",previewDescription:"현재 페이지에서 보낼 저장된 메모를 확인하세요.",confirm:"이 메모로 요청",confirming:"요청 중",cancel:"취소",stale:"메모가 바뀌어 최신 목록을 다시 불러왔습니다. 내용을 확인한 뒤 다시 요청하세요.",cancelRequest:"작업 취소",retrySame:"같은 요청 다시 시도",newRequest:"새 요청 만들기",duplicateWarning:zs(Ms)}),Ds="SCG_WORK_REQUEST_INVALID",qs="새로 보낼 메모가 없습니다. 이전 요청이 이미 실행됐을 수 있습니다. 변경 내용을 먼저 확인한 뒤, 추가 작업이 필요하면 메모를 편집하고 미리보기를 다시 여세요.",mu=Object.freeze({SCG_WORK_NO_ELIGIBLE:qs,SCG_WORK_REQUEST_INVALID:"작업 요청을 보내지 못했습니다.",SCG_WORK_PROVIDER_NONE:"작업 제공자가 선택되지 않아 요청을 보내지 못했습니다.",SCG_WORK_PROVIDER_UNREADY:"작업 제공자가 준비되지 않아 요청을 보내지 못했습니다.",SCG_WORK_WARNING_REQUIRED:"권한 경고 확인이 필요해 요청을 보내지 못했습니다.",SCG_WORK_GENERATION_CONFLICT:"작업 제공자 설정이 바뀌어 요청을 보내지 못했습니다.",SCG_WORK_ACTIVE:"이미 진행 중인 작업이 있어 새 요청을 보내지 못했습니다.",SCG_WORK_STALE_PREVIEW:"메모가 바뀌어 이 요청을 보내지 못했습니다."}),wu="작업 요청을 보내지 못했습니다.",_i=Object.freeze({duplicateWarning:Ms,previewDescription:Object.freeze(["현재 페이지에서 보낼 ",Oi("저장된 메모를 확인하세요"),"."]),reconnectingStatus:Object.freeze(["연결이 끊겨 결과를 아직 판단하지 못했습니다. 재연결 뒤 ",Oi("상태를 이어서 확인합니다"),"."])}),vu=Object.freeze({SCG_OMO_CONVERSATION_INCOMPATIBLE:"이 대화는 현재 OMO 런타임과 호환되지 않아 작업을 실행하지 않았습니다. 설정에서 새 세션 시작을 누른 뒤 다시 요청하세요.",SCG_OMO_RUNTIME_AUTHORITY_ABSENT:"이 Scene Glass 빌드에는 승인된 OMO 런타임 정보가 없어 작업을 실행하지 않았습니다.",SCG_OMO_RUNTIME_UNSUPPORTED:"upstream PTY prebuild 지원을 기다리는 동안 이 플랫폼에서 OMO 작업을 실행할 수 없습니다. darwin-arm64에서 실행하거나 다른 작업 제공자를 선택하세요.",SCG_OMO_RUNTIME_MISSING:`승인된 OMO 런타임이 설치되지 않아 작업을 실행하지 않았습니다. 터미널에서 ${Xt}을 실행한 뒤 다시 요청하세요.`,SCG_OMO_RUNTIME_INTEGRITY:"설치된 OMO 런타임이 승인된 파일과 달라 작업을 실행하지 않았습니다.",SCG_RUNTIME_AUTHORITY_ABSENT:"이 Scene Glass 빌드에는 승인된 런타임 정보가 없어 작업을 실행하지 않았습니다.",SCG_RUNTIME_UNSUPPORTED:"이 플랫폼에서 선택한 작업 제공자의 승인된 런타임을 실행할 수 없습니다.",SCG_RUNTIME_MISSING:"승인된 작업 제공자 런타임을 설치한 뒤 다시 요청하세요.",SCG_RUNTIME_INTEGRITY:"설치된 작업 제공자 런타임이 승인된 파일과 달라 작업을 실행하지 않았습니다.",SCG_RUNTIME_VERSION_MISMATCH:"작업 제공자 런타임 버전이 승인된 버전과 다릅니다.",SCG_RUNTIME_CONVERSATION_UNQUALIFIED:"이 대화는 현재 작업 제공자 런타임과 호환성이 확인되지 않았습니다.",SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED:"새 세션을 시작하세요. 기존 대화는 보존됩니다."});function bu(t){const e=wa(t);return Object.freeze(e===null?["작업 실행에 실패했습니다."]:[vu[e],` (${e})`])}function yu(t){return Object.freeze([mu[t]??wu,` (${t})`])}function zs(t){return t.map(e=>typeof e=="string"?e:e.text).join("")}function Eu(t){return`현재 페이지 메모 ${t}개`}function Su(t,e){return`${t}번 · ${e.slice(0,8)}`}function ku(t){if(t===void 0||t.trim()==="")return"저장된 메모";const e=t.replace(/\s+/gu," ").trim();return e.length>96?`${e.slice(0,95)}…`:e}const Cu=new Set(["queued","preparing","dispatching","delivered","running"]);function Iu(t){return Object.freeze({...t})}function Gs(t){const e=Object.freeze({pending:t.pending,reconnecting:t.connection!=="ready"&&t.result!==null&&!xu(t.result.state),failureCode:Ru(t.failureCode)}),i=Au(t.result,e),n=_u(i,e,t.result?.errorCode??null);return Object.freeze({pending:e.pending,phase:i,statusText:zs(n),statusUnits:n,tone:Tu(i),canCancel:e.pending!=="cancelling"&&t.connection==="ready"&&t.result!==null&&Cu.has(t.result.state),retry:e.pending==="cancelling"?"none":Ou(t.result),reconnecting:e.reconnecting,announcementKey:`${i}:${e.reconnecting?"reconnecting":"settled"}`,failureCode:e.failureCode})}function Au(t,e){return e.reconnecting?"indeterminate":e.pending==="cancelling"?"cancelling":t!==null?t.state==="delivered"?"dispatching":t.state:e.pending==="submitting"?"queued":e.failureCode===null?"idle":"request-failed"}function Ou(t){if(t===null)return"none";switch(fu(t)){case"retry-same-request":return"same-request";case"require-new-request":return"new-request";case"retry-unavailable":return"none"}}function _u(t,e,i){if(e.reconnecting)return _i.reconnectingStatus;switch(t){case"idle":return[""];case"request-failed":return yu(e.failureCode??Ds);case"queued":return["작업 요청이 대기열에 들어갔습니다."];case"preparing":return["작업 실행을 준비하고 있습니다."];case"dispatching":return["작업 제공자에게 요청을 전달하고 있습니다."];case"running":return["작업 제공자가 요청을 실행하고 있습니다."];case"cancelling":return["작업 취소 결과를 확인하고 있습니다."];case"completed":return["작업 제공자의 실행이 끝났습니다. 코드가 올바르다는 뜻은 아닙니다."];case"failed":return bu(i);case"cancelled":return["작업이 취소되었습니다."];case"indeterminate":return["작업 결과를 판단하지 못했습니다. 중복 실행을 피하려면 상태를 확인하세요."]}}function Tu(t){switch(t){case"idle":case"cancelled":return"neutral";case"queued":case"preparing":case"dispatching":case"running":case"cancelling":return"info";case"completed":return"positive";case"indeterminate":return"warning";case"failed":case"request-failed":return"danger"}}function Ru(t){return t===null?null:En.find(e=>e===t)??Ds}function xu(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="indeterminate"}function Nu(t){const e=zu(t.clientState);return Object.freeze({work:Mu(t,e),workRequest:Du(t,e),workReview:Pu(t.state,t.pageId),workDiff:Object.freeze({history:t.state.history,comparison:t.state.comparison,pending:!1})})}function Pu(t,e){if(e===null)return null;const i=st(t).find(n=>n.request.page.pageId===e&&n.result.state==="completed"&&n.result.reviewState==="pending");return i===void 0?null:Object.freeze({requestId:i.request.requestId,pending:!0})}function st(t){const e=t.request===null||t.result===null?[]:[Object.freeze({request:t.request,result:t.result,events:t.events})];return nt([...t.history,...e])}function Lt(t){return t.map(({request:e,result:i})=>`${e.requestId}:${i.eventSequence}:${i.state}:${i.reviewState}`).join(`
25
+ `)}function Lu(t){return Object.freeze({pending:t.pending(),conflict:t.conflict(),recovery:t.recovery(),failureCode:t.failureCode()})}function Mu(t,e){return Object.freeze({connection:e,selection:t.state.providerSelection,capabilities:t.state.providerCapabilities,capabilitiesPending:t.state.providerCapabilitiesLoading,readiness:t.state.providerReadiness,session:t.state.providerSession,warningContractVersion:t.state.warningContractVersion,requestState:su(t.state.result?.state??null,t.state.history),eligibleNoteCount:t.eligibleNoteCount===0?0:null,pending:t.provider.pending,conflict:t.provider.conflict,recovery:t.provider.recovery,failureCode:t.provider.failureCode,requestPending:t.flow.pending,requestFailureCode:t.flow.failureCode})}function Du(t,e){const i=Iu({connection:e,result:t.state.result??qu(t.state),pending:t.flow.pending,stale:t.flow.stale,failureCode:t.flow.failureCode});return Object.freeze({preview:t.flow.preview,summaries:new Map(t.annotations.map(n=>[n.id,n.memo])),stale:t.flow.stale,progress:i})}function qu(t){return t.history.find(e=>!Ee(e.result.state))?.result??null}function zu(t){switch(t){case"ready":return"ready";case"booting":case"connecting":return"connecting";case"unavailable":case"access-error":case"destroyed":return"unavailable"}}async function js(t,e){const i=ju(t),n=i.pageId===null?new Map:Es(i.records,i.pageId),s=new Map(t.bindings.map(o=>[o.annotation.id,o.resolution])),r=n.size===0?[]:await Promise.all(t.annotations.map(o=>du(o)));return Object.freeze(t.annotations.map((o,a)=>{const c=s.get(o.id),l=r[a],d=l===void 0?void 0:n.get(l),u=d===void 0?void 0:e?.evidence.get(d.requestId),h=e!==void 0&&i.pageId!==null&&l!==void 0&&d?.phase==="review-pending"&&e.evidence.get(d.requestId)?.classification==="changed"?Qd({projectId:e.projectId,pageId:i.pageId,requestId:d.requestId,annotationVersionDigest:l}):void 0;return Object.freeze({id:o.id,memo:o.memo,resolution:c===void 0?o.resolution.status:c.status==="resolved"?"resolved":c.reason,...c?.status==="resolved"?{element:c.element}:{},...d===void 0?{}:{workCompletion:d},...u===void 0?{}:{codeChangeEvidence:u},...h===void 0||e===void 0?{}:{badgeAttention:Object.freeze({token:h,state:e.store.isDismissed(h)?"seen":"pending"})}})}))}function Gu(t,e){const{token:i,records:n,annotations:s}=t,o=[...Es(n,i.pageId)].filter(([,a])=>a.requestId===i.requestId&&a.phase==="review-pending");return o.length>0&&o.every(([a])=>s.some(({badgeAttention:c})=>c!==void 0&&c.token.projectId===i.projectId&&c.token.pageId===i.pageId&&c.token.requestId===i.requestId&&c.token.annotationVersionDigest===a&&e.isDismissed(c.token)))}function ju(t){return"records"in t?Object.freeze({pageId:t.pageId,records:t.records}):t.request===null||t.result===null?Object.freeze({pageId:null,records:Object.freeze([])}):Object.freeze({pageId:t.request.page.pageId,records:Object.freeze([Object.freeze({request:t.request,result:t.result,events:Object.freeze([])})])})}const Wu=4,Uu=700,Ws=50;function Us(t){return Math.round(Ws*100/t)}function Vs(t={}){const e=t.reversals??Wu,i=t.windowMs??Uu,n=t.minimumLegPx??Ws;let s=0,r=0,o=0,a=0,c=0,l=!1,d=[];const u=()=>{s=0,l=!1,d=[]};return{push(h,f,b){if(!l)return l=!0,r=h,o=f,a=h,c=f,!1;const y=h-a,T=f-c,w=Math.abs(y)>=Math.abs(T)?y:T;if(w===0)return!1;const R=w>0?1:-1;if(s===0)return s=R,a=h,c=f,!1;if(R===s)return a=h,c=f,!1;const x=a-r,G=c-o,M=Math.abs(x)>=Math.abs(G)?x:G;return r=a,o=c,s=R,a=h,c=f,Math.abs(M)<n||(d=[...d,b].filter(v=>b-v<=i),d.length<e)?!1:(u(),!0)},reset:u}}const Bs=[0,60,80,100,120],Fs=80;class Vu{constructor(e){if(this.options=e,this.#t=e.projectId===void 0?null:`scg:overlay-shake:v1:${e.projectId}`,!(this.#t===null||e.storage===null))try{const i=e.storage.getItem(this.#t);if(i===null)return;const n=JSON.parse(i);typeof n=="object"&&n!==null&&"sensitivity"in n&&Object.keys(n).length===1&&$s(n.sensitivity)&&(this.#e=n.sensitivity)}catch(i){if(!(i instanceof Error))throw i}}options;#e=Fs;#t;get sensitivity(){return this.#e}select(e){if(this.#e=e,!(this.#t===null||this.options.storage===null))try{this.options.storage.setItem(this.#t,JSON.stringify({sensitivity:e}))}catch(i){if(!(i instanceof Error))throw i}}}function $s(t){return Bs.some(e=>e===t)}function Ks(){let t=!1,e=0,i;return{get isStarted(){return t},start(n){return t?!1:(t=!0,i=n,!0)},teardown(){return t?(t=!1,i=void 0,!0):!1},emit(n){if(!t||i===void 0)return;const s=Object.freeze({generation:e+=1,kind:n});try{i(s)}catch{}}}}class Bu{emitter=Ks();window;constructor(e={}){this.window=e.window??globalThis.window}start(e){this.emitter.start(e)&&(this.window.addEventListener("pageshow",this.onPageShow),this.emitter.emit("bootstrap"))}teardown(){this.emitter.teardown()&&this.window.removeEventListener("pageshow",this.onPageShow)}onPageShow=()=>{this.emitter.emit("pageshow")}}function Fu(t){return new Bu(t)}const $u="data-scg-id";function Ku(t){return t.type==="attributes"&&t.attributeName===$u}const Hu=75,Yu=1e3;class Xu{window;document;waitForHostReady;quietWindowMs;maximumWaitMs;active;latestGeneration=0;lastSettledGeneration=0;readyGeneration;isTornDown=!1;constructor(e={}){this.window=e.window??globalThis.window,this.document=e.document??this.window.document,this.waitForHostReady=e.waitForHostReady===!0,this.quietWindowMs=Hs(e.quietWindowMs,Hu,"quietWindowMs"),this.maximumWaitMs=Hs(e.maximumWaitMs,Yu,"maximumWaitMs")}notifyReady=(e=this.latestGeneration)=>{if(this.isTornDown||e<this.latestGeneration)return;const i=this.active;if(this.waitForHostReady&&i!==void 0&&i.generation===e){this.finish(i,!0);return}this.readyGeneration=e};waitFor(e,i={}){if(Zu(e),this.isTornDown||i.signal?.aborted===!0||e<this.latestGeneration)return Promise.resolve(!1);if(e===this.latestGeneration){if(this.active!==void 0)return Ys(this.active.promise,i.signal);if(this.lastSettledGeneration===e)return Promise.resolve(!0)}else{const a=this.active;this.latestGeneration=e,this.lastSettledGeneration=0,this.readyGeneration!==e&&(this.readyGeneration=void 0),a!==void 0&&this.finish(a,!1)}if(this.waitForHostReady&&this.readyGeneration===e)return this.lastSettledGeneration=e,Promise.resolve(!0);let n=()=>{};const s=new Promise(a=>{n=a}),r={generation:e,promise:s,resolve:n,cleanup:()=>{},closed:!1};this.active=r;const o=Ys(s,i.signal);return this.waitForHostReady?this.waitForHostSignal(r):this.waitForDomQuiet(r),o}isCurrent(e){return!this.isTornDown&&e===this.latestGeneration}teardown(){this.isTornDown||(this.isTornDown=!0,this.readyGeneration=void 0,this.active!==void 0&&this.finish(this.active,!1))}waitForHostSignal(e){let i;const n=()=>{i!==void 0&&(Ve(this.window,i),i=void 0)};e.cleanup=n;let s=!1;const r=Ti(this.window,()=>{s=!0,i=void 0,this.finish(e,!1)},this.maximumWaitMs);if(r===void 0){this.finish(e,!1);return}if(s||e.closed){Ve(this.window,r);return}i=r}waitForDomQuiet(e){let i,n,s,r,o;const a=()=>{n!==void 0&&(Ve(this.window,n),n=void 0)},c=()=>{r!==void 0&&(Mt(this.window,r),r=void 0),o!==void 0&&(Mt(this.window,o),o=void 0)},l=()=>{a(),c(),s!==void 0&&(Ve(this.window,s),s=void 0);const E=i;i=void 0;try{E?.disconnect()}catch{}},d=()=>!e.closed&&!this.isTornDown&&this.active===e&&e.generation===this.latestGeneration,u=()=>{let E=!1;const w=Xs(this.window,()=>{E=!0,o=void 0,d()&&this.finish(e,!0)});if(w!==void 0){if(E||!d()){Mt(this.window,w);return}o=w}},h=()=>{if(!d()||(a(),r!==void 0||o!==void 0))return;let E=!1;const w=Xs(this.window,()=>{E=!0,r=void 0,d()&&u()});if(w!==void 0){if(E||!d()){Mt(this.window,w);return}r=w}},f=()=>{if(!d())return;a(),c();let E=!1;const w=Ti(this.window,()=>{E=!0,n=void 0,h()},this.quietWindowMs);if(w!==void 0){if(E||!d()){Ve(this.window,w);return}n=w}};e.cleanup=l;let b=!1;const y=Ti(this.window,()=>{b=!0,s=void 0,this.finish(e,!1)},this.maximumWaitMs);if(y===void 0){this.finish(e,!1);return}if(b||e.closed){Ve(this.window,y);return}s=y;const T=this.document.defaultView?.MutationObserver??globalThis.MutationObserver;if(typeof T!="function"){this.finish(e,!1);return}try{const E=new T(w=>{w.every(Ku)||f()});i=E,E.observe(this.document,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),f()}catch{this.finish(e,!1)}}finish(e,i){if(e.closed)return;e.closed=!0,e.cleanup(),this.active===e&&(this.active=void 0);const n=i&&!this.isTornDown&&e.generation===this.latestGeneration;n&&(this.lastSettledGeneration=e.generation),e.resolve(n)}}function Qu(t){return new Xu(t)}function Zu(t){if(!Number.isSafeInteger(t)||t<1)throw new RangeError("generation must be a positive safe integer")}function Hs(t,e,i){const n=t??e;if(!Number.isFinite(n)||n<0)throw new RangeError(`${i} must be a non-negative finite number`);return n}function Ju(t,e){return t===void 0?()=>{}:(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e))}function Ys(t,e){return e===void 0?t:e.aborted?Promise.resolve(!1):new Promise(i=>{let n=!1,s=()=>{};const r=o=>{if(!n){n=!0;try{s()}catch{}i(o)}};if(s=Ju(e,()=>r(!1)),e.aborted){r(!1);return}t.then(o=>r(o),()=>r(!1))})}function Ti(t,e,i){const n=t.setTimeout;if(typeof n=="function")try{return n.call(t,e,i)}catch{return}}function Ve(t,e){try{t.clearTimeout(e)}catch{}}function Xs(t,e){const i=t.requestAnimationFrame;if(typeof i=="function")try{return i.call(t,e)}catch{return}}function Mt(t,e){try{t.cancelAnimationFrame(e)}catch{}}const Be=new WeakMap;class eh{emitter=Ks();window;observeHashChanges;constructor(e={}){this.window=e.window??globalThis.window,this.observeHashChanges=e.observeHashChanges===!0}start(e){if(this.emitter.start(e))try{this.window.addEventListener("popstate",this.onPopState),this.observeHashChanges&&this.window.addEventListener("hashchange",this.onHashChange),ih(this.window,this),this.emitter.emit("bootstrap")}catch(i){const n=[];try{this.window.removeEventListener("popstate",this.onPopState)}catch(s){n.push(s)}if(this.observeHashChanges)try{this.window.removeEventListener("hashchange",this.onHashChange)}catch(s){n.push(s)}try{Qs(this.window,this)}catch(s){n.push(s)}this.emitter.teardown(),er(i,n,"SPA navigation startup rollback failed")}}teardown(){if(!this.emitter.teardown())return;const e=[];try{this.window.removeEventListener("popstate",this.onPopState)}catch(i){e.push(i)}if(this.observeHashChanges)try{this.window.removeEventListener("hashchange",this.onHashChange)}catch(i){e.push(i)}try{Qs(this.window,this)}catch(i){e.push(i)}tr(e,"SPA navigation teardown failed")}emitHistoryNavigation(e){this.emitter.emit(e)}onPopState=()=>{this.emitter.emit("popstate")};onHashChange=()=>{this.emitter.emit("hashchange")}}function th(t){return new eh(t)}function ih(t,e){let i=Be.get(t);if(i!==void 0&&i.adapters.size===0&&(Ri(t,i),i=Be.get(t)),i===void 0){i=nh(t),Be.set(t,i);try{sh(t,i)}catch(n){const s=[];try{Ri(t,i)}catch(r){s.push(r)}er(n,s,"History patch startup rollback failed")}}i.adapters.add(e)}function Qs(t,e){const i=Be.get(t);i===void 0||!i.adapters.delete(e)||i.adapters.size===0&&Ri(t,i)}function nh(t){const e=t.history,i=Object.getOwnPropertyDescriptor(e,"pushState"),n=Object.getOwnPropertyDescriptor(e,"replaceState"),s={adapters:new Set,originalPushState:e.pushState,originalReplaceState:e.replaceState,hadOwnPushState:i!==void 0,hadOwnReplaceState:n!==void 0,originalPushStateDescriptor:i,originalReplaceStateDescriptor:n,pushStateWrapper:function(...r){Reflect.apply(s.originalPushState,this,r),ir(s,"pushstate")},replaceStateWrapper:function(...r){Reflect.apply(s.originalReplaceState,this,r),ir(s,"replacestate")}};return s}function sh(t,e){const i=t.history;if(i.pushState=e.pushStateWrapper,i.pushState!==e.pushStateWrapper)throw new Error("History pushState patch was not installed");if(i.replaceState=e.replaceStateWrapper,i.replaceState!==e.replaceStateWrapper)throw new Error("History replaceState patch was not installed")}function Ri(t,e){const i=t.history,n=Js(()=>i.pushState,()=>Zs(i,"pushState",()=>{i.pushState=e.originalPushState},e.hadOwnPushState,e.originalPushStateDescriptor),e.pushStateWrapper),s=Js(()=>i.replaceState,()=>Zs(i,"replaceState",()=>{i.replaceState=e.originalReplaceState},e.hadOwnReplaceState,e.originalReplaceStateDescriptor),e.replaceStateWrapper);n.resolved&&s.resolved&&Be.get(t)===e&&Be.delete(t),tr([...n.errors,...s.errors],"History patch restoration failed")}function Zs(t,e,i,n,s){if(!n){if(!Reflect.deleteProperty(t,e))throw new Error(`History ${e} patch could not be removed`);return}if(s===void 0)throw new Error(`History ${e} original descriptor is missing`);i(),Object.defineProperty(t,e,s)}function Js(t,e,i){const n=[];let s;try{s=t()}catch(r){return{errors:[r],resolved:!1}}if(s!==i)return{errors:n,resolved:!0};try{e()}catch(r){n.push(r)}try{if(t()!==i)return{errors:n,resolved:!0}}catch(r){return n.push(r),{errors:n,resolved:!1}}return n.length===0&&n.push(new Error("History patch wrapper remains installed after restoration")),{errors:n,resolved:!1}}function er(t,e,i){throw e.length===0?t:new AggregateError([t,...e],i)}function tr(t,e){if(t.length!==0)throw t.length===1?t[0]:new AggregateError(t,e)}function ir(t,e){for(const i of[...t.adapters])i.emitHistoryNavigation(e)}const rh=/^SCG_[A-Z0-9_]{1,80}$/;function oh(t){if(t===null)return ah();const e=t.createElement("output");e.className="scg-ui-status",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.setAttribute("role","status");let i=!1;const n=s=>{if(i)return;const r=nr(s.code),o=ch(s.kind);e.textContent=r===null?o:`${o} (${r})`,e.dataset.state=s.kind,s.kind==="error"?e.setAttribute("role","alert"):e.setAttribute("role","status")};return n({kind:"idle"}),{element:e,set:n,destroy(){i=!0,e.textContent="",e.removeAttribute("data-state"),e.remove()}}}function nr(t){return t!==void 0&&rh.test(t)?t:null}function ah(){return{element:null,set(){},destroy(){}}}function ch(t){switch(t){case"idle":return"Scene Glass 준비됨.";case"working":return"Scene Glass 처리 중…";case"ready":return"Scene Glass 작업 완료.";case"error":return"Scene Glass가 작업을 완료하지 못했습니다."}}function lh(t,e){return t.busy?"측정 동작을 처리 중입니다.":t.available?e==="measure"?"기준 요소를 고른 뒤 다른 요소에 마우스를 올리면 두 요소 사이 간격을 표시합니다. Esc 로 끕니다.":"요소를 클릭하면 가로·세로 크기를 표시합니다. 모퉁이 뱃지를 누르면 패딩과 마진까지 봅니다. Esc 로 끕니다.":"측정 기능 준비 전입니다. 페이지 연결을 확인하세요."}function de(t,e,i=""){const n=t.createElement("button");return n.className=`scg-ui-action ${e}`,n.type="button",n.textContent=i,n}function we(t,...e){const i=t.createElement("div");return i.className="scg-ui-control-cell",i.append(...e),i}function dh(t,e){const i=t.createElement("span");i.className="scg-ui-hint",i.tabIndex=0,i.setAttribute("role","img"),i.textContent="ⓘ";const n=t.createElement("span");return n.className="scg-ui-hint-popover",i.append(n),Dt(i,e),i}function uh(t,e,i){t.addEventListener("mouseenter",e),t.addEventListener("mouseleave",i),t.addEventListener("focus",e),t.addEventListener("blur",i)}function hh(t,e,i){t.removeEventListener("mouseenter",e),t.removeEventListener("mouseleave",i),t.removeEventListener("focus",e),t.removeEventListener("blur",i)}function Dt(t,e){t.setAttribute("aria-label",e);const i=t.querySelector(".scg-ui-hint-popover");i!==null&&(i.textContent=e)}function gh(t,e,i){const n=t.defaultView;if(i===null||n===null)return;const s=e.getBoundingClientRect();i.style.top=`${s.bottom+6}px`,i.style.left=`${Math.max(8,Math.min(s.left,n.innerWidth-i.offsetWidth-8))}px`}class fh{constructor(e,i){this.status=e,this.onActionStateChange=i}status;onActionStateChange;#e=[];#t={};#i=!1;#s;#n=!1;#o=!1;#r=!1;#a=!1;#l=null;#c=!1;#d=null;#u=0;#h=null;#g=0;#f=0;#m=!1;get annotations(){return this.#e}get capabilities(){return this.#t}get diagnosticsOpen(){return this.#i}get badgeAttention(){return this.#s}setBadgeAttention(e){this.#s={...e}}get selectionMode(){return this.#n}get measureMode(){return this.#o}get sizeMode(){return this.#r}get pendingSelectionElement(){return this.#l}get minimized(){return this.#c}get destroyed(){return this.#m}setAnnotations(e){this.#e=e.map(i=>({id:i.id,memo:i.memo,resolution:i.resolution,...i.element===void 0?{}:{element:i.element},...i.workCompletion===void 0?{}:{workCompletion:Object.freeze({...i.workCompletion})},...i.codeChangeEvidence===void 0?{}:{codeChangeEvidence:Object.freeze({...i.codeChangeEvidence})},...i.badgeAttention===void 0?{}:{badgeAttention:Object.freeze({...i.badgeAttention})}}))}setCapabilities(e){this.#t={...e}}setDiagnosticsOpen(e){this.#i=e}setMeasureMode(e){this.#o=e}setSizeMode(e){this.#r=e}setPageReady(e){this.#a=e,!e&&this.#s!==void 0&&(this.#s={...this.#s,pendingCount:0})}setPendingSelectionElement(e){this.#l=e}setMinimized(e,i=!1){this.#c=e,i&&(this.#d=null)}setActionEpoch(e){return e===this.#u?!1:(this.#u=e,this.#s=void 0,this.#h=null,this.#n=!1,!0)}pageActionAvailable(e){return this.#a&&e===!0}applySelectionMode(e){e!==this.#n&&(e?(this.#d=this.#c,this.#c=!0):this.#d!==null&&(this.#c=this.#d,this.#d=null),this.#n=e)}isActionInFlight(){return this.#h?.epoch===this.#u}setUnavailableStatus(e="SCG_CLIENT_UNAVAILABLE"){this.status.set({kind:"error",code:e})}setMemoBlankStatus(){this.status.set({kind:"error",code:"SCG_MEMO_BLANK"})}beginLatestCallback(){return this.#f+=1}ownsLatestCallback(e){return!this.#m&&e===this.#f}setCallbackError(e,i,n){this.ownsLatestCallback(n)&&this.status.set({kind:"error",code:sr(e,i)})}async performAction(e,i,n){const s=Object.freeze({epoch:this.#u,id:this.#g+=1});this.#h=s,this.onActionStateChange(),this.status.set({kind:"working"});try{const r=await e();if(!this.#w(s))return;this.status.set(n?.(r)??{kind:"ready"})}catch(r){this.#w(s)&&this.status.set({kind:"error",code:sr(r,i)})}finally{this.#w(s)&&(this.#h=null,this.onActionStateChange())}}destroy(){this.#m||(this.#m=!0,this.#e=[],this.#f+=1,this.#h=null)}#w(e){return!this.#m&&e.epoch===this.#u&&this.#h?.epoch===e.epoch&&this.#h.id===e.id}}function sr(t,e){if(typeof t=="object"&&t!==null&&"code"in t){const i=t.code;if(typeof i=="string"&&nr(i)!==null)return i}return e}let ph=0;class mh{constructor(e,i,n){this.document=e,this.session=i,this.renderRequested=n,this.selectionButton=de(e,"scg-ui-selection"),this.measureButton=de(e,"scg-ui-measure"),this.sizeButton=de(e,"scg-ui-size"),this.retryButton=de(e,"scg-ui-retry","재연결"),this.diagnosticsButton=de(e,"scg-ui-diagnostics"),this.exportProjectButton=de(e,"scg-ui-export-project","프로젝트 전체 복사"),this.exportPageButton=de(e,"scg-ui-export-page","현재 페이지 복사"),this.deleteAllButton=de(e,"scg-ui-delete-all","현재 페이지 메모 전체 삭제"),this.deleteAllCancelButton=de(e,"scg-ui-delete-all-cancel","전체 삭제 취소"),this.deleteAllCancelButton.hidden=!0;const s=this.#r("현재 페이지의 메모를 모두 삭제합니다.");this.#e=this.#r("페이지의 요소를 클릭해 메모를 달 대상으로 지정합니다."),this.#t=this.#r("기준 요소를 고른 뒤 다른 요소에 마우스를 올리면 두 요소 사이 간격을 표시합니다. Esc 로 끕니다."),this.#i=this.#r("요소를 클릭하면 가로·세로 크기를 표시합니다. 모퉁이 뱃지를 누르면 패딩과 마진까지 봅니다. Esc 로 끕니다.");const r=this.#r("Scene Glass 연결을 다시 시도합니다.");this.#s=this.#r("연결과 환경 진단 정보를 표시합니다.");const o=this.#r("이 프로젝트의 모든 메모를 AI 프롬프트로 만들어 클립보드에 복사합니다."),a=this.#r("현재 페이지의 메모로 AI 프롬프트를 만들어 클립보드에 복사합니다.");this.element=e.createElement("div"),this.element.className="scg-ui-controls",this.element.append(we(e,this.selectionButton,this.#e),we(e,this.exportPageButton,a),we(e,this.measureButton,this.#t),we(e,this.sizeButton,this.#i),we(e,this.retryButton,r),we(e,this.exportProjectButton,o),we(e,this.diagnosticsButton,this.#s),we(e,this.deleteAllButton,this.deleteAllCancelButton,s));const c=`scg-ui-prompt-${ph++}`;this.promptToggle=e.createElement("button"),this.promptToggle.className="scg-ui-prompt-toggle",this.promptToggle.type="button",this.promptToggle.setAttribute("aria-controls",c),this.promptOutput=e.createElement("textarea"),this.promptOutput.className="scg-ui-generated-prompt",this.promptOutput.id=c,this.promptOutput.readOnly=!0,this.promptOutput.rows=6,this.promptOutput.setAttribute("aria-label","생성된 프롬프트"),this.promptToggle.addEventListener("click",this.#l)}document;session;renderRequested;element;promptToggle;promptOutput;selectionButton;measureButton;sizeButton;retryButton;diagnosticsButton;exportProjectButton;exportPageButton;deleteAllButton;deleteAllCancelButton;#e;#t;#i;#s;#n=[];#o=!1;bindHint(e){this.#n.push(e),uh(e,this.#c,this.#d)}render(e){const i=this.session.selectionMode?"선택 모드를 종료합니다.":"페이지의 요소를 클릭해 메모를 달 대상으로 지정합니다.";this.selectionButton.textContent=this.session.selectionMode?"선택 종료":"요소 선택",Dt(this.#e,i),this.selectionButton.setAttribute("aria-pressed",String(this.session.selectionMode)),this.#a(this.measureButton,this.#t,"measure"),this.#a(this.sizeButton,this.#i,"size"),this.diagnosticsButton.textContent=this.session.diagnosticsOpen?"진단 닫기":"진단 열기",Dt(this.#s,this.session.diagnosticsOpen?"진단 패널을 닫습니다.":"연결과 환경 진단 정보를 표시합니다."),this.deleteAllButton.textContent=e?"정말 전체 삭제? 다시 클릭":"현재 페이지 메모 전체 삭제",this.deleteAllButton.dataset.confirming=String(e),this.deleteAllCancelButton.hidden=!e,this.promptToggle.textContent=`${this.#o?"▾":"▸"} 생성된 프롬프트`,this.promptToggle.setAttribute("aria-expanded",String(this.#o)),this.promptOutput.hidden=!this.#o}setDisabled(){const e=this.session.isActionInFlight(),i=this.session.capabilities;this.selectionButton.disabled=e||!this.session.pageActionAvailable(i.canSelect),this.measureButton.disabled=e||!this.session.pageActionAvailable(i.canMeasure),this.sizeButton.disabled=e||!this.session.pageActionAvailable(i.canInspectSize),this.retryButton.disabled=e||i.canRetry!==!0,this.diagnosticsButton.disabled=e||!this.session.diagnosticsOpen&&i.canOpenDiagnostics!==!0,this.exportProjectButton.disabled=e||i.canExportProject!==!0,this.exportPageButton.disabled=e||!this.session.pageActionAvailable(i.canExportCurrentPage),this.deleteAllButton.disabled=e||this.session.annotations.length===0||!this.session.pageActionAvailable(i.canDeleteAllCurrentPage),this.deleteAllCancelButton.disabled=e}requestRender(){this.renderRequested()}showPrompt(e){this.promptOutput.value=e,this.#o=!0}resetTransient(){this.promptOutput.value=""}destroy(){this.promptToggle.removeEventListener("click",this.#l);for(const e of this.#n)hh(e,this.#c,this.#d);this.#n.length=0,this.resetTransient()}#r(e){const i=dh(this.document,e);return this.bindHint(i),i}#a(e,i,n){const s=n==="measure",r=s?this.session.measureMode:this.session.sizeMode;e.textContent=r?s?"거리 측정 종료":"크기 측정 종료":s?"거리 측정":"크기 측정",e.setAttribute("aria-pressed",String(r));const o=this.session.pageActionAvailable(s?this.session.capabilities.canMeasure:this.session.capabilities.canInspectSize);Dt(i,lh({available:o,busy:this.session.isActionInFlight()},n))}#l=()=>{this.#o=!this.#o,this.renderRequested()};#c=e=>this.#u(e,!0);#d=e=>this.#u(e,!1);#u(e,i){const n=e.currentTarget;n.classList.toggle("scg-ui-hint--open",i),i&&gh(this.document,n,n.querySelector(".scg-ui-hint-popover"))}}class wh{constructor(e,i,n){this.session=e,this.controls=i,this.delegate=n,i.selectionButton.addEventListener("click",this.#t),i.measureButton.addEventListener("click",this.#i),i.sizeButton.addEventListener("click",this.#s),i.retryButton.addEventListener("click",this.#a),i.diagnosticsButton.addEventListener("click",this.#l),i.exportProjectButton.addEventListener("click",this.#c),i.exportPageButton.addEventListener("click",this.#d),i.deleteAllButton.addEventListener("click",this.#o),i.deleteAllCancelButton.addEventListener("click",this.#r)}session;controls;delegate;#e=!1;get deleteConfirming(){return this.#e}reconcile(){this.session.annotations.length===0&&(this.#e=!1)}resetTransient(){this.#e=!1}destroy(){const e=this.controls;e.selectionButton.removeEventListener("click",this.#t),e.measureButton.removeEventListener("click",this.#i),e.sizeButton.removeEventListener("click",this.#s),e.retryButton.removeEventListener("click",this.#a),e.diagnosticsButton.removeEventListener("click",this.#l),e.exportProjectButton.removeEventListener("click",this.#c),e.exportPageButton.removeEventListener("click",this.#d),e.deleteAllButton.removeEventListener("click",this.#o),e.deleteAllCancelButton.removeEventListener("click",this.#r)}#t=()=>this.#n("selection");#i=()=>this.#n("measure");#s=()=>this.#n("size");#n(e){const i=e==="selection"?this.session.capabilities.canSelect:e==="measure"?this.session.capabilities.canMeasure:this.session.capabilities.canInspectSize;if(!this.session.pageActionAvailable(i)){this.session.setUnavailableStatus("SCG_PAGE_UNREADY");return}if(!this.delegate.available(e)){this.session.setUnavailableStatus();return}const n=e==="selection"?!this.session.selectionMode:e==="measure"?!this.session.measureMode:!this.session.sizeMode,s=e==="selection"?"SCG_CLIENT_SELECTION_FAILED":e==="measure"?"SCG_CLIENT_MEASURE_FAILED":"SCG_CLIENT_SIZE_FAILED";this.session.performAction(()=>this.delegate.dispatch({kind:e,active:n}),s,()=>{e==="selection"?this.session.applySelectionMode(n):e==="measure"?this.session.setMeasureMode(n):this.session.setSizeMode(n),this.controls.requestRender()})}#o=()=>{if(!(this.session.destroyed||this.session.isActionInFlight()||!this.session.pageActionAvailable(this.session.capabilities.canDeleteAllCurrentPage))){if(!this.delegate.available("delete-all")){this.session.setUnavailableStatus();return}if(!this.#e){this.#e=!0,this.controls.requestRender();return}this.session.performAction(()=>this.delegate.dispatch({kind:"delete-all"}),"SCG_CLIENT_DELETE_FAILED").finally(()=>{this.#e=!1,this.controls.requestRender()})}};#r=()=>{this.session.isActionInFlight()||(this.#e=!1,this.controls.requestRender())};#a=()=>{if(this.session.capabilities.canRetry!==!0||!this.delegate.available("retry")){this.session.setUnavailableStatus();return}this.session.performAction(()=>this.delegate.dispatch({kind:"retry"}),"SCG_CLIENT_RETRY_FAILED")};#l=()=>{if(this.session.diagnosticsOpen){this.session.performAction(()=>{if(!this.delegate.available("close-diagnostics")){this.session.setUnavailableStatus();return}return this.delegate.dispatch({kind:"close-diagnostics"})},"SCG_CLIENT_DIAGNOSTICS_FAILED");return}if(this.session.capabilities.canOpenDiagnostics!==!0||!this.delegate.available("open-diagnostics")){this.session.setUnavailableStatus();return}this.session.performAction(()=>this.delegate.dispatch({kind:"open-diagnostics"}),"SCG_CLIENT_DIAGNOSTICS_FAILED")};#c=()=>this.#u("project");#d=()=>this.#u("page");#u(e){const i=e==="page",n=i?"export-page":"export-project";if(!(i?this.session.pageActionAvailable(this.session.capabilities.canExportCurrentPage):this.session.capabilities.canExportProject===!0)){this.session.setUnavailableStatus(i?"SCG_PAGE_UNREADY":void 0);return}if(!this.delegate.available(n)){this.session.setUnavailableStatus();return}this.session.performAction(async()=>vh(await this.delegate.dispatch({kind:n})),"SCG_CLIENT_EXPORT_FAILED",({markdown:r,copied:o})=>(typeof r=="string"&&this.controls.showPrompt(r),o?{kind:"ready",code:"SCG_CLIPBOARD_COPIED"}:void 0))}}async function vh(t){if(typeof t!="string")return{markdown:t,copied:!1};try{if(typeof navigator.clipboard?.writeText=="function")return await navigator.clipboard.writeText(t),{markdown:t,copied:!0}}catch{}return{markdown:t,copied:!1}}class bh{constructor(e,i,n){this.document=e,this.actions=i,this.changed=n,this.toggle=e.createElement("button"),this.toggle.className="scg-ui-annotations-toggle",this.toggle.type="button",this.list=e.createElement("ul"),this.list.className="scg-ui-annotations",this.list.id=`scg-ui-annotations-${rr++}`,this.toggle.setAttribute("aria-controls",this.list.id),this.orphanToggle=e.createElement("button"),this.orphanToggle.className="scg-ui-orphans-toggle",this.orphanToggle.type="button",this.orphanList=e.createElement("ul"),this.orphanList.className="scg-ui-orphans",this.orphanList.id=`scg-ui-orphans-${rr++}`,this.orphanToggle.setAttribute("aria-controls",this.orphanList.id),this.toggle.addEventListener("click",this.#i),this.orphanToggle.addEventListener("click",this.#s)}document;actions;changed;toggle;list;orphanToggle;orphanList;#e=!1;#t=!1;revealResolved(){this.#e||(this.#e=!0,this.changed())}render(e,i){const n=e.filter(({resolution:o})=>o==="resolved"),s=e.filter(({resolution:o})=>o!=="resolved"),r=this.#a();this.toggle.textContent=`${this.#e?"▾":"▸"} 메모 (${or(n)})`,this.toggle.setAttribute("aria-expanded",String(this.#e)),this.list.hidden=!this.#e,this.orphanToggle.hidden=s.length===0,this.orphanList.hidden=s.length===0||!this.#t,this.orphanToggle.textContent=`${this.#t?"▾":"▸"} 유실 데이터 (${or(s)})`,this.orphanToggle.setAttribute("aria-expanded",String(this.#t)),this.list.replaceChildren(...n.map((o,a)=>this.#n(o,a+1,i))),this.orphanList.replaceChildren(...s.map(o=>this.#o(o,i))),this.#l(r)}setDisabled(e){for(const i of this.list.querySelectorAll(".scg-ui-edit-memo"))i.disabled=e.edit;for(const i of this.orphanList.querySelectorAll(".scg-ui-edit-memo"))i.disabled=e.edit;for(const i of this.list.querySelectorAll(".scg-ui-delete-memo"))i.disabled=e.delete;for(const i of this.orphanList.querySelectorAll(".scg-ui-delete-memo"))i.disabled=e.delete}destroy(){this.toggle.removeEventListener("click",this.#i),this.orphanToggle.removeEventListener("click",this.#s),this.list.replaceChildren(),this.orphanList.replaceChildren()}#i=()=>{this.#e=!this.#e,this.changed()};#s=()=>{this.#t=!this.#t,this.changed()};#n(e,i,n){const s=this.#r(e),r=this.document.createElement("span");r.className="scg-ui-annotation-ordinal",r.textContent=String(i),r.setAttribute("aria-hidden","true");const o=this.document.createElement("div");o.className="scg-ui-annotation-body";const a=this.document.createElement("code");a.className="scg-ui-annotation-target",a.textContent=e.element?.localName.toLowerCase()??"",a.hidden=e.element===void 0;const c=this.document.createElement("p");c.className="scg-ui-annotation-memo";const l=this.document.createElement("button");return l.className="scg-ui-annotation-scroll",l.type="button",l.textContent=e.memo,l.title=e.memo,l.disabled=e.element===void 0,l.addEventListener("click",()=>{l.focus({preventScroll:!0}),e.badgeAttention!==void 0&&this.actions.dismissBadgeAttention?.(e.badgeAttention.token),this.actions.scroll(e)}),c.append(l),o.append(a,c,this.#c(ar(e,!1))),this.#d(o,e),s.append(r,o,this.#u(e,n)),s}#o(e,i){const n=this.#r(e),s=this.document.createElement("div");s.className="scg-ui-annotation-body";const r=this.document.createElement("p");return r.className="scg-ui-annotation-memo",r.textContent=e.memo,r.title=e.memo,s.append(r,this.#c(ar(e,!0))),this.#d(s,e),n.append(s,this.#u(e,i)),n}#r(e){const i=this.document.createElement("li");return i.className="scg-ui-annotation",i.dataset.annotationId=e.id,i.dataset.resolution=e.resolution,e.workCompletion!==void 0&&(i.dataset.workRequestId=e.workCompletion.requestId,i.dataset.workCompletion=e.workCompletion.phase),i}#a(){const e=this.document.activeElement;if(e===null)return null;const n=[...this.list.querySelectorAll(".scg-ui-annotation"),...this.orphanList.querySelectorAll(".scg-ui-annotation")].find(r=>r.contains(e)),s=yh.find(r=>e.className.split(/\s+/u).includes(r));return n?.dataset.annotationId===void 0||s===void 0?null:Object.freeze({annotationId:n.dataset.annotationId,actionClass:s})}#l(e){if(e===null)return;[...this.list.querySelectorAll(".scg-ui-annotation"),...this.orphanList.querySelectorAll(".scg-ui-annotation")].find(({dataset:n})=>n.annotationId===e.annotationId)?.querySelector(`.${e.actionClass}`)?.focus()}#c(e){const i=this.document.createElement("span");return i.className="scg-ui-annotation-resolution",i.textContent=e,i}#d(e,i){const n=i.badgeAttention?.state??i.codeChangeEvidence?.classification;if(n===void 0||n==="changed")return;const s=this.document.createElement("p");s.className="scg-ui-annotation-attention scg-ui-annotation-memo",s.dataset.attentionState=n,s.textContent=Eh[n],s.style.wordBreak="keep-all",e.append(s)}#u(e,i){const n=this.document.createElement("button");n.className="scg-ui-action scg-ui-copy-memo",n.type="button",n.textContent="복사",n.setAttribute("aria-label","메모 복사"),n.addEventListener("click",()=>this.actions.copy(e));const s=this.document.createElement("button");s.className="scg-ui-action scg-ui-edit-memo",s.type="button",s.textContent="수정",s.disabled=i.edit,s.addEventListener("click",()=>this.actions.edit(e));const r=this.document.createElement("button");r.className="scg-ui-action scg-ui-delete-memo",r.type="button",r.textContent="삭제",r.disabled=i.delete,r.addEventListener("click",()=>this.actions.delete(e));const o=this.document.createElement("div");return o.className="scg-ui-annotation-actions",o.append(n,s,r),o}}let rr=0;const yh=Object.freeze(["scg-ui-annotation-scroll","scg-ui-copy-memo","scg-ui-edit-memo","scg-ui-delete-memo"]),Eh={pending:`코드 변경 확인 대기
26
+ 모두 확인하면 요청 검토 완료`,seen:`코드 변경 확인됨
27
+ 모두 확인하면 요청 검토 완료`,unchanged:"확인된 코드 변경 없음",unknown:`코드 변경 확인 불가
28
+ 작업 실패와 별개`};function or(t){const e=t.filter(({workCompletion:i})=>i!==void 0).length;return`${t.length}${e===0?"":` · 작업 완료 ${e}`}`}function ar(t,e){const i=t.workCompletion?.phase;return i===void 0?e?"검토 필요":"연결됨":`작업 실행 완료 · ${i==="review-pending"?"검토 대기":"검토됨"}${e?" · 요소 유실":""}`}class Sh{constructor(e,i,n){this.document=e,this.actions=i,this.schedulePosition=n,e.addEventListener("click",this.#c),e.addEventListener("keydown",this.#d)}document;actions;schedulePosition;#e=null;#t=new Map;#i=null;#s=!1;get element(){return this.#e}mount(){this.#s||this.document.body===null||(this.#e===null&&(this.#e=this.document.createElement("div"),this.#e.className="scg-ui-badges"),this.#e.parentElement===null&&this.document.body.append(this.#e))}rebuild(e,i){if(this.mount(),this.#e===null)return;const n=e.filter(c=>c.resolution==="resolved"&&c.element!==void 0),s=new Set(n.map(({id:c})=>c));for(const[c,l]of this.#t)s.has(c)||(l.button.remove(),this.#t.delete(c));const r=n.map((c,l)=>{const d=this.#t.get(c.id)??this.#n(c);return this.#t.set(c.id,d),this.#o(d,c,l+1),d.button}),o=[...this.#e.querySelectorAll(".scg-ui-badge")],a=r.findIndex((c,l)=>c!==o[l]);if(a!==-1)for(const c of r.slice(a))c.parentElement===this.#e?this.#e.moveBefore(c,null):this.#e.append(c);this.#i!==null&&!s.has(this.#i)&&(this.#i=null),this.#a(this.#i),this.setDisabled(i),this.schedulePosition()}setDisabled(e){for(const i of this.#e?.querySelectorAll(".scg-ui-badge-edit")??[])i.disabled=e.edit;for(const i of this.#e?.querySelectorAll(".scg-ui-badge-delete")??[])i.disabled=e.delete}position(){if(this.#s||this.#e===null)return;const e=this.document.documentElement.clientWidth,i=this.document.documentElement.clientHeight;for(const{annotation:n,button:s}of this.#t.values()){const r=n.element,o=r.getBoundingClientRect();if(!(this.document.documentElement?.contains(r)===!0)||o.width===0||o.height===0||o.right<=0||o.bottom<=0||o.left>=e||o.top>=i){s.hidden=!0;continue}s.hidden=!1,s.style.left=`${Math.max(8,Math.min(o.left-8,e-s.offsetWidth-8))}px`,s.style.top=`${Math.max(8,Math.min(o.top-8,i-s.offsetHeight-8))}px`,s.classList.contains("scg-ui-badge--open")&&this.#l(s)}}destroy(){this.#s||(this.#s=!0,this.document.removeEventListener("click",this.#c),this.document.removeEventListener("keydown",this.#d),this.#t.clear(),this.#e?.remove(),this.#e=null,this.#i=null)}#n(e){const i=this.document.createElement("button");i.className="scg-ui-badge",i.type="button",i.dataset.scgBadgeFor=e.id,i.setAttribute("aria-expanded","false");const n=this.document.createElement("span");i.append(n);const s=this.document.createElement("span");s.className="scg-ui-badge-popover";const r=this.document.createElement("code");r.className="scg-ui-badge-target";const o=this.document.createElement("span");o.className="scg-ui-badge-memo";const a={annotation:e,button:i,number:n,target:r,memo:o};i.addEventListener("click",()=>{const u=a.annotation,h=u.badgeAttention,f=this.#i!==u.id;h!==void 0&&this.actions.dismissBadgeAttention?.(h.token),this.#a(f?u.id:null),f&&this.actions.scroll(u)});const c=this.#r("scg-ui-badge-edit","수정",()=>{this.#a(e.id),this.actions.edit(a.annotation)}),l=this.#r("scg-ui-badge-delete","삭제",()=>this.actions.delete(a.annotation)),d=this.document.createElement("span");return d.className="scg-ui-badge-actions",d.append(c,l),s.append(r,o,d),s.addEventListener("click",u=>u.stopPropagation()),i.append(s),a}#o(e,i,n){e.annotation=i,e.number.textContent=String(n),e.target.textContent=i.element.localName.toLowerCase(),e.memo.textContent=kh(i.memo),e.memo.title=i.memo;const s=e.button,r=i.workCompletion;r===void 0?(delete s.dataset.workRequestId,delete s.dataset.workCompletion):(s.dataset.workRequestId=r.requestId,s.dataset.workCompletion=r.phase);const o=i.badgeAttention;o===void 0?delete s.dataset.badgeAttention:s.dataset.badgeAttention=o.state;const a=r===void 0?"":` · 작업 실행 완료 · ${r.phase==="review-pending"?"검토 대기":"검토됨"}`;s.setAttribute("aria-label",`메모 ${n}: ${i.memo}${a}`),o===void 0?s.removeAttribute("aria-description"):s.setAttribute("aria-description",o.state==="pending"?"코드 변경 확인 대기 · 이 뱃지를 눌러 확인합니다. 모두 확인하면 요청 검토가 완료됩니다.":"코드 변경 확인함 · 모두 확인하면 요청 검토가 완료됩니다. 검토 대기 중이면 눌러 다시 시도합니다.")}#r(e,i,n){const s=this.document.createElement("button");return s.className=`scg-ui-action ${e}`,s.type="button",s.textContent=i,s.addEventListener("click",r=>{r.stopPropagation(),n()}),s}#a(e){this.#i=e;for(const i of this.#e?.querySelectorAll(".scg-ui-badge")??[]){const n=i.dataset.scgBadgeFor===e;i.classList.toggle("scg-ui-badge--open",n),i.setAttribute("aria-expanded",String(n)),n&&this.#l(i)}}#l(e){const i=e.querySelector(".scg-ui-badge-popover"),n=this.document.defaultView;if(i===null||n===null)return;const s=e.getBoundingClientRect();i.style.top=`${s.bottom+6}px`,i.style.left=`${Math.max(8,Math.min(s.left,n.innerWidth-i.offsetWidth-8))}px`}#c=e=>{this.#i!==null&&e.target instanceof Node&&!this.#e?.contains(e.target)&&this.#a(null)};#d=e=>{if(e.key!=="Escape"||this.#i===null)return;const i=[...this.#e?.querySelectorAll(".scg-ui-badge")??[]].find(n=>n.dataset.scgBadgeFor===this.#i);this.#a(null),i?.focus()}}function kh(t){return t.length>160?`${t.slice(0,159)}…`:t}class Ch{constructor(e){if(this.options=e,this.#i=e.projectId===void 0?null:`scg:overlay-settings:v1:${e.projectId}`,!(this.#i===null||e.storage===null))try{const i=e.storage.getItem(this.#i);if(i!==null){const n=JSON.parse(i);if(typeof n!="object"||n===null||!("side"in n)||Object.keys(n).length!==1||n.side!=="left"&&n.side!=="right")return;this.#e=n.side}this.#t=!0}catch(i){if(!(i instanceof Error))throw i;this.#t=!1}}options;#e="right";#t=!1;#i;get side(){return this.#e}get persistenceAvailable(){return this.#t}select(e){if(this.#e=e,!(this.#i===null||this.options.storage===null))try{this.options.storage.setItem(this.#i,JSON.stringify({side:e})),this.#t=!0}catch(i){if(!(i instanceof Error))throw i;this.#t=!1}}}function Ih(t){try{return t.defaultView?.localStorage??null}catch(e){if(!(e instanceof Error))throw e;return null}}let Ah=0;class Oh{constructor(e){this.options=e;const i=e.document,n=String(++Ah);this.toggle=i.createElement("button"),this.toggle.className="scg-ui-settings-toggle",this.toggle.type="button",this.toggle.setAttribute("aria-label","설정"),this.toggle.title="설정";const s=i.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("fill","currentColor"),s.setAttribute("aria-hidden","true"),s.setAttribute("focusable","false");const r=i.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"),s.append(r),this.toggle.append(s),this.toggle.id=`scg-ui-settings-toggle-${n}`,this.toggle.setAttribute("aria-expanded","false"),this.element=i.createElement("section"),this.element.className="scg-ui-settings",this.element.id=`scg-ui-settings-${n}`,this.element.hidden=!0,this.element.setAttribute("role","region"),this.element.setAttribute("aria-labelledby",this.toggle.id),this.toggle.setAttribute("aria-controls",this.element.id);const o=i.createElement("label");o.className="scg-ui-work-provider-label",o.textContent="패널 위치",this.#e=i.createElement("select"),this.#e.className="scg-ui-work-setting-select scg-ui-settings-side",this.#e.id=`scg-ui-settings-side-${n}`,o.htmlFor=this.#e.id;for(const[c,l]of[["left","왼쪽"],["right","오른쪽"]]){const d=i.createElement("option");d.value=c,d.textContent=l,this.#e.append(d)}this.#e.value=e.preferences.side,this.#s=i.createElement("p"),this.#s.className="scg-ui-settings-notice scg-ui-settings-persistence",this.#s.id=`scg-ui-settings-persistence-${n}`,this.#s.setAttribute("role","status"),this.#e.setAttribute("aria-describedby",this.#s.id),this.#l();const a=i.createElement("label");a.className="scg-ui-work-provider-label",a.textContent="흔들기 민감도",this.#t=i.createElement("select"),this.#t.className="scg-ui-work-setting-select scg-ui-settings-shake",this.#t.id=`scg-ui-settings-shake-${n}`,a.htmlFor=this.#t.id;for(const c of Bs){const l=i.createElement("option");l.value=String(c),l.textContent=c===0?"끄기":`${c}%`,this.#t.append(l)}this.#i=new Vu(e.shakeScope),this.#t.value=String(this.#i.sensitivity),e.onShakeSensitivityChange?.(this.#i.sensitivity),this.element.append(o,this.#e,this.#s,a,this.#t,e.configurationElement),this.toggle.addEventListener("click",this.#n),this.#e.addEventListener("change",this.#o),this.#t.addEventListener("change",this.#r),i.addEventListener("keydown",this.#a)}options;element;toggle;#e;#t;#i;#s;close(e=!0){this.element.hidden||(this.element.hidden=!0,this.toggle.setAttribute("aria-expanded","false"),this.options.onScreenChange(!1),e&&this.toggle.focus({preventScroll:!0}))}destroy(){this.options.document.removeEventListener("keydown",this.#a),this.toggle.removeEventListener("click",this.#n),this.#e.removeEventListener("change",this.#o),this.#t.removeEventListener("change",this.#r),this.element.remove(),this.toggle.remove()}#n=()=>{if(!this.element.hidden){this.close();return}this.element.hidden=!1,this.toggle.setAttribute("aria-expanded","true"),this.options.onScreenChange(!0),this.#e.focus({preventScroll:!0}),this.options.onCapabilitiesRead()};#o=()=>{const e=this.#e.value;e!=="left"&&e!=="right"||(this.options.preferences.select(e),this.options.onSideChange(e),this.#l())};#r=()=>{const e=Number(this.#t.value);$s(e)&&(this.#i.select(e),this.options.onShakeSensitivityChange?.(e))};#a=e=>{e.key!=="Escape"||this.element.hidden||(e.preventDefault(),e.stopPropagation(),this.close())};#l(){this.#s.hidden=this.options.preferences.persistenceAvailable,this.#s.dataset.persistence=this.options.preferences.persistenceAvailable?"available":"unavailable",this.#s.textContent=this.options.preferences.persistenceAvailable?"":"위치는 현재 화면에만 적용됩니다. 저장소를 사용할 수 없습니다."}}class _h{constructor(e,i,n){this.document=e,this.session=i,this.delegate=n,this.element=e.createElement("aside"),this.element.className="scg-ui-overlay",this.element.tabIndex=-1,this.element.setAttribute("aria-label","Scene Glass 메모 제어");const s=e.createElement("h2");s.className="scg-ui-heading",s.textContent="Scene Glass";const r=e.createElement("button");r.className="scg-ui-minimize",r.type="button",r.setAttribute("aria-label","미니마이즈"),r.textContent="−",this.headingRow=e.createElement("div"),this.headingRow.className="scg-ui-heading-row",this.headingRow.append(s,r),this.launcher=Th(e),r.addEventListener("click",this.#l),this.launcher.addEventListener("pointerdown",this.#c),this.launcher.addEventListener("pointermove",this.#u),this.launcher.addEventListener("pointerup",this.#h),this.launcher.addEventListener("pointercancel",this.#h),this.launcher.addEventListener("click",this.#g)}document;session;delegate;element;headingRow;launcher;#e=null;#t=null;#i=!1;#s=!1;#n;#o=!1;#r=null;configureSettings(e,i,n){const s={...e.projectId===void 0?{}:{projectId:e.projectId},storage:e.preferenceStorage===void 0?Ih(this.document):e.preferenceStorage},r=new Ch(s);this.#r=new Oh({document:this.document,configurationElement:i,preferences:r,shakeScope:s,onCapabilitiesRead:n,onSideChange:a=>this.#a(a),onShakeSensitivityChange:e.onShakeSensitivityChange,onScreenChange:a=>this.element.classList.toggle("scg-ui-overlay--settings",a)});const o=this.headingRow.querySelector(".scg-ui-minimize");this.headingRow.insertBefore(this.#r.toggle,o),this.#a(r.side)}closeSettings(e=!0){this.#r?.close(e)}append(...e){this.element.append(this.headingRow),this.#r!==null&&this.element.append(this.#r.element),this.element.append(...e)}#a(e){this.element.dataset.scgSide=e,this.launcher.dataset.scgSide=e,this.#e=null;for(const i of["left","top","right","bottom"])this.launcher.style.removeProperty(i)}applySelectionMode(e){this.session.applySelectionMode(e)}render(e){(this.session.minimized||e)&&(this.delegate.closeWarning(),this.closeSettings(!this.session.minimized));const i=this.session.minimized&&e;this.element.hidden=this.session.minimized&&!i,this.element.classList.toggle("scg-ui-overlay--composer-only",i),this.launcher.hidden=!this.session.minimized,this.#e!==null&&this.#f(this.#e.x,this.#e.y)}continueOwnedPointerDown(e){this.#d(e)}destroy(){if(this.#o)return;this.#o=!0,this.headingRow.querySelector(".scg-ui-minimize")?.removeEventListener("click",this.#l),this.launcher.removeEventListener("pointerdown",this.#c),this.launcher.removeEventListener("pointermove",this.#u),this.launcher.removeEventListener("pointerup",this.#h),this.launcher.removeEventListener("pointercancel",this.#h),this.launcher.removeEventListener("click",this.#g),this.#t!==null&&this.launcher.hasPointerCapture(this.#t.pointerId)&&this.launcher.releasePointerCapture(this.#t.pointerId),this.#t=null,this.#n!==void 0&&(clearTimeout(this.#n),this.#n=void 0),this.#r?.destroy(),this.element.replaceChildren(),this.element.remove(),this.launcher.remove()}#l=()=>{this.session.setMinimized(!0,!0),this.delegate.renderRequested(),this.launcher.focus({preventScroll:!0})};#c=e=>this.#d(e);#d(e){if(e.button!==0)return;const i=this.launcher.getBoundingClientRect();this.#t={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,launcherX:i.left,launcherY:i.top},this.#i=!1,this.launcher.setPointerCapture(e.pointerId)}#u=e=>{if(this.#t===null||e.pointerId!==this.#t.pointerId)return;const i=e.clientX-this.#t.startX,n=e.clientY-this.#t.startY;!this.#i&&i*i+n*n>16&&(this.#i=!0,this.launcher.classList.add("scg-ui-launcher--dragging")),this.#i&&(e.preventDefault(),this.#f(this.#t.launcherX+i,this.#t.launcherY+n))};#h=e=>{if(this.#t===null||e.pointerId!==this.#t.pointerId)return;const i=this.#i;this.#t=null,this.#i=!1,this.launcher.classList.remove("scg-ui-launcher--dragging"),this.launcher.hasPointerCapture(e.pointerId)&&this.launcher.releasePointerCapture(e.pointerId),i&&(this.#s=!0,this.#n=setTimeout(()=>{this.#s=!1,this.#n=void 0},0))};#g=e=>{if(this.#s){e.preventDefault(),e.stopPropagation(),this.#s=!1,this.#n!==void 0&&(clearTimeout(this.#n),this.#n=void 0);return}this.session.setMinimized(!1,!0),this.delegate.renderRequested(),(this.#r?.toggle??this.element).focus({preventScroll:!0})};#f(e,i){const n=this.document.defaultView,s={x:Math.min(Math.max(0,e),Math.max(0,(n?.innerWidth??42)-42)),y:Math.min(Math.max(0,i),Math.max(0,(n?.innerHeight??42)-42))};this.#e=s,this.launcher.style.left=`${s.x}px`,this.launcher.style.top=`${s.y}px`,this.launcher.style.right="auto",this.launcher.style.bottom="auto"}}function Th(t){const e=t.createElement("button");e.className="scg-ui-launcher",e.type="button",e.setAttribute("aria-label","Scene Glass 열기"),e.hidden=!0;const i=t.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("aria-hidden","true"),i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2.5");const n=t.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","10.5"),n.setAttribute("cy","10.5"),n.setAttribute("r","5.5");const s=t.createElementNS("http://www.w3.org/2000/svg","path");return s.setAttribute("d","m15 15 5 5"),i.append(n,s),e.append(i),e}class Rh{constructor(e,i,n){this.document=e,this.shell=i,this.delegate=n;const s=e.defaultView??e;for(const o of["pointerdown","mousedown","touchstart"])ue(this.#c,[s,o,this.#m,!0]);for(const o of["focusin","focusout"])ue(this.#c,[s,o,this.#w,!0]);const r=e.defaultView;r!==null&&(ue(this.#c,[r,"scroll",this.#u,!0]),ue(this.#c,[r,"resize",this.#u,!1]))}document;shell;delegate;#e=null;#t=[];#i=!1;#s=!1;#n;#o=null;#r=null;#a=null;#l;#c=[];#d=!1;open(e,i){if(this.#d||this.#s||(this.#e=e,this.#t=i,this.#i=!0,this.#b()))return;ue(this.#c,[this.document,"DOMContentLoaded",this.#p,!1]),ue(this.#c,[this.document,"readystatechange",this.#p,!1]);const n=this.document.defaultView;n!==null&&ue(this.#c,[n,"load",this.#p,!1]),this.document.readyState==="interactive"&&this.#n===void 0&&(this.#n=setTimeout(this.#p,50))}listenDocumentClick(e){ue(this.#c,[this.document,"click",i=>{i instanceof MouseEvent&&e(i)},!0])}listenDocumentKeydown(e){ue(this.#c,[this.document,"keydown",i=>{i instanceof KeyboardEvent&&e(i)},!1])}mark(e){e.setAttribute("data-scg-selector-overlay","true");for(const i of e.querySelectorAll("*"))i.setAttribute("data-scg-selector-overlay","true")}scheduleViewport(){if(this.#d||this.#o!==null)return;const e=this.document.defaultView;this.#o=e?.requestAnimationFrame(this.#h)??setTimeout(this.#h,0)}hideHighlight(){this.#l!==void 0&&(clearTimeout(this.#l),this.#l=void 0),this.#a=null,this.#r!==null&&(this.#r.hidden=!0)}showHighlight(e){this.#l!==void 0&&(clearTimeout(this.#l),this.#l=void 0),this.#g()!==null&&(this.#a=e,this.#f())}flashHighlight(e){e.scrollIntoView({behavior:"smooth",block:"center"}),this.#g()!==null&&(this.showHighlight(e),this.scheduleViewport(),this.#l=setTimeout(()=>{this.#a=null,this.#l=void 0,this.#r!==null&&(this.#r.hidden=!0)},1e3))}destroy(){if(!this.#d){this.#d=!0,this.#v();for(const[e,i,n,s]of this.#c.splice(0))e.removeEventListener(i,n,s);if(this.#o!==null){const e=this.document.defaultView;e!==null?e.cancelAnimationFrame(this.#o):clearTimeout(this.#o),this.#o=null}this.hideHighlight(),this.#r?.remove(),this.#r=null,this.#t=[],this.#e=null}}#u=()=>this.scheduleViewport();#h=()=>{this.#o=null,!this.#d&&(this.delegate.positionViewport(),this.#f())};#g(){const e=this.document.body;return e!==null&&this.#r===null&&(this.#r=this.document.createElement("div"),this.#r.className="scg-ui-highlight",this.#r.hidden=!0,this.mark(this.#r),e.append(this.#r)),this.#r}#f(){if(this.#r===null||this.#a===null)return;const e=this.#a.getBoundingClientRect();if(!(this.document.documentElement!==null&&this.document.documentElement.contains(this.#a)&&e.width>0&&e.height>0)){this.#r.hidden=!0;return}this.#r.hidden=!1,this.#r.style.left=`${e.left-4}px`,this.#r.style.top=`${e.top-4}px`,this.#r.style.width=`${e.width+8}px`,this.#r.style.height=`${e.height+8}px`}#m=e=>{const i=e.target;!(i instanceof Element)||!fe(i)||(e.stopImmediatePropagation(),Nh(i)||e.preventDefault(),e.type==="pointerdown"&&e instanceof PointerEvent&&this.shell.launcher.contains(i)&&this.shell.continueOwnedPointerDown(e))};#w=e=>{const i=e.type==="focusin"?e.target:e.relatedTarget;i instanceof Element&&fe(i)&&e.stopImmediatePropagation()};#p=()=>{this.#i&&this.#b()};#b(){const e=xh(this.document,this.#e);if(this.#d||this.#s||e===null)return!1;e.append(...this.#t);for(const i of this.#t)i instanceof HTMLElement&&i.localName!=="style"&&this.mark(i);return this.#s=!0,this.#v(),this.delegate.didMount(),!0}#v(){for(const e of[...this.#c]){const[i,n,s,r]=e;s===this.#p&&(n==="DOMContentLoaded"||n==="readystatechange"||n==="load")&&(i.removeEventListener(n,s,r),this.#c.splice(this.#c.indexOf(e),1))}this.#n!==void 0&&(clearTimeout(this.#n),this.#n=void 0)}}function ue(t,e){const[i,n,s,r]=e;i.addEventListener(n,s,r),t.push(e)}function xh(t,e){if(e!==null)return e;const i=t.defaultView,n=i===null?[]:[...t.querySelectorAll("[data-scg-root]")].filter(r=>r instanceof i.HTMLElement),[s]=n;return s!==void 0&&n.length===1?s:n.length>1||t.readyState==="complete"?t.body:null}function Nh(t){const e=t.localName;return e==="input"||e==="textarea"||e==="select"||t.isContentEditable===!0}class Ph{#e;constructor(e){this.#e=e}providerHandlers(){return{onProviderChange:({provider:e})=>this.#t(e),onExecutionSettingsChange:e=>{this.#e?.onWorkExecutionSettingsChange?.(e)},onWarningAcknowledge:({provider:e,remember:i})=>this.#e?.onWorkWarningAcknowledge?.({provider:e,remember:i}),onRequestIntent:()=>{this.#e?.onWorkRequestIntent?.({})},onSessionReset:()=>{this.#e?.onWorkSessionReset?.({})},onCapabilitiesRead:()=>this.readWorkCapabilities()}}readWorkCapabilities(){this.#e?.onWorkCapabilitiesRead?.()}requestHandlers(){return{onConfirm:e=>this.#i(e),onCancelRequest:()=>{this.#e?.onWorkCancel?.({})},onRetrySameRequest:()=>{this.#e?.onWorkRetrySame?.({})},onNewRequest:()=>{this.#e?.onWorkNewRequest?.({})},onDismissPreview:()=>{this.#e?.onWorkPreviewDismiss?.({})}}}acknowledgeWorkReview(e){return this.#e?.onWorkReviewAcknowledge?.({requestId:e})}compareWorkDiff(e,i){return this.#e?.onWorkDiffCompare?.({requestIdA:e,requestIdB:i})}memoAction(e){const i=this.#e;switch(e.kind){case"create":return i?.onCreateMemo===void 0?!1:()=>i.onCreateMemo?.({memo:e.memo});case"update":return i?.onUpdateMemo===void 0?!1:()=>i.onUpdateMemo?.({annotationId:e.annotationId,memo:e.memo});case"delete":return i?.onDeleteMemo===void 0?!1:()=>i.onDeleteMemo?.({annotationId:e.annotationId});case"cancel-selection":return i?.onSelectionModeChange===void 0?!1:()=>i.onSelectionModeChange?.({active:!1})}}promptForMemo(e){return this.#e?.onExportCurrentPage?.({annotationId:e})}memoHost(){return{action:e=>this.memoAction(e),dismissBadgeAttention:e=>{this.#e?.onBadgeAttentionDismiss?.({token:e})},clipboard:{prompt:e=>this.promptForMemo(e)}}}available(e){const i=this.#e;switch(e){case"selection":return i?.onSelectionModeChange!==void 0;case"measure":return i?.onMeasureModeChange!==void 0;case"size":return i?.onSizeModeChange!==void 0;case"delete-all":return i?.onDeleteAllCurrentPage!==void 0;case"retry":return i?.onRetry!==void 0;case"open-diagnostics":return i?.onOpenDiagnostics!==void 0;case"close-diagnostics":return i?.onCloseDiagnostics!==void 0;case"export-project":return i?.onExportProject!==void 0;case"export-page":return i?.onExportCurrentPage!==void 0}}dispatch(e){const i=this.#e;switch(e.kind){case"selection":return i?.onSelectionModeChange?.({active:e.active});case"measure":return i?.onMeasureModeChange?.({active:e.active});case"size":return i?.onSizeModeChange?.({active:e.active});case"delete-all":return i?.onDeleteAllCurrentPage?.({});case"retry":return i?.onRetry?.({});case"open-diagnostics":return i?.onOpenDiagnostics?.({});case"close-diagnostics":return i?.onCloseDiagnostics?.({});case"export-project":return i?.onExportProject?.({});case"export-page":return i?.onExportCurrentPage?.({})}}destroy(){this.#e=null}#t(e){this.#e?.onWorkProviderChange?.({provider:e})}#i(e){this.#e?.onWorkRequestConfirm?.({requestId:e})}}function Lh(t){return async e=>{try{const i=t.defaultView?.navigator.clipboard;return typeof i?.writeText!="function"?!1:(await i.writeText(e),!0)}catch{return!1}}}function Mh(t){t.session.performAction(async()=>{const e=await t.promptForMemo?.(t.annotation.id);if(typeof e!="string"||!await t.copyText(e))throw new Error("clipboard unavailable")},"SCG_CLIENT_CLIPBOARD_FAILED",()=>({kind:"ready",code:"SCG_CLIPBOARD_COPIED"}))}function Dh(t){const e=t.document.defaultView;if(!(t.target!==null&&t.document.documentElement?.contains(t.target)===!0)||e===null){t.highlight(null,"hide"),t.editor.style.top="8px",t.editor.style.left="8px";return}const n=t.target.getBoundingClientRect();t.editor.style.top=`${Math.max(8,Math.min(n.bottom+6,e.innerHeight-t.editor.offsetHeight-8))}px`,t.editor.style.left=`${Math.max(8,Math.min(n.left,e.innerWidth-t.editor.offsetWidth-8))}px`,t.highlight(t.target,"show")}function qh(t,e,i){t.key!=="Enter"||!t.metaKey&&!t.ctrlKey||e.disabled||(t.preventDefault(),i.requestSubmit(e))}function zh(t,e,i){const n=t.annotations.find(({id:s})=>s===e.id)?.element;n!==void 0&&i(n,"flash")}function Gh(t){return/mac|iphone|ipad|ipod/iu.test(t.defaultView?.navigator?.platform??"")}function jh(t){const e=[];let i=t;for(let n=0;n<3&&i!==null;n+=1){const s=i.localName.toLowerCase(),r=i.id===""?"":`#${i.id}`,o=typeof i.className=="string"&&i.className.trim()!==""?`.${i.className.trim().split(/\s+/u)[0]}`:"";e.unshift(`${s}${r}${o}`),i=i.parentElement}return e.join(" > ")}function Wh(t){const e=Object.assign(t.createElement("span"),{className:"scg-ui-hint"});e.tabIndex=0,e.setAttribute("role","img"),e.setAttribute("aria-label","작성한 메모를 저장합니다."),e.textContent="ⓘ";const i=Object.assign(t.createElement("span"),{className:"scg-ui-hint-popover"});return i.textContent="작성한 메모를 저장합니다.",e.append(i),e}class Uh{constructor(e,i,n){this.document=e,this.session=i,this.host=n,this.#r=n.clipboard?.copy??Lh(e),this.#a=n.clipboard?.prompt;const s=(c,l)=>Object.assign(e.createElement(c),{className:l});this.editor=s("form","scg-ui-editor"),this.#t=s("label","scg-ui-editor-label");const r=`scg-ui-memo-${Vh++}`;this.#t.htmlFor=r,this.#n=s("code","scg-ui-target-tag"),this.#o=s("code","scg-ui-target-path"),this.#s=s("div","scg-ui-target"),this.#s.append(this.#n,this.#o),this.input=s("textarea","scg-ui-memo"),this.input.id=r,this.input.name="memo",this.input.rows=4,this.input.required=!0,this.input.placeholder="피드백 혹은 메모",this.saveButton=s("button","scg-ui-action scg-ui-save-memo"),this.saveButton.type="submit",this.#i=s("span","scg-ui-save-memo-label");const o=s("kbd","scg-ui-keycap");o.textContent=`${Gh(e)?"⌘":"Ctrl"} ↵`,this.saveButton.append(this.#i,o),this.cancelButton=s("button","scg-ui-action scg-ui-cancel-edit"),this.cancelButton.type="button",this.cancelButton.textContent="취소",this.cancelButton.setAttribute("aria-label","편집 취소"),this.saveHint=Wh(e);const a=s("div","scg-ui-editor-actions");a.append(this.cancelButton,this.saveButton,this.saveHint),this.editor.append(this.#t,this.#s,this.input,a),this.input.addEventListener("keydown",this.#c),this.editor.addEventListener("submit",this.#d),this.cancelButton.addEventListener("click",this.#u)}document;session;host;editor;input;saveButton;cancelButton;saveHint;#e=null;#t;#i;#s;#n;#o;#r;#a;#l=!1;render(){const e=this.#e===null&&this.session.pendingSelectionElement!==null&&this.session.pageActionAvailable(this.session.capabilities.canCreateMemo),i=this.#e!==null||e,n=i&&!this.#l&&this.#e===null;this.editor.hidden=!i,this.#l=i,this.#t.textContent=this.#e===null?"새 메모":"메모 편집",this.#i.textContent=this.#e===null?"추가":"저장",this.saveButton.setAttribute("aria-label",this.#e===null?"메모 작성":"메모 저장");const s=this.#h();this.#n.textContent=s?.localName.toLowerCase()??"";const r=s===null?"":jh(s);return this.#o.textContent=r,this.#o.title=r,this.#s.hidden=s===null,this.cancelButton.hidden=!i,i||this.host.highlight(null,"hide"),n&&queueMicrotask(()=>{this.#l&&this.#e===null&&this.input.focus()}),i}position(){this.editor.hidden||Dh({document:this.document,editor:this.editor,target:this.#h(),highlight:(e,i)=>this.host.highlight(e,i)})}setDisabled(){const e=this.session.isActionInFlight(),i=this.#e===null?this.session.capabilities.canCreateMemo:this.session.capabilities.canUpdateMemo;this.input.disabled=e||!this.session.pageActionAvailable(i===!0),this.saveButton.disabled=this.input.disabled,this.cancelButton.disabled=e}edit(e){this.session.destroyed||this.session.isActionInFlight()||!this.session.pageActionAvailable(this.session.capabilities.canUpdateMemo)||(this.#e=e.id,this.input.value=e.memo,this.host.render(),this.input.focus())}copy(e){Mh({session:this.session,copyText:this.#r,promptForMemo:this.#a,annotation:e})}delete(e){if(this.session.destroyed||this.session.isActionInFlight()||!this.session.pageActionAvailable(this.session.capabilities.canDeleteMemo))return;const i=this.host.action({kind:"delete",annotationId:e.id});if(i===!1){this.session.setUnavailableStatus();return}this.session.performAction(i,"SCG_CLIENT_DELETE_FAILED")}scroll(e){zh(this.session,e,(i,n)=>this.host.highlight(i,n))}dismissBadgeAttention(e){this.host.dismissBadgeAttention?.(e)}reset(){this.#e=null,this.input.value=""}reconcile(){this.#e!==null&&!this.session.annotations.some(({id:e})=>e===this.#e)&&this.reset()}destroy(){this.reset(),this.input.removeEventListener("keydown",this.#c),this.editor.removeEventListener("submit",this.#d),this.cancelButton.removeEventListener("click",this.#u)}#c=e=>{qh(e,this.saveButton,this.editor)};#d=e=>{if(e.preventDefault(),this.session.isActionInFlight())return;const i=this.#e,n=i===null?this.session.capabilities.canCreateMemo:this.session.capabilities.canUpdateMemo;if(!this.session.pageActionAvailable(n)){this.session.setUnavailableStatus("SCG_PAGE_UNREADY");return}const s=this.input.value;if(s.trim().length===0){this.session.setMemoBlankStatus();return}const r=i===null?{kind:"create",memo:s}:{kind:"update",annotationId:i,memo:s},o=this.host.action(r);if(o===!1){this.session.setUnavailableStatus();return}const a=i===null?"SCG_CLIENT_CREATE_FAILED":"SCG_CLIENT_UPDATE_FAILED";this.session.performAction(o,a,()=>{this.reset(),i===null&&(this.session.setPendingSelectionElement(null),this.host.created?.()),this.host.highlight(null,"hide"),this.host.render()})};#u=()=>{if(this.session.isActionInFlight())return;const e=this.#e===null&&this.session.pendingSelectionElement!==null;if(this.reset(),this.session.setPendingSelectionElement(null),this.host.highlight(null,"hide"),this.host.render(),e){const i=this.host.action({kind:"cancel-selection"});if(i!==!1)try{Promise.resolve(i()).catch(()=>{})}catch{}}};#h(){return this.#e===null?this.session.pendingSelectionElement:this.session.annotations.find(({id:e})=>e===this.#e)?.element??null}}let Vh=0;const Bh=`/* ---------------------------------------------------------------------------
29
+ * 밝은 카드 표면. 위쪽 규칙들이 세운 어두운 패널을 여기서 덮는다 — 선택자 특정성을
30
+ * 같게 두고 순서로만 이기므로, 위 블록은 레이아웃 정의로 그대로 살아 있다.
31
+ * ------------------------------------------------------------------------- */
32
+ .scg-ui-overlay {
33
+ background: #fff;
34
+ border: 1px solid rgba(0, 0, 0, .08);
35
+ border-radius: 16px;
36
+ box-shadow: 0 12px 32px rgba(0, 0, 0, .12), 0 2px 8px rgba(0, 0, 0, .06);
37
+ color: #18181b;
38
+ padding: 14px;
39
+ }
40
+ .scg-ui-heading { color: #18181b; font-size: 14px; font-weight: 650; }
41
+ .scg-ui-heading-row { background: var(--scg-surface-card); box-shadow: 0 -16px 0 var(--scg-surface-card); color: var(--scg-text-primary); }
42
+ .scg-ui-heading-row .scg-ui-heading { color: var(--scg-text-primary); }
43
+ .scg-ui-minimize { background: #18181b; border: 0; border-radius: 8px; color: #fff; }
44
+
45
+ /* 메모 대상 — 태그 한 줄, 경로 한 줄. 경로는 넘치면 말줄임한다. */
46
+ .scg-ui-target { margin: 2px 0 10px; }
47
+ .scg-ui-target-tag,
48
+ .scg-ui-target-path,
49
+ .scg-ui-annotation-target {
50
+ display: block;
51
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
52
+ }
53
+ .scg-ui-target-tag { color: #18181b; font-size: 14px; font-weight: 600; }
54
+ .scg-ui-target-path {
55
+ color: #a1a1aa;
56
+ font-size: 12px;
57
+ overflow: hidden;
58
+ text-overflow: ellipsis;
59
+ white-space: nowrap;
60
+ }
61
+
62
+ .scg-ui-memo,
63
+ .scg-ui-generated-prompt {
64
+ background: #fff;
65
+ border: 1px solid rgba(0, 0, 0, .12);
66
+ border-radius: 12px;
67
+ color: #18181b;
68
+ padding: 12px;
69
+ width: 100%;
70
+ }
71
+ .scg-ui-memo::placeholder { color: #a1a1aa; }
72
+ .scg-ui-memo:focus-visible,
73
+ .scg-ui-generated-prompt:focus-visible { border-color: #18181b; outline: none; }
74
+
75
+ /* 푸터 — 취소는 글자 버튼, 저장은 검은 알약에 키캡을 얹는다. */
76
+ .scg-ui-editor-actions {
77
+ align-items: center;
78
+ display: flex;
79
+ gap: 8px;
80
+ justify-content: flex-end;
81
+ margin-top: 10px;
82
+ }
83
+ .scg-ui-cancel-edit {
84
+ background: transparent;
85
+ border: 0;
86
+ border-radius: 10px;
87
+ color: #52525b;
88
+ font-weight: 600;
89
+ padding: 8px 10px;
90
+ }
91
+ /* 다른 옅은 버튼(목록의 수정·삭제, 배지 카드)과 같은 호버로 맞춘다. */
92
+ .scg-ui-cancel-edit:hover:enabled {
93
+ background: #f4f4f5;
94
+ color: #18181b;
95
+ }
96
+ .scg-ui-save-memo {
97
+ align-items: center;
98
+ background: #18181b;
99
+ border: 0;
100
+ border-radius: 10px;
101
+ color: #fff;
102
+ display: inline-flex;
103
+ font-weight: 650;
104
+ gap: 8px;
105
+ padding: 9px 12px;
106
+ }
107
+ .scg-ui-save-memo:disabled { background: #d4d4d8; color: #fff; }
108
+ .scg-ui-keycap {
109
+ background: rgba(255, 255, 255, .18);
110
+ border-radius: 6px;
111
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
112
+ font-size: 11px;
113
+ padding: 2px 6px;
114
+ }
115
+
116
+ /* 두 접이 제목은 각자 한 줄을 쓴다 — 나란히 두면 어디까지가 한 항목인지 읽히지 않는다. */
117
+ .scg-ui-annotations-toggle,
118
+ .scg-ui-orphans-toggle {
119
+ background: transparent;
120
+ border: 0;
121
+ border-top: 1px solid rgba(0, 0, 0, .07);
122
+ color: #52525b;
123
+ display: block;
124
+ font-weight: 600;
125
+ padding: 10px 0;
126
+ text-align: left;
127
+ width: 100%;
128
+ }
129
+
130
+ /* 목록 한 줄 — 번호 배지 · 본문 · 오른쪽 동작. */
131
+ .scg-ui-annotation {
132
+ align-items: flex-start;
133
+ border-top: 1px solid rgba(0, 0, 0, .07);
134
+ display: flex;
135
+ gap: 10px;
136
+ padding: 10px 0;
137
+ }
138
+ .scg-ui-annotation-ordinal {
139
+ background: #18181b;
140
+ border-radius: 999px;
141
+ color: #fff;
142
+ flex: 0 0 auto;
143
+ font-size: 11px;
144
+ font-weight: 700;
145
+ line-height: 20px;
146
+ min-width: 20px;
147
+ text-align: center;
148
+ }
149
+ .scg-ui-annotation-body { flex: 1 1 auto; min-width: 0; }
150
+ .scg-ui-annotation-target { color: #18181b; font-size: 12px; font-weight: 600; }
151
+ .scg-ui-annotation-memo { color: #3f3f46; margin: 2px 0 0; }
152
+ .scg-ui-annotation-scroll {
153
+ background: transparent;
154
+ border: 0;
155
+ color: inherit;
156
+ padding: 0;
157
+ text-align: left;
158
+ }
159
+ .scg-ui-annotation-resolution { color: #a1a1aa; font-size: 11px; }
160
+ .scg-ui-annotation-actions { display: flex; flex: 0 0 auto; gap: 4px; }
161
+ .scg-ui-annotation-actions .scg-ui-action {
162
+ background: transparent;
163
+ border: 0;
164
+ border-radius: 8px;
165
+ color: #71717a;
166
+ font-size: 12px;
167
+ padding: 4px 6px;
168
+ }
169
+ .scg-ui-annotation-actions .scg-ui-action:hover:enabled {
170
+ background: #f4f4f5;
171
+ color: #18181b;
172
+ }
173
+
174
+ .scg-ui-prompt-toggle {
175
+ background: transparent;
176
+ border: 0;
177
+ border-top: 1px solid rgba(0, 0, 0, .07);
178
+ color: #52525b;
179
+ display: block;
180
+ font-weight: 600;
181
+ padding: 10px 0;
182
+ text-align: left;
183
+ width: 100%;
184
+ }
185
+ .scg-ui-generated-prompt[hidden] { display: none; }
186
+
187
+ /* 접힌 채 메모를 쓰는 동안의 패널 — 자리만 지키고 아무것도 그리지 않는다. */
188
+ .scg-ui-overlay--composer-only {
189
+ background: none !important;
190
+ border: 0 !important;
191
+ box-shadow: none !important;
192
+ height: 0 !important;
193
+ overflow: visible !important;
194
+ padding: 0 !important;
195
+ width: 0 !important;
196
+ }
197
+ .scg-ui-overlay--composer-only > *:not(.scg-ui-editor) { display: none !important; }
198
+
199
+ /* 모달이 열리면 라이브러리는 바깥 요소 전체의 포인터를 끈다. Scene Glass 는 그 "바깥" 에
200
+ 있으므로 패널이 보이는데도 눌리지 않게 된다 — 팝업이 뜬 화면은 리뷰가 불가능해진다.
201
+ 자기 소유 표면만 되찾는다. 호스트 요소는 하나도 건드리지 않으므로 모달의 차단은 그대로다.
202
+ 호스트가 인라인이나 유틸리티 클래스로 거는 것을 이겨야 해서 !important 가 필요하다. */
203
+ .scg-ui-overlay,
204
+ .scg-ui-launcher,
205
+ .scg-ui-editor,
206
+ .scg-ui-badge,
207
+ .scg-ui-badge-popover,
208
+ .scg-ui-hint,
209
+ .scg-ui-hint-popover {
210
+ pointer-events: auto !important;
211
+ }
212
+ .scg-ui-badges { pointer-events: none !important; }
213
+
214
+ /* 배지를 눌러 보는 메모 카드 — 작성기와 같은 흰 카드로 맞춘다. 위쪽 규칙이 세운 어두운
215
+ 팝오버를 덮되, 도움말 툴팁(.scg-ui-hint-popover)은 그대로 어둡게 둔다. */
216
+ .scg-ui-badge-popover {
217
+ background: #fff;
218
+ border: 1px solid rgba(0, 0, 0, .08);
219
+ border-radius: 16px;
220
+ box-shadow: 0 12px 32px rgba(0, 0, 0, .12), 0 2px 8px rgba(0, 0, 0, .06);
221
+ color: #18181b;
222
+ font: 500 13px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
223
+ max-width: min(320px, calc(100vw - 24px));
224
+ padding: 12px;
225
+ }
226
+ .scg-ui-badge-popover,
227
+ .scg-ui-badge-popover * { box-sizing: border-box; }
228
+ .scg-ui-badge-target {
229
+ color: #18181b;
230
+ display: block;
231
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
232
+ font-size: 12px;
233
+ font-weight: 600;
234
+ }
235
+ .scg-ui-badge-target[hidden] { display: none; }
236
+ .scg-ui-badge-memo {
237
+ color: #3f3f46;
238
+ display: block;
239
+ margin: 2px 0 10px;
240
+ }
241
+ .scg-ui-badge-actions {
242
+ display: flex;
243
+ gap: 4px;
244
+ justify-content: flex-end;
245
+ }
246
+ .scg-ui-badge-popover .scg-ui-action {
247
+ background: transparent;
248
+ border: 0;
249
+ border-radius: 8px;
250
+ color: #71717a;
251
+ font-size: 12px;
252
+ font-weight: 600;
253
+ margin: 0;
254
+ min-height: 28px;
255
+ padding: 4px 8px;
256
+ }
257
+ .scg-ui-badge-popover .scg-ui-action:hover:enabled { background: #f4f4f5; color: #18181b; }
258
+ .scg-ui-badge-popover .scg-ui-badge-delete {
259
+ border: 1px solid rgba(220, 38, 38, .35);
260
+ color: #dc2626;
261
+ }
262
+ .scg-ui-badge-popover .scg-ui-badge-delete:hover:enabled {
263
+ background: #fef2f2;
264
+ border-color: #dc2626;
265
+ color: #b91c1c;
266
+ }
267
+
268
+ /* 다크 테마가 남긴 면들을 걷는다 — 행은 카드가 아니라 실선으로만 나뉜다. */
269
+ .scg-ui-annotations,
270
+ .scg-ui-orphans {
271
+ list-style: none;
272
+ margin: 0;
273
+ padding: 0;
274
+ }
275
+ .scg-ui-annotation {
276
+ background: transparent;
277
+ border-bottom: 0;
278
+ border-left: 0;
279
+ border-radius: 0;
280
+ border-right: 0;
281
+ box-shadow: none;
282
+ margin: 0;
283
+ }
284
+ .scg-ui-annotation:first-child { border-top: 0; }
285
+ .scg-ui-annotation-memo,
286
+ .scg-ui-annotation-scroll { color: #3f3f46; }
287
+
288
+ `,Fh=`/* 상단 동작 — 칩 폭이 글자 길이를 따라 들쑥날쑥하지 않도록 2열 격자에 세운다.
289
+ 한 칸의 높이를 고정해 어느 줄에서도 같은 크기로 선다. */
290
+ .scg-ui-controls {
291
+ align-items: stretch;
292
+ display: grid;
293
+ gap: 6px;
294
+ grid-template-columns: 1fr 1fr;
295
+ margin-bottom: 12px;
296
+ }
297
+ .scg-ui-controls .scg-ui-action {
298
+ align-items: center;
299
+ background: #f4f4f5;
300
+ border: 1px solid rgba(0, 0, 0, .06);
301
+ border-radius: 10px;
302
+ color: #3f3f46;
303
+ display: flex;
304
+ font-weight: 600;
305
+ justify-content: center;
306
+ min-height: 34px;
307
+ padding: 0 10px;
308
+ text-align: center;
309
+ width: 100%;
310
+ }
311
+ .scg-ui-controls .scg-ui-action:hover:enabled { background: #e4e4e7; }
312
+ .scg-ui-controls .scg-ui-action:disabled { color: #a1a1aa; opacity: 1; }
313
+ .scg-ui-delete-all-cancel[hidden] { display: none; }
314
+
315
+ /* 요소 선택은 이 패널의 본 기능이다 — 한 줄을 통째로 쓰고 색으로 앞세운다. */
316
+ .scg-ui-controls .scg-ui-selection {
317
+ background: #2563eb;
318
+ border-color: #2563eb;
319
+ color: #fff;
320
+ font-weight: 700;
321
+ grid-column: 1 / -1;
322
+ min-height: 38px;
323
+ }
324
+ .scg-ui-controls .scg-ui-selection:hover:enabled { background: #1d4ed8; }
325
+ .scg-ui-controls .scg-ui-selection[aria-pressed="true"] {
326
+ background: #18181b;
327
+ border-color: #18181b;
328
+ box-shadow: 0 0 0 3px rgba(37, 99, 235, .28);
329
+ }
330
+
331
+ /* 한 칸 = 버튼 + 도움말을 나란히. 겹쳐 얹었더니 도움말이 버튼 위를 덮어 호버해도 설명이
332
+ 뜨지 않고 그 자리를 누르면 클릭까지 가로챘다 — 요소 선택이 여러 번 눌러야 켜지던 원인이다. */
333
+ .scg-ui-control-cell {
334
+ align-items: center;
335
+ display: flex;
336
+ gap: 4px;
337
+ }
338
+ /* 글자가 긴 것과 본 기능은 한 줄을 통째로 쓴다 — 반 칸에 가두면 두 줄로 깨진다. */
339
+ .scg-ui-control-cell:has(.scg-ui-selection),
340
+ .scg-ui-control-cell:has(.scg-ui-export-page),
341
+ .scg-ui-control-cell:has(.scg-ui-diagnostics),
342
+ .scg-ui-control-cell:has(.scg-ui-delete-all) { grid-column: 1 / -1; }
343
+ .scg-ui-control-cell .scg-ui-action { flex: 1 1 auto; min-width: 0; }
344
+ .scg-ui-control-cell .scg-ui-hint { flex: 0 0 auto; }
345
+
346
+ /* 페이지를 통째로 내보내는 것은 다른 버튼과 무게가 다르다 — 삭제가 빨간 테두리로 구분되듯
347
+ 테두리로 세워 둔다. 색은 초록이다: 앰버는 옆 칸의 빨강과 붙어 보여 가져오는 일과 지우는
348
+ 일이 한눈에 갈리지 않았다. 되돌릴 수 없는 일은 아니므로 글자색은 건드리지 않는다. */
349
+ .scg-ui-controls .scg-ui-export-page {
350
+ border: 1px solid rgba(16, 185, 129, .55);
351
+ }
352
+ .scg-ui-controls .scg-ui-export-page:hover:enabled {
353
+ border-color: #10b981;
354
+ }
355
+
356
+ /* 지우는 동작은 되돌릴 수 없다 — 빨간 테두리로 다른 것들과 구분해 둔다. */
357
+ .scg-ui-controls .scg-ui-delete-all,
358
+ .scg-ui-annotation-actions .scg-ui-delete-memo {
359
+ border: 1px solid rgba(220, 38, 38, .35);
360
+ color: #dc2626;
361
+ }
362
+ .scg-ui-controls .scg-ui-delete-all:hover:enabled,
363
+ .scg-ui-annotation-actions .scg-ui-delete-memo:hover:enabled {
364
+ background: #fef2f2;
365
+ border-color: #dc2626;
366
+ color: #b91c1c;
367
+ }
368
+ /* 두 번째 확인을 기다리는 동안은 채워서 되돌릴 수 없음을 더 분명히 한다. */
369
+ .scg-ui-controls .scg-ui-delete-all[data-confirming="true"] {
370
+ background: #dc2626;
371
+ border-color: #dc2626;
372
+ color: #fff;
373
+ }
374
+
375
+ /* 작성기는 대상 옆에 따로 떠 있는 표면이라 패널 규칙이 닿지 않는다 — 같은 카드로 맞춘다. */
376
+ .scg-ui-editor {
377
+ background: #fff;
378
+ border: 1px solid rgba(0, 0, 0, .08);
379
+ border-radius: 16px;
380
+ box-shadow: 0 12px 32px rgba(0, 0, 0, .12), 0 2px 8px rgba(0, 0, 0, .06);
381
+ color: #18181b;
382
+ max-width: min(420px, calc(100vw - 24px));
383
+ overflow: hidden;
384
+ padding: 14px;
385
+ width: min(420px, calc(100vw - 24px));
386
+ }
387
+ /* 작성기는 .scg-ui-overlay 밖에 떠 있어 위쪽 * 규칙이 닿지 않는다. 여기서 다시 걸지 않으면
388
+ width:100% 에 padding·border 가 더해져 카드 밖으로 삐져나간다. */
389
+ .scg-ui-editor,
390
+ .scg-ui-editor *,
391
+ .scg-ui-editor *::before,
392
+ .scg-ui-editor *::after { box-sizing: border-box; }
393
+ /* 긴 경로가 칸을 밀어내지 못하게 — 넘치면 줄이지 말고 잘라 낸다. */
394
+ .scg-ui-editor > * { max-width: 100%; min-width: 0; }
395
+ .scg-ui-memo { max-width: 100%; resize: vertical; }
396
+ .scg-ui-editor-label {
397
+ color: #71717a;
398
+ display: block;
399
+ font-size: 11px;
400
+ font-weight: 600;
401
+ margin-bottom: 6px;
402
+ }
403
+ `,$h=`.scg-ui-editor {
404
+ background: #0f172a;
405
+ border: 1px solid rgba(148, 163, 184, .45);
406
+ border-radius: 10px;
407
+ box-shadow: 0 8px 20px rgba(2, 6, 23, .35);
408
+ display: grid;
409
+ gap: 7px;
410
+ max-width: min(360px, calc(100vw - 16px));
411
+ padding: 10px;
412
+ position: fixed;
413
+ width: max-content;
414
+ z-index: 2147483645;
415
+ }
416
+ .scg-ui-editor-label,
417
+ .scg-ui-prompt-label {
418
+ color: #cbd5e1;
419
+ display: block;
420
+ font-size: 12px;
421
+ font-weight: 650;
422
+ margin-bottom: 5px;
423
+ }
424
+ .scg-ui-memo,
425
+ .scg-ui-generated-prompt {
426
+ appearance: none;
427
+ background: rgba(2, 6, 23, .62);
428
+ border: 1px solid rgba(148, 163, 184, .3);
429
+ border-radius: 10px;
430
+ color: #f8fafc;
431
+ font: 500 13px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
432
+ min-height: 76px;
433
+ outline: none;
434
+ padding: 10px;
435
+ resize: vertical;
436
+ width: 100%;
437
+ }
438
+ .scg-ui-memo:focus,
439
+ .scg-ui-generated-prompt:focus {
440
+ border-color: #38bdf8;
441
+ box-shadow: 0 0 0 3px rgba(56, 189, 248, .14);
442
+ }
443
+ .scg-ui-annotations,
444
+ .scg-ui-orphans {
445
+ display: grid;
446
+ gap: 8px;
447
+ list-style: none;
448
+ margin: 0 0 12px;
449
+ padding: 0;
450
+ }
451
+ .scg-ui-annotation {
452
+ background: rgba(30, 41, 59, .74);
453
+ border: 1px solid rgba(148, 163, 184, .2);
454
+ border-radius: 11px;
455
+ padding: 10px;
456
+ }
457
+ .scg-ui-annotation-memo {
458
+ color: #f1f5f9;
459
+ margin: 0 0 5px;
460
+ white-space: pre-wrap;
461
+ }
462
+ .scg-ui-annotation-scroll {
463
+ appearance: none;
464
+ background: transparent;
465
+ border: 0;
466
+ color: inherit;
467
+ cursor: pointer;
468
+ font: inherit;
469
+ padding: 0;
470
+ text-align: left;
471
+ white-space: pre-wrap;
472
+ }
473
+ .scg-ui-annotation-scroll:disabled {
474
+ cursor: default;
475
+ opacity: .7;
476
+ }
477
+ .scg-ui-highlight {
478
+ border: 3px solid #38bdf8;
479
+ border-radius: 6px;
480
+ box-sizing: border-box;
481
+ pointer-events: none;
482
+ position: fixed;
483
+ z-index: 2147483644;
484
+ }
485
+ .scg-ui-annotation-resolution {
486
+ color: #94a3b8;
487
+ display: block;
488
+ font-size: 11px;
489
+ margin-bottom: 8px;
490
+ }
491
+ .scg-ui-status {
492
+ color: #94a3b8;
493
+ display: block;
494
+ font-size: 11px;
495
+ margin-top: 9px;
496
+ }
497
+ .scg-ui-hint {
498
+ align-items: center;
499
+ border: 1px solid rgba(148, 163, 184, .38);
500
+ border-radius: 50%;
501
+ color: #bae6fd;
502
+ cursor: help;
503
+ display: inline-flex;
504
+ font-size: 12px;
505
+ height: 18px;
506
+ justify-content: center;
507
+ position: relative;
508
+ width: 18px;
509
+ }
510
+ .scg-ui-hint:focus-visible {
511
+ outline: 2px solid #38bdf8;
512
+ outline-offset: 2px;
513
+ }
514
+ .scg-ui-hint-popover,
515
+ .scg-ui-badge-popover {
516
+ background: #0f172a;
517
+ border: 1px solid rgba(148, 163, 184, .45);
518
+ border-radius: 7px;
519
+ box-shadow: 0 8px 20px rgba(2, 6, 23, .35);
520
+ color: #f8fafc;
521
+ display: none;
522
+ font-size: 11px;
523
+ font-weight: 500;
524
+ line-height: 1.35;
525
+ max-width: min(260px, calc(100vw - 24px));
526
+ padding: 6px 8px;
527
+ position: fixed;
528
+ white-space: normal;
529
+ width: max-content;
530
+ z-index: 2147483647;
531
+ }
532
+ .scg-ui-badge-popover {
533
+ pointer-events: auto;
534
+ }
535
+ .scg-ui-badge-memo {
536
+ display: block;
537
+ margin-bottom: 7px;
538
+ }
539
+ .scg-ui-badge-edit,
540
+ .scg-ui-badge-delete {
541
+ margin-right: 5px;
542
+ min-height: 26px;
543
+ padding: 3px 7px;
544
+ }
545
+ .scg-ui-hint--open .scg-ui-hint-popover,
546
+ .scg-ui-badge--open .scg-ui-badge-popover { display: block; }
547
+ .scg-ui-badges {
548
+ inset: 0;
549
+ pointer-events: none;
550
+ position: fixed;
551
+ z-index: 2147483645;
552
+ }
553
+ .scg-ui-badge {
554
+ align-items: center;
555
+ background: var(--scg-accent-pressed);
556
+ border: 2px solid #fff;
557
+ border-radius: 50%;
558
+ color: #fff;
559
+ cursor: pointer;
560
+ display: flex;
561
+ font: 700 11px/1 Inter, ui-sans-serif, system-ui, sans-serif;
562
+ height: 22px;
563
+ justify-content: center;
564
+ padding: 0;
565
+ pointer-events: auto;
566
+ position: fixed;
567
+ width: 22px;
568
+ }
569
+ .scg-ui-badge::after {
570
+ background: #fff;
571
+ border-radius: 2px;
572
+ content: "";
573
+ height: 7px;
574
+ position: absolute;
575
+ right: -4px;
576
+ top: 17px;
577
+ transform: rotate(-45deg);
578
+ width: 3px;
579
+ }
580
+ .scg-ui-badge:focus-visible {
581
+ outline: 2px solid #facc15;
582
+ outline-offset: 2px;
583
+ }
584
+ .scg-ui-badge-popover {
585
+ min-width: 140px;
586
+ }
587
+ @media (max-width: 480px) {
588
+ .scg-ui-overlay {
589
+ bottom: 10px;
590
+ max-height: calc(100dvh - 20px);
591
+ right: 10px;
592
+ width: calc(100vw - 20px);
593
+ }
594
+ .scg-ui-launcher {
595
+ bottom: 10px;
596
+ right: 10px;
597
+ }
598
+ }
599
+
600
+ `,Kh=`
601
+ .scg-ui-overlay {
602
+ -webkit-font-smoothing: antialiased;
603
+ background: rgba(15, 23, 42, .96);
604
+ border: 1px solid rgba(148, 163, 184, .28);
605
+ border-radius: 18px;
606
+ bottom: 20px;
607
+ box-shadow: 0 24px 64px rgba(2, 6, 23, .34), 0 4px 16px rgba(2, 6, 23, .18);
608
+ box-sizing: border-box;
609
+ color: #e2e8f0;
610
+ font: 500 13px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
611
+ letter-spacing: 0;
612
+ max-height: calc(100dvh - 40px);
613
+ overflow-y: auto;
614
+ padding: 16px;
615
+ position: fixed;
616
+ right: 20px;
617
+ text-align: left;
618
+ width: min(360px, calc(100vw - 40px));
619
+ z-index: 2147483646;
620
+ }
621
+ .scg-ui-overlay *,
622
+ .scg-ui-overlay *::before,
623
+ .scg-ui-overlay *::after { box-sizing: border-box; }
624
+ .scg-ui-heading {
625
+ color: #f8fafc;
626
+ font-size: 16px;
627
+ font-weight: 720;
628
+ letter-spacing: -.02em;
629
+ margin: 0 0 12px;
630
+ }
631
+ .scg-ui-heading-row {
632
+ align-items: center;
633
+ background: rgba(15, 23, 42, .96);
634
+ box-shadow: 0 -16px 0 rgba(15, 23, 42, .96);
635
+ display: flex;
636
+ justify-content: space-between;
637
+ margin-bottom: 12px;
638
+ min-width: 0;
639
+ position: sticky;
640
+ top: 0;
641
+ z-index: 1;
642
+ }
643
+ .scg-ui-heading-row .scg-ui-heading { margin-bottom: 0; }
644
+ .scg-ui-minimize,
645
+ .scg-ui-launcher {
646
+ appearance: none;
647
+ background: #0284c7;
648
+ border: 1px solid #38bdf8;
649
+ color: #fff;
650
+ cursor: pointer;
651
+ }
652
+ .scg-ui-minimize {
653
+ border-radius: 8px;
654
+ flex: 0 0 28px;
655
+ font: 700 18px/1 Inter, ui-sans-serif, system-ui, sans-serif;
656
+ height: 28px;
657
+ width: 28px;
658
+ }
659
+ .scg-ui-minimize:focus-visible,
660
+ .scg-ui-launcher:focus-visible,
661
+ .scg-ui-annotations-toggle:focus-visible,
662
+ .scg-ui-orphans-toggle:focus-visible,
663
+ .scg-ui-annotation-scroll:focus-visible {
664
+ outline: 2px solid #38bdf8;
665
+ outline-offset: 2px;
666
+ }
667
+ /* 접었을 때 화면에 남는 유일한 표시다 — 호스트 UI 와 섞이지 않도록 앰버로 세워 둔다.
668
+ 글자 없이 아이콘만 있으므로 획이 배경에 묻지 않게 어두운 앰버로 그린다. */
669
+ .scg-ui-launcher {
670
+ align-items: center;
671
+ background: #f59e0b;
672
+ border-color: #fbbf24;
673
+ border-radius: 50%;
674
+ bottom: 20px;
675
+ box-shadow: 0 8px 20px rgba(2, 6, 23, .35);
676
+ color: #78350f;
677
+ display: flex;
678
+ height: 42px;
679
+ justify-content: center;
680
+ padding: 0;
681
+ position: fixed;
682
+ right: 20px;
683
+ width: 42px;
684
+ cursor: grab;
685
+ touch-action: none;
686
+ user-select: none;
687
+ z-index: 2147483646;
688
+ }
689
+ .scg-ui-launcher--dragging { cursor: grabbing; }
690
+ .scg-ui-launcher svg {
691
+ height: 22px;
692
+ width: 22px;
693
+ }
694
+ .scg-ui-launcher[hidden],
695
+ .scg-ui-editor[hidden],
696
+ .scg-ui-annotations[hidden],
697
+ .scg-ui-orphans[hidden],
698
+ .scg-ui-badge[hidden] {
699
+ display: none;
700
+ }
701
+ .scg-ui-annotations-toggle,
702
+ .scg-ui-orphans-toggle {
703
+ appearance: none;
704
+ background: transparent;
705
+ border: 0;
706
+ color: #cbd5e1;
707
+ cursor: pointer;
708
+ font: 700 12px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
709
+ letter-spacing: .08em;
710
+ margin: 14px 0 8px;
711
+ padding: 0;
712
+ text-align: left;
713
+ text-transform: uppercase;
714
+ }
715
+ .scg-ui-controls,
716
+ .scg-ui-editor-actions {
717
+ display: flex;
718
+ flex-wrap: wrap;
719
+ gap: 7px;
720
+ margin-bottom: 12px;
721
+ }
722
+ .scg-ui-action {
723
+ appearance: none;
724
+ background: rgba(51, 65, 85, .82);
725
+ border: 1px solid rgba(148, 163, 184, .24);
726
+ border-radius: 9px;
727
+ color: #e2e8f0;
728
+ cursor: pointer;
729
+ font: inherit;
730
+ font-size: 12px;
731
+ font-weight: 650;
732
+ min-height: 32px;
733
+ padding: 6px 10px;
734
+ transition: background 120ms ease, border-color 120ms ease, transform 120ms ease;
735
+ }
736
+ .scg-ui-action:hover:not(:disabled) {
737
+ background: #475569;
738
+ border-color: rgba(203, 213, 225, .45);
739
+ transform: translateY(-1px);
740
+ }
741
+ .scg-ui-action:focus-visible {
742
+ outline: 2px solid #38bdf8;
743
+ outline-offset: 2px;
744
+ }
745
+ .scg-ui-action:disabled {
746
+ cursor: not-allowed;
747
+ opacity: .42;
748
+ }
749
+ .scg-ui-selection {
750
+ background: #0284c7;
751
+ border-color: #38bdf8;
752
+ color: #fff;
753
+ }
754
+ `,Hh=`
755
+ .scg-ui-overlay,
756
+ .scg-ui-editor,
757
+ .scg-ui-work-warning-layer,
758
+ .scg-ui-work-warning,
759
+ .scg-ui-work-preview-layer,
760
+ .scg-ui-work-preview,
761
+ .scg-ui-badges {
762
+ --scg-surface-card: #fff;
763
+ --scg-surface-muted: #f4f4f5;
764
+ --scg-surface-muted-strong: #e4e4e7;
765
+ --scg-surface-scrim: rgba(9, 9, 11, .44);
766
+ --scg-text-primary: #18181b;
767
+ --scg-text-body: #3f3f46;
768
+ --scg-text-secondary: #52525b;
769
+ --scg-text-tertiary: #71717a;
770
+ --scg-text-muted: #a1a1aa;
771
+ --scg-border-card: rgba(0, 0, 0, .08);
772
+ --scg-border-divider: rgba(0, 0, 0, .07);
773
+ --scg-border-control: rgba(0, 0, 0, .06);
774
+ --scg-border-field: #d4d4d8;
775
+ --scg-accent-primary: #2563eb;
776
+ --scg-accent-primary-hover: #1d4ed8;
777
+ --scg-accent-pressed: #18181b;
778
+ --scg-accent-ring: rgba(37, 99, 235, .28);
779
+ /* 6.1:1 on the card surface; the legacy literal ring fails that floor. */
780
+ --scg-focus-ring: #0369a1;
781
+ --scg-status-positive: #047857;
782
+ --scg-status-positive-bg: #ecfdf5;
783
+ --scg-status-positive-border: #a7f3d0;
784
+ --scg-status-warning: #9a3412;
785
+ --scg-status-warning-bg: #fff7ed;
786
+ --scg-status-warning-border: #fed7aa;
787
+ --scg-status-danger: #991b1b;
788
+ --scg-status-danger-bg: #fef2f2;
789
+ --scg-status-danger-border: #fecaca;
790
+ --scg-status-danger-action: #dc2626;
791
+ --scg-status-info: #1e40af;
792
+ --scg-status-info-bg: #eff6ff;
793
+ --scg-status-info-border: #bfdbfe;
794
+ --scg-status-neutral: #52525b;
795
+ --scg-status-neutral-bg: #f4f4f5;
796
+ --scg-status-neutral-border: #d4d4d8;
797
+ --scg-diff-surface: #fafafa;
798
+ --scg-diff-context: #3f3f46;
799
+ --scg-diff-added: #166534;
800
+ --scg-diff-added-bg: #f0fdf4;
801
+ --scg-diff-deleted: #991b1b;
802
+ --scg-diff-deleted-bg: #fef2f2;
803
+ --scg-diff-gutter: #71717a;
804
+ --scg-space-1: 2px;
805
+ --scg-space-2: 4px;
806
+ --scg-space-3: 6px;
807
+ --scg-space-4: 8px;
808
+ --scg-space-5: 10px;
809
+ --scg-space-6: 12px;
810
+ --scg-space-7: 14px;
811
+ --scg-space-8: 18px;
812
+ --scg-radius-card: 16px;
813
+ --scg-radius-control: 10px;
814
+ --scg-radius-field: 8px;
815
+ --scg-radius-pill: 999px;
816
+ --scg-shadow-card: 0 12px 32px rgba(0, 0, 0, .12), 0 2px 8px rgba(0, 0, 0, .06);
817
+ --scg-shadow-dialog: 0 24px 64px rgba(0, 0, 0, .22), 0 4px 12px rgba(0, 0, 0, .1);
818
+ --scg-duration-fast: 120ms;
819
+ --scg-badge-attention-color: #d97706;
820
+ --scg-duration-badge-attention: 2000ms;
821
+ }
822
+ `,Yh=`
823
+ .scg-ui-overlay {
824
+ max-block-size: min(680px, calc(100dvh - 40px));
825
+ inset-inline-end: 20px;
826
+ inset-inline-start: auto;
827
+ }
828
+ .scg-ui-overlay[data-scg-side="left"],
829
+ .scg-ui-launcher[data-scg-side="left"] {
830
+ left: auto;
831
+ right: auto;
832
+ inset-inline-start: 20px;
833
+ inset-inline-end: auto;
834
+ }
835
+ .scg-ui-launcher[data-scg-side="right"] {
836
+ inset-inline-start: auto;
837
+ inset-inline-end: 20px;
838
+ }
839
+ .scg-ui-heading-row { gap: var(--scg-space-3); }
840
+ .scg-ui-heading-row .scg-ui-heading { flex: 1; }
841
+ .scg-ui-settings-toggle {
842
+ appearance: none;
843
+ display: inline-flex;
844
+ align-items: center;
845
+ justify-content: center;
846
+ box-sizing: border-box;
847
+ inline-size: 28px;
848
+ block-size: 28px;
849
+ flex: 0 0 auto;
850
+ background: var(--scg-surface-muted);
851
+ border: 1px solid var(--scg-border-control);
852
+ border-radius: var(--scg-radius-field);
853
+ color: var(--scg-text-secondary);
854
+ cursor: pointer;
855
+ font: inherit;
856
+ font-size: 12px;
857
+ font-weight: 600;
858
+ padding: var(--scg-space-2);
859
+ }
860
+ .scg-ui-settings-toggle > svg { display: block; flex: 0 0 auto; }
861
+ .scg-ui-settings-toggle:hover,
862
+ .scg-ui-settings-toggle[aria-expanded="true"] { background: var(--scg-surface-muted-strong); color: var(--scg-text-primary); }
863
+ .scg-ui-settings-toggle:active { background: var(--scg-surface-muted); }
864
+ .scg-ui-settings-toggle:focus-visible,
865
+ .scg-ui-work-setting-select:focus-visible { outline: 2px solid var(--scg-focus-ring); outline-offset: 2px; }
866
+ .scg-ui-settings,
867
+ .scg-ui-work-configuration,
868
+ .scg-ui-work-execution {
869
+ display: grid;
870
+ gap: var(--scg-space-4);
871
+ min-inline-size: 0;
872
+ }
873
+ .scg-ui-settings {
874
+ border-block-end: 1px solid var(--scg-border-divider);
875
+ margin-block-end: var(--scg-space-6);
876
+ padding-block-end: var(--scg-space-6);
877
+ word-break: keep-all;
878
+ overflow-wrap: anywhere;
879
+ }
880
+ .scg-ui-settings-notice {
881
+ color: var(--scg-text-tertiary);
882
+ font-size: 11px;
883
+ line-height: 1.45;
884
+ margin: 0;
885
+ word-break: keep-all;
886
+ }
887
+ .scg-ui-settings[hidden],
888
+ .scg-ui-settings-persistence[hidden] { display: none; }
889
+ /* 설정은 본문을 대신하는 화면이다 — 머리글, 설정, 상태 출력, 제공자 알림 영역과 설정 알림만 남기고
890
+ 나머지 본문은 그대로 둔 채 감춘다. 접힌 상태·입력값은 돌아올 때 그대로다. */
891
+ .scg-ui-overlay--settings > *:not(.scg-ui-heading-row):not(.scg-ui-settings):not(.scg-ui-status):not(.scg-ui-work-announce):not(.scg-ui-panel-alert) {
892
+ display: none;
893
+ }
894
+ .scg-ui-work-setting-select {
895
+ background: var(--scg-surface-card);
896
+ border: 1px solid var(--scg-border-field);
897
+ border-radius: var(--scg-radius-field);
898
+ color: var(--scg-text-primary);
899
+ font: inherit;
900
+ font-size: 12px;
901
+ font-weight: 600;
902
+ inline-size: 100%;
903
+ min-inline-size: 0;
904
+ min-block-size: 34px;
905
+ padding: var(--scg-space-3) var(--scg-space-5);
906
+ }
907
+ .scg-ui-work-setting-select:hover:enabled { border-color: var(--scg-text-muted); }
908
+ .scg-ui-work-setting-select:disabled {
909
+ background: var(--scg-surface-muted);
910
+ color: var(--scg-text-muted);
911
+ cursor: not-allowed;
912
+ opacity: 1;
913
+ }
914
+ .scg-ui-work-request-section:focus { outline: none; }
915
+ /* Explanations live behind an info button and float over the content when asked for. */
916
+ .scg-ui-field-head {
917
+ align-items: center;
918
+ display: flex;
919
+ gap: var(--scg-space-2);
920
+ min-inline-size: 0;
921
+ position: relative;
922
+ }
923
+ .scg-ui-tip { display: inline-flex; }
924
+ .scg-ui-tip[hidden] { display: none; }
925
+ .scg-ui-tip-trigger {
926
+ align-items: center;
927
+ appearance: none;
928
+ background: var(--scg-surface-card);
929
+ block-size: 16px;
930
+ border: 1px solid var(--scg-border-control);
931
+ border-radius: var(--scg-radius-pill);
932
+ color: var(--scg-text-secondary);
933
+ cursor: help;
934
+ display: inline-flex;
935
+ flex: 0 0 auto;
936
+ font: inherit;
937
+ font-size: 10px;
938
+ font-style: italic;
939
+ font-weight: 700;
940
+ inline-size: 16px;
941
+ justify-content: center;
942
+ line-height: 1;
943
+ padding: 0;
944
+ }
945
+ .scg-ui-tip-trigger:hover { border-color: var(--scg-text-muted); color: var(--scg-text-primary); }
946
+ .scg-ui-tip-trigger:focus-visible { outline: 2px solid var(--scg-focus-ring); outline-offset: 2px; }
947
+ .scg-ui-tip-bubble {
948
+ background: var(--scg-text-primary);
949
+ border-radius: var(--scg-radius-field);
950
+ box-shadow: var(--scg-shadow-card);
951
+ color: var(--scg-surface-card);
952
+ font-size: 11px;
953
+ font-weight: 500;
954
+ inset-block-start: calc(100% + var(--scg-space-2));
955
+ inset-inline: 0;
956
+ line-height: 1.45;
957
+ opacity: 0;
958
+ padding: var(--scg-space-3) var(--scg-space-4);
959
+ pointer-events: none;
960
+ position: absolute;
961
+ transition: opacity var(--scg-duration-fast) ease;
962
+ visibility: hidden;
963
+ word-break: keep-all;
964
+ z-index: 3;
965
+ }
966
+ .scg-ui-tip:hover > .scg-ui-tip-bubble,
967
+ .scg-ui-tip-trigger:focus-visible + .scg-ui-tip-bubble {
968
+ opacity: 1;
969
+ pointer-events: auto;
970
+ visibility: visible;
971
+ }
972
+ .scg-ui-tip[data-dismissed="true"] > .scg-ui-tip-bubble {
973
+ opacity: 0;
974
+ pointer-events: none;
975
+ visibility: hidden;
976
+ }
977
+ @media (prefers-reduced-motion: reduce) {
978
+ .scg-ui-tip-bubble { transition: none; }
979
+ }
980
+ @media (max-width: 480px) {
981
+ .scg-ui-overlay { max-block-size: calc(100dvh - 20px); inset-inline-end: 10px; }
982
+ .scg-ui-overlay[data-scg-side="left"],
983
+ .scg-ui-launcher[data-scg-side="left"] { inset-inline-start: 10px; }
984
+ .scg-ui-launcher[data-scg-side="right"] { inset-inline-end: 10px; }
985
+ }
986
+ `,Xh=`
987
+ .scg-ui-work {
988
+ border-top: 1px solid var(--scg-border-divider);
989
+ display: grid;
990
+ gap: var(--scg-space-4);
991
+ margin-bottom: var(--scg-space-6);
992
+ padding-top: var(--scg-space-5);
993
+ }
994
+ .scg-ui-work:focus {
995
+ outline: none;
996
+ }
997
+ .scg-ui-work-provider-label {
998
+ color: var(--scg-text-secondary);
999
+ font-size: 11px;
1000
+ font-weight: 650;
1001
+ line-height: 1.35;
1002
+ }
1003
+ /* The native control keeps its own dropdown affordance: a bare box reads as a
1004
+ text field and hides that this is a choice. */
1005
+ .scg-ui-work-provider-select {
1006
+ background: var(--scg-surface-card);
1007
+ border: 1px solid var(--scg-border-field);
1008
+ border-radius: var(--scg-radius-field);
1009
+ color: var(--scg-text-primary);
1010
+ font: inherit;
1011
+ font-size: 12px;
1012
+ font-weight: 600;
1013
+ min-height: 34px;
1014
+ padding: var(--scg-space-3) var(--scg-space-5);
1015
+ width: 100%;
1016
+ }
1017
+ .scg-ui-work-provider-select:hover:enabled { border-color: var(--scg-text-muted); }
1018
+ .scg-ui-work-provider-select:focus-visible {
1019
+ outline: 2px solid var(--scg-focus-ring);
1020
+ outline-offset: 2px;
1021
+ }
1022
+ .scg-ui-work-provider-select:disabled {
1023
+ background: var(--scg-surface-muted);
1024
+ color: var(--scg-text-muted);
1025
+ cursor: not-allowed;
1026
+ opacity: 1;
1027
+ }
1028
+ .scg-ui-work-readiness {
1029
+ border: 1px solid var(--scg-status-neutral-border);
1030
+ border-radius: var(--scg-radius-field);
1031
+ font-size: 11px;
1032
+ font-weight: 650;
1033
+ line-height: 1.45;
1034
+ margin: 0;
1035
+ padding: var(--scg-space-3) var(--scg-space-4);
1036
+ word-break: keep-all;
1037
+ }
1038
+ .scg-ui-work-readiness[data-state="neutral"] {
1039
+ background: var(--scg-status-neutral-bg);
1040
+ border-color: var(--scg-status-neutral-border);
1041
+ color: var(--scg-status-neutral);
1042
+ }
1043
+ .scg-ui-work-readiness[data-state="positive"] {
1044
+ background: var(--scg-status-positive-bg);
1045
+ border-color: var(--scg-status-positive-border);
1046
+ color: var(--scg-status-positive);
1047
+ }
1048
+ .scg-ui-work-readiness[data-state="warning"] {
1049
+ background: var(--scg-status-warning-bg);
1050
+ border-color: var(--scg-status-warning-border);
1051
+ color: var(--scg-status-warning);
1052
+ }
1053
+ .scg-ui-work-readiness[data-state="danger"] {
1054
+ background: var(--scg-status-danger-bg);
1055
+ border-color: var(--scg-status-danger-border);
1056
+ color: var(--scg-status-danger);
1057
+ }
1058
+ .scg-ui-work-readiness[data-state="info"] {
1059
+ background: var(--scg-status-info-bg);
1060
+ border-color: var(--scg-status-info-border);
1061
+ color: var(--scg-status-info);
1062
+ }
1063
+ /* The panel already spends its one accent on 요소 선택. A request is a commit,
1064
+ so it reuses the dark commit fill the memo editor's save action established
1065
+ instead of competing with a second blue. */
1066
+ .scg-ui-overlay .scg-ui-work-request {
1067
+ background: var(--scg-accent-pressed);
1068
+ border: 1px solid var(--scg-accent-pressed);
1069
+ border-radius: var(--scg-radius-control);
1070
+ align-items: center;
1071
+ color: var(--scg-surface-card);
1072
+ display: inline-flex;
1073
+ font-weight: 700;
1074
+ gap: var(--scg-space-3);
1075
+ justify-content: center;
1076
+ min-height: 38px;
1077
+ width: 100%;
1078
+ }
1079
+ .scg-ui-work-request-spinner {
1080
+ block-size: 1em;
1081
+ border: 2px solid currentColor;
1082
+ border-block-start-color: transparent;
1083
+ border-radius: var(--scg-radius-pill);
1084
+ flex: 0 0 auto;
1085
+ inline-size: 1em;
1086
+ }
1087
+ .scg-ui-work-request-spinner:not([hidden]) {
1088
+ animation: scg-ui-work-request-spin calc(var(--scg-duration-fast) * 8) linear infinite;
1089
+ }
1090
+ .scg-ui-work-request-spinner[hidden] { display: none; }
1091
+ @keyframes scg-ui-work-request-spin {
1092
+ to { transform: rotate(1turn); }
1093
+ }
1094
+ .scg-ui-overlay .scg-ui-work-request:hover:enabled {
1095
+ background: var(--scg-text-body);
1096
+ border-color: var(--scg-text-body);
1097
+ }
1098
+ /* The panel's legacy rule paints a 1.9:1 ring; this one is more specific and
1099
+ uses the accessible token, so the selector and the action ring identically. */
1100
+ .scg-ui-overlay .scg-ui-work-request:focus-visible {
1101
+ outline: 2px solid var(--scg-focus-ring);
1102
+ outline-offset: 2px;
1103
+ }
1104
+ .scg-ui-overlay .scg-ui-work-request:disabled {
1105
+ background: var(--scg-surface-muted);
1106
+ border-color: var(--scg-border-control);
1107
+ color: var(--scg-text-muted);
1108
+ cursor: not-allowed;
1109
+ opacity: 1;
1110
+ }
1111
+ .scg-ui-work-request-reason {
1112
+ color: var(--scg-text-tertiary);
1113
+ font-size: 11px;
1114
+ line-height: 1.45;
1115
+ margin: 0;
1116
+ word-break: keep-all;
1117
+ }
1118
+ .scg-ui-work-request-reason:empty { display: none; }
1119
+ .scg-ui-work-failure {
1120
+ background: var(--scg-status-danger-bg);
1121
+ border: 1px solid var(--scg-status-danger-border);
1122
+ border-radius: var(--scg-radius-field);
1123
+ color: var(--scg-status-danger);
1124
+ font-size: 11px;
1125
+ font-weight: 650;
1126
+ line-height: 1.45;
1127
+ margin: 0;
1128
+ padding: var(--scg-space-3) var(--scg-space-4);
1129
+ word-break: keep-all;
1130
+ }
1131
+ .scg-ui-work-failure[hidden] { display: none; }
1132
+ .scg-ui-work-conflict,
1133
+ .scg-ui-work-session-conflict {
1134
+ background: var(--scg-status-info-bg);
1135
+ border: 1px solid var(--scg-status-info-border);
1136
+ border-radius: var(--scg-radius-field);
1137
+ color: var(--scg-status-info);
1138
+ font-size: 11px;
1139
+ font-weight: 650;
1140
+ line-height: 1.45;
1141
+ margin: 0;
1142
+ padding: var(--scg-space-3) var(--scg-space-4);
1143
+ word-break: keep-all;
1144
+ }
1145
+ .scg-ui-work-conflict[hidden],
1146
+ .scg-ui-work-session-conflict[hidden] { display: none; }
1147
+ .scg-ui-work-model-notice[hidden] { display: none; }
1148
+ .scg-ui-nowrap { white-space: nowrap; }
1149
+ /* The announcement channel is for assistive technology; the readiness notice
1150
+ already carries the same fact on screen. */
1151
+ .scg-ui-work-announce {
1152
+ clip-path: inset(50%);
1153
+ height: 1px;
1154
+ margin: 0;
1155
+ overflow: hidden;
1156
+ position: absolute;
1157
+ white-space: nowrap;
1158
+ width: 1px;
1159
+ }
1160
+ @media (prefers-reduced-motion: reduce) {
1161
+ .scg-ui-work-request-spinner:not([hidden]),
1162
+ .scg-ui-overlay .scg-ui-work-request:hover:enabled {
1163
+ animation: none;
1164
+ transform: none;
1165
+ }
1166
+ }
1167
+ `,Qh=`
1168
+ .scg-ui-work-session {
1169
+ border-top: 1px solid var(--scg-border-divider);
1170
+ display: grid;
1171
+ gap: var(--scg-space-3);
1172
+ margin-top: var(--scg-space-4);
1173
+ padding-top: var(--scg-space-4);
1174
+ }
1175
+ .scg-ui-work-session-heading { margin: 0; }
1176
+ .scg-ui-work-session-status {
1177
+ color: var(--scg-text-primary);
1178
+ font-size: 12px;
1179
+ font-weight: 600;
1180
+ line-height: 1.45;
1181
+ margin: 0;
1182
+ word-break: keep-all;
1183
+ }
1184
+ .scg-ui-work-session-status[hidden] { display: none; }
1185
+ /* A reset is a secondary, reversible choice next to the request commit, so it keeps the
1186
+ outlined control style instead of competing with the dark request fill. */
1187
+ .scg-ui-overlay .scg-ui-work-session-reset,
1188
+ .scg-ui-overlay .scg-ui-work-capabilities-retry {
1189
+ background: var(--scg-surface-card);
1190
+ border: 1px solid var(--scg-border-control);
1191
+ border-radius: var(--scg-radius-control);
1192
+ color: var(--scg-text-primary);
1193
+ font-weight: 650;
1194
+ min-height: 34px;
1195
+ width: 100%;
1196
+ }
1197
+ .scg-ui-overlay .scg-ui-work-session-reset:hover:enabled,
1198
+ .scg-ui-overlay .scg-ui-work-capabilities-retry:hover:enabled { border-color: var(--scg-text-muted); }
1199
+ .scg-ui-overlay .scg-ui-work-session-reset:focus-visible,
1200
+ .scg-ui-overlay .scg-ui-work-capabilities-retry:focus-visible {
1201
+ outline: 2px solid var(--scg-focus-ring);
1202
+ outline-offset: 2px;
1203
+ }
1204
+ .scg-ui-overlay .scg-ui-work-session-reset:disabled,
1205
+ .scg-ui-overlay .scg-ui-work-capabilities-retry:disabled {
1206
+ background: var(--scg-surface-muted);
1207
+ color: var(--scg-text-muted);
1208
+ cursor: not-allowed;
1209
+ opacity: 1;
1210
+ }
1211
+ .scg-ui-work-capabilities-retry[hidden] { display: none; }
1212
+ /* The blocked reason stays only as the reset control's description; on screen the settings
1213
+ alert shows it, so no line appears or disappears inside the panel. */
1214
+ .scg-ui-work-session-reason {
1215
+ clip-path: inset(50%);
1216
+ height: 1px;
1217
+ margin: 0;
1218
+ overflow: hidden;
1219
+ position: absolute;
1220
+ white-space: nowrap;
1221
+ width: 1px;
1222
+ }
1223
+ /* The panel notification area: a zero-height anchor after the footer status line, pinned to the
1224
+ bottom of the visible panel, so a notice covers the status line instead of pushing or covering
1225
+ any control. Settings notices show on the settings screen, request notices on the main one. */
1226
+ .scg-ui-panel-alert {
1227
+ block-size: 0;
1228
+ inset-block-end: 0;
1229
+ position: sticky;
1230
+ z-index: 2;
1231
+ }
1232
+ .scg-ui-panel-alert-text {
1233
+ background: var(--scg-status-info-bg);
1234
+ border: 1px solid var(--scg-status-info-border);
1235
+ border-radius: var(--scg-radius-field);
1236
+ box-shadow: var(--scg-shadow-card);
1237
+ color: var(--scg-status-info);
1238
+ font-size: 11px;
1239
+ font-weight: 650;
1240
+ inset-block-end: 0;
1241
+ inset-inline: 0;
1242
+ line-height: 1.45;
1243
+ margin: 0;
1244
+ padding: var(--scg-space-2) var(--scg-space-4);
1245
+ position: absolute;
1246
+ word-break: keep-all;
1247
+ }
1248
+ .scg-ui-panel-alert-text[hidden],
1249
+ .scg-ui-overlay:not(.scg-ui-overlay--settings) .scg-ui-settings-alert-text,
1250
+ .scg-ui-overlay--settings .scg-ui-work-request-alert-text { display: none; }
1251
+ /* A transient request reason stays only in the request button's description. */
1252
+ .scg-ui-work-request-reason[data-transient="true"] {
1253
+ clip-path: inset(50%);
1254
+ height: 1px;
1255
+ margin: 0;
1256
+ overflow: hidden;
1257
+ position: absolute;
1258
+ white-space: nowrap;
1259
+ width: 1px;
1260
+ }
1261
+ .scg-ui-work-session-warnings {
1262
+ display: grid;
1263
+ gap: var(--scg-space-3);
1264
+ }
1265
+ .scg-ui-work-session-warnings[hidden] { display: none; }
1266
+ .scg-ui-work-session-warning {
1267
+ background: var(--scg-status-warning-bg);
1268
+ border: 1px solid var(--scg-status-warning-border);
1269
+ border-radius: var(--scg-radius-field);
1270
+ color: var(--scg-status-warning);
1271
+ display: grid;
1272
+ font-size: 11px;
1273
+ font-weight: 650;
1274
+ gap: var(--scg-space-2);
1275
+ line-height: 1.45;
1276
+ padding: var(--scg-space-3) var(--scg-space-4);
1277
+ }
1278
+ .scg-ui-work-session-warning-text {
1279
+ margin: 0;
1280
+ word-break: keep-all;
1281
+ }
1282
+ /* A request ID has no break opportunities; it must wrap anywhere rather than overflow. */
1283
+ .scg-ui-work-session-warning-ids {
1284
+ margin: 0;
1285
+ overflow-wrap: anywhere;
1286
+ }
1287
+ .scg-ui-work-session-warning-label { margin-inline-end: var(--scg-space-1); }
1288
+ .scg-ui-work-session-warning-id {
1289
+ font: 600 11px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1290
+ }
1291
+ `,Zh=`
1292
+ .scg-ui-work-progress {
1293
+ border-top: 1px solid var(--scg-border-divider);
1294
+ display: grid;
1295
+ gap: var(--scg-space-4);
1296
+ padding-top: var(--scg-space-5);
1297
+ }
1298
+ .scg-ui-work-progress[hidden] { display: none; }
1299
+ .scg-ui-work-dependent { white-space: nowrap; }
1300
+ .scg-ui-work-progress-status,
1301
+ .scg-ui-work-duplicate-warning {
1302
+ border: 1px solid var(--scg-status-neutral-border);
1303
+ border-radius: var(--scg-radius-field);
1304
+ color: var(--scg-status-neutral);
1305
+ font-size: 11px;
1306
+ font-weight: 650;
1307
+ line-height: 1.45;
1308
+ margin: 0;
1309
+ overflow-wrap: break-word;
1310
+ padding: var(--scg-space-3) var(--scg-space-4);
1311
+ text-wrap: pretty;
1312
+ word-break: keep-all;
1313
+ }
1314
+ .scg-ui-work-progress[data-state="info"] .scg-ui-work-progress-status {
1315
+ background: var(--scg-status-info-bg);
1316
+ border-color: var(--scg-status-info-border);
1317
+ color: var(--scg-status-info);
1318
+ }
1319
+ .scg-ui-work-progress[data-state="positive"] .scg-ui-work-progress-status {
1320
+ background: var(--scg-status-positive-bg);
1321
+ border-color: var(--scg-status-positive-border);
1322
+ color: var(--scg-status-positive);
1323
+ }
1324
+ .scg-ui-work-progress[data-state="warning"] .scg-ui-work-progress-status,
1325
+ .scg-ui-work-duplicate-warning {
1326
+ background: var(--scg-status-warning-bg);
1327
+ border-color: var(--scg-status-warning-border);
1328
+ color: var(--scg-status-warning);
1329
+ }
1330
+ .scg-ui-work-progress[data-state="danger"] .scg-ui-work-progress-status {
1331
+ background: var(--scg-status-danger-bg);
1332
+ border-color: var(--scg-status-danger-border);
1333
+ color: var(--scg-status-danger);
1334
+ }
1335
+ .scg-ui-work-cancel,
1336
+ .scg-ui-work-retry-same,
1337
+ .scg-ui-work-new-request { width: 100%; }
1338
+ .scg-ui-work-progress .scg-ui-action {
1339
+ background: var(--scg-surface-card);
1340
+ border-color: var(--scg-border-control);
1341
+ color: var(--scg-text-body);
1342
+ }
1343
+ .scg-ui-work-progress .scg-ui-action:hover:not(:disabled) {
1344
+ background: var(--scg-surface-muted);
1345
+ border-color: var(--scg-text-muted);
1346
+ }
1347
+ .scg-ui-work-cancel { color: var(--scg-status-danger-action); }
1348
+ .scg-ui-work-preview-layer {
1349
+ align-items: center;
1350
+ display: grid;
1351
+ inset: 0;
1352
+ justify-items: center;
1353
+ padding: var(--scg-space-6);
1354
+ position: fixed;
1355
+ z-index: 2147483647;
1356
+ }
1357
+ .scg-ui-work-preview-layer[hidden] { display: none; }
1358
+ .scg-ui-work-preview-scrim {
1359
+ background: var(--scg-surface-scrim);
1360
+ inset: 0;
1361
+ position: fixed;
1362
+ }
1363
+ .scg-ui-work-preview {
1364
+ background: var(--scg-surface-card);
1365
+ border: 1px solid var(--scg-border-card);
1366
+ border-radius: var(--scg-radius-card);
1367
+ box-shadow: var(--scg-shadow-dialog);
1368
+ box-sizing: border-box;
1369
+ color: var(--scg-text-body);
1370
+ display: grid;
1371
+ gap: var(--scg-space-4);
1372
+ max-block-size: min(620px, calc(100dvh - 24px));
1373
+ inline-size: 440px;
1374
+ max-inline-size: calc(100vw - 24px);
1375
+ min-block-size: 0;
1376
+ padding: var(--scg-space-8);
1377
+ position: relative;
1378
+ }
1379
+ .scg-ui-work-preview-title {
1380
+ color: var(--scg-text-primary);
1381
+ font-size: 14px;
1382
+ font-weight: 650;
1383
+ line-height: 1.45;
1384
+ margin: 0;
1385
+ }
1386
+ .scg-ui-work-preview-description,
1387
+ .scg-ui-work-preview-execution,
1388
+ .scg-ui-work-preview-stale {
1389
+ font-size: 12px;
1390
+ line-height: 1.45;
1391
+ margin: 0;
1392
+ overflow-wrap: break-word;
1393
+ text-wrap: pretty;
1394
+ word-break: keep-all;
1395
+ }
1396
+ .scg-ui-work-preview-execution { min-inline-size: 0; }
1397
+ .scg-ui-work-preview-stale {
1398
+ background: var(--scg-status-warning-bg);
1399
+ border: 1px solid var(--scg-status-warning-border);
1400
+ border-radius: var(--scg-radius-field);
1401
+ color: var(--scg-status-warning);
1402
+ padding: var(--scg-space-3) var(--scg-space-4);
1403
+ }
1404
+ .scg-ui-work-preview-stale[hidden] { display: none; }
1405
+ .scg-ui-work-preview-list {
1406
+ display: grid;
1407
+ gap: var(--scg-space-3);
1408
+ list-style: none;
1409
+ margin: 0;
1410
+ min-block-size: 0;
1411
+ overflow-y: auto;
1412
+ padding: 0;
1413
+ }
1414
+ .scg-ui-work-preview-item {
1415
+ border-top: 1px solid var(--scg-border-divider);
1416
+ display: grid;
1417
+ gap: var(--scg-space-2);
1418
+ padding-block: var(--scg-space-4);
1419
+ }
1420
+ .scg-ui-work-preview-identity {
1421
+ color: var(--scg-text-tertiary);
1422
+ font: 650 11px/1.35 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1423
+ }
1424
+ .scg-ui-work-preview-summary {
1425
+ color: var(--scg-text-body);
1426
+ font-size: 12px;
1427
+ line-height: 1.45;
1428
+ overflow-wrap: break-word;
1429
+ text-wrap: pretty;
1430
+ word-break: keep-all;
1431
+ }
1432
+ .scg-ui-work-preview-actions {
1433
+ display: grid;
1434
+ gap: var(--scg-space-4);
1435
+ grid-template-columns: 1fr 1fr;
1436
+ }
1437
+ .scg-ui-work-preview-confirm {
1438
+ background: var(--scg-accent-pressed);
1439
+ border-color: var(--scg-accent-pressed);
1440
+ color: var(--scg-surface-card);
1441
+ }
1442
+ .scg-ui-work-preview :focus-visible {
1443
+ outline: 2px solid var(--scg-focus-ring);
1444
+ outline-offset: 2px;
1445
+ }
1446
+ @media (max-width: 480px) {
1447
+ .scg-ui-work-preview-actions { grid-template-columns: 1fr; }
1448
+ }
1449
+ @media (prefers-reduced-motion: reduce) {
1450
+ .scg-ui-work-progress .scg-ui-action,
1451
+ .scg-ui-work-preview .scg-ui-action { transition: none; transform: none; }
1452
+ }
1453
+ `,Jh=`
1454
+ .scg-ui-work-review {
1455
+ border-top: 1px solid var(--scg-border-divider);
1456
+ display: grid;
1457
+ gap: var(--scg-space-4);
1458
+ grid-template-columns: minmax(0, 1fr);
1459
+ margin-bottom: 0;
1460
+ padding-top: var(--scg-space-5);
1461
+ }
1462
+ .scg-ui-work-review[hidden] { display: none; }
1463
+ .scg-ui-work-review-status {
1464
+ background: var(--scg-status-positive-bg);
1465
+ border: 1px solid var(--scg-status-positive-border);
1466
+ border-radius: var(--scg-radius-field);
1467
+ color: var(--scg-status-positive);
1468
+ font-size: 11px;
1469
+ font-weight: 650;
1470
+ line-height: 1.45;
1471
+ margin: 0;
1472
+ overflow-wrap: break-word;
1473
+ padding: var(--scg-space-3) var(--scg-space-4);
1474
+ text-wrap: pretty;
1475
+ word-break: keep-all;
1476
+ }
1477
+ .scg-ui-work-review-acknowledge { width: 100%; }
1478
+ .scg-ui-annotation[data-work-completion] .scg-ui-annotation-resolution {
1479
+ color: var(--scg-status-positive);
1480
+ font-weight: 650;
1481
+ }
1482
+ .scg-ui-badge[data-badge-attention="pending"]::before {
1483
+ content: "";
1484
+ position: absolute;
1485
+ inset: calc(-1 * var(--scg-space-3));
1486
+ border: 3px solid var(--scg-badge-attention-color);
1487
+ border-radius: inherit;
1488
+ box-sizing: border-box;
1489
+ pointer-events: none;
1490
+ opacity: .35;
1491
+ animation: scg-badge-attention var(--scg-duration-badge-attention) ease-in-out infinite;
1492
+ }
1493
+ .scg-ui-badge:focus-visible {
1494
+ outline: 2px solid var(--scg-focus-ring);
1495
+ outline-offset: var(--scg-space-3);
1496
+ }
1497
+ @keyframes scg-badge-attention {
1498
+ 0%, 100% { opacity: .35; }
1499
+ 50% { opacity: 1; }
1500
+ }
1501
+ @media (prefers-reduced-motion: reduce) {
1502
+ .scg-ui-work-review .scg-ui-action { transition: none; transform: none; }
1503
+ .scg-ui-badge[data-badge-attention="pending"]::before {
1504
+ animation: none;
1505
+ opacity: 1;
1506
+ }
1507
+ }
1508
+ `,eg=`
1509
+ /* One layer, two siblings: the scrim owns the pointer and dims the page, the
1510
+ card sits above it untouched. The scrim is never a descendant of the card. */
1511
+ /* The layer paints nothing. It exists to hold one stacking context above every
1512
+ host element and to toggle both children with a single hidden state. */
1513
+ .scg-ui-work-warning-layer {
1514
+ position: fixed;
1515
+ z-index: 2147483647;
1516
+ }
1517
+ .scg-ui-work-warning-layer[hidden] { display: none; }
1518
+ .scg-ui-work-warning-scrim {
1519
+ background: var(--scg-surface-scrim);
1520
+ inset: 0;
1521
+ position: fixed;
1522
+ z-index: 0;
1523
+ }
1524
+ .scg-ui-work-warning {
1525
+ background: var(--scg-surface-card);
1526
+ border: 1px solid var(--scg-border-card);
1527
+ border-radius: var(--scg-radius-card);
1528
+ box-shadow: var(--scg-shadow-dialog);
1529
+ box-sizing: border-box;
1530
+ color: var(--scg-text-primary);
1531
+ display: grid;
1532
+ font: 500 13px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
1533
+ gap: var(--scg-space-4);
1534
+ /* Centred with auto margins, never with a transform: a transformed ancestor
1535
+ becomes the containing block for fixed children and would shrink the
1536
+ backdrop to the size of this card. */
1537
+ height: max-content;
1538
+ inset: 0;
1539
+ margin: auto;
1540
+ max-height: calc(100vh - 24px);
1541
+ max-width: calc(100vw - 24px);
1542
+ overflow-y: auto;
1543
+ padding: var(--scg-space-8);
1544
+ position: fixed;
1545
+ width: min(380px, calc(100vw - 24px));
1546
+ z-index: 1;
1547
+ }
1548
+
1549
+ .scg-ui-work-warning *,
1550
+ .scg-ui-work-warning *::before,
1551
+ .scg-ui-work-warning *::after { box-sizing: border-box; }
1552
+ .scg-ui-work-warning-title {
1553
+ color: var(--scg-text-primary);
1554
+ font-size: 14px;
1555
+ font-weight: 650;
1556
+ letter-spacing: -.01em;
1557
+ margin: 0;
1558
+ }
1559
+ .scg-ui-work-warning-body {
1560
+ color: var(--scg-text-body);
1561
+ margin: 0;
1562
+ word-break: keep-all;
1563
+ }
1564
+ .scg-ui-work-warning-provider {
1565
+ background: var(--scg-status-warning-bg);
1566
+ border: 1px solid var(--scg-status-warning-border);
1567
+ border-radius: var(--scg-radius-field);
1568
+ color: var(--scg-status-warning);
1569
+ font-size: 11px;
1570
+ font-weight: 650;
1571
+ margin: 0;
1572
+ padding: var(--scg-space-3) var(--scg-space-4);
1573
+ }
1574
+ .scg-ui-work-warning-optout-label {
1575
+ align-items: center;
1576
+ color: var(--scg-text-secondary);
1577
+ display: flex;
1578
+ font-size: 12px;
1579
+ font-weight: 600;
1580
+ gap: var(--scg-space-4);
1581
+ }
1582
+ .scg-ui-work-warning-optout {
1583
+ accent-color: var(--scg-accent-primary);
1584
+ height: 16px;
1585
+ margin: 0;
1586
+ width: 16px;
1587
+ }
1588
+ .scg-ui-work-warning-optout:focus-visible {
1589
+ outline: 2px solid var(--scg-focus-ring);
1590
+ outline-offset: 2px;
1591
+ }
1592
+ .scg-ui-work-warning-actions {
1593
+ display: flex;
1594
+ gap: var(--scg-space-4);
1595
+ justify-content: flex-end;
1596
+ }
1597
+ .scg-ui-work-warning .scg-ui-action {
1598
+ border-radius: var(--scg-radius-control);
1599
+ font-size: 12px;
1600
+ font-weight: 650;
1601
+ min-height: 34px;
1602
+ padding: var(--scg-space-4) var(--scg-space-6);
1603
+ transition: background var(--scg-duration-fast) ease, border-color var(--scg-duration-fast) ease;
1604
+ }
1605
+ .scg-ui-work-warning .scg-ui-work-warning-cancel {
1606
+ background: transparent;
1607
+ border: 0;
1608
+ color: var(--scg-text-secondary);
1609
+ }
1610
+ .scg-ui-work-warning .scg-ui-work-warning-cancel:hover:enabled {
1611
+ background: var(--scg-surface-muted);
1612
+ color: var(--scg-text-primary);
1613
+ }
1614
+ .scg-ui-work-warning .scg-ui-work-warning-confirm {
1615
+ background: var(--scg-accent-primary);
1616
+ border: 1px solid var(--scg-accent-primary);
1617
+ color: var(--scg-surface-card);
1618
+ }
1619
+ .scg-ui-work-warning .scg-ui-work-warning-confirm:hover:enabled {
1620
+ background: var(--scg-accent-primary-hover);
1621
+ border-color: var(--scg-accent-primary-hover);
1622
+ }
1623
+ .scg-ui-work-warning .scg-ui-action:focus-visible {
1624
+ outline: 2px solid var(--scg-focus-ring);
1625
+ outline-offset: 2px;
1626
+ }
1627
+ @media (prefers-reduced-motion: reduce) {
1628
+ .scg-ui-work-warning .scg-ui-action,
1629
+ .scg-ui-overlay .scg-ui-work-request,
1630
+ .scg-ui-work-provider-select {
1631
+ transition: none;
1632
+ }
1633
+ }
1634
+ @media (max-width: 480px) {
1635
+ .scg-ui-work-warning { width: calc(100vw - 20px); }
1636
+ }
1637
+ `;function tg(t){const e=t.createElement("style");return e.className="scg-ui-styles",e.textContent=`${Kh}${$h}${Bh}${Fh}${Hh}${Xh}${Qh}${eg}${Zh}${Jh}${Yh}`,e}function cr(t){const e=t.document,i=e.createElement("span");i.className="scg-ui-tip";const n=e.createElement("button");n.type="button",n.className="scg-ui-tip-trigger",n.textContent="i",n.setAttribute("aria-label",t.label);const s=e.createElement("span");s.className=["scg-ui-tip-bubble",t.bubbleClassName].filter(Boolean).join(" "),s.id=t.id,s.setAttribute("role","tooltip"),s.textContent=t.text,n.setAttribute("aria-describedby",s.id),i.append(n,s);const r=a=>{a.key!=="Escape"||i.dataset.dismissed==="true"||(a.stopPropagation(),i.dataset.dismissed="true")},o=()=>{delete i.dataset.dismissed};return n.addEventListener("keydown",r),n.addEventListener("blur",o),i.addEventListener("mouseleave",o),{element:i,trigger:n,bubble:s,setHidden(a){i.hidden=a,s.hidden=a},destroy(){n.removeEventListener("keydown",r),n.removeEventListener("blur",o),i.removeEventListener("mouseleave",o),i.remove()}}}const ig=Object.freeze({"eligibility-unknown":"저장된 메모가 있습니다. 새로 보낼 메모는 미리보기에서 확인합니다.","no-eligible-notes":qs}),xi=Object.freeze({selectLabel:"작업 제공자",requestLabel:"작업 요청",sectionLabel:"작업 제공자 설정"}),ng=Object.freeze({request:"작업 요청",previewing:"요청 준비 중",submitting:"요청 보내는 중",queued:"대기 중",preparing:"실행 준비 중",dispatching:"전달 중",running:"실행 중",cancelling:"취소 중",reconnecting:"상태 확인 중","request-failed":"요청 실패"}),Ni=Object.freeze({none:"사용 안 함","omo-native":"OMO Native","codex-cli":"Codex CLI","claude-code":"Claude Code"}),lr=Object.freeze({none:"제공자가 선택되지 않았습니다.",ready:"요청을 받을 준비가 되었습니다.",missing:"제공자를 찾지 못했습니다.","auth-required":"제공자 로그인이 필요합니다.",incompatible:"제공자 버전이 호환되지 않습니다.",unavailable:"제공자에 연결하지 못했습니다."}),sg=Object.freeze({none:"","select-provider":"목록에서 제공자를 고르세요.","install-provider":"제공자를 설치한 뒤 다시 확인하세요.","authenticate-provider":"터미널에서 제공자 로그인을 마친 뒤 다시 확인하세요.","update-provider":"지원되는 버전으로 올린 뒤 다시 확인하세요.","retry-provider":"제공자를 다시 실행한 뒤 재연결하세요."}),Fe=Object.freeze({disconnected:"연결이 끊겼습니다. 다시 연결한 뒤 요청하세요.","provider-unknown":"제공자 설정을 불러오는 중입니다.","work-active":"진행 중인 작업이 끝난 뒤에 요청하세요.",busy:"제공자 설정을 저장하는 중입니다.","settings-pending":"제공자 설정을 반영하는 중입니다. 끝나면 요청하세요.","none-provider":"작업을 보낼 제공자를 먼저 고르세요.","provider-unready":"고른 제공자가 아직 요청을 받지 못합니다.","no-eligible-notes":"이 페이지에 보낼 메모가 없습니다."}),rg=Object.freeze({SCG_WORK_PROVIDER_INVALID:"이 브라우저가 모르는 설정 형식을 받아 적용을 거부했습니다. 최신 버전으로 올린 뒤 다시 확인하세요.",SCG_WORK_ACTIVE:"진행 중인 작업이 있어 설정을 바꾸지 못했습니다."});function og(t){return`${rg[t]??ug} (${t})`}const ag=Object.freeze({SCG_OMO_RUNTIME_AUTHORITY_ABSENT:"이 Scene Glass 빌드에는 승인된 OMO 런타임 정보가 없습니다.",SCG_OMO_RUNTIME_UNSUPPORTED:"x64에서는 upstream PTY prebuild 지원을 기다리는 동안 OMO를 사용할 수 없습니다. darwin-arm64에서 실행하거나 다른 작업 제공자를 선택하세요. Scene Glass setup/start는 계속 지원됩니다.",SCG_OMO_RUNTIME_MISSING:"승인된 OMO 런타임이 설치되지 않았습니다.",SCG_OMO_RUNTIME_INTEGRITY:"설치된 OMO 런타임이 승인된 파일과 달라 실행하지 않았습니다.",SCG_RUNTIME_AUTHORITY_ABSENT:"이 Scene Glass 빌드에는 승인된 작업 제공자 런타임 정보가 없습니다.",SCG_RUNTIME_UNSUPPORTED:"이 플랫폼은 선택한 작업 제공자의 승인된 런타임을 지원하지 않습니다.",SCG_RUNTIME_MISSING:"승인된 작업 제공자 런타임이 설치되지 않았습니다.",SCG_RUNTIME_INTEGRITY:"설치된 작업 제공자 런타임이 승인된 파일과 달라 실행하지 않았습니다.",SCG_RUNTIME_VERSION_MISMATCH:"작업 제공자 런타임 버전이 승인된 버전과 다릅니다.",SCG_RUNTIME_CONVERSATION_UNQUALIFIED:"이 대화는 현재 작업 제공자 런타임과 호환성이 확인되지 않았습니다.",SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED:"새 세션을 시작하세요. 기존 대화는 보존됩니다."});function cg(t){return t==="start-new-session"?"설정에서 새 세션 시작을 누르세요.":`터미널에서 ${t}을 실행한 뒤 다시 확인하세요.`}function lg(t){if(t.runtime!==null){const{code:n,action:s}=t.runtime,r=s===null?"":` ${cg(s)}`;return`${ag[n]}${r} (${n})`}const e=sg[t.remediationKey],i=lr[t.readinessKey];return e===""?i:`${i} ${e}`}function dg(t){const e=Ni[t.provider];switch(t.announcementKey){case"conflict":return`제공자 설정이 최신 상태로 갱신되었습니다. 현재 제공자 ${e}.`;case"unknown":return Fe["provider-unknown"];case"disconnected":return Fe.disconnected;case"work-active":return Fe["work-active"];case"saving":return Fe.busy;case"none":case"ready":case"unready":return t.runtime?.code==="SCG_OMO_RUNTIME_UNSUPPORTED"?`${e} · 이 플랫폼에서는 OMO를 지원하지 않습니다. (${t.runtime.code})`:`${e} · ${lr[t.readinessKey]}`}}const ug="제공자 설정을 적용하지 못했습니다.",Z=Object.freeze({heading:"대화 세션",explanationLabel:"대화 세션 안내",modelNoticeLabel:"모델 변경 안내",resetLabel:"새 세션 시작",explanation:"다음 요청부터 새 대화로 시작합니다. 이전 대화는 지우지 않고, 모델과 추론 강도도 그대로 둡니다.",status:Object.freeze({continues:"다음 요청은 지금 대화를 이어 갑니다.","next-new":"다음 요청은 새 대화로 시작합니다.","new-session-pending":"새 세션을 준비했습니다. 다음 요청은 새 대화로 시작합니다.","restart-required":"기존 대화는 보존됩니다. 새 세션 시작을 눌러 주세요."}),block:Object.freeze({disconnected:"연결이 끊겼습니다. 다시 연결한 뒤에 시작하세요.",unknown:"대화 상태를 불러오는 중입니다.","work-active":"진행 중인 작업이 끝난 뒤에 시작하세요.",busy:"제공자 설정을 저장하는 중입니다.",resetting:"새 세션을 준비하는 중입니다.","none-provider":"작업을 보낼 제공자를 먼저 고르세요."}),modelNotice:"모델을 바꾸면 다음 요청부터 새 대화로 시작합니다. 추론 강도만 바꾸면 지금 대화를 이어 갑니다.",warning:Object.freeze({prior:"이전 요청이 끝났는지 확인하지 못했습니다. 그 요청이 시작한 프로세스가 아직 실행 중일지 모릅니다.",legacy:"이전 버전에서 진행 중이던 요청이 끝났는지 확인하지 못했습니다. 그 요청이 시작한 프로세스가 아직 실행 중일지 모릅니다.",requestLabel:"요청 ID",more:t=>`외 ${t}건`})}),dr="다른 곳에서 제공자 설정이 바뀌어 최신 값을 다시 불러왔습니다.",Ie=Object.freeze({title:"전체 권한 경고",productName:"Scene Glass",bodyBeforeProduct:"고른 제공자는 지금 로그인한 사용자의 권한으로 실행됩니다. 승인을 따로 묻지 않고, 프로젝트 바깥의 파일까지 읽고 고치고 지웁니다. 명령 실행과 네트워크 사용도 막지 않습니다. ",bodyAfterProduct:"는 이 권한을 좁히지 않습니다.",body:"고른 제공자는 지금 로그인한 사용자의 권한으로 실행됩니다. 승인을 따로 묻지 않고, 프로젝트 바깥의 파일까지 읽고 고치고 지웁니다. 명령 실행과 네트워크 사용도 막지 않습니다. Scene Glass는 이 권한을 좁히지 않습니다.",optOut:"다시 보지 않기",confirm:"이해했습니다",cancel:"취소"});class hg{constructor(e){this.options=e;const i=e.document;this.element=i.createElement("div"),this.element.className="scg-ui-work-execution",this.#s=cr({document:i,id:`scg-ui-work-model-notice-${e.idSuffix}`,label:Z.modelNoticeLabel,text:Z.modelNotice,bubbleClassName:"scg-ui-work-model-notice"}),this.#e=this.#c("model","모델",this.#s),this.#t=this.#c("effort","추론 강도"),this.#i=i.createElement("p"),this.#i.className="scg-ui-settings-notice scg-ui-work-capabilities",this.#i.id=`scg-ui-work-capabilities-${e.idSuffix}`,this.#e.setAttribute("aria-describedby",`${this.#s.bubble.id} ${this.#i.id}`),this.#t.setAttribute("aria-describedby",this.#i.id),this.element.append(this.#i),this.#n=i.createElement("button"),this.#n.type="button",this.#n.className="scg-ui-action scg-ui-work-capabilities-retry",this.#n.textContent="모델 목록 다시 확인",this.#n.hidden=!0,this.#n.setAttribute("aria-describedby",this.#i.id),this.element.append(this.#n),this.#n.addEventListener("click",this.#h),this.#e.addEventListener("change",this.#u),this.#t.addEventListener("change",this.#g)}options;element;#e;#t;#i;#s;#n;#o=sn;#r=[];#a=[];#l=!1;setState(e,i){this.#o=e.selection?.executionSettings??sn,this.#s.setHidden(i.provider==="none");const n=e.capabilities,s=e.capabilitiesPending!==!0&&n?.provider===i.provider&&n.status==="available",r=s?n.models:[],o=r.find(l=>l.model===this.#o.model);this.#r=r.map(l=>l.model),this.#a=o?.reasoningEfforts??[],this.#d(this.#e,r.map(l=>({value:l.model,label:l.displayName})),this.#o.model),this.#d(this.#t,this.#a.map(l=>({value:l,label:l})),this.#o.reasoningEffort);const a=i.selectDisabled||i.provider==="none"||e.capabilitiesPending===!0;this.#e.disabled=a||this.#r.length===0&&this.#o.model===null,this.#t.disabled=a||this.#o.model===null||this.#a.length===0&&this.#o.reasoningEffort===null,this.#e.setAttribute("aria-busy",String(e.capabilitiesPending===!0));const c=e.capabilitiesPending===!0?"loading":s?r.length===0?"models-empty":this.#o.model===null?"inherited":o===void 0?"model-unavailable":o.reasoningEfforts===null?"efforts-unknown":o.reasoningEfforts.length===0?"efforts-empty":this.#o.reasoningEffort!==null&&!this.#a.includes(this.#o.reasoningEffort)?"effort-unavailable":"available":"models-unknown";this.#i.dataset.capabilities=c,this.#i.textContent=gg[c],e.capabilitiesPending!==!0&&(this.#l=!1),this.#n.hidden=i.provider==="none"||s||this.options.onRetry===void 0||e.capabilitiesPending===!0&&!this.#l,this.#n.disabled=a,this.#n.setAttribute("aria-disabled",String(a)),this.#n.setAttribute("aria-busy",String(e.capabilitiesPending===!0))}destroy(){this.#e.removeEventListener("change",this.#u),this.#t.removeEventListener("change",this.#g),this.#n.removeEventListener("click",this.#h),this.#s.destroy(),this.element.remove()}#c(e,i,n){const s=this.options.document.createElement("label");s.className="scg-ui-work-provider-label",s.textContent=i;const r=this.options.document.createElement("select");if(r.className=`scg-ui-work-setting-select scg-ui-work-${e}-select`,r.id=`scg-ui-work-${e}-${this.options.idSuffix}`,s.htmlFor=r.id,n===void 0)return this.element.append(s,r),r;const o=this.options.document.createElement("div");return o.className="scg-ui-field-head",o.append(s,n.element),this.element.append(o,r),r}#d(e,i,n){const s=[{value:"",label:"기본 설정 상속"},...i];n!==null&&!i.some(r=>r.value===n)&&s.push({value:n,label:`${n} (현재 사용 불가)`}),e.replaceChildren(...s.map(r=>{const o=this.options.document.createElement("option");return o.value=r.value,o.textContent=r.label,o.disabled=r.value!==""&&!i.some(a=>a.value===r.value),o})),e.value=n??""}#u=()=>{const e=this.#e.value;this.#e.disabled||e!==""&&!this.#r.includes(e)||this.options.onChange({executionSettings:{model:e===""?null:e,reasoningEffort:null}})};#h=()=>{this.#n.hidden||this.#n.disabled||(this.#l=!0,this.#n.disabled=!0,this.#n.setAttribute("aria-disabled","true"),this.#n.setAttribute("aria-busy","true"),this.options.onRetry?.())};#g=()=>{const e=this.#t.value;this.#t.disabled||e!==""&&!this.#a.includes(e)||this.options.onChange({executionSettings:{model:this.#o.model,reasoningEffort:e===""?null:e}})}}const gg={loading:"모델 설정을 확인 중입니다.","models-unknown":"모델 목록을 확인하지 못했습니다. 선택한 설정은 유지됩니다. 목록을 다시 확인하세요.","models-empty":"이 제공자는 선택 가능한 모델을 제공하지 않습니다.",inherited:"제공자의 기본 모델과 추론 강도를 상속합니다.","model-unavailable":"선택한 모델은 현재 목록에 없습니다. 설정을 다시 선택하세요.","efforts-unknown":"이 모델의 추론 강도 목록을 확인하지 못했습니다.","efforts-empty":"이 모델은 추론 강도 선택을 지원하지 않습니다.","effort-unavailable":"선택한 추론 강도는 현재 목록에 없습니다. 설정을 다시 선택하세요.",available:"선택한 모델이 지원하는 추론 강도만 표시합니다."},fg=Object.freeze({queued:"queued",preparing:"preparing",dispatching:"dispatching",delivered:"dispatching",running:"running",cancelling:"cancelling",completed:null,failed:null,cancelled:null,indeterminate:null}),ve=Object.freeze({busy:!0,spinnerVisible:!0,enabled:!1});function pg(t){const e=t.requestState===null?null:fg[t.requestState];return t.connection!=="ready"&&e!==null?rt("reconnecting"):t.pending==="cancelling"?rt("cancelling"):e!==null?rt(e):t.pending==="submitting"?rt("submitting"):t.pending==="previewing"?rt("previewing"):t.failureCode!==null&&t.failureCode!=="SCG_WORK_NO_ELIGIBLE"?Object.freeze({phase:"request-failed",labelKey:"request-failed",busy:!1,spinnerVisible:!1,enabled:t.enabled}):Object.freeze({phase:"idle",labelKey:"request",busy:!1,spinnerVisible:!1,enabled:t.enabled})}function rt(t){switch(t){case"previewing":return Object.freeze({phase:t,labelKey:"previewing",...ve});case"submitting":return Object.freeze({phase:t,labelKey:"submitting",...ve});case"queued":return Object.freeze({phase:t,labelKey:"queued",...ve});case"preparing":return Object.freeze({phase:t,labelKey:"preparing",...ve});case"dispatching":return Object.freeze({phase:t,labelKey:"dispatching",...ve});case"running":return Object.freeze({phase:t,labelKey:"running",...ve});case"cancelling":return Object.freeze({phase:t,labelKey:"cancelling",...ve});case"reconnecting":return Object.freeze({phase:t,labelKey:"reconnecting",...ve})}}const mg=/^SCG_[A-Z0-9_]{1,80}$/u;function wg(t){const e=t.selection!==null&&t.readiness!==null&&t.recovery==="settled",i=t.selection?.provider??"none",n=t.readiness?.status??"none",s=t.readiness?.remediation??"select-provider",r=t.requestState!==null&&!Ee(t.requestState),o=vg(t,e,r),a=bg(t,{known:e,active:r,provider:i,readinessKey:n}),c=pg({connection:t.connection,requestState:t.requestState,pending:t.requestPending,failureCode:t.requestFailureCode,enabled:a===null}),l=i==="none"?null:i,d=a!==null||c.busy?null:t.requestFailureCode==="SCG_WORK_NO_ELIGIBLE"?"no-eligible-notes":t.eligibleNoteCount===null?"eligibility-unknown":null;return Object.freeze({provider:i,generation:t.selection?.generation??null,readinessKey:n,remediationKey:s,runtime:t.readiness?.runtime??null,readinessTone:Eg(n),selectDisabled:o!==null,selectBusy:t.pending!=="idle",lockReason:o,requestAction:c,requestBlock:a,requestNotice:d,warningRequired:yg(t,l),warningProvider:l,conflict:t.conflict,failureCode:mg.test(t.failureCode??"")?t.failureCode:null,announcementKey:Sg(t,{known:e,active:r,readinessKey:n,provider:i})})}function vg(t,e,i){return t.connection!=="ready"?"disconnected":e?i?"work-active":t.pending==="idle"?null:"saving":"unknown"}function bg(t,e){return t.connection!=="ready"?"disconnected":e.known?e.active?"work-active":t.pending!=="idle"?"busy":t.capabilitiesPending===!0?"settings-pending":e.provider==="none"?"none-provider":e.readinessKey!=="ready"?"provider-unready":t.eligibleNoteCount===0?"no-eligible-notes":null:"provider-unknown"}function yg(t,e){if(e===null||t.selection===null)return!1;const i=t.warningContractVersion;return!t.selection.warningAcknowledgments.some(n=>n.provider===e&&n.contractVersion===i)}function Eg(t){switch(t){case"none":return"neutral";case"ready":return"positive";case"missing":case"auth-required":case"incompatible":return"warning";case"unavailable":return"danger"}}function Sg(t,e){return t.conflict?"conflict":t.connection!=="ready"?"disconnected":e.known?e.active?"work-active":t.pending!=="idle"?"saving":e.provider==="none"?"none":e.readinessKey==="ready"?"ready":"unready":"unknown"}function kg(t,e){const i=t.createElement("button");i.className="scg-ui-action scg-ui-work-request",i.type="button";const n=t.createElement("span");n.className="scg-ui-work-request-spinner",n.setAttribute("aria-hidden","true"),n.hidden=!0;const s=t.createElement("span");s.className="scg-ui-work-request-label",s.textContent=xi.requestLabel,i.append(n,s);const r=t.createElement("p");r.className="scg-ui-work-request-reason",r.id=`scg-ui-work-reason-${e}`,i.setAttribute("aria-describedby",r.id);const o=t.createElement("p");return o.className="scg-ui-panel-alert-text scg-ui-work-request-alert-text",o.setAttribute("aria-hidden","true"),o.hidden=!0,{button:i,reason:r,alert:o,setState(a){const c=a.requestAction;i.dataset.requestPhase=c.phase,i.disabled=!c.enabled,i.setAttribute("aria-disabled",String(!c.enabled)),i.setAttribute("aria-busy",String(c.busy)),n.hidden=!c.spinnerVisible,s.textContent=ng[c.labelKey],r.textContent=a.requestBlock!==null?Fe[a.requestBlock]:a.requestNotice===null?"":ig[a.requestNotice],r.dataset.requestNotice=a.requestNotice??"";const l=a.requestBlock,d=l==="busy"||l==="settings-pending"?l:null;r.dataset.transient=String(d!==null);const u=d===null?"":Fe[d];o.dataset.requestBlock=d??"",o.textContent!==u&&(o.textContent=u),o.hidden=u===""}}}const Cg=3;class Ig{constructor(e){this.options=e;const i=e.document;this.element=i.createElement("div"),this.element.className="scg-ui-work-session";const n=i.createElement("p");n.className="scg-ui-work-provider-label scg-ui-work-session-heading",n.textContent=Z.heading,this.#e=cr({document:i,id:`scg-ui-work-session-help-${e.idSuffix}`,label:Z.explanationLabel,text:Z.explanation,bubbleClassName:"scg-ui-work-session-help"});const s=i.createElement("div");s.className="scg-ui-field-head",s.append(n,this.#e.element),this.#t=i.createElement("p"),this.#t.className="scg-ui-work-session-status",this.#i=this.#c(),this.#s=i.createElement("button"),this.#s.className="scg-ui-action scg-ui-work-session-reset",this.#s.type="button",this.#s.textContent=Z.resetLabel,this.#n=i.createElement("p"),this.#n.className="scg-ui-work-session-reason",this.#n.id=`scg-ui-work-session-reason-${e.idSuffix}`,this.#s.setAttribute("aria-describedby",`${this.#e.bubble.id} ${this.#n.id}`),this.#o=i.createElement("p"),this.#o.className="scg-ui-work-session-conflict",this.#o.dataset.state="info",this.#o.textContent=dr,this.#o.hidden=!0,this.element.append(s,this.#t,this.#o,this.#i,this.#s,this.#n),this.alertElement=i.createElement("p"),this.alertElement.className="scg-ui-panel-alert-text scg-ui-settings-alert-text",this.alertElement.setAttribute("aria-hidden","true"),this.alertElement.hidden=!0,this.requestWarnings=this.#c(),this.#s.addEventListener("click",this.#l)}options;element;requestWarnings;alertElement;#e;#t;#i;#s;#n;#o;#r=!1;#a="";setState(e){this.#r=e.resetEnabled,this.#s.disabled=!e.resetEnabled,this.#s.setAttribute("aria-disabled",String(!e.resetEnabled)),this.#s.setAttribute("aria-busy",String(e.resetBusy)),this.#n.dataset.sessionBlock=e.resetBlock??"",this.#n.textContent=e.resetBlock===null?"":Z.block[e.resetBlock];const i=e.resetBlock===null||e.resetBlock==="none-provider"?"":Z.block[e.resetBlock];this.alertElement.dataset.sessionBlock=i===""?"":e.resetBlock??"",this.alertElement.textContent!==i&&(this.alertElement.textContent=i),this.alertElement.hidden=i==="",this.#o.hidden=!e.conflict,this.#t.hidden=e.statusKey===null,this.#t.dataset.sessionState=e.statusKey??"",this.#t.textContent=e.statusKey===null?"":Z.status[e.statusKey];const n=JSON.stringify(e.warnings);if(n!==this.#a){this.#a=n;for(const s of[this.#i,this.requestWarnings])s.replaceChildren(...e.warnings.map(r=>this.#d(r))),s.hidden=e.warnings.length===0}}destroy(){this.#r=!1,this.#s.removeEventListener("click",this.#l),this.requestWarnings.remove(),this.#e.destroy(),this.alertElement.remove(),this.element.remove()}#l=()=>{!this.#r||this.#s.disabled||this.options.onReset()};#c(){const e=this.options.document.createElement("div");return e.className="scg-ui-work-session-warnings",e.hidden=!0,e}#d(e){const i=this.options.document,n=i.createElement("div");n.className="scg-ui-work-session-warning",n.dataset.state="warning",n.dataset.warningCode=e.code;const s=i.createElement("p");s.className="scg-ui-work-session-warning-text";const r=i.createElement("p");r.className="scg-ui-work-session-warning-ids";const o=i.createElement("span");o.className="scg-ui-work-session-warning-label",o.textContent=Z.warning.requestLabel,r.append(o);let a;e.code==="SCG_WORK_PRIOR_EXECUTION_UNCONFIRMED"?(s.textContent=Z.warning.prior,a=[e.requestId]):(s.textContent=Z.warning.legacy,a=e.requestIds.slice(0,Cg));for(const l of a){const d=i.createElement("code");d.className="scg-ui-work-session-warning-id",d.textContent=l,r.append(" ",d)}const c=e.code==="SCG_WORK_PRIOR_EXECUTION_UNCONFIRMED"?0:e.requestCount-a.length;return c>0&&r.append(` ${Z.warning.more(c)}`),n.append(s,r),n}}function Ag(t,e){const i=e.provider!=="none"&&t.session?.provider===e.provider?t.session:null,n=Og(t,e,i!==null);return Object.freeze({statusKey:i===null?null:i.state==="new-session-pending"?"new-session-pending":i.state==="restart-required"?"restart-required":i.nextRequestStartsNewConversation?"next-new":"continues",resetEnabled:n===null,resetBusy:t.pending==="resetting",resetBlock:n,warnings:i?.warnings??Object.freeze([]),conflict:e.conflict&&e.failureCode===null})}function Og(t,e,i){switch(e.lockReason){case"disconnected":return"disconnected";case"unknown":return"unknown";case"work-active":return"work-active";case"saving":return t.pending==="resetting"?"resetting":"busy"}return t.requestPending!=="idle"?"busy":e.provider==="none"?"none-provider":i?null:"unknown"}function ur(t,e,i){if(hr(t,e))return!0;const n=_g(null,i.fallbackFocus,i.background);if(n!==null)return n.focus(),!1;const s=t.ownerDocument.activeElement;return ot(t,s)&&typeof s=="object"&&s!==null&&"blur"in s&&typeof s.blur=="function"&&s.blur(),!1}function hr(t,e){return e===null||ot(t,e)||!Li(e)?!1:(e.focus(),!0)}function _g(t,e,i){const n=e();return n!==null&&Li(n)?n:Li(i)?i:null}function Pi(t){return typeof t=="object"&&t!==null&&"parentElement"in t}function ot(t,e){for(let i=e;Pi(i);i=i.parentElement)if(i===t)return!0;return!1}function Li(t){if(!ot(t.ownerDocument.body,t)||"disabled"in t&&t.disabled===!0)return!1;for(let e=t;e!==null;){if(!Tg(e)||e.hidden||e.inert)return!1;e=e.parentElement}return!0}function Tg(t){return Pi(t)&&"hidden"in t&&typeof t.hidden=="boolean"&&"inert"in t&&typeof t.inert=="boolean"}function Rg(t){const e=t.document,i=e.createElement("div");i.className="scg-ui-work-warning-layer",i.hidden=!0;const n=e.createElement("div");n.className="scg-ui-work-warning-scrim",n.setAttribute("aria-hidden","true");const s=e.createElement("div");s.className="scg-ui-work-warning",s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),i.append(n,s);const r=e.createElement("h2");r.className="scg-ui-work-warning-title",r.id=`scg-ui-work-warning-title-${t.idSuffix}`,r.textContent=Ie.title,s.setAttribute("aria-labelledby",r.id);const o=e.createElement("p");o.className="scg-ui-work-warning-body",o.id=`scg-ui-work-warning-body-${t.idSuffix}`;const a=e.createElement("span");a.className="scg-ui-nowrap",a.textContent=Ie.productName,o.append(Ie.bodyBeforeProduct,a,Ie.bodyAfterProduct),s.setAttribute("aria-describedby",o.id);const c=e.createElement("p");c.className="scg-ui-work-warning-provider";const l=e.createElement("input");l.className="scg-ui-work-warning-optout",l.type="checkbox";const d=e.createElement("span");d.textContent=Ie.optOut;const u=e.createElement("label");u.className="scg-ui-work-warning-optout-label",u.append(l,d);const h=e.createElement("button");h.className="scg-ui-action scg-ui-work-warning-cancel",h.type="button",h.textContent=Ie.cancel;const f=e.createElement("button");f.className="scg-ui-action scg-ui-work-warning-confirm",f.type="button",f.textContent=Ie.confirm;const b=e.createElement("div");b.className="scg-ui-work-warning-actions",b.append(h,f),s.append(r,o,c,u,b);const y=[l,h,f];let T=null,E=null;const w=()=>{const g=T;T=null,E=null,ur(i,g,t)},R=()=>{t.background.inert=!1,t.background.removeAttribute("aria-hidden")},x=()=>{i.hidden||(i.hidden=!0,l.checked=!1,e.removeEventListener("focusin",v),R(),w())},G=()=>{x()},M=()=>{const g=E,O=l.checked;g!==null&&(x(),t.handlers.onConfirm({provider:g,remember:O}))};function v(g){i.hidden||!Pi(g.target)||ot(s,g.target)||l.focus()}const S=g=>{if(i.hidden)return;if(g.key==="Escape"){g.preventDefault(),x();return}if(g.key!=="Tab")return;const O=e.activeElement,j=y.findIndex(be=>be===O),L=g.shiftKey?-1:1,U=y[(j+L+y.length)%y.length];U!==void 0&&(g.preventDefault(),U.focus())};return h.addEventListener("click",G),f.addEventListener("click",M),i.addEventListener("keydown",S),{element:i,open(g,O){T=g,E=O,l.checked=!1,c.textContent=Ni[O],i.hidden=!1,t.background.inert=!0,t.background.setAttribute("aria-hidden","true"),e.addEventListener("focusin",v),l.focus()},close:x,destroy(){i.hidden=!0,T=null,E=null,e.removeEventListener("focusin",v),R(),h.removeEventListener("click",G),f.removeEventListener("click",M),i.removeEventListener("keydown",S),i.remove()}}}let xg=0;const Ng=Object.freeze({connection:"connecting",selection:null,readiness:null,warningContractVersion:null,requestState:null,eligibleNoteCount:0,pending:"idle",conflict:!1,recovery:"pending",failureCode:null,requestPending:"idle",requestFailureCode:null});function Pg(t){const e=t.document,i=t.handlers,n=String(xg+=1),s=e.createElement("div");s.className="scg-ui-work",s.setAttribute("role","group"),s.setAttribute("aria-label",xi.sectionLabel),s.tabIndex=-1;const r=e.createElement("div");r.className="scg-ui-work-configuration";const o=e.createElement("div");o.className="scg-ui-work scg-ui-work-request-section",o.tabIndex=-1;const a=new hg({document:e,idSuffix:n,onChange:S=>i.onExecutionSettingsChange?.(S),...i.onCapabilitiesRead===void 0?{}:{onRetry:i.onCapabilitiesRead}}),c=e.createElement("label");c.className="scg-ui-work-provider-label",c.textContent=xi.selectLabel;const l=e.createElement("select");l.className="scg-ui-work-provider-select",l.id=`scg-ui-work-provider-${n}`,c.htmlFor=l.id;for(const S of Zt){const g=e.createElement("option");g.value=S,g.textContent=Ni[S],l.append(g)}const d=e.createElement("p");d.className="scg-ui-work-readiness",d.id=`scg-ui-work-readiness-${n}`;const u=kg(e,n),h=u.button,f=u.reason,b=e.createElement("p");b.className="scg-ui-work-conflict",b.dataset.state="info",b.hidden=!0,b.textContent=dr;const y=e.createElement("p");y.className="scg-ui-work-failure",y.dataset.state="danger",y.hidden=!0;const T=e.createElement("p");T.className="scg-ui-work-announce",T.setAttribute("role","status"),T.setAttribute("aria-live","polite"),T.setAttribute("aria-atomic","true");const E=new Ig({document:e,idSuffix:n,onReset:()=>i.onSessionReset?.()});r.append(c,l,a.element,E.element),o.append(d,E.requestWarnings,b,y,h,f);const w=e.createElement("div");w.className="scg-ui-panel-alert",w.append(E.alertElement,u.alert),s.append(r,o,T);const R=Rg({document:e,idSuffix:n,background:t.background,fallbackFocus:()=>h.disabled?o:h,handlers:{onConfirm:({provider:S,remember:g})=>{Promise.resolve(i.onWarningAcknowledge({provider:S,remember:g})).then(()=>{i.onRequestIntent()})}}});let x=null;const G=S=>{const g=wg(S);x!==null&&x.generation!==g.generation&&R.close(),x=g,E.setState(Ag(S,g)),l.value=g.provider,l.disabled=g.selectDisabled,l.setAttribute("aria-busy",String(g.selectBusy)),a.setState(S,g),d.hidden=g.readinessTone==="positive",d.textContent=d.hidden?"":lg(g),d.dataset.state=g.readinessTone,d.hidden?l.removeAttribute("aria-describedby"):l.setAttribute("aria-describedby",d.id),u.setState(g),b.hidden=!g.conflict||g.failureCode!==null,y.hidden=g.failureCode===null,y.textContent=g.failureCode===null?"":og(g.failureCode);const O=g.announcementKey==="ready"&&(S.requestFailureCode!==null||g.failureCode!==null)?"":dg(g);T.textContent!==O&&(T.textContent=O),g.requestAction.enabled||R.close()},M=()=>{l.disabled||i.onProviderChange({provider:mt(l.value)})},v=()=>{if(!(x===null||!x.requestAction.enabled)){if(t.onBeforeRequest?.(),x.warningRequired&&x.warningProvider!==null){R.open(h,x.warningProvider);return}i.onRequestIntent()}};return l.addEventListener("change",M),h.addEventListener("click",v),G(Ng),{element:s,configurationElement:r,requestElement:o,announcementElement:T,alertElement:w,requestControl:h,dialog:R.element,setState:G,closeWarning(){R.close()},destroy(){x=null,l.removeEventListener("change",M),h.removeEventListener("click",v),R.destroy(),a.destroy(),E.destroy(),r.remove(),o.remove(),T.remove(),w.remove(),s.remove()}}}function qt(t,e,i){e.textContent="";for(const n of i){if(typeof n=="string"){e.append(n);continue}const s=t.createElement("span");s.className="scg-ui-work-dependent",s.textContent=n.text,e.append(s)}}function at(t,e,i){const n=t.createElement("button");return n.className=`scg-ui-action ${e}`,n.type="button",n.textContent=i,n}class Lg{constructor(e){this.document=e,this.description=e.createElement("p"),this.description.className="scg-ui-work-preview-description",this.execution=e.createElement("p"),this.execution.className="scg-ui-work-preview-execution",this.list=e.createElement("ol"),this.list.className="scg-ui-work-preview-list"}document;description;execution;list;render(e,i){qt(this.document,this.description,[`${Eu(e.entries.length)}. `,..._i.previewDescription]);const n=e.executionSettings;this.execution.textContent=`모델: ${n?.model??"기본 설정 상속"} · 추론 강도: ${n?.reasoningEffort??"기본 설정 상속"}`,this.list.replaceChildren(...e.entries.map((s,r)=>{const o=this.document.createElement("li");o.className="scg-ui-work-preview-item";const a=this.document.createElement("code");a.className="scg-ui-work-preview-identity",a.textContent=Su(r+1,s.annotationId);const c=this.document.createElement("span");return c.className="scg-ui-work-preview-summary",c.textContent=ku(i.get(s.annotationId)),o.append(a,c),o}))}}let Mg=0;function Dg(t){const e=t.document,i=String(Mg+=1),n=e.createElement("section");n.className="scg-ui-work-progress",n.hidden=!0,n.setAttribute("aria-label","작업 진행 상태");const s=e.createElement("p");s.className="scg-ui-work-progress-status",s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),s.setAttribute("aria-atomic","true");const r=at(e,"scg-ui-work-cancel",le.cancelRequest),o=at(e,"scg-ui-work-retry-same",le.retrySame),a=at(e,"scg-ui-work-new-request",le.newRequest),c=e.createElement("p");c.className="scg-ui-work-duplicate-warning",qt(e,c,_i.duplicateWarning),c.hidden=!0,n.append(s,c,r,o,a);const l=e.createElement("div");l.className="scg-ui-work-preview-layer",l.hidden=!0;const d=e.createElement("div");d.className="scg-ui-work-preview-scrim",d.setAttribute("aria-hidden","true");const u=e.createElement("div");u.className="scg-ui-work-preview",u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true");const h=e.createElement("h2");h.className="scg-ui-work-preview-title",h.id=`scg-ui-work-preview-title-${i}`,h.textContent=le.previewTitle,u.setAttribute("aria-labelledby",h.id);const f=new Lg(e),{description:b,execution:y,list:T}=f;b.id=`scg-ui-work-preview-description-${i}`,u.setAttribute("aria-describedby",b.id);const E=e.createElement("p");E.className="scg-ui-work-preview-stale",E.textContent=le.stale,E.hidden=!0;const w=at(e,"scg-ui-work-preview-cancel",le.cancel),R=at(e,"scg-ui-work-preview-confirm",le.confirm),x=e.createElement("div");x.className="scg-ui-work-preview-actions",x.append(w,R),u.append(h,b,y,E,T,x),l.append(d,u);let G=null,M=null,v=!1,S="",g=null;const O=()=>{w.disabled=!1,R.disabled=!1,R.setAttribute("aria-busy","false"),R.textContent=le.confirm},j=(z=!1)=>{z||(M=null);const V=v;v=!1,l.hidden=!0,O(),E.hidden=!0,e.removeEventListener("focusin",L),t.background.inert=!1,t.background.removeAttribute("aria-hidden");const Oe=G;if(G=null,V){const Tf=ur(l,Oe,t);M=z&&!Tf?Oe:null}else z&&hr(l,M)&&(M=null)};function L(z){!l.hidden&&!ot(u,z.target)&&w.focus()}const U=()=>{R.disabled||(w.disabled=!0,R.disabled=!0,R.setAttribute("aria-busy","true"),R.textContent=le.confirming,t.handlers.onConfirm(t.requestId()))},be=()=>{j(),t.handlers.onDismissPreview()},br=z=>{if(z.key==="Escape"){z.preventDefault(),R.disabled||be();return}z.key==="Tab"&&(z.preventDefault(),(e.activeElement===w?R:w).focus())},yr=()=>{if(r.disabled)return;r.disabled=!0;const z=Gs({connection:"ready",result:null,pending:"cancelling",failureCode:null});qt(e,s,z.statusUnits),t.handlers.onCancelRequest()};return w.addEventListener("click",be),R.addEventListener("click",U),l.addEventListener("keydown",br),r.addEventListener("click",yr),o.addEventListener("click",t.handlers.onRetrySameRequest),a.addEventListener("click",t.handlers.onNewRequest),{element:n,dialog:l,openPreview(z,V,Oe){!l.hidden&&g===z.previewDigest||(M=null,G=Oe??G,g=z.previewDigest,E.hidden=!0,f.render(z,V),O(),v=!0,l.hidden=!1,t.background.inert=!0,t.background.setAttribute("aria-hidden","true"),e.addEventListener("focusin",L),w.focus())},refreshStale(z,V){!E.hidden&&g===z.previewDigest||(g=z.previewDigest,f.render(z,V),E.hidden=!1,O(),w.focus())},setProgress(z){const V=Gs(z);n.hidden=V.phase==="idle",n.dataset.state=V.tone;const Oe=`${V.announcementKey}:${V.failureCode??"none"}`;Oe!==S&&(qt(e,s,V.statusUnits),S=Oe),r.hidden=!V.canCancel&&V.pending!=="cancelling",r.disabled=!V.canCancel,o.hidden=V.retry!=="same-request",a.hidden=V.retry!=="new-request",c.hidden=V.retry!=="new-request",V.phase==="request-failed"&&j(!0)},closePreview:j,destroy(){j(),w.removeEventListener("click",be),R.removeEventListener("click",U),l.removeEventListener("keydown",br),r.removeEventListener("click",yr),o.removeEventListener("click",t.handlers.onRetrySameRequest),a.removeEventListener("click",t.handlers.onNewRequest),n.remove(),l.remove()}}}function qg(t){const e=t.document.createElement("section");e.className="scg-ui-work-review scg-ui-controls",e.hidden=!0,e.setAttribute("aria-label","완료된 작업 검토");const i=t.document.createElement("p");i.className="scg-ui-work-review-status";const n=t.document.createElement("button");n.className="scg-ui-action scg-ui-selection scg-ui-work-review-acknowledge",n.type="button",n.textContent="검토 완료",n.setAttribute("aria-busy","false"),e.append(i,n);let s=null;const r=new Set;let o=!1;const a=l=>{o||!r.delete(l)||s===l&&(n.disabled=!1,n.setAttribute("aria-busy","false"))},c=()=>{const l=s;o||l===null||r.has(l)||(r.add(l),n.disabled=!0,n.setAttribute("aria-busy","true"),Promise.resolve(t.onAcknowledge(l)).then(()=>a(l),()=>a(l)))};return n.addEventListener("click",c),{element:e,setState(l){const d=!l.pending&&t.document.activeElement===n;if(s=l.pending?l.requestId:null,e.hidden=!l.pending,!l.pending){delete e.dataset.requestId,delete e.dataset.resolvedCount,delete e.dataset.orphanedCount,i.textContent="",n.disabled=!0,n.setAttribute("aria-busy","false"),d&&t.fallbackFocus?.()?.focus();return}if(l.requestId===null)throw new TypeError("pending review requires a request id");e.dataset.requestId=l.requestId,e.dataset.resolvedCount=String(l.resolvedCount),e.dataset.orphanedCount=String(l.orphanedCount),i.textContent=`완료된 작업 메모 ${l.resolvedCount+l.orphanedCount}개가 검토를 기다립니다.`;const u=r.has(l.requestId);n.disabled=u,n.setAttribute("aria-busy",String(u))},destroy(){o||(o=!0,s=null,r.clear(),n.removeEventListener("click",c),e.remove())}}}function zg(t,e){let i=0,n=0;for(const s of t)s.workCompletion?.requestId!==e||s.workCompletion.phase!=="review-pending"||(s.resolution==="resolved"&&s.element!==void 0?i+=1:n+=1);return Object.freeze({resolvedCount:i,orphanedCount:n})}class Gg{constructor(e,i){this.document=e,this.#f=i.container??null,this.#g=new Ph(i),this.#e=tg(e),this.#t=oh(e),this.#i=new fh(this.#t,()=>this.#v()),this.#s=new mh(e,this.#i,()=>this.#p()),this.#n=new Uh(e,this.#i,{...this.#g.memoHost(),created:()=>this.#o.revealResolved(),render:()=>this.#p(),highlight:(s,r)=>{r==="show"&&s!==null?n.showHighlight(s):r==="flash"&&s!==null?n.flashHighlight(s):n.hideHighlight()}}),this.#o=new bh(e,this.#n,()=>this.#p()),this.#r=new Sh(e,this.#n,()=>n.scheduleViewport()),this.#a=new _h(e,this.#i,{closeWarning:()=>this.#l.closeWarning(),renderRequested:()=>this.#p()}),this.#l=Pg({document:e,background:this.#a.element,handlers:this.#g.providerHandlers(),onBeforeRequest:()=>this.#a.closeSettings(!1)}),this.#a.configureSettings(i,this.#l.configurationElement,()=>this.#g.readWorkCapabilities()),this.#c=Dg({document:e,background:this.#a.element,requestId:()=>jg(e),fallbackFocus:()=>this.#l.requestControl.disabled?this.#l.requestElement:this.#l.requestControl,handlers:this.#g.requestHandlers()}),this.#d=qg({document:e,onAcknowledge:s=>this.#g.acknowledgeWorkReview(s),fallbackFocus:()=>this.#o.toggle}),this.#a.append(this.#s.element,this.#l.requestElement,this.#c.element,this.#d.element,this.#n.editor,this.#o.toggle,this.#o.list,this.#o.orphanToggle,this.#o.orphanList,this.#s.promptToggle,this.#s.promptOutput),this.#t.element!==null&&this.#a.element.append(this.#t.element),this.#a.element.append(this.#l.announcementElement,this.#l.alertElement),this.#u=new wh(this.#i,this.#s,this.#g);const n=new Rh(e,this.#a,{didMount:()=>{this.#r.mount(),this.#r.rebuild(this.#i.annotations,this.#y()),this.#r.element!==null&&n.mark(this.#r.element)},positionViewport:()=>{this.#r.position(),this.#n.position()}});this.#h=n,this.#s.bindHint(this.#n.saveHint),n.mark(this.#a.launcher),this.#p()}document;#e;#t;#i;#s;#n;#o;#r;#a;#l;#c;#d;#u;#h;#g;#f;#m=null;open(){this.#i.destroyed||this.#h.open(this.#f,[this.#e,this.#a.element,this.#a.launcher,this.#l.dialog,this.#c.dialog])}setState(e){this.#i.destroyed||(e.actionEpoch!==void 0&&this.#i.setActionEpoch(e.actionEpoch)&&(this.#n.reset(),this.#s.resetTransient(),this.#u.resetTransient(),this.#a.closeSettings()),e.pendingSelectionElement!==void 0&&this.#i.setPendingSelectionElement(e.pendingSelectionElement),e.annotations!==void 0&&(this.#i.setAnnotations(e.annotations),this.#n.reconcile()),e.capabilities!==void 0&&this.#i.setCapabilities(e.capabilities),e.selectionMode!==void 0&&this.#a.applySelectionMode(e.selectionMode),e.measureMode!==void 0&&this.#i.setMeasureMode(e.measureMode),e.sizeMode!==void 0&&this.#i.setSizeMode(e.sizeMode),e.diagnosticsOpen!==void 0&&this.#i.setDiagnosticsOpen(e.diagnosticsOpen),e.badgeAttention!==void 0&&this.#i.setBadgeAttention(e.badgeAttention),e.pageReady!==void 0&&this.#i.setPageReady(e.pageReady),e.status!==void 0&&this.#t.set(e.status),e.work!==void 0&&this.#l.setState(e.work),e.workRequest!==void 0&&this.#w(e.workRequest),e.workReview!==void 0&&(this.#m=e.workReview),this.#p())}hasOpenDialog(){return[this.#c.dialog,this.#l.dialog].some(Wg)}destroy(){this.#i.destroyed||(this.#i.destroy(),this.#g.destroy(),this.#f=null,this.#h.destroy(),this.#n.reset(),this.#u.destroy(),this.#s.destroy(),this.#n.destroy(),this.#o.destroy(),this.#r.destroy(),this.#t.destroy(),this.#c.destroy(),this.#d.destroy(),this.#l.destroy(),this.#a.destroy(),this.#e.textContent="",this.#e.remove())}#w(e){e.preview!==null&&this.#a.closeSettings(!1),this.#c.setProgress(e.progress),e.preview===null?e.progress.failureCode===null&&this.#c.closePreview():e.stale?this.#c.refreshStale(e.preview,e.summaries):this.#c.openPreview(e.preview,e.summaries,this.#l.requestControl)}#p(){if(this.#i.destroyed)return;const e=this.#n.render();this.#a.render(e),(this.#i.minimized||e)&&this.#c.closePreview(),this.#u.reconcile(),this.#s.render(this.#u.deleteConfirming),this.#o.render(this.#i.annotations,this.#y()),this.#b(),this.#h.mark(this.#a.element),this.#r.rebuild(this.#i.annotations,this.#y()),this.#r.element!==null&&this.#h.mark(this.#r.element),this.#v(),e&&this.#n.position()}#b(){const e=this.#m;if(e===null){this.#d.setState({requestId:null,pending:!1,resolvedCount:0,orphanedCount:0});return}const i=zg(this.#i.annotations,e.requestId);this.#d.setState({...e,...i})}#v(){this.#s.setDisabled(),this.#n.setDisabled();const e=this.#y();this.#o.setDisabled(e),this.#r.setDisabled(e)}#y(){const e=this.#i.isActionInFlight();return{edit:e||!this.#i.pageActionAvailable(this.#i.capabilities.canUpdateMemo),delete:e||!this.#i.pageActionAvailable(this.#i.capabilities.canDeleteMemo)}}}function jg(t){const e=t.defaultView?.crypto??globalThis.crypto;if(typeof e?.randomUUID!="function")throw new TypeError("secure request identity is unavailable");return te(e.randomUUID(),"work request id")}const Wg=t=>t.isConnected&&!t.closest("[hidden]");function Ug(t={}){const e=Vg(t);return e===null?Bg():new Gg(e,t)}function Vg(t){return t.document!==void 0?t.document:t.container!==void 0?t.container.ownerDocument:typeof globalThis.document>"u"?null:globalThis.document}function Bg(){return{open(){},setState(){},hasOpenDialog:()=>!1,destroy(){}}}const Fg=75,$g=500,Kg=4096,gr=2147483647;class Hg{window;document;projectId;dependencies;crypto;navigation;settler;client;pageIdentityOverride;pageIdentityPolicy;controller;selector;overlay;measurementProviderFactory;api;work;pageExporter;workProvider;workSettings;workRequest;workEvidence;workEvidenceCache=new Map;badgeDismissalRevision=0;badgeDismissedAt=new Map;badgeAttention;workAnnotationProjection=[];workAnnotationTicket=null;workNoteCount=0;workReviewProjectionGeneration=0;diagnostics=null;diagnosticsTask=null;diagnosticsCleanupTask=null;diagnosticsOwner=0;mutationObserver=null;hostMutationTimer=null;selectedTarget=null;measurementSession=null;measureMode=!1;sizeMode=!1;measurementEscapeBound=!1;measurementActionGeneration=0;selectionEscapeBound=!1;shake=Vs({minimumLegPx:Us(Fs)});shakeBound=!1;captureTask=null;pageLoadTask=null;navigationGeneration=0;pageReadyGeneration=0;actionEpoch=0;selectionGeneration=0;pageReadyNavigationGeneration=null;readyControllerGeneration=null;readyPageId=null;navigationStarted=!1;navigationFailure=null;selectorCallbackFailure=null;destroyTask=null;destroyed=!1;constructor(e){if(this.window=e.window,this.document=e.document,this.projectId=e.projectId,this.dependencies=Jg(e),e.measurementProviderFactory!==void 0&&e.measurementProvider!==void 0)throw new TypeError("measurement provider authority is ambiguous");this.measurementProviderFactory=e.measurementProviderFactory??(e.measurementProvider===void 0?void 0:Zg(e.measurementProvider)),this.crypto=e.crypto??pf(),this.navigation=e.navigation==="spa"?th({window:this.window,observeHashChanges:!0}):Fu({window:this.window}),this.settler=Qu({window:this.window,document:this.document});const i=e.pageIdentity,n=i?.policy;this.pageIdentityOverride=i?.override,this.pageIdentityPolicy=n===void 0?void 0:Object.freeze({...n.includeQuery===void 0?{}:{includeQuery:n.includeQuery},...n.includeHash===void 0?{}:{includeHash:n.includeHash}});const s=e.openDiagnosticsPanel??this.openDefaultDiagnostics;this.client=new bd({endpoint:e.endpoint,diagnosticEndpoint:e.diagnosticEndpoint,...e.token===void 0?{}:{token:e.token},...this.dependencies,openDiagnosticsPanel:s,onHostReady:this.onHostReady,onStateChange:this.onClientState}),this.controller=new Ic({port:{listAnnotations:async o=>tf(await this.client.listAnnotations(o)),createAnnotation:async o=>nf(await this.client.createAnnotation(o)),updateAnnotation:async o=>sf(await this.client.updateAnnotation(o)),deleteAnnotation:async o=>rf(await this.client.deleteAnnotation(o))},onStateChange:this.onAnnotationState}),this.selector=Jc({document:this.document,onCallbackError:this.onSelectorCallbackError,onSelect:this.onSelection,onUnsupportedSelect:this.onUnsupportedSelection}),this.pageExporter=Fd({controller:this.controller,capture:()=>this.captureReadyPage(),assertCurrent:o=>this.assertCurrentPageAction(o),exportPrompt:o=>this.client.exportPrompt(o)}),this.overlay=Ug({document:this.document,projectId:this.projectId,onSelectionModeChange:this.setSelectionMode,onShakeSensitivityChange:this.applyShakeSensitivity,onMeasureModeChange:this.setMeasureMode,onSizeModeChange:this.setSizeMode,onCreateMemo:this.createMemo,onUpdateMemo:this.updateMemo,onDeleteMemo:this.deleteMemo,onDeleteAllCurrentPage:this.deleteAllCurrentPage,onRetry:this.retryFromOverlay,onOpenDiagnostics:this.openDiagnosticsFromOverlay,onCloseDiagnostics:this.closeDiagnosticsFromOverlay,onExportProject:this.exportProject,onExportCurrentPage:this.pageExporter.exportCurrentPage,onWorkProviderChange:o=>this.workSettings.changeProvider(o),onWorkExecutionSettingsChange:o=>this.workSettings.changeExecutionSettings(o),onWorkCapabilitiesRead:()=>this.workSettings.open(),onWorkSessionReset:()=>this.workSettings.resetSession(),onWorkWarningAcknowledge:this.acknowledgeWorkWarning,onWorkRequestIntent:this.previewWorkRequest,onWorkRequestConfirm:this.confirmWorkRequest,onWorkCancel:this.cancelWorkRequest,onWorkRetrySame:this.retrySameWorkRequest,onWorkNewRequest:this.previewWorkRequest,onWorkPreviewDismiss:this.dismissWorkPreview,onWorkReviewAcknowledge:this.acknowledgeWorkReview,onBadgeAttentionDismiss:this.dismissBadgeAttention,onWorkDiffCompare:this.compareWorkDiff}),this.overlay.open(),this.work=Nd({callTool:Vd((o,a,c)=>this.client.callWorkTool(o,a,c),this.pageExporter.capture),onStateChange:this.onWorkState,onHistoryRefresh:()=>{const o=this.workEvidenceCache,a=this.badgeDismissalRevision;return({retainedRequestIds:c,observedAfterStart:l})=>{if(this.destroyed||o!==this.workEvidenceCache)return;const d=new Set([...c,...l]);for(const[u,h]of this.badgeDismissedAt)h>a&&d.add(u);this.badgeAttention.updateRetainedHistory({projectId:this.projectId,complete:!0,requestIds:d});for(const[u,h]of o)(!d.has(u)||h.classification==="unknown")&&o.delete(u);for(const u of this.badgeDismissedAt.keys())d.has(u)||this.badgeDismissedAt.delete(u)}}}),this.workEvidence=this.createWorkEvidenceReader(),this.badgeAttention=Zd({projectId:this.projectId,getStorage:()=>this.window.sessionStorage??null}),this.workRequest=Md({controller:this.work,onChanged:this.onWorkRequestChanged}),this.workProvider=jd({controller:{setProvider:(o,a)=>this.work.setProvider(o,a),getState:()=>this.work.getState(),acknowledgeWarning:(o,a)=>this.work.acknowledgeWarning(o,a),resetProviderSession:()=>this.work.resetProviderSession(),refreshProvider:()=>this.work.refreshProvider(),refreshHistory:()=>this.work.refreshHistory()},onChanged:this.onWorkProviderChanged,onFailure:this.onWorkProviderFailure}),this.workSettings=new Wd({work:this.work,provider:this.workProvider,ready:()=>!this.destroyed&&this.client.state==="ready"});const r=this.client;this.api=Object.freeze({get state(){return r.state},notifyReady:()=>r.notifyReady(),retry:()=>r.retry(),openDiagnostics:()=>r.openDiagnostics(),destroy:()=>this.destroy()})}getApi(){return this.api}getWorkState(){return this.work.getState()}getWorkController(){return this.work}async start(){await this.client.start()}destroy(){if(this.destroyTask!==null)return this.destroyTask;if(this.destroyed)return Promise.resolve();this.destroyed=!0,this.diagnosticsOwner+=1,this.measurementActionGeneration+=1,this.navigationGeneration+=1,this.pageReadyGeneration+=1,this.actionEpoch+=1,this.selectionGeneration+=1,this.workReviewProjectionGeneration+=1,this.pageReadyNavigationGeneration=null,this.readyControllerGeneration=null,this.readyPageId=null;const e=Wt();return this.destroyTask=e.promise,Promise.resolve().then(()=>this.performDestroy()).then(e.resolve,e.reject),e.promise}async performDestroy(){const e=[],i=r=>{try{r()}catch(o){e.push(o)}};i(()=>{this.shakeBound&&typeof this.document.removeEventListener=="function"&&this.document.removeEventListener("pointermove",this.onShakeMove),this.shakeBound=!1}),i(()=>this.releaseSelectionEscape()),i(()=>this.releaseMeasurementEscape()),i(()=>this.destroyMeasurementCapability()),i(()=>this.stopMutationObserver()),i(()=>this.work.destroy()),i(()=>this.navigation.teardown()),i(()=>this.settler.teardown()),i(()=>this.selector.destroy()),i(()=>this.overlay.destroy()),this.selectedTarget=null,this.captureTask=null,this.pageLoadTask=null;const n=this.destroyDiagnostics();try{await n}catch(r){e.push(r)}i(()=>this.controller.destroy());let s;try{s=this.client.destroy()}catch(r){e.push(r),s=Promise.resolve()}try{await s}catch(r){e.push(r)}if(e.length>0)throw new AggregateError(e,"Scene Glass runtime cleanup failed")}createWorkEvidenceReader(){const e=this.workEvidenceCache,i=Jd(fi((n,s,r)=>{if(this.destroyed||e!==this.workEvidenceCache)throw k("SCG_CLIENT_UNAVAILABLE");return this.client.callWorkTool(n,s,r)}));return Object.freeze({read:async n=>{const s=e.get(n);if(s!==void 0)return s;const r=await i.read(n);return!this.destroyed&&e===this.workEvidenceCache&&e.set(n,r),r}})}onClientState=e=>{if(!this.destroyed)switch(this.workEvidenceCache=new Map,this.workEvidence=this.createWorkEvidenceReader(),e){case"ready":this.startNavigation(),this.recoverWorkSession();return;case"booting":case"connecting":this.measurementActionGeneration+=1,this.destroyMeasurementCapability(),this.invalidatePage();return;case"unavailable":this.measurementActionGeneration+=1,this.destroyMeasurementCapability(),this.invalidatePage(),this.setOverlayState({status:{kind:"error",code:"SCG_CLIENT_UNAVAILABLE"}});return;case"access-error":this.measurementActionGeneration+=1,this.destroyMeasurementCapability(),this.invalidatePage(),this.setOverlayState({status:{kind:"error",code:"SCG_CLIENT_ACCESS_DENIED"}});return;case"destroyed":return}};onWorkState=()=>{this.workSettings.refreshAfterSettlement(),this.publishWorkState(),this.projectCurrentWorkReview()};onWorkProviderChanged=()=>{this.publishWorkState()};onWorkRequestChanged=()=>{this.publishWorkState()};onWorkProviderFailure=()=>{this.publishWorkState()};acknowledgeWorkWarning=e=>this.workProvider.acknowledgeWarning(e);previewWorkRequest=async()=>{const e=this.captureReadyPage();await this.workRequest.preview(e.page),this.assertCurrentPageAction(e)};confirmWorkRequest=e=>this.workRequest.submit(e.requestId);cancelWorkRequest=()=>this.workRequest.cancel();dismissWorkPreview=()=>this.workRequest.dismissPreview();acknowledgeWorkReview=e=>this.work.acknowledgeReview(e.requestId);dismissBadgeAttention=async({token:e})=>{const i=this.controller.getState(),n=st(this.work.getState()),s=this.workAnnotationTicket;if(s===null||!this.isCurrentPageState(i)||s.pageId!==i.page?.pageId||s.revision!==i.revision||s.recordSignature!==Lt(n)||e.pageId!==this.readyPageId)return;const r=Ce(e);if(!this.workAnnotationProjection.some(({badgeAttention:a})=>a!==void 0&&Ce(a.token)===r)||(this.badgeAttention.isDismissed(e)||this.badgeDismissedAt.set(e.requestId,++this.badgeDismissalRevision),this.badgeAttention.dismiss(e),this.publishWorkAnnotations(this.workAnnotationProjection),!Gu({token:e,records:n,annotations:this.workAnnotationProjection},this.badgeAttention)))return;const o=this.captureReadyPage();try{await this.acknowledgeWorkReview({requestId:e.requestId})}catch{this.isCurrentPageState(this.controller.getState())&&o.navigationGeneration===this.navigationGeneration&&s.recordSignature===Lt(st(this.work.getState()))&&this.setOverlayState({status:{kind:"error",code:"SCG_CLIENT_WORK_REVIEW_FAILED"}})}};publishWorkAnnotations(e){this.workAnnotationProjection=Object.freeze(e.map(i=>{const n=i.badgeAttention;return n===void 0?i:Object.freeze({...i,badgeAttention:Object.freeze({token:n.token,state:this.badgeAttention.isDismissed(n.token)?"seen":"pending"})})})),this.setOverlayState({annotations:this.workAnnotationProjection})}compareWorkDiff=e=>this.work.compareDiff(e.requestIdA,e.requestIdB);retrySameWorkRequest=async()=>{await this.work.retryRequest()};async recoverWorkSession(){try{await this.workProvider.hydrate(),this.destroyed||await this.work.resume()}catch(e){if(!(e instanceof Error))throw e}}publishWorkState(){if(!this.destroyed)try{this.setOverlayState({})}catch{}}onHostReady=()=>{!this.destroyed&&this.client.state==="ready"&&this.navigationFailure===null&&this.startNavigation()};onAnnotationState=e=>{this.isCurrentPageState(e)&&this.renderAnnotationState(e)};onSelection=e=>{if(e?.status!=="selected"||this.destroyed||!this.isPageReady())return;this.selectionGeneration+=1,this.selectedTarget=null,this.captureTask=null;const i=this.navigationGeneration,n=this.selectionGeneration,s=this.captureSelectedElement(e.element,i,n);this.captureTask=s,s.then(()=>{this.captureTask===s&&(this.captureTask=null)},()=>{})};applyShakeSensitivity=e=>{this.shake=e===0?null:Vs({minimumLegPx:Us(e)})};onShakeMove=e=>{const i=this.shake;if(!(this.destroyed||i===null||!this.isPageReady())){if(this.selector.isReviewing||this.measureMode||this.sizeMode||this.selectedTarget!==null||this.overlay.hasOpenDialog()){i.reset();return}i.push(e.clientX,e.clientY,e.timeStamp)&&this.setSelectionMode({active:!0}).catch(()=>{})}};onSelectionKeyDown=e=>{e.key!=="Escape"||e.altKey||e.ctrlKey||e.metaKey||this.selectionEscapeBound&&(e.preventDefault(),e.stopPropagation(),this.setSelectionMode({active:!1}).catch(()=>{}))};releaseSelectionEscape(){this.selectionEscapeBound&&(this.document.removeEventListener("keydown",this.onSelectionKeyDown,!0),this.selectionEscapeBound=!1)}onUnsupportedSelection=e=>{this.destroyed||!this.isPageReady()||(this.selectionGeneration+=1,this.selectedTarget=null,this.captureTask=null,this.setOverlayState({pendingSelectionElement:null,status:{kind:"error",code:of(e.reason)}}))};onSelectorCallbackError=({error:e,phase:i})=>{const n=Object.assign(k("SCG_SELECTOR_CALLBACK_FAILED",e),{phase:i}),s=[],r=o=>{try{o()}catch(a){s.push(a)}};this.selectorCallbackFailure=n,this.destroyed||(r(()=>this.controller.setManualError("Scene Glass 요소 선택 콜백에 실패했습니다.",n.code)),r(()=>this.setOverlayState({status:{kind:"error",code:n.code}}))),s.length>0&&(this.selectorCallbackFailure=Ae(n,s))};setMeasureMode=async({active:e})=>{if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");const i=this.measurementActionGeneration+=1;if(!e){this.stopMeasuring(),this.setOverlayState({measureMode:!1});return}const n=await this.measurementControllersForActivation();this.assertCurrentMeasurementAction(i),this.stopSizeInspecting(),n.setMeasureMode({active:!0,selectedElement:null}),this.measureMode=!0,this.bindMeasurementEscape(),this.setOverlayState({measureMode:!0,sizeMode:!1})};setSizeMode=async({active:e})=>{if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");const i=this.measurementActionGeneration+=1;if(!e){this.stopSizeInspecting(),this.setOverlayState({sizeMode:!1});return}const n=await this.measurementControllersForActivation();this.assertCurrentMeasurementAction(i),this.stopMeasuring(),n.setSizeMode({active:!0,selectedElement:null}),this.sizeMode=!0,this.bindMeasurementEscape(),this.setOverlayState({measureMode:!1,sizeMode:!0})};assertCurrentMeasurementAction(e){if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");if(e!==this.measurementActionGeneration||!this.isPageReady())throw k("SCG_PREMIUM_UNAVAILABLE")}async measurementControllersForActivation(){if(!this.isPageReady())throw k("SCG_PREMIUM_UNAVAILABLE");const e=this.measurementSession;if(e!==null&&e.sessionId===this.client.getSessionId()&&e.navigationGeneration===this.navigationGeneration){if(e.controllers!==null)return e.controllers;if(e.loadTask!==null)return e.loadTask}else e!==null&&this.destroyMeasurementCapability();const i=this.measurementProviderFactory,n=this.client.getSessionId(),s=this.document.documentElement;if(i===void 0||n===null||s===null||!this.isPageReady())throw k("SCG_PREMIUM_UNAVAILABLE");let r;try{r=i.create(Object.freeze({sessionId:n}))}catch(l){throw k("SCG_PREMIUM_UNAVAILABLE",l)}const o=new AbortController,a={abortController:o,controllers:null,disposed:!1,sessionId:n,lease:r,loadTask:null,navigationGeneration:this.navigationGeneration};this.measurementSession=a;const c=Promise.resolve().then(()=>r.provider.load({signal:o.signal})).then(l=>{this.assertCurrentMeasurementSession(a);const d=l.activate(Object.freeze({root:s,createElement:this.document.createElement.bind(this.document),getComputedStyle:this.window.getComputedStyle.bind(this.window),requestAnimationFrame:this.window.requestAnimationFrame.bind(this.window),cancelAnimationFrame:this.window.cancelAnimationFrame.bind(this.window),signal:o.signal}));try{this.assertCurrentMeasurementSession(a)}catch(u){throw d.destroy(),u}return a.controllers=d,d}).catch(l=>{let d=l;if(this.measurementSession===a){this.measurementSession=null;try{this.disposeMeasurementSession(a)}catch(u){d=new AggregateError([l,u],"premium load cleanup failed",{cause:l})}}throw typeof l=="object"&&l!==null&&"code"in l&&l.code==="SCG_CLIENT_DESTROYED"?k("SCG_CLIENT_DESTROYED",d):k("SCG_PREMIUM_UNAVAILABLE",d)});return a.loadTask=c,c}assertCurrentMeasurementSession(e){if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");if(e.abortController.signal.aborted||this.measurementSession!==e||e.sessionId!==this.client.getSessionId()||e.navigationGeneration!==this.navigationGeneration||!this.isPageReady())throw k("SCG_PREMIUM_UNAVAILABLE")}stopMeasuring(){this.measurementSession?.controllers?.setMeasureMode({active:!1,selectedElement:null}),this.measureMode=!1,this.sizeMode||this.releaseMeasurementEscape()}stopSizeInspecting(){this.measurementSession?.controllers?.setSizeMode({active:!1,selectedElement:null}),this.sizeMode=!1,this.measureMode||this.releaseMeasurementEscape()}bindMeasurementEscape(){this.measurementEscapeBound||(this.document.addEventListener("keydown",this.onMeasurementKeyDown,!0),this.measurementEscapeBound=!0)}releaseMeasurementEscape(){this.measurementEscapeBound&&(this.document.removeEventListener("keydown",this.onMeasurementKeyDown,!0),this.measurementEscapeBound=!1)}onMeasurementKeyDown=e=>{if(e.key!=="Escape"||e.altKey||e.ctrlKey||e.metaKey||!this.measureMode&&!this.sizeMode)return;e.preventDefault(),e.stopPropagation(),(this.measureMode?this.setMeasureMode({active:!1}):this.setSizeMode({active:!1})).catch(()=>{})};destroyMeasurementCapability(){const e=this.measurementSession;this.measurementSession=null,this.measureMode=!1,this.sizeMode=!1,this.releaseMeasurementEscape(),e!==null&&this.disposeMeasurementSession(e)}disposeMeasurementSession(e){if(e.disposed)return;e.disposed=!0,e.abortController.abort();const i=[];if(e.controllers!==null)try{e.controllers.destroy()}catch(n){i.push(n)}e.controllers=null,e.loadTask=null;try{e.lease.destroy()}catch(n){i.push(n)}if(i.length>0)throw new AggregateError(i,"premium capability cleanup failed")}setSelectionMode=async({active:e})=>{if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");if(e){if(this.selectorCallbackFailure=null,this.captureReadyPage(),this.selectionGeneration+=1,this.selectedTarget=null,this.captureTask=null,this.stopSizeInspecting(),this.setOverlayState({pendingSelectionElement:null,selectionMode:!0,sizeMode:!1}),this.selector.stop(),this.selector.start(),!this.selector.isReviewing)throw this.releaseSelectionEscape(),k("SCG_SELECTION_UNAVAILABLE");this.document.addEventListener("keydown",this.onSelectionKeyDown,!0),this.selectionEscapeBound=!0;return}this.releaseSelectionEscape(),this.invalidateSelection()};createMemo=async({memo:e})=>{const i=this.captureReadyPage(),n=this.selectionGeneration,s=this.captureTask;if(s!==null&&(await s,this.assertCurrentPageAction(i)),this.selectionGeneration!==n)throw k("SCG_SELECTION_REQUIRED");if(this.selectorCallbackFailure!==null)throw this.selectorCallbackFailure;const r=this.selectedTarget;if(r===null||r.navigationGeneration!==i.navigationGeneration||r.selectionGeneration!==n)throw k("SCG_SELECTION_REQUIRED");this.assertCurrentPageAction(i);const o=await this.controller.create({operationId:jt(this.crypto),locator:r.locator,memo:e,surroundingText:r.surroundingText,domOrder:r.domOrder,resolution:r.resolution,...r.context===void 0?{}:{context:r.context}});this.assertCurrentPageAction(i),zt(o),this.selectionGeneration===n&&(this.selectedTarget=null),this.setOverlayState({pendingSelectionElement:null})};updateMemo=async({annotationId:e,memo:i})=>{const n=this.captureReadyPage(),s=await this.controller.update({annotationId:e,operationId:jt(this.crypto),patch:{memo:i}});this.assertCurrentPageAction(n),zt(s)};deleteMemo=async({annotationId:e})=>{const i=this.captureReadyPage(),n=await this.controller.delete({annotationId:e,operationId:jt(this.crypto)});this.assertCurrentPageAction(i),zt(n)};deleteAllCurrentPage=async()=>{const e=this.captureReadyPage(),i=this.controller.getState().annotations.map(n=>n.id);for(const n of i){this.assertCurrentPageAction(e);const s=await this.controller.delete({annotationId:n,operationId:jt(this.crypto)});this.assertCurrentPageAction(e),zt(s)}this.assertCurrentPageAction(e)};retryFromOverlay=async()=>{if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");const e=this.navigationFailure!==null;if(this.client.state==="unavailable"){await this.client.retry();const i=this.client.state;if(i!=="ready")throw k(i==="access-error"?"SCG_CLIENT_ACCESS_DENIED":"SCG_CLIENT_UNAVAILABLE")}else if(this.client.state!=="ready"||this.navigationStarted&&!e)throw k(this.client.state==="access-error"?"SCG_CLIENT_ACCESS_DENIED":"SCG_CLIENT_UNAVAILABLE");if(this.navigationStarted&&e?(this.navigationFailure=null,this.requestPageReload()):this.navigationStarted||(this.navigationFailure=null,this.startNavigation()),!this.navigationStarted)throw k("SCG_NAVIGATION_UNAVAILABLE")};openDiagnosticsFromOverlay=async()=>{this.assertClientReady(),await this.client.openDiagnostics()};closeDiagnosticsFromOverlay=async()=>{await this.destroyDiagnostics()};exportProject=async()=>(this.assertClientReady(),(await this.client.exportPrompt({mode:"project"})).markdown);openDefaultDiagnostics=e=>{const i=++this.diagnosticsOwner;return this.enqueueDiagnosticsOperation(()=>this.replaceDiagnostics(i,e))};async replaceDiagnostics(e,i){this.assertCurrentDiagnosticsOwner(e),await this.destroyDiagnosticsSurface(),this.assertCurrentDiagnosticsOwner(e);let n=null,s=null,r=null;try{n=new Xg(i,this.dependencies),this.assertCurrentDiagnosticsOwner(e),s=ol({projectId:this.projectId,transport:n}),this.assertCurrentDiagnosticsOwner(e),r=cl({document:this.document,controller:s}),this.assertCurrentDiagnosticsOwner(e),r.open(),this.assertCurrentDiagnosticsOwner(e),this.diagnostics={transport:n,controller:s,panel:r},this.destroyed||this.setOverlayState({diagnosticsOpen:!0})}catch(o){const a=[];try{await this.destroyDiagnosticResources({transport:n,controller:s,panel:r})}catch(c){a.push(c)}throw uf(o,a)}}startNavigation(){if(!this.destroyed){if(this.navigationStarted){this.requestPageReload();return}try{this.navigation.start(e=>this.requestPageReload(!1,e.kind!=="bootstrap")),this.navigationStarted=!0,this.startMutationObserver(),typeof this.document.addEventListener=="function"&&(this.document.addEventListener("pointermove",this.onShakeMove,{passive:!0}),this.shakeBound=!0),this.stampHostElementIds(),this.restoreOwnAccessibility(),this.navigationFailure=null,this.requestPageReload()}catch(e){this.navigationStarted=!1;const i=[];try{this.navigation.teardown()}catch(n){i.push(n)}try{this.stopMutationObserver()}catch(n){i.push(n)}this.navigationFailure=Ae(gf(e),i),this.invalidatePage(),this.setOverlayState({status:{kind:"error",code:this.navigationFailure.code}})}}}requestPageReload(e=!1,i=!1){if(!this.navigationStarted||this.navigationFailure!==null||this.destroyed||this.client.state!=="ready")return;i&&!e&&this.clearMeasurementForNavigation();const n=this.invalidatePage(e),s=this.settlePage(n,e);this.pageLoadTask=s,s.then(()=>{this.pageLoadTask===s&&(this.pageLoadTask=null)},r=>{this.pageLoadTask===s&&(this.pageLoadTask=null),this.isCurrentNavigationGeneration(n)&&this.setNavigationFailure(k("SCG_NAVIGATION_UNAVAILABLE",r))})}async settlePage(e,i=!1){const n=await this.settler.waitFor(e);if(!this.isCurrentNavigationGeneration(e))return;if(!n){this.setNavigationFailure(k("SCG_RENDER_SETTLEMENT_FAILED"));return}const s=Object.freeze({pathname:this.window.location.pathname,search:this.window.location.search,hash:this.window.location.hash}),r=this.pageIdentityOverride;let o,a;try{if(typeof r=="function"){if(o=await r(Object.freeze({location:s,navigationGeneration:e})),!this.isCurrentNavigationGeneration(e))return}else o=r;if(!this.isCurrentNavigationGeneration(e))return;a=await kl({location:s,...o===void 0?{}:{override:o},...this.pageIdentityPolicy===void 0?{}:{policy:this.pageIdentityPolicy}})}catch(d){if(this.isCurrentNavigationGeneration(e)){const u=k("SCG_PAGE_IDENTITY",d),h=[],f=b=>{try{b()}catch(y){h.push(y)}};this.navigationFailure=u,f(()=>this.controller.setManualError("Scene Glass가 메모 검토를 위해 현재 페이지를 확인하지 못했습니다.",u.code)),f(()=>this.setOverlayState({status:{kind:"error",code:u.code}})),h.length>0&&(this.navigationFailure=Ae(u,h))}return}if(!this.isCurrentNavigationGeneration(e))return;this.controller.setPage(a);const c=await this.controller.load();if(!this.isCurrentNavigationGeneration(e))return;if(c.status!=="applied"){c.status==="failed"&&this.setOverlayState({status:{kind:"error",code:c.error.code}});return}const l=this.controller.getState();if(l.page===void 0||l.revision===void 0){this.setOverlayState({status:{kind:"error",code:"SCG_ANNOTATION_STATE"}});return}i||(this.pageReadyGeneration+=1,this.actionEpoch+=1),this.pageReadyNavigationGeneration=e,this.readyControllerGeneration=l.generation,this.readyPageId=l.page.pageId,this.renderAnnotationState(l),this.setOverlayState({pageReady:!0,status:{kind:"ready"}})}isCurrentNavigationGeneration(e){return!this.destroyed&&this.navigationStarted&&this.client.state==="ready"&&this.navigationGeneration===e&&this.settler.isCurrent(e)}clearMeasurementForNavigation(){this.measurementActionGeneration+=1,this.destroyMeasurementCapability(),this.setOverlayState({measureMode:!1,sizeMode:!1})}invalidatePage(e=!1){return e?this.navigationGeneration:(this.navigationGeneration+=1,this.pageReadyGeneration+=1,this.actionEpoch+=1,this.pageReadyNavigationGeneration=null,this.readyControllerGeneration=null,this.readyPageId=null,this.workNoteCount=0,this.workAnnotationProjection=[],this.workReviewProjectionGeneration+=1,this.workRequest.invalidatePage(),this.work.invalidatePage(),this.invalidateSelection(),this.setOverlayState({annotations:[],pageReady:!1,status:{kind:"working"}}),this.navigationGeneration)}invalidateSelection(){this.selectionGeneration+=1,this.selectedTarget=null,this.captureTask=null,this.selector.stop(),this.setOverlayState({pendingSelectionElement:null,selectionMode:!1})}overlayCapabilities(){const e=!this.destroyed&&this.client.state==="ready",i=this.isPageReady(),n=e&&this.client.getSessionId()!==null&&i&&this.measurementProviderFactory!==void 0;return Object.freeze({canCreateMemo:i,canDeleteMemo:i,canDeleteAllCurrentPage:i,canExportCurrentPage:i,canExportProject:e,canOpenDiagnostics:e,canRetry:this.client.state==="unavailable"||e&&this.navigationFailure!==null,canMeasure:n,canInspectSize:n,canSelect:i,canUpdateMemo:i})}setOverlayState(e){const i=this.work.getState(),n=this.controller.getState();this.workRequest.syncContext({pageId:n.page?.pageId??null,revision:n.revision??null,providerGeneration:i.providerSelection?.generation??null});const s=Nu({clientState:this.client.state,state:i,flow:this.workRequest.snapshot(),provider:Lu(this.workProvider),annotations:n.annotations,eligibleNoteCount:this.workNoteCount,pageId:this.readyPageId});this.overlay.setState({...e,badgeAttention:Object.freeze({pendingCount:this.readyPageId===null?0:this.badgeAttention.pending((e.annotations??this.workAnnotationProjection).flatMap(({badgeAttention:r})=>r===void 0?[]:[r.token]),this.readyPageId).length,persistenceWarning:this.badgeAttention.persistenceWarning,reloadDurable:this.badgeAttention.reloadDurable}),actionEpoch:this.actionEpoch,capabilities:this.overlayCapabilities(),...s})}assertClientReady(){if(this.destroyed)throw k("SCG_CLIENT_DESTROYED");if(this.client.state!=="ready")throw k(this.client.state==="access-error"?"SCG_CLIENT_ACCESS_DENIED":"SCG_CLIENT_UNAVAILABLE")}isCurrentPageState(e){return this.isPageReady()&&this.readyControllerGeneration===e.generation&&this.readyPageId===e.page?.pageId}isPageReady(){return!this.destroyed&&this.navigationStarted&&this.client.state==="ready"&&this.pageReadyNavigationGeneration===this.navigationGeneration&&this.readyControllerGeneration!==null&&this.readyPageId!==null}captureReadyPage(){const e=this.controller.getState();if(!this.isCurrentPageState(e)||e.page===void 0||e.revision===void 0)throw k("SCG_PAGE_UNREADY");return Object.freeze({controllerGeneration:e.generation,navigationGeneration:this.navigationGeneration,page:e.page,readyGeneration:this.pageReadyGeneration})}assertCurrentPageAction(e){const i=this.controller.getState();if(!this.isCurrentPageState(i)||e.navigationGeneration!==this.navigationGeneration||e.readyGeneration!==this.pageReadyGeneration||e.controllerGeneration!==i.generation||e.page.pageId!==i.page?.pageId)throw k("SCG_PAGE_TRANSITION")}renderAnnotationState(e){this.workNoteCount=e.annotations.length,this.setOverlayState({annotations:ef(e.annotations,e.bindings),pageReady:!0,...e.error===void 0?{}:{status:{kind:"error",code:e.error.code}}}),this.projectCurrentWorkReview()}projectCurrentWorkReview(){if(this.destroyed)return;const e=this.controller.getState();if(!this.isCurrentPageState(e))return;const i=this.work.getState(),n=e.page?.pageId,s=e.revision;if(n===void 0||s===void 0)return;const r=st(i),o=Lt(r),a=this.workReviewProjectionGeneration+=1,c=Object.freeze({projectionGeneration:a,pageId:n,revision:s,recordSignature:o}),l={annotations:e.annotations,bindings:e.bindings,pageId:n,records:r},d=new Map(this.workEvidenceCache),u={projectId:this.projectId,evidence:d,store:this.badgeAttention},h=f=>{const b=this.controller.getState(),y=this.work.getState();return Ud(c,{projectionGeneration:this.workReviewProjectionGeneration,pageCurrent:this.isCurrentPageState(b),pageId:b.page?.pageId??null,revision:b.revision??null,recordSignature:Lt(st(y))})?(this.workAnnotationTicket=c,this.publishWorkAnnotations(f),!0):!1};js(l,u).then(async f=>{if(!h(f))return;const b=new Set(f.flatMap(({workCompletion:y})=>y?.phase==="review-pending"&&!d.has(y.requestId)?[y.requestId]:[]));await Promise.all([...b].map(async y=>{d.set(y,await this.workEvidence.read(y)),h(await js(l,u))}))}).catch(()=>{})}async captureSelectedElement(e,i,n){let s;try{s=await lc(e)}catch(a){this.publishSelectionCaptureFailure(a,i,n);return}if(!this.isCurrentSelection(i,n))return;if(!cf(e,this.document)||fe(e)){this.publishSelectionCaptureFailure(k("SCG_SELECTION_CAPTURE_FAILED"),i,n);return}const r=lf(e,this.document);if(r===void 0){this.publishSelectionCaptureFailure(k("SCG_SELECTION_CAPTURE_FAILED"),i,n);return}if(!this.isCurrentSelection(i,n))return;let o;try{o=Wc(e)}catch{}this.selectedTarget=Object.freeze({locator:s,surroundingText:af(e),domOrder:r,navigationGeneration:i,resolution:Object.freeze({status:"resolved",reason:null}),selectionGeneration:n,...o===void 0?{}:{context:o}}),this.selector.stop(),this.releaseSelectionEscape(),this.setOverlayState({pendingSelectionElement:e,selectionMode:!1})}publishSelectionCaptureFailure(e,i,n){if(!this.isCurrentSelection(i,n))return;const s=hf(e),r=[],o=a=>{try{a()}catch(c){r.push(c)}};if(this.selectedTarget=null,o(()=>this.selector.stop()),o(()=>this.setOverlayState({pendingSelectionElement:null,selectionMode:!1})),o(()=>this.controller.setManualError("Scene Glass가 선택한 요소를 캡처하지 못했습니다.",s.code)),r.length>0)throw Ae(s,r)}isCurrentSelection(e,i){return!this.destroyed&&this.navigationGeneration===e&&this.selectionGeneration===i}startMutationObserver(){if(this.mutationObserver!==null||this.destroyed)return;const e=this.document.defaultView?.MutationObserver??globalThis.MutationObserver;if(typeof e!="function")throw k("SCG_MUTATION_OBSERVER_UNAVAILABLE");const i=this.document.documentElement;if(i===null)throw k("SCG_MUTATION_OBSERVER_UNAVAILABLE");let n=null;try{n=new e(this.onHostMutations),n.observe(i,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.mutationObserver=n}catch(s){const r=[],o=n;this.mutationObserver=null,n=null;try{o?.disconnect()}catch(a){r.push(a)}throw Ae(k("SCG_MUTATION_OBSERVER_UNAVAILABLE",s),r)}}stopMutationObserver(){const e=this.hostMutationTimer,i=this.mutationObserver;this.hostMutationTimer=null,this.mutationObserver=null;const n=[];if(e!==null)try{this.window.clearTimeout(e)}catch(s){n.push(s)}try{i?.disconnect()}catch(s){n.push(s)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"Scene Glass mutation observer cleanup failed")}restoreOwnAccessibility(){if(typeof this.document.querySelectorAll=="function")for(const e of this.document.querySelectorAll('.scg-ui-overlay, .scg-ui-launcher, .scg-ui-editor, .scg-ui-badges, [data-scg-owned="true"]'))e.getAttribute("aria-hidden")==="true"&&e.removeAttribute("aria-hidden"),e.hasAttribute("inert")&&e.removeAttribute("inert")}stampHostElementIds(){const e=this.document.documentElement;if(!(e===null||this.destroyed))try{Dc(e,fe)}catch{}}onHostMutations=e=>{!this.navigationStarted||this.destroyed||this.client.state!=="ready"||e.some(i=>df(i))&&(this.hostMutationTimer!==null&&this.window.clearTimeout(this.hostMutationTimer),this.hostMutationTimer=this.window.setTimeout(()=>{this.hostMutationTimer=null,this.stampHostElementIds(),this.restoreOwnAccessibility(),this.requestPageReload(!0)},Fg))};setNavigationFailure(e){this.navigationFailure=e,this.setOverlayState({status:{kind:"error",code:e.code}})}enqueueDiagnosticsOperation(e){const i=this.diagnosticsTask??Promise.resolve(),n=Wt(),s=n.promise;return this.diagnosticsTask=s,i.then(e,e).then(n.resolve,n.reject),s.then(()=>{this.diagnosticsTask===s&&(this.diagnosticsTask=null)},()=>{this.diagnosticsTask===s&&(this.diagnosticsTask=null)}),s}assertCurrentDiagnosticsOwner(e){if(this.destroyed||this.diagnosticsOwner!==e)throw k("SCG_DIAGNOSTIC_CONNECTION_UNAVAILABLE")}destroyDiagnostics(){const e=this.diagnosticsCleanupTask;return this.enqueueDiagnosticsOperation(async()=>{const i=[];if(e!==null)try{await e}catch(n){i.push(n)}try{await this.destroyDiagnosticsSurface()}catch(n){i.push(n)}if(i.length===1)throw i[0];if(i.length>1)throw new AggregateError(i,"Scene Glass diagnostics cleanup failed")})}async destroyDiagnosticsSurface(){const e=this.diagnostics;if(this.diagnostics=null,e===null){this.destroyed||this.setOverlayState({diagnosticsOpen:!1});return}const i=this.destroyDiagnosticResources(e);this.diagnosticsCleanupTask=i,i.then(()=>{this.diagnosticsCleanupTask===i&&(this.diagnosticsCleanupTask=null)},()=>{this.diagnosticsCleanupTask===i&&(this.diagnosticsCleanupTask=null)});try{await i}finally{this.destroyed||this.setOverlayState({diagnosticsOpen:!1})}}async destroyDiagnosticResources(e){const i=[],n=s=>{try{s()}catch(r){i.push(r)}};if(e.panel!==null){const s=e.panel;n(()=>s.destroy())}if(e.controller!==null){const s=e.controller;n(()=>s.destroy())}if(e.transport!==null)try{await e.transport.destroy()}catch(s){i.push(s)}if(i.length>0)throw new AggregateError(i,"Scene Glass diagnostics cleanup failed")}}function Yg(t){return new Hg(t)}class Xg{constructor(e,i){this.dependencies=i,this.capability=e}dependencies;capability;client=null;closed=!1;initializingClient=null;closingClients=new WeakMap;closeTask=null;async issueProjectTestToken(){const e=this.capability;if(this.closed||e===null)throw k("SCG_DIAGNOSTIC_CAPABILITY_UNAVAILABLE");return Object.freeze({token:e.token})}async initialize(e){const i=this.capability;if(this.closed||i===null||e.token!==i.token||this.initializingClient!==null||this.client!==null)throw k("SCG_DIAGNOSTIC_CAPABILITY_UNAVAILABLE");const n=new ps({endpoint:i.endpoint,diagnosticEndpoint:i.endpoint,...Qg(i)?{diagnosticProxyAlias:i.token}:{token:i.token},...this.dependencies});this.initializingClient=n;try{await n.initializeSession()}catch(s){const r=this.closed||this.initializingClient!==n||this.client!==null;if(this.initializingClient===n&&(this.initializingClient=null,this.capability=null),r){const o=k("SCG_DIAGNOSTIC_CONNECTION_UNAVAILABLE",s);try{await this.closeAndDispose(n)}catch(a){throw Ae(o,[a])}throw o}throw n.dispose(),s}if(this.closed||this.initializingClient!==n||this.client!==null){this.initializingClient===n&&(this.initializingClient=null);const s=k("SCG_DIAGNOSTIC_CONNECTION_UNAVAILABLE");try{await this.closeAndDispose(n)}catch(r){throw Ae(s,[r])}throw s}return this.client=n,this.initializingClient=null,this.capability=null,Object.freeze({id:i.runId})}async sendInitializedNotification(){await this.requireClient().sendInitializedNotification()}async ping(){await this.requireClient().ping()}deleteClose(){return this.destroy()}destroy(){if(this.closeTask!==null)return this.closeTask;if(this.closed)return Promise.resolve();const e=Wt();this.closeTask=e.promise,this.closed=!0,this.capability=null;const i=this.client,n=this.initializingClient;this.client=null,this.initializingClient=null;const s=new Set;return i!==null&&s.add(i),n!==null&&s.add(n),Promise.resolve().then(()=>this.closeClients(s)).then(e.resolve,e.reject),e.promise}async closeClients(e){const i=[];for(const n of e)try{await this.closeAndDispose(n)}catch(s){i.push(s)}if(i.length>0)throw new AggregateError(i,"Scene Glass diagnostic cleanup failed")}closeAndDispose(e){const i=this.closingClients.get(e);if(i!==void 0)return i;const n=Wt(),s=n.promise;return this.closingClients.set(e,s),Promise.resolve().then(async()=>{try{await e.close()}finally{e.dispose()}}).then(n.resolve,n.reject),s}requireClient(){if(this.closed||this.client===null)throw k("SCG_DIAGNOSTIC_CONNECTION_UNAVAILABLE");return this.client}}function Qg(t){if(!/^scene-glass-vite-diagnostic-v1-[1-9][0-9]*$/u.test(t.token))return!1;try{const e=new URL(t.endpoint);return e.protocol==="http:"&&e.hostname==="127.0.0.1"&&e.pathname==="/@scene-glass/mcp"&&e.username===""&&e.password===""&&e.search===""&&e.hash===""&&e.port!==""&&e.port!=="4175"}catch{return!1}}function Zg(t){return Object.freeze({create:()=>Object.freeze({provider:t,destroy(){}})})}function Jg(t){return{...t.fetch===void 0?{}:{fetch:t.fetch},...t.now===void 0?{}:{now:t.now},...t.crypto===void 0?{}:{crypto:t.crypto}}}function ef(t,e){const i=new Map(e.map(n=>[n.annotation.id,n.resolution]));return t.map(n=>{const s=i.get(n.id);return Object.freeze({id:n.id,memo:n.memo,resolution:s===void 0?n.resolution.status:s.status==="resolved"?"resolved":s.reason,...s?.status==="resolved"?{element:s.element}:{}})})}function tf(t){return Object.freeze({annotations:t.annotations,revision:t.revision})}function nf(t){const{replay:e,revision:i}=t;if(e.kind!=="create")throw k("SCG_ANNOTATION_REPLAY_INVALID");return Object.freeze({revision:i,annotation:e.annotation})}function sf(t){const{replay:e,revision:i}=t;if(e.kind!=="update")throw k("SCG_ANNOTATION_REPLAY_INVALID");return Object.freeze({revision:i,annotation:e.annotation})}function rf(t){const{replay:e,revision:i}=t;if(e.kind!=="delete")throw k("SCG_ANNOTATION_REPLAY_INVALID");return Object.freeze({revision:i,annotationId:e.annotationId})}function zt(t){if(t.status!=="applied")throw t.status==="failed"?k(t.error.code):k("SCG_ANNOTATION_STALE")}function of(t){switch(t){case"canvas-subobject":return"SCG_SELECTION_UNSUPPORTED_CANVAS_SUBOBJECT";case"iframe-internal":return"SCG_SELECTION_UNSUPPORTED_IFRAME_INTERNAL";case"not-element":return"SCG_SELECTION_UNSUPPORTED_NOT_ELEMENT";case"shadow-child":return"SCG_SELECTION_UNSUPPORTED_SHADOW_CHILD";case"unmounted":return"SCG_SELECTION_UNSUPPORTED_UNMOUNTED"}}function af(t){const e="innerText"in t?t.innerText:void 0,n=(typeof e=="string"?e:t.textContent??"").replace(/\s+/gu," ").trim(),s=new TextEncoder;let r="",o=0,a=0;for(const c of n){if(a>=$g)break;const l=s.encode(c).byteLength;if(o+l>Kg)break;r+=c,o+=l,a+=1}return r}function cf(t,e){const i=e.documentElement;return t.ownerDocument===e&&i!==null&&i.contains(t)&&t.getRootNode()===e}function lf(t,e){let i=0;for(const n of e.querySelectorAll("*"))if(!fe(n)){if(n===t)return i;if(i>=gr)return gr;i+=1}}function df(t){if(t.type==="attributes"&&t.attributeName===ii)return!1;if(t.type!=="childList")return!Gt(t.target);if(Gt(t.target))return!1;for(const e of t.addedNodes)if(!Gt(e))return!0;for(const e of t.removedNodes)if(!Gt(e))return!0;return!1}function Gt(t){const e=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement;return e!==null&&fe(e)}function jt(t){const e=new Uint8Array(16);t.getRandomValues(e),e[6]=(e[6]??0)&15|64,e[8]=(e[8]??0)&63|128;const i=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return te(`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`,"operationId")}function Ae(t,e){return e.length===0||Object.defineProperty(t,"cleanupErrors",{configurable:!0,enumerable:!0,value:Object.freeze([...t.cleanupErrors??[],...e]),writable:!1}),t}function uf(t,e){if(e.length===0)return t;if(t instanceof Error){const i=t;return Object.defineProperty(i,"cleanupErrors",{configurable:!0,enumerable:!0,value:Object.freeze([...i.cleanupErrors??[],...e]),writable:!1}),i}return new AggregateError([t,...e],"Scene Glass diagnostics construction and cleanup failed")}function hf(t){return typeof t=="object"&&t!==null&&t.code==="SCG_SELECTION_CAPTURE_FAILED"&&t.name==="SceneGlassRuntimeError"?t:k("SCG_SELECTION_CAPTURE_FAILED",t)}function Wt(){let t,e;const i=new Promise((n,s)=>{e=n,t=s});if(e===void 0||t===void 0)throw new Error("Scene Glass could not create a deferred task");return Object.freeze({promise:i,resolve:e,reject:t})}function gf(t){const e=ff(t);return typeof t=="object"&&t!==null&&t.code===e&&t.name==="SceneGlassRuntimeError"?t:k(e,t)}function ff(t){return typeof t=="object"&&t!==null&&t.code==="SCG_MUTATION_OBSERVER_UNAVAILABLE"?"SCG_MUTATION_OBSERVER_UNAVAILABLE":"SCG_NAVIGATION_UNAVAILABLE"}function k(t,e){const i=Object.assign(new Error(t),{code:t});return e!==void 0&&Object.defineProperty(i,"cause",{value:e}),i.name="SceneGlassRuntimeError",i}function pf(){if(typeof globalThis.crypto?.getRandomValues!="function")throw k("SCG_CRYPTO_UNAVAILABLE");return globalThis.crypto}const mf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,fr="scg-coupon",wf="/@scene-glass/loader.js",vf="/@scene-glass/mcp",bf="/@scene-glass/diagnostic-runs";function pr(t={}){let e,i;try{e=t.window??Of(),i=t.document??_f()}catch{return}if(e===void 0||i===void 0)return;const n=e,s=i;try{Sf(n)}catch{return}try{const r=t.script??If(s);if(r===null)return Di(n);const o=r.getAttribute("data-scg-endpoint"),a=r.getAttribute("data-scg-project"),c=r.getAttribute("data-scg-token");r.removeAttribute("data-scg-token"),r.removeAttribute("data-scg-coupon"),r.removeAttribute("data-scg-coupon-endpoint");const l=r.getAttribute("data-scg-navigation"),d=t.pageIdentity===void 0?kf(r):t.pageIdentity;if(Mi(n))return;const u=Cf({endpointAttribute:o,origin:n.location.origin,project:a,sourceAttribute:r.getAttribute("src")});if(u===null||c!==null||d===null||!wr(a)||l!=="document"&&l!=="spa")return Di(n);const h=t.measurementProvider===void 0?yf({artifact:Ef(),document:s,origin:u.origin}):void 0,f=Yg({endpoint:u.mcp,diagnosticEndpoint:u.diagnostic,projectId:a,navigation:l,window:n,document:s,...d===void 0?{}:{pageIdentity:d},...t.measurementProvider===void 0?{}:{measurementProvider:t.measurementProvider},...h===void 0?{}:{measurementProviderFactory:h},...t.openDiagnosticsPanel===void 0?{}:{openDiagnosticsPanel:t.openDiagnosticsPanel},...t.fetch===void 0?{}:{fetch:t.fetch},...t.now===void 0?{}:{now:t.now},...t.crypto===void 0?{}:{crypto:t.crypto}}),b=f.getApi();if(!vr(n,b)){f.destroy();return}return f.start(),b}catch{return Di(n)}}function yf(t){const e=t.artifact;return e===void 0?void 0:Object.freeze({create:()=>{const n=new Ka({document:t.document,origin:t.origin,releaseArtifact:e});return Object.freeze({provider:n,destroy:()=>n.destroy()})}})}function Ef(){if(typeof globalThis.atob=="function")try{const t=JSON.parse(globalThis.atob("eyJtb2R1bGVJZCI6InNjZW5lLWdsYXNzLXByZW1pdW0tbWVhc3VyZW1lbnQtdjEiLCJuYW1lc3BhY2UiOiJzY2VuZS1nbGFzcy1wcmVtaXVtLW1lYXN1cmVtZW50LXYxIiwiYWJpVmVyc2lvbiI6MSwibW9kdWxlIjp7InBhdGgiOiJwcmVtaXVtL21lYXN1cmVtZW50LXYxLmpzIiwibWF4Qnl0ZXMiOjI2MjE0NCwibWVkaWFUeXBlIjoiYXBwbGljYXRpb24vamF2YXNjcmlwdDsgY2hhcnNldD11dGYtOCIsInNoYTI1NiI6InNoYTI1NjpmYmVkNTNiNzU1NDQwMTE5MGMyNTFmNjg3OWY3OTcyNzY5OTU0ZmMzNDFkNzZlN2Y2ZGRiYjcxMzk3OTkyMGQ0In0sInN0eWxlc2hlZXQiOnsicGF0aCI6InByZW1pdW0vbWVhc3VyZW1lbnQtdjEuY3NzIiwibWF4Qnl0ZXMiOjY1NTM2LCJtZWRpYVR5cGUiOiJ0ZXh0L2NzczsgY2hhcnNldD11dGYtOCIsInNoYTI1NiI6InNoYTI1Njo2ZGZkZDY0ODEzOTNkZjRmZDA2ZDNiYTA2ZTQwMzIxNTFhZjk2OThmZjUwMmYxNjA0NjUzNzViMzI2OWE3NDRlIn19"));return Ji(t)}catch{return}}function Sf(t){const e=new URL(t.location.href);e.searchParams.has(fr)&&(e.searchParams.delete(fr),t.history.replaceState(t.history.state,"",e.href))}function kf(t){const e=t.getAttribute("data-scg-page-identity");if(e==="")return null;const i=mr(t.getAttribute("data-scg-include-query")),n=mr(t.getAttribute("data-scg-include-hash"));if(i===null||n===null)return null;if(!(e===null&&i===void 0&&n===void 0))return Object.freeze({...e===null?{}:{override:e},...i===void 0&&n===void 0?{}:{policy:Object.freeze({includeQuery:i??!1,includeHash:n??!1})}})}function mr(t){if(t!==null)return t==="true"?!0:t==="false"?!1:null}function Cf(t){if(!wr(t.project)||t.endpointAttribute!==null||t.sourceAttribute!==wf)return null;let e;try{e=new URL(t.origin)}catch{return null}const i=Number(e.port);return e.protocol!=="http:"||e.hostname!=="127.0.0.1"||e.username!==""||e.password!==""||e.pathname!=="/"||e.search!==""||e.hash!==""||!Number.isInteger(i)||i<1024||i>65535||i===4175||e.origin!==t.origin?null:Object.freeze({mcp:`${e.origin}${vf}`,diagnostic:`${e.origin}${bf}`,origin:e.origin})}function wr(t){return t!==null&&mf.test(t)}function If(t){const e=t.currentScript;return e===null||typeof e.getAttribute!="function"||typeof e.removeAttribute!="function"?null:e}function Mi(t){try{return"SceneGlass"in t}catch{return!0}}function Di(t){if(Mi(t))return;const e=Af();return vr(t,e)?e:void 0}function vr(t,e){if(Mi(t))return!1;try{return Object.defineProperty(t,"SceneGlass",{configurable:!1,enumerable:!1,writable:!1,value:e}),!0}catch{return!1}}function Af(){let t="unavailable";return Object.freeze({get state(){return t},notifyReady(){},retry(){return Promise.resolve()},openDiagnostics(){return Promise.reject(new Error("Scene Glass is unavailable"))},destroy(){return t="destroyed",Promise.resolve()}})}function Of(){return typeof window>"u"?void 0:window}function _f(){return typeof document>"u"?void 0:document}return typeof window<"u"&&typeof document<"u"&&pr(),Ut.installSceneGlass=pr,Object.defineProperty(Ut,Symbol.toStringTag,{value:"Module"}),Ut})({});