@mearl/native-host 3.0.0-beta.1 → 3.0.0-beta.10

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.
Files changed (44) hide show
  1. package/README.md +119 -168
  2. package/README.zh-CN.md +319 -0
  3. package/dist/THIRD_PARTY_NOTICES.txt +22 -655
  4. package/dist/agent/chat-visualization.d.ts +3 -0
  5. package/dist/agent/managed-programs.d.ts +24 -0
  6. package/dist/agent/manager.d.ts +15 -2
  7. package/dist/agent/skill-manager.d.ts +8 -1
  8. package/dist/app-authorization.d.ts +8 -0
  9. package/dist/app-profile-catalog.d.ts +3 -1
  10. package/dist/browser-enhancement-gateway.d.ts +24 -0
  11. package/dist/browser-identity.d.ts +11 -0
  12. package/dist/browser-registry.d.ts +1 -0
  13. package/dist/browser-socket-request.d.ts +4 -0
  14. package/dist/capability-contracts.d.ts +15 -52
  15. package/dist/capability-hooks.d.ts +42 -0
  16. package/dist/cdp-backend/buffers.d.ts +11 -11
  17. package/dist/cdp-backend/capability-handlers.d.ts +1 -0
  18. package/dist/cdp-backend/cdp-session.d.ts +2 -0
  19. package/dist/cdp-backend/cdp-utils.d.ts +3 -8
  20. package/dist/cdp-backend/handlers.d.ts +2 -1
  21. package/dist/cdp-backend/http-handlers.d.ts +12 -9
  22. package/dist/cdp-backend/network-control.d.ts +5 -0
  23. package/dist/cdp-backend/page-dialogs.d.ts +14 -0
  24. package/dist/cdp-backend/request-cookies.d.ts +8 -0
  25. package/dist/cdp-backend/response-cookies.d.ts +8 -0
  26. package/dist/cdp-backend/send-request.d.ts +3 -2
  27. package/dist/control-session-manager.d.ts +1 -1
  28. package/dist/index.js +182 -217
  29. package/dist/install.js +1 -1
  30. package/dist/native-capability-services.d.ts +5 -2
  31. package/dist/node-capabilities.d.ts +1 -0
  32. package/dist/node-capabilities.js +2 -2
  33. package/dist/page-runtime-store.d.ts +2 -27
  34. package/dist/plugin-task-host.js +30 -45
  35. package/dist/plugin-worker.js +23 -38
  36. package/dist/pluginModelSessionWorker.js +1 -1
  37. package/dist/preset-auto-update.d.ts +18 -0
  38. package/dist/preset-components.d.ts +3 -1
  39. package/dist/provider-app-resources.d.ts +32 -0
  40. package/dist/provider-control.d.ts +1 -1
  41. package/dist/provider-enhancements.d.ts +21 -0
  42. package/package.json +13 -11
  43. package/dist/alipay-auth-code.d.ts +0 -13
  44. package/dist/cdp-backend/mtop-environment.d.ts +0 -7
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mearlCreateRequire } from 'node:module'; const require = __mearlCreateRequire(import.meta.url);
2
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key2 of __getOwnPropNames(from))!__hasOwnProp.call(to,key2)&&key2!==except&&__defProp(to,key2,{get:()=>from[key2],enumerable:!(desc=__getOwnPropDesc(from,key2))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));import{readFileSync,readdirSync}from"node:fs";import{spawnSync}from"node:child_process";function linuxProcessStat(pid){let stat2=readFileSync(`/proc/${pid}/stat`,"utf8"),end=stat2.lastIndexOf(")"),fields2=stat2.slice(end+2).trim().split(/\s+/),group=Number(fields2[2]),threads=Number(fields2[17]);if(end<0||!/^[A-Za-z]$/.test(fields2[0])||!Number.isSafeInteger(group)||group<0||!Number.isSafeInteger(threads)||threads<0||!/^\d+$/.test(fields2[19]??""))throw new Error("Invalid Linux process stat");return{state:fields2[0],group,threads,identity:fields2[19]}}function linuxProcessExited({state,threads}){return threads<=1&&(state==="Z"||state==="X"||state==="x")}function processIdentity(pid){if(!(!Number.isSafeInteger(pid)||pid<1))try{if(process.platform==="linux")return linuxProcessStat(pid).identity;let result=process.platform==="win32"?spawnSync("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:2e3,windowsHide:!0}):spawnSync("ps",["-p",String(pid),"-o","lstart="],{encoding:"utf8",timeout:2e3});return result.status===0&&result.stdout.trim()||void 0}catch{return}}function isProcessOwnerAlive(owner){if(!isAlive(owner.pid))return!1;if(typeof owner.processIdentity!="string")return!0;let current2=processIdentity(owner.pid);return current2===void 0||current2===owner.processIdentity}function isAlive(pid){if(!Number.isSafeInteger(pid)||!pid||pid<=0)return!1;try{if(process.kill(pid,0),process.platform==="linux")try{return!linuxProcessExited(linuxProcessStat(pid))}catch{return!0}return!0}catch(error2){return error2.code==="EPERM"}}function isProcessGroupAlive(group){if(!Number.isSafeInteger(group)||group<1)return!1;if(process.platform==="win32")return!0;let probe=()=>{try{return process.kill(-group,0),!0}catch(error2){return error2.code==="ESRCH"?!1:void 0}},present=probe();if(present!==!0)return present!==!1;if(process.platform!=="linux")return!0;let exitedMembers=()=>{let members=new Set;try{for(let name of readdirSync("/proc"))if(/^\d+$/.test(name))try{let stat2=linuxProcessStat(Number(name));if(stat2.group!==group)continue;if(!linuxProcessExited(stat2))return;members.add(`${name}:${stat2.identity}`)}catch(error2){if(!["ENOENT","ESRCH"].includes(error2.code??""))return}return members}catch{return}},first=exitedMembers();if(!first)return!0;let second=exitedMembers();return second?first.size&&first.size===second.size&&[...first].every(pid=>second.has(pid))?!1:probe()!==!1:!0}var init_process=__esm({"../daemon-core/dist/process.js"(){"use strict"}});import{join}from"node:path";import{homedir}from"node:os";import{createHash}from"node:crypto";function hashKey(key2){return createHash("sha256").update(key2).digest("hex").slice(0,16)}function keyedDir(subdir){return join(DAEMON_HOME,subdir)}function keyedConfigFile(subdir,key2){return join(keyedDir(subdir),`${hashKey(key2)}.json`)}var DAEMON_HOME,init_paths=__esm({"../daemon-core/dist/paths.js"(){"use strict";DAEMON_HOME=join(homedir(),".mearl")}});import{closeSync,existsSync,linkSync,openSync,statSync,mkdirSync,readFileSync as readFileSync2,writeFileSync,renameSync,rmSync,readdirSync as readdirSync2}from"node:fs";import{dirname,join as join2}from"node:path";import{randomUUID}from"node:crypto";function ensureDir(dir){existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}function pauseForLock(){Atomics.wait(lockWaitBuffer,0,0,LOCK_WAIT_MS)}function readRecordUnlocked(file){try{if(!existsSync(file))return null;let parsed=JSON.parse(readFileSync2(file,"utf-8"));return parsed&&typeof parsed.pid=="number"?parsed:null}catch{return null}}function removeRecordUnlocked(file){rmSync(file,{force:!0})}function writeRecordUnlocked(file,record2){let tmp=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify(record2),{mode:384}),renameSync(tmp,file)}catch(error2){try{rmSync(tmp,{force:!0})}catch{}throw error2}}function removeStaleLock(lockDir){let ownerFile=join2(lockDir,"owner.json"),owner=readRecordUnlocked(ownerFile);if(owner){if(isAlive(owner.pid))return!1}else try{if(Date.now()-statSync(lockDir).mtimeMs<OWNER_WRITE_GRACE_MS)return!1}catch{return!0}try{return rmSync(lockDir,{recursive:!0,force:!0}),!0}catch{return!1}}function withRecordLock(file,operation){ensureDir(dirname(file));let lockDir=`${file}.registry.lock`,ownerFile=join2(lockDir,"owner.json"),token=randomUUID(),deadline=Date.now()+LOCK_TIMEOUT_MS;for(;;){try{mkdirSync(lockDir,{mode:448})}catch(error2){if(error2.code!=="EEXIST")throw error2;if(!removeStaleLock(lockDir)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for registry lock: ${file}`,{cause:error2});pauseForLock()}continue}let ownerFd=null;try{ownerFd=openSync(ownerFile,"wx",384),writeFileSync(ownerFd,JSON.stringify({pid:process.pid,token}))}catch(error2){if(ownerFd!==null&&closeSync(ownerFd),ownerFd=null,error2.code==="EEXIST"){if(Date.now()>=deadline)throw new Error(`Timed out acquiring registry lock: ${file}`,{cause:error2});pauseForLock();continue}throw error2}finally{ownerFd!==null&&closeSync(ownerFd)}try{return operation()}finally{readRecordUnlocked(ownerFile)?.token===token&&rmSync(lockDir,{recursive:!0,force:!0})}}}function writeRecord(file,record2){withRecordLock(file,()=>writeRecordUnlocked(file,record2))}function claimRecord(file,record2){return withRecordLock(file,()=>{let candidate=`${file}.${process.pid}.${randomUUID()}.claim`;try{return writeFileSync(candidate,JSON.stringify(record2),{mode:384}),linkSync(candidate,file),!0}catch(error2){if(error2.code==="EEXIST")return!1;throw error2}finally{rmSync(candidate,{force:!0})}})}function readRecord(file){return readRecordUnlocked(file)}function removeRecordIfPid(file,pid){try{return withRecordLock(file,()=>readRecordUnlocked(file)?.pid!==pid?!1:(removeRecordUnlocked(file),!0))}catch{return!1}}function writeRecordIfPid(file,pid,record2){return withRecordLock(file,()=>readRecordUnlocked(file)?.pid!==pid?!1:(writeRecordUnlocked(file,record2),!0))}function removeInvalidRecord(file){try{return withRecordLock(file,()=>!existsSync(file)||readRecordUnlocked(file)?!1:(removeRecordUnlocked(file),!0))}catch{return!1}}function listRecordFiles(dir){try{return readdirSync2(dir).filter(name=>name.endsWith(".json")).map(name=>join2(dir,name))}catch{return[]}}var LOCK_WAIT_MS,LOCK_TIMEOUT_MS,OWNER_WRITE_GRACE_MS,lockWaitBuffer,init_registry=__esm({"../daemon-core/dist/registry.js"(){"use strict";init_process();LOCK_WAIT_MS=10,LOCK_TIMEOUT_MS=5e3,OWNER_WRITE_GRACE_MS=1e3,lockWaitBuffer=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))}});import{existsSync as existsSync2,statSync as statSync2,renameSync as renameSync2,readFileSync as readFileSync3,readdirSync as readdirSync3,rmSync as rmSync2}from"node:fs";import{join as join3}from"node:path";function rotateLogIfNeeded(logFile,maxBytes=DEFAULT_MAX_LOG_BYTES){try{if(!existsSync2(logFile)||statSync2(logFile).size<maxBytes)return;renameSync2(logFile,`${logFile}.1`)}catch{}}var DEFAULT_MAX_LOG_BYTES,init_log=__esm({"../daemon-core/dist/log.js"(){"use strict";DEFAULT_MAX_LOG_BYTES=5*1024*1024}});import{spawn}from"node:child_process";import{closeSync as closeSync2,openSync as openSync2}from"node:fs";import{dirname as dirname2}from"node:path";var init_daemon=__esm({"../daemon-core/dist/daemon.js"(){"use strict";init_process();init_registry();init_log()}});import fs from"node:fs";import path from"node:path";import{spawn as spawn2}from"node:child_process";import{AsyncLocalStorage}from"node:async_hooks";function versionManagerExecutableCandidates(home,names,options={}){let env=options.env??process.env,platform=options.platform??process.platform,readdirSync8=options.readdirSync??fs.readdirSync,fnmDefaultRoot=env.XDG_DATA_HOME?path.join(env.XDG_DATA_HOME,"fnm"):platform==="darwin"?path.join(home,"Library","Application Support","fnm"):platform==="win32"&&env.APPDATA?path.join(env.APPDATA,"fnm"):path.join(home,".local","share","fnm");return[path.join(env.NVM_DIR||path.join(home,".nvm"),"versions","node"),path.join(env.FNM_DIR||fnmDefaultRoot,"node-versions"),path.join(home,".fnm","node-versions")].filter((root,index,all)=>all.indexOf(root)===index).flatMap(root=>{try{return readdirSync8(root,{withFileTypes:!0}).filter(entry=>entry.isDirectory()).sort((left,right)=>right.name.localeCompare(left.name,void 0,{numeric:!0})).flatMap(entry=>names.flatMap(name=>[path.join(root,entry.name,"bin",name),path.join(root,entry.name,"installation","bin",name)]))}catch{return[]}})}function resolveSpawnCommand(executable,args,platform=process.platform,commandInterpreter=process.env.ComSpec){return platform==="win32"&&/\.(?:cmd|bat)$/i.test(executable)?{command:commandInterpreter||"cmd.exe",args:["/d","/s","/c",executable,...args]}:{command:executable,args}}function prependNodePath(env=process.env,nodeExecutable=process.execPath){return prependPathDirectory(path.dirname(nodeExecutable),env)}function prependPathDirectory(directory,env=process.env){let pathKey=Object.keys(env).find(key2=>key2.toLowerCase()==="path")||"PATH",entries=(env[pathKey]||"").split(path.delimiter).filter(Boolean);return entries.includes(directory)?env:{...env,[pathKey]:[directory,...entries].join(path.delimiter)}}var ownedCommands,init_command=__esm({"../daemon-core/dist/command.js"(){"use strict";init_process();ownedCommands=new AsyncLocalStorage}});var init_dist=__esm({"../daemon-core/dist/index.js"(){"use strict";init_process();init_paths();init_registry();init_log();init_daemon();init_command()}});function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function invalid(path8){throw new Error(`Invalid app profile: ${path8}`)}function text(value){return typeof value=="string"&&value.length<=4096&&Array.from(value).every(character=>character.charCodeAt(0)>8)}function strings(value){return Array.isArray(value)&&value.length<=200&&value.every(text)}function fields(value,required,optional,path8){(!record(value)||required.some(key2=>!Object.hasOwn(value,key2))||Object.keys(value).some(key2=>!required.includes(key2)&&!optional.includes(key2)))&&invalid(path8)}function stringMap(value){return record(value)&&Object.keys(value).length<=200&&Object.values(value).every(text)}function json(value,depth=0){return depth>25?!1:value===null||typeof value=="boolean"||text(value)?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.length<=1e3&&value.every(item=>json(item,depth+1)):record(value)&&Object.entries(value).every(([key2,item])=>!["__proto__","prototype","constructor"].includes(key2)&&json(item,depth+1))}function validateActions(value){let arrays=["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext","noop","silent"];fields(value,["open","close","title","systemInfo","mtop","noop"],[...arrays,"responses","behaviors"],"actions");for(let key2 of arrays)value[key2]!==void 0&&!strings(value[key2])&&invalid(`actions.${key2}`);value.responses!==void 0&&!record(value.responses)&&invalid("actions.responses"),value.behaviors!==void 0&&(!stringMap(value.behaviors)||!Object.values(value.behaviors).every(item=>BEHAVIORS.has(item)))&&invalid("actions.behaviors")}function validateAppProfileDefinition(value){json(value)||invalid("JSON"),JSON.stringify(value).length>65536&&invalid("definition exceeds 64 KiB"),fields(value,["name","label","appName","defaultAppVersion","uaTokens","globals","bridges","activeEvents","actions","schemes"],["pageRuntime","uaFamily","uaTemplate","policies","settings","settingsGroup","miniProgram","imagePicker","geolocation","urlSyncHostSuffixes","overlay","popBeforeOpenParam","messageEvent","nativeBack","layerUrlProxy","rootContainer","titleBarHiddenPathnames","statusBarBackgroundColors","titleBarHostStyles","forceH5Mtop"],"definition");for(let key2 of["name","label","appName","defaultAppVersion"])(!text(value[key2])||!value[key2])&&invalid(key2);if(/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)?$/.test(value.name)||invalid("name"),value.pageRuntime!==void 0){fields(value.pageRuntime,["id","sha256"],[],"pageRuntime");let runtime=value.pageRuntime;(typeof runtime.id!="string"||!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(runtime.id)||typeof runtime.sha256!="string"||!/^[a-f0-9]{64}$/.test(runtime.sha256))&&invalid("pageRuntime")}for(let key2 of["uaTokens","activeEvents","urlSyncHostSuffixes","titleBarHiddenPathnames"])value[key2]!==void 0&&!strings(value[key2])&&invalid(key2);stringMap(value.globals)||invalid("globals"),(!Array.isArray(value.bridges)||value.bridges.length>20)&&invalid("bridges");let globals=new Set;for(let bridge of value.bridges)fields(bridge,["global","style"],["persistent"],"bridges"),(!text(bridge.global)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(bridge.global)||bridge.global.split(".").some(part=>["__proto__","prototype","constructor"].includes(part))||globals.has(bridge.global)||!BRIDGE_STYLES.has(bridge.style)||bridge.persistent!==void 0&&typeof bridge.persistent!="boolean")&&invalid("bridge"),globals.add(bridge.global);if(validateActions(value.actions),value.settingsGroup!==void 0&&!["fliggy","alipay"].includes(value.settingsGroup)&&invalid("settingsGroup"),value.uaFamily!==void 0&&!["aliapp","wechatMiniProgram"].includes(value.uaFamily)&&invalid("uaFamily"),value.uaTemplate!==void 0&&(fields(value.uaTemplate,["ios","android"],[],"uaTemplate"),(!text(value.uaTemplate.ios)||!text(value.uaTemplate.android))&&invalid("uaTemplate")),value.policies!==void 0){fields(value.policies,[],["titleBar","navigatorLanguage","networkResult","languages","defaultLanguage"],"policies");let p=value.policies;p.titleBar!==void 0&&!["default","taobao","fliggy","alipay","wechat"].includes(p.titleBar)&&invalid("policies.titleBar"),p.networkResult!==void 0&&!["default","alipay"].includes(p.networkResult)&&invalid("policies.networkResult"),p.navigatorLanguage!==void 0&&typeof p.navigatorLanguage!="boolean"&&invalid("policies.navigatorLanguage"),p.languages!==void 0&&(!strings(p.languages)||!p.languages.length)&&invalid("policies.languages"),p.defaultLanguage!==void 0&&(!text(p.defaultLanguage)||p.languages&&!p.languages.includes(p.defaultLanguage))&&invalid("policies.defaultLanguage")}(!Array.isArray(value.schemes)||value.schemes.length>100)&&invalid("schemes");for(let rule of value.schemes){fields(rule,["match"],["hostSuffixes","param","useCurrentOrigin","targetPath","targetHostPrefix","targetParams"],"scheme");for(let key2 of["match","param","targetPath","targetHostPrefix"])rule[key2]!==void 0&&!text(rule[key2])&&invalid(`scheme.${key2}`);rule.hostSuffixes!==void 0&&!strings(rule.hostSuffixes)&&invalid("scheme.hostSuffixes"),rule.useCurrentOrigin!==void 0&&typeof rule.useCurrentOrigin!="boolean"&&invalid("scheme.useCurrentOrigin"),rule.targetParams!==void 0&&!stringMap(rule.targetParams)&&invalid("scheme.targetParams")}if(value.settings!==void 0){(!Array.isArray(value.settings)||value.settings.length>30)&&invalid("settings");let ids=new Set;for(let setting of value.settings){if(fields(setting,["id","label","type","target"],["choices","minimum","maximum"],"setting"),(!text(setting.id)||!/^[a-z][a-zA-Z0-9-]*$/.test(setting.id)||ids.has(setting.id)||!text(setting.label)||!["select","boolean","number","text","json"].includes(setting.type))&&invalid("setting"),ids.add(setting.id),record(setting.target)&&setting.target.option!==void 0)fields(setting.target,["option"],[],"setting.target"),setting.target.option!=="language"&&invalid("setting.target.option");else{fields(setting.target,["method"],["field"],"setting.target"),(!text(setting.target.method)||!setting.target.method||["__proto__","prototype","constructor"].includes(setting.target.method)||setting.target.field!==void 0&&(!text(setting.target.field)||["__proto__","prototype","constructor"].includes(setting.target.field)))&&invalid("setting.target.method");let method=setting.target.method;["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext"].some(key2=>value.actions[key2]?.includes(method))&&invalid("setting targets a structural method")}setting.choices!==void 0&&(!Array.isArray(setting.choices)||!setting.choices.length||setting.choices.some(choice=>!record(choice)||!text(choice.label)||!text(choice.value)))&&invalid("setting.choices");for(let key2 of["minimum","maximum"])setting[key2]!==void 0&&typeof setting[key2]!="number"&&invalid(`setting.${key2}`);setting.type==="select"&&!Array.isArray(setting.choices)&&invalid("setting.choices required"),setting.minimum!==void 0&&setting.maximum!==void 0&&setting.minimum>setting.maximum&&invalid("setting range"),"option"in setting.target&&!["select","text"].includes(setting.type)&&invalid("setting.option type")}}for(let key2 of["forceH5Mtop"])value[key2]!==void 0&&typeof value[key2]!="boolean"&&invalid(key2);for(let key2 of["popBeforeOpenParam","messageEvent"])value[key2]!==void 0&&!text(value[key2])&&invalid(key2);return value.statusBarBackgroundColors!==void 0&&!stringMap(value.statusBarBackgroundColors)&&invalid("statusBarBackgroundColors"),validateStructuredOptions(value),JSON.parse(JSON.stringify(value))}function validateStructuredOptions(value){let shapes={nativeBack:[[],["event","controlFunction","handler"]],geolocation:[["reverseGeocodeApi","version"],[]],layerUrlProxy:[["sourceHostPrefix","pathPrefix","targetHostSuffixes"],["defaultTargetHost"]],imagePicker:[["schemes","api","version","fcId","fcGroup","uploadUrlFunction","prefix","region"],[]],overlay:[["enabledParam","topRatioParam","radiusParam","maskAlphaParam","tapCloseParam","defaultTopRatio","defaultRadius","defaultMaskAlpha","defaultTapClose"],["heightRatioParam","tapCloseSelectors","silentTapClose","maxWidthPx","maxWidthMinAppVersion"]]};for(let[key2,[required,optional]]of Object.entries(shapes))if(value[key2]!==void 0){fields(value[key2],required,optional,key2);for(let[field,item]of Object.entries(value[key2]))(field==="maxWidthPx"?typeof item=="number"&&Number.isFinite(item)&&item>0:field==="maxWidthMinAppVersion"?typeof item=="string"&&/^\d+(?:\.\d+)*$/.test(item):field.startsWith("default")&&field!=="defaultTargetHost"?field==="defaultTapClose"?typeof item=="boolean":typeof item=="number":field==="silentTapClose"?typeof item=="boolean":["schemes","targetHostSuffixes","tapCloseSelectors"].includes(field)?strings(item):text(item))||invalid(`${key2}.${field}`)}if(value.rootContainer!==void 0&&(fields(value.rootContainer,[],["statusBarHeightCookie"],"rootContainer"),value.rootContainer.statusBarHeightCookie!==void 0&&(fields(value.rootContainer.statusBarHeightCookie,["name"],["domain","path"],"rootContainer.statusBarHeightCookie"),Object.values(value.rootContainer.statusBarHeightCookie).every(text)||invalid("rootContainer.statusBarHeightCookie"))),value.titleBarHostStyles!==void 0&&(!Array.isArray(value.titleBarHostStyles)||value.titleBarHostStyles.some(rule=>(fields(rule,["hostSuffix"],["titleBarBackgroundColor","statusBarBackgroundColor"],"titleBarHostStyle"),!Object.values(rule).every(text))))&&invalid("titleBarHostStyles"),value.miniProgram!==void 0){fields(value.miniProgram,[],["paymentRoutes","nativeRoutes","messageRules"],"miniProgram");let shapes2={paymentRoutes:[["pathname","paymentParamsParam","successUrlParams","failureUrlParams"],["hostSuffixes","successResultParam","forwardParams","useCurrentOrigin"]],nativeRoutes:[["pathname","actions"],["hostSuffixes"]],messageRules:[["type","action"],["hostSuffixes"]]};for(let[key2,list2]of Object.entries(value.miniProgram)){(!Array.isArray(list2)||list2.length>100)&&invalid(`miniProgram.${key2}`);for(let rule of list2){fields(rule,...shapes2[key2],`miniProgram.${key2}`);for(let[field,item]of Object.entries(rule))(["hostSuffixes","successUrlParams","failureUrlParams","forwardParams","actions"].includes(field)?!strings(item):field==="useCurrentOrigin"?typeof item!="boolean":!text(item))&&invalid(`miniProgram.${key2}.${field}`);key2==="messageRules"&&!["stageBackData","closeAll"].includes(rule.action)&&invalid("miniProgram.messageRules.action"),key2==="nativeRoutes"&&!rule.actions.every(action=>["navigateMiniProgram","subscribeMessage"].includes(action))&&invalid("miniProgram.nativeRoutes.actions")}}}}function validateAppProfileContribution(value){if(value===void 0)return;fields(value,["version","profiles"],[],"contribution"),(value.version!==1||!Array.isArray(value.profiles)||!value.profiles.length||value.profiles.length>20)&&invalid("contribution");let profiles=value.profiles.map(validateAppProfileDefinition);return JSON.stringify(profiles).length>256e3&&invalid("contribution exceeds 256 KiB"),profiles.some(profile=>profile.name.includes("/"))&&invalid("contribution names must be local identifiers"),new Set(profiles.map(profile=>profile.name)).size!==profiles.length&&invalid("duplicate profile name"),{version:1,profiles}}var BRIDGE_STYLES,APP_BRIDGE_BEHAVIORS,BEHAVIORS,init_appProfileDefinition=__esm({"../browser-core/dist/appProfileDefinition.js"(){"use strict";BRIDGE_STYLES=new Set(["windvane","fliggy","alipay","callback","btrip","invoke","callHandler","amap","didi","easybikeNative","mega","wechat","wechatMiniProgram"]),APP_BRIDGE_BEHAVIORS=["navigate","closeAll","closeBackData","postMessage","notifySubscribe","notifyUnsubscribe","notifyPost","sharedFileRead","sharedFileWrite","sharedDataGet","sharedDataSet","legacyBroadcastCreate","legacyBroadcastPost","legacyBroadcastClose","memoryGet","memorySet","memoryDelete","availabilityMap","userInfo","authCode","networkInfo","geolocation","permission","imagePicker","prefetch","fptTrack","mtopStream","previewFile","toast","unsupportedNativeInput","payment","userTrack","calendar","networkQualityMonitor","beaconRequest","voiceRecognition"],BEHAVIORS=new Set(APP_BRIDGE_BEHAVIORS)}});var init_types=__esm({"../browser-core/dist/types.js"(){"use strict"}});var init_capture=__esm({"../browser-core/dist/capture.js"(){"use strict"}});var init_eventFilters=__esm({"../browser-core/dist/eventFilters.js"(){"use strict";init_capture()}});var init_requestSerializer=__esm({"../browser-core/dist/requestSerializer.js"(){"use strict"}});var textEncoder,init_boundedRequestBuffer=__esm({"../browser-core/dist/boundedRequestBuffer.js"(){"use strict";textEncoder=new TextEncoder}});var ALLOWED_ORIGINS,ALLOWED_ORIGINS_LIST,init_proxyPermissions=__esm({"../browser-core/dist/proxyPermissions.js"(){"use strict";ALLOWED_ORIGINS=["*://localhost/*","*://127.0.0.1/*"],ALLOWED_ORIGINS_LIST=[...ALLOWED_ORIGINS]}});var init_domTyping=__esm({"../browser-core/dist/domTyping.js"(){"use strict"}});var init_domSelectors=__esm({"../browser-core/dist/domSelectors.js"(){"use strict"}});function scrollElementInPage(direction,distance,targetLabel,containerPolicy="self"){let element=this?.nodeType===3?this.parentElement:this,targetDocument=element?.nodeType===9?element:null;if(targetDocument&&(element=targetDocument.scrollingElement),!element||element.isConnected===!1)return{error:"Cannot resolve scroll container: "+targetLabel};let startingElement=element,ancestorDistance=0;function scrollMetrics(candidate){let scrollTop=Number(candidate?.scrollTop),scrollHeight=Number(candidate?.scrollHeight),clientHeight=Number(candidate?.clientHeight);if(!Number.isFinite(scrollTop)||!Number.isFinite(scrollHeight)||!Number.isFinite(clientHeight))return null;let ownerDocument=candidate.ownerDocument,isRootScroller=!!ownerDocument&&candidate===ownerDocument.scrollingElement,maxScrollTop=Math.max(0,scrollHeight-clientHeight),overflowAllowsScroll=!0;try{let overflowY=ownerDocument?.defaultView?.getComputedStyle(candidate).overflowY;!isRootScroller&&(overflowY==="visible"||overflowY==="clip")&&(overflowAllowsScroll=!1)}catch{}return{scrollTop,scrollHeight,clientHeight,maxScrollTop,isRootScroller,usable:isRootScroller||maxScrollTop>0&&overflowAllowsScroll}}function documentFallback(documentRef){let windowRef=documentRef.defaultView,visited=new Set,viewportWidth=Number(windowRef?.innerWidth)||Number(element?.clientWidth)||0,viewportHeight=Number(windowRef?.innerHeight)||Number(element?.clientHeight)||0,points=[[viewportWidth/2,viewportHeight/2],[viewportWidth/2,viewportHeight*.75],[viewportWidth/2,viewportHeight*.25]];function containerDepth(candidate){if(candidate===documentRef.body||candidate===documentRef.documentElement)return 0;let depth=0,cursor=candidate;for(;cursor&&cursor!==documentRef.body&&cursor!==documentRef.documentElement;)depth+=1,cursor=cursor.parentElement;return depth}function canMove(metrics2){return direction==="up"||direction==="top"?metrics2.scrollTop>0:metrics2.scrollTop<metrics2.maxScrollTop}let sampledPageContainer;for(let[x,y]of points){let candidate=null;try{candidate=documentRef.elementFromPoint?.(x,y)??null}catch{}for(;candidate&&candidate.nodeType===1;){if(!visited.has(candidate)){visited.add(candidate);let candidateMetrics=scrollMetrics(candidate);if(candidateMetrics?.usable&&candidateMetrics.maxScrollTop>0&&canMove(candidateMetrics)){let resolved={element:candidate,metrics:candidateMetrics,distance:containerDepth(candidate)};if(candidate===documentRef.body||candidate===documentRef.documentElement)sampledPageContainer??=resolved;else return resolved}}candidate=candidate.parentElement}}if(sampledPageContainer)return sampledPageContainer;let best,candidates=Array.from(documentRef.querySelectorAll?.("*")??[]).slice(0,1e4);for(let candidate of candidates){let candidateMetrics=scrollMetrics(candidate);if(!candidateMetrics?.usable||candidateMetrics.maxScrollTop<=0||!canMove(candidateMetrics))continue;let rect,style;try{rect=candidate.getBoundingClientRect(),style=windowRef?.getComputedStyle(candidate)}catch{continue}if(!rect||rect.width<=0||rect.height<=0||style?.display==="none"||style?.visibility==="hidden"||style?.visibility==="collapse")continue;let visibleWidth=Math.max(0,Math.min(rect.right,viewportWidth)-Math.max(rect.left,0)),visibleHeight=Math.max(0,Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0)),area=visibleWidth*visibleHeight;if(area<=0)continue;let depth=containerDepth(candidate);(!best||depth<best.distance||depth===best.distance&&area>best.area)&&(best={element:candidate,metrics:candidateMetrics,distance:depth,area})}return best?{element:best.element,metrics:best.metrics,distance:best.distance}:null}function selectorFor(candidate){let documentRef=candidate?.ownerDocument;if(!documentRef||candidate.nodeType!==1)return"";if(candidate===documentRef.documentElement)return"html";if(candidate===documentRef.body)return"body";let escapeCss=value=>documentRef.defaultView?.CSS?.escape?documentRef.defaultView.CSS.escape(value):value.replace(/[^a-zA-Z0-9_-]/g,character=>"\\"+character);if(candidate.id){let idSelector="#"+escapeCss(String(candidate.id));try{if(documentRef.querySelectorAll(idSelector).length===1)return idSelector}catch{}}let path8=[],cursor=candidate;for(;cursor&&cursor.nodeType===1&&path8.length<8;){let tag=String(cursor.tagName||"").toLowerCase();if(!tag)break;let parent=cursor.parentElement;if(!parent){path8.unshift(tag);break}let siblings=Array.from(parent.children).filter(sibling2=>sibling2.tagName===cursor.tagName),index=siblings.indexOf(cursor)+1;if(path8.unshift(siblings.length>1?tag+":nth-of-type("+index+")":tag),cursor=parent,cursor===documentRef.documentElement){path8.unshift("html");break}}return path8.join(" > ")}let metrics=scrollMetrics(element);if(!metrics)return{error:"Element is not scrollable: "+targetLabel};if(targetDocument){let fallback=documentFallback(targetDocument);fallback&&(element=fallback.element,metrics=fallback.metrics,ancestorDistance=fallback.distance)}if(!metrics.usable&&containerPolicy==="nearest"){let candidate=element.parentElement;for(;candidate;){ancestorDistance+=1;let candidateMetrics=scrollMetrics(candidate);if(candidateMetrics?.usable){element=candidate,metrics=candidateMetrics;break}candidate=candidate.parentElement}}if(!metrics.usable&&!metrics.isRootScroller)return{error:"Element is not scrollable: "+targetLabel+(containerPolicy==="nearest"?" (no scrollable ancestor found)":"")};let targetTop;switch(direction){case"top":targetTop=0;break;case"bottom":targetTop=metrics.maxScrollTop;break;case"up":targetTop=Math.max(0,metrics.scrollTop-Math.abs(distance));break;default:targetTop=Math.min(metrics.maxScrollTop,metrics.scrollTop+Math.abs(distance));break}if(typeof element.scrollTo=="function")try{element.scrollTo({top:targetTop,left:Number(element.scrollLeft)||0,behavior:"instant"})}catch{element.scrollTop=targetTop}else element.scrollTop=targetTop;let actualScrollTop=Number(element.scrollTop);return!metrics.isRootScroller&&targetTop!==metrics.scrollTop&&actualScrollTop===metrics.scrollTop?{error:"Element is not scrollable: "+targetLabel}:{scrollY:Math.round(actualScrollTop),scrollHeight:metrics.scrollHeight,clientHeight:metrics.clientHeight,maxScrollY:Math.round(metrics.maxScrollTop),scrollYBefore:Math.round(metrics.scrollTop),scrollYAfter:Math.round(actualScrollTop),moved:actualScrollTop!==metrics.scrollTop,atTop:actualScrollTop<=0,atBottom:actualScrollTop>=metrics.maxScrollTop,target:targetLabel,resolvedContainer:targetDocument&&element===targetDocument.body&&element!==startingElement?"document-body":targetDocument&&element!==startingElement?"document-descendant":element===startingElement?"self":"nearest-scrollable-ancestor",ancestorDistance,...targetDocument&&element!==startingElement?{containerSelector:selectorFor(element)}:{}}}var SCROLL_ELEMENT_IN_PAGE_SOURCE,init_domScrolling=__esm({"../browser-core/dist/domScrolling.js"(){"use strict";init_domSelectors();SCROLL_ELEMENT_IN_PAGE_SOURCE=scrollElementInPage.toString()}});function inspectElementsInPage(selector,filter,styles,maxResults,invalidSelectorHint,includeOuterHTML=!1){let context=this?.nodeType===3?this.parentElement:this,documentRef=context?.nodeType===9?context:context?.ownerDocument;if(!documentRef)return{error:"page_inspect cannot resolve the target document"};let scanLimit=1e4,candidates;if(context?.nodeType===9){let effectiveSelector=selector??"*";try{candidates=Array.from(documentRef.querySelectorAll(effectiveSelector))}catch(error2){return{error:'Invalid CSS selector "'+effectiveSelector+'": '+(error2 instanceof Error?error2.message:String(error2))+". "+invalidSelectorHint}}}else if(context?.nodeType===1&&context.isConnected!==!1)candidates=[context];else return{error:"page_inspect target is detached from the document"};let candidateCount=candidates.length,scanTruncated=filter!=="all"&&candidateCount>scanLimit;candidates=filter==="all"?candidates.slice(0,maxResults):scanTruncated?candidates.slice(0,scanLimit):candidates;let windowRef=documentRef.defaultView,viewportWidth=Number(windowRef?.innerWidth)||0,viewportHeight=Number(windowRef?.innerHeight)||0;function round(value){return Math.round(value*1e3)/1e3}function controlState(element){let state={};for(let name of["checked","selected","pressed","expanded","disabled","readonly"]){let value=element.getAttribute?.("aria-"+name);(value==="true"||value==="false"||value==="mixed"&&(name==="checked"||name==="pressed"))&&(state[name]={value:value==="mixed"?"mixed":value==="true",source:"aria"})}let tag=String(element.tagName||"").toLowerCase(),type=String(element.type||"").toLowerCase();if(tag==="input"&&(type==="checkbox"||type==="radio")&&(state.checked={value:type==="checkbox"&&element.indeterminate?"mixed":!!element.checked,source:"native"}),tag==="option"&&(state.selected={value:!!element.selected,source:"native"}),["button","input","select","textarea","option","optgroup","fieldset"].includes(tag)){let disabled=element.matches?.(":disabled")??!!element.disabled;(disabled||!state.disabled)&&(state.disabled={value:disabled,source:"native"})}return(tag==="textarea"||tag==="input"&&["text","search","tel","url","email","password","date","month","week","time","datetime-local","number"].includes(type))&&(element.readOnly||!state.readonly)&&(state.readonly={value:!!element.readOnly,source:"native"}),state}function escapeCss(value){return windowRef?.CSS&&typeof windowRef.CSS.escape=="function"?windowRef.CSS.escape(value):value.replace(/[^a-zA-Z0-9_-]/g,character=>"\\"+character)}function selectorFor(element){if(element.id){let idSelector="#"+escapeCss(String(element.id));try{if(documentRef.querySelectorAll(idSelector).length===1)return idSelector}catch{}}let path8=[],cursor=element;for(;cursor&&cursor.nodeType===1&&path8.length<8;){let tag=String(cursor.tagName||"").toLowerCase();if(!tag)break;let parent=cursor.parentElement;if(!parent){path8.unshift(tag);break}let siblings=Array.from(parent.children).filter(sibling2=>sibling2.tagName===cursor.tagName),index=siblings.indexOf(cursor)+1;if(path8.unshift(siblings.length>1?tag+":nth-of-type("+index+")":tag),cursor=parent,cursor===documentRef.documentElement){path8.unshift("html");break}}return path8.join(" > ")}function readStyle(style,property){let cssValue=style.getPropertyValue?.(property);if(cssValue)return String(cssValue);let camelName=property.replace(/-([a-z])/g,(_match,letter)=>letter.toUpperCase());return String(style[camelName]??"")}function isScrollable(element,style){let canScrollX=Number(element.scrollWidth)>Number(element.clientWidth)&&!["visible","clip"].includes(String(style.overflowX)),canScrollY=Number(element.scrollHeight)>Number(element.clientHeight)&&!["visible","clip"].includes(String(style.overflowY));return canScrollX||canScrollY}function nearestScrollContainer(element){let candidate=element,ancestorDistance=0;for(;candidate&&candidate.nodeType===1;){let style=windowRef.getComputedStyle(candidate);if(isScrollable(candidate,style))return{selector:selectorFor(candidate),tag:String(candidate.tagName||"").toLowerCase(),ancestorDistance,scrollWidth:Number(candidate.scrollWidth)||0,scrollHeight:Number(candidate.scrollHeight)||0,clientWidth:Number(candidate.clientWidth)||0,clientHeight:Number(candidate.clientHeight)||0,scrollLeft:Number(candidate.scrollLeft)||0,scrollTop:Number(candidate.scrollTop)||0,overflowX:String(style.overflowX||""),overflowY:String(style.overflowY||"")};candidate=candidate.parentElement,ancestorDistance+=1}}function hitTargetInfo(element,rect,visible,style){let left=Math.max(0,Number(rect.left)||0),right=Math.min(viewportWidth,Number(rect.right)||0),top=Math.max(0,Number(rect.top)||0),bottom=Math.min(viewportHeight,Number(rect.bottom)||0),x=round(left+Math.max(0,right-left)/2),y=round(top+Math.max(0,bottom-top)/2),hit=null;try{hit=visible?documentRef.elementFromPoint?.(x,y)??null:null}catch{}let topmost=!!hit&&(hit===element||element.contains?.(hit)),target=hit?{selector:selectorFor(hit),tag:String(hit.tagName||"").toLowerCase(),text:String(hit.innerText??hit.textContent??"").trim().replace(/\s+/g," ").slice(0,120)}:void 0;return{point:{x,y},topmost,receivesPointerEvents:visible&&style.pointerEvents!=="none"&&topmost,...target?{target}:{},...!topmost&&target?{occludedBy:target}:{}}}let matches=[],count=filter==="all"?candidateCount:0;for(let element of candidates){let style=windowRef.getComputedStyle(element),scrollWidth=Number(element.scrollWidth)||0,scrollHeight=Number(element.scrollHeight)||0,clientWidth=Number(element.clientWidth)||0,clientHeight=Number(element.clientHeight)||0,horizontalOverflow=Math.max(0,scrollWidth-clientWidth),verticalOverflow=Math.max(0,scrollHeight-clientHeight),scrollable=isScrollable(element,style);if(!(filter==="all"||filter==="overflowing"&&(horizontalOverflow>0||verticalOverflow>0)||filter==="horizontal-overflow"&&horizontalOverflow>0||filter==="vertical-overflow"&&verticalOverflow>0||filter==="scrollable"&&scrollable)||(filter!=="all"&&(count+=1),matches.length>=maxResults))continue;let rect=element.getBoundingClientRect(),opacity=Number(style.opacity),visible=rect.width>0&&rect.height>0&&style.display!=="none"&&style.visibility!=="hidden"&&style.visibility!=="collapse"&&(!Number.isFinite(opacity)||opacity>0)&&rect.right>0&&rect.bottom>0&&rect.left<viewportWidth&&rect.top<viewportHeight,computedStyle={};for(let property of styles)computedStyle[property]=readStyle(style,property);let scrollContainer=nearestScrollContainer(element),hitTest=hitTargetInfo(element,rect,visible,style),state=controlState(element);matches.push({selector:selectorFor(element),tag:String(element.tagName||"").toLowerCase(),text:String(element.innerText??element.textContent??"").trim().replace(/\s+/g," ").slice(0,240),visible,hitTest,...Object.keys(state).length?{state}:{},boundingBox:{x:round(rect.x),y:round(rect.y),width:round(rect.width),height:round(rect.height),top:round(rect.top),right:round(rect.right),bottom:round(rect.bottom),left:round(rect.left)},computedStyle,scroll:{scrollWidth,scrollHeight,clientWidth,clientHeight,overflowX:String(style.overflowX||""),overflowY:String(style.overflowY||""),horizontalOverflow,verticalOverflow},...scrollContainer?{scrollContainer}:{},...includeOuterHTML?{outerHTML:String(element.outerHTML??"").slice(0,3e3)}:{}})}return{...selector!==void 0?{selector}:{},filter,candidateCount,count,matches,truncated:scanTruncated||count>matches.length,...scanTruncated?{scanTruncated:!0}:{}}}var INSPECT_ELEMENTS_IN_PAGE_SOURCE,init_domInspection=__esm({"../browser-core/dist/domInspection.js"(){"use strict";init_domSelectors();INSPECT_ELEMENTS_IN_PAGE_SOURCE=inspectElementsInPage.toString()}});var init_domSnapshot=__esm({"../browser-core/dist/domSnapshot.js"(){"use strict"}});var init_deviceEmulation=__esm({"../browser-core/dist/deviceEmulation.js"(){"use strict"}});var init_debuggerTarget=__esm({"../browser-core/dist/debuggerTarget.js"(){"use strict"}});var SHELL_BODY,MAX_DOCUMENT_BYTES,init_rootWebViewNavigation=__esm({"../browser-core/dist/rootWebViewNavigation.js"(){"use strict";SHELL_BODY=btoa('<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"></head><body></body></html>'),MAX_DOCUMENT_BYTES=16*1024*1024}});var init_axTextMatch=__esm({"../browser-core/dist/axTextMatch.js"(){"use strict"}});var init_domClicking=__esm({"../browser-core/dist/domClicking.js"(){"use strict"}});function dragBetweenPointsInPage(from,points,pointerType){let target=document.elementFromPoint(from.x,from.y);if(!target)return{dragged:!1,steps:0,error:`No element found at drag start point (${from.x}, ${from.y})`};if(points.length===0)return{dragged:!1,steps:0,error:"Drag path must contain at least one point"};let view=target.ownerDocument.defaultView??window,realm=view,pointerId=1,pointerInit=(point,buttons,pressure)=>({bubbles:!0,cancelable:!0,composed:!0,view,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,button:0,buttons,pointerId,pointerType,isPrimary:!0,pressure,width:1,height:1}),dispatchPointer=(type,point,buttons,pressure)=>typeof realm.PointerEvent!="function"?!1:(target.dispatchEvent(new realm.PointerEvent(type,pointerInit(point,buttons,pressure))),!0),dispatchMouse=(type,point,buttons)=>typeof realm.MouseEvent!="function"?!1:(target.dispatchEvent(new realm.MouseEvent(type,{bubbles:!0,cancelable:!0,composed:!0,view,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,button:0,buttons})),!0),createTouch=point=>{let init={identifier:pointerId,target,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,pageX:point.x+view.scrollX,pageY:point.y+view.scrollY,radiusX:1,radiusY:1,rotationAngle:0,force:.5};return typeof realm.Touch=="function"?new realm.Touch(init):init},dispatchTouch=(type,point)=>{if(typeof realm.TouchEvent!="function")return!1;let touch=createTouch(point),activeTouches=type==="touchend"?[]:[touch];return target.dispatchEvent(new realm.TouchEvent(type,{bubbles:!0,cancelable:!0,composed:!0,touches:activeTouches,targetTouches:activeTouches,changedTouches:[touch]})),!0},dispatched=dispatchPointer("pointerdown",from,1,.5);dispatched=pointerType==="touch"?dispatchTouch("touchstart",from)||dispatched:dispatchMouse("mousedown",from,1)||dispatched;for(let point of points)dispatched=dispatchPointer("pointermove",point,1,.5)||dispatched,dispatched=pointerType==="touch"?dispatchTouch("touchmove",point)||dispatched:dispatchMouse("mousemove",point,1)||dispatched;let end=points[points.length-1];return dispatched=pointerType==="touch"?dispatchTouch("touchend",end)||dispatched:dispatchMouse("mouseup",end,0)||dispatched,dispatched=dispatchPointer("pointerup",end,0,0)||dispatched,dispatched?{dragged:!0,steps:points.length}:{dragged:!1,steps:0,error:"This page does not support synthetic drag events"}}var DRAG_BETWEEN_POINTS_IN_PAGE_SOURCE,init_pageDragging=__esm({"../browser-core/dist/pageDragging.js"(){"use strict";DRAG_BETWEEN_POINTS_IN_PAGE_SOURCE=dragBetweenPointsInPage.toString()}});var PAGE_PRESS_KEY_DESCRIPTORS,init_pagePressing=__esm({"../browser-core/dist/pagePressing.js"(){"use strict";PAGE_PRESS_KEY_DESCRIPTORS=Object.freeze({Enter:{key:"Enter",code:"Enter",keyCode:13,text:"\r"},Tab:{key:"Tab",code:"Tab",keyCode:9},Escape:{key:"Escape",code:"Escape",keyCode:27},Backspace:{key:"Backspace",code:"Backspace",keyCode:8},Delete:{key:"Delete",code:"Delete",keyCode:46},ArrowUp:{key:"ArrowUp",code:"ArrowUp",keyCode:38},ArrowDown:{key:"ArrowDown",code:"ArrowDown",keyCode:40},ArrowLeft:{key:"ArrowLeft",code:"ArrowLeft",keyCode:37},ArrowRight:{key:"ArrowRight",code:"ArrowRight",keyCode:39},Home:{key:"Home",code:"Home",keyCode:36},End:{key:"End",code:"End",keyCode:35},PageUp:{key:"PageUp",code:"PageUp",keyCode:33},PageDown:{key:"PageDown",code:"PageDown",keyCode:34},Space:{key:" ",code:"Space",keyCode:32,text:" "}})}});var init_axSnapshot=__esm({"../browser-core/dist/axSnapshot.js"(){"use strict"}});var init_pageObserver=__esm({"../browser-core/dist/pageObserver.js"(){"use strict"}});var init_navigationTracker=__esm({"../browser-core/dist/navigationTracker.js"(){"use strict"}});function resolvePageEvalExpression(params){if(typeof params.expression!="string"||!params.expression.trim())throw new Error("Invalid expression");if(params.args===void 0)return params.expression;if(!Array.isArray(params.args))throw new Error("page_eval args must be an array");return`(${params.expression})(...JSON.parse(${JSON.stringify(JSON.stringify(params.args))}))`}function validatePageUserScriptParams(params){if(!Number.isSafeInteger(params?.tabId)||params.tabId<0)throw new Error("Invalid target tab");if(typeof params.worldId!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(params.worldId))throw new Error("Invalid user script worldId");if(typeof params.code!="string"||!params.code.trim()||params.code.length>256*1024)throw new Error("User script code must be non-empty and within 256 KiB characters")}function actionRequiresTabId(action){return typeof action=="string"&&TAB_ID_REQUIRED_ACTION_SET.has(action)}function validateRequiredActionTabId(action,data2){let cookieAction=action==="get_cookie"||action==="set_cookie";if(!actionRequiresTabId(action)&&!cookieAction)return;let input=data2&&typeof data2=="object"&&!Array.isArray(data2)?data2:void 0,tabId=input?.tabId;if(cookieAction&&tabId===void 0){if(action==="set_cookie"&&input?.reload===!0)throw new Error("set_cookie: reload requires tabId");if(typeof input?.url!="string"||!input.url.trim())throw new Error(`${action}: specify url or tabId`);return}if(typeof tabId!="number"||!Number.isSafeInteger(tabId)||tabId<0)throw new Error(`${action} requires a numeric tabId. Call tab_open or tab_list to obtain a tabId.`)}function isBrowserCapabilityAction(value){return typeof value=="string"&&Object.hasOwn(BROWSER_CAPABILITY_ACTIONS,value)}var BROWSER_DEVICE_PRESET_NAMES,APP_PROFILE_NAMES,TAB_ID_REQUIRED_ACTIONS,TAB_ID_REQUIRED_ACTION_SET,PAGE_ACT_ACTIONS,EXTENSION_BROWSER_ACTIONS,BROWSER_CAPABILITY_ACTIONS,init_browserActionProtocol=__esm({"../browser-core/dist/browserActionProtocol.js"(){"use strict";BROWSER_DEVICE_PRESET_NAMES=["iphone-duo-folded","iphone-duo-unfolded","iphone-17-pro","iphone-17e","pixel-11","ipad-mini-a17-pro","galaxy-s26","pura-x-max","iphone-15-pro","iphone-se","pixel-8","ipad-mini","galaxy-s23"],APP_PROFILE_NAMES=["fliggy","taobao","wechat","alipay"];TAB_ID_REQUIRED_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","set_mock","get_mocks","page_screenshot","tab_close","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_inspect","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_download","page_frames","set_device_emulation","set_app_profile","set_timezone","run_actions"],TAB_ID_REQUIRED_ACTION_SET=new Set(TAB_ID_REQUIRED_ACTIONS);PAGE_ACT_ACTIONS=["page_click","page_drag","page_type","page_hover","page_scroll","page_press","page_upload","page_eval"],EXTENSION_BROWSER_ACTIONS={tab_checkpoint:!0,capture_checkpoint:!0,get_requests:!0,get_logs:!0,get_events:!0,set_mock:!0,get_mocks:!0,set_rule:!0,get_rules:!0,send_request:!0,send_mtop_request:!0,browser_release:!0,page_screenshot:!0,tab_open:!0,tab_close:!0,tab_list:!0,tab_group:!0,page_click:!0,page_drag:!0,page_type:!0,page_scroll:!0,page_hover:!0,page_eval:!0,page_runtime:!0,page_inspect:!0,page_snapshot:!0,page_press:!0,page_wait:!0,page_navigate:!0,page_upload:!0,page_frames:!0,set_device_emulation:!0,set_app_profile:!0,set_timezone:!0,get_cookie:!0,set_cookie:!0,request_domain_permission:!0,run_actions:!0},BROWSER_CAPABILITY_ACTIONS={...EXTENSION_BROWSER_ACTIONS,page_download:!0}}});var init_pageAct=__esm({"../browser-core/dist/pageAct.js"(){"use strict";init_pageObserver();init_browserActionProtocol()}});var init_backendNodeRefs=__esm({"../browser-core/dist/backendNodeRefs.js"(){"use strict"}});var init_pageEffectRefs=__esm({"../browser-core/dist/pageEffectRefs.js"(){"use strict"}});var init_pageWait=__esm({"../browser-core/dist/pageWait.js"(){"use strict";init_domSelectors()}});var init_pageNavigation=__esm({"../browser-core/dist/pageNavigation.js"(){"use strict"}});var init_tabMatching=__esm({"../browser-core/dist/tabMatching.js"(){"use strict"}});var AGENT_CHAT_MAX_IMAGE_BYTES,AGENT_CHAT_MAX_TOTAL_IMAGE_BYTES,init_agentChat=__esm({"../browser-core/dist/agentChat.js"(){"use strict";AGENT_CHAT_MAX_IMAGE_BYTES=10*1024*1024,AGENT_CHAT_MAX_TOTAL_IMAGE_BYTES=20*1024*1024}});var init_agentSkills=__esm({"../browser-core/dist/agentSkills.js"(){"use strict"}});var init_agentServiceProtocol=__esm({"../browser-core/dist/agentServiceProtocol.js"(){"use strict"}});var init_toolbox=__esm({"../browser-core/dist/toolbox.js"(){"use strict"}});function parseToolboxIcon(value){if(typeof value!="string")return;let icon=value.trim();if(!icon||icon.length>32*1024)return;if(/^[a-z][a-z0-9-]{0,39}$/.test(icon))return{kind:"name",name:icon};if(/^(?:<\?xml\s[^>]*\?>\s*)?<svg\b[^>]*(?:\/>|>[\s\S]*<\/svg\s*>)$/i.test(icon)){let svg=/<svg\b[^>]*\sxmlns\s*=/i.test(icon)?icon:icon.replace(/<svg\b/i,'<svg xmlns="http://www.w3.org/2000/svg"');try{return{kind:"image",src:`data:image/svg+xml,${encodeURIComponent(svg)}`,.../\bcurrentColor\b/i.test(svg)?{monochrome:!0}:{}}}catch{return}}let dataHeader=/^data:image\/(?:svg\+xml|png|jpeg|gif|webp|avif)(?:;charset=utf-8|;utf8)?(?:;base64)?,/i.exec(icon);if(dataHeader&&icon.length>dataHeader[0].length)return{kind:"image",src:icon};try{let url=new URL(icon);if(["http:","https:"].includes(url.protocol)&&!url.username&&!url.password)return{kind:"image",src:url.href}}catch{}}var init_toolboxIcon=__esm({"../browser-core/dist/toolboxIcon.js"(){"use strict"}});var init_pluginExecution=__esm({"../browser-core/dist/pluginExecution.js"(){"use strict"}});function isPluginTaskActive(state){return state==="queued"||state==="running"||state==="cancelling"}function isPluginTaskId(value){return typeof value=="string"&&/^pt_[0-9a-f-]{36}_[0-9a-f-]{36}$/i.test(value)}var init_pluginTasks=__esm({"../browser-core/dist/pluginTasks.js"(){"use strict"}});function isPluginPageInvalidation(error2){let value=error2,codes=["PLUGIN_PAGE_INVALIDATED","PLUGIN_PAGE_NOT_FOUND","PLUGIN_PAGE_TARGET_CHANGED","DOMAIN_PERMISSION_REQUIRED"],message=typeof value?.message=="string"?value.message:"";return codes.includes(String(value?.code))||codes.some(code=>message.startsWith(`${code}:`))}function isPluginPageUnavailable(error2){return error2?.code==="PLUGIN_PAGE_UNAVAILABLE"}function pluginPageUnavailable(error2){return Object.assign(new Error("Plugin page host is temporarily unavailable",{cause:error2}),{code:"PLUGIN_PAGE_UNAVAILABLE"})}function isPluginPageMatchPattern(value){return typeof value=="string"&&value.length<=2048&&pattern.test(value)}function matchesPluginPageURL(matches,value){let url;try{url=new URL(value)}catch{return!1}return["http:","https:"].includes(url.protocol)?matches.some(item=>{let match=item.match(pattern);if(!match||match[1]!=="*"&&match[1].toLowerCase()+":"!==url.protocol)return!1;let host=match[2].toLowerCase();if(host!=="*"&&host!==url.hostname&&!(host.startsWith("*.")&&(url.hostname===host.slice(2)||url.hostname.endsWith(host.slice(1))))||match[3]&&match[3].slice(1)!==(url.port||(url.protocol==="https:"?"443":"80")))return!1;let expression="^"+match[4].split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$";return new RegExp(expression).test(url.pathname+url.search)}):!1}function isPluginPageInstanceId(value){return typeof value=="string"&&/^pi_[0-9a-f-]{36}$/i.test(value)}var pattern,init_pluginPages=__esm({"../browser-core/dist/pluginPages.js"(){"use strict";pattern=/^(https?|\*):\/\/(\*|\*\.[a-z0-9.-]+|[a-z0-9.-]+|localhost)(:\d+)?(\/[^#]*)$/i}});var init_pluginPageRuntime=__esm({"../browser-core/dist/pluginPageRuntime.js"(){"use strict"}});var init_pluginPageHost=__esm({"../browser-core/dist/pluginPageHost.js"(){"use strict";init_pluginPageRuntime();init_pluginPages()}});var init_runActions=__esm({"../browser-core/dist/runActions.js"(){"use strict";init_browserActionProtocol();init_pageAct()}});var init_sendRequestFiles=__esm({"../browser-core/dist/sendRequestFiles.js"(){"use strict";init_browserActionProtocol()}});var init_sendRequestHeaders=__esm({"../browser-core/dist/sendRequestHeaders.js"(){"use strict";init_sendRequestFiles()}});var init_cookie=__esm({"../browser-core/dist/cookie.js"(){"use strict"}});var init_controlledFavicon=__esm({"../browser-core/dist/controlledFavicon.js"(){"use strict"}});var init_sseParser=__esm({"../browser-core/dist/sseParser.js"(){"use strict"}});var init_mockResponse=__esm({"../browser-core/dist/mockResponse.js"(){"use strict"}});var init_pluginState=__esm({"../browser-core/dist/pluginState.js"(){"use strict"}});var init_pluginModels=__esm({"../browser-core/dist/pluginModels.js"(){"use strict"}});var init_pluginRecovery=__esm({"../browser-core/dist/pluginRecovery.js"(){"use strict"}});var init_pluginDiagnostics=__esm({"../browser-core/dist/pluginDiagnostics.js"(){"use strict"}});var init_rootWebViewDocument=__esm({"../browser-core/dist/rootWebViewDocument.js"(){"use strict"}});var init_extensionServiceProtocol=__esm({"../browser-core/dist/extensionServiceProtocol.js"(){"use strict";init_agentServiceProtocol();init_toolbox()}});var init_requestStreamCapture=__esm({"../browser-core/dist/requestStreamCapture.js"(){"use strict"}});var init_responseText=__esm({"../browser-core/dist/responseText.js"(){"use strict"}});var init_consumeSseResponse=__esm({"../browser-core/dist/consumeSseResponse.js"(){"use strict";init_sseParser()}});var init_queryString=__esm({"../browser-core/dist/queryString.js"(){"use strict"}});var init_extensionVersion=__esm({"../browser-core/dist/extensionVersion.js"(){"use strict"}});var init_nativeHostNames=__esm({"../browser-core/dist/nativeHostNames.js"(){"use strict"}});var init_dist2=__esm({"../browser-core/dist/index.js"(){"use strict";init_appProfileDefinition();init_types();init_eventFilters();init_requestSerializer();init_boundedRequestBuffer();init_proxyPermissions();init_domTyping();init_domSelectors();init_domScrolling();init_domInspection();init_domSnapshot();init_deviceEmulation();init_debuggerTarget();init_rootWebViewNavigation();init_axTextMatch();init_domClicking();init_pageDragging();init_pagePressing();init_axSnapshot();init_pageObserver();init_navigationTracker();init_pageAct();init_backendNodeRefs();init_pageEffectRefs();init_pageWait();init_pageNavigation();init_tabMatching();init_agentChat();init_agentSkills();init_agentServiceProtocol();init_toolbox();init_toolboxIcon();init_pluginExecution();init_pluginTasks();init_pluginPages();init_pluginPageRuntime();init_pluginPageHost();init_browserActionProtocol();init_runActions();init_sendRequestFiles();init_sendRequestHeaders();init_cookie();init_controlledFavicon();init_capture();init_sseParser();init_mockResponse();init_pluginState();init_pluginModels();init_pluginRecovery();init_pluginDiagnostics();init_rootWebViewDocument();init_extensionServiceProtocol();init_requestStreamCapture();init_responseText();init_consumeSseResponse();init_queryString();init_extensionVersion();init_nativeHostNames()}});var APP_PROFILE_NAME_LIST,DEVICE_PRESET_TYPE,PAGE_DIAGNOSTICS_PARAM,PAGE_OBSERVE_PARAM,PAGE_ACTION_RESULT,COMMANDS,COMMAND_MAP,init_commands=__esm({"../client/src/commands.ts"(){"use strict";init_dist2();APP_PROFILE_NAME_LIST=APP_PROFILE_NAMES.join("/"),DEVICE_PRESET_TYPE=BROWSER_DEVICE_PRESET_NAMES.map(name=>JSON.stringify(name)).join(" | "),PAGE_DIAGNOSTICS_PARAM={name:"diagnostics",type:"object | boolean",description:"默认关闭;传 true 返回动作期间新增的 error logs/业务 requests,或传对象自定义通道与过滤",details:["logs: boolean | { level, limit, filter };true 默认采集 error 日志","requests: boolean | { count, filter, source, includeBody, includeHeaders, maxBodySize, fields, keysOnly }","events: boolean | { source, event_type, filter, limit, includeRaw };埋点需显式开启","各通道过滤字段同 get_logs / get_requests / get_events;observe=false 时仍返回诊断增量,但不等待 DOM/导航稳定"]},PAGE_OBSERVE_PARAM={name:"observe",type:"object | false",description:"默认开启 DOM/导航观察;传 false 关闭,不影响显式请求的 diagnostics",details:["quietMs: number,DOM 变化后的稳定窗口,默认 100ms","firstChangeTimeoutMs: number,无 DOM 变化时的观察窗口,默认 500ms","timeoutMs: number,DOM 观察阶段最大时间,默认 3000ms","navigationGraceMs: number,低信息量点击/按键的导航宽限,默认 1000ms;相关网络活动可延长宽限","navigationTimeoutMs: number,导航就绪最大等待时间,默认 15000ms","networkIdleMs: number,文档完成且相关请求归零后的静默时间,默认 500ms","contentReadyAfterMs: number,结构稳定兜底保护期,默认 min(5000, navigationTimeoutMs / 2),并限制在导航超时前"]},PAGE_ACTION_RESULT=["默认返回 { action, observation };action.success 只表示动作成功,业务效果需结合 observation 和目标状态判断。","observe=false 且未开启 diagnostics 时返回裸动作结果(如 { clicked: true }),没有 action/observation;开启 diagnostics 时返回 { action, diagnostics }。","包装结果中的 action.stage=precondition 表示未派发,省略 observation/diagnostics;dispatch-uncertain 表示可能已派发,先查看 action.attempt 与可用观察或最小快照核验,避免重复提交。失败以退出码 1 结束。","observation.effects 返回通知、控件和焦点增量,可直接复用 node.ref/selector;changed=true 且 effects 为空不表示失败。","effects.texts 按需返回普通可见文本的 selector/text,不代表可点击控件或业务成功;超限或覆盖不完整时仍提示补快照。","fullSnapshotRecommended/snapshotReasons 提示是否补充快照;openedTabs 返回可继续操作的 tabId 和 ready。navigation 模式的 ready 表示新页面就绪。","显式开启的诊断通道在 diagnostics 中返回动作期间增量,与 observe 独立。"],COMMANDS=[{name:"browser_control",description:"把控制会话交给用户;用户在 Mearl 浏览器管理页交还后重新观察页面",params:[{name:"operation",type:'"handoff" | "resume"',required:!0,description:"交给用户操作;resume 仅在用户明确交还后使用"},{name:"tabId",type:"number",description:"可选的目标页面"},{name:"reason",type:"string",description:"用户需要处理的事项"}],notes:["必须携带 --session;接管停止后续派发,已经发出的操作可能仍然生效。"]},{name:"page_download",description:"先监听再点击,等待下载完成并创建浏览器文件产物",outputFlag:!0,params:[{name:"tabId",type:"number",required:!0,description:"下载来源页面"},{name:"trigger",type:"object",required:!0,description:"page_click 参数,不含 tabId"},{name:"url",type:"string",description:"预期下载 URL;扩展无法通过 referrer 归属时需显式指定"},{name:"timeout",type:"number",description:"下载等待毫秒,默认 30000,范围 1000–300000"}],notes:["--output 把文件分块保存到调用方机器;未指定时返回 artifactId,可供 page_upload 复用。","共享 CDP 浏览器保持原下载目录;Chrome 未返回文件路径时明确报错。超时不能直接重复点击。"]},{name:"tab_checkpoint",description:"为目标标签页建立日志、请求和埋点增量边界",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_open 获取"}],examples:[`tab_checkpoint --payload '{"tabId":12345}'`]},{name:"get_requests",description:"获取最近的网络请求(mtop 或普通 xhr/fetch)",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"count",type:"number",description:"返回条数,默认 10"},{name:"source",type:'"mtop" | "requests" | "all"',description:"数据来源,不填时默认 mtop;all 返回全部业务请求"},{name:"filter",type:"string",description:"按 URL 或 API 名称过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的请求"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 或同类查询 cursor 之后的请求"},{name:"includeBody",type:"boolean",description:"是否包含请求/响应体;指定 fields 时默认 false,否则默认 true"},{name:"includeHeaders",type:"boolean",description:"是否包含请求/响应头,默认 false"},{name:"maxBodySize",type:"number",description:"单个请求/响应体最大字符数,默认 50000"},{name:"fields",type:"string[]",description:"从响应体提取指定字段路径,最多 100 个"},{name:"keysOnly",type:"boolean",description:"只返回数据结构,不返回叶子值"}],notes:["流式请求开始后即进入缓冲区;页面及 App 桥代发的 MTop SSE 都归入 mtop。无法归属当前页面 target 的 Service Worker 请求不在采集范围内。"],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。","省略正文时不返回 postData / responseBody 字段;指定 fields 后需要同时读取全文时显式传 includeBody:true。","isPending 标记未完成请求;SSE 的 responseBody 保存按序到达的 event/data/timestamp/duration 分片。敏感请求头返回脱敏值。"],examples:[`get_requests --payload '{"tabId":12345,"count":5}'`,`get_requests --payload '{"tabId":12345,"source":"mtop","filter":"cart"}'`]},{name:"get_logs",description:"获取浏览器控制台日志",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"limit",type:"number",description:"返回最新 N 条,默认 100"},{name:"level",type:"string",description:"按日志级别过滤:log/info/warn/error/all"},{name:"filter",type:"string",description:"按内容过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的日志"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 或同类查询 cursor 之后的日志"}],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。"],examples:[`get_logs --payload '{"tabId":12345,"limit":10,"level":"error"}'`]},{name:"get_events",description:"获取 RUM/aplus/ARMS 埋点事件",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"source",type:'"rum" | "aplus" | "arms" | "all"',description:"数据来源,默认 all"},{name:"event_type",type:"string",description:"按事件类型过滤,支持正则,如 CLK/PV"},{name:"filter",type:"string",description:"按 name 或 url 过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的事件"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 之后的事件"},{name:"limit",type:"number",description:"返回条数,默认 20"},{name:"includeRaw",type:"boolean",description:"返回完整 URL、_raw 和 _context;默认 false"}],notes:["tab_open 新页从首屏采集;既有页面首次查询才启用采集,需要刷新或重新触发埋点。同批事件不会被 limit 拆开。"],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。","captureStatus 为 armed/active/inactive;空结果附 hint 时按提示刷新或触发。默认去除 tracking URL query 与 _raw/_context,includeRaw=true 时保留。"],examples:[`get_events --payload '{"tabId":12345,"source":"aplus","event_type":"CLK","limit":10}'`,`get_events --payload '{"tabId":12345,"filter":"order","includeRaw":true,"limit":1}'`,`get_events --payload '{"tabId":12345,"source":"all","limit":20}'`]},{name:"set_mock",description:"设置 API mock 数据",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"apiName",type:"string",required:!0,description:"API 名称或正则表达式"},{name:"mockData",type:"object",description:"完整 mock 响应数据(与 fields 二选一)"},{name:"fields",type:"array",description:"按字段路径修改真实响应(与 mockData 二选一)"},{name:"enabled",type:"boolean",description:"是否启用,默认 true。false 时恢复真实数据"},{name:"duration",type:"number",description:"完整响应时长(毫秒):mock 的总耗时,绕过真实服务器精确控制"},{name:"conditions",type:"object",description:"请求 query/body 字段子集匹配;$index 从 0 开始指定调用顺序"}],notes:["启用时至少提供 mockData 或非空 fields;非空 fields 优先。fields 每项 { path: string, value: any },path 支持点号和数组索引。","相同 apiName 的多条无条件 Mock 会覆盖;conditions 子集匹配 query/body(含 data 内层),不同条件可共存;$index 从 0 起控制调用顺序,不参与字段匹配。","大字段可用顶层 @<绝对路径> 文件引用或 --payload-file;文件展开后仍受 Native Messaging 单条消息大小限制。"],examples:[`set_mock --payload '{"tabId":12345,"apiName":"mtop.cart.query","mockData":{"ret":["SUCCESS::调用成功"]}}'`,"set_mock --payload-file ./mock-data.json"]},{name:"get_mocks",description:"查看当前生效的 mock 列表",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"apiName",type:"string",description:"按 API 名称或正则表达式过滤"}],examples:[`get_mocks --payload '{"tabId":12345}'`]},{name:"set_rule",description:"添加浏览器请求规则;enabled=false 且传 ruleId 时彻底删除规则",params:[{name:"ruleId",type:"number",description:"删除时必填,从 get_rules 获取"},{name:"enabled",type:"boolean",description:"省略时添加;false 时按 ruleId 删除"},{name:"actionType",type:'"redirect" | "block" | "allow" | "upgradeScheme" | "modifyHeaders"',description:"添加时必填,规则动作"},{name:"filter",type:"string",description:"添加时必填,URL 过滤表达式"},{name:"redirectUrl",type:"string",description:"redirect 动作的目标 URL"},{name:"requestHeaders",type:"array",description:"modifyHeaders 动作的请求头修改列表",details:['每项 { header: string, operation: "set" | "append" | "remove", value?: string };set/append 需 value']},{name:"responseHeaders",type:"array",description:"modifyHeaders 动作的响应头修改列表",details:['每项 { header: string, operation: "set" | "append" | "remove", value?: string };set/append 需 value']},{name:"initiatorDomains",type:"string",description:"发起方域名过滤"},{name:"resourceTypes",type:"string[]",description:"资源类型过滤"},{name:"priority",type:"number",description:"规则优先级"},{name:"description",type:"string",description:"规则说明"}],notes:["扩展模式规则持久化;CDP 仅支持会话级 modifyHeaders 请求头 set,不支持响应头、initiatorDomains 或其他动作。Provider 是否支持以其能力声明为准。","扩展模式会检查规则请求 URL 和显式来源域名的访问权限;缺失时仍保存规则,返回 warnings 和 missingOrigins,不自动弹窗。可在请求规则页面授权,或按提示调用 request_domain_permission。复杂 URL 表达式无法完整推断域名时会提示手动检查。"],examples:[`set_rule --payload '{"actionType":"block","filter":"^https://example\\\\.com/ads/.*"}'`,`set_rule --payload '{"ruleId":42,"enabled":false}'`]},{name:"get_rules",description:"查看当前模式的请求规则;扩展模式包含 Options 面板配置的规则",examples:["get_rules"]},{name:"send_request",description:"发送 HTTP 请求,自动携带浏览器 Cookie,支持 multipart 和原始二进制上传",params:[{name:"url",type:"string",required:!0,description:"完整目标 URL"},{name:"method",type:"string",description:"HTTP 方法,默认 GET"},{name:"headers",type:"object",description:"自定义请求头"},{name:"params",type:"object",description:"URL 查询参数"},{name:"body",type:"any",description:"请求体(传对象时自动 JSON 序列化)"},{name:"bodyFile",type:"object",description:"原始二进制请求体:filePath 或 base64 二选一,可选 contentType(默认 application/octet-stream);与 body/formData/files 互斥"},{name:"formData",type:"object",description:"multipart 文本字段(值支持 string/number/boolean)"},{name:"files",type:"SendRequestFile[]",description:"multipart 文件,最多 20 个、总计不超过 40 MiB;Base64 文件总计不超过 7 MiB。每项传 fieldName 和绝对 filePath,或传 base64 + filename",details:["fieldName: string(必填);filePath: string 与 base64: string 二选一","filename: string,base64 时必填,filePath 时默认文件 basename","contentType: string(可选),默认按文件名推断 MIME,否则 application/octet-stream"]},{name:"withCookies",type:"boolean",description:"是否附加浏览器 Cookie,默认 true"},{name:"responseType",type:'"json" | "text" | "auto"',description:"响应解析方式,默认 auto"},{name:"timeout",type:"number",description:"超时毫秒数,默认 30000"}],notes:["需要托管认证的接口使用相应能力插件;不要手工传入其管理的凭据。","body 不能与 formData/files 组合;bodyFile 以原始字节发送,不包 multipart boundary,不能用于 GET/HEAD。","bodyFile.filePath 属于 native-host,最大 40 MiB;base64 解码后最大 7 MiB。multipart 不手工设置 Content-Type,由 Mearl 生成 boundary。","filePath 属于请求执行宿主;无法引用远端路径时用 base64。"],result:["返回 status、statusText、headers、body、bodyType、attachedCookieCount;bodyType 为 json/text/base64,二进制 body 需解码后保存。"],examples:[`send_request --payload '{"url":"https://api.example.com/data","method":"GET"}'`,`send_request --payload '{"url":"https://api.example.com/upload","method":"POST","formData":{"folder":"assets"},"files":[{"fieldName":"file","filePath":"/absolute/path/image.png"}]}'`,`send_request --payload '{"url":"https://api.example.com/upload","method":"POST","bodyFile":{"filePath":"/absolute/path/image.png","contentType":"image/png"}}'`]},{name:"send_mtop_request",description:"使用目标浏览器 Cookie 发起 mtop 请求,自动处理签名和 token",params:[{name:"api",type:"string",required:!0,description:"mtop API 名称"},{name:"data",type:"object",description:"请求数据"},{name:"version",type:"string",description:"API 版本,默认 1.0"},{name:"method",type:"string",description:"HTTP 方法,默认 GET"},{name:"appKey",type:"string",description:"签名使用的 appKey,默认 12574478"},{name:"env",type:'"prod" | "pre"',description:"请求环境,默认 prod"},{name:"timeout",type:"number",description:"超时毫秒数,默认 10000"}],notes:["需要目标浏览器有对应登录态;Mearl 自动处理签名,不依赖页面脚本。api 以 mopen. 开头时使用 mopen 协议。","env=prod 使用 h5api.m.taobao.com,pre 使用 h5api.wapa.taobao.com。"],result:["返回 success、response、requestData;业务成功需检查 response.ret。"],examples:[`send_mtop_request --payload '{"api":"mtop.trade.order.detail","data":{"orderId":"123"}}'`]},{name:"browser_list",description:"列出所有浏览器及其连接状态、类型和 Provider 托管实例信息",summary:"列出本地及远端浏览器与连接状态",examples:["browser_list"]},{name:"browser_release",description:"释放当前浏览器的调试控制和会话级临时效果(含设备/时区模拟);不用于普通任务收尾,Provider 实例的行为以 mearl <providerId> 为准",params:[{name:"closeCreatedTabs",type:"boolean",description:"带 --session 时关闭会话创建的过程页,默认 false"},{name:"keepTabIds",type:"number[]",description:"保留的结果页面;复用的用户页面始终保留"},{name:"preserveEnvironment",type:"boolean",description:"带 --session 时默认 true,保留 Mock 与模拟现场;false 清理这些页面的环境"},{name:"keepArtifactIds",type:"string[]",description:"保留在浏览器宿主的文件产物;其余会话临时文件删除"}],notes:["带 --session 时可用于任务收尾,只释放该会话;未带会话时保留原浏览器级释放行为,活动会话存在时拒绝全局释放。"],summary:"释放浏览器调试控制和会话级临时效果",examples:["browser_release","browser_release --browser chrome-a"]},{name:"browser_launch",description:"启动本地 Chrome,或通过已注册 Provider 创建浏览器实例",params:[{name:"name",type:"string",description:"本地实例名称;使用 local Provider 时必填"},{name:"provider",type:"string",description:"运行环境,默认 local;可传 mearl --help 中展示的已注册 Provider ID"},{name:"providerOptions",type:"Record<string, JSON value>",description:"所选 Provider 声明的结构化启动参数;不能与顶层启动字段混用"},{name:"headless",type:"boolean",description:"本地 Provider 是否无头运行,默认 true"},{name:"userAgentMode",type:'"default" | "desktop"',description:"本地 UA 模式:default 使用默认 UA;desktop 使用匹配本机版本的 UA"},{name:"persistent",type:"boolean",description:"本地实例关闭后是否保留 Profile,默认 false"},{name:"url",type:"string",description:"登录完成后打开的初始页面"},{name:"executablePath",type:"string",description:"自定义 Chrome 可执行文件路径"},{name:"copyCookieDomains",type:"string[] | string | { presets?: string[]; domains?: string[] }",description:"从控制浏览器复制 Cookie:可传域名数组、已安装能力提供的范围名,或组合范围与额外域名"}],examples:[`browser_launch --payload '{"provider":"brow","providerOptions":{}}'`,`browser_launch --payload '{"name":"figma","userAgentMode":"desktop","copyCookieDomains":["figma.com"]}'`,`browser_launch --payload '{"name":"with-cookies","copyCookieDomains":["example.com","sub.example.org"]}'`]},{name:"browser_close",description:"关闭指定托管浏览器,并按 Provider 策略保留或清理持久化数据",params:[{name:"browser",type:"string",required:!0,description:"托管浏览器的 browserId 或名称"},{name:"deleteProfile",type:"boolean",description:"强制删除持久化数据,默认 false"}],examples:[`browser_close --payload '{"browser":"managed:account-a"}'`,`browser_close --payload '{"browser":"account-b","deleteProfile":true}'`]},{name:"tab_open",description:"打开或按 URL 规则复用 Tab,并等待新页面加载完成",aliases:["tab_new","new_tab","tab_create","create_tab"],params:[{name:"url",type:"string",required:!0,description:"要打开的 URL"},{name:"active",type:"boolean",description:"是否激活目标 Tab,默认 false;扩展免打扰默认开启,使用后台焦点模拟,关闭后才切换前台;响应返回 activation"},{name:"openerTabId",type:"number",description:"来源 Tab ID;用于把目标 Tab 关联到来源侧边栏对话"},{name:"closeExisting",type:"boolean",description:"打开前先关闭 Agent 受控的已有标签页,默认 false"},{name:"group",type:"string",description:"把新 Tab 加入指定标题的标签页分组(同名分组存在则加入,否则新建)。仅扩展模式支持"},{name:"reuse",type:'"never" | "prefer" | "require"',description:"never 始终新开;prefer 优先复用;require 只允许复用。默认 never"},{name:"match",type:"object",description:"复用匹配规则:urlPattern(支持 *)、ignoreSearch、ignoreHash、onMultiple(error/first)"},{name:"restoreFocusOnClose",type:"boolean",description:"关闭本次新开的 active Tab 后恢复原活动标签页,默认 false"},{name:"emulation",type:"object",description:"开 tab 即进入移动端模拟态(首屏即移动态、无需 reload)。字段同 set_device_emulation 去掉 enabled/reload;与 appProfile、deviceShell=true、orientation=landscape、splitScreen=true 组合可首屏进入左右分屏"},{name:"appProfile",type:"string",description:"按已安装档案应用 App 环境;内置基础档案只提供 UA/版本,完整桥由能力包提供。需要 iframe WebView 和系统栏时同时传 emulation.deviceShell=true"},{name:"os",type:'"ios" | "android"',description:"与 appProfile 配合;容器系统,默认 ios"},{name:"bridgeConfig",type:"object",description:"与 appProfile 配合;声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}}"}],notes:["emulation / appProfile 只应用到新建 Tab;复用 Tab 要切换状态时用对应设置 action。","closeExisting 不能与复用或 openerTabId 组合;多匹配默认报错,match.onMultiple=first 可显式选择第一个。"],result:["返回 tabId、url、title、opened/reused;reused=true 的既有页面应保留。","active=true 时 activation 包含 tabActive、windowFocused、windowState、visibilityState;emulation 返回实际生效配置。","capture.cursor 是导航前诊断边界,可分别用于 get_logs/get_requests/get_events 的 after。"],examples:[`tab_open --payload '{"url":"https://example.com"}'`,`tab_open --payload '{"url":"https://example.com/page","reuse":"prefer","match":{"ignoreSearch":true}}'`,`tab_open --payload '{"url":"https://m.example.com","emulation":{"preset":"iphone-17-pro"}}'`,`tab_open --payload '{"url":"https://example.com/app/home","appProfile":"fliggy"}'`,`tab_open --payload '{"url":"https://example.com/app/home","appProfile":"fliggy","emulation":{"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}}'`,`tab_open --payload '{"url":"https://example.com","appProfile":"fliggy","os":"android"}'`,`tab_open --payload '{"url":"https://example.com","group":"验证任务"}'`]},{name:"tab_close",description:"关闭指定标签页",aliases:["tab_remove","remove_tab","tab_delete","delete_tab"],params:[{name:"tabId",type:"number",required:!0,description:"要关闭的标签页 ID"}],examples:[`tab_close --payload '{"tabId":123}'`]},{name:"tab_list",description:"列出目标浏览器所有窗口中的标签页",aliases:["tabs","list_tabs","show_tabs"],examples:["tab_list"]},{name:"tab_group",description:"把同一窗口中的标签页加入分组,或通过 ungroup 取消分组并保留标签页;仅扩展模式支持",params:[{name:"tabIds",type:"number[]",required:!0,description:"标签页 ID,分组最多 100 个,取消分组最多 1000 个"},{name:"title",type:"string",required:!1,description:"分组标题;取消分组时省略"},{name:"ungroup",type:"boolean",required:!1,description:"为 true 时取消分组并保留标签页"}],examples:[`tab_group --payload '{"tabIds":[123,124],"title":"项目文档"}'`,`tab_group --payload '{"tabIds":[123,124],"ungroup":true}'`]},{name:"page_click",description:"点击页面元素,支持 CSS/@ref、可见文本或视口坐标定位",params:[{name:"selector",type:"string",description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)。不支持 :has-text/:visible 等 Playwright 私有伪类"},{name:"text",type:"string",description:"按可见文本(accessibility name)定位。需要时配合 role/exact 消歧;多匹配会报错并列出候选"},{name:"point",type:"{ x: number; y: number }",description:'按视口坐标点击(CSS 像素)。默认使用 outer-viewport;容器或 iframe 内坐标配合 coordinateSpace: "active-frame"'},{name:"frameId",type:"string",description:"浏览器扩展后端:显式指定 CSS/text 查询或 active-frame 坐标所属的 frame;省略时容器模式自动使用当前业务 frame"},{name:"coordinateSpace",type:'"outer-viewport" | "active-frame"',description:"仅配合 point 使用;默认 outer-viewport;浏览器扩展后端的 active-frame 会换算 iframe 偏移与缩放后派发可信输入"},{name:"role",type:"string",description:"配合 text 使用,按 AX role 过滤(如 button、link、heading)"},{name:"exact",type:"boolean",description:"配合 text 使用,默认 true 精确匹配;false 时按子串匹配"},{name:"scope",type:"string",description:"配合 text 使用,把文本匹配限制在指定 CSS 元素或 @eN ref 子树内,适合消除重复文案歧义"},{name:"clickMode",type:'"auto" | "dom" | "mouse" | "touch"',description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["selector / text / point 必须且只能提供一个。隐藏页 auto 使用 DOM;只有明确依赖真实用户手势时才激活页面。","原生 select 可按 option 文本点击;checkbox/radio 返回 controlState.checkedBefore/checkedAfter。"],examples:[`page_click --payload '{"tabId":12345,"text":"提交"}'`,`page_click --payload '{"tabId":12345,"text":"退款明细","role":"button"}'`,`page_click --payload '{"tabId":12345,"text":"确定","scope":"@e12"}'`,`page_click --payload '{"tabId":12345,"selector":"@e3"}'`,`page_click --payload '{"tabId":12345,"selector":".submit-btn"}'`,`page_click --payload '{"tabId":12345,"selector":".gesture-btn","clickMode":"touch"}'`,`page_click --payload '{"tabId":12345,"point":{"x":336,"y":117}}'`,`page_click --payload '{"tabId":12345,"point":{"x":196,"y":240},"coordinateSpace":"active-frame"}'`]},{name:"page_drag",description:"拖动页面元素或视口坐标,适用于轮播图、滑块和拖放",params:[{name:"from",type:"string | { x: number; y: number }",required:!0,description:"起点:原生 CSS、@eN ref,或 { x, y } 视口坐标(CSS 像素)"},{name:"to",type:"string | { x: number; y: number }",required:!0,description:"终点:原生 CSS、@eN ref,或 { x, y } 视口坐标(CSS 像素)"},{name:"dragMode",type:'"auto" | "dom" | "mouse" | "touch"',description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式"},{name:"durationMs",type:"number",description:"拖动持续时间,0–5000ms,默认 400ms;内部自动分段移动"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["起点会自动滚入视口,终点必须同时位于当前视口;否则先滚动页面。隐藏页 auto 使用 DOM,不切换活动页。"],examples:[`page_drag --payload '{"tabId":12345,"from":{"x":350,"y":80},"to":{"x":80,"y":80}}'`,`page_drag --payload '{"tabId":12345,"from":"@e3","to":"#drop-zone","dragMode":"mouse"}'`]},{name:"page_type",description:"向输入框填写文本,兼容 React 受控组件",params:[{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)"},{name:"text",type:"string",required:!0,description:"要填写的文本"},{name:"clearFirst",type:"boolean",description:"是否先清空原有内容,默认 true"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,examples:[`page_type --payload '{"tabId":12345,"selector":"@e6","text":"搜索关键词"}'`]},{name:"page_hover",description:"将鼠标悬停在页面元素上",params:[{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,examples:[`page_hover --payload '{"tabId":12345,"selector":".nav-menu"}'`]},{name:"page_scroll",description:"滚动页面或指定容器;页面根不可滚动时自动发现活动滚动区",params:[{name:"direction",type:'"up" | "down" | "top" | "bottom"',required:!0,description:"滚动方向"},{name:"distance",type:"number",description:"滚动距离(px),默认 600"},{name:"selector",type:"string",description:"目标滚动容器的原生 CSS 选择器,或 page_snapshot 返回的 @eN ref;不传时滚动页面"},{name:"containerPolicy",type:'"self" | "nearest"',description:"默认 self,要求 selector 本身可滚动;nearest 会在其不可滚动时使用最近的可滚动祖先"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:[...PAGE_ACTION_RESULT,"action.data 返回 moved、atTop/atBottom、scrollYBefore/After、maxScrollY、resolvedContainer 和 ancestorDistance;自动发现的内部容器提供可复用 containerSelector。"],examples:[`page_scroll --payload '{"tabId":12345,"direction":"down"}'`,`page_scroll --payload '{"tabId":12345,"direction":"bottom"}'`,`page_scroll --payload '{"tabId":12345,"selector":".virtual-list","direction":"down","distance":800}'`,`page_scroll --payload '{"tabId":12345,"selector":"@e8","containerPolicy":"nearest","direction":"bottom"}'`]},{name:"page_runtime",description:"页面运行时传输适配器;插件使用 PluginPageClient 或 app.page",params:[{name:"operation",type:"string",required:!0,description:"resolve/attach/get/send/detach/activation"}]},{name:"page_eval",description:"在页面上下文中执行任意 JavaScript 表达式",params:[{name:"expression",type:"string",required:!0,description:"要执行的 JS 表达式;传 args 时须求值为函数"},{name:"args",type:"unknown[]",description:"传给页面函数的 JSON 参数;SDK/CLI 自动处理大参数分块,保持指定执行环境"},{name:"executionWorld",type:"string",description:"main(默认)读取网页 JS;isolated 使用命名隔离环境,扩展连接无需 debugger"},{name:"worldId",type:"string",description:"isolated 必填,小写字母开头,允许数字和连字符,最长 64 字符"},{name:"awaitPromise",type:"boolean",description:"表达式返回 Promise 时等待完成,默认 true"},{name:"frameId",type:"string",description:"page_frames 返回的目标 frame ID,扩展/CDP 均支持;省略时容器/设备外壳使用当前业务 frame,普通页面使用主 frame"},{...PAGE_OBSERVE_PARAM,type:"object",description:"仅在表达式会修改页面且需要观察结果时显式传入;不传保持轻量裸执行"},PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["优先使用结构化 action;仅在其无法表达需求时执行最小范围脚本。"],result:["默认返回 { result };observe 对象启用观察并返回 { action, observation };仅开启 diagnostics 时返回 { action, diagnostics }。diagnostics=false 不启用包装。失败阶段语义同 page_click。"],examples:[`page_eval --payload '{"tabId":12345,"expression":"document.title"}'`]},{name:"page_inspect",description:"查询 DOM 元素的控件状态、数量、边框盒、计算样式、遮挡、溢出和最近滚动容器",params:[{name:"selector",type:"string",description:"原生 CSS、page_snapshot 返回的 @eN ref,或 DevTools Elements 当前选区 $0;做全页溢出诊断时可省略"},{name:"filter",type:'"all" | "overflowing" | "horizontal-overflow" | "vertical-overflow" | "scrollable"',description:"结果过滤;省略 selector 时必须指定非 all 的过滤条件"},{name:"styles",type:"string[]",description:"要返回的计算样式属性,默认 display/position/box-sizing/overflow-x/overflow-y"},{name:"maxResults",type:"number",description:"最多返回的明细数,默认 20,最大 100;未触发 scanTruncated 时 count 为完整命中数"},{name:"includeOuterHTML",type:"boolean",description:"是否返回 outerHTML(最多 3000 字符);$0 默认 true,其他目标默认 false"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:["matches[] 包含 boundingBox、computedStyle、hitTest、scroll 溢出量及可用的 scrollContainer。receivesPointerEvents=false 时读取 occludedBy。","state 返回原生/ARIA 状态及来源;缺失字段表示未知。","$0 还返回 resolvedSelector、属性、XPath 和可用框架信息。"],examples:[`page_inspect --payload '{"tabId":12345,"selector":".form-field","styles":["display","width"]}'`,`page_inspect --payload '{"tabId":12345,"selector":"@e8"}'`,`page_inspect --payload '{"tabId":12345,"selector":"$0"}'`,`page_inspect --payload '{"tabId":12345,"filter":"horizontal-overflow"}'`,`page_inspect --payload '{"tabId":12345,"filter":"scrollable"}'`]},{name:"page_press",description:"在页面中按下键盘按键或组合键",params:[{name:"key",type:"string",required:!0,description:"按键名称:Enter/Tab/Escape/Backspace 等"},{name:"modifiers",type:"string[]",description:"修饰键数组:ctrl/alt/shift/meta/cmd"},{name:"pressMode",type:'"auto" | "dom" | "keyboard"',description:"派发模式;auto 默认在隐藏页降级为 DOM 键盘事件"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["隐藏页 DOM 模式支持 Tab 焦点移动、原生控件 Enter/Space 激活和输入框 Enter 提交;编辑、选择、方向键和页面滚动等原生行为需可见页与 pressMode=keyboard。"],result:[...PAGE_ACTION_RESULT,"action.data.dispatchMode / fallbackReason / defaultAction 说明实际输入路径。"],examples:[`page_press --payload '{"tabId":12345,"key":"Enter"}'`]},{name:"page_wait",description:"等待指定时间、元素状态、可见文本或页面条件成立",params:[{name:"time",type:"number",description:"等待毫秒数(与 selector/text/condition 四选一)"},{name:"selector",type:"string",description:"目标 CSS 选择器(与 time/text/condition 四选一)"},{name:"state",type:'"attached" | "detached" | "visible" | "hidden"',description:"selector 的目标状态,默认 attached"},{name:"text",type:"string",description:"等待页面出现的可见文本"},{name:"exact",type:"boolean",description:"text 是否精确匹配,默认 false"},{name:"condition",type:"string",description:"在页面主上下文轮询的 JS 表达式,返回 truthy 时结束"},{name:"timeout",type:"number",description:"等待超时毫秒数,默认 10000"},{name:"interval",type:"number",description:"轮询间隔毫秒数,默认 200"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["time / selector / text / condition 必须且只能提供一个;time 范围 0–60000ms。页面交互已有内置观察,仅在需要独立等待条件时使用。"],examples:[`page_wait --payload '{"tabId":12345,"time":1000}'`,`page_wait --payload '{"tabId":12345,"selector":".dialog","state":"visible"}'`,`page_wait --payload '{"tabId":12345,"selector":".loading","state":"hidden"}'`,`page_wait --payload '{"tabId":12345,"text":"提交成功"}'`,`page_wait --payload '{"tabId":12345,"condition":"window.appReady === true","timeout":30000}'`]},{name:"page_navigate",description:"在当前标签页内导航到 URL、刷新页面,或沿浏览历史后退/前进",params:[{name:"url",type:"string",description:"要导航到的 URL;与 refresh/history 互斥"},{name:"refresh",type:"boolean",description:"为 true 时直接重新加载当前页面;与 url/history 互斥"},{name:"history",type:'"back" | "forward"',description:"沿当前标签页浏览历史后退或前进;与 url/refresh 互斥"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["url / refresh=true / history 必须且只能提供一个。"],examples:[`page_navigate --payload '{"tabId":12345,"url":"https://example.com/page2"}'`,`page_navigate --payload '{"tabId":12345,"refresh":true}'`,`page_navigate --payload '{"tabId":12345,"history":"back"}'`]},{name:"page_upload",description:'向 <input type="file"> 元素上传一个或多个文件',params:[{name:"files",type:"object[]",description:"调用方绝对路径 {filePath} 或浏览器产物 {artifactId};与 filePaths 二选一"},{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀),必须指向 input[type=file]"},{name:"filePaths",type:"string[]",description:"浏览器宿主上的绝对路径数组;与 files 二选一"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["直接写入 input[type=file],不依赖 file chooser;隐藏的文件节点也可上传。外部 Provider 的文件中转能力查询 mearl <providerId>。"],examples:[`page_upload --payload '{"tabId":12345,"selector":"#file-input","filePaths":["/Users/me/photo.jpg"]}'`]},{name:"page_snapshot",description:"获取带 @ref 的页面结构快照,默认使用无障碍树,也可显式读取渲染 DOM",params:[{name:"depth",type:"number",description:"树深度,默认 15,复杂页面可调大"},{name:"mode",type:'"full" | "interactive" | "viewport" | "dom"',description:"默认 full;interactive/viewport 裁剪 AX 树;AX 信息缺失时可显式使用 dom 读取渲染 DOM"},{name:"rootSelector",type:"string",description:"只获取指定 CSS 元素的局部子树,可与 mode 组合;与 rootRef 互斥"},{name:"rootRef",type:"string",description:"以已有 @eN ref 为根获取局部子树;与 rootSelector 互斥"},{name:"ancestorDepth",type:"number",description:"rootRef 向上扩展的 DOM 祖先层数,默认 0,最大 20"},{name:"query",type:"{ text?: string; role?: string; exact?: boolean }",description:"服务端按 name / role 过滤当前模式的树,只保留命中节点及祖先路径"},{name:"maxNodes",type:"number",description:"最多输出节点数,0 表示不限制"},{name:"maxChars",type:"number",description:"快照文本最大字符数,默认 60000,超出保留首尾;传 0 不限制"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["query.text / query.role 至少提供一个;query.exact 默认 true。每次快照刷新有效 ref 集合。","interactive 无 AX 控件时回退到 viewport,不会自动改用 dom;Canvas 内容需截图。"],result:["返回 snapshot、elementCount、outputNodeCount、mode;截断时 truncated=true。","snapshot 中的 @eN 可直接用于操作;内部节点映射仅保存在运行时。无名称、无 ref 且无状态的分组折叠到子节点。","query 返回 matches 与完整 matchCount,matches 最多 100 项,裁剪时 matchesTruncated=true。容器/iframe 的视口裁剪返回 outerViewport、contentViewport 和滚动位置。"],examples:[`page_snapshot --payload '{"tabId":12345}'`,`page_snapshot --payload '{"tabId":1,"mode":"viewport"}'`,`page_snapshot --payload '{"tabId":1,"mode":"dom"}'`,`page_snapshot --payload '{"tabId":1,"rootSelector":"[role=dialog]"}'`,`page_snapshot --payload '{"tabId":1,"rootRef":"@e8","ancestorDepth":1}'`,`page_snapshot --payload '{"tabId":1,"query":{"text":"保存","role":"button"}}'`]},{name:"page_screenshot",description:"获取当前视口或指定元素截图",outputFlag:!0,params:[{name:"selector",type:"string",description:"CSS 选择器,提供后只截取该元素区域"},{name:"format",type:'"png" | "jpeg"',description:"图片格式,默认 png"},{name:"quality",type:"number",description:"JPEG 压缩质量(0-100),默认 80"},{name:"captureMode",type:'"cdp" | "visible"',description:"默认 cdp;visible 使用活动标签页截图,普通网页无需 debugger;设备模拟复用模拟会话并截取业务视口,不支持 selector"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["使用 --output <path> 保存图片;省略时 stdout 返回含 base64 data 的 JSON,避免直接将其加载为文本。"],result:["meta 包含 format、width、height、size、url、title;宽高为实际截图的物理像素。"],examples:[`page_screenshot --payload '{"tabId":12345}' --output ./screenshot.png`,`page_screenshot --payload '{"tabId":12345,"selector":".product-card"}' --output ./card.png`]},{name:"set_device_emulation",description:"把目标 tab 切换为移动端模拟(视口/DPR/UA/触摸/视觉比例),等价 DevTools 设备工具栏,作用域 per-tab;需保持调试控制才持续生效",summary:"设置或清除目标标签页的设备模拟",params:[{name:"enabled",type:"boolean",required:!0,description:"true=启用,false=清除"},{name:"preset",type:DEVICE_PRESET_TYPE,description:"内置设备预设,提供 width/height/DPR/UA 默认值;旧机型 ID 继续兼容"},{name:"width",type:"number",description:"视口宽度(覆盖 preset)"},{name:"height",type:"number",description:"视口高度(覆盖 preset)"},{name:"deviceScaleFactor",type:"number",description:"DPR(覆盖 preset)"},{name:"scale",type:"number",description:"画面视觉比例,不改变视口尺寸或 DPR;必须为有限正数,默认 1"},{name:"mobile",type:"boolean",description:"是否走移动渲染模式,默认从 preset 推断"},{name:"userAgent",type:"string",description:"自定义 UA(覆盖 preset)"},{name:"orientation",type:'"portrait" | "landscape"',description:"横竖屏,默认 portrait"},{name:"touch",type:"boolean",description:"是否启用触摸事件,默认从 preset 推断;无 preset 时跟随 mobile"},{name:"deviceShell",type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},{name:"splitScreen",type:"boolean",description:"是否将首页与业务页分置左右 WebView;仅在已启用 App 档案、deviceShell=true、横屏时生效,默认 false"},{name:"reload",type:"boolean",description:"启用后是否重载页面,默认 true"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["无 preset 时 width/height 必须成对提供且 userAgent 必填;mobile 默认 true,touch 跟随 mobile。","deviceShell 开启/移除时必须重载;splitScreen 仅在已启用 App 档案、deviceShell=true、横屏时生效。"],result:["返回实际 viewport(width/height/deviceScaleFactor/scale)、UA、mobile、touch、orientation、deviceShell、splitScreen 和 reloaded;应以响应确认生效状态。"],examples:[`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"iphone-17-pro"}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"pixel-11","orientation":"landscape"}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":false}'`]},{name:"set_app_profile",description:"设置已安装的 App 档案;完整 JSBridge 由能力包提供。可同时设置 MTop 页面接口环境,传 emulation 时联动设备模拟",summary:"设置或清除目标标签页的 App 容器模拟",params:[{name:"enabled",type:"boolean",required:!0,description:"true=启用,false=清除"},{name:"profile",type:"string",description:`容器档案名(enabled=true 时必填);内置 ${APP_PROFILE_NAME_LIST}`},{name:"os",type:'"ios" | "android"',description:"容器系统,默认 ios"},{name:"refreshDefinition",type:"boolean",description:"立即采用最新档案定义,保留用户显式设置"},{name:"lockDefinition",type:"boolean",description:"固定当前定义;默认在下次刷新或文档导航时自动更新"},{name:"appVersion",type:"string",description:"覆盖档案默认 App 版本号"},{name:"deviceModel",type:"string",description:"Android 机型名(拼入 UA 与 __DEVICE_MODEL__)"},{name:"bridgeConfig",type:"object",description:"声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}};不执行配置脚本"},{name:"mtopEnv",type:'"default" | "prod" | "pre"',description:"可选 MTop 页面接口环境;default 关闭环境改写,省略时保持当前设置。仅作用于目标 tab"},{name:"emulation",type:"object",description:"可选设备联动参数,字段同 set_device_emulation 去掉 enabled/reload;字段覆盖档案推荐设备,deviceShell 默认 true,横屏时可传 splitScreen=true。省略时不设置或清除设备"},{name:"reload",type:"boolean",description:"应用/清除后是否重载页面,默认 true"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["只有用户明确要求 App/客户端/容器/JSBridge 模拟时启用。移动视口或普通 H5 调试使用 set_device_emulation。","emulation={} 使用档案推荐设备;enabled=false 时省略 emulation 只清除 App 注入,传 {} 同时清除设备模拟。","bridgeConfig.methods 按方法声明 behavior / response / noop 三选一,可传 silent;只支持受控行为、固定 JSON 回包或成功空实现,不执行配置脚本。"],result:["返回 enabled、profile、label、userAgent、os、mtopEnv、reloaded;联动设备时额外返回实际 emulation。"],examples:[`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"fliggy"}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"fliggy","mtopEnv":"pre"}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false,"mtopEnv":"prod"}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"fliggy","emulation":{}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"alipay","emulation":{"preset":"pixel-11","deviceShell":true}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"fliggy","emulation":{"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false,"emulation":{}}'`]},{name:"set_timezone",description:"覆盖目标 tab 的时区,传空字符串恢复浏览器默认时区",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"},{name:"timezone",type:"string",required:!0,description:"IANA 时区标识(如 Asia/Shanghai);空字符串表示清除覆盖"}],examples:[`set_timezone --payload '{"tabId":12345,"timezone":"America/New_York"}'`,`set_timezone --payload '{"tabId":12345,"timezone":""}'`]},{name:"get_cookie",description:"从目标浏览器读取一个指定非分区 Cookie;拒绝返回 HttpOnly Cookie",params:[{name:"tabId",type:"number",description:"可选;指定标签页的 Cookie 存储区,省略时使用浏览器默认存储区"},{name:"name",type:"string",required:!0,description:"要读取的 Cookie 名称;不支持列举全部 Cookie"},{name:"url",type:"string",description:"Cookie 查询 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},{name:"domain",type:"string",description:"可选精确域过滤,只允许 Cookie 查询 URL 的 host 或其父域"},{name:"path",type:"string",description:"可选精确 path 过滤"}],notes:["只读取指定非分区 Cookie,不列举全部、不回退分区 Cookie,拒绝 HttpOnly;禁止读取认证 Token。指定 url 不导航,指定 tabId 仅选择存储区时不启动采集。"],result:["找到时 found=true 并返回 value/domain/path;不存在时 found=false。"],examples:[`get_cookie --payload '{"tabId":12345,"name":"feature_flag"}'`,`get_cookie --payload '{"url":"https://www.taobao.com/","name":"tracknick"}'`,`get_cookie --payload '{"tabId":12345,"name":"feature_channel","domain":"example.com"}'`,`get_cookie --payload '{"tabId":12345,"name":"tracknick","url":"https://www.taobao.com/","domain":"example.com","path":"/"}'`]},{name:"set_cookie",description:"在目标浏览器设置一个指定非分区 session Cookie,可选刷新指定页面",params:[{name:"tabId",type:"number",description:"可选;指定标签页的 Cookie 存储区,reload=true 时必填"},{name:"url",type:"string",description:"Cookie 目标 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},{name:"name",type:"string",required:!0,description:"Cookie 名称"},{name:"value",type:"string",required:!0,description:"Cookie 值,可传空字符串;空字符串不会删除 Cookie"},{name:"domain",type:"string",description:"Cookie 域,默认目标 URL 的 host;只允许目标 host 或其父域"},{name:"path",type:"string",description:"Cookie path,默认 /"},{name:"reload",type:"boolean",description:"设置后是否刷新指定 tabId,默认 false;true 时必须传 tabId"}],notes:["仅写非分区 session Cookie,不支持删除。reload=true 时校验目标域与刷新页域的授权。"],result:["返回 url/name/domain/path/reloaded,指定标签页时包含 tabId;不回显 Cookie 值。"],examples:[`set_cookie --payload '{"tabId":12345,"name":"feature_flag","value":"enabled"}'`,`set_cookie --payload '{"url":"https://www.taobao.com/","name":"feature_flag","value":"enabled"}'`,`set_cookie --payload '{"tabId":12345,"name":"feature_channel","value":"3.6.63","domain":"example.com","reload":true}'`]},{name:"page_frames",description:"获取页面主 frame 与所有 iframe 列表",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:["frames[] 包含 frameId、url、name 和 isMainFrame;frameId 可用于 page_eval 等支持 frame 定位的 action。"],examples:[`page_frames --payload '{"tabId":12345}'`]},{name:"request_domain_permission",description:"申请访问指定域名的权限(必要时弹窗让用户授权)",params:[{name:"domain",type:"string",required:!0,description:"需要授权的域名,如 example.com"}],notes:["domain 使用纯主机名,不传 URL。在 send_request 或 set_rule 提示缺少浏览器域名权限时申请。","弹窗等待用户选择,90 秒超时或关闭按拒绝处理;granted=true 后才重试原请求。"],result:["返回 granted、domain,授权成功时包含 origin。"],examples:[`request_domain_permission --payload '{"domain":"example.com"}'`]},{name:"run_actions",description:"批量顺序执行多个 action,减少往返延迟。遇错即停,返回已完成步骤结果;步骤内的页面动作不带内置观察",summary:"批量顺序执行多个 action,遇错即停",params:[{name:"actions",type:"Array<{action: string, data?: object}>",required:!0,description:"要依次执行的 action 列表"},{name:"tabId",type:"number",required:!0,description:"所有步骤共享的 tabId,步骤自身指定的优先"}],notes:["最多 50 步,不允许嵌套 run_actions;需要根据每步效果决策时逐步调用普通 action。"],result:["返回 results、completedSteps、totalSteps;失败时包含 error/failedStep,后续步骤未执行。"],examples:[`run_actions --payload '{"tabId":12345,"actions":[{"action":"page_hover","data":{"selector":"#menu"}},{"action":"page_click","data":{"selector":"#menu-item"}}]}'`]}],COMMAND_MAP=new Map(COMMANDS.map(command=>[command.name,command]))}});import{statSync as statSync3}from"node:fs";function pluginFileVersion(path8){let stat2=statSync3(path8);if(!stat2.isFile())throw new Error(`插件资源不是文件: ${path8}`);return`${stat2.dev}-${stat2.ino}-${stat2.mtimeMs}-${stat2.ctimeMs}-${stat2.size}`}var init_pluginSource=__esm({"../client/src/plugins/pluginSource.ts"(){"use strict"}});import{createHash as createHash2}from"node:crypto";import{readFileSync as readFileSync4,realpathSync}from"node:fs";import{basename,dirname as dirname3,extname,isAbsolute,join as join4,relative,resolve,sep}from"node:path";function pluginRoot(entry){let entryDirectory=dirname3(entry);return basename(entryDirectory)==="scripts"?dirname3(entryDirectory):entryDirectory}function attributeValue(tag,name){let match=tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return match?.[1]??match?.[2]??match?.[3]}function removeAttribute(tag,name){return tag.replace(new RegExp(`\\s+${name}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+)`,"i"),"")}function isEmbeddedReference(reference){return/^(?:data:|blob:|#)/i.test(reference.trim())}function isRemoteReference(reference){return/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(reference.trim())}function contentType(path8){return MIME_TYPES[extname(path8).toLowerCase()]??"application/octet-stream"}function escapeStyleText(value){return value.replace(/<\/style/gi,"\\3C /style")}function escapeScriptText(value){return value.replace(/<\/script/gi,"<\\/script")}function buildPluginPageBundle(entry,pageEntry){let root=realpathSync(pluginRoot(entry)),sourceBytes=0,countedFiles=new Set,sources={},resolveLocalFile=(reference,fromFile)=>{let cleanReference=reference.trim().split(/[?#]/,1)[0];if(!cleanReference||isEmbeddedReference(cleanReference))return"";if(isRemoteReference(cleanReference)||isAbsolute(cleanReference))throw new Error(`toolbox.page 不允许远程或绝对资源: ${reference}`);let sourcePath=resolve(dirname3(fromFile),cleanReference),resolved=realpathSync(sourcePath),relativePath=relative(root,resolved);if(relativePath===".."||relativePath.startsWith(`..${sep}`)||isAbsolute(relativePath))throw new Error(`toolbox.page 资源超出插件目录: ${reference}`);return sources[sourcePath]=pluginFileVersion(sourcePath),resolved},readAsset=path8=>{sources[path8]??=pluginFileVersion(path8);let content2=readFileSync4(path8);if(!countedFiles.has(path8)&&(countedFiles.add(path8),sourceBytes+=content2.byteLength,sourceBytes>MAX_PAGE_SOURCE_BYTES))throw new Error("toolbox.page 源文件总大小不能超过 16 MiB");return content2},dataUrl=(reference,fromFile)=>{if(isEmbeddedReference(reference))return reference;let path8=resolveLocalFile(reference,fromFile);return`data:${contentType(path8)};base64,${readAsset(path8).toString("base64")}`},inlineCss=(css,cssPath)=>css.replace(/url\(\s*(['"]?)([^'"()]+)\1\s*\)/gi,(_match,_quote,reference)=>{let value=reference.trim();return isEmbeddedReference(value)?`url("${value}")`:`url("${dataUrl(value,cssPath)}")`}),absoluteEntry=resolveLocalFile(pageEntry,join4(root,"__toolbox_entry__"));if(extname(absoluteEntry).toLowerCase()!==".html")throw new Error("toolbox.page.entry 必须指向 HTML 文件");let html=readAsset(absoluteEntry).toString("utf8").replace(/^\uFEFF/,"");if(!/<html\b|<!doctype\b/i.test(html))throw new Error("toolbox.page.entry 必须是完整 HTML 文档");if(/<base\b/i.test(html))throw new Error("toolbox.page 不允许声明 base 标签");if(/<meta\b[^>]*http-equiv\s*=\s*["']?content-security-policy/i.test(html))throw new Error("toolbox.page 的安全策略由 Mearl 管理,请移除 CSP meta 标签");html=html.replace(/<link\b[^>]*>/gi,tag=>{let rel=attributeValue(tag,"rel")?.toLowerCase().split(/\s+/)??[],href=attributeValue(tag,"href");if(rel.includes("stylesheet")){if(!href)throw new Error("toolbox.page stylesheet 缺少 href");let cssPath=resolveLocalFile(href,absoluteEntry),css=inlineCss(readAsset(cssPath).toString("utf8"),cssPath);return`<style data-mearl-source="${href.replaceAll('"',"&quot;")}">${escapeStyleText(css)}</style>`}if(href&&rel.some(value=>["icon","apple-touch-icon"].includes(value)))return tag.replace(href,dataUrl(href,absoluteEntry));if(href&&isRemoteReference(href))throw new Error(`toolbox.page 不允许远程 link 资源: ${href}`);return tag}),html=html.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,tag=>{let src=attributeValue(tag,"src");if(!src)return tag;let scriptPath=resolveLocalFile(src,absoluteEntry),script=readAsset(scriptPath).toString("utf8");if(attributeValue(tag,"type")?.toLowerCase()==="module"&&/(?:^|[;\n]\s*)(?:import\s|export\s)|\bimport\s*\(/m.test(script))throw new Error("toolbox.page 的模块脚本必须先打包为无 import 的单文件");return`${removeAttribute(tag.slice(0,tag.indexOf(">")+1),"src")}${escapeScriptText(script)}</script>`}),html=html.replace(/(<(?:img|source|video|audio|track|input)\b[^>]*?\s(?:src|poster)\s*=\s*)(["'])([^"']+)\2/gi,(_match,prefix,quote,reference)=>`${prefix}${quote}${dataUrl(reference,absoluteEntry)}${quote}`);let injection=`<meta name="color-scheme" content="light dark">${PAGE_SECURITY_META}${PAGE_THEME_STYLE}<script data-mearl-bridge>${escapeScriptText(PAGE_BRIDGE_SCRIPT)}</script>`;html=/<head\b[^>]*>/i.test(html)?html.replace(/<head\b[^>]*>/i,tag=>`${tag}${injection}`):html.replace(/<html\b[^>]*>/i,tag=>`${tag}<head>${injection}</head>`);let content=html,buffer=Buffer.from(content,"utf8");if(buffer.byteLength>MAX_PAGE_BUNDLE_BYTES)throw new Error("toolbox.page 打包后不能超过 24 MiB");return{content,hash:createHash2("sha256").update(buffer).digest("hex"),size:buffer.byteLength,chunks:Math.ceil(buffer.byteLength/PLUGIN_PAGE_CHUNK_BYTES),sources}}var PLUGIN_PAGE_CHUNK_BYTES,MAX_PAGE_SOURCE_BYTES,MAX_PAGE_BUNDLE_BYTES,MIME_TYPES,PAGE_BRIDGE_SCRIPT,PAGE_SECURITY_META,PAGE_THEME_STYLE,PLUGIN_PAGE_RUNTIME_HASH,init_pluginPageBundle=__esm({"../client/src/plugins/pluginPageBundle.ts"(){"use strict";init_pluginSource();PLUGIN_PAGE_CHUNK_BYTES=384*1024,MAX_PAGE_SOURCE_BYTES=16*1024*1024,MAX_PAGE_BUNDLE_BYTES=24*1024*1024,MIME_TYPES={".avif":"image/avif",".gif":"image/gif",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".ogg":"audio/ogg",".otf":"font/otf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"},PAGE_BRIDGE_SCRIPT=String.raw`(() => {
2
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key2 of __getOwnPropNames(from))!__hasOwnProp.call(to,key2)&&key2!==except&&__defProp(to,key2,{get:()=>from[key2],enumerable:!(desc=__getOwnPropDesc(from,key2))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));import{createRequire}from"node:module";import{fileURLToPath}from"node:url";var require2,CLIENT_VERSION,PLUGIN_TASK_HOST_PATH,PLUGIN_WORKER_PATH,SCRIPT_WORKER_PATH,PLUGIN_MODEL_SESSION_WORKER_PATH,init_runtimePaths=__esm({"../client/src/runtimePaths.ts"(){"use strict";require2=createRequire(import.meta.url),CLIENT_VERSION=require2("../package.json").version,PLUGIN_TASK_HOST_PATH=fileURLToPath(new URL("./plugin-task-host.js",import.meta.url)),PLUGIN_WORKER_PATH=fileURLToPath(new URL("./plugin-worker.js",import.meta.url)),SCRIPT_WORKER_PATH=fileURLToPath(new URL("./scriptWorker.js",import.meta.url)),PLUGIN_MODEL_SESSION_WORKER_PATH=fileURLToPath(new URL("./pluginModelSessionWorker.js",import.meta.url))}});import{readFileSync,readdirSync}from"node:fs";import{spawnSync}from"node:child_process";function linuxProcessStat(pid){let stat2=readFileSync(`/proc/${pid}/stat`,"utf8"),end=stat2.lastIndexOf(")"),fields2=stat2.slice(end+2).trim().split(/\s+/),group=Number(fields2[2]),threads=Number(fields2[17]);if(end<0||!/^[A-Za-z]$/.test(fields2[0])||!Number.isSafeInteger(group)||group<0||!Number.isSafeInteger(threads)||threads<0||!/^\d+$/.test(fields2[19]??""))throw new Error("Invalid Linux process stat");return{state:fields2[0],group,threads,identity:fields2[19]}}function linuxProcessExited({state,threads}){return threads<=1&&(state==="Z"||state==="X"||state==="x")}function processIdentity(pid){if(!(!Number.isSafeInteger(pid)||pid<1))try{if(process.platform==="linux")return linuxProcessStat(pid).identity;let result=process.platform==="win32"?spawnSync("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:2e3,windowsHide:!0}):spawnSync("ps",["-p",String(pid),"-o","lstart="],{encoding:"utf8",timeout:2e3});return result.status===0&&result.stdout.trim()||void 0}catch{return}}function isProcessOwnerAlive(owner){if(!isAlive(owner.pid))return!1;if(typeof owner.processIdentity!="string")return!0;let current=processIdentity(owner.pid);return current===void 0||current===owner.processIdentity}function isAlive(pid){if(!Number.isSafeInteger(pid)||!pid||pid<=0)return!1;try{if(process.kill(pid,0),process.platform==="linux")try{return!linuxProcessExited(linuxProcessStat(pid))}catch{return!0}return!0}catch(error2){return error2.code==="EPERM"}}function isProcessGroupAlive(group){if(!Number.isSafeInteger(group)||group<1)return!1;if(process.platform==="win32")return!0;let probe=()=>{try{return process.kill(-group,0),!0}catch(error2){return error2.code==="ESRCH"?!1:void 0}},present=probe();if(present!==!0)return present!==!1;if(process.platform!=="linux")return!0;let exitedMembers=()=>{let members=new Set;try{for(let name of readdirSync("/proc"))if(/^\d+$/.test(name))try{let stat2=linuxProcessStat(Number(name));if(stat2.group!==group)continue;if(!linuxProcessExited(stat2))return;members.add(`${name}:${stat2.identity}`)}catch(error2){if(!["ENOENT","ESRCH"].includes(error2.code??""))return}return members}catch{return}},first=exitedMembers();if(!first)return!0;let second=exitedMembers();return second?first.size&&first.size===second.size&&[...first].every(pid=>second.has(pid))?!1:probe()!==!1:!0}var init_process=__esm({"../daemon-core/dist/process.js"(){"use strict"}});import{join}from"node:path";import{homedir}from"node:os";import{createHash}from"node:crypto";function hashKey(key2){return createHash("sha256").update(key2).digest("hex").slice(0,16)}function keyedDir(subdir){return join(DAEMON_HOME,subdir)}function keyedConfigFile(subdir,key2){return join(keyedDir(subdir),`${hashKey(key2)}.json`)}var DAEMON_HOME,init_paths=__esm({"../daemon-core/dist/paths.js"(){"use strict";DAEMON_HOME=join(homedir(),".mearl")}});import{closeSync,existsSync,linkSync,openSync,statSync,mkdirSync,readFileSync as readFileSync2,writeFileSync,renameSync,rmSync,readdirSync as readdirSync2}from"node:fs";import{dirname,join as join2}from"node:path";import{randomUUID}from"node:crypto";function ensureDir(dir){existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}function pauseForLock(){Atomics.wait(lockWaitBuffer,0,0,LOCK_WAIT_MS)}function readRecordUnlocked(file){try{if(!existsSync(file))return null;let parsed=JSON.parse(readFileSync2(file,"utf-8"));return parsed&&typeof parsed.pid=="number"?parsed:null}catch{return null}}function removeRecordUnlocked(file){rmSync(file,{force:!0})}function writeRecordUnlocked(file,record2){let tmp=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify(record2),{mode:384}),renameSync(tmp,file)}catch(error2){try{rmSync(tmp,{force:!0})}catch{}throw error2}}function removeStaleLock(lockDir){let ownerFile=join2(lockDir,"owner.json"),owner=readRecordUnlocked(ownerFile);if(owner){if(isAlive(owner.pid))return!1}else try{if(Date.now()-statSync(lockDir).mtimeMs<OWNER_WRITE_GRACE_MS)return!1}catch{return!0}try{return rmSync(lockDir,{recursive:!0,force:!0}),!0}catch{return!1}}function withRecordLock(file,operation){ensureDir(dirname(file));let lockDir=`${file}.registry.lock`,ownerFile=join2(lockDir,"owner.json"),token=randomUUID(),deadline=Date.now()+LOCK_TIMEOUT_MS;for(;;){try{mkdirSync(lockDir,{mode:448})}catch(error2){if(error2.code!=="EEXIST")throw error2;if(!removeStaleLock(lockDir)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for registry lock: ${file}`,{cause:error2});pauseForLock()}continue}let ownerFd=null;try{ownerFd=openSync(ownerFile,"wx",384),writeFileSync(ownerFd,JSON.stringify({pid:process.pid,token}))}catch(error2){if(ownerFd!==null&&closeSync(ownerFd),ownerFd=null,error2.code==="EEXIST"){if(Date.now()>=deadline)throw new Error(`Timed out acquiring registry lock: ${file}`,{cause:error2});pauseForLock();continue}throw error2}finally{ownerFd!==null&&closeSync(ownerFd)}try{return operation()}finally{readRecordUnlocked(ownerFile)?.token===token&&rmSync(lockDir,{recursive:!0,force:!0})}}}function writeRecord(file,record2){withRecordLock(file,()=>writeRecordUnlocked(file,record2))}function claimRecord(file,record2){return withRecordLock(file,()=>{let candidate=`${file}.${process.pid}.${randomUUID()}.claim`;try{return writeFileSync(candidate,JSON.stringify(record2),{mode:384}),linkSync(candidate,file),!0}catch(error2){if(error2.code==="EEXIST")return!1;throw error2}finally{rmSync(candidate,{force:!0})}})}function readRecord(file){return readRecordUnlocked(file)}function removeRecordIfPid(file,pid){try{return withRecordLock(file,()=>readRecordUnlocked(file)?.pid!==pid?!1:(removeRecordUnlocked(file),!0))}catch{return!1}}function writeRecordIfPid(file,pid,record2){return withRecordLock(file,()=>readRecordUnlocked(file)?.pid!==pid?!1:(writeRecordUnlocked(file,record2),!0))}function removeInvalidRecord(file){try{return withRecordLock(file,()=>!existsSync(file)||readRecordUnlocked(file)?!1:(removeRecordUnlocked(file),!0))}catch{return!1}}function listRecordFiles(dir){try{return readdirSync2(dir).filter(name=>name.endsWith(".json")).map(name=>join2(dir,name))}catch{return[]}}function readLiveRecords(dir){let out=[];for(let file of listRecordFiles(dir)){let rec=readRecord(file);rec&&isAlive(rec.pid)?out.push(rec):rec?removeRecordIfPid(file,rec.pid):removeInvalidRecord(file)}return out}var LOCK_WAIT_MS,LOCK_TIMEOUT_MS,OWNER_WRITE_GRACE_MS,lockWaitBuffer,init_registry=__esm({"../daemon-core/dist/registry.js"(){"use strict";init_process();LOCK_WAIT_MS=10,LOCK_TIMEOUT_MS=5e3,OWNER_WRITE_GRACE_MS=1e3,lockWaitBuffer=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))}});import{existsSync as existsSync2,statSync as statSync2,renameSync as renameSync2,readFileSync as readFileSync3,readdirSync as readdirSync3,rmSync as rmSync2}from"node:fs";import{join as join3}from"node:path";function rotateLogIfNeeded(logFile,maxBytes=DEFAULT_MAX_LOG_BYTES){try{if(!existsSync2(logFile)||statSync2(logFile).size<maxBytes)return;renameSync2(logFile,`${logFile}.1`)}catch{}}var DEFAULT_MAX_LOG_BYTES,init_log=__esm({"../daemon-core/dist/log.js"(){"use strict";DEFAULT_MAX_LOG_BYTES=5*1024*1024}});import{spawn}from"node:child_process";import{closeSync as closeSync2,openSync as openSync2}from"node:fs";import{dirname as dirname2}from"node:path";var init_daemon=__esm({"../daemon-core/dist/daemon.js"(){"use strict";init_process();init_registry();init_log()}});import fs from"node:fs";import path from"node:path";import{spawn as spawn2}from"node:child_process";import{AsyncLocalStorage}from"node:async_hooks";function versionManagerExecutableCandidates(home,names,options={}){let env=options.env??process.env,platform=options.platform??process.platform,readdirSync8=options.readdirSync??fs.readdirSync,fnmDefaultRoot=env.XDG_DATA_HOME?path.join(env.XDG_DATA_HOME,"fnm"):platform==="darwin"?path.join(home,"Library","Application Support","fnm"):platform==="win32"&&env.APPDATA?path.join(env.APPDATA,"fnm"):path.join(home,".local","share","fnm");return[path.join(env.NVM_DIR||path.join(home,".nvm"),"versions","node"),path.join(env.FNM_DIR||fnmDefaultRoot,"node-versions"),path.join(home,".fnm","node-versions")].filter((root,index,all)=>all.indexOf(root)===index).flatMap(root=>{try{return readdirSync8(root,{withFileTypes:!0}).filter(entry=>entry.isDirectory()).sort((left,right)=>right.name.localeCompare(left.name,void 0,{numeric:!0})).flatMap(entry=>names.flatMap(name=>[path.join(root,entry.name,"bin",name),path.join(root,entry.name,"installation","bin",name)]))}catch{return[]}})}function resolveSpawnCommand(executable,args,platform=process.platform,commandInterpreter=process.env.ComSpec){return platform==="win32"&&/\.(?:cmd|bat)$/i.test(executable)?{command:commandInterpreter||"cmd.exe",args:["/d","/s","/c",executable,...args]}:{command:executable,args}}function prependNodePath(env=process.env,nodeExecutable=process.execPath){return prependPathDirectory(path.dirname(nodeExecutable),env)}function prependPathDirectory(directory,env=process.env){let pathKey=Object.keys(env).find(key2=>key2.toLowerCase()==="path")||"PATH",entries=(env[pathKey]||"").split(path.delimiter).filter(Boolean);return entries.includes(directory)?env:{...env,[pathKey]:[directory,...entries].join(path.delimiter)}}function npmExecEnvironment(env=process.env){return Object.fromEntries(Object.entries(env).filter(([key2])=>key2.toLowerCase()!=="npm_config_package"))}var ownedCommands,init_command=__esm({"../daemon-core/dist/command.js"(){"use strict";init_process();ownedCommands=new AsyncLocalStorage}});var init_dist=__esm({"../daemon-core/dist/index.js"(){"use strict";init_process();init_paths();init_registry();init_log();init_daemon();init_command()}});function isAppBridgeBehavior(value){return typeof value=="string"&&/^[a-zA-Z][a-zA-Z0-9_.:-]{0,95}$/.test(value)}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function invalid(path7){throw new Error(`Invalid app profile: ${path7}`)}function text(value){return typeof value=="string"&&value.length<=4096&&Array.from(value).every(character=>character.charCodeAt(0)>8)}function strings(value){return Array.isArray(value)&&value.length<=200&&value.every(text)}function fields(value,required,optional,path7){(!record(value)||required.some(key2=>!Object.hasOwn(value,key2))||Object.keys(value).some(key2=>!required.includes(key2)&&!optional.includes(key2)))&&invalid(path7)}function stringMap(value){return record(value)&&Object.keys(value).length<=200&&Object.values(value).every(text)}function json(value,depth=0){return depth>25?!1:value===null||typeof value=="boolean"||text(value)?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.length<=1e3&&value.every(item=>json(item,depth+1)):record(value)&&Object.entries(value).every(([key2,item])=>!["__proto__","prototype","constructor"].includes(key2)&&json(item,depth+1))}function validateActions(value){let arrays=["open","close","title","navigationBar","statusBar","systemInfo","protocol","kvGet","kvSet","kvDelete","pageContext","noop","silent"];fields(value,["open","close","title","systemInfo","protocol","noop"],[...arrays,"responses","behaviors"],"actions");for(let key2 of arrays)value[key2]!==void 0&&!strings(value[key2])&&invalid(`actions.${key2}`);value.responses!==void 0&&!record(value.responses)&&invalid("actions.responses"),value.behaviors!==void 0&&(!stringMap(value.behaviors)||!Object.values(value.behaviors).every(item=>isAppBridgeBehavior(item)))&&invalid("actions.behaviors")}function validateAppProfileDefinition(value){json(value)||invalid("JSON"),JSON.stringify(value).length>65536&&invalid("definition exceeds 64 KiB"),fields(value,["name","label","appName","defaultAppVersion","uaTokens","globals","bridges","activeEvents","actions","schemes"],["usage","actionIcon","labels","pageRuntime","uaFamily","uaTemplate","policies","settings","settingsGroup","settingsUi","authorization","miniProgram","imagePicker","urlSyncHostSuffixes","overlay","popBeforeOpenParam","messageEvent","nativeBack","layerUrlProxy","rootContainer","titleBarHiddenPathnames","statusBarBackgroundColors","titleBarHostStyles","runtimeOptions"],"definition");for(let key2 of["name","label","appName","defaultAppVersion"])(!text(value[key2])||!value[key2])&&invalid(key2);if(/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)?$/.test(value.name)||invalid("name"),value.usage!==void 0){let usage=value.usage;fields(usage,[],["description","limitations","skills","documentation"],"usage"),new TextEncoder().encode(JSON.stringify(usage)).byteLength>4096&&invalid("usage exceeds 4 KiB"),usage.description!==void 0&&(!text(usage.description)||usage.description.length>512)&&invalid("usage.description");for(let key2 of["limitations","skills"]){let items=usage[key2];items!==void 0&&(!Array.isArray(items)||items.length>8||items.some(item=>!text(item)||!item||item.length>256))&&invalid(`usage.${key2}`)}if(usage.documentation!==void 0){(!Array.isArray(usage.documentation)||usage.documentation.length>8)&&invalid("usage.documentation");for(let link of usage.documentation){fields(link,["title","url"],[],"usage.documentation"),(!text(link.title)||!link.title||link.title.length>128||!text(link.url)||link.url.length>1024)&&invalid("usage.documentation");let url;try{url=new URL(link.url)}catch{invalid("usage.documentation.url")}(url.protocol!=="https:"||url.username||url.password)&&invalid("usage.documentation.url")}}}if(value.pageRuntime!==void 0){fields(value.pageRuntime,["id","sha256"],[],"pageRuntime");let runtime=value.pageRuntime;(typeof runtime.id!="string"||!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(runtime.id)||typeof runtime.sha256!="string"||!/^[a-f0-9]{64}$/.test(runtime.sha256))&&invalid("pageRuntime")}for(let key2 of["uaTokens","activeEvents","urlSyncHostSuffixes","titleBarHiddenPathnames"])value[key2]!==void 0&&!strings(value[key2])&&invalid(key2);stringMap(value.globals)||invalid("globals"),(!Array.isArray(value.bridges)||value.bridges.length>20)&&invalid("bridges");let globals=new Set;for(let bridge of value.bridges)fields(bridge,["global","style"],["persistent"],"bridges"),(!text(bridge.global)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(bridge.global)||bridge.global.split(".").some(part=>["__proto__","prototype","constructor"].includes(part))||globals.has(bridge.global)||typeof bridge.style!="string"||!/^[a-zA-Z][a-zA-Z0-9-]{0,63}$/.test(bridge.style)||bridge.persistent!==void 0&&typeof bridge.persistent!="boolean")&&invalid("bridge"),globals.add(bridge.global);if(validateActions(value.actions),value.labels!==void 0&&(fields(value.labels,["en"],["zh_CN"],"labels"),(!text(value.labels.en)||!value.labels.en||value.labels.en.length>120||value.labels.zh_CN!==void 0&&(!text(value.labels.zh_CN)||value.labels.zh_CN.length>120))&&invalid("labels")),value.actionIcon!==void 0&&(typeof value.actionIcon!="string"||value.actionIcon.length>32768||!/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(value.actionIcon))&&invalid("actionIcon"),value.authorization!==void 0&&(!record(value.authorization)||Object.keys(value.authorization).sort().join(",")!=="hook,method"||typeof value.authorization.hook!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,95}$/.test(value.authorization.hook)||typeof value.authorization.method!="string"||!value.authorization.method||value.authorization.method.length>200)&&invalid("authorization"),value.settingsUi!==void 0&&value.settingsUi!=="runtime")throw new Error("Invalid App settings UI");if(value.settingsGroup!==void 0&&(typeof value.settingsGroup!="string"||value.settingsGroup.length>64)&&invalid("settingsGroup"),value.uaFamily!==void 0&&(typeof value.uaFamily!="string"||value.uaFamily.length>64)&&invalid("uaFamily"),value.uaTemplate!==void 0&&(fields(value.uaTemplate,["ios","android"],[],"uaTemplate"),(!text(value.uaTemplate.ios)||!text(value.uaTemplate.android))&&invalid("uaTemplate")),value.policies!==void 0){fields(value.policies,[],["titleBar","navigatorLanguage","networkResult","languages","defaultLanguage"],"policies");let p=value.policies;p.titleBar!==void 0&&(typeof p.titleBar!="string"||p.titleBar.length>64)&&invalid("policies.titleBar"),p.networkResult!==void 0&&(typeof p.networkResult!="string"||p.networkResult.length>64)&&invalid("policies.networkResult"),p.navigatorLanguage!==void 0&&typeof p.navigatorLanguage!="boolean"&&invalid("policies.navigatorLanguage"),p.languages!==void 0&&(!strings(p.languages)||!p.languages.length)&&invalid("policies.languages"),p.defaultLanguage!==void 0&&(!text(p.defaultLanguage)||p.languages&&!p.languages.includes(p.defaultLanguage))&&invalid("policies.defaultLanguage")}(!Array.isArray(value.schemes)||value.schemes.length>100)&&invalid("schemes");for(let rule of value.schemes){fields(rule,["match"],["hostSuffixes","param","useCurrentOrigin","targetPath","targetHostPrefix","targetParams"],"scheme");for(let key2 of["match","param","targetPath","targetHostPrefix"])rule[key2]!==void 0&&!text(rule[key2])&&invalid(`scheme.${key2}`);rule.hostSuffixes!==void 0&&!strings(rule.hostSuffixes)&&invalid("scheme.hostSuffixes"),rule.useCurrentOrigin!==void 0&&typeof rule.useCurrentOrigin!="boolean"&&invalid("scheme.useCurrentOrigin"),rule.targetParams!==void 0&&!stringMap(rule.targetParams)&&invalid("scheme.targetParams")}if(value.settings!==void 0){(!Array.isArray(value.settings)||value.settings.length>30)&&invalid("settings");let ids=new Set;for(let setting of value.settings){if(fields(setting,["id","label","type","target"],["choices","minimum","maximum"],"setting"),(!text(setting.id)||!/^[a-z][a-zA-Z0-9-]*$/.test(setting.id)||ids.has(setting.id)||!text(setting.label)||!["select","boolean","number","text","json"].includes(setting.type))&&invalid("setting"),ids.add(setting.id),record(setting.target)&&setting.target.option!==void 0)fields(setting.target,["option"],[],"setting.target"),setting.target.option!=="language"&&invalid("setting.target.option");else{fields(setting.target,["method"],["field"],"setting.target"),(!text(setting.target.method)||!setting.target.method||["__proto__","prototype","constructor"].includes(setting.target.method)||setting.target.field!==void 0&&(!text(setting.target.field)||["__proto__","prototype","constructor"].includes(setting.target.field)))&&invalid("setting.target.method");let method=setting.target.method;["open","close","title","navigationBar","statusBar","systemInfo","protocol","kvGet","kvSet","kvDelete","pageContext"].some(key2=>value.actions[key2]?.includes(method))&&invalid("setting targets a structural method")}setting.choices!==void 0&&(!Array.isArray(setting.choices)||!setting.choices.length||setting.choices.some(choice=>!record(choice)||!text(choice.label)||!text(choice.value)))&&invalid("setting.choices");for(let key2 of["minimum","maximum"])setting[key2]!==void 0&&typeof setting[key2]!="number"&&invalid(`setting.${key2}`);setting.type==="select"&&!Array.isArray(setting.choices)&&invalid("setting.choices required"),setting.minimum!==void 0&&setting.maximum!==void 0&&setting.minimum>setting.maximum&&invalid("setting range"),"option"in setting.target&&!["select","text"].includes(setting.type)&&invalid("setting.option type")}}value.runtimeOptions!==void 0&&(!record(value.runtimeOptions)||!json(value.runtimeOptions))&&invalid("runtimeOptions");for(let key2 of["popBeforeOpenParam","messageEvent"])value[key2]!==void 0&&!text(value[key2])&&invalid(key2);return value.statusBarBackgroundColors!==void 0&&!stringMap(value.statusBarBackgroundColors)&&invalid("statusBarBackgroundColors"),validateStructuredOptions(value),JSON.parse(JSON.stringify(value))}function validateStructuredOptions(value){let shapes={nativeBack:[[],["event","controlFunction","handler"]],layerUrlProxy:[["sourceHostPrefix","pathPrefix","targetHostSuffixes"],["defaultTargetHost"]],imagePicker:[["schemes","api","version","fcId","fcGroup","uploadUrlFunction","prefix","region"],[]],overlay:[["enabledParam","topRatioParam","radiusParam","maskAlphaParam","tapCloseParam","defaultTopRatio","defaultRadius","defaultMaskAlpha","defaultTapClose"],["heightRatioParam","tapCloseSelectors","silentTapClose","maxWidthPx","maxWidthMinAppVersion"]]};for(let[key2,[required,optional]]of Object.entries(shapes))if(value[key2]!==void 0){fields(value[key2],required,optional,key2);for(let[field,item]of Object.entries(value[key2]))(field==="maxWidthPx"?typeof item=="number"&&Number.isFinite(item)&&item>0:field==="maxWidthMinAppVersion"?typeof item=="string"&&/^\d+(?:\.\d+)*$/.test(item):field.startsWith("default")&&field!=="defaultTargetHost"?field==="defaultTapClose"?typeof item=="boolean":typeof item=="number":field==="silentTapClose"?typeof item=="boolean":["schemes","targetHostSuffixes","tapCloseSelectors"].includes(field)?strings(item):text(item))||invalid(`${key2}.${field}`)}if(value.rootContainer!==void 0&&(fields(value.rootContainer,[],["statusBarHeightCookie"],"rootContainer"),value.rootContainer.statusBarHeightCookie!==void 0&&(fields(value.rootContainer.statusBarHeightCookie,["name"],["domain","path"],"rootContainer.statusBarHeightCookie"),Object.values(value.rootContainer.statusBarHeightCookie).every(text)||invalid("rootContainer.statusBarHeightCookie"))),value.titleBarHostStyles!==void 0&&(!Array.isArray(value.titleBarHostStyles)||value.titleBarHostStyles.some(rule=>(fields(rule,["hostSuffix"],["titleBarBackgroundColor","statusBarBackgroundColor"],"titleBarHostStyle"),!Object.values(rule).every(text))))&&invalid("titleBarHostStyles"),value.miniProgram!==void 0){fields(value.miniProgram,[],["paymentRoutes","nativeRoutes","messageRules"],"miniProgram");let shapes2={paymentRoutes:[["pathname","paymentParamsParam","successUrlParams","failureUrlParams"],["hostSuffixes","successResultParam","forwardParams","useCurrentOrigin"]],nativeRoutes:[["pathname","actions"],["hostSuffixes"]],messageRules:[["type","action"],["hostSuffixes"]]};for(let[key2,list]of Object.entries(value.miniProgram)){(!Array.isArray(list)||list.length>100)&&invalid(`miniProgram.${key2}`);for(let rule of list){fields(rule,...shapes2[key2],`miniProgram.${key2}`);for(let[field,item]of Object.entries(rule))(["hostSuffixes","successUrlParams","failureUrlParams","forwardParams","actions"].includes(field)?!strings(item):field==="useCurrentOrigin"?typeof item!="boolean":!text(item))&&invalid(`miniProgram.${key2}.${field}`);key2==="messageRules"&&!["stageBackData","closeAll"].includes(rule.action)&&invalid("miniProgram.messageRules.action"),key2==="nativeRoutes"&&!rule.actions.every(action=>["navigateMiniProgram","subscribeMessage"].includes(action))&&invalid("miniProgram.nativeRoutes.actions")}}}}function validateAppProfileContribution(value){if(value===void 0)return;fields(value,["version","profiles"],[],"contribution"),(value.version!==1||!Array.isArray(value.profiles)||!value.profiles.length||value.profiles.length>20)&&invalid("contribution");let profiles=value.profiles.map(validateAppProfileDefinition);return JSON.stringify(profiles).length>256e3&&invalid("contribution exceeds 256 KiB"),profiles.some(profile=>profile.name.includes("/"))&&invalid("contribution names must be local identifiers"),new Set(profiles.map(profile=>profile.name)).size!==profiles.length&&invalid("duplicate profile name"),{version:1,profiles}}var init_appProfileDefinition=__esm({"../browser-core/dist/appProfileDefinition.js"(){"use strict"}});var init_types=__esm({"../browser-core/dist/types.js"(){"use strict"}});var init_deviceEnvironmentObservation=__esm({"../browser-core/dist/deviceEnvironmentObservation.js"(){"use strict"}});var init_browserEnhancement=__esm({"../browser-core/dist/browserEnhancement.js"(){"use strict";init_deviceEnvironmentObservation()}});function parseBrowserListParams(value){if(value===void 0)return;if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid browser_list request");let keys=Object.keys(value);if(!keys.length)return;let params=value,form=params.launchForm;if(keys.some(key2=>key2!=="provider"&&key2!=="launchForm")||typeof params.provider!="string"||!params.provider.trim()||!form||typeof form!="object"||Array.isArray(form)||Object.keys(form).some(key2=>key2!=="variant"&&key2!=="values")||form.variant!==void 0&&typeof form.variant!="string"||!form.values||typeof form.values!="object"||Array.isArray(form.values))throw new Error("browser_list discovery requires provider and launchForm with values");return params}var init_browserDiscovery=__esm({"../browser-core/dist/browserDiscovery.js"(){"use strict"}});var init_providerAppResources=__esm({"../browser-core/dist/providerAppResources.js"(){"use strict"}});var init_capture=__esm({"../browser-core/dist/capture.js"(){"use strict"}});var init_eventFilters=__esm({"../browser-core/dist/eventFilters.js"(){"use strict";init_capture()}});var init_dataStructure=__esm({"../browser-core/dist/dataStructure.js"(){"use strict"}});var init_requestSerializer=__esm({"../browser-core/dist/requestSerializer.js"(){"use strict";init_dataStructure()}});var textEncoder,init_boundedRequestBuffer=__esm({"../browser-core/dist/boundedRequestBuffer.js"(){"use strict";textEncoder=new TextEncoder}});var ALLOWED_ORIGINS,ALLOWED_ORIGINS_LIST,init_proxyPermissions=__esm({"../browser-core/dist/proxyPermissions.js"(){"use strict";ALLOWED_ORIGINS=["*://localhost/*","*://127.0.0.1/*"],ALLOWED_ORIGINS_LIST=[...ALLOWED_ORIGINS]}});var init_domTyping=__esm({"../browser-core/dist/domTyping.js"(){"use strict"}});var init_domSelectors=__esm({"../browser-core/dist/domSelectors.js"(){"use strict"}});function scrollElementInPage(direction,distance,targetLabel,containerPolicy="self"){let element=this?.nodeType===3?this.parentElement:this,targetDocument=element?.nodeType===9?element:null;if(targetDocument&&(element=targetDocument.scrollingElement),!element||element.isConnected===!1)return{error:"Cannot resolve scroll container: "+targetLabel};let startingElement=element,ancestorDistance=0;function scrollMetrics(candidate){let scrollTop=Number(candidate?.scrollTop),scrollHeight=Number(candidate?.scrollHeight),clientHeight=Number(candidate?.clientHeight);if(!Number.isFinite(scrollTop)||!Number.isFinite(scrollHeight)||!Number.isFinite(clientHeight))return null;let ownerDocument=candidate.ownerDocument,isRootScroller=!!ownerDocument&&candidate===ownerDocument.scrollingElement,maxScrollTop=Math.max(0,scrollHeight-clientHeight),overflowAllowsScroll=!0;try{let overflowY=ownerDocument?.defaultView?.getComputedStyle(candidate).overflowY;!isRootScroller&&(overflowY==="visible"||overflowY==="clip")&&(overflowAllowsScroll=!1)}catch{}return{scrollTop,scrollHeight,clientHeight,maxScrollTop,isRootScroller,usable:isRootScroller||maxScrollTop>0&&overflowAllowsScroll}}function documentFallback(documentRef){let windowRef=documentRef.defaultView,visited=new Set,viewportWidth=Number(windowRef?.innerWidth)||Number(element?.clientWidth)||0,viewportHeight=Number(windowRef?.innerHeight)||Number(element?.clientHeight)||0,points=[[viewportWidth/2,viewportHeight/2],[viewportWidth/2,viewportHeight*.75],[viewportWidth/2,viewportHeight*.25]];function containerDepth(candidate){if(candidate===documentRef.body||candidate===documentRef.documentElement)return 0;let depth=0,cursor=candidate;for(;cursor&&cursor!==documentRef.body&&cursor!==documentRef.documentElement;)depth+=1,cursor=cursor.parentElement;return depth}function canMove(metrics2){return direction==="up"||direction==="top"?metrics2.scrollTop>0:metrics2.scrollTop<metrics2.maxScrollTop}let sampledPageContainer;for(let[x,y]of points){let candidate=null;try{candidate=documentRef.elementFromPoint?.(x,y)??null}catch{}for(;candidate&&candidate.nodeType===1;){if(!visited.has(candidate)){visited.add(candidate);let candidateMetrics=scrollMetrics(candidate);if(candidateMetrics?.usable&&candidateMetrics.maxScrollTop>0&&canMove(candidateMetrics)){let resolved={element:candidate,metrics:candidateMetrics,distance:containerDepth(candidate)};if(candidate===documentRef.body||candidate===documentRef.documentElement)sampledPageContainer??=resolved;else return resolved}}candidate=candidate.parentElement}}if(sampledPageContainer)return sampledPageContainer;let best,candidates=Array.from(documentRef.querySelectorAll?.("*")??[]).slice(0,1e4);for(let candidate of candidates){let candidateMetrics=scrollMetrics(candidate);if(!candidateMetrics?.usable||candidateMetrics.maxScrollTop<=0||!canMove(candidateMetrics))continue;let rect,style;try{rect=candidate.getBoundingClientRect(),style=windowRef?.getComputedStyle(candidate)}catch{continue}if(!rect||rect.width<=0||rect.height<=0||style?.display==="none"||style?.visibility==="hidden"||style?.visibility==="collapse")continue;let visibleWidth=Math.max(0,Math.min(rect.right,viewportWidth)-Math.max(rect.left,0)),visibleHeight=Math.max(0,Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0)),area=visibleWidth*visibleHeight;if(area<=0)continue;let depth=containerDepth(candidate);(!best||depth<best.distance||depth===best.distance&&area>best.area)&&(best={element:candidate,metrics:candidateMetrics,distance:depth,area})}return best?{element:best.element,metrics:best.metrics,distance:best.distance}:null}function selectorFor(candidate){let documentRef=candidate?.ownerDocument;if(!documentRef||candidate.nodeType!==1)return"";if(candidate===documentRef.documentElement)return"html";if(candidate===documentRef.body)return"body";let escapeCss=value=>documentRef.defaultView?.CSS?.escape?documentRef.defaultView.CSS.escape(value):value.replace(/[^a-zA-Z0-9_-]/g,character=>"\\"+character);if(candidate.id){let idSelector="#"+escapeCss(String(candidate.id));try{if(documentRef.querySelectorAll(idSelector).length===1)return idSelector}catch{}}let path7=[],cursor=candidate;for(;cursor&&cursor.nodeType===1&&path7.length<8;){let tag=String(cursor.tagName||"").toLowerCase();if(!tag)break;let parent=cursor.parentElement;if(!parent){path7.unshift(tag);break}let siblings=Array.from(parent.children).filter(sibling=>sibling.tagName===cursor.tagName),index=siblings.indexOf(cursor)+1;if(path7.unshift(siblings.length>1?tag+":nth-of-type("+index+")":tag),cursor=parent,cursor===documentRef.documentElement){path7.unshift("html");break}}return path7.join(" > ")}let metrics=scrollMetrics(element);if(!metrics)return{error:"Element is not scrollable: "+targetLabel};if(targetDocument){let fallback=documentFallback(targetDocument);fallback&&(element=fallback.element,metrics=fallback.metrics,ancestorDistance=fallback.distance)}if(!metrics.usable&&containerPolicy==="nearest"){let candidate=element.parentElement;for(;candidate;){ancestorDistance+=1;let candidateMetrics=scrollMetrics(candidate);if(candidateMetrics?.usable){element=candidate,metrics=candidateMetrics;break}candidate=candidate.parentElement}}if(!metrics.usable&&!metrics.isRootScroller)return{error:"Element is not scrollable: "+targetLabel+(containerPolicy==="nearest"?" (no scrollable ancestor found)":"")};let targetTop;switch(direction){case"top":targetTop=0;break;case"bottom":targetTop=metrics.maxScrollTop;break;case"up":targetTop=Math.max(0,metrics.scrollTop-Math.abs(distance));break;default:targetTop=Math.min(metrics.maxScrollTop,metrics.scrollTop+Math.abs(distance));break}if(typeof element.scrollTo=="function")try{element.scrollTo({top:targetTop,left:Number(element.scrollLeft)||0,behavior:"instant"})}catch{element.scrollTop=targetTop}else element.scrollTop=targetTop;let actualScrollTop=Number(element.scrollTop);return!metrics.isRootScroller&&targetTop!==metrics.scrollTop&&actualScrollTop===metrics.scrollTop?{error:"Element is not scrollable: "+targetLabel}:{scrollY:Math.round(actualScrollTop),scrollHeight:metrics.scrollHeight,clientHeight:metrics.clientHeight,maxScrollY:Math.round(metrics.maxScrollTop),scrollYBefore:Math.round(metrics.scrollTop),scrollYAfter:Math.round(actualScrollTop),moved:actualScrollTop!==metrics.scrollTop,atTop:actualScrollTop<=0,atBottom:actualScrollTop>=metrics.maxScrollTop,target:targetLabel,resolvedContainer:targetDocument&&element===targetDocument.body&&element!==startingElement?"document-body":targetDocument&&element!==startingElement?"document-descendant":element===startingElement?"self":"nearest-scrollable-ancestor",ancestorDistance,...targetDocument&&element!==startingElement?{containerSelector:selectorFor(element)}:{}}}var SCROLL_ELEMENT_IN_PAGE_SOURCE,init_domScrolling=__esm({"../browser-core/dist/domScrolling.js"(){"use strict";init_domSelectors();SCROLL_ELEMENT_IN_PAGE_SOURCE=scrollElementInPage.toString()}});function inspectElementsInPage(selector,filter,styles,maxResults,invalidSelectorHint,includeOuterHTML=!1){let context=this?.nodeType===3?this.parentElement:this,documentRef=context?.nodeType===9?context:context?.ownerDocument;if(!documentRef)return{error:"page_inspect cannot resolve the target document"};let scanLimit=1e4,candidates;if(context?.nodeType===9){let effectiveSelector=selector??"*";try{candidates=Array.from(documentRef.querySelectorAll(effectiveSelector))}catch(error2){return{error:'Invalid CSS selector "'+effectiveSelector+'": '+(error2 instanceof Error?error2.message:String(error2))+". "+invalidSelectorHint}}}else if(context?.nodeType===1&&context.isConnected!==!1)candidates=[context];else return{error:"page_inspect target is detached from the document"};let candidateCount=candidates.length,scanTruncated=filter!=="all"&&candidateCount>scanLimit;candidates=filter==="all"?candidates.slice(0,maxResults):scanTruncated?candidates.slice(0,scanLimit):candidates;let windowRef=documentRef.defaultView,viewportWidth=Number(windowRef?.innerWidth)||0,viewportHeight=Number(windowRef?.innerHeight)||0;function round(value){return Math.round(value*1e3)/1e3}function controlState(element){let state={};for(let name of["checked","selected","pressed","expanded","disabled","readonly"]){let value=element.getAttribute?.("aria-"+name);(value==="true"||value==="false"||value==="mixed"&&(name==="checked"||name==="pressed"))&&(state[name]={value:value==="mixed"?"mixed":value==="true",source:"aria"})}let tag=String(element.tagName||"").toLowerCase(),type=String(element.type||"").toLowerCase();if(tag==="input"&&(type==="checkbox"||type==="radio")&&(state.checked={value:type==="checkbox"&&element.indeterminate?"mixed":!!element.checked,source:"native"}),tag==="option"&&(state.selected={value:!!element.selected,source:"native"}),["button","input","select","textarea","option","optgroup","fieldset"].includes(tag)){let disabled=element.matches?.(":disabled")??!!element.disabled;(disabled||!state.disabled)&&(state.disabled={value:disabled,source:"native"})}return(tag==="textarea"||tag==="input"&&["text","search","tel","url","email","password","date","month","week","time","datetime-local","number"].includes(type))&&(element.readOnly||!state.readonly)&&(state.readonly={value:!!element.readOnly,source:"native"}),state}function escapeCss(value){return windowRef?.CSS&&typeof windowRef.CSS.escape=="function"?windowRef.CSS.escape(value):value.replace(/[^a-zA-Z0-9_-]/g,character=>"\\"+character)}function selectorFor(element){if(element.id){let idSelector="#"+escapeCss(String(element.id));try{if(documentRef.querySelectorAll(idSelector).length===1)return idSelector}catch{}}let path7=[],cursor=element;for(;cursor&&cursor.nodeType===1&&path7.length<8;){let tag=String(cursor.tagName||"").toLowerCase();if(!tag)break;let parent=cursor.parentElement;if(!parent){path7.unshift(tag);break}let siblings=Array.from(parent.children).filter(sibling=>sibling.tagName===cursor.tagName),index=siblings.indexOf(cursor)+1;if(path7.unshift(siblings.length>1?tag+":nth-of-type("+index+")":tag),cursor=parent,cursor===documentRef.documentElement){path7.unshift("html");break}}return path7.join(" > ")}function readStyle(style,property){let cssValue=style.getPropertyValue?.(property);if(cssValue)return String(cssValue);let camelName=property.replace(/-([a-z])/g,(_match,letter)=>letter.toUpperCase());return String(style[camelName]??"")}function isScrollable(element,style){let canScrollX=Number(element.scrollWidth)>Number(element.clientWidth)&&!["visible","clip"].includes(String(style.overflowX)),canScrollY=Number(element.scrollHeight)>Number(element.clientHeight)&&!["visible","clip"].includes(String(style.overflowY));return canScrollX||canScrollY}function nearestScrollContainer(element){let candidate=element,ancestorDistance=0;for(;candidate&&candidate.nodeType===1;){let style=windowRef.getComputedStyle(candidate);if(isScrollable(candidate,style))return{selector:selectorFor(candidate),tag:String(candidate.tagName||"").toLowerCase(),ancestorDistance,scrollWidth:Number(candidate.scrollWidth)||0,scrollHeight:Number(candidate.scrollHeight)||0,clientWidth:Number(candidate.clientWidth)||0,clientHeight:Number(candidate.clientHeight)||0,scrollLeft:Number(candidate.scrollLeft)||0,scrollTop:Number(candidate.scrollTop)||0,overflowX:String(style.overflowX||""),overflowY:String(style.overflowY||"")};candidate=candidate.parentElement,ancestorDistance+=1}}function hitTargetInfo(element,rect,visible,style){let left=Math.max(0,Number(rect.left)||0),right=Math.min(viewportWidth,Number(rect.right)||0),top=Math.max(0,Number(rect.top)||0),bottom=Math.min(viewportHeight,Number(rect.bottom)||0),x=round(left+Math.max(0,right-left)/2),y=round(top+Math.max(0,bottom-top)/2),hit=null;try{hit=visible?documentRef.elementFromPoint?.(x,y)??null:null;let visited=new Set;for(;hit?.shadowRoot?.elementFromPoint&&!visited.has(hit);){visited.add(hit);let inner=hit.shadowRoot.elementFromPoint(x,y);if(!inner||inner===hit)break;hit=inner}}catch{}let composedHit=hit;for(;composedHit&&composedHit!==element;)composedHit=composedHit.parentElement||composedHit.getRootNode?.().host;let topmost=!!hit&&(!!composedHit||element.contains?.(hit)),target=hit?{selector:selectorFor(hit),tag:String(hit.tagName||"").toLowerCase(),text:String(hit.innerText??hit.textContent??"").trim().replace(/\s+/g," ").slice(0,120)}:void 0;return{point:{x,y},topmost,receivesPointerEvents:visible&&style.pointerEvents!=="none"&&topmost,...target?{target}:{},...!topmost&&target?{occludedBy:target}:{}}}let matches=[],count=filter==="all"?candidateCount:0;for(let element of candidates){let style=windowRef.getComputedStyle(element),scrollWidth=Number(element.scrollWidth)||0,scrollHeight=Number(element.scrollHeight)||0,clientWidth=Number(element.clientWidth)||0,clientHeight=Number(element.clientHeight)||0,horizontalOverflow=Math.max(0,scrollWidth-clientWidth),verticalOverflow=Math.max(0,scrollHeight-clientHeight),scrollable=isScrollable(element,style);if(!(filter==="all"||filter==="overflowing"&&(horizontalOverflow>0||verticalOverflow>0)||filter==="horizontal-overflow"&&horizontalOverflow>0||filter==="vertical-overflow"&&verticalOverflow>0||filter==="scrollable"&&scrollable)||(filter!=="all"&&(count+=1),matches.length>=maxResults))continue;let rect=element.getBoundingClientRect(),opacity=Number(style.opacity),visible=rect.width>0&&rect.height>0&&style.display!=="none"&&style.visibility!=="hidden"&&style.visibility!=="collapse"&&(!Number.isFinite(opacity)||opacity>0)&&rect.right>0&&rect.bottom>0&&rect.left<viewportWidth&&rect.top<viewportHeight,computedStyle={};for(let property of styles)computedStyle[property]=readStyle(style,property);let scrollContainer=nearestScrollContainer(element),hitTest=hitTargetInfo(element,rect,visible,style),state=controlState(element);matches.push({selector:selectorFor(element),tag:String(element.tagName||"").toLowerCase(),text:String(element.innerText??element.textContent??"").trim().replace(/\s+/g," ").slice(0,240),visible,hitTest,...Object.keys(state).length?{state}:{},boundingBox:{x:round(rect.x),y:round(rect.y),width:round(rect.width),height:round(rect.height),top:round(rect.top),right:round(rect.right),bottom:round(rect.bottom),left:round(rect.left)},computedStyle,scroll:{scrollWidth,scrollHeight,clientWidth,clientHeight,overflowX:String(style.overflowX||""),overflowY:String(style.overflowY||""),horizontalOverflow,verticalOverflow},...scrollContainer?{scrollContainer}:{},...includeOuterHTML?{outerHTML:String(element.outerHTML??"").slice(0,3e3)}:{}})}return{...selector!==void 0?{selector}:{},filter,candidateCount,count,matches,truncated:scanTruncated||count>matches.length,...scanTruncated?{scanTruncated:!0}:{}}}var INSPECT_ELEMENTS_IN_PAGE_SOURCE,init_domInspection=__esm({"../browser-core/dist/domInspection.js"(){"use strict";init_domSelectors();INSPECT_ELEMENTS_IN_PAGE_SOURCE=inspectElementsInPage.toString()}});var init_domSnapshot=__esm({"../browser-core/dist/domSnapshot.js"(){"use strict"}});var init_deviceEmulation=__esm({"../browser-core/dist/deviceEmulation.js"(){"use strict"}});var init_debuggerTarget=__esm({"../browser-core/dist/debuggerTarget.js"(){"use strict"}});var SHELL_BODY,MAX_DOCUMENT_BYTES,init_rootWebViewNavigation=__esm({"../browser-core/dist/rootWebViewNavigation.js"(){"use strict";SHELL_BODY=btoa('<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"></head><body></body></html>'),MAX_DOCUMENT_BYTES=16*1024*1024}});var init_axTextMatch=__esm({"../browser-core/dist/axTextMatch.js"(){"use strict"}});var init_domClicking=__esm({"../browser-core/dist/domClicking.js"(){"use strict"}});function dragBetweenPointsInPage(from,points,pointerType){let target=document.elementFromPoint(from.x,from.y);if(!target)return{dragged:!1,steps:0,error:`No element found at drag start point (${from.x}, ${from.y})`};if(points.length===0)return{dragged:!1,steps:0,error:"Drag path must contain at least one point"};let view=target.ownerDocument.defaultView??window,realm=view,pointerId=1,pointerInit=(point,buttons,pressure)=>({bubbles:!0,cancelable:!0,composed:!0,view,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,button:0,buttons,pointerId,pointerType,isPrimary:!0,pressure,width:1,height:1}),dispatchPointer=(type,point,buttons,pressure)=>typeof realm.PointerEvent!="function"?!1:(target.dispatchEvent(new realm.PointerEvent(type,pointerInit(point,buttons,pressure))),!0),dispatchMouse=(type,point,buttons)=>typeof realm.MouseEvent!="function"?!1:(target.dispatchEvent(new realm.MouseEvent(type,{bubbles:!0,cancelable:!0,composed:!0,view,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,button:0,buttons})),!0),createTouch=point=>{let init={identifier:pointerId,target,clientX:point.x,clientY:point.y,screenX:point.x,screenY:point.y,pageX:point.x+view.scrollX,pageY:point.y+view.scrollY,radiusX:1,radiusY:1,rotationAngle:0,force:.5};return typeof realm.Touch=="function"?new realm.Touch(init):init},dispatchTouch=(type,point)=>{if(typeof realm.TouchEvent!="function")return!1;let touch=createTouch(point),activeTouches=type==="touchend"?[]:[touch];return target.dispatchEvent(new realm.TouchEvent(type,{bubbles:!0,cancelable:!0,composed:!0,touches:activeTouches,targetTouches:activeTouches,changedTouches:[touch]})),!0},dispatched=dispatchPointer("pointerdown",from,1,.5);dispatched=pointerType==="touch"?dispatchTouch("touchstart",from)||dispatched:dispatchMouse("mousedown",from,1)||dispatched;for(let point of points)dispatched=dispatchPointer("pointermove",point,1,.5)||dispatched,dispatched=pointerType==="touch"?dispatchTouch("touchmove",point)||dispatched:dispatchMouse("mousemove",point,1)||dispatched;let end=points[points.length-1];return dispatched=pointerType==="touch"?dispatchTouch("touchend",end)||dispatched:dispatchMouse("mouseup",end,0)||dispatched,dispatched=dispatchPointer("pointerup",end,0,0)||dispatched,dispatched?{dragged:!0,steps:points.length}:{dragged:!1,steps:0,error:"This page does not support synthetic drag events"}}var DRAG_BETWEEN_POINTS_IN_PAGE_SOURCE,init_pageDragging=__esm({"../browser-core/dist/pageDragging.js"(){"use strict";DRAG_BETWEEN_POINTS_IN_PAGE_SOURCE=dragBetweenPointsInPage.toString()}});var PAGE_PRESS_KEY_DESCRIPTORS,init_pagePressing=__esm({"../browser-core/dist/pagePressing.js"(){"use strict";PAGE_PRESS_KEY_DESCRIPTORS=Object.freeze({Enter:{key:"Enter",code:"Enter",keyCode:13,text:"\r"},Tab:{key:"Tab",code:"Tab",keyCode:9},Escape:{key:"Escape",code:"Escape",keyCode:27},Backspace:{key:"Backspace",code:"Backspace",keyCode:8},Delete:{key:"Delete",code:"Delete",keyCode:46},ArrowUp:{key:"ArrowUp",code:"ArrowUp",keyCode:38},ArrowDown:{key:"ArrowDown",code:"ArrowDown",keyCode:40},ArrowLeft:{key:"ArrowLeft",code:"ArrowLeft",keyCode:37},ArrowRight:{key:"ArrowRight",code:"ArrowRight",keyCode:39},Home:{key:"Home",code:"Home",keyCode:36},End:{key:"End",code:"End",keyCode:35},PageUp:{key:"PageUp",code:"PageUp",keyCode:33},PageDown:{key:"PageDown",code:"PageDown",keyCode:34},Space:{key:" ",code:"Space",keyCode:32,text:" "}})}});var init_axSnapshot=__esm({"../browser-core/dist/axSnapshot.js"(){"use strict"}});var init_pageObserver=__esm({"../browser-core/dist/pageObserver.js"(){"use strict"}});var init_navigationTracker=__esm({"../browser-core/dist/navigationTracker.js"(){"use strict"}});function resolvePageEvalExpression(params){if(typeof params.expression!="string"||!params.expression.trim())throw new Error("Invalid expression");if(params.args===void 0)return params.expression;if(!Array.isArray(params.args))throw new Error("page_eval args must be an array");return`(${params.expression})(...JSON.parse(${JSON.stringify(JSON.stringify(params.args))}))`}function validatePageUserScriptParams(params){if(!Number.isSafeInteger(params?.tabId)||params.tabId<0)throw new Error("Invalid target tab");if(typeof params.worldId!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(params.worldId))throw new Error("Invalid user script worldId");if(typeof params.code!="string"||!params.code.trim()||params.code.length>256*1024)throw new Error("User script code must be non-empty and within 256 KiB characters")}function actionRequiresTabId(action){return typeof action=="string"&&TAB_ID_REQUIRED_ACTION_SET.has(action)}function validateRequiredActionTabId(action,data){if(action==="get_capabilities"&&data&&typeof data=="object"&&["tabId","tabIds","openerTabId"].some(key2=>Object.hasOwn(data,key2)))throw new Error("get_capabilities does not accept page targets");let cookieAction=action==="get_cookie"||action==="set_cookie";if(!actionRequiresTabId(action)&&!cookieAction)return;let input=data&&typeof data=="object"&&!Array.isArray(data)?data:void 0,tabId=input?.tabId;if(cookieAction&&tabId===void 0){if(action==="set_cookie"&&input?.reload===!0)throw new Error("set_cookie: reload requires tabId");if(typeof input?.url!="string"||!input.url.trim())throw new Error(`${action}: specify url or tabId`);return}if(typeof tabId!="number"||!Number.isSafeInteger(tabId)||tabId<0)throw new Error(`${action} requires a numeric tabId. Call tab_open or tab_list to obtain a tabId.`)}function isBrowserCapabilityAction(value){return typeof value=="string"&&Object.hasOwn(BROWSER_CAPABILITY_ACTIONS,value)}var BROWSER_DEVICE_PRESET_NAMES,TAB_ID_REQUIRED_ACTIONS,TAB_ID_REQUIRED_ACTION_SET,PAGE_ACT_ACTIONS,EXTENSION_BROWSER_ACTIONS,BROWSER_CAPABILITY_ACTIONS,init_browserActionProtocol=__esm({"../browser-core/dist/browserActionProtocol.js"(){"use strict";BROWSER_DEVICE_PRESET_NAMES=["iphone-duo-folded","iphone-duo-unfolded","iphone-17-pro","iphone-17e","pixel-11","ipad-mini-a17-pro","galaxy-s26","pura-x-max","iphone-15-pro","iphone-se","pixel-8","ipad-mini","galaxy-s23"];TAB_ID_REQUIRED_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","set_mock","get_mocks","page_screenshot","tab_close","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_inspect","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_download","page_frames","set_device_emulation","set_app_profile","set_timezone","run_actions"],TAB_ID_REQUIRED_ACTION_SET=new Set(TAB_ID_REQUIRED_ACTIONS);PAGE_ACT_ACTIONS=["page_click","page_drag","page_type","page_hover","page_scroll","page_press","page_upload","page_eval"],EXTENSION_BROWSER_ACTIONS={tab_checkpoint:!0,capture_checkpoint:!0,get_requests:!0,get_logs:!0,get_events:!0,set_mock:!0,get_mocks:!0,set_rule:!0,get_rules:!0,get_capabilities:!0,send_request:!0,browser_release:!0,page_screenshot:!0,tab_open:!0,tab_close:!0,tab_list:!0,tab_group:!0,page_click:!0,page_drag:!0,page_type:!0,page_scroll:!0,page_hover:!0,page_eval:!0,page_runtime:!0,page_inspect:!0,page_snapshot:!0,page_press:!0,page_wait:!0,page_navigate:!0,page_upload:!0,page_frames:!0,set_device_emulation:!0,set_app_profile:!0,set_timezone:!0,get_cookie:!0,set_cookie:!0,request_permission:!0,run_actions:!0},BROWSER_CAPABILITY_ACTIONS={...EXTENSION_BROWSER_ACTIONS,page_download:!0}}});var init_pageAct=__esm({"../browser-core/dist/pageAct.js"(){"use strict";init_pageObserver();init_browserActionProtocol()}});var init_pageDialog=__esm({"../browser-core/dist/pageDialog.js"(){"use strict";init_pageAct()}});var init_backendNodeRefs=__esm({"../browser-core/dist/backendNodeRefs.js"(){"use strict"}});var init_pageEffectRefs=__esm({"../browser-core/dist/pageEffectRefs.js"(){"use strict"}});var init_pageWait=__esm({"../browser-core/dist/pageWait.js"(){"use strict";init_domSelectors()}});var init_pageNavigation=__esm({"../browser-core/dist/pageNavigation.js"(){"use strict"}});var init_tabMatching=__esm({"../browser-core/dist/tabMatching.js"(){"use strict"}});var AGENT_CHAT_MAX_IMAGE_BYTES,AGENT_CHAT_MAX_TOTAL_IMAGE_BYTES,init_agentChat=__esm({"../browser-core/dist/agentChat.js"(){"use strict";AGENT_CHAT_MAX_IMAGE_BYTES=10*1024*1024,AGENT_CHAT_MAX_TOTAL_IMAGE_BYTES=20*1024*1024}});var init_agentSkills=__esm({"../browser-core/dist/agentSkills.js"(){"use strict"}});var init_agentServiceProtocol=__esm({"../browser-core/dist/agentServiceProtocol.js"(){"use strict"}});var init_toolbox=__esm({"../browser-core/dist/toolbox.js"(){"use strict"}});function parseToolboxIcon(value){if(typeof value!="string")return;let icon=value.trim();if(!icon||icon.length>32*1024)return;if(/^[a-z][a-z0-9-]{0,39}$/.test(icon))return{kind:"name",name:icon};if(/^(?:<\?xml\s[^>]*\?>\s*)?<svg\b[^>]*(?:\/>|>[\s\S]*<\/svg\s*>)$/i.test(icon)){let svg=/<svg\b[^>]*\sxmlns\s*=/i.test(icon)?icon:icon.replace(/<svg\b/i,'<svg xmlns="http://www.w3.org/2000/svg"');try{return{kind:"image",src:`data:image/svg+xml,${encodeURIComponent(svg)}`,.../\bcurrentColor\b/i.test(svg)?{monochrome:!0}:{}}}catch{return}}let dataHeader=/^data:image\/(?:svg\+xml|png|jpeg|gif|webp|avif)(?:;charset=utf-8|;utf8)?(?:;base64)?,/i.exec(icon);if(dataHeader&&icon.length>dataHeader[0].length)return{kind:"image",src:icon};try{let url=new URL(icon);if(["http:","https:"].includes(url.protocol)&&!url.username&&!url.password)return{kind:"image",src:url.href}}catch{}}var init_toolboxIcon=__esm({"../browser-core/dist/toolboxIcon.js"(){"use strict"}});var init_pluginExecution=__esm({"../browser-core/dist/pluginExecution.js"(){"use strict"}});function isPluginTaskActive(state){return state==="queued"||state==="running"||state==="cancelling"}function isPluginTaskId(value){return typeof value=="string"&&/^pt_[0-9a-f-]{36}_[0-9a-f-]{36}$/i.test(value)}var init_pluginTasks=__esm({"../browser-core/dist/pluginTasks.js"(){"use strict"}});function isPluginPageInvalidation(error2){let value=error2,codes=["PLUGIN_PAGE_INVALIDATED","PLUGIN_PAGE_NOT_FOUND","PLUGIN_PAGE_TARGET_CHANGED","DOMAIN_PERMISSION_REQUIRED"],message=typeof value?.message=="string"?value.message:"";return codes.includes(String(value?.code))||codes.some(code=>message.startsWith(`${code}:`))}function isPluginPageUnavailable(error2){return error2?.code==="PLUGIN_PAGE_UNAVAILABLE"}function pluginPageUnavailable(error2){return Object.assign(new Error("Plugin page host is temporarily unavailable",{cause:error2}),{code:"PLUGIN_PAGE_UNAVAILABLE"})}function isPluginPageMatchPattern(value){return typeof value=="string"&&value.length<=2048&&pattern.test(value)}function matchesPluginPageURL(matches,value){let url;try{url=new URL(value)}catch{return!1}return["http:","https:"].includes(url.protocol)?matches.some(item=>{let match=item.match(pattern);if(!match||match[1]!=="*"&&match[1].toLowerCase()+":"!==url.protocol)return!1;let host=match[2].toLowerCase();if(host!=="*"&&host!==url.hostname&&!(host.startsWith("*.")&&(url.hostname===host.slice(2)||url.hostname.endsWith(host.slice(1))))||match[3]&&match[3].slice(1)!==(url.port||(url.protocol==="https:"?"443":"80")))return!1;let expression="^"+match[4].split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$";return new RegExp(expression).test(url.pathname+url.search)}):!1}function isPluginPageInstanceId(value){return typeof value=="string"&&/^pi_[0-9a-f-]{36}$/i.test(value)}var pattern,init_pluginPages=__esm({"../browser-core/dist/pluginPages.js"(){"use strict";pattern=/^(https?|\*):\/\/(\*|\*\.[a-z0-9.-]+|[a-z0-9.-]+|localhost)(:\d+)?(\/[^#]*)$/i}});var init_pluginPageRuntime=__esm({"../browser-core/dist/pluginPageRuntime.js"(){"use strict"}});var init_pluginPageHost=__esm({"../browser-core/dist/pluginPageHost.js"(){"use strict";init_pluginPageRuntime();init_pluginPages()}});var init_browserCapabilities=__esm({"../browser-core/dist/browserCapabilities.js"(){"use strict";init_browserActionProtocol()}});var init_runActions=__esm({"../browser-core/dist/runActions.js"(){"use strict";init_browserActionProtocol();init_pageAct()}});var init_sendRequestFiles=__esm({"../browser-core/dist/sendRequestFiles.js"(){"use strict";init_browserActionProtocol()}});var init_sendRequestHeaders=__esm({"../browser-core/dist/sendRequestHeaders.js"(){"use strict";init_sendRequestFiles()}});var init_cookie=__esm({"../browser-core/dist/cookie.js"(){"use strict"}});var init_controlledFavicon=__esm({"../browser-core/dist/controlledFavicon.js"(){"use strict"}});var init_sseParser=__esm({"../browser-core/dist/sseParser.js"(){"use strict"}});var init_mockResponse=__esm({"../browser-core/dist/mockResponse.js"(){"use strict"}});var init_pluginState=__esm({"../browser-core/dist/pluginState.js"(){"use strict"}});var init_pluginModels=__esm({"../browser-core/dist/pluginModels.js"(){"use strict"}});var init_pluginRecovery=__esm({"../browser-core/dist/pluginRecovery.js"(){"use strict"}});var init_pluginDiagnostics=__esm({"../browser-core/dist/pluginDiagnostics.js"(){"use strict"}});var init_rootWebViewDocument=__esm({"../browser-core/dist/rootWebViewDocument.js"(){"use strict"}});var init_extensionServiceProtocol=__esm({"../browser-core/dist/extensionServiceProtocol.js"(){"use strict";init_agentServiceProtocol();init_toolbox()}});var init_requestStreamCapture=__esm({"../browser-core/dist/requestStreamCapture.js"(){"use strict"}});var init_responseText=__esm({"../browser-core/dist/responseText.js"(){"use strict"}});var init_consumeSseResponse=__esm({"../browser-core/dist/consumeSseResponse.js"(){"use strict";init_sseParser()}});var init_queryString=__esm({"../browser-core/dist/queryString.js"(){"use strict"}});var init_extensionVersion=__esm({"../browser-core/dist/extensionVersion.js"(){"use strict"}});var init_nativeHostNames=__esm({"../browser-core/dist/nativeHostNames.js"(){"use strict"}});var init_requestMetadata=__esm({"../browser-core/dist/requestMetadata.js"(){"use strict"}});var init_dist2=__esm({"../browser-core/dist/index.js"(){"use strict";init_appProfileDefinition();init_types();init_browserEnhancement();init_browserDiscovery();init_providerAppResources();init_eventFilters();init_requestSerializer();init_boundedRequestBuffer();init_proxyPermissions();init_domTyping();init_domSelectors();init_domScrolling();init_domInspection();init_domSnapshot();init_deviceEmulation();init_deviceEnvironmentObservation();init_debuggerTarget();init_rootWebViewNavigation();init_axTextMatch();init_domClicking();init_pageDragging();init_pagePressing();init_axSnapshot();init_pageObserver();init_navigationTracker();init_pageAct();init_pageDialog();init_backendNodeRefs();init_pageEffectRefs();init_pageWait();init_pageNavigation();init_tabMatching();init_agentChat();init_agentSkills();init_agentServiceProtocol();init_toolbox();init_toolboxIcon();init_pluginExecution();init_pluginTasks();init_pluginPages();init_pluginPageRuntime();init_pluginPageHost();init_browserActionProtocol();init_browserCapabilities();init_runActions();init_sendRequestFiles();init_sendRequestHeaders();init_cookie();init_controlledFavicon();init_capture();init_sseParser();init_mockResponse();init_pluginState();init_pluginModels();init_pluginRecovery();init_pluginDiagnostics();init_rootWebViewDocument();init_extensionServiceProtocol();init_requestStreamCapture();init_responseText();init_consumeSseResponse();init_queryString();init_extensionVersion();init_nativeHostNames();init_dataStructure();init_requestMetadata()}});var DEVICE_PRESET_TYPE,PAGE_DIAGNOSTICS_PARAM,PAGE_OBSERVE_PARAM,PAGE_ACTION_RESULT,COMMANDS,COMMAND_MAP,init_commands=__esm({"../client/src/commands.ts"(){"use strict";init_dist2();DEVICE_PRESET_TYPE=BROWSER_DEVICE_PRESET_NAMES.map(name=>JSON.stringify(name)).join(" | "),PAGE_DIAGNOSTICS_PARAM={name:"diagnostics",type:"object | boolean",description:"默认关闭;传 true 返回动作期间新增的 error logs/业务 requests,或传对象自定义通道与过滤",details:["logs: boolean | { level, limit, filter };true 默认采集 error 日志","requests: boolean | { count, filter, source, includeBody, includeHeaders, maxBodySize, fields, keysOnly }","events: boolean | { source, event_type, filter, limit, includeRaw };埋点需显式开启","各通道过滤字段同 get_logs / get_requests / get_events;observe=false 时仍返回诊断增量,但不等待 DOM/导航稳定"]},PAGE_OBSERVE_PARAM={name:"observe",type:"object | false",description:"默认开启 DOM/导航观察;传 false 关闭,不影响显式请求的 diagnostics",details:["quietMs: number,DOM 变化后的稳定窗口,默认 100ms","firstChangeTimeoutMs: number,无 DOM 变化时的观察窗口,默认 500ms","timeoutMs: number,DOM 观察阶段最大时间,默认 3000ms","navigationGraceMs: number,低信息量点击/按键的导航宽限,默认 1000ms;相关网络活动可延长宽限","navigationTimeoutMs: number,导航就绪最大等待时间,默认 15000ms","networkIdleMs: number,文档完成且相关请求归零后的静默时间,默认 500ms","contentReadyAfterMs: number,结构稳定兜底保护期,默认 min(5000, navigationTimeoutMs / 2),并限制在导航超时前"]},PAGE_ACTION_RESULT=["默认返回 { action, observation };action.success 只表示动作成功,业务效果需结合 observation 和目标状态判断。","observe=false 且未开启 diagnostics 时返回裸动作结果(如 { clicked: true }),没有 action/observation;开启 diagnostics 时返回 { action, diagnostics }。","包装结果中的 action.stage=precondition 表示未派发,省略 observation/diagnostics;dispatch-uncertain 表示可能已派发,先查看 action.attempt 与可用观察或最小快照核验,避免重复提交。CLI 单次调用失败以退出码 1 结束;脚本需检查 action.success。","observation.effects 返回通知、控件和焦点增量,可直接复用 node.ref/selector;changed=true 且 effects 为空不表示失败。","effects.texts 按需返回普通可见文本的 selector/text,不代表可点击控件或业务成功;超限或覆盖不完整时仍提示补快照。","fullSnapshotRecommended/snapshotReasons 提示是否补充快照;openedTabs 返回可继续操作的 tabId 和 ready。navigation 模式的 ready 表示新页面就绪。","显式开启的诊断通道在 diagnostics 中返回动作期间增量,与 observe 独立。"],COMMANDS=[{name:"get_capabilities",description:"只读查询当前目标浏览器的动作、设备和已安装 App 能力、限制与 Skill/帮助入口;不打开页面或启用模拟",params:[{name:"app",type:"string",description:"可选,使用目录中的完整 App ID 查询桥方法、可调设置和默认版本详情"}],notes:["沿用 --browser / --session 路由;不传 app 返回摘要。apps.status=partial 表示目录未完整取得,unsupported 表示目标未提供目录;不能把两者当作未安装。","available=false 的 App 当前不可启用;支持某个 action 不代表已有域名权限或真实设备授权。按需读取 usage.skills / usage.documentation,查询不会自动安装或加载 Skill。"],examples:["get_capabilities",`get_capabilities --payload '{"app":"example/app"}'`]},{name:"browser_control",description:"把控制会话交给用户;用户在 Mearl 浏览器管理页交还后重新观察页面",params:[{name:"operation",type:'"handoff" | "resume"',required:!0,description:"交给用户操作;resume 仅在用户明确交还后使用"},{name:"tabId",type:"number",description:"可选的目标页面"},{name:"reason",type:"string",description:"用户需要处理的事项"}],notes:["必须携带 --session;接管停止后续派发,已经发出的操作可能仍然生效。"]},{name:"page_download",description:"先监听再点击,等待下载完成并创建浏览器文件产物",outputFlag:!0,params:[{name:"tabId",type:"number",required:!0,description:"下载来源页面"},{name:"trigger",type:"object",required:!0,description:"page_click 参数,不含 tabId"},{name:"url",type:"string",description:"预期下载 URL;扩展无法通过 referrer 归属时需显式指定"},{name:"timeout",type:"number",description:"下载等待毫秒,默认 30000,范围 1000–300000"}],notes:["--output 把文件分块保存到调用方机器;未指定时返回 artifactId,可供 page_upload 复用。","共享 CDP 浏览器保持原下载目录;Chrome 未返回文件路径时明确报错。超时不能直接重复点击。"]},{name:"tab_checkpoint",description:"为目标标签页建立日志、请求和埋点增量边界",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_open 获取"}],examples:[`tab_checkpoint --payload '{"tabId":12345}'`]},{name:"get_requests",description:"获取最近的网络请求(协议请求或普通 xhr/fetch)",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"count",type:"number",description:"返回条数,默认 10"},{name:"source",type:'"protocol" | "requests" | "all"',description:"数据来源,不填时默认 all;all 返回全部业务请求"},{name:"filter",type:"string",description:"按 URL 或 API 名称过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的请求"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 或同类查询 cursor 之后的请求"},{name:"includeBody",type:"boolean",description:"是否包含请求/响应体;指定 fields 时默认 false,否则默认 true"},{name:"includeHeaders",type:"boolean",description:"是否包含请求/响应头,默认 false"},{name:"maxBodySize",type:"number",description:"单个请求/响应体最大字符数,默认 50000"},{name:"fields",type:"string[]",description:"从响应体提取指定字段路径,最多 100 个"},{name:"keysOnly",type:"boolean",description:"只返回数据结构,不返回叶子值"}],notes:["流式请求开始后即进入缓冲区;页面及 App 桥代发的 协议 SSE 都归入 protocol。无法归属当前页面 target 的 Service Worker 请求不在采集范围内。"],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。","省略正文时不返回 postData / responseBody 字段;指定 fields 后需要同时读取全文时显式传 includeBody:true。","isPending 标记未完成请求;SSE 的 responseBody 保存按序到达的 event/data/timestamp/duration 分片。敏感请求头返回脱敏值。"],examples:[`get_requests --payload '{"tabId":12345,"count":5}'`,`get_requests --payload '{"tabId":12345,"source":"protocol","filter":"cart"}'`]},{name:"get_logs",description:"获取浏览器控制台日志",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"limit",type:"number",description:"返回最新 N 条,默认 100"},{name:"level",type:"string",description:"按日志级别过滤:log/info/warn/error/all"},{name:"filter",type:"string",description:"按内容过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的日志"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 或同类查询 cursor 之后的日志"}],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。"],examples:[`get_logs --payload '{"tabId":12345,"limit":10,"level":"error"}'`]},{name:"get_events",description:"获取 RUM/aplus/ARMS 埋点事件",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"source",type:'"rum" | "aplus" | "arms" | "all"',description:"数据来源,默认 all"},{name:"event_type",type:"string",description:"按事件类型过滤,支持正则,如 CLK/PV"},{name:"filter",type:"string",description:"按 name 或 url 过滤,支持正则"},{name:"since",type:"number",description:"只返回最近 N 秒内的事件"},{name:"after",type:"string",description:"只返回指定 tab checkpoint 之后的事件"},{name:"limit",type:"number",description:"返回条数,默认 20"},{name:"includeRaw",type:"boolean",description:"返回完整 URL、_raw 和 _context;默认 false"}],notes:["tab_open 新页从首屏采集;既有页面首次查询才启用采集,需要刷新或重新触发埋点。同批事件不会被 limit 拆开。"],result:["nextCursor 用于同类查询续读,hasMore 表示还有数据,gap 表示缓冲区淘汰造成缺口;checkpoint cursor 可分别用于三类查询的初始边界。","captureStatus 为 armed/active/inactive;空结果附 hint 时按提示刷新或触发。默认去除 tracking URL query 与 _raw/_context,includeRaw=true 时保留。"],examples:[`get_events --payload '{"tabId":12345,"source":"aplus","event_type":"CLK","limit":10}'`,`get_events --payload '{"tabId":12345,"filter":"order","includeRaw":true,"limit":1}'`,`get_events --payload '{"tabId":12345,"source":"all","limit":20}'`]},{name:"set_mock",description:"设置 API mock 数据",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"apiName",type:"string",required:!0,description:"API 名称或正则表达式"},{name:"mockData",type:"object",description:"完整 mock 响应数据(与 fields 二选一)"},{name:"fields",type:"array",description:"按字段路径修改真实响应(与 mockData 二选一)"},{name:"enabled",type:"boolean",description:"是否启用,默认 true。false 时恢复真实数据"},{name:"duration",type:"number",description:"完整响应时长(毫秒):mock 的总耗时,绕过真实服务器精确控制"},{name:"conditions",type:"object",description:"请求 query/body 字段子集匹配;$index 从 0 开始指定调用顺序"}],notes:["启用时至少提供 mockData 或非空 fields;非空 fields 优先。fields 每项 { path: string, value: any },path 支持点号和数组索引。","相同 apiName 的多条无条件 Mock 会覆盖;conditions 子集匹配 query/body(含 data 内层),不同条件可共存;$index 从 0 起控制调用顺序,不参与字段匹配。","大字段可用顶层 @<绝对路径> 文件引用或 --payload-file;文件展开后仍受 Native Messaging 单条消息大小限制。"],examples:[`set_mock --payload '{"tabId":12345,"apiName":"cart.query","mockData":{"ret":["SUCCESS::调用成功"]}}'`,"set_mock --payload-file ./mock-data.json"]},{name:"get_mocks",description:"查看当前生效的 mock 列表",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID,从 tab_list 获取"},{name:"apiName",type:"string",description:"按 API 名称或正则表达式过滤"}],examples:[`get_mocks --payload '{"tabId":12345}'`]},{name:"set_rule",description:"添加浏览器请求规则;enabled=false 且传 ruleId 时彻底删除规则",params:[{name:"ruleId",type:"number",description:"删除时必填,从 get_rules 获取"},{name:"enabled",type:"boolean",description:"省略时添加;false 时按 ruleId 删除"},{name:"actionType",type:'"redirect" | "block" | "allow" | "upgradeScheme" | "modifyHeaders"',description:"添加时必填,规则动作"},{name:"filter",type:"string",description:"添加时必填,URL 过滤表达式"},{name:"redirectUrl",type:"string",description:"redirect 动作的目标 URL"},{name:"requestHeaders",type:"array",description:"modifyHeaders 动作的请求头修改列表",details:['每项 { header: string, operation: "set" | "append" | "remove", value?: string };set/append 需 value']},{name:"responseHeaders",type:"array",description:"modifyHeaders 动作的响应头修改列表",details:['每项 { header: string, operation: "set" | "append" | "remove", value?: string };set/append 需 value']},{name:"initiatorDomains",type:"string",description:"发起方域名过滤"},{name:"resourceTypes",type:"string[]",description:"资源类型过滤"},{name:"priority",type:"number",description:"规则优先级"},{name:"description",type:"string",description:"规则说明"}],notes:["扩展模式规则持久化;CDP 仅支持会话级 modifyHeaders 请求头 set,不支持响应头、initiatorDomains 或其他动作。Provider 是否支持以其能力声明为准。","扩展模式会检查规则请求 URL 和显式来源域名的访问权限;缺失时仍保存规则,返回 warnings 和 missingOrigins,不自动弹窗。可在请求规则页面授权,或按提示调用 request_permission。复杂 URL 表达式无法完整推断域名时会提示手动检查。"],examples:[`set_rule --payload '{"actionType":"block","filter":"^https://example\\\\.com/ads/.*"}'`,`set_rule --payload '{"ruleId":42,"enabled":false}'`]},{name:"get_rules",description:"查看当前模式的请求规则;扩展模式包含 Options 面板配置的规则",examples:["get_rules"]},{name:"send_request",description:"发送 HTTP 请求,自动携带浏览器 Cookie,支持 multipart 和原始二进制上传",params:[{name:"url",type:"string",required:!0,description:"完整目标 URL"},{name:"method",type:"string",description:"HTTP 方法,默认 GET"},{name:"headers",type:"object",description:"自定义请求头"},{name:"params",type:"object",description:"URL 查询参数"},{name:"body",type:"any",description:"请求体(传对象时自动 JSON 序列化)"},{name:"bodyFile",type:"object",description:"原始二进制请求体:filePath 或 base64 二选一,可选 contentType(默认 application/octet-stream);与 body/formData/files 互斥"},{name:"formData",type:"object",description:"multipart 文本字段(值支持 string/number/boolean)"},{name:"files",type:"SendRequestFile[]",description:"multipart 文件,最多 20 个、总计不超过 40 MiB;Base64 文件总计不超过 7 MiB。每项传 fieldName 和绝对 filePath,或传 base64 + filename",details:["fieldName: string(必填);filePath: string 与 base64: string 二选一","filename: string,base64 时必填,filePath 时默认文件 basename","contentType: string(可选),默认按文件名推断 MIME,否则 application/octet-stream"]},{name:"withCookies",type:"boolean",description:"是否附加浏览器 Cookie,默认 true"},{name:"responseType",type:'"json" | "text" | "auto"',description:"响应解析方式,默认 auto"},{name:"timeout",type:"number",description:"超时毫秒数,默认 30000"}],notes:["需要托管认证的接口使用相应能力插件;不要手工传入其管理的凭据。","body 不能与 formData/files 组合;bodyFile 以原始字节发送,不包 multipart boundary,不能用于 GET/HEAD。","bodyFile.filePath 属于 native-host,最大 40 MiB;base64 解码后最大 7 MiB。multipart 不手工设置 Content-Type,由 Mearl 生成 boundary。","filePath 属于请求执行宿主;无法引用远端路径时用 base64。"],result:["返回 status、statusText、headers、body、bodyType、attachedCookieCount;bodyType 为 json/text/base64,二进制 body 需解码后保存。"],examples:[`send_request --payload '{"url":"https://api.example.com/data","method":"GET"}'`,`send_request --payload '{"url":"https://api.example.com/upload","method":"POST","formData":{"folder":"assets"},"files":[{"fieldName":"file","filePath":"/absolute/path/image.png"}]}'`,`send_request --payload '{"url":"https://api.example.com/upload","method":"POST","bodyFile":{"filePath":"/absolute/path/image.png","contentType":"image/png"}}'`]},{name:"browser_list",description:"列出所有浏览器及其连接状态、类型和 Provider 托管实例信息",summary:"列出本地及远端浏览器与连接状态",params:[{name:"provider",type:"string",description:"配合 launchForm,仅查询一个本机已安装 Provider 的启动候选;需 --local"},{name:"launchForm",type:"object",description:"现有动态启动表单请求:{variant?,values:{}},不创建或接入实例"}],examples:["browser_list","browser_list --local"]},{name:"browser_release",description:"释放当前浏览器的调试控制和会话级临时效果(含设备/时区模拟);不用于普通任务收尾,Provider 实例的行为以 mearl <providerId> 为准",params:[{name:"closeCreatedTabs",type:"boolean",description:"带 --session 时关闭会话创建的过程页,默认 false"},{name:"keepTabIds",type:"number[]",description:"保留的结果页面;复用的用户页面始终保留"},{name:"preserveEnvironment",type:"boolean",description:"带 --session 时默认 true,保留 Mock 与模拟现场;false 清理这些页面的环境"},{name:"keepArtifactIds",type:"string[]",description:"保留在浏览器宿主的文件产物;其余会话临时文件删除"}],notes:["带 --session 时可用于任务收尾,只释放该会话;未带会话时保留原浏览器级释放行为,活动会话存在时拒绝全局释放。"],summary:"释放浏览器调试控制和会话级临时效果",examples:["browser_release","browser_release --browser chrome-a"]},{name:"browser_launch",description:"启动本地 Chrome,或通过已注册 Provider 创建浏览器实例",params:[{name:"name",type:"string",description:"本地实例名称;使用 local Provider 时必填"},{name:"provider",type:"string",description:"运行环境,默认 local;可传 mearl --help 中展示的已注册 Provider ID"},{name:"providerOptions",type:"Record<string, JSON value>",description:"所选 Provider 声明的结构化启动参数;不能与顶层启动字段混用"},{name:"headless",type:"boolean",description:"本地 Provider 是否无头运行,默认 true"},{name:"userAgentMode",type:'"default" | "desktop"',description:"本地 UA 模式:default 使用默认 UA;desktop 使用匹配本机版本的 UA"},{name:"persistent",type:"boolean",description:"本地实例关闭后是否保留 Profile,默认 false"},{name:"url",type:"string",description:"登录完成后打开的初始页面"},{name:"executablePath",type:"string",description:"自定义 Chrome 可执行文件路径"},{name:"copyCookieDomains",type:"string[] | string | { presets?: string[]; domains?: string[] }",description:"从控制浏览器复制 Cookie:可传域名数组、已安装能力提供的范围名,或组合范围与额外域名"}],examples:[`browser_launch --payload '{"provider":"brow","providerOptions":{}}'`,`browser_launch --payload '{"name":"figma","userAgentMode":"desktop","copyCookieDomains":["figma.com"]}'`,`browser_launch --payload '{"name":"with-cookies","copyCookieDomains":["example.com","sub.example.org"]}'`]},{name:"browser_close",description:"关闭指定托管浏览器,并按 Provider 策略保留或清理持久化数据",params:[{name:"browser",type:"string",required:!0,description:"托管浏览器的 browserId 或名称"},{name:"deleteProfile",type:"boolean",description:"强制删除持久化数据,默认 false"}],examples:[`browser_close --payload '{"browser":"managed:account-a"}'`,`browser_close --payload '{"browser":"account-b","deleteProfile":true}'`]},{name:"tab_open",description:"打开或按 URL 规则复用 Tab,并等待新页面加载完成",aliases:["tab_new","new_tab","tab_create","create_tab"],aliasExamples:{tab_activate:`tab_open --payload '{"url":"https://example.com","reuse":"require","active":true}'`},params:[{name:"url",type:"string",required:!0,description:"要打开的 URL"},{name:"active",type:"boolean",description:"是否激活目标 Tab,默认 false;扩展免打扰默认开启,使用后台焦点模拟,关闭后才切换前台;响应返回 activation"},{name:"openerTabId",type:"number",description:"来源 Tab ID;用于把目标 Tab 关联到来源侧边栏对话"},{name:"closeExisting",type:"boolean",description:"打开前先关闭 Agent 受控的已有标签页,默认 false"},{name:"group",type:"string",description:"把新 Tab 加入指定标题的标签页分组(同名分组存在则加入,否则新建)。仅扩展模式支持"},{name:"reuse",type:'"never" | "prefer" | "require"',description:"never 始终新开;prefer 优先复用;require 只允许复用。默认 never"},{name:"match",type:"object",description:"复用匹配规则:urlPattern(支持 *)、ignoreSearch、ignoreHash、onMultiple(error/first)"},{name:"restoreFocusOnClose",type:"boolean",description:"关闭本次新开的 active Tab 后恢复原活动标签页,默认 false"},{name:"emulation",type:"object",description:"开 tab 即进入移动端模拟态(首屏即移动态、无需 reload)。字段同 set_device_emulation 去掉 enabled/reload;与 appProfile、deviceShell=true、orientation=landscape、splitScreen=true 组合可首屏进入左右分屏"},{name:"appProfile",type:"string",description:"按已安装档案应用 App 环境,ID 与限制见当前动态帮助。需要 iframe WebView 和系统栏时同时传 emulation.deviceShell=true"},{name:"os",type:'"ios" | "android"',description:"与 appProfile 配合;容器系统,默认 ios"},{name:"bridgeConfig",type:"object",description:"与 appProfile 配合;声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}}"}],notes:["emulation / appProfile 只应用到新建 Tab;复用 Tab 要切换状态时用对应设置 action。","closeExisting 不能与复用或 openerTabId 组合;多匹配默认报错,match.onMultiple=first 可显式选择第一个。"],result:["返回 tabId、url、title、opened/reused;reused=true 的既有页面应保留。","active=true 时 activation 包含 tabActive、windowFocused、windowState、visibilityState;emulation 返回实际生效配置。","capture.cursor 是导航前诊断边界,可分别用于 get_logs/get_requests/get_events 的 after。"],examples:[`tab_open --payload '{"url":"https://example.com"}'`,`tab_open --payload '{"url":"https://example.com/page","reuse":"prefer","match":{"ignoreSearch":true}}'`,`tab_open --payload '{"url":"https://m.example.com","emulation":{"preset":"iphone-17-pro"}}'`,`tab_open --payload '{"url":"https://example.com/app/home","appProfile":"reader"}'`,`tab_open --payload '{"url":"https://example.com/app/home","appProfile":"reader","emulation":{"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}}'`,`tab_open --payload '{"url":"https://example.com","appProfile":"reader","os":"android"}'`,`tab_open --payload '{"url":"https://example.com","group":"验证任务"}'`]},{name:"tab_close",description:"关闭指定标签页",aliases:["tab_remove","remove_tab","tab_delete","delete_tab"],params:[{name:"tabId",type:"number",required:!0,description:"要关闭的标签页 ID"}],examples:[`tab_close --payload '{"tabId":123}'`]},{name:"tab_list",description:"列出目标浏览器所有窗口中的标签页",aliases:["tabs","list_tabs","show_tabs"],examples:["tab_list"]},{name:"tab_group",description:"把同一窗口中的标签页加入分组,或通过 ungroup 取消分组并保留标签页;仅扩展模式支持",params:[{name:"tabIds",type:"number[]",required:!0,description:"标签页 ID,分组最多 100 个,取消分组最多 1000 个"},{name:"title",type:"string",required:!1,description:"分组标题;取消分组时省略"},{name:"ungroup",type:"boolean",required:!1,description:"为 true 时取消分组并保留标签页"}],examples:[`tab_group --payload '{"tabIds":[123,124],"title":"项目文档"}'`,`tab_group --payload '{"tabIds":[123,124],"ungroup":true}'`]},{name:"page_click",description:"点击页面元素,支持 CSS/@ref、可见文本或视口坐标定位",aliasExamples:{page_select:`page_click --payload '{"tabId":12345,"text":"选项文案","role":"option"}'`},params:[{name:"selector",type:"string",description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)。不支持 :has-text/:visible 等 Playwright 私有伪类"},{name:"text",type:"string",description:"按可见文本(accessibility name)定位。需要时配合 role/exact 消歧;多匹配会报错并列出候选"},{name:"point",type:"{ x: number; y: number }",description:'按视口坐标点击(CSS 像素)。默认使用 outer-viewport;容器或 iframe 内坐标配合 coordinateSpace: "active-frame"'},{name:"frameId",type:"string",description:"浏览器扩展后端:显式指定 CSS/text 查询或 active-frame 坐标所属的 frame;省略时容器模式自动使用当前业务 frame"},{name:"coordinateSpace",type:'"outer-viewport" | "active-frame"',description:"仅配合 point 使用;默认 outer-viewport;浏览器扩展后端的 active-frame 会换算 iframe 偏移与缩放后派发可信输入"},{name:"role",type:"string",description:"配合 text 使用,按 AX role 过滤(如 button、link、heading)"},{name:"exact",type:"boolean",description:"配合 text 使用,默认 true 精确匹配;false 时按子串匹配"},{name:"scope",type:"string",description:"配合 text 使用,把文本匹配限制在指定 CSS 元素或 @eN ref 子树内,适合消除重复文案歧义"},{name:"clickMode",type:'"auto" | "dom" | "mouse" | "touch"',description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["selector / text / point 必须且只能提供一个。隐藏页 auto 使用 DOM;只有明确依赖真实用户手势时才激活页面。","auto 对原生 option、checkbox/radio 使用状态感知的 DOM 路径;显式 mouse/touch 保留可信输入。","原生 select 可按 option 文本点击;auto/dom 返回 selectionState.valueBefore/valueAfter/selectedAfter,检查选中状态是否保持。checkbox/radio 返回 controlState.checkedBefore/checkedAfter。"],examples:[`page_click --payload '{"tabId":12345,"text":"提交"}'`,`page_click --payload '{"tabId":12345,"text":"退款明细","role":"button"}'`,`page_click --payload '{"tabId":12345,"text":"确定","scope":"@e12"}'`,`page_click --payload '{"tabId":12345,"selector":"@e3"}'`,`page_click --payload '{"tabId":12345,"selector":".submit-btn"}'`,`page_click --payload '{"tabId":12345,"selector":".gesture-btn","clickMode":"touch"}'`,`page_click --payload '{"tabId":12345,"point":{"x":336,"y":117}}'`,`page_click --payload '{"tabId":12345,"point":{"x":196,"y":240},"coordinateSpace":"active-frame"}'`]},{name:"page_drag",description:"拖动页面元素或视口坐标,适用于轮播图、滑块和拖放",params:[{name:"from",type:"string | { x: number; y: number }",required:!0,description:"起点:原生 CSS、@eN ref,或 { x, y } 视口坐标(CSS 像素)"},{name:"to",type:"string | { x: number; y: number }",required:!0,description:"终点:原生 CSS、@eN ref,或 { x, y } 视口坐标(CSS 像素)"},{name:"dragMode",type:'"auto" | "dom" | "mouse" | "touch"',description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式"},{name:"durationMs",type:"number",description:"拖动持续时间,0–5000ms,默认 400ms;内部自动分段移动"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["起点会自动滚入视口,终点必须同时位于当前视口;否则先滚动页面。隐藏页 auto 使用 DOM,不切换活动页。"],examples:[`page_drag --payload '{"tabId":12345,"from":{"x":350,"y":80},"to":{"x":80,"y":80}}'`,`page_drag --payload '{"tabId":12345,"from":"@e3","to":"#drop-zone","dragMode":"mouse"}'`]},{name:"page_type",description:"向输入框填写文本,兼容 React 受控组件",aliasExamples:{page_fill:`page_type --payload '{"tabId":12345,"selector":"@e6","text":"填写内容","clearFirst":true}'`},params:[{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)"},{name:"text",type:"string",required:!0,description:"要填写的文本"},{name:"clearFirst",type:"boolean",description:"是否先清空原有内容,默认 true"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,examples:[`page_type --payload '{"tabId":12345,"selector":"@e6","text":"搜索关键词"}'`]},{name:"page_hover",description:"将鼠标悬停在页面元素上",params:[{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀)"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,examples:[`page_hover --payload '{"tabId":12345,"selector":".nav-menu"}'`]},{name:"page_scroll",description:"滚动页面或指定容器;页面根不可滚动时自动发现活动滚动区",params:[{name:"direction",type:'"up" | "down" | "top" | "bottom"',required:!0,description:"滚动方向"},{name:"distance",type:"number",description:"滚动距离(px),默认 600"},{name:"selector",type:"string",description:"目标滚动容器的原生 CSS 选择器,或 page_snapshot 返回的 @eN ref;不传时滚动页面"},{name:"containerPolicy",type:'"self" | "nearest"',description:"默认 self,要求 selector 本身可滚动;nearest 会在其不可滚动时使用最近的可滚动祖先"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:[...PAGE_ACTION_RESULT,"action.data 返回 moved、atTop/atBottom、scrollYBefore/After、maxScrollY、resolvedContainer 和 ancestorDistance;自动发现的内部容器提供可复用 containerSelector。"],examples:[`page_scroll --payload '{"tabId":12345,"direction":"down"}'`,`page_scroll --payload '{"tabId":12345,"direction":"bottom"}'`,`page_scroll --payload '{"tabId":12345,"selector":".virtual-list","direction":"down","distance":800}'`,`page_scroll --payload '{"tabId":12345,"selector":"@e8","containerPolicy":"nearest","direction":"bottom"}'`]},{name:"page_runtime",description:"页面运行时传输适配器;插件使用 PluginPageClient 或 app.page",params:[{name:"operation",type:"string",required:!0,description:"resolve/attach/get/send/detach/activation"}]},{name:"page_eval",description:"在页面上下文中执行任意 JavaScript 表达式",params:[{name:"expression",type:"string",required:!0,description:"要执行的 JS 表达式;传 args 时须求值为函数"},{name:"args",type:"unknown[]",description:"传给页面函数的 JSON 参数;SDK/CLI 自动处理大参数分块,保持指定执行环境"},{name:"executionWorld",type:"string",description:"main(默认)读取网页 JS;isolated 使用命名隔离环境,扩展连接无需 debugger"},{name:"worldId",type:"string",description:"isolated 必填,小写字母开头,允许数字和连字符,最长 64 字符"},{name:"awaitPromise",type:"boolean",description:"表达式返回 Promise 时等待完成,默认 true"},{name:"frameId",type:"string",description:"page_frames 返回的目标 frame ID,扩展/CDP 均支持;省略时容器/设备外壳使用当前业务 frame,普通页面使用主 frame"},{...PAGE_OBSERVE_PARAM,type:"object",description:"仅在表达式会修改页面且需要观察结果时显式传入;不传保持轻量裸执行"},PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["优先使用结构化 action;仅在其无法表达需求时执行最小范围脚本。"],result:["默认返回 { result };observe 对象启用观察并返回 { action, observation };仅开启 diagnostics 时返回 { action, diagnostics }。diagnostics=false 不启用包装。失败阶段语义同 page_click。"],examples:[`page_eval --payload '{"tabId":12345,"expression":"document.title"}'`]},{name:"page_inspect",description:"查询 DOM 元素的控件状态、数量、边框盒、计算样式、遮挡、溢出和最近滚动容器",params:[{name:"selector",type:"string",description:"原生 CSS、page_snapshot 返回的 @eN ref,或 DevTools Elements 当前选区 $0;做全页溢出诊断时可省略"},{name:"filter",type:'"all" | "overflowing" | "horizontal-overflow" | "vertical-overflow" | "scrollable"',description:"结果过滤;省略 selector 时必须指定非 all 的过滤条件"},{name:"styles",type:"string[]",description:"要返回的计算样式属性,默认 display/position/box-sizing/overflow-x/overflow-y"},{name:"maxResults",type:"number",description:"最多返回的明细数,默认 20,最大 100;未触发 scanTruncated 时 count 为完整命中数"},{name:"includeOuterHTML",type:"boolean",description:"是否返回 outerHTML(最多 3000 字符);$0 默认 true,其他目标默认 false"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:["matches[] 包含 boundingBox、computedStyle、hitTest、scroll 溢出量及可用的 scrollContainer。receivesPointerEvents=false 时读取 occludedBy。","state 返回原生/ARIA 状态及来源;缺失字段表示未知。","$0 还返回 resolvedSelector、属性、XPath 和可用框架信息。"],examples:[`page_inspect --payload '{"tabId":12345,"selector":".form-field","styles":["display","width"]}'`,`page_inspect --payload '{"tabId":12345,"selector":"@e8"}'`,`page_inspect --payload '{"tabId":12345,"selector":"$0"}'`,`page_inspect --payload '{"tabId":12345,"filter":"horizontal-overflow"}'`,`page_inspect --payload '{"tabId":12345,"filter":"scrollable"}'`]},{name:"page_press",description:"在页面中按下键盘按键或组合键",params:[{name:"key",type:"string",required:!0,description:"按键名称:Enter/Tab/Escape/Backspace 等"},{name:"modifiers",type:"string[]",description:"修饰键数组:ctrl/alt/shift/meta/cmd"},{name:"dialogId",type:"string",description:"原生弹窗回执或 page_snapshot 中的 dialog.id;仅配合 Enter 接受或 Escape 取消"},{name:"promptText",type:"string",description:"仅用于 dialogId + Enter 接受原生 prompt 时填写文本"},{name:"pressMode",type:'"auto" | "dom" | "keyboard"',description:"派发模式;auto 默认在隐藏页降级为 DOM 键盘事件"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["隐藏页 DOM 模式支持 Tab 焦点移动、原生控件 Enter/Space 激活和输入框 Enter 提交;编辑、选择、方向键和页面滚动等原生行为需可见页与 pressMode=keyboard。","原生 alert/confirm/prompt/beforeunload 弹窗需显式传 dialogId;普通 Enter 不处理弹窗。弹窗处理绕过 DOM 观察,不自动重放被中断的动作;处理后重新读取页面。"],result:[...PAGE_ACTION_RESULT,"action.data.dispatchMode / fallbackReason / defaultAction 说明实际输入路径。"],examples:[`page_press --payload '{"tabId":12345,"key":"Enter"}'`]},{name:"page_wait",description:"等待指定时间、元素状态、可见文本或页面条件成立",params:[{name:"time",type:"number",description:"等待毫秒数(与 selector/text/condition 四选一)"},{name:"selector",type:"string",description:"目标 CSS 选择器(与 time/text/condition 四选一)"},{name:"state",type:'"attached" | "detached" | "visible" | "hidden"',description:"selector 的目标状态,默认 attached"},{name:"text",type:"string",description:"等待页面出现的可见文本"},{name:"exact",type:"boolean",description:"text 是否精确匹配,默认 false"},{name:"condition",type:"string",description:"在页面主上下文轮询的 JS 表达式,返回 truthy 时结束"},{name:"timeout",type:"number",description:"等待超时毫秒数,默认 10000"},{name:"interval",type:"number",description:"轮询间隔毫秒数,默认 200"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["time / selector / text / condition 必须且只能提供一个;time 范围 0–60000ms。页面交互已有内置观察,仅在需要独立等待条件时使用。","等待后须立即执行已知动作时,用 mearl run 在同一脚本中 await pageWait 后紧接 pageClick,避免模型往返。整体 --timeout 须覆盖等待及后续动作;等待失败不继续点击。"],examples:[`page_wait --payload '{"tabId":12345,"time":1000}'`,`page_wait --payload '{"tabId":12345,"selector":".dialog","state":"visible"}'`,`page_wait --payload '{"tabId":12345,"selector":".loading","state":"hidden"}'`,`page_wait --payload '{"tabId":12345,"text":"提交成功"}'`,`page_wait --payload '{"tabId":12345,"condition":"window.appReady === true","timeout":30000}'`]},{name:"page_navigate",description:"在当前标签页内导航到 URL、刷新页面,或沿浏览历史后退/前进",aliasExamples:{page_reload:`page_navigate --payload '{"tabId":12345,"refresh":true}'`},params:[{name:"url",type:"string",description:"要导航到的 URL;与 refresh/history 互斥"},{name:"refresh",type:"boolean",description:"为 true 时直接重新加载当前页面;与 url/history 互斥"},{name:"history",type:'"back" | "forward"',description:"沿当前标签页浏览历史后退或前进;与 url/refresh 互斥"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["url / refresh=true / history 必须且只能提供一个。"],examples:[`page_navigate --payload '{"tabId":12345,"url":"https://example.com/page2"}'`,`page_navigate --payload '{"tabId":12345,"refresh":true}'`,`page_navigate --payload '{"tabId":12345,"history":"back"}'`]},{name:"page_upload",description:'向 <input type="file"> 元素上传一个或多个文件',params:[{name:"files",type:"object[]",description:"调用方绝对路径 {filePath} 或浏览器产物 {artifactId};与 filePaths 二选一"},{name:"selector",type:"string",required:!0,description:"原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 @eN ref(必须带 @ 前缀),必须指向 input[type=file]"},{name:"filePaths",type:"string[]",description:"浏览器宿主上的绝对路径数组;与 files 二选一"},PAGE_OBSERVE_PARAM,PAGE_DIAGNOSTICS_PARAM,{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:PAGE_ACTION_RESULT,notes:["直接写入 input[type=file],不依赖 file chooser;隐藏的文件节点也可上传。外部 Provider 的文件中转能力查询 mearl <providerId>。"],examples:[`page_upload --payload '{"tabId":12345,"selector":"#file-input","filePaths":["/Users/me/photo.jpg"]}'`]},{name:"page_snapshot",description:"获取带 @ref 的页面结构快照,默认使用无障碍树,也可显式读取渲染 DOM",params:[{name:"depth",type:"number",description:"树深度,默认 15,复杂页面可调大"},{name:"mode",type:'"full" | "interactive" | "viewport" | "dom"',description:"默认 full;interactive/viewport 裁剪 AX 树;AX 信息缺失时可显式使用 dom 读取渲染 DOM"},{name:"rootSelector",type:"string",description:"只获取指定 CSS 元素的局部子树,可与 mode 组合;与 rootRef 互斥"},{name:"rootRef",type:"string",description:"以已有 @eN ref 为根获取局部子树;与 rootSelector 互斥"},{name:"ancestorDepth",type:"number",description:"rootRef 向上扩展的 DOM 祖先层数,默认 0,最大 20"},{name:"query",type:"{ text?: string; role?: string; exact?: boolean }",description:"服务端按 name / role 过滤当前模式的树,只保留命中节点及祖先路径"},{name:"maxNodes",type:"number",description:"最多输出节点数,0 表示不限制"},{name:"maxChars",type:"number",description:"快照文本最大字符数,默认 60000,超出保留首尾;传 0 不限制"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["query.text / query.role 至少提供一个;query.exact 默认 true。每次快照刷新有效 ref 集合。","interactive 无 AX 控件时回退到 viewport,不会自动改用 dom;Canvas 内容需截图。"],result:["返回 snapshot、elementCount、outputNodeCount、mode;截断时 truncated=true。","snapshot 中的 @eN 可直接用于操作;内部节点映射仅保存在运行时。无名称、无 ref 且无状态的分组折叠到子节点。","query 返回 matches 与完整 matchCount,matches 最多 100 项,裁剪时 matchesTruncated=true。容器/iframe 的视口裁剪返回 outerViewport、contentViewport 和滚动位置。"],examples:[`page_snapshot --payload '{"tabId":12345}'`,`page_snapshot --payload '{"tabId":1,"mode":"viewport"}'`,`page_snapshot --payload '{"tabId":1,"mode":"dom"}'`,`page_snapshot --payload '{"tabId":1,"rootSelector":"[role=dialog]"}'`,`page_snapshot --payload '{"tabId":1,"rootRef":"@e8","ancestorDepth":1}'`,`page_snapshot --payload '{"tabId":1,"query":{"text":"保存","role":"button"}}'`]},{name:"page_screenshot",description:"获取当前视口或指定元素截图",outputFlag:!0,params:[{name:"selector",type:"string",description:"CSS 选择器,提供后只截取该元素区域"},{name:"format",type:'"png" | "jpeg"',description:"图片格式,默认 png"},{name:"quality",type:"number",description:"JPEG 压缩质量(0-100),默认 80"},{name:"captureMode",type:'"cdp" | "visible"',description:"默认 cdp;visible 使用活动标签页截图,普通网页无需 debugger;设备模拟复用模拟会话并截取业务视口,不支持 selector"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["使用 --output <path> 保存图片;省略时 stdout 返回含 base64 data 的 JSON,避免直接将其加载为文本。"],result:["meta 包含 format、width、height、size、url、title;宽高为实际截图的物理像素。"],examples:[`page_screenshot --payload '{"tabId":12345}' --output ./screenshot.png`,`page_screenshot --payload '{"tabId":12345,"selector":".product-card"}' --output ./card.png`]},{name:"set_device_emulation",description:"把目标 tab 切换为移动端模拟(视口/DPR/UA/触摸/视觉比例),等价 DevTools 设备工具栏,作用域 per-tab;需保持调试控制才持续生效",summary:"设置或清除目标标签页的设备模拟",params:[{name:"enabled",type:"boolean",required:!0,description:"true=启用,false=清除"},{name:"preset",type:DEVICE_PRESET_TYPE,description:"内置设备预设,提供 width/height/DPR/UA 默认值;旧机型 ID 继续兼容"},{name:"width",type:"number",description:"视口宽度(覆盖 preset)"},{name:"height",type:"number",description:"视口高度(覆盖 preset)"},{name:"deviceScaleFactor",type:"number",description:"DPR(覆盖 preset)"},{name:"scale",type:"number",description:"画面视觉比例,不改变视口尺寸或 DPR;必须为有限正数,默认 1"},{name:"mobile",type:"boolean",description:"是否走移动渲染模式,默认从 preset 推断"},{name:"userAgent",type:"string",description:"自定义 UA(覆盖 preset)"},{name:"orientation",type:'"portrait" | "landscape"',description:"横竖屏,默认 portrait"},{name:"touch",type:"boolean",description:"是否启用触摸事件,默认从 preset 推断;无 preset 时跟随 mobile"},{name:"deviceShell",type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},{name:"splitScreen",type:"boolean",description:"是否将首页与业务页分置左右 WebView;仅在已启用 App 档案、deviceShell=true、横屏时生效,默认 false"},{name:"reload",type:"boolean",description:"启用后是否重载页面,默认 true"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["无 preset 时 width/height 必须成对提供且 userAgent 必填;mobile 默认 true,touch 跟随 mobile。","deviceShell 开启/移除时必须重载;splitScreen 仅在已启用 App 档案、deviceShell=true、横屏时生效。"],result:["返回实际 viewport(width/height/deviceScaleFactor/scale)、UA、mobile、touch、orientation、deviceShell、splitScreen 和 reloaded;应以响应确认生效状态。"],examples:[`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"iphone-17-pro"}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"pixel-11","orientation":"landscape"}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":true,"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}'`,`set_device_emulation --payload '{"tabId":12345,"enabled":false}'`]},{name:"set_app_profile",description:"设置已安装的 App 档案;完整 JSBridge 由能力包提供。可同时设置已安装的网络控件,传 emulation 时联动设备模拟",summary:"设置或清除目标标签页的 App 容器模拟",params:[{name:"enabled",type:"boolean",required:!0,description:"true=启用,false=清除"},{name:"profile",type:"string",description:"已安装的容器档案 ID(enabled=true 时必填);当前动态帮助直接展示目标浏览器目录"},{name:"os",type:'"ios" | "android"',description:"容器系统,默认 ios"},{name:"refreshDefinition",type:"boolean",description:"立即采用最新档案定义,保留用户显式设置"},{name:"lockDefinition",type:"boolean",description:"固定当前定义;默认在下次刷新或文档导航时自动更新"},{name:"appVersion",type:"string",description:"覆盖档案默认 App 版本号"},{name:"deviceModel",type:"string",description:"Android 机型名(拼入 UA 与 __DEVICE_MODEL__)"},{name:"bridgeConfig",type:"object",description:"声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}};不执行配置脚本"},{name:"networkControl",type:"object | null",description:"可选已安装网络控件 {id,value};null 清除,省略时保持当前设置。仅作用于目标 tab"},{name:"emulation",type:"object",description:"可选设备联动参数,字段同 set_device_emulation 去掉 enabled/reload;字段覆盖档案推荐设备,deviceShell 默认 true,横屏时可传 splitScreen=true。省略时不设置或清除设备"},{name:"reload",type:"boolean",description:"应用/清除后是否重载页面,默认 true"},{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],notes:["只有用户明确要求 App/客户端/容器/JSBridge 模拟时启用。移动视口或普通 H5 调试使用 set_device_emulation。","emulation={} 使用档案推荐设备;enabled=false 时省略 emulation 只清除 App 注入,传 {} 同时清除设备模拟。","bridgeConfig.methods 按方法声明 behavior / response / noop 三选一,可传 silent;只支持受控行为、固定 JSON 回包或成功空实现,不执行配置脚本。"],result:["返回 enabled、profile、label、userAgent、os、networkControl、reloaded;联动设备时额外返回实际 emulation。"],examples:[`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"reader"}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"reader","networkControl":{"id":"environment","value":"pre"}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false,"networkControl":null}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"reader","emulation":{}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"wallet","emulation":{"preset":"pixel-11","deviceShell":true}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":true,"profile":"reader","emulation":{"preset":"ipad-mini-a17-pro","orientation":"landscape","deviceShell":true,"splitScreen":true}}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false}'`,`set_app_profile --payload '{"tabId":12345,"enabled":false,"emulation":{}}'`]},{name:"set_timezone",description:"覆盖目标 tab 的时区,传空字符串恢复浏览器默认时区",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"},{name:"timezone",type:"string",required:!0,description:"IANA 时区标识(如 Asia/Shanghai);空字符串表示清除覆盖"}],examples:[`set_timezone --payload '{"tabId":12345,"timezone":"America/New_York"}'`,`set_timezone --payload '{"tabId":12345,"timezone":""}'`]},{name:"get_cookie",description:"从目标浏览器读取一个指定非分区 Cookie;拒绝返回 HttpOnly Cookie",params:[{name:"tabId",type:"number",description:"可选;指定标签页的 Cookie 存储区,省略时使用浏览器默认存储区"},{name:"name",type:"string",required:!0,description:"要读取的 Cookie 名称;不支持列举全部 Cookie"},{name:"url",type:"string",description:"Cookie 查询 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},{name:"domain",type:"string",description:"可选精确域过滤,只允许 Cookie 查询 URL 的 host 或其父域"},{name:"path",type:"string",description:"可选精确 path 过滤"}],notes:["只读取指定非分区 Cookie,不列举全部、不回退分区 Cookie,拒绝 HttpOnly;禁止读取认证 Token。指定 url 不导航,指定 tabId 仅选择存储区时不启动采集。"],result:["找到时 found=true 并返回 value/domain/path;不存在时 found=false。"],examples:[`get_cookie --payload '{"tabId":12345,"name":"feature_flag"}'`,`get_cookie --payload '{"url":"https://www.shop.com/","name":"account_name"}'`,`get_cookie --payload '{"tabId":12345,"name":"feature_channel","domain":"example.com"}'`,`get_cookie --payload '{"tabId":12345,"name":"account_name","url":"https://www.shop.com/","domain":"example.com","path":"/"}'`]},{name:"set_cookie",description:"在目标浏览器设置一个指定非分区 session Cookie,可选刷新指定页面",params:[{name:"tabId",type:"number",description:"可选;指定标签页的 Cookie 存储区,reload=true 时必填"},{name:"url",type:"string",description:"Cookie 目标 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},{name:"name",type:"string",required:!0,description:"Cookie 名称"},{name:"value",type:"string",required:!0,description:"Cookie 值,可传空字符串;空字符串不会删除 Cookie"},{name:"domain",type:"string",description:"Cookie 域,默认目标 URL 的 host;只允许目标 host 或其父域"},{name:"path",type:"string",description:"Cookie path,默认 /"},{name:"reload",type:"boolean",description:"设置后是否刷新指定 tabId,默认 false;true 时必须传 tabId"}],notes:["仅写非分区 session Cookie,不支持删除。reload=true 时校验目标域与刷新页域的授权。"],result:["返回 url/name/domain/path/reloaded,指定标签页时包含 tabId;不回显 Cookie 值。"],examples:[`set_cookie --payload '{"tabId":12345,"name":"feature_flag","value":"enabled"}'`,`set_cookie --payload '{"url":"https://www.shop.com/","name":"feature_flag","value":"enabled"}'`,`set_cookie --payload '{"tabId":12345,"name":"feature_channel","value":"3.6.63","domain":"example.com","reload":true}'`]},{name:"page_frames",description:"获取页面主 frame 与所有 iframe 列表",params:[{name:"tabId",type:"number",required:!0,description:"目标标签页 ID"}],result:["frames[] 包含 frameId、url、name 和 isMainFrame;frameId 可用于 page_eval 等支持 frame 定位的 action。"],examples:[`page_frames --payload '{"tabId":12345}'`]},{name:"request_permission",description:"申请访问指定域名的权限(必要时弹窗让用户授权)",params:[{name:"domain",type:"string",required:!0,description:"需要授权的域名,如 example.com"}],notes:["domain 使用纯主机名,不传 URL。在 send_request 或 set_rule 提示缺少浏览器域名权限时申请。","弹窗等待用户选择,90 秒超时或关闭按拒绝处理;granted=true 后才重试原请求。"],result:["返回 granted、domain,授权成功时包含 origin。"],examples:[`request_permission --payload '{"domain":"example.com"}'`]},{name:"run_actions",description:"批量顺序执行多个 action,减少往返延迟。遇错即停,返回已完成步骤结果;步骤内的页面动作不带内置观察",summary:"批量顺序执行多个 action,遇错即停",params:[{name:"actions",type:"Array<{action: string, data?: object}>",required:!0,description:"要依次执行的 action 列表"},{name:"tabId",type:"number",required:!0,description:"所有步骤共享的 tabId,步骤自身指定的优先"}],notes:["最多 50 步,不允许嵌套 run_actions;需要根据每步效果决策时逐步调用普通 action。"],result:["返回 results、completedSteps、totalSteps;失败时包含 error/failedStep,后续步骤未执行。"],examples:[`run_actions --payload '{"tabId":12345,"actions":[{"action":"page_hover","data":{"selector":"#menu"}},{"action":"page_click","data":{"selector":"#menu-item"}}]}'`]}],COMMAND_MAP=new Map(COMMANDS.map(command=>[command.name,command]))}});import{statSync as statSync3}from"node:fs";function pluginFileVersion(path7){let stat2=statSync3(path7);if(!stat2.isFile())throw new Error(`插件资源不是文件: ${path7}`);return`${stat2.dev}-${stat2.ino}-${stat2.mtimeMs}-${stat2.ctimeMs}-${stat2.size}`}var init_pluginSource=__esm({"../client/src/plugins/pluginSource.ts"(){"use strict"}});import{createHash as createHash2}from"node:crypto";import{readFileSync as readFileSync4,realpathSync}from"node:fs";import{basename,dirname as dirname3,extname,isAbsolute,join as join4,relative,resolve,sep}from"node:path";function pluginRoot(entry){let entryDirectory=dirname3(entry);return basename(entryDirectory)==="scripts"?dirname3(entryDirectory):entryDirectory}function attributeValue(tag,name){let match=tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return match?.[1]??match?.[2]??match?.[3]}function removeAttribute(tag,name){return tag.replace(new RegExp(`\\s+${name}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+)`,"i"),"")}function isEmbeddedReference(reference){return/^(?:data:|blob:|#)/i.test(reference.trim())}function isRemoteReference(reference){return/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(reference.trim())}function contentType(path7){return MIME_TYPES[extname(path7).toLowerCase()]??"application/octet-stream"}function escapeStyleText(value){return value.replace(/<\/style/gi,"\\3C /style")}function escapeScriptText(value){return value.replace(/<\/script/gi,"<\\/script")}function buildPluginPageBundle(entry,pageEntry){let root=realpathSync(pluginRoot(entry)),sourceBytes=0,countedFiles=new Set,sources={},resolveLocalFile=(reference,fromFile)=>{let cleanReference=reference.trim().split(/[?#]/,1)[0];if(!cleanReference||isEmbeddedReference(cleanReference))return"";if(isRemoteReference(cleanReference)||isAbsolute(cleanReference))throw new Error(`toolbox.page 不允许远程或绝对资源: ${reference}`);let sourcePath=resolve(dirname3(fromFile),cleanReference),resolved=realpathSync(sourcePath),relativePath=relative(root,resolved);if(relativePath===".."||relativePath.startsWith(`..${sep}`)||isAbsolute(relativePath))throw new Error(`toolbox.page 资源超出插件目录: ${reference}`);return sources[sourcePath]=pluginFileVersion(sourcePath),resolved},readAsset=path7=>{sources[path7]??=pluginFileVersion(path7);let content2=readFileSync4(path7);if(!countedFiles.has(path7)&&(countedFiles.add(path7),sourceBytes+=content2.byteLength,sourceBytes>MAX_PAGE_SOURCE_BYTES))throw new Error("toolbox.page 源文件总大小不能超过 16 MiB");return content2},dataUrl=(reference,fromFile)=>{if(isEmbeddedReference(reference))return reference;let path7=resolveLocalFile(reference,fromFile);return`data:${contentType(path7)};base64,${readAsset(path7).toString("base64")}`},inlineCss=(css,cssPath)=>css.replace(/url\(\s*(['"]?)([^'"()]+)\1\s*\)/gi,(_match,_quote,reference)=>{let value=reference.trim();return isEmbeddedReference(value)?`url("${value}")`:`url("${dataUrl(value,cssPath)}")`}),absoluteEntry=resolveLocalFile(pageEntry,join4(root,"__toolbox_entry__"));if(extname(absoluteEntry).toLowerCase()!==".html")throw new Error("toolbox.page.entry 必须指向 HTML 文件");let html=readAsset(absoluteEntry).toString("utf8").replace(/^\uFEFF/,"");if(!/<html\b|<!doctype\b/i.test(html))throw new Error("toolbox.page.entry 必须是完整 HTML 文档");if(/<base\b/i.test(html))throw new Error("toolbox.page 不允许声明 base 标签");if(/<meta\b[^>]*http-equiv\s*=\s*["']?content-security-policy/i.test(html))throw new Error("toolbox.page 的安全策略由 Mearl 管理,请移除 CSP meta 标签");html=html.replace(/<link\b[^>]*>/gi,tag=>{let rel=attributeValue(tag,"rel")?.toLowerCase().split(/\s+/)??[],href=attributeValue(tag,"href");if(rel.includes("stylesheet")){if(!href)throw new Error("toolbox.page stylesheet 缺少 href");let cssPath=resolveLocalFile(href,absoluteEntry),css=inlineCss(readAsset(cssPath).toString("utf8"),cssPath);return`<style data-mearl-source="${href.replaceAll('"',"&quot;")}">${escapeStyleText(css)}</style>`}if(href&&rel.some(value=>["icon","apple-touch-icon"].includes(value)))return tag.replace(href,dataUrl(href,absoluteEntry));if(href&&isRemoteReference(href))throw new Error(`toolbox.page 不允许远程 link 资源: ${href}`);return tag}),html=html.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,tag=>{let src=attributeValue(tag,"src");if(!src)return tag;let scriptPath=resolveLocalFile(src,absoluteEntry),script=readAsset(scriptPath).toString("utf8");if(attributeValue(tag,"type")?.toLowerCase()==="module"&&/(?:^|[;\n]\s*)(?:import\s|export\s)|\bimport\s*\(/m.test(script))throw new Error("toolbox.page 的模块脚本必须先打包为无 import 的单文件");return`${removeAttribute(tag.slice(0,tag.indexOf(">")+1),"src")}${escapeScriptText(script)}</script>`}),html=html.replace(/(<(?:img|source|video|audio|track|input)\b[^>]*?\s(?:src|poster)\s*=\s*)(["'])([^"']+)\2/gi,(_match,prefix,quote,reference)=>`${prefix}${quote}${dataUrl(reference,absoluteEntry)}${quote}`);let injection=`<meta name="color-scheme" content="light dark">${PAGE_SECURITY_META}${PAGE_THEME_STYLE}<script data-mearl-bridge>${escapeScriptText(PAGE_BRIDGE_SCRIPT)}</script>`;html=/<head\b[^>]*>/i.test(html)?html.replace(/<head\b[^>]*>/i,tag=>`${tag}${injection}`):html.replace(/<html\b[^>]*>/i,tag=>`${tag}<head>${injection}</head>`);let content=html,buffer=Buffer.from(content,"utf8");if(buffer.byteLength>MAX_PAGE_BUNDLE_BYTES)throw new Error("toolbox.page 打包后不能超过 24 MiB");return{content,hash:createHash2("sha256").update(buffer).digest("hex"),size:buffer.byteLength,chunks:Math.ceil(buffer.byteLength/PLUGIN_PAGE_CHUNK_BYTES),sources}}var PLUGIN_PAGE_CHUNK_BYTES,MAX_PAGE_SOURCE_BYTES,MAX_PAGE_BUNDLE_BYTES,MIME_TYPES,PAGE_BRIDGE_SCRIPT,PAGE_SECURITY_META,PAGE_THEME_STYLE,PLUGIN_PAGE_RUNTIME_HASH,init_pluginPageBundle=__esm({"../client/src/plugins/pluginPageBundle.ts"(){"use strict";init_pluginSource();PLUGIN_PAGE_CHUNK_BYTES=384*1024,MAX_PAGE_SOURCE_BYTES=16*1024*1024,MAX_PAGE_BUNDLE_BYTES=24*1024*1024,MIME_TYPES={".avif":"image/avif",".gif":"image/gif",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".ogg":"audio/ogg",".otf":"font/otf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"},PAGE_BRIDGE_SCRIPT=String.raw`(() => {
3
3
  let context = null;
4
4
  let port = null;
5
5
  let requestSequence = 0;
@@ -604,24 +604,9 @@ body {
604
604
  color: var(--mearl-text-primary);
605
605
  }
606
606
  button, input, select, textarea { font: inherit; }
607
- </style>`,PLUGIN_PAGE_RUNTIME_HASH=createHash2("sha256").update(PAGE_BRIDGE_SCRIPT).update(PAGE_SECURITY_META).update(PAGE_THEME_STYLE).digest("hex")}});import{randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync3,mkdirSync as mkdirSync2,openSync as openSync3,readFileSync as readFileSync5,readSync,readdirSync as readdirSync4,renameSync as renameSync3,rmSync as rmSync3,statSync as statSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{isAbsolute as isAbsolute2,join as join5,resolve as resolve2}from"node:path";function pluginRegistrationNeedsRefresh(registration,includePage=!1){return!registration.source||pluginFileVersion(registration.entry)!==registration.source.entry||Object.entries(registration.source.profiles??{}).some(([path8,version2])=>{try{return pluginFileVersion(path8)!==version2}catch{return!0}})?!0:!includePage||!registration.toolbox?!1:registration.source.pageRuntime!==PLUGIN_PAGE_RUNTIME_HASH||!registration.source.page?!0:Object.entries(registration.source.page).some(([path8,version2])=>pluginFileVersion(path8)!==version2)}function pluginDirectory(){return resolve2(process.env.MEARL_PLUGIN_DIR||join5(homedir2(),".mearl","plugins"))}function pluginPageDirectory(){return join5(pluginDirectory(),".pages")}function pluginPageBundlePath(name,hash){return join5(pluginPageDirectory(),`${name}-${hash}.html`)}function removePluginPageBundles(name,exceptHash){let files;try{files=readdirSync4(pluginPageDirectory())}catch(error2){if(error2.code==="ENOENT")return;throw error2}let keep=exceptHash?`${name}-${exceptHash}.html`:void 0;for(let file of files)file===keep||!file.startsWith(`${name}-`)||!file.endsWith(".html")||rmSync3(join5(pluginPageDirectory(),file),{force:!0})}function normalizePageBundle(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("invalid page bundle");let candidate=value;if(typeof candidate.hash!="string"||!/^[a-f0-9]{64}$/.test(candidate.hash)||!Number.isInteger(candidate.size)||(candidate.size??0)<=0||!Number.isInteger(candidate.chunks)||candidate.chunks!==Math.ceil((candidate.size??0)/PLUGIN_PAGE_CHUNK_BYTES))throw new Error("invalid page bundle");return{hash:candidate.hash,size:candidate.size,chunks:candidate.chunks}}function persistPluginPageBundle(name,bundle){let directory=pluginPageDirectory();mkdirSync2(directory,{recursive:!0,mode:448});let target=pluginPageBundlePath(name,bundle.hash);try{if(statSync4(target).isFile())return}catch{}let temporary=`${target}.${randomUUID2()}.tmp`;try{writeFileSync2(temporary,bundle.content,{mode:384,flag:"wx"}),renameSync3(temporary,target)}finally{rmSync3(temporary,{force:!0})}}function assertPluginName(name){if(!/^[a-z][a-z0-9-]*$/.test(name)||RESERVED_NAMES.has(name)||COMMAND_MAP.has(name))throw new PluginError("PLUGIN_INVALID_NAME",`不可用的插件名称: ${name}`)}function normalizePluginToolboxContribution(value){if(value===void 0)return;if(!value||typeof value!="object"||Array.isArray(value))throw new Error("toolbox 必须是对象");let candidate=value;if(candidate.displayMode!==void 0&&!["popup","tab","both"].includes(candidate.displayMode))throw new Error("toolbox.displayMode 必须是 popup、tab 或 both");let title=typeof candidate.title=="string"?candidate.title.trim():"",description=typeof candidate.description=="string"?candidate.description.trim():void 0,icon=typeof candidate.icon=="string"?candidate.icon.trim():void 0;if(candidate.version!==1)throw new Error("toolbox.version 必须为 1");if(!title||title.length>80)throw new Error("toolbox.title 必须是 1-80 个字符");if(description&&description.length>240)throw new Error("toolbox.description 不能超过 240 个字符");if(icon&&!parseToolboxIcon(icon))throw new Error("toolbox.icon 必须是图标名称、SVG、图片 Data URL 或 HTTP(S) 图片地址,最多 32768 个字符");let locales;if(candidate.locales!==void 0){if(!candidate.locales||typeof candidate.locales!="object"||Array.isArray(candidate.locales))throw new Error("toolbox.locales 必须是对象");let entries=Object.entries(candidate.locales);if(entries.length===0||entries.length>20)throw new Error("toolbox.locales 必须包含 1-20 个语言");locales=Object.fromEntries(entries.map(([locale,localized])=>{if(!/^[a-z]{2,3}(?:[_-][A-Za-z0-9]{2,8})*$/.test(locale))throw new Error(`toolbox.locales 包含无效语言: ${locale}`);if(!localized||typeof localized!="object"||Array.isArray(localized))throw new Error(`toolbox.locales.${locale} 必须是对象`);let localizedTitle=typeof localized.title=="string"?localized.title.trim():void 0,localizedDescription=typeof localized.description=="string"?localized.description.trim():void 0;if(localizedTitle!==void 0&&(!localizedTitle||localizedTitle.length>80))throw new Error(`toolbox.locales.${locale}.title 必须是 1-80 个字符`);if(localizedDescription!==void 0&&localizedDescription.length>240)throw new Error(`toolbox.locales.${locale}.description 不能超过 240 个字符`);if(!localizedTitle&&!localizedDescription)throw new Error(`toolbox.locales.${locale} 至少声明 title 或 description`);return[locale,{...localizedTitle?{title:localizedTitle}:{},...localizedDescription?{description:localizedDescription}:{}}]}))}if(!candidate.page||typeof candidate.page!="object"||Array.isArray(candidate.page))throw new Error("toolbox.page 必须是对象");let pageCandidate=candidate.page;if(pageCandidate.type!=="sandbox")throw new Error("toolbox.page.type 必须为 sandbox");if(pageCandidate.runtime!==void 0&&pageCandidate.runtime!=="preact")throw new Error("toolbox.page.runtime 仅支持 preact");let pageEntry=typeof pageCandidate.entry=="string"?pageCandidate.entry.trim():"";if(!pageEntry||pageEntry.length>240||isAbsolute2(pageEntry)||pageEntry.includes("\\")||pageEntry.split("/").some(segment=>!segment||segment==="."||segment===".."))throw new Error("toolbox.page.entry 必须是插件目录内的相对 HTML 路径");if(!Array.isArray(pageCandidate.commands))throw new Error("toolbox.page.commands 必须是命令名称数组");let commands=pageCandidate.commands.map(command=>typeof command=="string"?command.trim():"");if(commands.length===0||commands.length>64||new Set(commands).size!==commands.length||commands.some(command=>!/^[a-z][a-z0-9-]*$/.test(command)))throw new Error("toolbox.page.commands 必须包含 1-64 个不重复的插件命令名称");let page={type:"sandbox",...pageCandidate.runtime?{runtime:pageCandidate.runtime}:{},entry:pageEntry,commands};if("lifecycle"in pageCandidate)throw new Error("toolbox.page.lifecycle is unsupported; declare pageRuntime and activation rules");let agent;if(candidate.agent!==void 0){if(!candidate.agent||typeof candidate.agent!="object"||Array.isArray(candidate.agent))throw new Error("toolbox.agent 必须是对象");let agentCandidate=candidate.agent,skill=typeof agentCandidate.skill=="string"?agentCandidate.skill.trim():"";if(!skill||skill.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(skill))throw new Error("toolbox.agent.skill 必须是有效的 Skill 名称");let layout=agentCandidate.layout;if(layout!==void 0&&layout!=="drawer"&&layout!=="workspace")throw new Error("toolbox.agent.layout 必须是 drawer 或 workspace");agent={skill,...layout?{layout}:{}}}if(candidate.order!==void 0&&(!Number.isInteger(candidate.order)||candidate.order<0||candidate.order>1e4))throw new Error("toolbox.order 必须是 0-10000 的整数");return{version:1,title,...candidate.displayMode!==void 0?{displayMode:candidate.displayMode}:{},...description?{description}:{},...icon?{icon}:{},...locales?{locales}:{},...agent?{agent}:{},page,...candidate.order!==void 0?{order:candidate.order}:{}}}function findPluginDirectoryEntry(directory){for(let filename of["main.mjs","main.py"]){let entry=join5(directory,"scripts",filename);try{if(statSync4(entry).isFile())return entry}catch{}}}function resolvePluginEntry(target){let absolute=resolve2(target);try{let entry=statSync4(absolute).isDirectory()?findPluginDirectoryEntry(absolute):absolute;if(!entry)throw new Error("not a file");if(!statSync4(entry).isFile())throw new Error("not a file");return entry}catch{throw new PluginError("PLUGIN_ENTRY_MISSING",`入口不存在: ${absolute}(目录默认使用 scripts/main.mjs 或 scripts/main.py)`)}}function registerPlugin(name,target,description,options={}){assertPluginName(name);let entry=resolvePluginEntry(target),entryVersion=pluginFileVersion(entry),directory=pluginDirectory();mkdirSync2(directory,{recursive:!0,mode:448});let file=join5(directory,`${name}.json`),temporary=`${file}.${randomUUID2()}.tmp`,summary=description?.trim(),managedBy=options.managedBy?.trim(),toolbox;try{toolbox=normalizePluginToolboxContribution(options.toolbox)}catch(error2){throw new PluginError("PLUGIN_INVALID_TOOLBOX",error2 instanceof Error?error2.message:String(error2))}let builtPage;if(toolbox){try{builtPage=buildPluginPageBundle(entry,toolbox.page.entry)}catch(error2){throw new PluginError("PLUGIN_INVALID_TOOLBOX_PAGE",error2 instanceof Error?error2.message:String(error2))}persistPluginPageBundle(name,builtPage)}let record2={entry,...options.hasPublicCommands!==void 0?{hasPublicCommands:options.hasPublicCommands}:{},source:{entry:entryVersion,...options.profileSources?{profiles:options.profileSources}:{},...builtPage?{page:builtPage.sources,pageRuntime:PLUGIN_PAGE_RUNTIME_HASH}:{}},...summary?{description:summary}:{},...managedBy?{managedBy}:{},...toolbox?{toolbox}:{},...options.appProfiles?{appProfiles:validateAppProfileContribution(options.appProfiles)}:{},...builtPage?{pageBundle:{hash:builtPage.hash,size:builtPage.size,chunks:builtPage.chunks}}:{}};try{writeFileSync2(temporary,`${JSON.stringify(record2)}
608
- `,{mode:384,flag:"wx"}),renameSync3(temporary,file)}finally{rmSync3(temporary,{force:!0})}return removePluginPageBundles(name,builtPage?.hash),entry}function unregisterPlugin(name){assertPluginName(name);let file=join5(pluginDirectory(),`${name}.json`);try{return rmSync3(file),rmSync3(join5(pluginDirectory(),".host","installations",`${name}.json`),{force:!0}),removePluginPageBundles(name),!0}catch(error2){if(error2.code==="ENOENT")return!1;throw new PluginError("PLUGIN_UNINSTALL_FAILED",`无法移除插件注册: ${file}`)}}function findPluginRegistration(name){if(!/^[a-z][a-z0-9-]*$/.test(name))return;let file=join5(pluginDirectory(),`${name}.json`),content;try{content=readFileSync5(file,"utf8")}catch(error2){if(error2.code==="ENOENT")return;throw new PluginError("PLUGIN_REGISTRY_INVALID",`无法读取插件记录: ${file}`)}try{let record2=JSON.parse(content);if(typeof record2?.entry!="string"||!isAbsolute2(record2.entry))throw new Error("invalid entry");if(record2.hasPublicCommands!==void 0&&typeof record2.hasPublicCommands!="boolean")throw new Error("invalid public commands");let description=typeof record2.description=="string"&&record2.description.trim()?record2.description.trim():void 0,managedBy=typeof record2.managedBy=="string"&&record2.managedBy.trim()?record2.managedBy.trim():void 0,toolbox=normalizePluginToolboxContribution(record2.toolbox),pageBundle=toolbox?normalizePageBundle(record2.pageBundle):void 0,appProfiles=validateAppProfileContribution(record2.appProfiles),source=record2.source;if(source!==void 0&&(!source||typeof source!="object"||Array.isArray(source)||typeof source.entry!="string"||source.profiles!==void 0&&(!source.profiles||typeof source.profiles!="object"||Array.isArray(source.profiles)||Object.entries(source.profiles).some(([path8,version2])=>!isAbsolute2(path8)||typeof version2!="string"))||source.pageRuntime!==void 0&&(typeof source.pageRuntime!="string"||!/^[a-f0-9]{64}$/.test(source.pageRuntime))||source.page!==void 0&&(!source.page||typeof source.page!="object"||Array.isArray(source.page)||Object.entries(source.page).some(([path8,version2])=>!isAbsolute2(path8)||typeof version2!="string"))))throw new Error("invalid source");return{entry:record2.entry,...record2.hasPublicCommands!==void 0?{hasPublicCommands:record2.hasPublicCommands}:{},...description?{description}:{},...managedBy?{managedBy}:{},...toolbox?{toolbox}:{},...pageBundle?{pageBundle}:{},...appProfiles?{appProfiles}:{},...source?{source}:{}}}catch{throw new PluginError("PLUGIN_REGISTRY_INVALID",`无效的插件记录: ${file}`)}}function readPluginPageBundleChunk(name,hash,index){assertPluginName(name);let bundle=findPluginRegistration(name)?.pageBundle;if(!bundle||bundle.hash!==hash)throw new PluginError("PLUGIN_PAGE_CHANGED",`插件页面已更新: ${name}`);if(!Number.isInteger(index)||index<0||index>=bundle.chunks)throw new PluginError("PLUGIN_PAGE_CHUNK_INVALID",`插件页面分块无效: ${index}`);let path8=pluginPageBundlePath(name,hash),size;try{size=statSync4(path8).size}catch{throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物不存在: ${name}`)}if(size!==bundle.size)throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物损坏: ${name}`);let start=index*PLUGIN_PAGE_CHUNK_BYTES,content=Buffer.allocUnsafe(Math.min(PLUGIN_PAGE_CHUNK_BYTES,bundle.size-start)),descriptor;try{descriptor=openSync3(path8,"r")}catch{throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物无法读取: ${name}`)}let bytesRead;try{bytesRead=readSync(descriptor,content,0,content.byteLength,start)}finally{closeSync3(descriptor)}if(bytesRead!==content.byteLength)throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物损坏: ${name}`);return{data:content.toString("base64"),hash,index,total:bundle.chunks}}function findPluginEntry(name){return findPluginRegistration(name)?.entry}function listPluginNames(){try{return readdirSync4(pluginDirectory()).filter(file=>/^[a-z][a-z0-9-]*\.json$/.test(file)).map(file=>file.slice(0,-5)).sort()}catch(error2){if(error2.code==="ENOENT")return[];throw new PluginError("PLUGIN_REGISTRY_INVALID","无法读取插件目录")}}var RESERVED_NAMES,PluginError,init_pluginRegistry=__esm({"../client/src/plugins/pluginRegistry.ts"(){"use strict";init_dist2();init_dist2();init_commands();init_pluginPageBundle();init_pluginSource();RESERVED_NAMES=new Set(["check","help","connector_list","capture_checkpoint","plugin","plugins"]),PluginError=class extends Error{constructor(code,message){super(`${code}: ${message}`);this.code=code}code}}});import{createHash as createHash3}from"node:crypto";import{tmpdir}from"node:os";import{join as join6}from"node:path";function pluginHostPaths(){let registry=pluginDirectory(),key2=createHash3("sha256").update(registry).digest("hex").slice(0,16),home=join6(registry,".host");return{registry,home,lease:join6(home,"service.json"),log:join6(home,"service.log"),installations:join6(home,"installations"),revisions:join6(home,"revisions"),tasks:join6(home,"tasks"),state:join6(home,"state"),socket:process.platform==="win32"?`\\\\.\\pipe\\mearl-plugin-${key2}`:join6(tmpdir(),`mp-${key2}.sock`)}}var init_pluginHostPaths=__esm({"../client/src/plugins/runtime/pluginHostPaths.ts"(){"use strict";init_pluginRegistry()}});var CODEX_MODEL_CAPABILITY,init_capabilities=__esm({"../agent-runtime/dist/capabilities.js"(){"use strict";CODEX_MODEL_CAPABILITY={provider:"codex",modes:["agent"],permissions:["read-only"],structuredOutput:!0,streaming:!0,cancellation:!0}}});var require_code=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.regexpCode=exports.getEsmExportName=exports.getProperty=exports.safeStringify=exports.stringify=exports.strConcat=exports.addCodeArg=exports.str=exports._=exports.nil=exports._Code=exports.Name=exports.IDENTIFIER=exports._CodeOrName=void 0;var _CodeOrName=class{};exports._CodeOrName=_CodeOrName;exports.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{constructor(s){if(super(),!exports.IDENTIFIER.test(s))throw new Error("CodeGen: name must be a valid identifier");this.str=s}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};exports.Name=Name;var _Code=class extends _CodeOrName{constructor(code){super(),this._items=typeof code=="string"?[code]:code}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let item=this._items[0];return item===""||item==='""'}get str(){var _a;return(_a=this._str)!==null&&_a!==void 0?_a:this._str=this._items.reduce((s,c)=>`${s}${c}`,"")}get names(){var _a;return(_a=this._names)!==null&&_a!==void 0?_a:this._names=this._items.reduce((names,c)=>(c instanceof Name&&(names[c.str]=(names[c.str]||0)+1),names),{})}};exports._Code=_Code;exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i2=0;for(;i2<args.length;)addCodeArg(code,args[i2]),code.push(strs[++i2]);return new _Code(code)}exports._=_;var plus=new _Code("+");function str(strs,...args){let expr=[safeStringify(strs[0])],i2=0;for(;i2<args.length;)expr.push(plus),addCodeArg(expr,args[i2]),expr.push(plus,safeStringify(strs[++i2]));return optimize(expr),new _Code(expr)}exports.str=str;function addCodeArg(code,arg){arg instanceof _Code?code.push(...arg._items):arg instanceof Name?code.push(arg):code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i2=1;for(;i2<expr.length-1;){if(expr[i2]===plus){let res=mergeExprItems(expr[i2-1],expr[i2+1]);if(res!==void 0){expr.splice(i2-1,3,res);continue}expr[i2++]="+"}i2++}}function mergeExprItems(a,b){if(b==='""')return a;if(a==='""')return b;if(typeof a=="string")return b instanceof Name||a[a.length-1]!=='"'?void 0:typeof b!="string"?`${a.slice(0,-1)}${b}"`:b[0]==='"'?a.slice(0,-1)+b.slice(1):void 0;if(typeof b=="string"&&b[0]==='"'&&!(a instanceof Name))return`"${a}${b.slice(1)}`}function strConcat(c1,c2){return c2.emptyStr()?c1:c1.emptyStr()?c2:str`${c1}${c2}`}exports.strConcat=strConcat;function interpolate(x){return typeof x=="number"||typeof x=="boolean"||x===null?x:safeStringify(Array.isArray(x)?x.join(","):x)}function stringify(x){return new _Code(safeStringify(x))}exports.stringify=stringify;function safeStringify(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}exports.safeStringify=safeStringify;function getProperty(key2){return typeof key2=="string"&&exports.IDENTIFIER.test(key2)?new _Code(`.${key2}`):_`[${key2}]`}exports.getProperty=getProperty;function getEsmExportName(key2){if(typeof key2=="string"&&exports.IDENTIFIER.test(key2))return new _Code(`${key2}`);throw new Error(`CodeGen: invalid export name: ${key2}, use explicit $id name mapping`)}exports.getEsmExportName=getEsmExportName;function regexpCode(rx){return new _Code(rx.toString())}exports.regexpCode=regexpCode}});var require_scope=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ValueScope=exports.ValueScopeName=exports.Scope=exports.varKinds=exports.UsedValueState=void 0;var code_1=require_code(),ValueError=class extends Error{constructor(name){super(`CodeGen: "code" for ${name} not defined`),this.value=name.value}},UsedValueState;(function(UsedValueState2){UsedValueState2[UsedValueState2.Started=0]="Started",UsedValueState2[UsedValueState2.Completed=1]="Completed"})(UsedValueState||(exports.UsedValueState=UsedValueState={}));exports.varKinds={const:new code_1.Name("const"),let:new code_1.Name("let"),var:new code_1.Name("var")};var Scope3=class{constructor({prefixes,parent}={}){this._names={},this._prefixes=prefixes,this._parent=parent}toName(nameOrPrefix){return nameOrPrefix instanceof code_1.Name?nameOrPrefix:this.name(nameOrPrefix)}name(prefix){return new code_1.Name(this._newName(prefix))}_newName(prefix){let ng=this._names[prefix]||this._nameGroup(prefix);return`${prefix}${ng.index++}`}_nameGroup(prefix){var _a,_b;if(!((_b=(_a=this._parent)===null||_a===void 0?void 0:_a._prefixes)===null||_b===void 0)&&_b.has(prefix)||this._prefixes&&!this._prefixes.has(prefix))throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);return this._names[prefix]={prefix,index:0}}};exports.Scope=Scope3;var ValueScopeName=class extends code_1.Name{constructor(prefix,nameStr){super(nameStr),this.prefix=prefix}setValue(value,{property,itemIndex}){this.value=value,this.scopePath=(0,code_1._)`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;var line=(0,code_1._)`\n`,ValueScope=class extends Scope3{constructor(opts){super(opts),this._values={},this._scope=opts.scope,this.opts={...opts,_n:opts.lines?line:code_1.nil}}get(){return this._scope}name(prefix){return new ValueScopeName(prefix,this._newName(prefix))}value(nameOrPrefix,value){var _a;if(value.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let name=this.toName(nameOrPrefix),{prefix}=name,valueKey=(_a=value.key)!==null&&_a!==void 0?_a:value.ref,vs=this._values[prefix];if(vs){let _name=vs.get(valueKey);if(_name)return _name}else vs=this._values[prefix]=new Map;vs.set(valueKey,name);let s=this._scope[prefix]||(this._scope[prefix]=[]),itemIndex=s.length;return s[itemIndex]=value.ref,name.setValue(value,{property:prefix,itemIndex}),name}getValue(prefix,keyOrRef){let vs=this._values[prefix];if(vs)return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,name=>{if(name.scopePath===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return(0,code_1._)`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,name=>{if(name.value===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return name.value.code},usedValues,getCode)}_reduceValues(values,valueCode,usedValues={},getCode){let code=code_1.nil;for(let prefix in values){let vs=values[prefix];if(!vs)continue;let nameSet=usedValues[prefix]=usedValues[prefix]||new Map;vs.forEach(name=>{if(nameSet.has(name))return;nameSet.set(name,UsedValueState.Started);let c=valueCode(name);if(c){let def=this.opts.es5?exports.varKinds.var:exports.varKinds.const;code=(0,code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode?.(name))code=(0,code_1._)`${code}${c}${this.opts._n}`;else throw new ValueError(name);nameSet.set(name,UsedValueState.Completed)})}return code}};exports.ValueScope=ValueScope}});var require_codegen=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.or=exports.and=exports.not=exports.CodeGen=exports.operators=exports.varKinds=exports.ValueScopeName=exports.ValueScope=exports.Scope=exports.Name=exports.regexpCode=exports.stringify=exports.getProperty=exports.nil=exports.strConcat=exports.str=exports._=void 0;var code_1=require_code(),scope_1=require_scope(),code_2=require_code();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return code_2._}});Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return code_2.str}});Object.defineProperty(exports,"strConcat",{enumerable:!0,get:function(){return code_2.strConcat}});Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return code_2.nil}});Object.defineProperty(exports,"getProperty",{enumerable:!0,get:function(){return code_2.getProperty}});Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return code_2.stringify}});Object.defineProperty(exports,"regexpCode",{enumerable:!0,get:function(){return code_2.regexpCode}});Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return code_2.Name}});var scope_2=require_scope();Object.defineProperty(exports,"Scope",{enumerable:!0,get:function(){return scope_2.Scope}});Object.defineProperty(exports,"ValueScope",{enumerable:!0,get:function(){return scope_2.ValueScope}});Object.defineProperty(exports,"ValueScopeName",{enumerable:!0,get:function(){return scope_2.ValueScopeName}});Object.defineProperty(exports,"varKinds",{enumerable:!0,get:function(){return scope_2.varKinds}});exports.operators={GT:new code_1._Code(">"),GTE:new code_1._Code(">="),LT:new code_1._Code("<"),LTE:new code_1._Code("<="),EQ:new code_1._Code("==="),NEQ:new code_1._Code("!=="),NOT:new code_1._Code("!"),OR:new code_1._Code("||"),AND:new code_1._Code("&&"),ADD:new code_1._Code("+")};var Node4=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node4{constructor(varKind,name,rhs){super(),this.varKind=varKind,this.name=name,this.rhs=rhs}render({es5,_n}){let varKind=es5?scope_1.varKinds.var:this.varKind,rhs=this.rhs===void 0?"":` = ${this.rhs}`;return`${varKind} ${this.name}${rhs};`+_n}optimizeNames(names,constants2){if(names[this.name.str])return this.rhs&&(this.rhs=optimizeExpr(this.rhs,names,constants2)),this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node4{constructor(lhs,rhs,sideEffects){super(),this.lhs=lhs,this.rhs=rhs,this.sideEffects=sideEffects}render({_n}){return`${this.lhs} = ${this.rhs};`+_n}optimizeNames(names,constants2){if(!(this.lhs instanceof code_1.Name&&!names[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,names,constants2),this}get names(){let names=this.lhs instanceof code_1.Name?{}:{...this.lhs.names};return addExprNames(names,this.rhs)}},AssignOp=class extends Assign{constructor(lhs,op,rhs,sideEffects){super(lhs,rhs,sideEffects),this.op=op}render({_n}){return`${this.lhs} ${this.op}= ${this.rhs};`+_n}},Label=class extends Node4{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node4{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node4{constructor(error2){super(),this.error=error2}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node4{constructor(code){super(),this.code=code}render({_n}){return`${this.code};`+_n}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(names,constants2){return this.code=optimizeExpr(this.code,names,constants2),this}get names(){return this.code instanceof code_1._CodeOrName?this.code.names:{}}},ParentNode=class extends Node4{constructor(nodes=[]){super(),this.nodes=nodes}render(opts){return this.nodes.reduce((code,n)=>code+n.render(opts),"")}optimizeNodes(){let{nodes}=this,i2=nodes.length;for(;i2--;){let n=nodes[i2].optimizeNodes();Array.isArray(n)?nodes.splice(i2,1,...n):n?nodes[i2]=n:nodes.splice(i2,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants2){let{nodes}=this,i2=nodes.length;for(;i2--;){let n=nodes[i2];n.optimizeNames(names,constants2)||(subtractNames(names,n.names),nodes.splice(i2,1))}return nodes.length>0?this:void 0}get names(){return this.nodes.reduce((names,n)=>addNames(names,n.names),{})}},BlockNode=class extends ParentNode{render(opts){return"{"+opts._n+super.render(opts)+"}"+opts._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind="else";var If=class _If extends BlockNode{constructor(condition,nodes){super(nodes),this.condition=condition}render(opts){let code=`if(${this.condition})`+super.render(opts);return this.else&&(code+="else "+this.else.render(opts)),code}optimizeNodes(){super.optimizeNodes();let cond=this.condition;if(cond===!0)return this.nodes;let e=this.else;if(e){let ns=e.optimizeNodes();e=this.else=Array.isArray(ns)?new Else(ns):ns}if(e)return cond===!1?e instanceof _If?e:e.nodes:this.nodes.length?this:new _If(not(cond),e instanceof _If?[e]:e.nodes);if(!(cond===!1||!this.nodes.length))return this}optimizeNames(names,constants2){var _a;if(this.else=(_a=this.else)===null||_a===void 0?void 0:_a.optimizeNames(names,constants2),!!(super.optimizeNames(names,constants2)||this.else))return this.condition=optimizeExpr(this.condition,names,constants2),this}get names(){let names=super.names;return addExprNames(names,this.condition),this.else&&addNames(names,this.else.names),names}};If.kind="if";var For=class extends BlockNode{};For.kind="for";var ForLoop=class extends For{constructor(iteration){super(),this.iteration=iteration}render(opts){return`for(${this.iteration})`+super.render(opts)}optimizeNames(names,constants2){if(super.optimizeNames(names,constants2))return this.iteration=optimizeExpr(this.iteration,names,constants2),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(varKind,name,from,to){super(),this.varKind=varKind,this.name=name,this.from=from,this.to=to}render(opts){let varKind=opts.es5?scope_1.varKinds.var:this.varKind,{name,from,to}=this;return`for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)`+super.render(opts)}get names(){let names=addExprNames(super.names,this.from);return addExprNames(names,this.to)}},ForIter=class extends For{constructor(loop,varKind,name,iterable){super(),this.loop=loop,this.varKind=varKind,this.name=name,this.iterable=iterable}render(opts){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(opts)}optimizeNames(names,constants2){if(super.optimizeNames(names,constants2))return this.iterable=optimizeExpr(this.iterable,names,constants2),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(name,args,async){super(),this.name=name,this.args=args,this.async=async}render(opts){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(opts)}};Func.kind="func";var Return=class extends ParentNode{render(opts){return"return "+super.render(opts)}};Return.kind="return";var Try=class extends BlockNode{render(opts){let code="try"+super.render(opts);return this.catch&&(code+=this.catch.render(opts)),this.finally&&(code+=this.finally.render(opts)),code}optimizeNodes(){var _a,_b;return super.optimizeNodes(),(_a=this.catch)===null||_a===void 0||_a.optimizeNodes(),(_b=this.finally)===null||_b===void 0||_b.optimizeNodes(),this}optimizeNames(names,constants2){var _a,_b;return super.optimizeNames(names,constants2),(_a=this.catch)===null||_a===void 0||_a.optimizeNames(names,constants2),(_b=this.finally)===null||_b===void 0||_b.optimizeNames(names,constants2),this}get names(){let names=super.names;return this.catch&&addNames(names,this.catch.names),this.finally&&addNames(names,this.finally.names),names}},Catch=class extends BlockNode{constructor(error2){super(),this.error=error2}render(opts){return`catch(${this.error})`+super.render(opts)}};Catch.kind="catch";var Finally=class extends BlockNode{render(opts){return"finally"+super.render(opts)}};Finally.kind="finally";var CodeGen=class{constructor(extScope,opts={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...opts,_n:opts.lines?`
609
- `:""},this._extScope=extScope,this._scope=new scope_1.Scope({parent:extScope}),this._nodes=[new Root]}toString(){return this._root.render(this.opts)}name(prefix){return this._scope.name(prefix)}scopeName(prefix){return this._extScope.name(prefix)}scopeValue(prefixOrName,value){let name=this._extScope.value(prefixOrName,value);return(this._values[name.prefix]||(this._values[name.prefix]=new Set)).add(name),name}getScopeValue(prefix,keyOrRef){return this._extScope.getValue(prefix,keyOrRef)}scopeRefs(scopeName){return this._extScope.scopeRefs(scopeName,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(varKind,nameOrPrefix,rhs,constant){let name=this._scope.toName(nameOrPrefix);return rhs!==void 0&&constant&&(this._constants[name.str]=rhs),this._leafNode(new Def(varKind,name,rhs)),name}const(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.const,nameOrPrefix,rhs,_constant)}let(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.let,nameOrPrefix,rhs,_constant)}var(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.var,nameOrPrefix,rhs,_constant)}assign(lhs,rhs,sideEffects){return this._leafNode(new Assign(lhs,rhs,sideEffects))}add(lhs,rhs){return this._leafNode(new AssignOp(lhs,exports.operators.ADD,rhs))}code(c){return typeof c=="function"?c():c!==code_1.nil&&this._leafNode(new AnyCode(c)),this}object(...keyValues){let code=["{"];for(let[key2,value]of keyValues)code.length>1&&code.push(","),code.push(key2),(key2!==value||this.opts.es5)&&(code.push(":"),(0,code_1.addCodeArg)(code,value));return code.push("}"),new code_1._Code(code)}if(condition,thenBody,elseBody){if(this._blockNode(new If(condition)),thenBody&&elseBody)this.code(thenBody).else().code(elseBody).endIf();else if(thenBody)this.code(thenBody).endIf();else if(elseBody)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(condition){return this._elseNode(new If(condition))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(If,Else)}_for(node,forBody){return this._blockNode(node),forBody&&this.code(forBody).endFor(),this}for(iteration,forBody){return this._for(new ForLoop(iteration),forBody)}forRange(nameOrPrefix,from,to,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.let){let name=this._scope.toName(nameOrPrefix);return this._for(new ForRange(varKind,name,from,to),()=>forBody(name))}forOf(nameOrPrefix,iterable,forBody,varKind=scope_1.varKinds.const){let name=this._scope.toName(nameOrPrefix);if(this.opts.es5){let arr=iterable instanceof code_1.Name?iterable:this.var("_arr",iterable);return this.forRange("_i",0,(0,code_1._)`${arr}.length`,i2=>{this.var(name,(0,code_1._)`${arr}[${i2}]`),forBody(name)})}return this._for(new ForIter("of",varKind,name,iterable),()=>forBody(name))}forIn(nameOrPrefix,obj,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.const){if(this.opts.ownProperties)return this.forOf(nameOrPrefix,(0,code_1._)`Object.keys(${obj})`,forBody);let name=this._scope.toName(nameOrPrefix);return this._for(new ForIter("in",varKind,name,obj),()=>forBody(name))}endFor(){return this._endBlockNode(For)}label(label){return this._leafNode(new Label(label))}break(label){return this._leafNode(new Break(label))}return(value){let node=new Return;if(this._blockNode(node),this.code(value),node.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Return)}try(tryBody,catchCode,finallyCode){if(!catchCode&&!finallyCode)throw new Error('CodeGen: "try" without "catch" and "finally"');let node=new Try;if(this._blockNode(node),this.code(tryBody),catchCode){let error2=this.name("e");this._currNode=node.catch=new Catch(error2),catchCode(error2)}return finallyCode&&(this._currNode=node.finally=new Finally,this.code(finallyCode)),this._endBlockNode(Catch,Finally)}throw(error2){return this._leafNode(new Throw(error2))}block(body,nodeCount){return this._blockStarts.push(this._nodes.length),body&&this.code(body).endBlock(nodeCount),this}endBlock(nodeCount){let len=this._blockStarts.pop();if(len===void 0)throw new Error("CodeGen: not in self-balancing block");let toClose=this._nodes.length-len;if(toClose<0||nodeCount!==void 0&&toClose!==nodeCount)throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);return this._nodes.length=len,this}func(name,args=code_1.nil,async,funcBody){return this._blockNode(new Func(name,args,async)),funcBody&&this.code(funcBody).endFunc(),this}endFunc(){return this._endBlockNode(Func)}optimize(n=1){for(;n-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(node){return this._currNode.nodes.push(node),this}_blockNode(node){this._currNode.nodes.push(node),this._nodes.push(node)}_endBlockNode(N1,N2){let n=this._currNode;if(n instanceof N1||N2&&n instanceof N2)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N2?`${N1.kind}/${N2.kind}`:N1.kind}"`)}_elseNode(node){let n=this._currNode;if(!(n instanceof If))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=node,this}get _root(){return this._nodes[0]}get _currNode(){let ns=this._nodes;return ns[ns.length-1]}set _currNode(node){let ns=this._nodes;ns[ns.length-1]=node}};exports.CodeGen=CodeGen;function addNames(names,from){for(let n in from)names[n]=(names[n]||0)+(from[n]||0);return names}function addExprNames(names,from){return from instanceof code_1._CodeOrName?addNames(names,from.names):names}function optimizeExpr(expr,names,constants2){if(expr instanceof code_1.Name)return replaceName(expr);if(!canOptimize(expr))return expr;return new code_1._Code(expr._items.reduce((items,c)=>(c instanceof code_1.Name&&(c=replaceName(c)),c instanceof code_1._Code?items.push(...c._items):items.push(c),items),[]));function replaceName(n){let c=constants2[n.str];return c===void 0||names[n.str]!==1?n:(delete names[n.str],c)}function canOptimize(e){return e instanceof code_1._Code&&e._items.some(c=>c instanceof code_1.Name&&names[c.str]===1&&constants2[c.str]!==void 0)}}function subtractNames(names,from){for(let n in from)names[n]=(names[n]||0)-(from[n]||0)}function not(x){return typeof x=="boolean"||typeof x=="number"||x===null?!x:(0,code_1._)`!${par(x)}`}exports.not=not;var andCode=mappend(exports.operators.AND);function and(...args){return args.reduce(andCode)}exports.and=and;var orCode=mappend(exports.operators.OR);function or(...args){return args.reduce(orCode)}exports.or=or;function mappend(op){return(x,y)=>x===code_1.nil?y:y===code_1.nil?x:(0,code_1._)`${par(x)} ${op} ${par(y)}`}function par(x){return x instanceof code_1.Name?x:(0,code_1._)`(${x})`}}});var require_util=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.checkStrictMode=exports.getErrorPath=exports.Type=exports.useFunc=exports.setEvaluated=exports.evaluatedPropsToName=exports.mergeEvaluated=exports.eachItem=exports.unescapeJsonPointer=exports.escapeJsonPointer=exports.escapeFragment=exports.unescapeFragment=exports.schemaRefOrVal=exports.schemaHasRulesButRef=exports.schemaHasRules=exports.checkUnknownRules=exports.alwaysValidSchema=exports.toHash=void 0;var codegen_1=require_codegen(),code_1=require_code();function toHash(arr){let hash={};for(let item of arr)hash[item]=!0;return hash}exports.toHash=toHash;function alwaysValidSchema(it,schema){return typeof schema=="boolean"?schema:Object.keys(schema).length===0?!0:(checkUnknownRules(it,schema),!schemaHasRules(schema,it.self.RULES.all))}exports.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(it,schema=it.schema){let{opts,self}=it;if(!opts.strictSchema||typeof schema=="boolean")return;let rules=self.RULES.keywords;for(let key2 in schema)rules[key2]||checkStrictMode(it,`unknown keyword: "${key2}"`)}exports.checkUnknownRules=checkUnknownRules;function schemaHasRules(schema,rules){if(typeof schema=="boolean")return!schema;for(let key2 in schema)if(rules[key2])return!0;return!1}exports.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(schema,RULES){if(typeof schema=="boolean")return!schema;for(let key2 in schema)if(key2!=="$ref"&&RULES.all[key2])return!0;return!1}exports.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef,schemaPath},schema,keyword,$data){if(!$data){if(typeof schema=="number"||typeof schema=="boolean")return schema;if(typeof schema=="string")return(0,codegen_1._)`${schema}`}return(0,codegen_1._)`${topSchemaRef}${schemaPath}${(0,codegen_1.getProperty)(keyword)}`}exports.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}exports.unescapeFragment=unescapeFragment;function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}exports.escapeFragment=escapeFragment;function escapeJsonPointer(str){return typeof str=="number"?`${str}`:str.replace(/~/g,"~0").replace(/\//g,"~1")}exports.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}exports.unescapeJsonPointer=unescapeJsonPointer;function eachItem(xs,f){if(Array.isArray(xs))for(let x of xs)f(x);else f(xs)}exports.eachItem=eachItem;function makeMergeEvaluated({mergeNames,mergeToName,mergeValues,resultToName}){return(gen,from,to,toName)=>{let res=to===void 0?from:to instanceof codegen_1.Name?(from instanceof codegen_1.Name?mergeNames(gen,from,to):mergeToName(gen,from,to),to):from instanceof codegen_1.Name?(mergeToName(gen,to,from),from):mergeValues(from,to);return toName===codegen_1.Name&&!(res instanceof codegen_1.Name)?resultToName(gen,res):res}}exports.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>{gen.if((0,codegen_1._)`${from} === true`,()=>gen.assign(to,!0),()=>gen.assign(to,(0,codegen_1._)`${to} || {}`).code((0,codegen_1._)`Object.assign(${to}, ${from})`))}),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>{from===!0?gen.assign(to,!0):(gen.assign(to,(0,codegen_1._)`${to} || {}`),setEvaluated(gen,to,from))}),mergeValues:(from,to)=>from===!0?!0:{...from,...to},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>gen.assign(to,(0,codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>gen.assign(to,from===!0?!0:(0,codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),mergeValues:(from,to)=>from===!0?!0:Math.max(from,to),resultToName:(gen,items)=>gen.var("items",items)})};function evaluatedPropsToName(gen,ps){if(ps===!0)return gen.var("props",!0);let props=gen.var("props",(0,codegen_1._)`{}`);return ps!==void 0&&setEvaluated(gen,props,ps),props}exports.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(gen,props,ps){Object.keys(ps).forEach(p=>gen.assign((0,codegen_1._)`${props}${(0,codegen_1.getProperty)(p)}`,!0))}exports.setEvaluated=setEvaluated;var snippets={};function useFunc(gen,f){return gen.scopeValue("func",{ref:f,code:snippets[f.code]||(snippets[f.code]=new code_1._Code(f.code))})}exports.useFunc=useFunc;var Type;(function(Type2){Type2[Type2.Num=0]="Num",Type2[Type2.Str=1]="Str"})(Type||(exports.Type=Type={}));function getErrorPath(dataProp,dataPropType,jsPropertySyntax){if(dataProp instanceof codegen_1.Name){let isNumber=dataPropType===Type.Num;return jsPropertySyntax?isNumber?(0,codegen_1._)`"[" + ${dataProp} + "]"`:(0,codegen_1._)`"['" + ${dataProp} + "']"`:isNumber?(0,codegen_1._)`"/" + ${dataProp}`:(0,codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return jsPropertySyntax?(0,codegen_1.getProperty)(dataProp).toString():"/"+escapeJsonPointer(dataProp)}exports.getErrorPath=getErrorPath;function checkStrictMode(it,msg,mode=it.opts.strictSchema){if(mode){if(msg=`strict mode: ${msg}`,mode===!0)throw new Error(msg);it.self.logger.warn(msg)}}exports.checkStrictMode=checkStrictMode}});var require_names=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),names={data:new codegen_1.Name("data"),valCxt:new codegen_1.Name("valCxt"),instancePath:new codegen_1.Name("instancePath"),parentData:new codegen_1.Name("parentData"),parentDataProperty:new codegen_1.Name("parentDataProperty"),rootData:new codegen_1.Name("rootData"),dynamicAnchors:new codegen_1.Name("dynamicAnchors"),vErrors:new codegen_1.Name("vErrors"),errors:new codegen_1.Name("errors"),this:new codegen_1.Name("this"),self:new codegen_1.Name("self"),scope:new codegen_1.Name("scope"),json:new codegen_1.Name("json"),jsonPos:new codegen_1.Name("jsonPos"),jsonLen:new codegen_1.Name("jsonLen"),jsonPart:new codegen_1.Name("jsonPart")};exports.default=names}});var require_errors=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.extendErrors=exports.resetErrorsCount=exports.reportExtraError=exports.reportError=exports.keyword$DataError=exports.keywordError=void 0;var codegen_1=require_codegen(),util_1=require_util(),names_1=require_names();exports.keywordError={message:({keyword})=>(0,codegen_1.str)`must pass "${keyword}" keyword validation`};exports.keyword$DataError={message:({keyword,schemaType})=>schemaType?(0,codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)`:(0,codegen_1.str)`"${keyword}" keyword is invalid ($data)`};function reportError(cxt,error2=exports.keywordError,errorPaths,overrideAllErrors){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error2,errorPaths);overrideAllErrors??(compositeRule||allErrors)?addError(gen,errObj):returnErrors(it,(0,codegen_1._)`[${errObj}]`)}exports.reportError=reportError;function reportExtraError(cxt,error2=exports.keywordError,errorPaths){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error2,errorPaths);addError(gen,errObj),compositeRule||allErrors||returnErrors(it,names_1.default.vErrors)}exports.reportExtraError=reportExtraError;function resetErrorsCount(gen,errsCount){gen.assign(names_1.default.errors,errsCount),gen.if((0,codegen_1._)`${names_1.default.vErrors} !== null`,()=>gen.if(errsCount,()=>gen.assign((0,codegen_1._)`${names_1.default.vErrors}.length`,errsCount),()=>gen.assign(names_1.default.vErrors,null)))}exports.resetErrorsCount=resetErrorsCount;function extendErrors({gen,keyword,schemaValue,data:data2,errsCount,it}){if(errsCount===void 0)throw new Error("ajv implementation error");let err=gen.name("err");gen.forRange("i",errsCount,names_1.default.errors,i2=>{gen.const(err,(0,codegen_1._)`${names_1.default.vErrors}[${i2}]`),gen.if((0,codegen_1._)`${err}.instancePath === undefined`,()=>gen.assign((0,codegen_1._)`${err}.instancePath`,(0,codegen_1.strConcat)(names_1.default.instancePath,it.errorPath))),gen.assign((0,codegen_1._)`${err}.schemaPath`,(0,codegen_1.str)`${it.errSchemaPath}/${keyword}`),it.opts.verbose&&(gen.assign((0,codegen_1._)`${err}.schema`,schemaValue),gen.assign((0,codegen_1._)`${err}.data`,data2))})}exports.extendErrors=extendErrors;function addError(gen,errObj){let err=gen.const("err",errObj);gen.if((0,codegen_1._)`${names_1.default.vErrors} === null`,()=>gen.assign(names_1.default.vErrors,(0,codegen_1._)`[${err}]`),(0,codegen_1._)`${names_1.default.vErrors}.push(${err})`),gen.code((0,codegen_1._)`${names_1.default.errors}++`)}function returnErrors(it,errs){let{gen,validateName,schemaEnv}=it;schemaEnv.$async?gen.throw((0,codegen_1._)`new ${it.ValidationError}(${errs})`):(gen.assign((0,codegen_1._)`${validateName}.errors`,errs),gen.return(!1))}var E={keyword:new codegen_1.Name("keyword"),schemaPath:new codegen_1.Name("schemaPath"),params:new codegen_1.Name("params"),propertyName:new codegen_1.Name("propertyName"),message:new codegen_1.Name("message"),schema:new codegen_1.Name("schema"),parentSchema:new codegen_1.Name("parentSchema")};function errorObjectCode(cxt,error2,errorPaths){let{createErrors}=cxt.it;return createErrors===!1?(0,codegen_1._)`{}`:errorObject(cxt,error2,errorPaths)}function errorObject(cxt,error2,errorPaths={}){let{gen,it}=cxt,keyValues=[errorInstancePath(it,errorPaths),errorSchemaPath(cxt,errorPaths)];return extraErrorProps(cxt,error2,keyValues),gen.object(...keyValues)}function errorInstancePath({errorPath},{instancePath}){let instPath=instancePath?(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(instancePath,util_1.Type.Str)}`:errorPath;return[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,instPath)]}function errorSchemaPath({keyword,it:{errSchemaPath}},{schemaPath,parentSchema}){let schPath=parentSchema?errSchemaPath:(0,codegen_1.str)`${errSchemaPath}/${keyword}`;return schemaPath&&(schPath=(0,codegen_1.str)`${schPath}${(0,util_1.getErrorPath)(schemaPath,util_1.Type.Str)}`),[E.schemaPath,schPath]}function extraErrorProps(cxt,{params,message},keyValues){let{keyword,data:data2,schemaValue,it}=cxt,{opts,propertyName,topSchemaRef,schemaPath}=it;keyValues.push([E.keyword,keyword],[E.params,typeof params=="function"?params(cxt):params||(0,codegen_1._)`{}`]),opts.messages&&keyValues.push([E.message,typeof message=="function"?message(cxt):message]),opts.verbose&&keyValues.push([E.schema,schemaValue],[E.parentSchema,(0,codegen_1._)`${topSchemaRef}${schemaPath}`],[names_1.default.data,data2]),propertyName&&keyValues.push([E.propertyName,propertyName])}}});var require_boolSchema=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.boolOrEmptySchema=exports.topBoolOrEmptySchema=void 0;var errors_1=require_errors(),codegen_1=require_codegen(),names_1=require_names(),boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(it){let{gen,schema,validateName}=it;schema===!1?falseSchemaError(it,!1):typeof schema=="object"&&schema.$async===!0?gen.return(names_1.default.data):(gen.assign((0,codegen_1._)`${validateName}.errors`,null),gen.return(!0))}exports.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(it,valid){let{gen,schema}=it;schema===!1?(gen.var(valid,!1),falseSchemaError(it)):gen.var(valid,!0)}exports.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(it,overrideAllErrors){let{gen,data:data2}=it,cxt={gen,keyword:"false schema",data:data2,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it};(0,errors_1.reportError)(cxt,boolError,void 0,overrideAllErrors)}}});var require_rules=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRules=exports.isJSONType=void 0;var _jsonTypes=["string","number","integer","boolean","null","object","array"],jsonTypes=new Set(_jsonTypes);function isJSONType(x){return typeof x=="string"&&jsonTypes.has(x)}exports.isJSONType=isJSONType;function getRules(){let groups={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...groups,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},groups.number,groups.string,groups.array,groups.object],post:{rules:[]},all:{},keywords:{}}}exports.getRules=getRules}});var require_applicability=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.shouldUseRule=exports.shouldUseGroup=exports.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema,self},type){let group=self.RULES.types[type];return group&&group!==!0&&shouldUseGroup(schema,group)}exports.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(schema,group){return group.rules.some(rule=>shouldUseRule(schema,rule))}exports.shouldUseGroup=shouldUseGroup;function shouldUseRule(schema,rule){var _a;return schema[rule.keyword]!==void 0||((_a=rule.definition.implements)===null||_a===void 0?void 0:_a.some(kwd=>schema[kwd]!==void 0))}exports.shouldUseRule=shouldUseRule}});var require_dataType=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.reportTypeError=exports.checkDataTypes=exports.checkDataType=exports.coerceAndCheckDataType=exports.getJSONTypes=exports.getSchemaTypes=exports.DataType=void 0;var rules_1=require_rules(),applicability_1=require_applicability(),errors_1=require_errors(),codegen_1=require_codegen(),util_1=require_util(),DataType;(function(DataType2){DataType2[DataType2.Correct=0]="Correct",DataType2[DataType2.Wrong=1]="Wrong"})(DataType||(exports.DataType=DataType={}));function getSchemaTypes(schema){let types2=getJSONTypes(schema.type);if(types2.includes("null")){if(schema.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!types2.length&&schema.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');schema.nullable===!0&&types2.push("null")}return types2}exports.getSchemaTypes=getSchemaTypes;function getJSONTypes(ts){let types2=Array.isArray(ts)?ts:ts?[ts]:[];if(types2.every(rules_1.isJSONType))return types2;throw new Error("type must be JSONType or JSONType[]: "+types2.join(","))}exports.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(it,types2){let{gen,data:data2,opts}=it,coerceTo=coerceToTypes(types2,opts.coerceTypes),checkTypes=types2.length>0&&!(coerceTo.length===0&&types2.length===1&&(0,applicability_1.schemaHasRulesForType)(it,types2[0]));if(checkTypes){let wrongType=checkDataTypes(types2,data2,opts.strictNumbers,DataType.Wrong);gen.if(wrongType,()=>{coerceTo.length?coerceData(it,types2,coerceTo):reportTypeError(it)})}return checkTypes}exports.coerceAndCheckDataType=coerceAndCheckDataType;var COERCIBLE=new Set(["string","number","integer","boolean","null"]);function coerceToTypes(types2,coerceTypes){return coerceTypes?types2.filter(t=>COERCIBLE.has(t)||coerceTypes==="array"&&t==="array"):[]}function coerceData(it,types2,coerceTo){let{gen,data:data2,opts}=it,dataType=gen.let("dataType",(0,codegen_1._)`typeof ${data2}`),coerced=gen.let("coerced",(0,codegen_1._)`undefined`);opts.coerceTypes==="array"&&gen.if((0,codegen_1._)`${dataType} == 'object' && Array.isArray(${data2}) && ${data2}.length == 1`,()=>gen.assign(data2,(0,codegen_1._)`${data2}[0]`).assign(dataType,(0,codegen_1._)`typeof ${data2}`).if(checkDataTypes(types2,data2,opts.strictNumbers),()=>gen.assign(coerced,data2))),gen.if((0,codegen_1._)`${coerced} !== undefined`);for(let t of coerceTo)(COERCIBLE.has(t)||t==="array"&&opts.coerceTypes==="array")&&coerceSpecificType(t);gen.else(),reportTypeError(it),gen.endIf(),gen.if((0,codegen_1._)`${coerced} !== undefined`,()=>{gen.assign(data2,coerced),assignParentData(it,coerced)});function coerceSpecificType(t){switch(t){case"string":gen.elseIf((0,codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced,(0,codegen_1._)`"" + ${data2}`).elseIf((0,codegen_1._)`${data2} === null`).assign(coerced,(0,codegen_1._)`""`);return;case"number":gen.elseIf((0,codegen_1._)`${dataType} == "boolean" || ${data2} === null
610
- || (${dataType} == "string" && ${data2} && ${data2} == +${data2})`).assign(coerced,(0,codegen_1._)`+${data2}`);return;case"integer":gen.elseIf((0,codegen_1._)`${dataType} === "boolean" || ${data2} === null
611
- || (${dataType} === "string" && ${data2} && ${data2} == +${data2} && !(${data2} % 1))`).assign(coerced,(0,codegen_1._)`+${data2}`);return;case"boolean":gen.elseIf((0,codegen_1._)`${data2} === "false" || ${data2} === 0 || ${data2} === null`).assign(coerced,!1).elseIf((0,codegen_1._)`${data2} === "true" || ${data2} === 1`).assign(coerced,!0);return;case"null":gen.elseIf((0,codegen_1._)`${data2} === "" || ${data2} === 0 || ${data2} === false`),gen.assign(coerced,null);return;case"array":gen.elseIf((0,codegen_1._)`${dataType} === "string" || ${dataType} === "number"
612
- || ${dataType} === "boolean" || ${data2} === null`).assign(coerced,(0,codegen_1._)`[${data2}]`)}}}function assignParentData({gen,parentData,parentDataProperty},expr){gen.if((0,codegen_1._)`${parentData} !== undefined`,()=>gen.assign((0,codegen_1._)`${parentData}[${parentDataProperty}]`,expr))}function checkDataType(dataType,data2,strictNums,correct=DataType.Correct){let EQ=correct===DataType.Correct?codegen_1.operators.EQ:codegen_1.operators.NEQ,cond;switch(dataType){case"null":return(0,codegen_1._)`${data2} ${EQ} null`;case"array":cond=(0,codegen_1._)`Array.isArray(${data2})`;break;case"object":cond=(0,codegen_1._)`${data2} && typeof ${data2} == "object" && !Array.isArray(${data2})`;break;case"integer":cond=numCond((0,codegen_1._)`!(${data2} % 1) && !isNaN(${data2})`);break;case"number":cond=numCond();break;default:return(0,codegen_1._)`typeof ${data2} ${EQ} ${dataType}`}return correct===DataType.Correct?cond:(0,codegen_1.not)(cond);function numCond(_cond=codegen_1.nil){return(0,codegen_1.and)((0,codegen_1._)`typeof ${data2} == "number"`,_cond,strictNums?(0,codegen_1._)`isFinite(${data2})`:codegen_1.nil)}}exports.checkDataType=checkDataType;function checkDataTypes(dataTypes,data2,strictNums,correct){if(dataTypes.length===1)return checkDataType(dataTypes[0],data2,strictNums,correct);let cond,types2=(0,util_1.toHash)(dataTypes);if(types2.array&&types2.object){let notObj=(0,codegen_1._)`typeof ${data2} != "object"`;cond=types2.null?notObj:(0,codegen_1._)`!${data2} || ${notObj}`,delete types2.null,delete types2.array,delete types2.object}else cond=codegen_1.nil;types2.number&&delete types2.integer;for(let t in types2)cond=(0,codegen_1.and)(cond,checkDataType(t,data2,strictNums,correct));return cond}exports.checkDataTypes=checkDataTypes;var typeError={message:({schema})=>`must be ${schema}`,params:({schema,schemaValue})=>typeof schema=="string"?(0,codegen_1._)`{type: ${schema}}`:(0,codegen_1._)`{type: ${schemaValue}}`};function reportTypeError(it){let cxt=getTypeErrorContext(it);(0,errors_1.reportError)(cxt,typeError)}exports.reportTypeError=reportTypeError;function getTypeErrorContext(it){let{gen,data:data2,schema}=it,schemaCode=(0,util_1.schemaRefOrVal)(it,schema,"type");return{gen,keyword:"type",data:data2,schema:schema.type,schemaCode,schemaValue:schemaCode,parentSchema:schema,params:{},it}}}});var require_defaults=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.assignDefaults=void 0;var codegen_1=require_codegen(),util_1=require_util();function assignDefaults(it,ty){let{properties,items}=it.schema;if(ty==="object"&&properties)for(let key2 in properties)assignDefault(it,key2,properties[key2].default);else ty==="array"&&Array.isArray(items)&&items.forEach((sch,i2)=>assignDefault(it,i2,sch.default))}exports.assignDefaults=assignDefaults;function assignDefault(it,prop,defaultValue){let{gen,compositeRule,data:data2,opts}=it;if(defaultValue===void 0)return;let childData=(0,codegen_1._)`${data2}${(0,codegen_1.getProperty)(prop)}`;if(compositeRule){(0,util_1.checkStrictMode)(it,`default is ignored for: ${childData}`);return}let condition=(0,codegen_1._)`${childData} === undefined`;opts.useDefaults==="empty"&&(condition=(0,codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`),gen.if(condition,(0,codegen_1._)`${childData} = ${(0,codegen_1.stringify)(defaultValue)}`)}}});var require_code2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.validateUnion=exports.validateArray=exports.usePattern=exports.callValidateCode=exports.schemaProperties=exports.allSchemaProperties=exports.noPropertyInData=exports.propertyInData=exports.isOwnProperty=exports.hasPropFunc=exports.reportMissingProp=exports.checkMissingProp=exports.checkReportMissingProp=void 0;var codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),util_2=require_util();function checkReportMissingProp(cxt,prop){let{gen,data:data2,it}=cxt;gen.if(noPropertyInData(gen,data2,prop,it.opts.ownProperties),()=>{cxt.setParams({missingProperty:(0,codegen_1._)`${prop}`},!0),cxt.error()})}exports.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen,data:data2,it:{opts}},properties,missing){return(0,codegen_1.or)(...properties.map(prop=>(0,codegen_1.and)(noPropertyInData(gen,data2,prop,opts.ownProperties),(0,codegen_1._)`${missing} = ${prop}`)))}exports.checkMissingProp=checkMissingProp;function reportMissingProp(cxt,missing){cxt.setParams({missingProperty:missing},!0),cxt.error()}exports.reportMissingProp=reportMissingProp;function hasPropFunc(gen){return gen.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,codegen_1._)`Object.prototype.hasOwnProperty`})}exports.hasPropFunc=hasPropFunc;function isOwnProperty(gen,data2,property){return(0,codegen_1._)`${hasPropFunc(gen)}.call(${data2}, ${property})`}exports.isOwnProperty=isOwnProperty;function propertyInData(gen,data2,property,ownProperties){let cond=(0,codegen_1._)`${data2}${(0,codegen_1.getProperty)(property)} !== undefined`;return ownProperties?(0,codegen_1._)`${cond} && ${isOwnProperty(gen,data2,property)}`:cond}exports.propertyInData=propertyInData;function noPropertyInData(gen,data2,property,ownProperties){let cond=(0,codegen_1._)`${data2}${(0,codegen_1.getProperty)(property)} === undefined`;return ownProperties?(0,codegen_1.or)(cond,(0,codegen_1.not)(isOwnProperty(gen,data2,property))):cond}exports.noPropertyInData=noPropertyInData;function allSchemaProperties(schemaMap){return schemaMap?Object.keys(schemaMap).filter(p=>p!=="__proto__"):[]}exports.allSchemaProperties=allSchemaProperties;function schemaProperties(it,schemaMap){return allSchemaProperties(schemaMap).filter(p=>!(0,util_1.alwaysValidSchema)(it,schemaMap[p]))}exports.schemaProperties=schemaProperties;function callValidateCode({schemaCode,data:data2,it:{gen,topSchemaRef,schemaPath,errorPath},it},func,context,passSchema){let dataAndSchema=passSchema?(0,codegen_1._)`${schemaCode}, ${data2}, ${topSchemaRef}${schemaPath}`:data2,valCxt=[[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,errorPath)],[names_1.default.parentData,it.parentData],[names_1.default.parentDataProperty,it.parentDataProperty],[names_1.default.rootData,names_1.default.rootData]];it.opts.dynamicRef&&valCxt.push([names_1.default.dynamicAnchors,names_1.default.dynamicAnchors]);let args=(0,codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;return context!==codegen_1.nil?(0,codegen_1._)`${func}.call(${context}, ${args})`:(0,codegen_1._)`${func}(${args})`}exports.callValidateCode=callValidateCode;var newRegExp=(0,codegen_1._)`new RegExp`;function usePattern({gen,it:{opts}},pattern2){let u=opts.unicodeRegExp?"u":"",{regExp}=opts.code,rx=regExp(pattern2,u);return gen.scopeValue("pattern",{key:rx.toString(),ref:rx,code:(0,codegen_1._)`${regExp.code==="new RegExp"?newRegExp:(0,util_2.useFunc)(gen,regExp)}(${pattern2}, ${u})`})}exports.usePattern=usePattern;function validateArray(cxt){let{gen,data:data2,keyword,it}=cxt,valid=gen.name("valid");if(it.allErrors){let validArr=gen.let("valid",!0);return validateItems(()=>gen.assign(validArr,!1)),validArr}return gen.var(valid,!0),validateItems(()=>gen.break()),valid;function validateItems(notValid){let len=gen.const("len",(0,codegen_1._)`${data2}.length`);gen.forRange("i",0,len,i2=>{cxt.subschema({keyword,dataProp:i2,dataPropType:util_1.Type.Num},valid),gen.if((0,codegen_1.not)(valid),notValid)})}}exports.validateArray=validateArray;function validateUnion(cxt){let{gen,schema,keyword,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(schema.some(sch=>(0,util_1.alwaysValidSchema)(it,sch))&&!it.opts.unevaluated)return;let valid=gen.let("valid",!1),schValid=gen.name("_valid");gen.block(()=>schema.forEach((_sch,i2)=>{let schCxt=cxt.subschema({keyword,schemaProp:i2,compositeRule:!0},schValid);gen.assign(valid,(0,codegen_1._)`${valid} || ${schValid}`),cxt.mergeValidEvaluated(schCxt,schValid)||gen.if((0,codegen_1.not)(valid))})),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0))}exports.validateUnion=validateUnion}});var require_keyword=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.validateKeywordUsage=exports.validSchemaType=exports.funcKeywordCode=exports.macroKeywordCode=void 0;var codegen_1=require_codegen(),names_1=require_names(),code_1=require_code2(),errors_1=require_errors();function macroKeywordCode(cxt,def){let{gen,keyword,schema,parentSchema,it}=cxt,macroSchema=def.macro.call(it.self,schema,parentSchema,it),schemaRef=useKeyword(gen,keyword,macroSchema);it.opts.validateSchema!==!1&&it.self.validateSchema(macroSchema,!0);let valid=gen.name("valid");cxt.subschema({schema:macroSchema,schemaPath:codegen_1.nil,errSchemaPath:`${it.errSchemaPath}/${keyword}`,topSchemaRef:schemaRef,compositeRule:!0},valid),cxt.pass(valid,()=>cxt.error(!0))}exports.macroKeywordCode=macroKeywordCode;function funcKeywordCode(cxt,def){var _a;let{gen,keyword,schema,parentSchema,$data,it}=cxt;checkAsyncKeyword(it,def);let validate=!$data&&def.compile?def.compile.call(it.self,schema,parentSchema,it):def.validate,validateRef=useKeyword(gen,keyword,validate),valid=gen.let("valid");cxt.block$data(valid,validateKeyword),cxt.ok((_a=def.valid)!==null&&_a!==void 0?_a:valid);function validateKeyword(){if(def.errors===!1)assignValid(),def.modifying&&modifyData(cxt),reportErrs(()=>cxt.error());else{let ruleErrs=def.async?validateAsync():validateSync();def.modifying&&modifyData(cxt),reportErrs(()=>addErrs(cxt,ruleErrs))}}function validateAsync(){let ruleErrs=gen.let("ruleErrs",null);return gen.try(()=>assignValid((0,codegen_1._)`await `),e=>gen.assign(valid,!1).if((0,codegen_1._)`${e} instanceof ${it.ValidationError}`,()=>gen.assign(ruleErrs,(0,codegen_1._)`${e}.errors`),()=>gen.throw(e))),ruleErrs}function validateSync(){let validateErrs=(0,codegen_1._)`${validateRef}.errors`;return gen.assign(validateErrs,null),assignValid(codegen_1.nil),validateErrs}function assignValid(_await=def.async?(0,codegen_1._)`await `:codegen_1.nil){let passCxt=it.opts.passContext?names_1.default.this:names_1.default.self,passSchema=!("compile"in def&&!$data||def.schema===!1);gen.assign(valid,(0,codegen_1._)`${_await}${(0,code_1.callValidateCode)(cxt,validateRef,passCxt,passSchema)}`,def.modifying)}function reportErrs(errors){var _a2;gen.if((0,codegen_1.not)((_a2=def.valid)!==null&&_a2!==void 0?_a2:valid),errors)}}exports.funcKeywordCode=funcKeywordCode;function modifyData(cxt){let{gen,data:data2,it}=cxt;gen.if(it.parentData,()=>gen.assign(data2,(0,codegen_1._)`${it.parentData}[${it.parentDataProperty}]`))}function addErrs(cxt,errs){let{gen}=cxt;gen.if((0,codegen_1._)`Array.isArray(${errs})`,()=>{gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`),(0,errors_1.extendErrors)(cxt)},()=>cxt.error())}function checkAsyncKeyword({schemaEnv},def){if(def.async&&!schemaEnv.$async)throw new Error("async keyword in sync schema")}function useKeyword(gen,keyword,result){if(result===void 0)throw new Error(`keyword "${keyword}" failed to compile`);return gen.scopeValue("keyword",typeof result=="function"?{ref:result}:{ref:result,code:(0,codegen_1.stringify)(result)})}function validSchemaType(schema,schemaType,allowUndefined=!1){return!schemaType.length||schemaType.some(st=>st==="array"?Array.isArray(schema):st==="object"?schema&&typeof schema=="object"&&!Array.isArray(schema):typeof schema==st||allowUndefined&&typeof schema>"u")}exports.validSchemaType=validSchemaType;function validateKeywordUsage({schema,opts,self,errSchemaPath},def,keyword){if(Array.isArray(def.keyword)?!def.keyword.includes(keyword):def.keyword!==keyword)throw new Error("ajv implementation error");let deps=def.dependencies;if(deps?.some(kwd=>!Object.prototype.hasOwnProperty.call(schema,kwd)))throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);if(def.validateSchema&&!def.validateSchema(schema[keyword])){let msg=`keyword "${keyword}" value is invalid at path "${errSchemaPath}": `+self.errorsText(def.validateSchema.errors);if(opts.validateSchema==="log")self.logger.error(msg);else throw new Error(msg)}}exports.validateKeywordUsage=validateKeywordUsage}});var require_subschema=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.extendSubschemaMode=exports.extendSubschemaData=exports.getSubschema=void 0;var codegen_1=require_codegen(),util_1=require_util();function getSubschema(it,{keyword,schemaProp,schema,schemaPath,errSchemaPath,topSchemaRef}){if(keyword!==void 0&&schema!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(keyword!==void 0){let sch=it.schema[keyword];return schemaProp===void 0?{schema:sch,schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}`}:{schema:sch[schemaProp],schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}${(0,codegen_1.getProperty)(schemaProp)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}/${(0,util_1.escapeFragment)(schemaProp)}`}}if(schema!==void 0){if(schemaPath===void 0||errSchemaPath===void 0||topSchemaRef===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema,schemaPath,topSchemaRef,errSchemaPath}}throw new Error('either "keyword" or "schema" must be passed')}exports.getSubschema=getSubschema;function extendSubschemaData(subschema,it,{dataProp,dataPropType:dpType,data:data2,dataTypes,propertyName}){if(data2!==void 0&&dataProp!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen}=it;if(dataProp!==void 0){let{errorPath,dataPathArr,opts}=it,nextData=gen.let("data",(0,codegen_1._)`${it.data}${(0,codegen_1.getProperty)(dataProp)}`,!0);dataContextProps(nextData),subschema.errorPath=(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(dataProp,dpType,opts.jsPropertySyntax)}`,subschema.parentDataProperty=(0,codegen_1._)`${dataProp}`,subschema.dataPathArr=[...dataPathArr,subschema.parentDataProperty]}if(data2!==void 0){let nextData=data2 instanceof codegen_1.Name?data2:gen.let("data",data2,!0);dataContextProps(nextData),propertyName!==void 0&&(subschema.propertyName=propertyName)}dataTypes&&(subschema.dataTypes=dataTypes);function dataContextProps(_nextData){subschema.data=_nextData,subschema.dataLevel=it.dataLevel+1,subschema.dataTypes=[],it.definedProperties=new Set,subschema.parentData=it.data,subschema.dataNames=[...it.dataNames,_nextData]}}exports.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(subschema,{jtdDiscriminator,jtdMetadata,compositeRule,createErrors,allErrors}){compositeRule!==void 0&&(subschema.compositeRule=compositeRule),createErrors!==void 0&&(subschema.createErrors=createErrors),allErrors!==void 0&&(subschema.allErrors=allErrors),subschema.jtdDiscriminator=jtdDiscriminator,subschema.jtdMetadata=jtdMetadata}exports.extendSubschemaMode=extendSubschemaMode}});var require_fast_deep_equal=__commonJS({"../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports,module){"use strict";module.exports=function equal(a,b){if(a===b)return!0;if(a&&b&&typeof a=="object"&&typeof b=="object"){if(a.constructor!==b.constructor)return!1;var length,i2,keys;if(Array.isArray(a)){if(length=a.length,length!=b.length)return!1;for(i2=length;i2--!==0;)if(!equal(a[i2],b[i2]))return!1;return!0}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();if(keys=Object.keys(a),length=keys.length,length!==Object.keys(b).length)return!1;for(i2=length;i2--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i2]))return!1;for(i2=length;i2--!==0;){var key2=keys[i2];if(!equal(a[key2],b[key2]))return!1}return!0}return a!==a&&b!==b}}});var require_json_schema_traverse=__commonJS({"../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports,module){"use strict";var traverse=module.exports=function(schema,opts,cb){typeof opts=="function"&&(cb=opts,opts={}),cb=opts.cb||cb;var pre=typeof cb=="function"?cb:cb.pre||function(){},post=cb.post||function(){};_traverse(opts,pre,post,schema,"",schema)};traverse.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};traverse.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};traverse.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};traverse.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(opts,pre,post,schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(schema&&typeof schema=="object"&&!Array.isArray(schema)){pre(schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex);for(var key2 in schema){var sch=schema[key2];if(Array.isArray(sch)){if(key2 in traverse.arrayKeywords)for(var i2=0;i2<sch.length;i2++)_traverse(opts,pre,post,sch[i2],jsonPtr+"/"+key2+"/"+i2,rootSchema,jsonPtr,key2,schema,i2)}else if(key2 in traverse.propsKeywords){if(sch&&typeof sch=="object")for(var prop in sch)_traverse(opts,pre,post,sch[prop],jsonPtr+"/"+key2+"/"+escapeJsonPtr(prop),rootSchema,jsonPtr,key2,schema,prop)}else(key2 in traverse.keywords||opts.allKeys&&!(key2 in traverse.skipKeywords))&&_traverse(opts,pre,post,sch,jsonPtr+"/"+key2,rootSchema,jsonPtr,key2,schema)}post(schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex)}}function escapeJsonPtr(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}}});var require_resolve=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getSchemaRefs=exports.resolveUrl=exports.normalizeId=exports._getFullPath=exports.getFullPath=exports.inlineRef=void 0;var util_1=require_util(),equal=require_fast_deep_equal(),traverse=require_json_schema_traverse(),SIMPLE_INLINED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function inlineRef(schema,limit=!0){return typeof schema=="boolean"?!0:limit===!0?!hasRef(schema):limit?countKeys(schema)<=limit:!1}exports.inlineRef=inlineRef;var REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(schema){for(let key2 in schema){if(REF_KEYWORDS.has(key2))return!0;let sch=schema[key2];if(Array.isArray(sch)&&sch.some(hasRef)||typeof sch=="object"&&hasRef(sch))return!0}return!1}function countKeys(schema){let count=0;for(let key2 in schema){if(key2==="$ref")return 1/0;if(count++,!SIMPLE_INLINED.has(key2)&&(typeof schema[key2]=="object"&&(0,util_1.eachItem)(schema[key2],sch=>count+=countKeys(sch)),count===1/0))return 1/0}return count}function getFullPath(resolver,id="",normalize){normalize!==!1&&(id=normalizeId(id));let p=resolver.parse(id);return _getFullPath(resolver,p)}exports.getFullPath=getFullPath;function _getFullPath(resolver,p){return resolver.serialize(p).split("#")[0]+"#"}exports._getFullPath=_getFullPath;var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}exports.normalizeId=normalizeId;function resolveUrl(resolver,baseId,id){return id=normalizeId(id),resolver.resolve(baseId,id)}exports.resolveUrl=resolveUrl;var ANCHOR=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(schema,baseId){if(typeof schema=="boolean")return{};let{schemaId,uriResolver}=this.opts,schId=normalizeId(schema[schemaId]||baseId),baseIds={"":schId},pathPrefix=getFullPath(uriResolver,schId,!1),localRefs={},schemaRefs=new Set;return traverse(schema,{allKeys:!0},(sch,jsonPtr,_,parentJsonPtr)=>{if(parentJsonPtr===void 0)return;let fullPath=pathPrefix+jsonPtr,innerBaseId=baseIds[parentJsonPtr];typeof sch[schemaId]=="string"&&(innerBaseId=addRef.call(this,sch[schemaId])),addAnchor.call(this,sch.$anchor),addAnchor.call(this,sch.$dynamicAnchor),baseIds[jsonPtr]=innerBaseId;function addRef(ref2){let _resolve=this.opts.uriResolver.resolve;if(ref2=normalizeId(innerBaseId?_resolve(innerBaseId,ref2):ref2),schemaRefs.has(ref2))throw ambiguos(ref2);schemaRefs.add(ref2);let schOrRef=this.refs[ref2];return typeof schOrRef=="string"&&(schOrRef=this.refs[schOrRef]),typeof schOrRef=="object"?checkAmbiguosRef(sch,schOrRef.schema,ref2):ref2!==normalizeId(fullPath)&&(ref2[0]==="#"?(checkAmbiguosRef(sch,localRefs[ref2],ref2),localRefs[ref2]=sch):this.refs[ref2]=fullPath),ref2}function addAnchor(anchor){if(typeof anchor=="string"){if(!ANCHOR.test(anchor))throw new Error(`invalid anchor "${anchor}"`);addRef.call(this,`#${anchor}`)}}}),localRefs;function checkAmbiguosRef(sch1,sch2,ref2){if(sch2!==void 0&&!equal(sch1,sch2))throw ambiguos(ref2)}function ambiguos(ref2){return new Error(`reference "${ref2}" resolves to more than one schema`)}}exports.getSchemaRefs=getSchemaRefs}});var require_validate=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getData=exports.KeywordCxt=exports.validateFunctionCode=void 0;var boolSchema_1=require_boolSchema(),dataType_1=require_dataType(),applicability_1=require_applicability(),dataType_2=require_dataType(),defaults_1=require_defaults(),keyword_1=require_keyword(),subschema_1=require_subschema(),codegen_1=require_codegen(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),errors_1=require_errors();function validateFunctionCode(it){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){topSchemaObjCode(it);return}validateFunction(it,()=>(0,boolSchema_1.topBoolOrEmptySchema)(it))}exports.validateFunctionCode=validateFunctionCode;function validateFunction({gen,validateName,schema,schemaEnv,opts},body){opts.code.es5?gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`,schemaEnv.$async,()=>{gen.code((0,codegen_1._)`"use strict"; ${funcSourceUrl(schema,opts)}`),destructureValCxtES5(gen,opts),gen.code(body)}):gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`,schemaEnv.$async,()=>gen.code(funcSourceUrl(schema,opts)).code(body))}function destructureValCxt(opts){return(0,codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef?(0,codegen_1._)`, ${names_1.default.dynamicAnchors}={}`:codegen_1.nil}}={}`}function destructureValCxtES5(gen,opts){gen.if(names_1.default.valCxt,()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`),gen.var(names_1.default.parentData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`),gen.var(names_1.default.rootData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`)},()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`""`),gen.var(names_1.default.parentData,(0,codegen_1._)`undefined`),gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`undefined`),gen.var(names_1.default.rootData,names_1.default.data),opts.dynamicRef&&gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`{}`)})}function topSchemaObjCode(it){let{schema,opts,gen}=it;validateFunction(it,()=>{opts.$comment&&schema.$comment&&commentKeyword(it),checkNoDefault(it),gen.let(names_1.default.vErrors,null),gen.let(names_1.default.errors,0),opts.unevaluated&&resetEvaluated(it),typeAndKeywords(it),returnResults(it)})}function resetEvaluated(it){let{gen,validateName}=it;it.evaluated=gen.const("evaluated",(0,codegen_1._)`${validateName}.evaluated`),gen.if((0,codegen_1._)`${it.evaluated}.dynamicProps`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.props`,(0,codegen_1._)`undefined`)),gen.if((0,codegen_1._)`${it.evaluated}.dynamicItems`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.items`,(0,codegen_1._)`undefined`))}function funcSourceUrl(schema,opts){let schId=typeof schema=="object"&&schema[opts.schemaId];return schId&&(opts.code.source||opts.code.process)?(0,codegen_1._)`/*# sourceURL=${schId} */`:codegen_1.nil}function subschemaCode(it,valid){if(isSchemaObj(it)&&(checkKeywords(it),schemaCxtHasRules(it))){subSchemaObjCode(it,valid);return}(0,boolSchema_1.boolOrEmptySchema)(it,valid)}function schemaCxtHasRules({schema,self}){if(typeof schema=="boolean")return!schema;for(let key2 in schema)if(self.RULES.all[key2])return!0;return!1}function isSchemaObj(it){return typeof it.schema!="boolean"}function subSchemaObjCode(it,valid){let{schema,gen,opts}=it;opts.$comment&&schema.$comment&&commentKeyword(it),updateContext(it),checkAsyncSchema(it);let errsCount=gen.const("_errs",names_1.default.errors);typeAndKeywords(it,errsCount),gen.var(valid,(0,codegen_1._)`${errsCount} === ${names_1.default.errors}`)}function checkKeywords(it){(0,util_1.checkUnknownRules)(it),checkRefsAndKeywords(it)}function typeAndKeywords(it,errsCount){if(it.opts.jtd)return schemaKeywords(it,[],!1,errsCount);let types2=(0,dataType_1.getSchemaTypes)(it.schema),checkedTypes=(0,dataType_1.coerceAndCheckDataType)(it,types2);schemaKeywords(it,types2,!checkedTypes,errsCount)}function checkRefsAndKeywords(it){let{schema,errSchemaPath,opts,self}=it;schema.$ref&&opts.ignoreKeywordsWithRef&&(0,util_1.schemaHasRulesButRef)(schema,self.RULES)&&self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)}function checkNoDefault(it){let{schema,opts}=it;schema.default!==void 0&&opts.useDefaults&&opts.strictSchema&&(0,util_1.checkStrictMode)(it,"default is ignored in the schema root")}function updateContext(it){let schId=it.schema[it.opts.schemaId];schId&&(it.baseId=(0,resolve_1.resolveUrl)(it.opts.uriResolver,it.baseId,schId))}function checkAsyncSchema(it){if(it.schema.$async&&!it.schemaEnv.$async)throw new Error("async schema in sync schema")}function commentKeyword({gen,schemaEnv,schema,errSchemaPath,opts}){let msg=schema.$comment;if(opts.$comment===!0)gen.code((0,codegen_1._)`${names_1.default.self}.logger.log(${msg})`);else if(typeof opts.$comment=="function"){let schemaPath=(0,codegen_1.str)`${errSchemaPath}/$comment`,rootName=gen.scopeValue("root",{ref:schemaEnv.root});gen.code((0,codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)}}function returnResults(it){let{gen,schemaEnv,validateName,ValidationError,opts}=it;schemaEnv.$async?gen.if((0,codegen_1._)`${names_1.default.errors} === 0`,()=>gen.return(names_1.default.data),()=>gen.throw((0,codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)):(gen.assign((0,codegen_1._)`${validateName}.errors`,names_1.default.vErrors),opts.unevaluated&&assignEvaluated(it),gen.return((0,codegen_1._)`${names_1.default.errors} === 0`))}function assignEvaluated({gen,evaluated,props,items}){props instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.props`,props),items instanceof codegen_1.Name&&gen.assign((0,codegen_1._)`${evaluated}.items`,items)}function schemaKeywords(it,types2,typeErrors,errsCount){let{gen,schema,data:data2,allErrors,opts,self}=it,{RULES}=self;if(schema.$ref&&(opts.ignoreKeywordsWithRef||!(0,util_1.schemaHasRulesButRef)(schema,RULES))){gen.block(()=>keywordCode(it,"$ref",RULES.all.$ref.definition));return}opts.jtd||checkStrictTypes(it,types2),gen.block(()=>{for(let group of RULES.rules)groupKeywords(group);groupKeywords(RULES.post)});function groupKeywords(group){(0,applicability_1.shouldUseGroup)(schema,group)&&(group.type?(gen.if((0,dataType_2.checkDataType)(group.type,data2,opts.strictNumbers)),iterateKeywords(it,group),types2.length===1&&types2[0]===group.type&&typeErrors&&(gen.else(),(0,dataType_2.reportTypeError)(it)),gen.endIf()):iterateKeywords(it,group),allErrors||gen.if((0,codegen_1._)`${names_1.default.errors} === ${errsCount||0}`))}}function iterateKeywords(it,group){let{gen,schema,opts:{useDefaults}}=it;useDefaults&&(0,defaults_1.assignDefaults)(it,group.type),gen.block(()=>{for(let rule of group.rules)(0,applicability_1.shouldUseRule)(schema,rule)&&keywordCode(it,rule.keyword,rule.definition,group.type)})}function checkStrictTypes(it,types2){it.schemaEnv.meta||!it.opts.strictTypes||(checkContextTypes(it,types2),it.opts.allowUnionTypes||checkMultipleTypes(it,types2),checkKeywordTypes(it,it.dataTypes))}function checkContextTypes(it,types2){if(types2.length){if(!it.dataTypes.length){it.dataTypes=types2;return}types2.forEach(t=>{includesType(it.dataTypes,t)||strictTypesError(it,`type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)}),narrowSchemaTypes(it,types2)}}function checkMultipleTypes(it,ts){ts.length>1&&!(ts.length===2&&ts.includes("null"))&&strictTypesError(it,"use allowUnionTypes to allow union type keyword")}function checkKeywordTypes(it,ts){let rules=it.self.RULES.all;for(let keyword in rules){let rule=rules[keyword];if(typeof rule=="object"&&(0,applicability_1.shouldUseRule)(it.schema,rule)){let{type}=rule.definition;type.length&&!type.some(t=>hasApplicableType(ts,t))&&strictTypesError(it,`missing type "${type.join(",")}" for keyword "${keyword}"`)}}}function hasApplicableType(schTs,kwdT){return schTs.includes(kwdT)||kwdT==="number"&&schTs.includes("integer")}function includesType(ts,t){return ts.includes(t)||t==="integer"&&ts.includes("number")}function narrowSchemaTypes(it,withTypes){let ts=[];for(let t of it.dataTypes)includesType(withTypes,t)?ts.push(t):withTypes.includes("integer")&&t==="number"&&ts.push("integer");it.dataTypes=ts}function strictTypesError(it,msg){let schemaPath=it.schemaEnv.baseId+it.errSchemaPath;msg+=` at "${schemaPath}" (strictTypes)`,(0,util_1.checkStrictMode)(it,msg,it.opts.strictTypes)}var KeywordCxt=class{constructor(it,def,keyword){if((0,keyword_1.validateKeywordUsage)(it,def,keyword),this.gen=it.gen,this.allErrors=it.allErrors,this.keyword=keyword,this.data=it.data,this.schema=it.schema[keyword],this.$data=def.$data&&it.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,util_1.schemaRefOrVal)(it,this.schema,keyword,this.$data),this.schemaType=def.schemaType,this.parentSchema=it.schema,this.params={},this.it=it,this.def=def,this.$data)this.schemaCode=it.gen.const("vSchema",getData(this.$data,it));else if(this.schemaCode=this.schemaValue,!(0,keyword_1.validSchemaType)(this.schema,def.schemaType,def.allowUndefined))throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);("code"in def?def.trackErrors:def.errors!==!1)&&(this.errsCount=it.gen.const("_errs",names_1.default.errors))}result(condition,successAction,failAction){this.failResult((0,codegen_1.not)(condition),successAction,failAction)}failResult(condition,successAction,failAction){this.gen.if(condition),failAction?failAction():this.error(),successAction?(this.gen.else(),successAction(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(condition,failAction){this.failResult((0,codegen_1.not)(condition),void 0,failAction)}fail(condition){if(condition===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(condition),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(condition){if(!this.$data)return this.fail(condition);let{schemaCode}=this;this.fail((0,codegen_1._)`${schemaCode} !== undefined && (${(0,codegen_1.or)(this.invalid$data(),condition)})`)}error(append,errorParams,errorPaths){if(errorParams){this.setParams(errorParams),this._error(append,errorPaths),this.setParams({});return}this._error(append,errorPaths)}_error(append,errorPaths){(append?errors_1.reportExtraError:errors_1.reportError)(this,this.def.error,errorPaths)}$dataError(){(0,errors_1.reportError)(this,this.def.$dataError||errors_1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(cond){this.allErrors||this.gen.if(cond)}setParams(obj,assign){assign?Object.assign(this.params,obj):this.params=obj}block$data(valid,codeBlock,$dataValid=codegen_1.nil){this.gen.block(()=>{this.check$data(valid,$dataValid),codeBlock()})}check$data(valid=codegen_1.nil,$dataValid=codegen_1.nil){if(!this.$data)return;let{gen,schemaCode,schemaType,def}=this;gen.if((0,codegen_1.or)((0,codegen_1._)`${schemaCode} === undefined`,$dataValid)),valid!==codegen_1.nil&&gen.assign(valid,!0),(schemaType.length||def.validateSchema)&&(gen.elseIf(this.invalid$data()),this.$dataError(),valid!==codegen_1.nil&&gen.assign(valid,!1)),gen.else()}invalid$data(){let{gen,schemaCode,schemaType,def,it}=this;return(0,codegen_1.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(schemaType.length){if(!(schemaCode instanceof codegen_1.Name))throw new Error("ajv implementation error");let st=Array.isArray(schemaType)?schemaType:[schemaType];return(0,codegen_1._)`${(0,dataType_2.checkDataTypes)(st,schemaCode,it.opts.strictNumbers,dataType_2.DataType.Wrong)}`}return codegen_1.nil}function invalid$DataSchema(){if(def.validateSchema){let validateSchemaRef=gen.scopeValue("validate$data",{ref:def.validateSchema});return(0,codegen_1._)`!${validateSchemaRef}(${schemaCode})`}return codegen_1.nil}}subschema(appl,valid){let subschema=(0,subschema_1.getSubschema)(this.it,appl);(0,subschema_1.extendSubschemaData)(subschema,this.it,appl),(0,subschema_1.extendSubschemaMode)(subschema,appl);let nextContext={...this.it,...subschema,items:void 0,props:void 0};return subschemaCode(nextContext,valid),nextContext}mergeEvaluated(schemaCxt,toName){let{it,gen}=this;it.opts.unevaluated&&(it.props!==!0&&schemaCxt.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schemaCxt.props,it.props,toName)),it.items!==!0&&schemaCxt.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schemaCxt.items,it.items,toName)))}mergeValidEvaluated(schemaCxt,valid){let{it,gen}=this;if(it.opts.unevaluated&&(it.props!==!0||it.items!==!0))return gen.if(valid,()=>this.mergeEvaluated(schemaCxt,codegen_1.Name)),!0}};exports.KeywordCxt=KeywordCxt;function keywordCode(it,keyword,def,ruleType){let cxt=new KeywordCxt(it,def,keyword);"code"in def?def.code(cxt,ruleType):cxt.$data&&def.validate?(0,keyword_1.funcKeywordCode)(cxt,def):"macro"in def?(0,keyword_1.macroKeywordCode)(cxt,def):(def.compile||def.validate)&&(0,keyword_1.funcKeywordCode)(cxt,def)}var JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/,RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,{dataLevel,dataNames,dataPathArr}){let jsonPointer,data2;if($data==="")return names_1.default.rootData;if($data[0]==="/"){if(!JSON_POINTER.test($data))throw new Error(`Invalid JSON-pointer: ${$data}`);jsonPointer=$data,data2=names_1.default.rootData}else{let matches=RELATIVE_JSON_POINTER.exec($data);if(!matches)throw new Error(`Invalid JSON-pointer: ${$data}`);let up=+matches[1];if(jsonPointer=matches[2],jsonPointer==="#"){if(up>=dataLevel)throw new Error(errorMsg("property/index",up));return dataPathArr[dataLevel-up]}if(up>dataLevel)throw new Error(errorMsg("data",up));if(data2=dataNames[dataLevel-up],!jsonPointer)return data2}let expr=data2,segments=jsonPointer.split("/");for(let segment of segments)segment&&(data2=(0,codegen_1._)`${data2}${(0,codegen_1.getProperty)((0,util_1.unescapeJsonPointer)(segment))}`,expr=(0,codegen_1._)`${expr} && ${data2}`);return expr;function errorMsg(pointerType,up){return`Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`}}exports.getData=getData}});var require_validation_error=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var ValidationError=class extends Error{constructor(errors){super("validation failed"),this.errors=errors,this.ajv=this.validation=!0}};exports.default=ValidationError}});var require_ref_error=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var resolve_1=require_resolve(),MissingRefError=class extends Error{constructor(resolver,baseId,ref2,msg){super(msg||`can't resolve reference ${ref2} from id ${baseId}`),this.missingRef=(0,resolve_1.resolveUrl)(resolver,baseId,ref2),this.missingSchema=(0,resolve_1.normalizeId)((0,resolve_1.getFullPath)(resolver,this.missingRef))}};exports.default=MissingRefError}});var require_compile=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.resolveSchema=exports.getCompilingSchema=exports.resolveRef=exports.compileSchema=exports.SchemaEnv=void 0;var codegen_1=require_codegen(),validation_error_1=require_validation_error(),names_1=require_names(),resolve_1=require_resolve(),util_1=require_util(),validate_1=require_validate(),SchemaEnv=class{constructor(env){var _a;this.refs={},this.dynamicAnchors={};let schema;typeof env.schema=="object"&&(schema=env.schema),this.schema=env.schema,this.schemaId=env.schemaId,this.root=env.root||this,this.baseId=(_a=env.baseId)!==null&&_a!==void 0?_a:(0,resolve_1.normalizeId)(schema?.[env.schemaId||"$id"]),this.schemaPath=env.schemaPath,this.localRefs=env.localRefs,this.meta=env.meta,this.$async=schema?.$async,this.refs={}}};exports.SchemaEnv=SchemaEnv;function compileSchema(sch){let _sch=getCompilingSchema.call(this,sch);if(_sch)return _sch;let rootId=(0,resolve_1.getFullPath)(this.opts.uriResolver,sch.root.baseId),{es5,lines}=this.opts.code,{ownProperties}=this.opts,gen=new codegen_1.CodeGen(this.scope,{es5,lines,ownProperties}),_ValidationError;sch.$async&&(_ValidationError=gen.scopeValue("Error",{ref:validation_error_1.default,code:(0,codegen_1._)`require("ajv/dist/runtime/validation_error").default`}));let validateName=gen.scopeName("validate");sch.validateName=validateName;let schemaCxt={gen,allErrors:this.opts.allErrors,data:names_1.default.data,parentData:names_1.default.parentData,parentDataProperty:names_1.default.parentDataProperty,dataNames:[names_1.default.data],dataPathArr:[codegen_1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:gen.scopeValue("schema",this.opts.code.source===!0?{ref:sch.schema,code:(0,codegen_1.stringify)(sch.schema)}:{ref:sch.schema}),validateName,ValidationError:_ValidationError,schema:sch.schema,schemaEnv:sch,rootId,baseId:sch.baseId||rootId,schemaPath:codegen_1.nil,errSchemaPath:sch.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,codegen_1._)`""`,opts:this.opts,self:this},sourceCode;try{this._compilations.add(sch),(0,validate_1.validateFunctionCode)(schemaCxt),gen.optimize(this.opts.code.optimize);let validateCode=gen.toString();sourceCode=`${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`,this.opts.code.process&&(sourceCode=this.opts.code.process(sourceCode,sch));let validate=new Function(`${names_1.default.self}`,`${names_1.default.scope}`,sourceCode)(this,this.scope.get());if(this.scope.value(validateName,{ref:validate}),validate.errors=null,validate.schema=sch.schema,validate.schemaEnv=sch,sch.$async&&(validate.$async=!0),this.opts.code.source===!0&&(validate.source={validateName,validateCode,scopeValues:gen._values}),this.opts.unevaluated){let{props,items}=schemaCxt;validate.evaluated={props:props instanceof codegen_1.Name?void 0:props,items:items instanceof codegen_1.Name?void 0:items,dynamicProps:props instanceof codegen_1.Name,dynamicItems:items instanceof codegen_1.Name},validate.source&&(validate.source.evaluated=(0,codegen_1.stringify)(validate.evaluated))}return sch.validate=validate,sch}catch(e){throw delete sch.validate,delete sch.validateName,sourceCode&&this.logger.error("Error compiling schema, function code:",sourceCode),e}finally{this._compilations.delete(sch)}}exports.compileSchema=compileSchema;function resolveRef(root,baseId,ref2){var _a;ref2=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,ref2);let schOrFunc=root.refs[ref2];if(schOrFunc)return schOrFunc;let _sch=resolve7.call(this,root,ref2);if(_sch===void 0){let schema=(_a=root.localRefs)===null||_a===void 0?void 0:_a[ref2],{schemaId}=this.opts;schema&&(_sch=new SchemaEnv({schema,schemaId,root,baseId}))}if(_sch!==void 0)return root.refs[ref2]=inlineOrCompile.call(this,_sch)}exports.resolveRef=resolveRef;function inlineOrCompile(sch){return(0,resolve_1.inlineRef)(sch.schema,this.opts.inlineRefs)?sch.schema:sch.validate?sch:compileSchema.call(this,sch)}function getCompilingSchema(schEnv){for(let sch of this._compilations)if(sameSchemaEnv(sch,schEnv))return sch}exports.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(s1,s2){return s1.schema===s2.schema&&s1.root===s2.root&&s1.baseId===s2.baseId}function resolve7(root,ref2){let sch;for(;typeof(sch=this.refs[ref2])=="string";)ref2=sch;return sch||this.schemas[ref2]||resolveSchema.call(this,root,ref2)}function resolveSchema(root,ref2){let p=this.opts.uriResolver.parse(ref2),refPath=(0,resolve_1._getFullPath)(this.opts.uriResolver,p),baseId=(0,resolve_1.getFullPath)(this.opts.uriResolver,root.baseId,void 0);if(Object.keys(root.schema).length>0&&refPath===baseId)return getJsonPointer.call(this,p,root);let id=(0,resolve_1.normalizeId)(refPath),schOrRef=this.refs[id]||this.schemas[id];if(typeof schOrRef=="string"){let sch=resolveSchema.call(this,root,schOrRef);return typeof sch?.schema!="object"?void 0:getJsonPointer.call(this,p,sch)}if(typeof schOrRef?.schema=="object"){if(schOrRef.validate||compileSchema.call(this,schOrRef),id===(0,resolve_1.normalizeId)(ref2)){let{schema}=schOrRef,{schemaId}=this.opts,schId=schema[schemaId];return schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId)),new SchemaEnv({schema,schemaId,root,baseId})}return getJsonPointer.call(this,p,schOrRef)}}exports.resolveSchema=resolveSchema;var PREVENT_SCOPE_CHANGE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,{baseId,schema,root}){var _a;if(((_a=parsedRef.fragment)===null||_a===void 0?void 0:_a[0])!=="/")return;for(let part of parsedRef.fragment.slice(1).split("/")){if(typeof schema=="boolean")return;let partSchema=schema[(0,util_1.unescapeFragment)(part)];if(partSchema===void 0)return;schema=partSchema;let schId=typeof schema=="object"&&schema[this.opts.schemaId];!PREVENT_SCOPE_CHANGE.has(part)&&schId&&(baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId))}let env;if(typeof schema!="boolean"&&schema.$ref&&!(0,util_1.schemaHasRulesButRef)(schema,this.RULES)){let $ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schema.$ref);env=resolveSchema.call(this,root,$ref)}let{schemaId}=this.opts;if(env=env||new SchemaEnv({schema,schemaId,root,baseId}),env.schema!==env.root.schema)return env}}});var require_data=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json"(exports,module){module.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}});var require_utils=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.9/node_modules/fast-uri/lib/utils.js"(exports,module){"use strict";var isUUID=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),isIPv4=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),isPort=RegExp.prototype.test.bind(/^\d*$/u),isHexPair=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),isUnreserved=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),isPathCharacter=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),isQueryFragmentCharacter=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),isUserinfoCharacter=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),BYTE_HEX=new Array(256);{let HEX_DIGITS="0123456789ABCDEF";for(let i2=0;i2<256;i2++)BYTE_HEX[i2]="%"+HEX_DIGITS[i2>>4]+HEX_DIGITS[i2&15]}function percentEncodeNonAscii(cp){return cp<2048?BYTE_HEX[192|cp>>6]+BYTE_HEX[128|cp&63]:cp<65536?BYTE_HEX[224|cp>>12]+BYTE_HEX[128|cp>>6&63]+BYTE_HEX[128|cp&63]:BYTE_HEX[240|cp>>18]+BYTE_HEX[128|cp>>12&63]+BYTE_HEX[128|cp>>6&63]+BYTE_HEX[128|cp&63]}function stringArrayToHexStripped(input){let acc="",code=0,i2=0;for(i2=0;i2<input.length;i2++)if(code=input[i2].charCodeAt(0),code!==48){if(!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i2];break}for(i2+=1;i2<input.length;i2++){if(code=input[i2].charCodeAt(0),!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102))return"";acc+=input[i2]}return acc}var isHextet=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),isIPvFuture=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),isZoneCharacter=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),nonSimpleDomain=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function isZoneIdentifier(zone){if(zone.length===0)return!1;for(let i2=0;i2<zone.length;i2++)if(!isZoneCharacter(zone[i2])){if(zone[i2]==="%"&&i2+2<zone.length&&isHexPair(zone.slice(i2+1,i2+3))){i2+=2;continue}return!1}return!0}function compressIPv6ZeroRun(hextets){let bestStart=-1,bestLength=0,runStart=-1,runLength=0;for(let i2=0;i2<hextets.length;i2++)hextets[i2]==="0"?(runStart===-1&&(runStart=i2),runLength++,runLength>bestLength&&(bestLength=runLength,bestStart=runStart)):(runStart=-1,runLength=0);if(bestLength<2)return hextets.join(":");let head=hextets.slice(0,bestStart).join(":"),tail=hextets.slice(bestStart+bestLength).join(":");return head+"::"+tail}function normalizeIPv6Address(input){let compression=input.indexOf("::");if(compression!==-1&&input.indexOf("::",compression+1)!==-1)return;let left=compression===-1?input.split(":"):input.slice(0,compression).split(":"),right=compression===-1?[]:input.slice(compression+2).split(":");compression!==-1&&(left.length===1&&left[0]===""&&(left.length=0),right.length===1&&right[0]===""&&(right.length=0));let parts=left.concat(right),hextetCount=0;for(let i2=0;i2<parts.length;i2++){let part=parts[i2];if(part==="")return;if(part.indexOf(".")!==-1){if(i2!==parts.length-1||compression!==-1&&right.length===0||!isIPv4(part))return;hextetCount+=2;continue}if(!isHextet(part))return;parts[i2]=parseInt(part,16).toString(16),hextetCount++}if(compression===-1)return hextetCount!==8?void 0:compressIPv6ZeroRun(parts);if(hextetCount>=8)return;let expanded=parts.slice(0,left.length);for(let i2=hextetCount;i2<8;i2++)expanded.push("0");for(let i2=left.length;i2<parts.length;i2++)expanded.push(parts[i2]);return compressIPv6ZeroRun(expanded)}function normalizeIPv6(host){let bracketed=host[0]==="["&&host[host.length-1]==="]";if((host[0]==="["||host[host.length-1]==="]")&&!bracketed)return{host,isIPV6:!1,error:!0};let input=bracketed?host.slice(1,-1):host;if(bracketed&&isIPvFuture(input))return input=input.toLowerCase(),{host:`[${input}]`,escapedHost:input,isIPV6:!1,isIPVFuture:!0};if(findToken(input,":")<2)return{host,isIPV6:!1,error:bracketed};let zoneIdentifier="",zoneSeparator=input.indexOf("%");if(zoneSeparator!==-1){let separatorLength=input.slice(zoneSeparator,zoneSeparator+3).toLowerCase()==="%25"?3:1;if(zoneIdentifier=input.slice(zoneSeparator+separatorLength),!isZoneIdentifier(zoneIdentifier))return{host,isIPV6:!1,error:!0};input=input.slice(0,zoneSeparator)}let address=normalizeIPv6Address(input);return address===void 0?{host,isIPV6:!1,error:!0}:{host:address+(zoneIdentifier?"%"+zoneIdentifier:""),escapedHost:address+(zoneIdentifier?"%25"+zoneIdentifier:""),isIPV6:!0}}function findToken(str,token){let ind=0;for(let i2=0;i2<str.length;i2++)str[i2]===token&&ind++;return ind}function removeDotSegments(path8){let input=path8,output=[],nextSlash=-1,len=0;for(;len=input.length;){if(len===1){if(input===".")break;if(input==="/"){output.push("/");break}else{output.push(input);break}}else if(len===2){if(input[0]==="."){if(input[1]===".")break;if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&(input[1]==="."||input[1]==="/")){output.push("/");break}}else if(len===3&&input==="/.."){output.length!==0&&output.pop(),output.push("/");break}if(input[0]==="."){if(input[1]==="."){if(input[2]==="/"){input=input.slice(3);continue}}else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"&&input[1]==="."){if(input[2]==="/"){input=input.slice(2);continue}else if(input[2]==="."&&input[3]==="/"){input=input.slice(3),output.length!==0&&output.pop();continue}}if((nextSlash=input.indexOf("/",1))===-1){output.push(input);break}else output.push(input.slice(0,nextSlash)),input=input.slice(nextSlash)}return output.join("")}function removeDotSegmentsRelative(path8){if(path8===""||path8[0]==="/")return removeDotSegments(path8);let segments=path8.split("/"),last=segments.length-1,output=[],trailingDirectory=!1;for(let i2=0;i2<=last;i2++){let segment=segments[i2];segment==="."||segment===".."?(segment===".."&&(output.length!==0&&output[output.length-1]!==".."?output.pop():output.push("..")),trailingDirectory=i2===last):output.push(segment)}return trailingDirectory&&output[output.length-1]!==".."&&output.push(""),(output.length===0||output[0]===""||output[0].includes(":"))&&output.unshift("."),output.join("/")}var HOST_DELIMS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},HOST_DELIM_RE=/[@/?#:]/g,HOST_DELIM_NO_COLON_RE=/[@/?#]/g;function reescapeHostDelimiters(host,isIP){let re=isIP?HOST_DELIM_NO_COLON_RE:HOST_DELIM_RE;return re.lastIndex=0,host.replace(re,ch=>HOST_DELIMS[ch])}function normalizePercentEncoding(input,decodeUnreserved=!1){if(input.indexOf("%")===-1)return input;let output="";for(let i2=0;i2<input.length;i2++){if(input[i2]==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){let normalizedHex=hex.toUpperCase(),decoded=String.fromCharCode(parseInt(normalizedHex,16));decodeUnreserved&&isUnreserved(decoded)?output+=decoded:output+="%"+normalizedHex,i2+=2;continue}}output+=input[i2]}return output}function normalizePathEncoding(input){let output="";for(let i2=0;i2<input.length;i2++){let ch=input[i2];if(ch==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){let normalizedHex=hex.toUpperCase(),decoded=String.fromCharCode(parseInt(normalizedHex,16));decoded!=="."&&isUnreserved(decoded)?output+=decoded:output+="%"+normalizedHex,i2+=2;continue}}if(isPathCharacter(ch))output+=ch;else{let code=input.charCodeAt(i2);if(code<128)output+=isEscapeSafe(code)?ch:BYTE_HEX[code];else if(code<55296||code>57343)output+=percentEncodeNonAscii(code);else if(code<=56319&&i2+1<input.length){let low=input.charCodeAt(i2+1);low>=56320&&low<=57343?(output+=percentEncodeNonAscii(65536+(code-55296<<10)+(low-56320)),i2++):output+=percentEncodeNonAscii(65533)}else output+=percentEncodeNonAscii(65533)}}return output}function serializePathEncoding(input,pathNoScheme=!1){let output="",firstSegment=pathNoScheme&&input[0]!=="/";for(let i2=0;i2<input.length;i2++){let ch=input[i2];if(ch==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){output+="%"+hex.toUpperCase(),i2+=2;continue}}if(ch==="/"&&(firstSegment=!1),isPathCharacter(ch)&&(ch!==":"||!firstSegment))output+=ch;else{let code=input.charCodeAt(i2);if(code<128)output+=BYTE_HEX[code];else if(code<55296||code>57343)output+=percentEncodeNonAscii(code);else if(code<=56319&&i2+1<input.length){let low=input.charCodeAt(i2+1);low>=56320&&low<=57343?(output+=percentEncodeNonAscii(65536+(code-55296<<10)+(low-56320)),i2++):output+=percentEncodeNonAscii(65533)}else output+=percentEncodeNonAscii(65533)}}return output}function encodeComponent(input,isAllowed){let output="";for(let i2=0;i2<input.length;i2++){let ch=input[i2];if(ch==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){output+="%"+hex.toUpperCase(),i2+=2;continue}}if(isAllowed(ch))output+=ch;else{let code=input.charCodeAt(i2);if(code<128)output+=BYTE_HEX[code];else if(code<55296||code>57343)output+=percentEncodeNonAscii(code);else if(code<=56319&&i2+1<input.length){let low=input.charCodeAt(i2+1);low>=56320&&low<=57343?(output+=percentEncodeNonAscii(65536+(code-55296<<10)+(low-56320)),i2++):output+=percentEncodeNonAscii(65533)}else output+=percentEncodeNonAscii(65533)}}return output}function encodeUserinfo(input){return encodeComponent(input,isUserinfoCharacter)}function encodeQuery(input){return encodeComponent(input,isQueryFragmentCharacter)}function encodeFragment(input){return encodeComponent(input,isQueryFragmentCharacter)}function isEscapeSafe(cp){return cp>=48&&cp<=57||cp>=65&&cp<=90||cp>=97&&cp<=122||cp===42||cp===43||cp===45||cp===46||cp===47||cp===64||cp===95}function normalizeQueryFragmentEncoding(input){let output="";for(let i2=0;i2<input.length;i2++){let ch=input[i2];if(ch==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){let normalizedHex=hex.toUpperCase(),decoded=String.fromCharCode(parseInt(normalizedHex,16));isUnreserved(decoded)?output+=decoded:output+="%"+normalizedHex,i2+=2;continue}}if(isQueryFragmentCharacter(ch))output+=ch;else{let code=input.charCodeAt(i2);if(code<128)output+=isEscapeSafe(code)?ch:BYTE_HEX[code];else if(code<55296||code>57343)output+=percentEncodeNonAscii(code);else if(code<=56319&&i2+1<input.length){let low=input.charCodeAt(i2+1);low>=56320&&low<=57343?(output+=percentEncodeNonAscii(65536+(code-55296<<10)+(low-56320)),i2++):output+=percentEncodeNonAscii(65533)}else output+=percentEncodeNonAscii(65533)}}return output}function escapePreservingEscapes(input){let output="";for(let i2=0;i2<input.length;i2++){if(input[i2]==="%"&&i2+2<input.length){let hex=input.slice(i2+1,i2+3);if(isHexPair(hex)){output+="%"+hex.toUpperCase(),i2+=2;continue}}output+=escape(input[i2])}return output}function recomposeAuthority(component){let uriTokens=[];if(component.userinfo!==void 0&&(uriTokens.push(encodeUserinfo(component.userinfo)),uriTokens.push("@")),component.host!==void 0){let host=component.host;if(!isIPv4(host)){let ipV6res=normalizeIPv6(host);ipV6res.isIPV6!==!0&&ipV6res.isIPVFuture!==!0&&(host=normalizePercentEncoding(host,!0),ipV6res=normalizeIPv6(host)),ipV6res.isIPV6===!0||ipV6res.isIPVFuture===!0?host=`[${ipV6res.escapedHost}]`:host=reescapeHostDelimiters(host,!1)}uriTokens.push(host)}if(typeof component.port=="number"||typeof component.port=="string"){let port=String(component.port);if(!isPort(port))throw new TypeError("URI port is malformed.");uriTokens.push(":"),uriTokens.push(port)}return uriTokens.length?uriTokens.join(""):void 0}module.exports={nonSimpleDomain,recomposeAuthority,reescapeHostDelimiters,normalizePercentEncoding,normalizePathEncoding,serializePathEncoding,normalizeQueryFragmentEncoding,encodeUserinfo,encodeQuery,encodeFragment,escapePreservingEscapes,removeDotSegments,removeDotSegmentsRelative,isIPv4,isUUID,normalizeIPv6,stringArrayToHexStripped}}});var require_schemes=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.9/node_modules/fast-uri/lib/schemes.js"(exports,module){"use strict";var{isUUID}=require_utils(),URN_REG=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,supportedSchemeNames=["http","https","ws","wss","urn","urn:uuid"];function isValidSchemeName(name){return supportedSchemeNames.indexOf(name)!==-1}function wsIsSecure(wsComponent){return wsComponent.secure===!0?!0:wsComponent.secure===!1?!1:wsComponent.scheme?wsComponent.scheme.length===3&&(wsComponent.scheme[0]==="w"||wsComponent.scheme[0]==="W")&&(wsComponent.scheme[1]==="s"||wsComponent.scheme[1]==="S")&&(wsComponent.scheme[2]==="s"||wsComponent.scheme[2]==="S"):!1}function httpParse(component){return component.host||(component.error=component.error||"HTTP URIs must have a host."),component}function httpSerialize(component){let secure=String(component.scheme).toLowerCase()==="https";return(component.port===(secure?443:80)||component.port==="")&&(component.port=void 0),component.path||(component.path="/"),component}function wsParse(wsComponent){return wsComponent.secure=wsIsSecure(wsComponent),wsComponent.resourceName=(wsComponent.path||"/")+(wsComponent.query?"?"+wsComponent.query:""),wsComponent.path=void 0,wsComponent.query=void 0,wsComponent}function wsSerialize(wsComponent){if((wsComponent.port===(wsIsSecure(wsComponent)?443:80)||wsComponent.port==="")&&(wsComponent.port=void 0),typeof wsComponent.secure=="boolean"&&(wsComponent.scheme=wsComponent.secure?"wss":"ws",wsComponent.secure=void 0),wsComponent.resourceName){let queryIndex=wsComponent.resourceName.indexOf("?"),path8=queryIndex===-1?wsComponent.resourceName:wsComponent.resourceName.slice(0,queryIndex);wsComponent.path=path8&&path8!=="/"?path8:void 0,wsComponent.query=queryIndex===-1?void 0:wsComponent.resourceName.slice(queryIndex+1),wsComponent.resourceName=void 0}return wsComponent.fragment=void 0,wsComponent}function urnParse(urnComponent,options){if(!urnComponent.path)return urnComponent.error="URN can not be parsed",urnComponent;let matches=urnComponent.path.match(URN_REG);if(matches&&matches[0]===urnComponent.path){let scheme=options.scheme||urnComponent.scheme||"urn";urnComponent.nid=matches[1].toLowerCase(),urnComponent.nss=matches[2];let urnScheme=`${scheme}:${options.nid||urnComponent.nid}`,schemeHandler=getSchemeHandler(urnScheme);urnComponent.path=void 0,schemeHandler&&(urnComponent=schemeHandler.parse(urnComponent,options))}else urnComponent.error=urnComponent.error||"URN can not be parsed.";return urnComponent}function urnSerialize(urnComponent,options){if(urnComponent.nid===void 0)throw new Error("URN without nid cannot be serialized");let scheme=options.scheme||urnComponent.scheme||"urn",nid=urnComponent.nid.toLowerCase(),urnScheme=`${scheme}:${options.nid||nid}`,schemeHandler=getSchemeHandler(urnScheme);schemeHandler&&(urnComponent=schemeHandler.serialize(urnComponent,options));let uriComponent=urnComponent,nss=urnComponent.nss;return uriComponent.path=`${nid||options.nid}:${nss}`,options.skipEscape=!0,uriComponent}function urnuuidParse(urnComponent,options){let uuidComponent=urnComponent;return uuidComponent.uuid=uuidComponent.nss,uuidComponent.nss=void 0,!options.tolerant&&(!uuidComponent.uuid||!isUUID(uuidComponent.uuid))&&(uuidComponent.error=uuidComponent.error||"UUID is not valid."),uuidComponent}function urnuuidSerialize(uuidComponent){let urnComponent=uuidComponent;return urnComponent.nss=(uuidComponent.uuid||"").toLowerCase(),urnComponent}var http={scheme:"http",domainHost:!0,parse:httpParse,serialize:httpSerialize},https={scheme:"https",domainHost:http.domainHost,parse:httpParse,serialize:httpSerialize},ws={scheme:"ws",domainHost:!0,parse:wsParse,serialize:wsSerialize},wss={scheme:"wss",domainHost:ws.domainHost,parse:ws.parse,serialize:ws.serialize},urn={scheme:"urn",parse:urnParse,serialize:urnSerialize,skipNormalize:!0},urnuuid={scheme:"urn:uuid",parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:!0},SCHEMES={http,https,ws,wss,urn,"urn:uuid":urnuuid};Object.setPrototypeOf(SCHEMES,null);function getSchemeHandler(scheme){return scheme&&(SCHEMES[scheme]||SCHEMES[scheme.toLowerCase()])||void 0}module.exports={wsIsSecure,SCHEMES,isValidSchemeName,getSchemeHandler}}});var require_fast_uri=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.9/node_modules/fast-uri/index.js"(exports,module){"use strict";var{normalizeIPv6,removeDotSegments,removeDotSegmentsRelative,recomposeAuthority,normalizePercentEncoding,normalizePathEncoding,serializePathEncoding,normalizeQueryFragmentEncoding,encodeQuery,encodeFragment,reescapeHostDelimiters,isIPv4,nonSimpleDomain}=require_utils(),{SCHEMES,getSchemeHandler}=require_schemes(),VALID_SCHEME=/^[A-Za-z][A-Za-z0-9+.-]*$/u,MALFORMED_SCHEME_ERROR="URI scheme is malformed.",MALFORMED_HOST_ERROR="URI host is malformed.",FORBIDDEN_DOMAIN_HOST_CHARACTER=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function validateScheme(scheme){let stringScheme=String(scheme);if(!VALID_SCHEME.test(stringScheme))throw new TypeError(MALFORMED_SCHEME_ERROR);return stringScheme}function normalize(uri,options){return typeof uri=="string"?uri=normalizeString(uri,options):typeof uri=="object"&&(uri=parse4(serialize(uri,options),options)),uri}function resolve7(baseURI,relativeURI,options){let schemelessOptions=options?Object.assign({scheme:"null"},options):{scheme:"null"},{parsed:baseParsed,malformedAuthorityOrPort:baseMalformed,malformedPercentEncoding:baseMalformedPercentEncoding,malformedSchemeSpecific:baseMalformedSchemeSpecific,malformedHost:baseMalformedHost,malformedScheme:baseMalformedScheme}=parseWithStatus(baseURI,schemelessOptions),{parsed:relativeParsed,malformedAuthorityOrPort:relativeMalformed,malformedPercentEncoding:relativeMalformedPercentEncoding,malformedSchemeSpecific:relativeMalformedSchemeSpecific,malformedHost:relativeMalformedHost,malformedScheme:relativeMalformedScheme}=parseWithStatus(relativeURI,schemelessOptions);if(baseMalformed||relativeMalformed||baseMalformedPercentEncoding||relativeMalformedPercentEncoding||baseMalformedSchemeSpecific||relativeMalformedSchemeSpecific||baseMalformedHost||relativeMalformedHost||baseMalformedScheme||relativeMalformedScheme)throw new Error(baseParsed.error||relativeParsed.error||"URI is malformed.");let resolved=resolveComponent(baseParsed,relativeParsed,schemelessOptions,!0),resolvedSchemeHandler=getSchemeHandler(options&&options.scheme||resolved.scheme),resolvedHost=resolved.host,resolvedHostIsIP=resolvedHost!==void 0&&resolvedHost!==""&&(isIPv4(resolvedHost)||normalizeIPv6(resolvedHost).isIPV6);if(hasForbiddenDomainHost(resolved,options||{},resolvedSchemeHandler,resolvedHostIsIP))throw new Error(MALFORMED_HOST_ERROR);canonicalizeHost(resolved,options||{},resolvedSchemeHandler,resolvedHostIsIP);let encodedASCIIHost=resolvedHost&&resolvedHost.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(resolvedHost);if(resolved.error&&!encodedASCIIHost)throw new Error(resolved.error);return schemelessOptions.skipEscape=!0,serialize(resolved,schemelessOptions)}function resolveComponent(base,relative6,options,skipNormalization){let target={};if(skipNormalization||(base=parse4(serialize(base,options),options),relative6=parse4(serialize(relative6,options),options)),options=options||{},!options.tolerant&&relative6.scheme)target.scheme=relative6.scheme,target.userinfo=relative6.userinfo,target.host=relative6.host,target.port=relative6.port,target.path=removeDotSegments(relative6.path||""),target.query=relative6.query;else{if(relative6.userinfo!==void 0||relative6.host!==void 0||relative6.port!==void 0)target.userinfo=relative6.userinfo,target.host=relative6.host,target.port=relative6.port,target.path=removeDotSegments(relative6.path||""),target.query=relative6.query;else{if(!relative6.path)target.path=base.path,relative6.query!==void 0?target.query=relative6.query:target.query=base.query;else{if(relative6.path[0]==="/")target.path=removeDotSegments(relative6.path);else{let baseHasAuthority=base.userinfo!==void 0||base.host!==void 0||base.port!==void 0;baseHasAuthority&&!base.path?target.path="/"+relative6.path:base.path?target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative6.path:target.path=relative6.path,target.path=base.scheme===void 0&&!baseHasAuthority&&target.path[0]!=="/"?removeDotSegmentsRelative(target.path):removeDotSegments(target.path)}target.query=relative6.query}target.userinfo=base.userinfo,target.host=base.host,target.port=base.port}target.scheme=base.scheme}return target.fragment=relative6.fragment,target}function equal(uriA,uriB,options){let normalizedA=normalizeComparableURI(uriA,options),normalizedB=normalizeComparableURI(uriB,options);return normalizedA!==void 0&&normalizedB!==void 0&&normalizedA===normalizedB}function serialize(cmpts,opts){let component={host:cmpts.host,scheme:cmpts.scheme,userinfo:cmpts.userinfo,port:cmpts.port,path:cmpts.path,query:cmpts.query,nid:cmpts.nid,nss:cmpts.nss,uuid:cmpts.uuid,fragment:cmpts.fragment,reference:cmpts.reference,resourceName:cmpts.resourceName,secure:cmpts.secure,error:""},options=Object.assign({},opts),uriTokens=[];component.scheme&&(component.scheme=validateScheme(component.scheme));let schemeHandler=getSchemeHandler(options.scheme||component.scheme);schemeHandler&&schemeHandler.serialize&&schemeHandler.serialize(component,options);let hasAuthority=component.userinfo!==void 0||component.host!==void 0||component.port!==void 0,schemelessReference=(component.scheme===void 0||options.reference==="suffix")&&!hasAuthority,pathNoScheme=!options.skipEscape&&schemelessReference;component.path!==void 0&&(options.skipEscape?component.path=normalizePercentEncoding(component.path):component.path=serializePathEncoding(component.path,pathNoScheme)),options.reference!=="suffix"&&component.scheme&&(component.scheme=validateScheme(component.scheme),uriTokens.push(component.scheme,":"));let authority=recomposeAuthority(component);if(authority!==void 0&&(options.reference!=="suffix"&&uriTokens.push("//"),uriTokens.push(authority),component.path&&component.path[0]!=="/"&&uriTokens.push("/")),component.path!==void 0){let s=component.path;!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath)&&(s=schemelessReference&&s[0]!=="/"?removeDotSegmentsRelative(s):removeDotSegments(s)),schemelessReference&&(s=serializePathEncoding(s,!0)),authority===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),uriTokens.push(s)}return component.query!==void 0&&uriTokens.push("?",encodeQuery(component.query)),component.fragment!==void 0&&uriTokens.push("#",encodeFragment(component.fragment)),uriTokens.join("")}var URI_PARSE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,AUTHORITY_PREFIX=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,AUTHORITY_INTRODUCER_REGION=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function getParseError(parsed,matches){if(matches[2]!==void 0&&parsed.path&&parsed.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof parsed.port=="number"&&(parsed.port<0||parsed.port>65535))return"URI port is malformed."}function hasMalformedPercentEncoding(component){if(component===void 0)return!1;let percent=component.indexOf("%");for(;percent!==-1;){if(percent+2>=component.length||!/^[\da-f]{2}$/iu.test(component.slice(percent+1,percent+3)))return!0;percent=component.indexOf("%",percent+3)}return!1}function isIPLiteral(host){return host[0]==="["&&host[host.length-1]==="]"}function hasMalformedComponentPercentEncoding(matches){let host=matches[4];return hasMalformedPercentEncoding(matches[3])||host!==void 0&&!isIPLiteral(host)&&hasMalformedPercentEncoding(host)||hasMalformedPercentEncoding(matches[6])||hasMalformedPercentEncoding(matches[7])||hasMalformedPercentEncoding(matches[8])}function canonicalizeHost(parsed,options,schemeHandler,isIP){if(hasForbiddenDomainHost(parsed,options,schemeHandler,isIP))return parsed.error=parsed.error||MALFORMED_HOST_ERROR,!0;if(!options.unicodeSupport&&(!schemeHandler||!schemeHandler.unicodeSupport)&&parsed.host&&!isIPLiteral(parsed.host)&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)&&isIP===!1&&nonSimpleDomain(parsed.host)){let url;try{url=new URL("http://"+parsed.host)}catch(e){return parsed.error=parsed.error||"Host's domain name can not be converted to ASCII: "+e,!0}if(!isHostOnlyURL(url))return parsed.error=parsed.error||MALFORMED_HOST_ERROR,!0;parsed.host=url.hostname}return!1}function hasForbiddenDomainHost(parsed,options,schemeHandler,isIP){return!!(parsed.host&&isIP===!1&&!isIPLiteral(parsed.host)&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)&&FORBIDDEN_DOMAIN_HOST_CHARACTER.test(parsed.host))}function isHostOnlyURL(url){return url.username===""&&url.password===""&&url.port===""&&url.pathname==="/"&&url.search===""&&url.hash===""&&url.hostname!==""}function parseWithStatus(uri,opts){let options=Object.assign({},opts),parsed={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},malformedAuthorityOrPort=!1,malformedPercentEncoding=!1,malformedSchemeSpecific=!1,malformedHost=!1,malformedIPLiteral=!1,malformedScheme=!1,isIP=!1;options.reference==="suffix"&&(options.scheme?uri=options.scheme+":"+uri:uri="//"+uri);let authorityMatch=uri.match(AUTHORITY_PREFIX);authorityMatch!==null&&authorityMatch[1].indexOf("\\")!==-1&&(parsed.error="URI authority must not contain a literal backslash.",malformedAuthorityOrPort=!0);let introducerMatch=uri.match(AUTHORITY_INTRODUCER_REGION);if(introducerMatch!==null){let region=introducerMatch[1],normalizedRegion=region.replace(/[\t\n\r]/g,"");normalizedRegion.length>=2&&(normalizedRegion.slice(0,2)!=="//"?(parsed.error=parsed.error||"URI authority must not contain a literal backslash.",malformedAuthorityOrPort=!0):region.length!==normalizedRegion.length&&(parsed.error=parsed.error||"URI authority introducer must not contain whitespace.",malformedAuthorityOrPort=!0))}let matches=uri.match(URI_PARSE);if(matches){parsed.scheme=matches[1],parsed.userinfo=matches[3],parsed.host=matches[4],parsed.port=parseInt(matches[5],10),parsed.path=matches[6]||"",parsed.query=matches[7],parsed.fragment=matches[8],parsed.scheme!==void 0&&(VALID_SCHEME.test(parsed.scheme)?parsed.scheme=parsed.scheme.toLowerCase():(parsed.error=parsed.error||MALFORMED_SCHEME_ERROR,malformedScheme=!0)),malformedPercentEncoding=hasMalformedComponentPercentEncoding(matches),malformedPercentEncoding&&(parsed.error=parsed.error||"URI contains malformed percent-encoding."),isNaN(parsed.port)&&(parsed.port=matches[5]);let parseError=getParseError(parsed,matches);if(parseError!==void 0&&(parsed.error=parsed.error||parseError,malformedAuthorityOrPort=!0),parsed.host)if(isIPv4(parsed.host)===!1){let bracketedIPLiteral=isIPLiteral(parsed.host),hasIPLiteralBracket=parsed.host.indexOf("[")!==-1||parsed.host.indexOf("]")!==-1,ipv6result=normalizeIPv6(parsed.host);isIP=ipv6result.isIPV6||ipv6result.isIPVFuture===!0,malformedIPLiteral=hasIPLiteralBracket&&(!bracketedIPLiteral||ipv6result.error===!0),parsed.host=isIP?ipv6result.host:ipv6result.host.toLowerCase(),malformedIPLiteral&&(parsed.error=parsed.error||MALFORMED_HOST_ERROR,malformedAuthorityOrPort=!0)}else isIP=!0;parsed.scheme===void 0&&parsed.userinfo===void 0&&parsed.host===void 0&&parsed.port===void 0&&parsed.query===void 0&&!parsed.path?parsed.reference="same-document":parsed.scheme===void 0?parsed.reference="relative":parsed.fragment===void 0?parsed.reference="absolute":parsed.reference="uri",options.reference&&options.reference!=="suffix"&&options.reference!==parsed.reference&&(parsed.error=parsed.error||"URI is not a "+options.reference+" reference.");let schemeHandler=getSchemeHandler(options.scheme||parsed.scheme);if(malformedIPLiteral||(malformedHost=canonicalizeHost(parsed,options,schemeHandler,isIP)),uri.indexOf("%")!==-1&&parsed.host!==void 0&&!malformedIPLiteral){let host=isIP?parsed.host:normalizePercentEncoding(parsed.host,!0);isIP||(host=normalizePercentEncoding(host.toLowerCase())),parsed.host=isIP||options.scheme!=="null"?reescapeHostDelimiters(host,isIP):host}(!schemeHandler||schemeHandler&&!schemeHandler.skipNormalize)&&(parsed.path&&(parsed.path=normalizePathEncoding(parsed.path)),parsed.query&&(parsed.query=normalizeQueryFragmentEncoding(parsed.query)),parsed.fragment&&(parsed.fragment=normalizeQueryFragmentEncoding(parsed.fragment))),schemeHandler&&schemeHandler.parse&&(schemeHandler.parse(parsed,options),schemeHandler===SCHEMES.urn&&parsed.nid===void 0&&(malformedSchemeSpecific=!0))}else parsed.error=parsed.error||"URI can not be parsed.";return{parsed,malformedAuthorityOrPort,malformedPercentEncoding,malformedSchemeSpecific,malformedHost,malformedScheme}}function parse4(uri,opts){return parseWithStatus(uri,opts).parsed}function normalizeString(uri,opts){return normalizeStringWithStatus(uri,opts).normalized}function normalizeStringWithStatus(uri,opts){let{parsed,malformedAuthorityOrPort,malformedPercentEncoding,malformedSchemeSpecific,malformedHost,malformedScheme}=parseWithStatus(uri,opts);return{normalized:malformedAuthorityOrPort||malformedPercentEncoding||malformedSchemeSpecific||malformedHost||malformedScheme?uri:serialize(parsed,opts),malformedAuthorityOrPort,malformedPercentEncoding,malformedSchemeSpecific,malformedHost,malformedScheme}}function normalizeComparableURI(uri,opts){if(typeof uri!="string"&&typeof uri!="object")return;let value;try{value=typeof uri=="string"?uri:serialize(uri,opts)}catch{return}let{normalized,malformedAuthorityOrPort,malformedPercentEncoding,malformedSchemeSpecific,malformedHost,malformedScheme}=normalizeStringWithStatus(value,opts);return malformedAuthorityOrPort||malformedPercentEncoding||malformedSchemeSpecific||malformedHost||malformedScheme?void 0:normalized}var fastUri={SCHEMES,normalize,resolve:resolve7,resolveComponent,equal,serialize,parse:parse4};module.exports=fastUri;module.exports.default=fastUri;module.exports.fastUri=fastUri}});var require_uri=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var uri=require_fast_uri();uri.code='require("ajv/dist/runtime/uri").default';exports.default=uri}});var require_core=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=void 0;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error(),ref_error_1=require_ref_error(),rules_1=require_rules(),compile_1=require_compile(),codegen_2=require_codegen(),resolve_1=require_resolve(),dataType_1=require_dataType(),util_1=require_util(),$dataRefSchema=require_data(),uri_1=require_uri(),defaultRegExp=(str,flags)=>new RegExp(str,flags);defaultRegExp.code="new RegExp";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes"],EXT_SCOPE_NAMES=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),removedOptions={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},deprecatedOptions={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},MAX_EXPRESSION=200;function requiredOptions(o){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0;let s=o.strict,_optz=(_a=o.code)===null||_a===void 0?void 0:_a.optimize,optimize=_optz===!0||_optz===void 0?1:_optz||0,regExp=(_c=(_b=o.code)===null||_b===void 0?void 0:_b.regExp)!==null&&_c!==void 0?_c:defaultRegExp,uriResolver=(_d=o.uriResolver)!==null&&_d!==void 0?_d:uri_1.default;return{strictSchema:(_f=(_e=o.strictSchema)!==null&&_e!==void 0?_e:s)!==null&&_f!==void 0?_f:!0,strictNumbers:(_h=(_g=o.strictNumbers)!==null&&_g!==void 0?_g:s)!==null&&_h!==void 0?_h:!0,strictTypes:(_k=(_j=o.strictTypes)!==null&&_j!==void 0?_j:s)!==null&&_k!==void 0?_k:"log",strictTuples:(_m=(_l=o.strictTuples)!==null&&_l!==void 0?_l:s)!==null&&_m!==void 0?_m:"log",strictRequired:(_p=(_o=o.strictRequired)!==null&&_o!==void 0?_o:s)!==null&&_p!==void 0?_p:!1,code:o.code?{...o.code,optimize,regExp}:{optimize,regExp},loopRequired:(_q=o.loopRequired)!==null&&_q!==void 0?_q:MAX_EXPRESSION,loopEnum:(_r=o.loopEnum)!==null&&_r!==void 0?_r:MAX_EXPRESSION,meta:(_s=o.meta)!==null&&_s!==void 0?_s:!0,messages:(_t=o.messages)!==null&&_t!==void 0?_t:!0,inlineRefs:(_u=o.inlineRefs)!==null&&_u!==void 0?_u:!0,schemaId:(_v=o.schemaId)!==null&&_v!==void 0?_v:"$id",addUsedSchema:(_w=o.addUsedSchema)!==null&&_w!==void 0?_w:!0,validateSchema:(_x=o.validateSchema)!==null&&_x!==void 0?_x:!0,validateFormats:(_y=o.validateFormats)!==null&&_y!==void 0?_y:!0,unicodeRegExp:(_z=o.unicodeRegExp)!==null&&_z!==void 0?_z:!0,int32range:(_0=o.int32range)!==null&&_0!==void 0?_0:!0,uriResolver}}var Ajv3=class{constructor(opts={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,opts=this.opts={...opts,...requiredOptions(opts)};let{es5,lines}=this.opts.code;this.scope=new codegen_2.ValueScope({scope:{},prefixes:EXT_SCOPE_NAMES,es5,lines}),this.logger=getLogger(opts.logger);let formatOpt=opts.validateFormats;opts.validateFormats=!1,this.RULES=(0,rules_1.getRules)(),checkOptions.call(this,removedOptions,opts,"NOT SUPPORTED"),checkOptions.call(this,deprecatedOptions,opts,"DEPRECATED","warn"),this._metaOpts=getMetaSchemaOptions.call(this),opts.formats&&addInitialFormats.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),opts.keywords&&addInitialKeywords.call(this,opts.keywords),typeof opts.meta=="object"&&this.addMetaSchema(opts.meta),addInitialSchemas.call(this),opts.validateFormats=formatOpt}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data,meta,schemaId}=this.opts,_dataRefSchema=$dataRefSchema;schemaId==="id"&&(_dataRefSchema={...$dataRefSchema},_dataRefSchema.id=_dataRefSchema.$id,delete _dataRefSchema.$id),meta&&$data&&this.addMetaSchema(_dataRefSchema,_dataRefSchema[schemaId],!1)}defaultMeta(){let{meta,schemaId}=this.opts;return this.opts.defaultMeta=typeof meta=="object"?meta[schemaId]||meta:void 0}validate(schemaKeyRef,data2){let v;if(typeof schemaKeyRef=="string"){if(v=this.getSchema(schemaKeyRef),!v)throw new Error(`no schema with key or ref "${schemaKeyRef}"`)}else v=this.compile(schemaKeyRef);let valid=v(data2);return"$async"in v||(this.errors=v.errors),valid}compile(schema,_meta){let sch=this._addSchema(schema,_meta);return sch.validate||this._compileSchemaEnv(sch)}compileAsync(schema,meta){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema}=this.opts;return runCompileAsync.call(this,schema,meta);async function runCompileAsync(_schema,_meta){await loadMetaSchema.call(this,_schema.$schema);let sch=this._addSchema(_schema,_meta);return sch.validate||_compileAsync.call(this,sch)}async function loadMetaSchema($ref){$ref&&!this.getSchema($ref)&&await runCompileAsync.call(this,{$ref},!0)}async function _compileAsync(sch){try{return this._compileSchemaEnv(sch)}catch(e){if(!(e instanceof ref_error_1.default))throw e;return checkLoaded.call(this,e),await loadMissingSchema.call(this,e.missingSchema),_compileAsync.call(this,sch)}}function checkLoaded({missingSchema:ref2,missingRef}){if(this.refs[ref2])throw new Error(`AnySchema ${ref2} is loaded but ${missingRef} cannot be resolved`)}async function loadMissingSchema(ref2){let _schema=await _loadSchema.call(this,ref2);this.refs[ref2]||await loadMetaSchema.call(this,_schema.$schema),this.refs[ref2]||this.addSchema(_schema,ref2,meta)}async function _loadSchema(ref2){let p=this._loading[ref2];if(p)return p;try{return await(this._loading[ref2]=loadSchema(ref2))}finally{delete this._loading[ref2]}}}addSchema(schema,key2,_meta,_validateSchema=this.opts.validateSchema){if(Array.isArray(schema)){for(let sch of schema)this.addSchema(sch,void 0,_meta,_validateSchema);return this}let id;if(typeof schema=="object"){let{schemaId}=this.opts;if(id=schema[schemaId],id!==void 0&&typeof id!="string")throw new Error(`schema ${schemaId} must be string`)}return key2=(0,resolve_1.normalizeId)(key2||id),this._checkUnique(key2),this.schemas[key2]=this._addSchema(schema,_meta,key2,_validateSchema,!0),this}addMetaSchema(schema,key2,_validateSchema=this.opts.validateSchema){return this.addSchema(schema,key2,!0,_validateSchema),this}validateSchema(schema,throwOrLogError){if(typeof schema=="boolean")return!0;let $schema;if($schema=schema.$schema,$schema!==void 0&&typeof $schema!="string")throw new Error("$schema must be a string");if($schema=$schema||this.opts.defaultMeta||this.defaultMeta(),!$schema)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let valid=this.validate($schema,schema);if(!valid&&throwOrLogError){let message="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(message);else throw new Error(message)}return valid}getSchema(keyRef){let sch;for(;typeof(sch=getSchEnv.call(this,keyRef))=="string";)keyRef=sch;if(sch===void 0){let{schemaId}=this.opts,root=new compile_1.SchemaEnv({schema:{},schemaId});if(sch=compile_1.resolveSchema.call(this,root,keyRef),!sch)return;this.refs[keyRef]=sch}return sch.validate||this._compileSchemaEnv(sch)}removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp)return this._removeAllSchemas(this.schemas,schemaKeyRef),this._removeAllSchemas(this.refs,schemaKeyRef),this;switch(typeof schemaKeyRef){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let sch=getSchEnv.call(this,schemaKeyRef);return typeof sch=="object"&&this._cache.delete(sch.schema),delete this.schemas[schemaKeyRef],delete this.refs[schemaKeyRef],this}case"object":{let cacheKey=schemaKeyRef;this._cache.delete(cacheKey);let id=schemaKeyRef[this.opts.schemaId];return id&&(id=(0,resolve_1.normalizeId)(id),delete this.schemas[id],delete this.refs[id]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(definitions){for(let def of definitions)this.addKeyword(def);return this}addKeyword(kwdOrDef,def){let keyword;if(typeof kwdOrDef=="string")keyword=kwdOrDef,typeof def=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),def.keyword=keyword);else if(typeof kwdOrDef=="object"&&def===void 0){if(def=kwdOrDef,keyword=def.keyword,Array.isArray(keyword)&&!keyword.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(checkKeyword.call(this,keyword,def),!def)return(0,util_1.eachItem)(keyword,kwd=>addRule.call(this,kwd)),this;keywordMetaschema.call(this,def);let definition={...def,type:(0,dataType_1.getJSONTypes)(def.type),schemaType:(0,dataType_1.getJSONTypes)(def.schemaType)};return(0,util_1.eachItem)(keyword,definition.type.length===0?k=>addRule.call(this,k,definition):k=>definition.type.forEach(t=>addRule.call(this,k,definition,t))),this}getKeyword(keyword){let rule=this.RULES.all[keyword];return typeof rule=="object"?rule.definition:!!rule}removeKeyword(keyword){let{RULES}=this;delete RULES.keywords[keyword],delete RULES.all[keyword];for(let group of RULES.rules){let i2=group.rules.findIndex(rule=>rule.keyword===keyword);i2>=0&&group.rules.splice(i2,1)}return this}addFormat(name,format){return typeof format=="string"&&(format=new RegExp(format)),this.formats[name]=format,this}errorsText(errors=this.errors,{separator=", ",dataVar="data"}={}){return!errors||errors.length===0?"No errors":errors.map(e=>`${dataVar}${e.instancePath} ${e.message}`).reduce((text3,msg)=>text3+separator+msg)}$dataMetaSchema(metaSchema,keywordsJsonPointers){let rules=this.RULES.all;metaSchema=JSON.parse(JSON.stringify(metaSchema));for(let jsonPointer of keywordsJsonPointers){let segments=jsonPointer.split("/").slice(1),keywords2=metaSchema;for(let seg of segments)keywords2=keywords2[seg];for(let key2 in rules){let rule=rules[key2];if(typeof rule!="object")continue;let{$data}=rule.definition,schema=keywords2[key2];$data&&schema&&(keywords2[key2]=schemaOrData(schema))}}return metaSchema}_removeAllSchemas(schemas,regex){for(let keyRef in schemas){let sch=schemas[keyRef];(!regex||regex.test(keyRef))&&(typeof sch=="string"?delete schemas[keyRef]:sch&&!sch.meta&&(this._cache.delete(sch.schema),delete schemas[keyRef]))}}_addSchema(schema,meta,baseId,validateSchema=this.opts.validateSchema,addSchema=this.opts.addUsedSchema){let id,{schemaId}=this.opts;if(typeof schema=="object")id=schema[schemaId];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof schema!="boolean")throw new Error("schema must be object or boolean")}let sch=this._cache.get(schema);if(sch!==void 0)return sch;baseId=(0,resolve_1.normalizeId)(id||baseId);let localRefs=resolve_1.getSchemaRefs.call(this,schema,baseId);return sch=new compile_1.SchemaEnv({schema,schemaId,meta,baseId,localRefs}),this._cache.set(sch.schema,sch),addSchema&&!baseId.startsWith("#")&&(baseId&&this._checkUnique(baseId),this.refs[baseId]=sch),validateSchema&&this.validateSchema(schema,!0),sch}_checkUnique(id){if(this.schemas[id]||this.refs[id])throw new Error(`schema with key or id "${id}" already exists`)}_compileSchemaEnv(sch){if(sch.meta?this._compileMetaSchema(sch):compile_1.compileSchema.call(this,sch),!sch.validate)throw new Error("ajv implementation error");return sch.validate}_compileMetaSchema(sch){let currentOpts=this.opts;this.opts=this._metaOpts;try{compile_1.compileSchema.call(this,sch)}finally{this.opts=currentOpts}}};Ajv3.ValidationError=validation_error_1.default;Ajv3.MissingRefError=ref_error_1.default;exports.default=Ajv3;function checkOptions(checkOpts,options,msg,log="error"){for(let key2 in checkOpts){let opt=key2;opt in options&&this.logger[log](`${msg}: option ${key2}. ${checkOpts[opt]}`)}}function getSchEnv(keyRef){return keyRef=(0,resolve_1.normalizeId)(keyRef),this.schemas[keyRef]||this.refs[keyRef]}function addInitialSchemas(){let optsSchemas=this.opts.schemas;if(optsSchemas)if(Array.isArray(optsSchemas))this.addSchema(optsSchemas);else for(let key2 in optsSchemas)this.addSchema(optsSchemas[key2],key2)}function addInitialFormats(){for(let name in this.opts.formats){let format=this.opts.formats[name];format&&this.addFormat(name,format)}}function addInitialKeywords(defs){if(Array.isArray(defs)){this.addVocabulary(defs);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let keyword in defs){let def=defs[keyword];def.keyword||(def.keyword=keyword),this.addKeyword(def)}}function getMetaSchemaOptions(){let metaOpts={...this.opts};for(let opt of META_IGNORE_OPTIONS)delete metaOpts[opt];return metaOpts}var noLogs={log(){},warn(){},error(){}};function getLogger(logger){if(logger===!1)return noLogs;if(logger===void 0)return console;if(logger.log&&logger.warn&&logger.error)return logger;throw new Error("logger must implement log, warn and error methods")}var KEYWORD_NAME=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(keyword,def){let{RULES}=this;if((0,util_1.eachItem)(keyword,kwd=>{if(RULES.keywords[kwd])throw new Error(`Keyword ${kwd} is already defined`);if(!KEYWORD_NAME.test(kwd))throw new Error(`Keyword ${kwd} has invalid name`)}),!!def&&def.$data&&!("code"in def||"validate"in def))throw new Error('$data keyword must have "code" or "validate" function')}function addRule(keyword,definition,dataType){var _a;let post=definition?.post;if(dataType&&post)throw new Error('keyword with "post" flag cannot have "type"');let{RULES}=this,ruleGroup=post?RULES.post:RULES.rules.find(({type:t})=>t===dataType);if(ruleGroup||(ruleGroup={type:dataType,rules:[]},RULES.rules.push(ruleGroup)),RULES.keywords[keyword]=!0,!definition)return;let rule={keyword,definition:{...definition,type:(0,dataType_1.getJSONTypes)(definition.type),schemaType:(0,dataType_1.getJSONTypes)(definition.schemaType)}};definition.before?addBeforeRule.call(this,ruleGroup,rule,definition.before):ruleGroup.rules.push(rule),RULES.all[keyword]=rule,(_a=definition.implements)===null||_a===void 0||_a.forEach(kwd=>this.addKeyword(kwd))}function addBeforeRule(ruleGroup,rule,before){let i2=ruleGroup.rules.findIndex(_rule=>_rule.keyword===before);i2>=0?ruleGroup.rules.splice(i2,0,rule):(ruleGroup.rules.push(rule),this.logger.warn(`rule ${before} is not defined`))}function keywordMetaschema(def){let{metaSchema}=def;metaSchema!==void 0&&(def.$data&&this.opts.$data&&(metaSchema=schemaOrData(metaSchema)),def.validateSchema=this.compile(metaSchema,!0))}var $dataRef={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function schemaOrData(schema){return{anyOf:[schema,$dataRef]}}}});var require_id=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var def={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};exports.default=def}});var require_ref=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.callRef=exports.getValidate=void 0;var ref_error_1=require_ref_error(),code_1=require_code2(),codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),util_1=require_util(),def={keyword:"$ref",schemaType:"string",code(cxt){let{gen,schema:$ref,it}=cxt,{baseId,schemaEnv:env,validateName,opts,self}=it,{root}=env;if(($ref==="#"||$ref==="#/")&&baseId===root.baseId)return callRootRef();let schOrEnv=compile_1.resolveRef.call(self,root,baseId,$ref);if(schOrEnv===void 0)throw new ref_error_1.default(it.opts.uriResolver,baseId,$ref);if(schOrEnv instanceof compile_1.SchemaEnv)return callValidate(schOrEnv);return inlineRefSchema(schOrEnv);function callRootRef(){if(env===root)return callRef(cxt,validateName,env,env.$async);let rootName=gen.scopeValue("root",{ref:root});return callRef(cxt,(0,codegen_1._)`${rootName}.validate`,root,root.$async)}function callValidate(sch){let v=getValidate(cxt,sch);callRef(cxt,v,sch,sch.$async)}function inlineRefSchema(sch){let schName=gen.scopeValue("schema",opts.code.source===!0?{ref:sch,code:(0,codegen_1.stringify)(sch)}:{ref:sch}),valid=gen.name("valid"),schCxt=cxt.subschema({schema:sch,dataTypes:[],schemaPath:codegen_1.nil,topSchemaRef:schName,errSchemaPath:$ref},valid);cxt.mergeEvaluated(schCxt),cxt.ok(valid)}}};function getValidate(cxt,sch){let{gen}=cxt;return sch.validate?gen.scopeValue("validate",{ref:sch.validate}):(0,codegen_1._)`${gen.scopeValue("wrapper",{ref:sch})}.validate`}exports.getValidate=getValidate;function callRef(cxt,v,sch,$async){let{gen,it}=cxt,{allErrors,schemaEnv:env,opts}=it,passCxt=opts.passContext?names_1.default.this:codegen_1.nil;$async?callAsyncRef():callSyncRef();function callAsyncRef(){if(!env.$async)throw new Error("async schema referenced by sync schema");let valid=gen.let("valid");gen.try(()=>{gen.code((0,codegen_1._)`await ${(0,code_1.callValidateCode)(cxt,v,passCxt)}`),addEvaluatedFrom(v),allErrors||gen.assign(valid,!0)},e=>{gen.if((0,codegen_1._)`!(${e} instanceof ${it.ValidationError})`,()=>gen.throw(e)),addErrorsFrom(e),allErrors||gen.assign(valid,!1)}),cxt.ok(valid)}function callSyncRef(){cxt.result((0,code_1.callValidateCode)(cxt,v,passCxt),()=>addEvaluatedFrom(v),()=>addErrorsFrom(v))}function addErrorsFrom(source){let errs=(0,codegen_1._)`${source}.errors`;gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`),gen.assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`)}function addEvaluatedFrom(source){var _a;if(!it.opts.unevaluated)return;let schEvaluated=(_a=sch?.validate)===null||_a===void 0?void 0:_a.evaluated;if(it.props!==!0)if(schEvaluated&&!schEvaluated.dynamicProps)schEvaluated.props!==void 0&&(it.props=util_1.mergeEvaluated.props(gen,schEvaluated.props,it.props));else{let props=gen.var("props",(0,codegen_1._)`${source}.evaluated.props`);it.props=util_1.mergeEvaluated.props(gen,props,it.props,codegen_1.Name)}if(it.items!==!0)if(schEvaluated&&!schEvaluated.dynamicItems)schEvaluated.items!==void 0&&(it.items=util_1.mergeEvaluated.items(gen,schEvaluated.items,it.items));else{let items=gen.var("items",(0,codegen_1._)`${source}.evaluated.items`);it.items=util_1.mergeEvaluated.items(gen,items,it.items,codegen_1.Name)}}}exports.callRef=callRef;exports.default=def}});var require_core2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var id_1=require_id(),ref_1=require_ref(),core=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];exports.default=core}});var require_limitNumber=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={maximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},minimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},exclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},exclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},error2={message:({keyword,schemaCode})=>(0,codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`},def={keyword:Object.keys(KWDs),type:"number",schemaType:"number",$data:!0,error:error2,code(cxt){let{keyword,data:data2,schemaCode}=cxt;cxt.fail$data((0,codegen_1._)`${data2} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data2})`)}};exports.default=def}});var require_multipleOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),error2={message:({schemaCode})=>(0,codegen_1.str)`must be multiple of ${schemaCode}`,params:({schemaCode})=>(0,codegen_1._)`{multipleOf: ${schemaCode}}`},def={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:error2,code(cxt){let{gen,data:data2,schemaCode,it}=cxt,prec=it.opts.multipleOfPrecision,res=gen.let("res"),invalid2=prec?(0,codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`:(0,codegen_1._)`${res} !== parseInt(${res})`;cxt.fail$data((0,codegen_1._)`(${schemaCode} === 0 || (${res} = ${data2}/${schemaCode}, ${invalid2}))`)}};exports.default=def}});var require_ucs2length=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});function ucs2length(str){let len=str.length,length=0,pos=0,value;for(;pos<len;)length++,value=str.charCodeAt(pos++),value>=55296&&value<=56319&&pos<len&&(value=str.charCodeAt(pos),(value&64512)===56320&&pos++);return length}exports.default=ucs2length;ucs2length.code='require("ajv/dist/runtime/ucs2length").default'}});var require_limitLength=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),ucs2length_1=require_ucs2length(),error2={message({keyword,schemaCode}){let comp=keyword==="maxLength"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},def={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:error2,code(cxt){let{keyword,data:data2,schemaCode,it}=cxt,op=keyword==="maxLength"?codegen_1.operators.GT:codegen_1.operators.LT,len=it.opts.unicode===!1?(0,codegen_1._)`${data2}.length`:(0,codegen_1._)`${(0,util_1.useFunc)(cxt.gen,ucs2length_1.default)}(${data2})`;cxt.fail$data((0,codegen_1._)`${len} ${op} ${schemaCode}`)}};exports.default=def}});var require_pattern=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var code_1=require_code2(),util_1=require_util(),codegen_1=require_codegen(),error2={message:({schemaCode})=>(0,codegen_1.str)`must match pattern "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{pattern: ${schemaCode}}`},def={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:error2,code(cxt){let{gen,data:data2,$data,schema,schemaCode,it}=cxt,u=it.opts.unicodeRegExp?"u":"";if($data){let{regExp}=it.opts.code,regExpCode=regExp.code==="new RegExp"?(0,codegen_1._)`new RegExp`:(0,util_1.useFunc)(gen,regExp),valid=gen.let("valid");gen.try(()=>gen.assign(valid,(0,codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data2})`),()=>gen.assign(valid,!1)),cxt.fail$data((0,codegen_1._)`!${valid}`)}else{let regExp=(0,code_1.usePattern)(cxt,schema);cxt.fail$data((0,codegen_1._)`!${regExp}.test(${data2})`)}}};exports.default=def}});var require_limitProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),error2={message({keyword,schemaCode}){let comp=keyword==="maxProperties"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},def={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:error2,code(cxt){let{keyword,data:data2,schemaCode}=cxt,op=keyword==="maxProperties"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`Object.keys(${data2}).length ${op} ${schemaCode}`)}};exports.default=def}});var require_required=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var code_1=require_code2(),codegen_1=require_codegen(),util_1=require_util(),error2={message:({params:{missingProperty}})=>(0,codegen_1.str)`must have required property '${missingProperty}'`,params:({params:{missingProperty}})=>(0,codegen_1._)`{missingProperty: ${missingProperty}}`},def={keyword:"required",type:"object",schemaType:"array",$data:!0,error:error2,code(cxt){let{gen,schema,schemaCode,data:data2,$data,it}=cxt,{opts}=it;if(!$data&&schema.length===0)return;let useLoop=schema.length>=opts.loopRequired;if(it.allErrors?allErrorsMode():exitOnErrorMode(),opts.strictRequired){let props=cxt.parentSchema.properties,{definedProperties}=cxt.it;for(let requiredKey of schema)if(props?.[requiredKey]===void 0&&!definedProperties.has(requiredKey)){let schemaPath=it.schemaEnv.baseId+it.errSchemaPath,msg=`required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;(0,util_1.checkStrictMode)(it,msg,it.opts.strictRequired)}}function allErrorsMode(){if(useLoop||$data)cxt.block$data(codegen_1.nil,loopAllRequired);else for(let prop of schema)(0,code_1.checkReportMissingProp)(cxt,prop)}function exitOnErrorMode(){let missing=gen.let("missing");if(useLoop||$data){let valid=gen.let("valid",!0);cxt.block$data(valid,()=>loopUntilMissing(missing,valid)),cxt.ok(valid)}else gen.if((0,code_1.checkMissingProp)(cxt,schema,missing)),(0,code_1.reportMissingProp)(cxt,missing),gen.else()}function loopAllRequired(){gen.forOf("prop",schemaCode,prop=>{cxt.setParams({missingProperty:prop}),gen.if((0,code_1.noPropertyInData)(gen,data2,prop,opts.ownProperties),()=>cxt.error())})}function loopUntilMissing(missing,valid){cxt.setParams({missingProperty:missing}),gen.forOf(missing,schemaCode,()=>{gen.assign(valid,(0,code_1.propertyInData)(gen,data2,missing,opts.ownProperties)),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(),gen.break()})},codegen_1.nil)}}};exports.default=def}});var require_limitItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),error2={message({keyword,schemaCode}){let comp=keyword==="maxItems"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`},def={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:error2,code(cxt){let{keyword,data:data2,schemaCode}=cxt,op=keyword==="maxItems"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`${data2}.length ${op} ${schemaCode}`)}};exports.default=def}});var require_equal=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var equal=require_fast_deep_equal();equal.code='require("ajv/dist/runtime/equal").default';exports.default=equal}});var require_uniqueItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dataType_1=require_dataType(),codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),error2={message:({params:{i:i2,j}})=>(0,codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`,params:({params:{i:i2,j}})=>(0,codegen_1._)`{i: ${i2}, j: ${j}}`},def={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:error2,code(cxt){let{gen,data:data2,$data,schema,parentSchema,schemaCode,it}=cxt;if(!$data&&!schema)return;let valid=gen.let("valid"),itemTypes=parentSchema.items?(0,dataType_1.getSchemaTypes)(parentSchema.items):[];cxt.block$data(valid,validateUniqueItems,(0,codegen_1._)`${schemaCode} === false`),cxt.ok(valid);function validateUniqueItems(){let i2=gen.let("i",(0,codegen_1._)`${data2}.length`),j=gen.let("j");cxt.setParams({i:i2,j}),gen.assign(valid,!0),gen.if((0,codegen_1._)`${i2} > 1`,()=>(canOptimize()?loopN:loopN2)(i2,j))}function canOptimize(){return itemTypes.length>0&&!itemTypes.some(t=>t==="object"||t==="array")}function loopN(i2,j){let item=gen.name("item"),wrongType=(0,dataType_1.checkDataTypes)(itemTypes,item,it.opts.strictNumbers,dataType_1.DataType.Wrong),indices=gen.const("indices",(0,codegen_1._)`{}`);gen.for((0,codegen_1._)`;${i2}--;`,()=>{gen.let(item,(0,codegen_1._)`${data2}[${i2}]`),gen.if(wrongType,(0,codegen_1._)`continue`),itemTypes.length>1&&gen.if((0,codegen_1._)`typeof ${item} == "string"`,(0,codegen_1._)`${item} += "_"`),gen.if((0,codegen_1._)`typeof ${indices}[${item}] == "number"`,()=>{gen.assign(j,(0,codegen_1._)`${indices}[${item}]`),cxt.error(),gen.assign(valid,!1).break()}).code((0,codegen_1._)`${indices}[${item}] = ${i2}`)})}function loopN2(i2,j){let eql=(0,util_1.useFunc)(gen,equal_1.default),outer=gen.name("outer");gen.label(outer).for((0,codegen_1._)`;${i2}--;`,()=>gen.for((0,codegen_1._)`${j} = ${i2}; ${j}--;`,()=>gen.if((0,codegen_1._)`${eql}(${data2}[${i2}], ${data2}[${j}])`,()=>{cxt.error(),gen.assign(valid,!1).break(outer)})))}}};exports.default=def}});var require_const=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),error2={message:"must be equal to constant",params:({schemaCode})=>(0,codegen_1._)`{allowedValue: ${schemaCode}}`},def={keyword:"const",$data:!0,error:error2,code(cxt){let{gen,data:data2,$data,schemaCode,schema}=cxt;$data||schema&&typeof schema=="object"?cxt.fail$data((0,codegen_1._)`!${(0,util_1.useFunc)(gen,equal_1.default)}(${data2}, ${schemaCode})`):cxt.fail((0,codegen_1._)`${schema} !== ${data2}`)}};exports.default=def}});var require_enum=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),equal_1=require_equal(),error2={message:"must be equal to one of the allowed values",params:({schemaCode})=>(0,codegen_1._)`{allowedValues: ${schemaCode}}`},def={keyword:"enum",schemaType:"array",$data:!0,error:error2,code(cxt){let{gen,data:data2,$data,schema,schemaCode,it}=cxt;if(!$data&&schema.length===0)throw new Error("enum must have non-empty array");let useLoop=schema.length>=it.opts.loopEnum,eql,getEql=()=>eql??(eql=(0,util_1.useFunc)(gen,equal_1.default)),valid;if(useLoop||$data)valid=gen.let("valid"),cxt.block$data(valid,loopEnum);else{if(!Array.isArray(schema))throw new Error("ajv implementation error");let vSchema=gen.const("vSchema",schemaCode);valid=(0,codegen_1.or)(...schema.map((_x,i2)=>equalCode(vSchema,i2)))}cxt.pass(valid);function loopEnum(){gen.assign(valid,!1),gen.forOf("v",schemaCode,v=>gen.if((0,codegen_1._)`${getEql()}(${data2}, ${v})`,()=>gen.assign(valid,!0).break()))}function equalCode(vSchema,i2){let sch=schema[i2];return typeof sch=="object"&&sch!==null?(0,codegen_1._)`${getEql()}(${data2}, ${vSchema}[${i2}])`:(0,codegen_1._)`${data2} === ${sch}`}}};exports.default=def}});var require_validation=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var limitNumber_1=require_limitNumber(),multipleOf_1=require_multipleOf(),limitLength_1=require_limitLength(),pattern_1=require_pattern(),limitProperties_1=require_limitProperties(),required_1=require_required(),limitItems_1=require_limitItems(),uniqueItems_1=require_uniqueItems(),const_1=require_const(),enum_1=require_enum(),validation=[limitNumber_1.default,multipleOf_1.default,limitLength_1.default,pattern_1.default,limitProperties_1.default,required_1.default,limitItems_1.default,uniqueItems_1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},const_1.default,enum_1.default];exports.default=validation}});var require_additionalItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.validateAdditionalItems=void 0;var codegen_1=require_codegen(),util_1=require_util(),error2={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},def={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:error2,code(cxt){let{parentSchema,it}=cxt,{items}=parentSchema;if(!Array.isArray(items)){(0,util_1.checkStrictMode)(it,'"additionalItems" is ignored when "items" is not an array of schemas');return}validateAdditionalItems(cxt,items)}};function validateAdditionalItems(cxt,items){let{gen,schema,data:data2,keyword,it}=cxt;it.items=!0;let len=gen.const("len",(0,codegen_1._)`${data2}.length`);if(schema===!1)cxt.setParams({len:items.length}),cxt.pass((0,codegen_1._)`${len} <= ${items.length}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items.length}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid)),cxt.ok(valid)}function validateItems(valid){gen.forRange("i",items.length,len,i2=>{cxt.subschema({keyword,dataProp:i2,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}exports.validateAdditionalItems=validateAdditionalItems;exports.default=def}});var require_items=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.validateTuple=void 0;var codegen_1=require_codegen(),util_1=require_util(),code_1=require_code2(),def={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(cxt){let{schema,it}=cxt;if(Array.isArray(schema))return validateTuple(cxt,"additionalItems",schema);it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema)&&cxt.ok((0,code_1.validateArray)(cxt))}};function validateTuple(cxt,extraItems,schArr=cxt.schema){let{gen,parentSchema,data:data2,keyword,it}=cxt;checkStrictTuple(parentSchema),it.opts.unevaluated&&schArr.length&&it.items!==!0&&(it.items=util_1.mergeEvaluated.items(gen,schArr.length,it.items));let valid=gen.name("valid"),len=gen.const("len",(0,codegen_1._)`${data2}.length`);schArr.forEach((sch,i2)=>{(0,util_1.alwaysValidSchema)(it,sch)||(gen.if((0,codegen_1._)`${len} > ${i2}`,()=>cxt.subschema({keyword,schemaProp:i2,dataProp:i2},valid)),cxt.ok(valid))});function checkStrictTuple(sch){let{opts,errSchemaPath}=it,l=schArr.length,fullTuple=l===sch.minItems&&(l===sch.maxItems||sch[extraItems]===!1);if(opts.strictTuples&&!fullTuple){let msg=`"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;(0,util_1.checkStrictMode)(it,msg,opts.strictTuples)}}}exports.validateTuple=validateTuple;exports.default=def}});var require_prefixItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var items_1=require_items(),def={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:cxt=>(0,items_1.validateTuple)(cxt,"items")};exports.default=def}});var require_items2020=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),code_1=require_code2(),additionalItems_1=require_additionalItems(),error2={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},def={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:error2,code(cxt){let{schema,parentSchema,it}=cxt,{prefixItems}=parentSchema;it.items=!0,!(0,util_1.alwaysValidSchema)(it,schema)&&(prefixItems?(0,additionalItems_1.validateAdditionalItems)(cxt,prefixItems):cxt.ok((0,code_1.validateArray)(cxt)))}};exports.default=def}});var require_contains=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:({params:{min,max}})=>max===void 0?(0,codegen_1.str)`must contain at least ${min} valid item(s)`:(0,codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,params:({params:{min,max}})=>max===void 0?(0,codegen_1._)`{minContains: ${min}}`:(0,codegen_1._)`{minContains: ${min}, maxContains: ${max}}`},def={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:error2,code(cxt){let{gen,schema,parentSchema,data:data2,it}=cxt,min,max,{minContains,maxContains}=parentSchema;it.opts.next?(min=minContains===void 0?1:minContains,max=maxContains):min=1;let len=gen.const("len",(0,codegen_1._)`${data2}.length`);if(cxt.setParams({min,max}),max===void 0&&min===0){(0,util_1.checkStrictMode)(it,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(max!==void 0&&min>max){(0,util_1.checkStrictMode)(it,'"minContains" > "maxContains" is always invalid'),cxt.fail();return}if((0,util_1.alwaysValidSchema)(it,schema)){let cond=(0,codegen_1._)`${len} >= ${min}`;max!==void 0&&(cond=(0,codegen_1._)`${cond} && ${len} <= ${max}`),cxt.pass(cond);return}it.items=!0;let valid=gen.name("valid");max===void 0&&min===1?validateItems(valid,()=>gen.if(valid,()=>gen.break())):min===0?(gen.let(valid,!0),max!==void 0&&gen.if((0,codegen_1._)`${data2}.length > 0`,validateItemsWithCount)):(gen.let(valid,!1),validateItemsWithCount()),cxt.result(valid,()=>cxt.reset());function validateItemsWithCount(){let schValid=gen.name("_valid"),count=gen.let("count",0);validateItems(schValid,()=>gen.if(schValid,()=>checkLimits(count)))}function validateItems(_valid,block){gen.forRange("i",0,len,i2=>{cxt.subschema({keyword:"contains",dataProp:i2,dataPropType:util_1.Type.Num,compositeRule:!0},_valid),block()})}function checkLimits(count){gen.code((0,codegen_1._)`${count}++`),max===void 0?gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0).break()):(gen.if((0,codegen_1._)`${count} > ${max}`,()=>gen.assign(valid,!1).break()),min===1?gen.assign(valid,!0):gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,!0)))}}};exports.default=def}});var require_dependencies=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.validateSchemaDeps=exports.validatePropertyDeps=exports.error=void 0;var codegen_1=require_codegen(),util_1=require_util(),code_1=require_code2();exports.error={message:({params:{property,depsCount,deps}})=>{let property_ies=depsCount===1?"property":"properties";return(0,codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`},params:({params:{property,depsCount,deps,missingProperty}})=>(0,codegen_1._)`{property: ${property},
613
- missingProperty: ${missingProperty},
614
- depsCount: ${depsCount},
615
- deps: ${deps}}`};var def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){let[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps),validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){let propertyDeps={},schemaDeps={};for(let key2 in schema){if(key2==="__proto__")continue;let deps=Array.isArray(schema[key2])?propertyDeps:schemaDeps;deps[key2]=schema[key2]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){let{gen,data:data2,it}=cxt;if(Object.keys(propertyDeps).length===0)return;let missing=gen.let("missing");for(let prop in propertyDeps){let deps=propertyDeps[prop];if(deps.length===0)continue;let hasProperty=(0,code_1.propertyInData)(gen,data2,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")}),it.allErrors?gen.if(hasProperty,()=>{for(let depProp of deps)(0,code_1.checkReportMissingProp)(cxt,depProp)}):(gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`),(0,code_1.reportMissingProp)(cxt,missing),gen.else())}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){let{gen,data:data2,keyword,it}=cxt,valid=gen.name("valid");for(let prop in schemaDeps)(0,util_1.alwaysValidSchema)(it,schemaDeps[prop])||(gen.if((0,code_1.propertyInData)(gen,data2,prop,it.opts.ownProperties),()=>{let schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,!0)),cxt.ok(valid))}exports.validateSchemaDeps=validateSchemaDeps;exports.default=def}});var require_propertyNames=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`},def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error2,code(cxt){let{gen,schema,data:data2,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;let valid=gen.name("valid");gen.forIn("key",data2,key2=>{cxt.setParams({propertyName:key2}),cxt.subschema({keyword:"propertyNames",data:key2,dataTypes:["string"],propertyName:key2,compositeRule:!0},valid),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(!0),it.allErrors||gen.break()})}),cxt.ok(valid)}};exports.default=def}});var require_additionalProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var code_1=require_code2(),codegen_1=require_codegen(),names_1=require_names(),util_1=require_util(),error2={message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`},def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:error2,code(cxt){let{gen,schema,parentSchema,data:data2,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,opts}=it;if(it.props=!0,opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;let props=(0,code_1.allSchemaProperties)(parentSchema.properties),patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties(),cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data2,key2=>{!props.length&&!patProps.length?additionalPropertyCode(key2):gen.if(isAdditional(key2),()=>additionalPropertyCode(key2))})}function isAdditional(key2){let definedProp;if(props.length>8){let propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key2)}else props.length?definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key2} === ${p}`)):definedProp=codegen_1.nil;return patProps.length&&(definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key2})`))),(0,codegen_1.not)(definedProp)}function deleteAdditional(key2){gen.code((0,codegen_1._)`delete ${data2}[${key2}]`)}function additionalPropertyCode(key2){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===!1){deleteAdditional(key2);return}if(schema===!1){cxt.setParams({additionalProperty:key2}),cxt.error(),allErrors||gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.name("valid");opts.removeAdditional==="failing"?(applyAdditionalSchema(key2,valid,!1),gen.if((0,codegen_1.not)(valid),()=>{cxt.reset(),deleteAdditional(key2)})):(applyAdditionalSchema(key2,valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break()))}}function applyAdditionalSchema(key2,valid,errors){let subschema={keyword:"additionalProperties",dataProp:key2,dataPropType:util_1.Type.Str};errors===!1&&Object.assign(subschema,{compositeRule:!0,createErrors:!1,allErrors:!1}),cxt.subschema(subschema,valid)}}};exports.default=def}});var require_properties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var validate_1=require_validate(),code_1=require_code2(),util_1=require_util(),additionalProperties_1=require_additionalProperties(),def={keyword:"properties",type:"object",schemaType:"object",code(cxt){let{gen,schema,parentSchema,data:data2,it}=cxt;it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0&&additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"));let allProps=(0,code_1.allSchemaProperties)(schema);for(let prop of allProps)it.definedProperties.add(prop);it.opts.unevaluated&&allProps.length&&it.props!==!0&&(it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props));let properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;let valid=gen.name("valid");for(let prop of properties)hasDefault(prop)?applyPropertySchema(prop):(gen.if((0,code_1.propertyInData)(gen,data2,prop,it.opts.ownProperties)),applyPropertySchema(prop),it.allErrors||gen.else().var(valid,!0),gen.endIf()),cxt.it.definedProperties.add(prop),cxt.ok(valid);function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def}});var require_patternProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var code_1=require_code2(),codegen_1=require_codegen(),util_1=require_util(),util_2=require_util(),def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){let{gen,schema,data:data2,parentSchema,it}=cxt,{opts}=it,patterns=(0,code_1.allSchemaProperties)(schema),alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===!0))return;let checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties,valid=gen.name("valid");it.props!==!0&&!(it.props instanceof codegen_1.Name)&&(it.props=(0,util_2.evaluatedPropsToName)(gen,it.props));let{props}=it;validatePatternProperties();function validatePatternProperties(){for(let pat of patterns)checkProperties&&checkMatchingProperties(pat),it.allErrors?validateProperties(pat):(gen.var(valid,!0),validateProperties(pat),gen.if(valid))}function checkMatchingProperties(pat){for(let prop in checkProperties)new RegExp(pat).test(prop)&&(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}function validateProperties(pat){gen.forIn("key",data2,key2=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key2})`,()=>{let alwaysValid=alwaysValidPatterns.includes(pat);alwaysValid||cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key2,dataPropType:util_2.Type.Str},valid),it.opts.unevaluated&&props!==!0?gen.assign((0,codegen_1._)`${props}[${key2}]`,!0):!alwaysValid&&!it.allErrors&&gen.if((0,codegen_1.not)(valid),()=>gen.break())})})}}};exports.default=def}});var require_not=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util_1=require_util(),def={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(cxt){let{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}let valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},valid),cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def}});var require_anyOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var code_1=require_code2(),def={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def}});var require_oneOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`},def={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:error2,code(cxt){let{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;let schArr=schema,valid=gen.let("valid",!1),passing=gen.let("passing",null),schValid=gen.name("_valid");cxt.setParams({passing}),gen.block(validateOneOf),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0));function validateOneOf(){schArr.forEach((sch,i2)=>{let schCxt;(0,util_1.alwaysValidSchema)(it,sch)?gen.var(schValid,!0):schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i2,compositeRule:!0},schValid),i2>0&&gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,!1).assign(passing,(0,codegen_1._)`[${passing}, ${i2}]`).else(),gen.if(schValid,()=>{gen.assign(valid,!0),gen.assign(passing,i2),schCxt&&cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def}});var require_allOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util_1=require_util(),def={keyword:"allOf",schemaType:"array",code(cxt){let{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");let valid=gen.name("valid");schema.forEach((sch,i2)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;let schCxt=cxt.subschema({keyword:"allOf",schemaProp:i2},valid);cxt.ok(valid),cxt.mergeEvaluated(schCxt)})}};exports.default=def}});var require_if=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`},def={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:error2,code(cxt){let{gen,parentSchema,it}=cxt;parentSchema.then===void 0&&parentSchema.else===void 0&&(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored');let hasThen=hasSchema(it,"then"),hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;let valid=gen.let("valid",!0),schValid=gen.name("_valid");if(validateIf(),cxt.reset(),hasThen&&hasElse){let ifClause=gen.let("ifClause");cxt.setParams({ifClause}),gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else hasThen?gen.if(schValid,validateClause("then")):gen.if((0,codegen_1.not)(schValid),validateClause("else"));cxt.pass(valid,()=>cxt.error(!0));function validateIf(){let schCxt=cxt.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{let schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid),cxt.mergeValidEvaluated(schCxt,valid),ifClause?gen.assign(ifClause,(0,codegen_1._)`${keyword}`):cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){let schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports.default=def}});var require_thenElse=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util_1=require_util(),def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){parentSchema.if===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def}});var require_applicator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var additionalItems_1=require_additionalItems(),prefixItems_1=require_prefixItems(),items_1=require_items(),items2020_1=require_items2020(),contains_1=require_contains(),dependencies_1=require_dependencies(),propertyNames_1=require_propertyNames(),additionalProperties_1=require_additionalProperties(),properties_1=require_properties(),patternProperties_1=require_patternProperties(),not_1=require_not(),anyOf_1=require_anyOf(),oneOf_1=require_oneOf(),allOf_1=require_allOf(),if_1=require_if(),thenElse_1=require_thenElse();function getApplicator(draft2020=!1){let applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];return draft2020?applicator.push(prefixItems_1.default,items2020_1.default):applicator.push(additionalItems_1.default,items_1.default),applicator.push(contains_1.default),applicator}exports.default=getApplicator}});var require_format=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),error2={message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`},def={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:error2,code(cxt,ruleType){let{gen,data:data2,$data,schema,schemaCode,it}=cxt,{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`),fType=gen.let("fType"),format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef)),cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return opts.strictSchema===!1?codegen_1.nil:(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){let callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data2}) : ${format}(${data2}))`:(0,codegen_1._)`${format}(${data2})`,validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data2}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){let formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===!0)return;let[fmtType,format,fmtRef]=getFormat(formatDef);fmtType===ruleType&&cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===!1){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){let code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0,fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});return typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)?[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]:["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data2})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data2})`:(0,codegen_1._)`${fmtRef}.test(${data2})`}}}};exports.default=def}});var require_format2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var format_1=require_format(),format=[format_1.default];exports.default=format}});var require_metadata=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.contentVocabulary=exports.metadataVocabulary=void 0;exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}});var require_draft7=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var core_1=require_core2(),validation_1=require_validation(),applicator_1=require_applicator(),format_1=require_format2(),metadata_1=require_metadata(),draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies}});var require_types=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2.Tag="tag",DiscrError2.Mapping="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))}});var require_discriminator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),types_1=require_types(),compile_1=require_compile(),ref_error_1=require_ref_error(),util_1=require_util(),error2={message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`},def={keyword:"discriminator",type:"object",schemaType:"object",error:error2,code(cxt){let{gen,data:data2,schema,parentSchema,it}=cxt,{oneOf}=parentSchema;if(!it.opts.discriminator)throw new Error("discriminator: requires discriminator option");let tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");let valid=gen.let("valid",!1),tag=gen.const("tag",(0,codegen_1._)`${data2}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(!1,{discrError:types_1.DiscrError.Tag,tag,tagName})),cxt.ok(valid);function validateMapping(){let mapping=getMapping();gen.if(!1);for(let tagValue in mapping)gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`),gen.assign(valid,applyTagSchema(mapping[tagValue]));gen.else(),cxt.error(!1,{discrError:types_1.DiscrError.Mapping,tag,tagName}),gen.endIf()}function applyTagSchema(schemaProp){let _valid=gen.name("valid"),schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);return cxt.mergeEvaluated(schCxt,codegen_1.Name),_valid}function getMapping(){var _a;let oneOfMapping={},topRequired=hasRequired(parentSchema),tagRequired=!0;for(let i2=0;i2<oneOf.length;i2++){let sch=oneOf[i2];if(sch?.$ref&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){let ref2=sch.$ref;if(sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref2),sch instanceof compile_1.SchemaEnv&&(sch=sch.schema),sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref2)}let propSch=(_a=sch?.properties)===null||_a===void 0?void 0:_a[tagName];if(typeof propSch!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);tagRequired=tagRequired&&(topRequired||hasRequired(sch)),addMappings(propSch,i2)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required}){return Array.isArray(required)&&required.includes(tagName)}function addMappings(sch,i2){if(sch.const)addMapping(sch.const,i2);else if(sch.enum)for(let tagValue of sch.enum)addMapping(tagValue,i2);else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}function addMapping(tagValue,i2){if(typeof tagValue!="string"||tagValue in oneOfMapping)throw new Error(`discriminator: "${tagName}" values must be unique strings`);oneOfMapping[tagValue]=i2}}}};exports.default=def}});var require_json_schema_draft_07=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports,module){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}});var require_ajv=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;var core_1=require_core(),draft7_1=require_draft7(),discriminator_1=require_discriminator(),draft7MetaSchema=require_json_schema_draft_07(),META_SUPPORT_DATA=["/properties"],META_SCHEMA_ID="http://json-schema.org/draft-07/schema",Ajv3=class extends core_1.default{_addVocabularies(){super._addVocabularies(),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,!1),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv3;module.exports=exports=Ajv3;module.exports.Ajv=Ajv3;Object.defineProperty(exports,"__esModule",{value:!0});exports.default=Ajv3;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})}});import{createHash as createHash4}from"node:crypto";function compilePluginStateSchema(schema){let validate=validators.get(schema);return validate||(validate=new import_ajv.Ajv({strict:!0}).compile(schema),validators.set(schema,validate)),validate}function normalizePluginState(value){if(value===void 0)return;let declaration=JSON.parse(JSON.stringify(value));if(!declaration||declaration.version!==1||!declaration.collections||Array.isArray(declaration.collections)||Object.keys(declaration.collections).length>32||Buffer.byteLength(JSON.stringify(declaration))>128*1024)throw new Error("Invalid stateStorage declaration");for(let[name,collection]of Object.entries(declaration.collections)){if(!/^[a-z][a-z0-9-]{0,63}$/.test(name)||!collection||!["installation","host","browser-session","instance"].includes(collection.scope)||!["persistent","cache","memory"].includes(collection.storage)||!Number.isSafeInteger(collection.schemaVersion)||collection.schemaVersion<1||!collection.schema||typeof collection.schema!="object"||Array.isArray(collection.schema)||collection.schema.$async)throw new Error(`Invalid state collection: ${name}`);if(["browser-session","instance"].includes(collection.scope)&&!["cache","memory"].includes(collection.storage))throw new Error("Document state requires cache or memory storage");if(collection.storage==="memory"&&!["browser-session","instance"].includes(collection.scope))throw new Error("Memory state requires a browser session or instance scope");if(collection.maxEntries!==void 0&&(!Number.isSafeInteger(collection.maxEntries)||collection.maxEntries<1||collection.maxEntries>4096))throw new Error("State maxEntries must be between 1 and 4096");if(collection.maxBytes!==void 0&&(!Number.isSafeInteger(collection.maxBytes)||collection.maxBytes<1||collection.maxBytes>(collection.storage==="memory"?128:16)*1024*1024))throw new Error("State maxBytes exceeds its storage limit");if(collection.ttlMs!==void 0&&(!Number.isSafeInteger(collection.ttlMs)||collection.ttlMs<1||collection.ttlMs>7*864e5))throw new Error("State TTL must be between 1 ms and 7 days");if(collection.storage==="persistent"&&collection.ttlMs!==void 0)throw new Error("Persistent state does not accept TTL");compilePluginStateSchema(collection.schema)}return declaration}function pluginStateSignature(collection){return createHash4("sha256").update(JSON.stringify(collection,(_key,value)=>value&&typeof value=="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0)):value)).digest("hex")}var import_ajv,validators,init_pluginStateDefinition=__esm({"../client/src/plugins/sdk/pluginStateDefinition.ts"(){"use strict";import_ajv=__toESM(require_ajv(),1),validators=new WeakMap}});var pluginModelDefinition_exports={};__export(pluginModelDefinition_exports,{normalizePluginModel:()=>normalizePluginModel,pluginModelCapabilities:()=>pluginModelCapabilities,validatePluginModelResult:()=>validatePluginModelResult});function pluginModelCapabilities(){return{providers:[CODEX_MODEL_CAPABILITY]}}function normalizePluginModel(value){let request=value;if(!request||typeof request!="object"||Array.isArray(request)||typeof request.prompt!="string"||!request.prompt.trim()||Buffer.byteLength(JSON.stringify(request))>256*1024||request.instructions!==void 0&&typeof request.instructions!="string"||request.conversation!==void 0&&(typeof request.conversation!="string"||!/^[a-zA-Z0-9:_-]{1,80}$/.test(request.conversation))||request.model!==void 0&&(typeof request.model!="string"||!request.model.trim()||request.model.length>256)||request.reasoningEffort!==void 0&&!["none","minimal","low","medium","high","xhigh","max"].includes(request.reasoningEffort)||Object.keys(request).some(key2=>!["provider","mode","prompt","instructions","model","reasoningEffort","outputSchema","permissions","conversation"].includes(key2)))throw new Error("Invalid model execution request");let capability=pluginModelCapabilities().providers.find(item=>item.provider===request.provider);if(!capability?.modes.includes(request.mode)||request.mode==="agent"&&!capability.permissions.includes(request.permissions)||request.mode==="generate"&&request.permissions!==void 0)throw Object.assign(new Error("Requested model mode or permissions are unsupported; choose an advertised capability explicitly"),{code:"PLUGIN_MODEL_CAPABILITY_UNSUPPORTED"});if(request.outputSchema!==void 0){if(!capability.structuredOutput||!request.outputSchema||typeof request.outputSchema!="object"||Array.isArray(request.outputSchema)||request.outputSchema.$async||Buffer.byteLength(JSON.stringify(request.outputSchema))>64*1024)throw new Error("Invalid model output schema");compilePluginStateSchema(request.outputSchema)}return JSON.parse(JSON.stringify(request))}function validatePluginModelResult(request,value){let result=value;if(!result||typeof result.text!="string"||result.provider!==request.provider||result.mode!==request.mode)throw new Error("Invalid model execution result");if(request.outputSchema){let output;try{output=JSON.parse(result.text)}catch{throw Object.assign(new Error("Model returned invalid JSON"),{code:"PLUGIN_MODEL_SCHEMA_INVALID"})}if(!compilePluginStateSchema(request.outputSchema)(output))throw Object.assign(new Error("Model result does not match the output schema"),{code:"PLUGIN_MODEL_SCHEMA_INVALID"});return{...result,output}}return result}var init_pluginModelDefinition=__esm({"../client/src/plugins/sdk/pluginModelDefinition.ts"(){"use strict";init_capabilities();init_pluginStateDefinition()}});import{createHash as createHash5}from"node:crypto";function normalizePluginTaskRecovery(value){if(value===void 0)return;let declaration=JSON.parse(JSON.stringify(value));if(!declaration||declaration.version!==1||!declaration.commands||typeof declaration.commands!="object"||Array.isArray(declaration.commands)||Object.keys(declaration.commands).length>32||Buffer.byteLength(JSON.stringify(declaration))>128*1024)throw new Error("Invalid taskRecovery declaration");for(let[command,definition]of Object.entries(declaration.commands)){if(!/^[a-z][a-z0-9-]*$/.test(command)||!definition||!Number.isSafeInteger(definition.checkpointVersion)||definition.checkpointVersion<1||!definition.schema||typeof definition.schema!="object"||Array.isArray(definition.schema)||definition.schema.$async)throw new Error("Invalid task checkpoint definition");if(compilePluginStateSchema(definition.schema),definition.migrateFrom!==void 0){if(!Array.isArray(definition.migrateFrom)||definition.migrateFrom.length<1||definition.migrateFrom.length>16)throw new Error("Invalid checkpoint migration sources");let versions=new Set;for(let source of definition.migrateFrom){if(!source||!Number.isSafeInteger(source.version)||source.version<1||source.version>=definition.checkpointVersion||versions.has(source.version)||!source.schema||typeof source.schema!="object"||Array.isArray(source.schema)||source.schema.$async)throw new Error("Checkpoint migrations require distinct older versions and schemas");compilePluginStateSchema(source.schema),versions.add(source.version)}}}return declaration}function pluginRecoverySignature(value){return createHash5("sha256").update(JSON.stringify(value,(_key,item)=>item&&typeof item=="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a<b?-1:a>b?1:0)):item)).digest("hex")}var init_pluginRecoveryDefinition=__esm({"../client/src/plugins/sdk/pluginRecoveryDefinition.ts"(){"use strict";init_pluginStateDefinition()}});import{randomUUID as randomUUID3}from"node:crypto";import{linkSync as linkSync2,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync as rmSync4,writeFileSync as writeFileSync3}from"node:fs";import{join as join7}from"node:path";function localPluginExecutionHost(){let directory=pluginDirectory(),hostId=hostIds.get(directory);if(!hostId){mkdirSync3(directory,{recursive:!0,mode:448});let file=join7(directory,".execution-host-id"),proposed=randomUUID3(),temporary=`${file}.${proposed}.tmp`;try{writeFileSync3(temporary,proposed,{flag:"wx",mode:384}),linkSync2(temporary,file)}catch(error2){if(error2.code!=="EEXIST")throw error2}finally{rmSync4(temporary,{force:!0})}if(hostId=readFileSync6(file,"utf8").trim(),!UUID.test(hostId))throw new Error("Invalid plugin execution host identity");hostIds.set(directory,hostId)}return Object.freeze({hostId,epoch})}function createPluginInvocationIdentity(plugin,source,parent){return Object.freeze({invocationId:randomUUID3(),host:parent?.host??localPluginExecutionHost(),plugin,source,...parent?{parentInvocationId:parent.invocationId}:{}})}var epoch,hostIds,UUID,init_pluginExecution2=__esm({"../client/src/plugins/runtime/pluginExecution.ts"(){"use strict";init_pluginRegistry();epoch=randomUUID3(),hostIds=new Map,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i}});import{createRequire}from"node:module";import{fileURLToPath}from"node:url";var require2,CLIENT_VERSION,PLUGIN_TASK_HOST_PATH,PLUGIN_WORKER_PATH,PLUGIN_MODEL_SESSION_WORKER_PATH,init_runtimePaths=__esm({"../client/src/runtimePaths.ts"(){"use strict";require2=createRequire(import.meta.url),CLIENT_VERSION=require2("../package.json").version,PLUGIN_TASK_HOST_PATH=fileURLToPath(new URL("./plugin-task-host.js",import.meta.url)),PLUGIN_WORKER_PATH=fileURLToPath(new URL("./plugin-worker.js",import.meta.url)),PLUGIN_MODEL_SESSION_WORKER_PATH=fileURLToPath(new URL("./pluginModelSessionWorker.js",import.meta.url))}});function serializePluginExecutionError(error2){let value=error2,metadata=Object.fromEntries(Object.entries(value&&typeof value=="object"?value:{}).filter(([key2,field])=>!["__proto__","prototype","constructor","message","stack","code","details"].includes(key2)&&(field===null||["string","number","boolean"].includes(typeof field)))),serialized={message:typeof value?.message=="string"?value.message:String(error2),...typeof value?.code=="string"?{code:value.code}:{},...value?.details&&typeof value.details=="object"&&!Array.isArray(value.details)?{details:value.details}:{},...Object.keys(metadata).length?{metadata}:{}};try{if(Buffer.byteLength(JSON.stringify(serialized))<=64*1024)return serialized}catch{}return{message:Buffer.from(serialized.message).subarray(0,8192).toString("utf8"),...serialized.code?{code:serialized.code.slice(0,256)}:{},details:{diagnosticTruncated:!0},metadata:Object.fromEntries(Object.entries(metadata).slice(0,32).map(([key2,field])=>[key2.slice(0,128),typeof field=="string"?field.slice(0,512):field]))}}function pluginExecutionError(value){return Object.assign(new Error(value.message),{...Object.fromEntries(Object.entries(value.metadata??{}).filter(([key2])=>!["__proto__","prototype","constructor","message","stack","code","details"].includes(key2))),...value.code?{code:value.code}:{},...value.details?{details:value.details}:{}})}var init_pluginExecutorProtocol=__esm({"../client/src/plugins/runtime/pluginExecutorProtocol.ts"(){"use strict"}});import{execFile}from"node:child_process";async function stopPluginProcessTree(pid){if(!Number.isSafeInteger(pid)||pid<1)throw new Error("Invalid plugin process group");if(process.platform==="win32")return new Promise((resolve7,reject)=>{execFile("taskkill",["/PID",String(pid),"/T","/F"],{windowsHide:!0,timeout:5e3},error2=>{error2?reject(error2):resolve7()})});try{process.kill(-pid,"SIGKILL")}catch(error2){if(error2.code==="ESRCH")return;throw error2}let deadline=Date.now()+5e3;for(;isProcessGroupAlive(pid);){if(Date.now()>=deadline)throw new Error("Unable to confirm plugin process group stopped");await new Promise(resolve7=>setTimeout(resolve7,20))}}var init_pluginProcessTree=__esm({"../client/src/plugins/runtime/pluginProcessTree.ts"(){"use strict";init_dist()}});import{fork}from"node:child_process";async function executeRegisteredPlugin(plugin,invocation,context,options={},dependencies={}){let{signal,onProgress,source,access="public",executionTimeoutMs,cancellationGraceMs=1e3,workerPath,cwd,environment,describe,model,recovery,migration,expectedRecovery,onExecutorStarted,onExecutorStopped,onDiagnostic,...invokeOptions}=options;for(let[name,value]of[["executionTimeoutMs",executionTimeoutMs],["cancellationGraceMs",cancellationGraceMs]])if(value!==void 0&&(!Number.isSafeInteger(value)||value<1||value>2147483647))throw new Error(`${name} must be a positive integer within the timer range`);signal?.throwIfAborted();let registration=dependencies.registration??findPluginRegistration(plugin);if(!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${plugin}`);let identity=context.invocation??createPluginInvocationIdentity(plugin,source??context.source??"sdk",context.parentInvocation),entryVersion=pluginFileVersion(registration.entry);return new Promise((resolve7,reject)=>{let child=fork(workerPath??PLUGIN_WORKER_PATH,[],{stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced",execArgv:[],detached:process.platform!=="win32",...cwd?{cwd}:{},...environment?{env:environment}:{}}),stderr="",outcome,stopping,cleanupError,treeStopRequested=!1,treeCleanup=Promise.resolve(),exited=!1,graceTimer,deadlineTimer,pendingActions=new Map;child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr=`${stderr}${chunk}`.slice(-65536)});let send=message=>{if(!(!child.connected||exited))try{child.send(message,error2=>{error2&&!exited&&stop(error2)})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}},kill=()=>{if(!child.pid||exited||treeStopRequested)return;treeStopRequested=!0;let pid=child.pid;treeCleanup=Promise.resolve().then(()=>(dependencies.stopProcessTree??stopPluginProcessTree)(pid)).catch(()=>{cleanupError=Object.assign(new Error("Unable to confirm plugin process-tree cleanup"),{code:"PLUGIN_EXECUTOR_CLEANUP_FAILED",details:{executionStopped:!1}}),child.kill("SIGKILL")})},stop=error2=>{stopping||outcome||exited||(stopping=error2,send({type:"cancel",error:serializePluginExecutionError(error2)}),graceTimer=setTimeout(kill,cancellationGraceMs))},abort=()=>stop(Object.assign(new Error("Plugin execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"}));signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted&&abort(),executionTimeoutMs!==void 0&&(deadlineTimer=setTimeout(()=>stop(Object.assign(new Error("Plugin execution deadline exceeded"),{code:"PLUGIN_EXECUTION_DEADLINE"})),executionTimeoutMs)),child.on("message",raw=>{if(!(exited||!raw||typeof raw!="object")){if(raw.type==="result"||raw.type==="error"){if(!outcome&&!stopping)try{outcome=raw.type==="result"?{value:JSON.parse(raw.json).value}:{error:pluginExecutionError(raw.error)},raw.type==="result"&&pendingActions.size&&(outcome={error:Object.assign(new Error("Plugin returned with pending host calls"),{code:"PLUGIN_PENDING_HOST_CALLS",details:{pendingActions:[...pendingActions.values()]}})})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}kill();return}if(!(stopping||outcome))if(raw.type==="diagnostic"&&model)try{onDiagnostic?.(raw.metadata)}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}else if(raw.type==="progress")try{onProgress?.(raw.progress)}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}else raw.type==="invoke"&&(pendingActions.set(raw.id,raw.action),Promise.resolve().then(()=>{if(stopping||exited)throw stopping??new Error("Plugin execution ended");let options2={...invokeOptions,...raw.options};return raw.stream?context.invoke(raw.action,raw.payload,options2,progress=>{!stopping&&!outcome&&pendingActions.has(raw.id)&&send({type:"invoke-progress",id:raw.id,progress})}):context.invoke(raw.action,raw.payload,options2)}).then(result=>send({type:"response",id:raw.id,result}),error2=>send({type:"response",id:raw.id,error:serializePluginExecutionError(error2)})).finally(()=>pendingActions.delete(raw.id)))}});let cleanup=()=>{exited=!0,signal?.removeEventListener("abort",abort),graceTimer&&clearTimeout(graceTimer),deadlineTimer&&clearTimeout(deadlineTimer)};child.once("error",error2=>{cleanup(),reject(error2)}),child.once("exit",()=>{kill(),child.stderr?.destroy()}),child.once("close",(code,exitSignal)=>{cleanup(),treeCleanup.then(()=>{if(!cleanupError&&treeStopRequested)try{onExecutorStopped?.()}catch(error2){reject(error2);return}cleanupError?reject(cleanupError):stopping?(Object.assign(stopping,{details:{pendingActions:[...pendingActions.values()],executionStopped:!0}}),reject(stopping)):outcome?.error?reject(outcome.error):outcome?resolve7(outcome.value):reject(Object.assign(new Error(stderr.trim()||`Plugin executor exited (${code??exitSignal})`),{code:"PLUGIN_EXECUTOR_EXITED"}))})});try{child.pid&&onExecutorStarted?.({pid:child.pid,processIdentity:processIdentity(child.pid)}),send({type:"start",plugin,invocation,options:invokeOptions,identity,entry:registration.entry,entryVersion,access,describe,model,recovery,migration,expectedRecovery,...dependencies.registration?{registration}:{}})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}})}var init_pluginExecutor=__esm({"../client/src/plugins/runtime/pluginExecutor.ts"(){"use strict";init_runtimePaths();init_pluginRegistry();init_pluginSource();init_pluginExecution2();init_pluginExecutorProtocol();init_pluginProcessTree();init_dist()}});function isInAstralSet(code,set){for(var pos=65536,i2=0;i2<set.length;i2+=2){if(pos+=set[i2],pos>code)return!1;if(pos+=set[i2+1],pos>=code)return!0}return!1}function isIdentifierStart(code,astral){return code<65?code===36:code<91?!0:code<97?code===95:code<123?!0:code<=65535?code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code)):astral===!1?!1:isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){return code<48?code===36:code<58?!0:code<65?!1:code<91?!0:code<97?code===95:code<123?!0:code<=65535?code>=170&&nonASCIIidentifier.test(String.fromCharCode(code)):astral===!1?!1:isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}function binop(name,prec){return new TokenType(name,{beforeExpr:!0,binop:prec})}function kw(name,options){return options===void 0&&(options={}),options.keyword=name,keywords[name]=new TokenType(name,options)}function isNewLine(code){return code===10||code===13||code===8232||code===8233}function nextLineBreak(code,from,end){end===void 0&&(end=code.length);for(var i2=from;i2<end;i2++){var next=code.charCodeAt(i2);if(isNewLine(next))return i2<end-1&&next===13&&code.charCodeAt(i2+1)===10?i2+2:i2+1}return-1}function wordsRegexp(words){return regexpCache[words]||(regexpCache[words]=new RegExp("^(?:"+words.replace(/ /g,"|")+")$"))}function codePointToString(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode((code>>10)+55296,(code&1023)+56320))}function getLineInfo(input,offset2){for(var line=1,cur=0;;){var nextBreak=nextLineBreak(input,cur,offset2);if(nextBreak<0)return new Position(line,offset2-cur);++line,cur=nextBreak}}function getOptions(opts){var options={};for(var opt in defaultOptions)options[opt]=opts&&hasOwn(opts,opt)?opts[opt]:defaultOptions[opt];if(options.ecmaVersion==="latest"?options.ecmaVersion=1e8:options.ecmaVersion==null?(!warnedAboutEcmaVersion&&typeof console=="object"&&console.warn&&(warnedAboutEcmaVersion=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
616
- Defaulting to 2020, but this will stop working in the future.`)),options.ecmaVersion=11):options.ecmaVersion>=2015&&(options.ecmaVersion-=2009),options.allowReserved==null&&(options.allowReserved=options.ecmaVersion<5),(!opts||opts.allowHashBang==null)&&(options.allowHashBang=options.ecmaVersion>=14),isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)&&(options.onComment=pushComment(options,options.onComment)),options.sourceType==="commonjs"&&options.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return options}function pushComment(options,array){return function(block,text3,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text3,start,end};options.locations&&(comment.loc=new SourceLocation(this,startLoc,endLoc)),options.ranges&&(comment.range=[start,end]),array.push(comment)}}function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}function keywordOpAt(parser,pos){for(var end=pos+1,stop=Math.min(parser.input.length,pos+11);end<stop;){var ch=parser.fullCharCodeAt(end);if(!isIdentifierChar(ch,!0))break;end+=ch<=65535?1:2}return end===pos+2&&parser.input.slice(pos,end)==="in"||end===pos+10&&parser.input.slice(pos,end)==="instanceof"}function isPrivateNameConflicted(privateNameMap,element){var name=element.key.name,curr=privateNameMap[name],next="true";return element.type==="MethodDefinition"&&(element.kind==="get"||element.kind==="set")&&(next=(element.static?"s":"i")+element.kind),curr==="iget"&&next==="iset"||curr==="iset"&&next==="iget"||curr==="sget"&&next==="sset"||curr==="sset"&&next==="sget"?(privateNameMap[name]="true",!1):curr?!0:(privateNameMap[name]=next,!1)}function checkKeyName(node,name){var computed=node.computed,key2=node.key;return!computed&&(key2.type==="Identifier"&&key2.name===name||key2.type==="Literal"&&key2.value===name)}function isLocalVariableAccess(node){return node.type==="Identifier"||node.type==="ParenthesizedExpression"&&isLocalVariableAccess(node.expression)}function isPrivateFieldAccess(node){return node.type==="MemberExpression"&&node.property.type==="PrivateIdentifier"||node.type==="ChainExpression"&&isPrivateFieldAccess(node.expression)||node.type==="ParenthesizedExpression"&&isPrivateFieldAccess(node.expression)}function finishNodeAt(node,type,pos,loc){return node.type=type,node.end=pos,this.options.locations&&(node.loc.end=loc),this.options.ranges&&(node.range[1]=pos),node}function buildUnicodeData(ecmaVersion2){var d=data[ecmaVersion2]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion2]+" "+unicodeGeneralCategoryValues),binaryOfStrings:wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion2]),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion2])}};d.nonBinary.Script_Extensions=d.nonBinary.Script,d.nonBinary.gc=d.nonBinary.General_Category,d.nonBinary.sc=d.nonBinary.Script,d.nonBinary.scx=d.nonBinary.Script_Extensions}function hasProp(obj){for(var _ in obj)return!0;return!1}function isRegularExpressionModifier(ch){return ch===105||ch===109||ch===115}function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,!0)||ch===36||ch===95}function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,!0)||ch===36||ch===95||ch===8204||ch===8205}function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}function isValidUnicode(ch){return ch>=0&&ch<=1114111}function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}function isClassSetReservedDoublePunctuatorCharacter(ch){return ch===33||ch>=35&&ch<=38||ch>=42&&ch<=44||ch===46||ch>=58&&ch<=64||ch===94||ch===96||ch===126}function isClassSetSyntaxCharacter(ch){return ch===40||ch===41||ch===45||ch===47||ch>=91&&ch<=93||ch>=123&&ch<=125}function isClassSetReservedPunctuator(ch){return ch===33||ch===35||ch===37||ch===38||ch===44||ch===45||ch>=58&&ch<=62||ch===64||ch===96||ch===126}function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){return ch>=65&&ch<=70?10+(ch-65):ch>=97&&ch<=102?10+(ch-97):ch-48}function isOctalDigit(ch){return ch>=48&&ch<=55}function stringToNumber(str,isLegacyOctalNumericLiteral){return isLegacyOctalNumericLiteral?parseInt(str,8):parseFloat(str.replace(/_/g,""))}function stringToBigInt(str){return typeof BigInt!="function"?null:BigInt(str.replace(/_/g,""))}function parse3(input,options){return Parser.parse(input,options)}var astralIdentifierCodes,astralIdentifierStartCodes,nonASCIIidentifierChars,nonASCIIidentifierStartChars,reservedWords,ecma5AndLessKeywords,keywords$1,keywordRelationalOperator,nonASCIIidentifierStart,nonASCIIidentifier,TokenType,beforeExpr,startsExpr,keywords,types$1,lineBreak,lineBreakG,nonASCIIwhitespace,skipWhiteSpace,ref,hasOwnProperty,toString,hasOwn,isArray,regexpCache,loneSurrogate,Position,SourceLocation,defaultOptions,warnedAboutEcmaVersion,SCOPE_TOP,SCOPE_FUNCTION,SCOPE_ASYNC,SCOPE_GENERATOR,SCOPE_ARROW,SCOPE_SIMPLE_CATCH,SCOPE_SUPER,SCOPE_DIRECT_SUPER,SCOPE_CLASS_STATIC_BLOCK,SCOPE_CLASS_FIELD_INIT,SCOPE_SWITCH,SCOPE_VAR,BIND_NONE,BIND_VAR,BIND_LEXICAL,BIND_FUNCTION,BIND_SIMPLE_CATCH,BIND_OUTSIDE,Parser,prototypeAccessors,pp$9,literal,DestructuringErrors,pp$8,loopLabel,switchLabel,empty$1,FUNC_STATEMENT,FUNC_HANGING_STATEMENT,FUNC_NULLABLE_ID,pp$7,TokContext,types,pp$6,pp$5,empty,pp$4,pp$3,Scope,Node2,pp$2,scriptValuesAddedInUnicode,ecma9BinaryProperties,ecma10BinaryProperties,ecma11BinaryProperties,ecma12BinaryProperties,ecma13BinaryProperties,ecma14BinaryProperties,unicodeBinaryProperties,ecma14BinaryPropertiesOfStrings,unicodeBinaryPropertiesOfStrings,unicodeGeneralCategoryValues,ecma9ScriptValues,ecma10ScriptValues,ecma11ScriptValues,ecma12ScriptValues,ecma13ScriptValues,ecma14ScriptValues,unicodeScriptValues,data,ecmaVersion,i,list,pp$1,BranchID,RegExpValidationState,CharSetNone,CharSetOk,CharSetString,Token,pp,INVALID_TEMPLATE_ESCAPE_ERROR,version,init_acorn=__esm({"../../node_modules/.pnpm/acorn@8.19.0/node_modules/acorn/dist/acorn.mjs"(){astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,31,4,33,15,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,7,0,259,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,481,1,61,4,4,5,9,7,3,6,31,3,149,2,12,2,9,1,3,0,33,1,1357,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,13,65,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,18,21,18,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,18,0,182,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,22,0,239,18,16,0,2,12,2,33,125,0,80,921,103,111,6,206,13,310,2314,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7386,37,33,96,114,14,913,15,50,7710,3,2,6,2,1,2,296,10,0,30,2,3,0,15,4,8,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,340,2,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,129,15,6,55,50,49,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4382,2,5773,3,7472,16,621,2467,541,1507,4938,6,8489,39815,11327],nonASCIIidentifierChars="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄ-׉ؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୓-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-᫰ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・",nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆ՘ՙՠ-ֈ֋֌א-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-࢏ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚ౜ౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ೜-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿ₏-₟ℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-꟝꟢꟱-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩ꭬꭭ꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",keywords$1={5:ecma5AndLessKeywords,"5module":ecma5AndLessKeywords+" export import",6:ecma5AndLessKeywords+" const class extends export import super"},keywordRelationalOperator=/^in(stanceof)?$/,nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]"),nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");TokenType=function(label,conf){conf===void 0&&(conf={}),this.label=label,this.keyword=conf.keyword,this.beforeExpr=!!conf.beforeExpr,this.startsExpr=!!conf.startsExpr,this.isLoop=!!conf.isLoop,this.isAssign=!!conf.isAssign,this.prefix=!!conf.prefix,this.postfix=!!conf.postfix,this.binop=conf.binop||null,this.updateContext=null};beforeExpr={beforeExpr:!0},startsExpr={startsExpr:!0},keywords={};types$1={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),privateId:new TokenType("privateId",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:!0,startsExpr:!0}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:!0,startsExpr:!0}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),questionDot:new TokenType("?."),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:!0,startsExpr:!0}),eq:new TokenType("=",{beforeExpr:!0,isAssign:!0}),assign:new TokenType("_=",{beforeExpr:!0,isAssign:!0}),incDec:new TokenType("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new TokenType("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("</>/<=/>=",7),bitShift:binop("<</>>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:!0}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:!0,beforeExpr:!0}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:!0}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:!0}),_with:kw("with"),_new:kw("new",{beforeExpr:!0,startsExpr:!0}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:!0,binop:7}),_instanceof:kw("instanceof",{beforeExpr:!0,binop:7}),_typeof:kw("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:kw("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:kw("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},lineBreak=/\r\n?|\n|\u2028|\u2029/,lineBreakG=new RegExp(lineBreak.source,"g");nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,ref=Object.prototype,hasOwnProperty=ref.hasOwnProperty,toString=ref.toString,hasOwn=Object.hasOwn||(function(obj,propName){return hasOwnProperty.call(obj,propName)}),isArray=Array.isArray||(function(obj){return toString.call(obj)==="[object Array]"}),regexpCache=Object.create(null);loneSurrogate=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Position=function(line,col){this.line=line,this.column=col};Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};SourceLocation=function(p,start,end){this.start=start,this.end=end,p.sourceFile!==null&&(this.source=p.sourceFile)};defaultOptions={ecmaVersion:null,sourceType:"script",strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,startLocation:null,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},warnedAboutEcmaVersion=!1;SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128,SCOPE_CLASS_STATIC_BLOCK=256,SCOPE_CLASS_FIELD_INIT=512,SCOPE_SWITCH=1024,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION|SCOPE_CLASS_STATIC_BLOCK;BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5,Parser=function(options,input,startPos){this.options=options=getOptions(options),this.sourceFile=options.sourceFile,this.keywords=wordsRegexp(keywords$1[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";options.allowReserved!==!0&&(reserved=reservedWords[options.ecmaVersion>=6?6:options.ecmaVersion===5?5:3],options.sourceType==="module"&&(reserved+=" await")),this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict),this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind),this.input=String(input),this.containsEsc=!1,this.pos=startPos||0,this.curLine=1,options.startLocation?(this.lineStart=this.pos-options.startLocation.column,this.curLine=options.startLocation.line):startPos?(this.lineStart=this.input.lastIndexOf(`
617
- `,startPos-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length)):this.lineStart=0,this.type=types$1.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=options.sourceType==="module",this.strict=this.inModule||options.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType==="commonjs"?SCOPE_FUNCTION:SCOPE_TOP),this.regexpState=null,this.privateNameStack=[]},prototypeAccessors={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};Parser.prototype.parse=function(){var this$1$1=this,node=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return this$1$1.parseTopLevel(node)})};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.canAwait.get=function(){for(var i2=this.scopeStack.length-1;i2>=0;i2--){var ref2=this.scopeStack[i2],flags=ref2.flags;if(flags&(SCOPE_CLASS_STATIC_BLOCK|SCOPE_CLASS_FIELD_INIT))return!1;if(flags&SCOPE_FUNCTION)return(flags&SCOPE_ASYNC)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};prototypeAccessors.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&SCOPE_TOP)};prototypeAccessors.allowSuper.get=function(){var ref2=this.currentThisScope(),flags=ref2.flags;return(flags&SCOPE_SUPER)>0||this.options.allowSuperOutsideMethod};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};prototypeAccessors.allowNewDotTarget.get=function(){for(var i2=this.scopeStack.length-1;i2>=0;i2--){var ref2=this.scopeStack[i2],flags=ref2.flags;if(flags&(SCOPE_CLASS_STATIC_BLOCK|SCOPE_CLASS_FIELD_INIT)||flags&SCOPE_FUNCTION&&!(flags&SCOPE_ARROW))return!0}return!1};prototypeAccessors.allowUsing.get=function(){var ref2=this.currentScope(),flags=ref2.flags;return!(flags&SCOPE_SWITCH||!this.inModule&&flags&SCOPE_TOP)};prototypeAccessors.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&SCOPE_CLASS_STATIC_BLOCK)>0};Parser.extend=function(){for(var plugins=[],len=arguments.length;len--;)plugins[len]=arguments[len];for(var cls=this,i2=0;i2<plugins.length;i2++)cls=plugins[i2](cls);return cls};Parser.parse=function(input,options){return new this(options,input).parse()};Parser.parseExpressionAt=function(input,pos,options){var parser=new this(options,input,pos);return parser.nextToken(),parser.parseExpression()};Parser.tokenizer=function(input,options){return new this(options,input)};Object.defineProperties(Parser.prototype,prototypeAccessors);pp$9=Parser.prototype,literal=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;pp$9.strictDirective=function(start){if(this.options.ecmaVersion<5)return!1;for(;;){skipWhiteSpace.lastIndex=start,start+=skipWhiteSpace.exec(this.input)[0].length;var match=literal.exec(this.input.slice(start));if(!match)return!1;if((match[1]||match[2])==="use strict"){skipWhiteSpace.lastIndex=start+match[0].length;var spaceAfter=skipWhiteSpace.exec(this.input),end=spaceAfter.index+spaceAfter[0].length,next=this.input.charAt(end);return next===";"||next==="}"||lineBreak.test(spaceAfter[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(next)||next==="!"&&this.input.charAt(end+1)==="="||next==="i"&&keywordOpAt(this,end))}start+=match[0].length,skipWhiteSpace.lastIndex=start,start+=skipWhiteSpace.exec(this.input)[0].length,this.input[start]===";"&&start++}};pp$9.eat=function(type){return this.type===type?(this.next(),!0):!1};pp$9.isContextual=function(name){return this.type===types$1.name&&this.value===name&&!this.containsEsc};pp$9.eatContextual=function(name){return this.isContextual(name)?(this.next(),!0):!1};pp$9.catchStackOverflow=function(f){try{return f()}catch(e){if(e instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message)||/\btoo much recursion\b/i.test(e.message)))this.raise(this.start,"Not enough stack space to parse input");else throw e}};pp$9.expectContextual=function(name){this.eatContextual(name)||this.unexpected()};pp$9.canInsertSemicolon=function(){return this.type===types$1.eof||this.type===types$1.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$9.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};pp$9.semicolon=function(){!this.eat(types$1.semi)&&!this.insertSemicolon()&&this.unexpected()};pp$9.afterTrailingComma=function(tokType,notNext){if(this.type===tokType)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),notNext||this.next(),!0};pp$9.expect=function(type){this.eat(type)||this.unexpected()};pp$9.unexpected=function(pos){this.raise(pos??this.start,"Unexpected token")};DestructuringErrors=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};pp$9.checkPatternErrors=function(refDestructuringErrors,isAssign){if(refDestructuringErrors){refDestructuringErrors.trailingComma>-1&&this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element");var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;parens>-1&&this.raiseRecoverable(parens,isAssign?"Assigning to rvalue":"Parenthesized pattern")}};pp$9.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors)return!1;var shorthandAssign=refDestructuringErrors.shorthandAssign,doubleProto=refDestructuringErrors.doubleProto;if(!andThrow)return shorthandAssign>=0||doubleProto>=0;shorthandAssign>=0&&this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns"),doubleProto>=0&&this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")};pp$9.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")};pp$9.isSimpleAssignTarget=function(expr){return expr.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(expr.expression):expr.type==="Identifier"||expr.type==="MemberExpression"};pp$8=Parser.prototype;pp$8.parseTopLevel=function(node){var exports$1=Object.create(null);for(node.body||(node.body=[]);this.type!==types$1.eof;){var stmt=this.parseStatement(null,!0,exports$1);node.body.push(stmt)}if(this.inModule)for(var i2=0,list2=Object.keys(this.undefinedExports);i2<list2.length;i2+=1){var name=list2[i2];this.raiseRecoverable(this.undefinedExports[name].start,"Export '"+name+"' is not defined")}return this.adaptDirectivePrologue(node.body),this.next(),node.sourceType=this.options.sourceType==="commonjs"?"script":this.options.sourceType,this.finishNode(node,"Program")};loopLabel={kind:"loop"},switchLabel={kind:"switch"};pp$8.isLet=function(context){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input),next=this.pos+skip[0].length,nextCh=this.fullCharCodeAt(next);if(nextCh===91||nextCh===92)return!0;if(context)return!1;if(nextCh===123)return!0;if(isIdentifierStart(nextCh)){var start=next;do next+=nextCh<=65535?1:2;while(isIdentifierChar(nextCh=this.fullCharCodeAt(next)));if(nextCh===92)return!0;var ident=this.input.slice(start,next);if(!keywordRelationalOperator.test(ident))return!0}return!1};pp$8.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input),next=this.pos+skip[0].length,after;return!lineBreak.test(this.input.slice(this.pos,next))&&this.input.slice(next,next+8)==="function"&&(next+8===this.input.length||!(isIdentifierChar(after=this.fullCharCodeAt(next+8))||after===92))};pp$8.isUsingKeyword=function(isAwaitUsing,isFor){if(this.options.ecmaVersion<17||!this.isContextual(isAwaitUsing?"await":"using"))return!1;skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input),next=this.pos+skip[0].length;if(lineBreak.test(this.input.slice(this.pos,next)))return!1;if(isAwaitUsing){var usingEndPos=next+5,after;if(this.input.slice(next,usingEndPos)!=="using"||usingEndPos===this.input.length||isIdentifierChar(after=this.fullCharCodeAt(usingEndPos))||after===92)return!1;skipWhiteSpace.lastIndex=usingEndPos;var skipAfterUsing=skipWhiteSpace.exec(this.input);if(next=usingEndPos+skipAfterUsing[0].length,skipAfterUsing&&lineBreak.test(this.input.slice(usingEndPos,next)))return!1}var ch=this.fullCharCodeAt(next);if(!isIdentifierStart(ch)&&ch!==92)return!1;var idStart=next;do next+=ch<=65535?1:2;while(isIdentifierChar(ch=this.fullCharCodeAt(next)));if(ch===92)return!0;var id=this.input.slice(idStart,next);if(keywordRelationalOperator.test(id))return!1;if(isFor&&!isAwaitUsing&&id==="of"){skipWhiteSpace.lastIndex=next;var skipAfterOf=skipWhiteSpace.exec(this.input);if(next=next+skipAfterOf[0].length,this.input.charCodeAt(next)!==61||(ch=this.input.charCodeAt(next+1))===61||ch===62)return!1}return!0};pp$8.isAwaitUsing=function(isFor){return this.isUsingKeyword(!0,isFor)};pp$8.isUsing=function(isFor){return this.isUsingKeyword(!1,isFor)};pp$8.parseStatement=function(context,topLevel,exports$1){var starttype=this.type,node=this.startNode(),kind;switch(this.isLet(context)&&(starttype=types$1._var,kind="let"),starttype){case types$1._break:case types$1._continue:return this.parseBreakContinueStatement(node,starttype.keyword);case types$1._debugger:return this.parseDebuggerStatement(node);case types$1._do:return this.parseDoStatement(node);case types$1._for:return this.parseForStatement(node);case types$1._function:return context&&(this.strict||context!=="if"&&context!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(node,!1,!context);case types$1._class:return context&&this.unexpected(),this.parseClass(node,!0);case types$1._if:return this.parseIfStatement(node);case types$1._return:return this.parseReturnStatement(node);case types$1._switch:return this.parseSwitchStatement(node);case types$1._throw:return this.parseThrowStatement(node);case types$1._try:return this.parseTryStatement(node);case types$1._const:case types$1._var:return kind=kind||this.value,context&&kind!=="var"&&this.unexpected(),this.parseVarStatement(node,kind);case types$1._while:return this.parseWhileStatement(node);case types$1._with:return this.parseWithStatement(node);case types$1.braceL:return this.parseBlock(!0,node);case types$1.semi:return this.parseEmptyStatement(node);case types$1._export:case types$1._import:if(this.options.ecmaVersion>10&&starttype===types$1._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input),next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40||nextCh===46)return this.parseExpressionStatement(node,this.parseExpression())}return this.options.allowImportExportEverywhere||(topLevel||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),starttype===types$1._import?this.parseImport(node):this.parseExport(node,exports$1);default:if(this.isAsyncFunction())return context&&this.unexpected(),this.next(),this.parseFunctionStatement(node,!0,!context);var usingKind=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(usingKind)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),context&&this.raise(this.start,"Using declaration is not allowed in single-statement positions"),usingKind==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(node,!1,usingKind),this.semicolon(),this.finishNode(node,"VariableDeclaration");var maybeName=this.value,expr=this.parseExpression();return starttype===types$1.name&&expr.type==="Identifier"&&this.eat(types$1.colon)?this.parseLabeledStatement(node,maybeName,expr,context):this.parseExpressionStatement(node,expr)}};pp$8.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next(),this.eat(types$1.semi)||this.insertSemicolon()?node.label=null:this.type!==types$1.name?this.unexpected():(node.label=this.parseIdent(),this.semicolon());for(var i2=0;i2<this.labels.length;++i2){var lab=this.labels[i2];if((node.label==null||lab.name===node.label.name)&&(lab.kind!=null&&(isBreak||lab.kind==="loop")||node.label&&isBreak))break}return i2===this.labels.length&&this.raise(node.start,"Unsyntactic "+keyword),this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement")};pp$8.parseDebuggerStatement=function(node){return this.next(),this.semicolon(),this.finishNode(node,"DebuggerStatement")};pp$8.parseDoStatement=function(node){return this.next(),this.labels.push(loopLabel),node.body=this.parseStatement("do"),this.labels.pop(),this.expect(types$1._while),node.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(types$1.semi):this.semicolon(),this.finishNode(node,"DoWhileStatement")};pp$8.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(loopLabel),this.enterScope(0),this.expect(types$1.parenL),this.type===types$1.semi)return awaitAt>-1&&this.unexpected(awaitAt),this.parseFor(node,null);var isLet=this.isLet();if(this.type===types$1._var||this.type===types$1._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;return this.next(),this.parseVar(init$1,!0,kind),this.finishNode(init$1,"VariableDeclaration"),this.parseForAfterInit(node,init$1,awaitAt)}var startsWithLet=this.isContextual("let"),isForOf=!1,usingKind=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(usingKind){var init$2=this.startNode();return this.next(),usingKind==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(init$2,!0,usingKind),this.finishNode(init$2,"VariableDeclaration"),this.parseForAfterInit(node,init$2,awaitAt)}var containsEsc=this.containsEsc,refDestructuringErrors=new DestructuringErrors,initPos=this.start,init=awaitAt>-1?this.parseExprSubscripts(refDestructuringErrors,"await"):this.parseExpression(!0,refDestructuringErrors);return this.type===types$1._in||(isForOf=this.options.ecmaVersion>=6&&this.isContextual("of"))?(awaitAt>-1?(this.type===types$1._in&&this.unexpected(awaitAt),node.await=!0):isForOf&&this.options.ecmaVersion>=8&&(init.start===initPos&&!containsEsc&&init.type==="Identifier"&&init.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(node.await=!1)),startsWithLet&&isForOf&&this.raise(init.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(init,!1,refDestructuringErrors),this.checkLValPattern(init),this.parseForIn(node,init)):(this.checkExpressionErrors(refDestructuringErrors,!0),awaitAt>-1&&this.unexpected(awaitAt),this.parseFor(node,init))};pp$8.parseForAfterInit=function(node,init,awaitAt){return(this.type===types$1._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init.declarations.length===1?(this.type===types$1._in?((init.kind==="using"||init.kind==="await using")&&!init.declarations[0].init&&this.raise(this.start,"Using declaration is not allowed in for-in loops"),this.options.ecmaVersion>=9&&awaitAt>-1&&this.unexpected(awaitAt)):this.options.ecmaVersion>=9&&(node.await=awaitAt>-1),this.parseForIn(node,init)):(awaitAt>-1&&this.unexpected(awaitAt),this.parseFor(node,init))};pp$8.parseFunctionStatement=function(node,isAsync,declarationPosition){return this.next(),this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),!1,isAsync)};pp$8.parseIfStatement=function(node){return this.next(),node.test=this.parseParenExpression(),node.consequent=this.parseStatement("if"),node.alternate=this.eat(types$1._else)?this.parseStatement("if"):null,this.finishNode(node,"IfStatement")};pp$8.parseReturnStatement=function(node){return this.allowReturn||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(types$1.semi)||this.insertSemicolon()?node.argument=null:(node.argument=this.parseExpression(),this.semicolon()),this.finishNode(node,"ReturnStatement")};pp$8.parseSwitchStatement=function(node){this.next(),node.discriminant=this.parseParenExpression(),node.cases=[],this.expect(types$1.braceL),this.labels.push(switchLabel),this.enterScope(SCOPE_SWITCH);for(var cur,sawDefault=!1;this.type!==types$1.braceR;)if(this.type===types$1._case||this.type===types$1._default){var isCase=this.type===types$1._case;cur&&this.finishNode(cur,"SwitchCase"),node.cases.push(cur=this.startNode()),cur.consequent=[],this.next(),isCase?cur.test=this.parseExpression():(sawDefault&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),sawDefault=!0,cur.test=null),this.expect(types$1.colon)}else cur||this.unexpected(),cur.consequent.push(this.parseStatement(null));return this.exitScope(),cur&&this.finishNode(cur,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(node,"SwitchStatement")};pp$8.parseThrowStatement=function(node){return this.next(),lineBreak.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),node.argument=this.parseExpression(),this.semicolon(),this.finishNode(node,"ThrowStatement")};empty$1=[];pp$8.parseCatchClauseParam=function(){var param=this.parseBindingAtom(),simple=param.type==="Identifier";return this.enterScope(simple?SCOPE_SIMPLE_CATCH:0),this.checkLValPattern(param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL),this.expect(types$1.parenR),param};pp$8.parseTryStatement=function(node){if(this.next(),node.block=this.parseBlock(),node.handler=null,this.type===types$1._catch){var clause=this.startNode();this.next(),this.eat(types$1.parenL)?clause.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),clause.param=null,this.enterScope(0)),clause.body=this.parseBlock(!1),this.exitScope(),node.handler=this.finishNode(clause,"CatchClause")}return node.finalizer=this.eat(types$1._finally)?this.parseBlock():null,!node.handler&&!node.finalizer&&this.raise(node.start,"Missing catch or finally clause"),this.finishNode(node,"TryStatement")};pp$8.parseVarStatement=function(node,kind,allowMissingInitializer){return this.next(),this.parseVar(node,!1,kind,allowMissingInitializer),this.semicolon(),this.finishNode(node,"VariableDeclaration")};pp$8.parseWhileStatement=function(node){return this.next(),node.test=this.parseParenExpression(),this.labels.push(loopLabel),node.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(node,"WhileStatement")};pp$8.parseWithStatement=function(node){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),node.object=this.parseParenExpression(),node.body=this.parseStatement("with"),this.finishNode(node,"WithStatement")};pp$8.parseEmptyStatement=function(node){return this.next(),this.finishNode(node,"EmptyStatement")};pp$8.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list2=this.labels;i$1<list2.length;i$1+=1){var label=list2[i$1];label.name===maybeName&&this.raise(expr.start,"Label '"+maybeName+"' is already declared")}for(var kind=this.type.isLoop?"loop":this.type===types$1._switch?"switch":null,i2=this.labels.length-1;i2>=0;i2--){var label$1=this.labels[i2];if(label$1.statementStart===node.start)label$1.statementStart=this.start,label$1.kind=kind;else break}return this.labels.push({name:maybeName,kind,statementStart:this.start}),node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label"),this.labels.pop(),node.label=expr,this.finishNode(node,"LabeledStatement")};pp$8.parseExpressionStatement=function(node,expr){return node.expression=expr,this.semicolon(),this.finishNode(node,"ExpressionStatement")};pp$8.parseBlock=function(createNewLexicalScope,node,exitStrict){for(createNewLexicalScope===void 0&&(createNewLexicalScope=!0),node===void 0&&(node=this.startNode()),node.body=[],this.expect(types$1.braceL),createNewLexicalScope&&this.enterScope(0);this.type!==types$1.braceR;){var stmt=this.parseStatement(null);node.body.push(stmt)}return exitStrict&&(this.strict=!1),this.next(),createNewLexicalScope&&this.exitScope(),this.finishNode(node,"BlockStatement")};pp$8.parseFor=function(node,init){return node.init=init,this.expect(types$1.semi),node.test=this.type===types$1.semi?null:this.parseExpression(),this.expect(types$1.semi),node.update=this.type===types$1.parenR?null:this.parseExpression(),this.expect(types$1.parenR),node.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(node,"ForStatement")};pp$8.parseForIn=function(node,init){var isForIn=this.type===types$1._in;return this.next(),init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")&&this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer"),node.left=init,node.right=isForIn?this.parseExpression():this.parseMaybeAssign(),this.expect(types$1.parenR),node.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$8.parseVar=function(node,isFor,kind,allowMissingInitializer){for(node.declarations=[],node.kind=kind;;){var decl=this.startNode();if(this.parseVarId(decl,kind),this.eat(types$1.eq)?decl.init=this.parseMaybeAssign(isFor):!allowMissingInitializer&&kind==="const"&&!(this.type===types$1._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!allowMissingInitializer&&(kind==="using"||kind==="await using")&&this.options.ecmaVersion>=17&&this.type!==types$1._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+kind+" declaration"):!allowMissingInitializer&&decl.id.type!=="Identifier"&&!(isFor&&(this.type===types$1._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):decl.init=null,node.declarations.push(this.finishNode(decl,"VariableDeclarator")),!this.eat(types$1.comma))break}return node};pp$8.parseVarId=function(decl,kind){decl.id=kind==="using"||kind==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,!1)};FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$8.parseFunction=function(node,statement,allowExpressionBody,isAsync,forInit){this.initFunction(node),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync)&&(this.type===types$1.star&&statement&FUNC_HANGING_STATEMENT&&this.unexpected(),node.generator=this.eat(types$1.star)),this.options.ecmaVersion>=8&&(node.async=!!isAsync),statement&FUNC_STATEMENT&&(node.id=statement&FUNC_NULLABLE_ID&&this.type!==types$1.name?null:this.parseIdent(),node.id&&!(statement&FUNC_HANGING_STATEMENT)&&this.checkLValSimple(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION));var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(functionFlags(node.async,node.generator)),statement&FUNC_STATEMENT||(node.id=this.type===types$1.name?this.parseIdent():null),this.parseFunctionParams(node),this.parseFunctionBody(node,allowExpressionBody,!1,forInit),this.yieldPos=oldYieldPos,this.awaitPos=oldAwaitPos,this.awaitIdentPos=oldAwaitIdentPos,this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$8.parseFunctionParams=function(node){this.expect(types$1.parenL),node.params=this.parseBindingList(types$1.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};pp$8.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=!0,this.parseClassId(node,isStatement),this.parseClassSuper(node);var privateNameMap=this.enterClassBody(),classBody=this.startNode(),hadConstructor=!1;for(classBody.body=[],this.expect(types$1.braceL);this.type!==types$1.braceR;){var element=this.parseClassElement(node.superClass!==null);element&&(classBody.body.push(element),element.type==="MethodDefinition"&&element.kind==="constructor"?(hadConstructor&&this.raiseRecoverable(element.start,"Duplicate constructor in the same class"),hadConstructor=!0):element.key&&element.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(privateNameMap,element)&&this.raiseRecoverable(element.key.start,"Identifier '#"+element.key.name+"' has already been declared"))}return this.strict=oldStrict,this.next(),node.body=this.finishNode(classBody,"ClassBody"),this.exitClassBody(),this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$8.parseClassElement=function(constructorAllowsSuper){if(this.eat(types$1.semi))return null;var ecmaVersion2=this.options.ecmaVersion,node=this.startNode(),keyName="",isGenerator=!1,isAsync=!1,kind="method",isStatic=!1;if(this.eatContextual("static")){if(ecmaVersion2>=13&&this.eat(types$1.braceL))return this.parseClassStaticBlock(node),node;this.isClassElementNameStart()||this.type===types$1.star?isStatic=!0:keyName="static"}if(node.static=isStatic,!keyName&&ecmaVersion2>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===types$1.star)&&!this.canInsertSemicolon()?isAsync=!0:keyName="async"),!keyName&&(ecmaVersion2>=9||!isAsync)&&this.eat(types$1.star)&&(isGenerator=!0),!keyName&&!isAsync&&!isGenerator){var lastValue=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?kind=lastValue:keyName=lastValue)}if(keyName?(node.computed=!1,node.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),node.key.name=keyName,this.finishNode(node.key,"Identifier")):this.parseClassElementName(node),ecmaVersion2<13||this.type===types$1.parenL||kind!=="method"||isGenerator||isAsync){var isConstructor=!node.static&&checkKeyName(node,"constructor"),allowsDirectSuper=isConstructor&&constructorAllowsSuper;isConstructor&&kind!=="method"&&this.raise(node.key.start,"Constructor can't have get/set modifier"),node.kind=isConstructor?"constructor":kind,this.parseClassMethod(node,isGenerator,isAsync,allowsDirectSuper)}else this.parseClassField(node);return node};pp$8.isClassElementNameStart=function(){return this.type===types$1.name||this.type===types$1.privateId||this.type===types$1.num||this.type===types$1.string||this.type===types$1.bracketL||this.type.keyword};pp$8.parseClassElementName=function(element){this.type===types$1.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),element.computed=!1,element.key=this.parsePrivateIdent()):this.parsePropertyName(element)};pp$8.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){var key2=method.key;method.kind==="constructor"?(isGenerator&&this.raise(key2.start,"Constructor can't be a generator"),isAsync&&this.raise(key2.start,"Constructor can't be an async method")):method.static&&checkKeyName(method,"prototype")&&this.raise(key2.start,"Classes may not have a static property named prototype");var value=method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return method.kind==="get"&&value.params.length!==0&&this.raiseRecoverable(value.start,"getter should have no params"),method.kind==="set"&&value.params.length!==1&&this.raiseRecoverable(value.start,"setter should have exactly one param"),method.kind==="set"&&value.params[0].type==="RestElement"&&this.raiseRecoverable(value.params[0].start,"Setter cannot use rest params"),this.finishNode(method,"MethodDefinition")};pp$8.parseClassField=function(field){return checkKeyName(field,"constructor")?this.raise(field.key.start,"Classes can't have a field named 'constructor'"):field.static&&checkKeyName(field,"prototype")&&this.raise(field.key.start,"Classes can't have a static field named 'prototype'"),this.eat(types$1.eq)?(this.enterScope(SCOPE_CLASS_FIELD_INIT|SCOPE_SUPER),field.value=this.parseMaybeAssign(),this.exitScope()):field.value=null,this.semicolon(),this.finishNode(field,"PropertyDefinition")};pp$8.parseClassStaticBlock=function(node){node.body=[];var oldLabels=this.labels;for(this.labels=[],this.enterScope(SCOPE_CLASS_STATIC_BLOCK|SCOPE_SUPER);this.type!==types$1.braceR;){var stmt=this.parseStatement(null);node.body.push(stmt)}return this.next(),this.exitScope(),this.labels=oldLabels,this.finishNode(node,"StaticBlock")};pp$8.parseClassId=function(node,isStatement){this.type===types$1.name?(node.id=this.parseIdent(),isStatement&&this.checkLValSimple(node.id,BIND_LEXICAL,!1)):(isStatement===!0&&this.unexpected(),node.id=null)};pp$8.parseClassSuper=function(node){node.superClass=this.eat(types$1._extends)?this.parseExprSubscripts(null,!1):null};pp$8.enterClassBody=function(){var element={declared:Object.create(null),used:[]};return this.privateNameStack.push(element),element.declared};pp$8.exitClassBody=function(){var ref2=this.privateNameStack.pop(),declared=ref2.declared,used=ref2.used;if(this.options.checkPrivateFields)for(var len=this.privateNameStack.length,parent=len===0?null:this.privateNameStack[len-1],i2=0;i2<used.length;++i2){var id=used[i2];hasOwn(declared,id.name)||(parent?parent.used.push(id):this.raiseRecoverable(id.start,"Private field '#"+id.name+"' must be declared in an enclosing class"))}};pp$8.parseExportAllDeclaration=function(node,exports$1){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(node.exported=this.parseModuleExportName(),this.checkExport(exports$1,node.exported,this.lastTokStart)):node.exported=null),this.expectContextual("from"),this.type!==types$1.string&&this.unexpected(),node.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(node.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(node,"ExportAllDeclaration")};pp$8.parseExport=function(node,exports$1){if(this.next(),this.eat(types$1.star))return this.parseExportAllDeclaration(node,exports$1);if(this.eat(types$1._default))return this.checkExport(exports$1,"default",this.lastTokStart),node.declaration=this.parseExportDefaultDeclaration(),this.finishNode(node,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())node.declaration=this.parseExportDeclaration(node),node.declaration.type==="VariableDeclaration"?this.checkVariableExport(exports$1,node.declaration.declarations):this.checkExport(exports$1,node.declaration.id,node.declaration.id.start),node.specifiers=[],node.source=null,this.options.ecmaVersion>=16&&(node.attributes=[]);else{if(node.declaration=null,node.specifiers=this.parseExportSpecifiers(exports$1),this.eatContextual("from"))this.type!==types$1.string&&this.unexpected(),node.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(node.attributes=this.parseWithClause());else{for(var i2=0,list2=node.specifiers;i2<list2.length;i2+=1){var spec=list2[i2];this.checkUnreserved(spec.local),this.checkLocalExport(spec.local),spec.local.type==="Literal"&&this.raise(spec.local.start,"A string literal cannot be used as an exported binding without `from`.")}node.source=null,this.options.ecmaVersion>=16&&(node.attributes=[])}this.semicolon()}return this.finishNode(node,"ExportNamedDeclaration")};pp$8.parseExportDeclaration=function(node){return this.parseStatement(null)};pp$8.parseExportDefaultDeclaration=function(){var isAsync;if(this.type===types$1._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();return this.next(),isAsync&&this.next(),this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,!1,isAsync)}else if(this.type===types$1._class){var cNode=this.startNode();return this.parseClass(cNode,"nullableID")}else{var declaration=this.parseMaybeAssign();return this.semicolon(),declaration}};pp$8.checkExport=function(exports$1,name,pos){exports$1&&(typeof name!="string"&&(name=name.type==="Identifier"?name.name:name.value),hasOwn(exports$1,name)&&this.raiseRecoverable(pos,"Duplicate export '"+name+"'"),exports$1[name]=!0)};pp$8.checkPatternExport=function(exports$1,pat){var type=pat.type;if(type==="Identifier")this.checkExport(exports$1,pat,pat.start);else if(type==="ObjectPattern")for(var i2=0,list2=pat.properties;i2<list2.length;i2+=1){var prop=list2[i2];this.checkPatternExport(exports$1,prop)}else if(type==="ArrayPattern")for(var i$1=0,list$1=pat.elements;i$1<list$1.length;i$1+=1){var elt=list$1[i$1];elt&&this.checkPatternExport(exports$1,elt)}else type==="Property"?this.checkPatternExport(exports$1,pat.value):type==="AssignmentPattern"?this.checkPatternExport(exports$1,pat.left):type==="RestElement"&&this.checkPatternExport(exports$1,pat.argument)};pp$8.checkVariableExport=function(exports$1,decls){if(exports$1)for(var i2=0,list2=decls;i2<list2.length;i2+=1){var decl=list2[i2];this.checkPatternExport(exports$1,decl.id)}};pp$8.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};pp$8.parseExportSpecifier=function(exports$1){var node=this.startNode();return node.local=this.parseModuleExportName(),node.exported=this.eatContextual("as")?this.parseModuleExportName():node.local,this.checkExport(exports$1,node.exported,node.exported.start),this.finishNode(node,"ExportSpecifier")};pp$8.parseExportSpecifiers=function(exports$1){var nodes=[],first=!0;for(this.expect(types$1.braceL);!this.eat(types$1.braceR);){if(first)first=!1;else if(this.expect(types$1.comma),this.afterTrailingComma(types$1.braceR))break;nodes.push(this.parseExportSpecifier(exports$1))}return nodes};pp$8.parseImport=function(node){return this.next(),this.type===types$1.string?(node.specifiers=empty$1,node.source=this.parseExprAtom()):(node.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),node.source=this.type===types$1.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(node.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(node,"ImportDeclaration")};pp$8.parseImportSpecifier=function(){var node=this.startNode();return node.imported=this.parseModuleExportName(),this.eatContextual("as")?node.local=this.parseIdent():(this.checkUnreserved(node.imported),node.local=node.imported),this.checkLValSimple(node.local,BIND_LEXICAL),this.finishNode(node,"ImportSpecifier")};pp$8.parseImportDefaultSpecifier=function(){var node=this.startNode();return node.local=this.parseIdent(),this.checkLValSimple(node.local,BIND_LEXICAL),this.finishNode(node,"ImportDefaultSpecifier")};pp$8.parseImportNamespaceSpecifier=function(){var node=this.startNode();return this.next(),this.expectContextual("as"),node.local=this.parseIdent(),this.checkLValSimple(node.local,BIND_LEXICAL),this.finishNode(node,"ImportNamespaceSpecifier")};pp$8.parseImportSpecifiers=function(){var nodes=[],first=!0;if(this.type===types$1.name&&(nodes.push(this.parseImportDefaultSpecifier()),!this.eat(types$1.comma)))return nodes;if(this.type===types$1.star)return nodes.push(this.parseImportNamespaceSpecifier()),nodes;for(this.expect(types$1.braceL);!this.eat(types$1.braceR);){if(first)first=!1;else if(this.expect(types$1.comma),this.afterTrailingComma(types$1.braceR))break;nodes.push(this.parseImportSpecifier())}return nodes};pp$8.parseWithClause=function(){var nodes=[];if(!this.eat(types$1._with))return nodes;this.expect(types$1.braceL);for(var attributeKeys={},first=!0;!this.eat(types$1.braceR);){if(first)first=!1;else if(this.expect(types$1.comma),this.afterTrailingComma(types$1.braceR))break;var attr=this.parseImportAttribute(),keyName=attr.key.type==="Identifier"?attr.key.name:attr.key.value;hasOwn(attributeKeys,keyName)&&this.raiseRecoverable(attr.key.start,"Duplicate attribute key '"+keyName+"'"),attributeKeys[keyName]=!0,nodes.push(attr)}return nodes};pp$8.parseImportAttribute=function(){var node=this.startNode();return node.key=this.type===types$1.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(types$1.colon),this.type!==types$1.string&&this.unexpected(),node.value=this.parseExprAtom(),this.finishNode(node,"ImportAttribute")};pp$8.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===types$1.string){var stringLiteral=this.parseLiteral(this.value);return loneSurrogate.test(stringLiteral.value)&&this.raise(stringLiteral.start,"An export name cannot include a lone surrogate."),stringLiteral}return this.parseIdent(!0)};pp$8.adaptDirectivePrologue=function(statements){for(var i2=0;i2<statements.length&&this.isDirectiveCandidate(statements[i2]);++i2)statements[i2].directive=statements[i2].expression.raw.slice(1,-1)};pp$8.isDirectiveCandidate=function(statement){return this.options.ecmaVersion>=5&&statement.type==="ExpressionStatement"&&statement.expression.type==="Literal"&&typeof statement.expression.value=="string"&&(this.input[statement.start]==='"'||this.input[statement.start]==="'")};pp$7=Parser.prototype;pp$7.toAssignable=function(node,isBinding,refDestructuringErrors){if(this.options.ecmaVersion>=6&&node)switch(node.type){case"Identifier":this.inAsync&&node.name==="await"&&this.raise(node.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern",refDestructuringErrors&&this.checkPatternErrors(refDestructuringErrors,!0);for(var i2=0,list2=node.properties;i2<list2.length;i2+=1){var prop=list2[i2];this.toAssignable(prop,isBinding),prop.type==="RestElement"&&(prop.argument.type==="ArrayPattern"||prop.argument.type==="ObjectPattern")&&this.raise(prop.argument.start,"Unexpected token")}break;case"Property":node.kind!=="init"&&this.raise(node.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(node.value,isBinding);break;case"ArrayExpression":node.type="ArrayPattern",refDestructuringErrors&&this.checkPatternErrors(refDestructuringErrors,!0),this.toAssignableList(node.elements,isBinding);break;case"SpreadElement":node.type="RestElement",this.toAssignable(node.argument,isBinding),node.argument.type==="AssignmentPattern"&&this.raise(node.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":node.operator!=="="&&this.raise(node.left.end,"Only '=' operator can be used for specifying default value."),node.type="AssignmentPattern",delete node.operator,this.toAssignable(node.left,isBinding);break;case"ParenthesizedExpression":this.toAssignable(node.expression,isBinding,refDestructuringErrors);break;case"ChainExpression":this.raiseRecoverable(node.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!isBinding)break;default:this.raise(node.start,"Assigning to rvalue")}else refDestructuringErrors&&this.checkPatternErrors(refDestructuringErrors,!0);return node};pp$7.toAssignableList=function(exprList,isBinding){for(var end=exprList.length,i2=0;i2<end;i2++){var elt=exprList[i2];elt&&this.toAssignable(elt,isBinding)}if(end){var last=exprList[end-1];this.options.ecmaVersion===6&&isBinding&&last&&last.type==="RestElement"&&last.argument.type!=="Identifier"&&this.unexpected(last.argument.start)}return exprList};pp$7.parseSpread=function(refDestructuringErrors){var node=this.startNode();return this.next(),node.argument=this.parseMaybeAssign(!1,refDestructuringErrors),this.finishNode(node,"SpreadElement")};pp$7.parseRestBinding=function(){var node=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==types$1.name&&this.unexpected(),node.argument=this.parseBindingAtom(),this.finishNode(node,"RestElement")};pp$7.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case types$1.bracketL:var node=this.startNode();return this.next(),node.elements=this.parseBindingList(types$1.bracketR,!0,!0),this.finishNode(node,"ArrayPattern");case types$1.braceL:return this.parseObj(!0)}return this.parseIdent()};pp$7.parseBindingList=function(close,allowEmpty,allowTrailingComma,allowModifiers){for(var elts=[],first=!0;!this.eat(close);)if(first?first=!1:this.expect(types$1.comma),allowEmpty&&this.type===types$1.comma)elts.push(null);else{if(allowTrailingComma&&this.afterTrailingComma(close))break;if(this.type===types$1.ellipsis){var rest=this.parseRestBinding();this.parseBindingListItem(rest),elts.push(rest),this.type===types$1.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(close);break}else elts.push(this.parseAssignableListItem(allowModifiers))}return elts};pp$7.parseAssignableListItem=function(allowModifiers){var elem=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(elem),elem};pp$7.parseBindingListItem=function(param){return param};pp$7.parseMaybeDefault=function(startPos,startLoc,left){if(left=left||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(types$1.eq))return left;var node=this.startNodeAt(startPos,startLoc);return node.left=left,node.right=this.parseMaybeAssign(),this.finishNode(node,"AssignmentPattern")};pp$7.checkLValSimple=function(expr,bindingType,checkClashes){bindingType===void 0&&(bindingType=BIND_NONE);var isBind=bindingType!==BIND_NONE;switch(expr.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(expr.name)&&this.raiseRecoverable(expr.start,(isBind?"Binding ":"Assigning to ")+expr.name+" in strict mode"),isBind&&(bindingType===BIND_LEXICAL&&expr.name==="let"&&this.raiseRecoverable(expr.start,"let is disallowed as a lexically bound name"),checkClashes&&(hasOwn(checkClashes,expr.name)&&this.raiseRecoverable(expr.start,"Argument name clash"),checkClashes[expr.name]=!0),bindingType!==BIND_OUTSIDE&&this.declareName(expr.name,bindingType,expr.start));break;case"ChainExpression":this.raiseRecoverable(expr.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":isBind&&this.raiseRecoverable(expr.start,"Binding member expression");break;case"ParenthesizedExpression":return isBind&&this.raiseRecoverable(expr.start,"Binding parenthesized expression"),this.checkLValSimple(expr.expression,bindingType,checkClashes);default:this.raise(expr.start,(isBind?"Binding":"Assigning to")+" rvalue")}};pp$7.checkLValPattern=function(expr,bindingType,checkClashes){switch(bindingType===void 0&&(bindingType=BIND_NONE),expr.type){case"ObjectPattern":for(var i2=0,list2=expr.properties;i2<list2.length;i2+=1){var prop=list2[i2];this.checkLValInnerPattern(prop,bindingType,checkClashes)}break;case"ArrayPattern":for(var i$1=0,list$1=expr.elements;i$1<list$1.length;i$1+=1){var elem=list$1[i$1];elem&&this.checkLValInnerPattern(elem,bindingType,checkClashes)}break;default:this.checkLValSimple(expr,bindingType,checkClashes)}};pp$7.checkLValInnerPattern=function(expr,bindingType,checkClashes){switch(bindingType===void 0&&(bindingType=BIND_NONE),expr.type){case"Property":this.checkLValInnerPattern(expr.value,bindingType,checkClashes);break;case"AssignmentPattern":this.checkLValPattern(expr.left,bindingType,checkClashes);break;case"RestElement":this.checkLValPattern(expr.argument,bindingType,checkClashes);break;default:this.checkLValPattern(expr,bindingType,checkClashes)}};TokContext=function(token,isExpr,preserveSpace,override,generator){this.token=token,this.isExpr=!!isExpr,this.preserveSpace=!!preserveSpace,this.override=override,this.generator=!!generator},types={b_stat:new TokContext("{",!1),b_expr:new TokContext("{",!0),b_tmpl:new TokContext("${",!1),p_stat:new TokContext("(",!1),p_expr:new TokContext("(",!0),q_tmpl:new TokContext("`",!0,!0,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",!1),f_expr:new TokContext("function",!0),f_expr_gen:new TokContext("function",!0,!1,null,!0),f_gen:new TokContext("function",!1,!1,null,!0)},pp$6=Parser.prototype;pp$6.initialContext=function(){return[types.b_stat]};pp$6.curContext=function(){return this.context[this.context.length-1]};pp$6.braceIsBlock=function(prevType){var parent=this.curContext();return parent===types.f_expr||parent===types.f_stat?!0:prevType===types$1.colon&&(parent===types.b_stat||parent===types.b_expr)?!parent.isExpr:prevType===types$1._return||prevType===types$1.name&&this.exprAllowed?lineBreak.test(this.input.slice(this.lastTokEnd,this.start)):prevType===types$1._else||prevType===types$1.semi||prevType===types$1.eof||prevType===types$1.parenR||prevType===types$1.arrow?!0:prevType===types$1.braceL?parent===types.b_stat:prevType===types$1._var||prevType===types$1._const||prevType===types$1.name?!1:!this.exprAllowed};pp$6.inGeneratorContext=function(){for(var i2=this.context.length-1;i2>=1;i2--){var context=this.context[i2];if(context.token==="function")return context.generator}return!1};pp$6.updateContext=function(prevType){var update,type=this.type;type.keyword&&prevType===types$1.dot?this.exprAllowed=!1:(update=type.updateContext)?update.call(this,prevType):this.exprAllowed=type.beforeExpr};pp$6.overrideContext=function(tokenCtx){this.curContext()!==tokenCtx&&(this.context[this.context.length-1]=tokenCtx)};types$1.parenR.updateContext=types$1.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var out=this.context.pop();out===types.b_stat&&this.curContext().token==="function"&&(out=this.context.pop()),this.exprAllowed=!out.isExpr};types$1.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types.b_stat:types.b_expr),this.exprAllowed=!0};types$1.dollarBraceL.updateContext=function(){this.context.push(types.b_tmpl),this.exprAllowed=!0};types$1.parenL.updateContext=function(prevType){var statementParens=prevType===types$1._if||prevType===types$1._for||prevType===types$1._with||prevType===types$1._while;this.context.push(statementParens?types.p_stat:types.p_expr),this.exprAllowed=!0};types$1.incDec.updateContext=function(){};types$1._function.updateContext=types$1._class.updateContext=function(prevType){prevType.beforeExpr&&prevType!==types$1._else&&!(prevType===types$1.semi&&this.curContext()!==types.p_stat)&&!(prevType===types$1._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types$1.colon||prevType===types$1.braceL)&&this.curContext()===types.b_stat)?this.context.push(types.f_expr):this.context.push(types.f_stat),this.exprAllowed=!1};types$1.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};types$1.backQuote.updateContext=function(){this.curContext()===types.q_tmpl?this.context.pop():this.context.push(types.q_tmpl),this.exprAllowed=!1};types$1.star.updateContext=function(prevType){if(prevType===types$1._function){var index=this.context.length-1;this.context[index]===types.f_expr?this.context[index]=types.f_expr_gen:this.context[index]=types.f_gen}this.exprAllowed=!0};types$1.name.updateContext=function(prevType){var allowed=!1;this.options.ecmaVersion>=6&&prevType!==types$1.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(allowed=!0),this.exprAllowed=allowed};pp$5=Parser.prototype;pp$5.checkPropClash=function(prop,propHash,refDestructuringErrors){if(!(this.options.ecmaVersion>=9&&prop.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(prop.computed||prop.method||prop.shorthand))){var key2=prop.key,name;switch(key2.type){case"Identifier":name=key2.name;break;case"Literal":name=String(key2.value);break;default:return}var kind=prop.kind;if(this.options.ecmaVersion>=6){name==="__proto__"&&kind==="init"&&(propHash.proto&&(refDestructuringErrors?refDestructuringErrors.doubleProto<0&&(refDestructuringErrors.doubleProto=key2.start):this.raiseRecoverable(key2.start,"Redefinition of __proto__ property")),propHash.proto=!0);return}name="$"+name;var other=propHash[name];if(other){var redefinition;kind==="init"?redefinition=this.strict&&other.init||other.get||other.set:redefinition=other.init||other[kind],redefinition&&this.raiseRecoverable(key2.start,"Redefinition of property")}else other=propHash[name]={init:!1,get:!1,set:!1};other[kind]=!0}};pp$5.parseExpression=function(forInit,refDestructuringErrors){var this$1$1=this;return this.catchStackOverflow(function(){var startPos=this$1$1.start,startLoc=this$1$1.startLoc,expr=this$1$1.parseMaybeAssign(forInit,refDestructuringErrors);if(this$1$1.type===types$1.comma){var node=this$1$1.startNodeAt(startPos,startLoc);for(node.expressions=[expr];this$1$1.eat(types$1.comma);)node.expressions.push(this$1$1.parseMaybeAssign(forInit,refDestructuringErrors));return this$1$1.finishNode(node,"SequenceExpression")}return expr})};pp$5.parseMaybeAssign=function(forInit,refDestructuringErrors,afterLeftParse){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(forInit);this.exprAllowed=!1}var ownDestructuringErrors=!1,oldParenAssign=-1,oldTrailingComma=-1,oldDoubleProto=-1;refDestructuringErrors?(oldParenAssign=refDestructuringErrors.parenthesizedAssign,oldTrailingComma=refDestructuringErrors.trailingComma,oldDoubleProto=refDestructuringErrors.doubleProto,refDestructuringErrors.parenthesizedAssign=refDestructuringErrors.trailingComma=-1):(refDestructuringErrors=new DestructuringErrors,ownDestructuringErrors=!0);var startPos=this.start,startLoc=this.startLoc;(this.type===types$1.parenL||this.type===types$1.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=forInit==="await");var left=this.parseMaybeConditional(forInit,refDestructuringErrors);if(afterLeftParse&&(left=afterLeftParse.call(this,left,startPos,startLoc)),this.type.isAssign){var node=this.startNodeAt(startPos,startLoc);return node.operator=this.value,this.type===types$1.eq&&(left=this.toAssignable(left,!1,refDestructuringErrors)),ownDestructuringErrors||(refDestructuringErrors.parenthesizedAssign=refDestructuringErrors.trailingComma=-1,refDestructuringErrors.shorthandAssign>=left.start&&(refDestructuringErrors.shorthandAssign=-1),refDestructuringErrors.doubleProto>=left.start&&(refDestructuringErrors.doubleProto=-1)),this.type===types$1.eq?this.checkLValPattern(left):this.checkLValSimple(left),node.left=left,this.next(),node.right=this.parseMaybeAssign(forInit),oldDoubleProto>-1&&(refDestructuringErrors.doubleProto=oldDoubleProto),this.finishNode(node,"AssignmentExpression")}else ownDestructuringErrors&&this.checkExpressionErrors(refDestructuringErrors,!0);return oldParenAssign>-1&&(refDestructuringErrors.parenthesizedAssign=oldParenAssign),oldTrailingComma>-1&&(refDestructuringErrors.trailingComma=oldTrailingComma),left};pp$5.parseMaybeConditional=function(forInit,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc,expr=this.parseExprOps(forInit,refDestructuringErrors);if(this.checkExpressionErrors(refDestructuringErrors))return expr;if(!(expr.type==="ArrowFunctionExpression"&&expr.start===startPos)&&this.eat(types$1.question)){var node=this.startNodeAt(startPos,startLoc);return node.test=expr,node.consequent=this.parseMaybeAssign(),this.expect(types$1.colon),node.alternate=this.parseMaybeAssign(forInit),this.finishNode(node,"ConditionalExpression")}return expr};pp$5.parseExprOps=function(forInit,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc,expr=this.parseMaybeUnary(refDestructuringErrors,!1,!1,forInit);return this.checkExpressionErrors(refDestructuringErrors)||expr.start===startPos&&expr.type==="ArrowFunctionExpression"?expr:this.parseExprOp(expr,startPos,startLoc,-1,forInit)};pp$5.parseExprOp=function(left,leftStartPos,leftStartLoc,minPrec,forInit){var prec=this.type.binop;if(prec!=null&&(!forInit||this.type!==types$1._in)&&prec>minPrec){var logical=this.type===types$1.logicalOR||this.type===types$1.logicalAND,coalesce=this.type===types$1.coalesce;coalesce&&(prec=types$1.logicalAND.binop);var op=this.value;this.next();var startPos=this.start,startLoc=this.startLoc,right=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,forInit),startPos,startLoc,prec,forInit),node=this.buildBinary(leftStartPos,leftStartLoc,left,right,op,logical||coalesce);return(logical&&this.type===types$1.coalesce||coalesce&&(this.type===types$1.logicalOR||this.type===types$1.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(node,leftStartPos,leftStartLoc,minPrec,forInit)}return left};pp$5.buildBinary=function(startPos,startLoc,left,right,op,logical){right.type==="PrivateIdentifier"&&this.raise(right.start,"Private identifier can only be left side of binary expression");var node=this.startNodeAt(startPos,startLoc);return node.left=left,node.operator=op,node.right=right,this.finishNode(node,logical?"LogicalExpression":"BinaryExpression")};pp$5.parseMaybeUnary=function(refDestructuringErrors,sawUnary,incDec,forInit){var startPos=this.start,startLoc=this.startLoc,expr;if(this.isContextual("await")&&this.canAwait)expr=this.parseAwait(forInit),sawUnary=!0;else if(this.type.prefix){var node=this.startNode(),update=this.type===types$1.incDec;node.operator=this.value,node.prefix=!0,this.next(),node.argument=this.parseMaybeUnary(null,!0,update,forInit),this.checkExpressionErrors(refDestructuringErrors,!0),update?this.checkLValSimple(node.argument):this.strict&&node.operator==="delete"&&isLocalVariableAccess(node.argument)?this.raiseRecoverable(node.start,"Deleting local variable in strict mode"):node.operator==="delete"&&isPrivateFieldAccess(node.argument)?this.raiseRecoverable(node.start,"Private fields can not be deleted"):sawUnary=!0,expr=this.finishNode(node,update?"UpdateExpression":"UnaryExpression")}else if(!sawUnary&&this.type===types$1.privateId)(forInit||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),expr=this.parsePrivateIdent(),this.type!==types$1._in&&this.unexpected();else{if(expr=this.parseExprSubscripts(refDestructuringErrors,forInit),this.checkExpressionErrors(refDestructuringErrors))return expr;for(;this.type.postfix&&!this.canInsertSemicolon();){var node$1=this.startNodeAt(startPos,startLoc);node$1.operator=this.value,node$1.prefix=!1,node$1.argument=expr,this.checkLValSimple(expr),this.next(),expr=this.finishNode(node$1,"UpdateExpression")}}if(!incDec&&!(expr.type==="ArrowFunctionExpression"&&expr.start===startPos)&&this.eat(types$1.starstar))if(sawUnary)this.unexpected(this.lastTokStart);else return this.buildBinary(startPos,startLoc,expr,this.parseMaybeUnary(null,!1,!1,forInit),"**",!1);else return expr};pp$5.parseExprSubscripts=function(refDestructuringErrors,forInit){var startPos=this.start,startLoc=this.startLoc,oldDoubleProto=-1,oldShorthandAssign=-1;refDestructuringErrors&&(oldDoubleProto=refDestructuringErrors.doubleProto,oldShorthandAssign=refDestructuringErrors.shorthandAssign,refDestructuringErrors.doubleProto=refDestructuringErrors.shorthandAssign=-1);var expr=this.parseExprAtom(refDestructuringErrors,forInit);if(expr.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return expr;var result=this.parseSubscripts(expr,startPos,startLoc,!1,forInit);return refDestructuringErrors&&(result.end>expr.end&&(this.checkExpressionErrors(refDestructuringErrors,!0),refDestructuringErrors.parenthesizedAssign>=result.start&&(refDestructuringErrors.parenthesizedAssign=-1),refDestructuringErrors.parenthesizedBind>=result.start&&(refDestructuringErrors.parenthesizedBind=-1),refDestructuringErrors.trailingComma>=result.start&&(refDestructuringErrors.trailingComma=-1)),oldDoubleProto>-1&&(refDestructuringErrors.doubleProto=oldDoubleProto),oldShorthandAssign>-1&&(refDestructuringErrors.shorthandAssign=oldShorthandAssign)),result};pp$5.parseSubscripts=function(base,startPos,startLoc,noCalls,forInit){for(var maybeAsyncArrow=this.options.ecmaVersion>=8&&base.type==="Identifier"&&base.name==="async"&&this.lastTokEnd===base.end&&!this.canInsertSemicolon()&&base.end-base.start===5&&this.potentialArrowAt===base.start,optionalChained=!1;;){var element=this.parseSubscript(base,startPos,startLoc,noCalls,maybeAsyncArrow,optionalChained,forInit);if(element.optional&&(optionalChained=!0),element.end===base.end||element.type==="ArrowFunctionExpression"){if(optionalChained){var chainNode=this.startNodeAt(startPos,startLoc);chainNode.expression=element,element=this.finishNode(chainNode,"ChainExpression")}return element}base=element,maybeAsyncArrow=!1}};pp$5.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(types$1.arrow)};pp$5.parseSubscriptAsyncArrow=function(startPos,startLoc,exprList,forInit){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList,!0,forInit)};pp$5.parseSubscript=function(base,startPos,startLoc,noCalls,maybeAsyncArrow,optionalChained,forInit){var optionalSupported=this.options.ecmaVersion>=11,optional=optionalSupported&&this.eat(types$1.questionDot);noCalls&&optional&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var computed=this.eat(types$1.bracketL);if(computed||optional&&this.type!==types$1.parenL&&this.type!==types$1.backQuote||this.eat(types$1.dot)){var node=this.startNodeAt(startPos,startLoc);node.object=base,computed?(node.property=this.parseExpression(),this.expect(types$1.bracketR)):this.type===types$1.privateId&&base.type!=="Super"?node.property=this.parsePrivateIdent():node.property=this.parseIdent(this.options.allowReserved!=="never"),node.computed=!!computed,optionalSupported&&(node.optional=optional),base=this.finishNode(node,"MemberExpression")}else if(!noCalls&&this.eat(types$1.parenL)){var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var exprList=this.parseExprList(types$1.parenR,this.options.ecmaVersion>=8,!1,refDestructuringErrors);if(maybeAsyncArrow&&!optional&&this.shouldParseAsyncArrow())return this.checkPatternErrors(refDestructuringErrors,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=oldYieldPos,this.awaitPos=oldAwaitPos,this.awaitIdentPos=oldAwaitIdentPos,this.parseSubscriptAsyncArrow(startPos,startLoc,exprList,forInit);this.checkExpressionErrors(refDestructuringErrors,!0),this.yieldPos=oldYieldPos||this.yieldPos,this.awaitPos=oldAwaitPos||this.awaitPos,this.awaitIdentPos=oldAwaitIdentPos||this.awaitIdentPos;var node$1=this.startNodeAt(startPos,startLoc);node$1.callee=base,node$1.arguments=exprList,optionalSupported&&(node$1.optional=optional),base=this.finishNode(node$1,"CallExpression")}else if(this.type===types$1.backQuote){(optional||optionalChained)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var node$2=this.startNodeAt(startPos,startLoc);node$2.tag=base,node$2.quasi=this.parseTemplate({isTagged:!0}),base=this.finishNode(node$2,"TaggedTemplateExpression")}return base};pp$5.parseExprAtom=function(refDestructuringErrors,forInit,forNew){this.type===types$1.slash&&this.readRegexp();var node,canBeArrow=this.potentialArrowAt===this.start;switch(this.type){case types$1._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),node=this.startNode(),this.next(),this.type===types$1.parenL&&!this.allowDirectSuper&&this.raise(node.start,"super() call outside constructor of a subclass"),this.type!==types$1.dot&&this.type!==types$1.bracketL&&this.type!==types$1.parenL&&this.unexpected(),this.finishNode(node,"Super");case types$1._this:return node=this.startNode(),this.next(),this.finishNode(node,"ThisExpression");case types$1.name:var startPos=this.start,startLoc=this.startLoc,containsEsc=this.containsEsc,id=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types$1._function))return this.overrideContext(types.f_expr),this.parseFunction(this.startNodeAt(startPos,startLoc),0,!1,!0,forInit);if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types$1.arrow))return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],!1,forInit);if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types$1.name&&!containsEsc&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return id=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(types$1.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],!0,forInit)}return id;case types$1.regexp:var value=this.value;return node=this.parseLiteral(value.value),node.regex={pattern:value.pattern,flags:value.flags},node;case types$1.num:case types$1.string:return this.parseLiteral(this.value);case types$1._null:case types$1._true:case types$1._false:return node=this.startNode(),node.value=this.type===types$1._null?null:this.type===types$1._true,node.raw=this.type.keyword,this.next(),this.finishNode(node,"Literal");case types$1.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow,forInit);return refDestructuringErrors&&(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)&&(refDestructuringErrors.parenthesizedAssign=start),refDestructuringErrors.parenthesizedBind<0&&(refDestructuringErrors.parenthesizedBind=start)),expr;case types$1.bracketL:return node=this.startNode(),this.next(),node.elements=this.parseExprList(types$1.bracketR,!0,!0,refDestructuringErrors),this.finishNode(node,"ArrayExpression");case types$1.braceL:return this.overrideContext(types.b_expr),this.parseObj(!1,refDestructuringErrors);case types$1._function:return node=this.startNode(),this.next(),this.parseFunction(node,0);case types$1._class:return this.parseClass(this.startNode(),!1);case types$1._new:return this.parseNew();case types$1.backQuote:return this.parseTemplate();case types$1._import:return this.options.ecmaVersion>=11?this.parseExprImport(forNew):this.unexpected();default:return this.parseExprAtomDefault()}};pp$5.parseExprAtomDefault=function(){this.unexpected()};pp$5.parseExprImport=function(forNew){var node=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===types$1.parenL&&!forNew)return this.parseDynamicImport(node);if(this.type===types$1.dot){var meta=this.startNodeAt(node.start,node.loc&&node.loc.start);return meta.name="import",node.meta=this.finishNode(meta,"Identifier"),this.parseImportMeta(node)}else this.unexpected()};pp$5.parseDynamicImport=function(node){if(this.next(),node.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(types$1.parenR)?node.options=null:(this.expect(types$1.comma),this.afterTrailingComma(types$1.parenR)?node.options=null:(node.options=this.parseMaybeAssign(),this.eat(types$1.parenR)||(this.expect(types$1.comma),this.afterTrailingComma(types$1.parenR)||this.unexpected())));else if(!this.eat(types$1.parenR)){var errorPos=this.start;this.eat(types$1.comma)&&this.eat(types$1.parenR)?this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()"):this.unexpected(errorPos)}return this.finishNode(node,"ImportExpression")};pp$5.parseImportMeta=function(node){this.next();var containsEsc=this.containsEsc;return node.property=this.parseIdent(!0),node.property.name!=="meta"&&this.raiseRecoverable(node.property.start,"The only valid meta property for import is 'import.meta'"),containsEsc&&this.raiseRecoverable(node.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(node.start,"Cannot use 'import.meta' outside a module"),this.finishNode(node,"MetaProperty")};pp$5.parseLiteral=function(value){var node=this.startNode();return node.value=value,node.raw=this.input.slice(this.start,this.end),node.raw.charCodeAt(node.raw.length-1)===110&&(node.bigint=node.value!=null?node.value.toString():node.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(node,"Literal")};pp$5.parseParenExpression=function(){this.expect(types$1.parenL);var val=this.parseExpression();return this.expect(types$1.parenR),val};pp$5.shouldParseArrow=function(exprList){return!this.canInsertSemicolon()};pp$5.parseParenAndDistinguishExpression=function(canBeArrow,forInit){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc,exprList=[],first=!0,lastIsComma=!1,refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;for(this.yieldPos=0,this.awaitPos=0;this.type!==types$1.parenR;)if(first?first=!1:this.expect(types$1.comma),allowTrailingComma&&this.afterTrailingComma(types$1.parenR,!0)){lastIsComma=!0;break}else if(this.type===types$1.ellipsis){spreadStart=this.start,exprList.push(this.parseParenItem(this.parseRestBinding())),this.type===types$1.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else exprList.push(this.parseMaybeAssign(!1,refDestructuringErrors,this.parseParenItem));var innerEndPos=this.lastTokEnd,innerEndLoc=this.lastTokEndLoc;if(this.expect(types$1.parenR),canBeArrow&&this.shouldParseArrow(exprList)&&this.eat(types$1.arrow))return this.checkPatternErrors(refDestructuringErrors,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=oldYieldPos,this.awaitPos=oldAwaitPos,this.parseParenArrowList(startPos,startLoc,exprList,forInit);(!exprList.length||lastIsComma)&&this.unexpected(this.lastTokStart),spreadStart&&this.unexpected(spreadStart),this.checkExpressionErrors(refDestructuringErrors,!0),this.yieldPos=oldYieldPos||this.yieldPos,this.awaitPos=oldAwaitPos||this.awaitPos,exprList.length>1?(val=this.startNodeAt(innerStartPos,innerStartLoc),val.expressions=exprList,this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)):val=exprList[0]}else val=this.parseParenExpression();if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);return par.expression=val,this.finishNode(par,"ParenthesizedExpression")}else return val};pp$5.parseParenItem=function(item){return item};pp$5.parseParenArrowList=function(startPos,startLoc,exprList,forInit){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList,!1,forInit)};empty=[];pp$5.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var node=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===types$1.dot){var meta=this.startNodeAt(node.start,node.loc&&node.loc.start);meta.name="new",node.meta=this.finishNode(meta,"Identifier"),this.next();var containsEsc=this.containsEsc;return node.property=this.parseIdent(!0),node.property.name!=="target"&&this.raiseRecoverable(node.property.start,"The only valid meta property for new is 'new.target'"),containsEsc&&this.raiseRecoverable(node.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(node.start,"'new.target' can only be used in functions and class static block"),this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc;return node.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),startPos,startLoc,!0,!1),node.callee.type==="Super"&&this.raiseRecoverable(startPos,"Invalid use of 'super'"),this.eat(types$1.parenL)?node.arguments=this.parseExprList(types$1.parenR,this.options.ecmaVersion>=8,!1):node.arguments=empty,this.finishNode(node,"NewExpression")};pp$5.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged,elem=this.startNode();return this.type===types$1.invalidTemplate?(isTagged||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),elem.value={raw:this.value.replace(/\r\n?/g,`
618
- `),cooked:null}):elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
619
- `),cooked:this.value},this.next(),elem.tail=this.type===types$1.backQuote,this.finishNode(elem,"TemplateElement")};pp$5.parseTemplate=function(ref2){ref2===void 0&&(ref2={});var isTagged=ref2.isTagged;isTagged===void 0&&(isTagged=!1);var node=this.startNode();this.next(),node.expressions=[];var curElt=this.parseTemplateElement({isTagged});for(node.quasis=[curElt];!curElt.tail;)this.type===types$1.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(types$1.dollarBraceL),node.expressions.push(this.parseExpression()),this.expect(types$1.braceR),node.quasis.push(curElt=this.parseTemplateElement({isTagged}));return this.next(),this.finishNode(node,"TemplateLiteral")};pp$5.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types$1.name||this.type===types$1.num||this.type===types$1.string||this.type===types$1.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types$1.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$5.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=!0,propHash={};for(node.properties=[],this.next();!this.eat(types$1.braceR);){if(first)first=!1;else if(this.expect(types$1.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(types$1.braceR))break;var prop=this.parseProperty(isPattern,refDestructuringErrors);isPattern||this.checkPropClash(prop,propHash,refDestructuringErrors),node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$5.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types$1.ellipsis))return isPattern?(prop.argument=this.parseIdent(!1),this.type===types$1.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(prop,"RestElement")):(prop.argument=this.parseMaybeAssign(!1,refDestructuringErrors),this.type===types$1.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0&&(refDestructuringErrors.trailingComma=this.start),this.finishNode(prop,"SpreadElement"));this.options.ecmaVersion>=6&&(prop.method=!1,prop.shorthand=!1,(isPattern||refDestructuringErrors)&&(startPos=this.start,startLoc=this.startLoc),isPattern||(isGenerator=this.eat(types$1.star)));var containsEsc=this.containsEsc;return this.parsePropertyName(prop),!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)?(isAsync=!0,isGenerator=this.options.ecmaVersion>=9&&this.eat(types$1.star),this.parsePropertyName(prop)):isAsync=!1,this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc),this.finishNode(prop,"Property")};pp$5.parseGetterSetter=function(prop){var kind=prop.key.name;this.parsePropertyName(prop),prop.value=this.parseMethod(!1),prop.kind=kind;var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;prop.kind==="get"?this.raiseRecoverable(start,"getter should have no params"):this.raiseRecoverable(start,"setter should have exactly one param")}else prop.kind==="set"&&prop.value.params[0].type==="RestElement"&&this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")};pp$5.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){(isGenerator||isAsync)&&this.type===types$1.colon&&this.unexpected(),this.eat(types$1.colon)?(prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,refDestructuringErrors),prop.kind="init"):this.options.ecmaVersion>=6&&this.type===types$1.parenL?(isPattern&&this.unexpected(),prop.method=!0,prop.value=this.parseMethod(isGenerator,isAsync),prop.kind="init"):!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&this.type!==types$1.comma&&this.type!==types$1.braceR&&this.type!==types$1.eq?((isGenerator||isAsync)&&this.unexpected(),this.parseGetterSetter(prop)):this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"?((isGenerator||isAsync)&&this.unexpected(),this.checkUnreserved(prop.key),prop.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=startPos),isPattern?prop.value=this.parseMaybeDefault(startPos,startLoc,this.copyNode(prop.key)):this.type===types$1.eq&&refDestructuringErrors?(refDestructuringErrors.shorthandAssign<0&&(refDestructuringErrors.shorthandAssign=this.start),prop.value=this.parseMaybeDefault(startPos,startLoc,this.copyNode(prop.key))):prop.value=this.copyNode(prop.key),prop.kind="init",prop.shorthand=!0):this.unexpected()};pp$5.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types$1.bracketL))return prop.computed=!0,prop.key=this.parseMaybeAssign(),this.expect(types$1.bracketR),prop.key;prop.computed=!1}return prop.key=this.type===types$1.num||this.type===types$1.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$5.initFunction=function(node){node.id=null,this.options.ecmaVersion>=6&&(node.generator=node.expression=!1),this.options.ecmaVersion>=8&&(node.async=!1)};pp$5.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;return this.initFunction(node),this.options.ecmaVersion>=6&&(node.generator=isGenerator),this.options.ecmaVersion>=8&&(node.async=!!isAsync),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0)),this.expect(types$1.parenL),node.params=this.parseBindingList(types$1.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(node,!1,!0,!1),this.yieldPos=oldYieldPos,this.awaitPos=oldAwaitPos,this.awaitIdentPos=oldAwaitIdentPos,this.finishNode(node,"FunctionExpression")};pp$5.parseArrowExpression=function(node,params,isAsync,forInit){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;return this.enterScope(functionFlags(isAsync,!1)|SCOPE_ARROW),this.initFunction(node),this.options.ecmaVersion>=8&&(node.async=!!isAsync),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,node.params=this.toAssignableList(params,!0),this.parseFunctionBody(node,!0,!1,forInit),this.yieldPos=oldYieldPos,this.awaitPos=oldAwaitPos,this.awaitIdentPos=oldAwaitIdentPos,this.finishNode(node,"ArrowFunctionExpression")};pp$5.parseFunctionBody=function(node,isArrowFunction,isMethod,forInit){var isExpression=isArrowFunction&&this.type!==types$1.braceL,oldStrict=this.strict,useStrict=!1;if(isExpression)node.body=this.parseMaybeAssign(forInit),node.expression=!0,this.checkParams(node,!1);else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);(!oldStrict||nonSimple)&&(useStrict=this.strictDirective(this.end),useStrict&&nonSimple&&this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var oldLabels=this.labels;this.labels=[],useStrict&&(this.strict=!0),this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params)),this.strict&&node.id&&this.checkLValSimple(node.id,BIND_OUTSIDE),node.body=this.parseBlock(!1,void 0,useStrict&&!oldStrict),node.expression=!1,this.adaptDirectivePrologue(node.body.body),this.labels=oldLabels}this.exitScope()};pp$5.isSimpleParamList=function(params){for(var i2=0,list2=params;i2<list2.length;i2+=1){var param=list2[i2];if(param.type!=="Identifier")return!1}return!0};pp$5.checkParams=function(node,allowDuplicates){for(var nameHash=Object.create(null),i2=0,list2=node.params;i2<list2.length;i2+=1){var param=list2[i2];this.checkLValInnerPattern(param,BIND_VAR,allowDuplicates?null:nameHash)}};pp$5.parseExprList=function(close,allowTrailingComma,allowEmpty,refDestructuringErrors){for(var elts=[],first=!0;!this.eat(close);){if(first)first=!1;else if(this.expect(types$1.comma),allowTrailingComma&&this.afterTrailingComma(close))break;var elt=void 0;allowEmpty&&this.type===types$1.comma?elt=null:this.type===types$1.ellipsis?(elt=this.parseSpread(refDestructuringErrors),refDestructuringErrors&&this.type===types$1.comma&&refDestructuringErrors.trailingComma<0&&(refDestructuringErrors.trailingComma=this.start)):elt=this.parseMaybeAssign(!1,refDestructuringErrors),elts.push(elt)}return elts};pp$5.checkUnreserved=function(ref2){var start=ref2.start,end=ref2.end,name=ref2.name;if(this.inGenerator&&name==="yield"&&this.raiseRecoverable(start,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&name==="await"&&this.raiseRecoverable(start,"Cannot use 'await' as identifier inside an async function"),!(this.currentThisScope().flags&SCOPE_VAR)&&name==="arguments"&&this.raiseRecoverable(start,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&(name==="arguments"||name==="await")&&this.raise(start,"Cannot use "+name+" in class static initialization block"),this.keywords.test(name)&&this.raise(start,"Unexpected keyword '"+name+"'"),!(this.options.ecmaVersion<6&&this.input.slice(start,end).indexOf("\\")!==-1)){var re=this.strict?this.reservedWordsStrict:this.reservedWords;re.test(name)&&(!this.inAsync&&name==="await"&&this.raiseRecoverable(start,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(start,"The keyword '"+name+"' is reserved"))}};pp$5.parseIdent=function(liberal){var node=this.parseIdentNode();return this.next(!!liberal),this.finishNode(node,"Identifier"),liberal||(this.checkUnreserved(node),node.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=node.start)),node};pp$5.parseIdentNode=function(){var node=this.startNode();return this.type===types$1.name?node.name=this.value:this.type.keyword?(node.name=this.type.keyword,(node.name==="class"||node.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=types$1.name):this.unexpected(),node};pp$5.parsePrivateIdent=function(){var node=this.startNode();return this.type===types$1.privateId?node.name=this.value:this.unexpected(),this.next(),this.finishNode(node,"PrivateIdentifier"),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(node.start,"Private field '#"+node.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(node)),node};pp$5.parseYield=function(forInit){this.yieldPos||(this.yieldPos=this.start);var node=this.startNode();return this.next(),this.type===types$1.semi||this.canInsertSemicolon()||this.type!==types$1.star&&!this.type.startsExpr?(node.delegate=!1,node.argument=null):(node.delegate=this.eat(types$1.star),node.argument=this.parseMaybeAssign(forInit)),this.finishNode(node,"YieldExpression")};pp$5.parseAwait=function(forInit){this.awaitPos||(this.awaitPos=this.start);var node=this.startNode();return this.next(),node.argument=this.parseMaybeUnary(null,!0,!1,forInit),this.finishNode(node,"AwaitExpression")};pp$4=Parser.prototype;pp$4.raise=function(pos,message){var loc=getLineInfo(this.input,pos);message+=" ("+loc.line+":"+loc.column+")",this.sourceFile&&(message+=" in "+this.sourceFile);var err=new SyntaxError(message);throw err.pos=pos,err.loc=loc,err.raisedAt=this.pos,err};pp$4.raiseRecoverable=pp$4.raise;pp$4.curPosition=function(){if(this.options.locations)return new Position(this.curLine,this.pos-this.lineStart)};pp$3=Parser.prototype,Scope=function(flags){this.flags=flags,this.var=[],this.lexical=[],this.functions=[]};pp$3.enterScope=function(flags){this.scopeStack.push(new Scope(flags))};pp$3.exitScope=function(){this.scopeStack.pop()};pp$3.treatFunctionsAsVarInScope=function(scope){return scope.flags&SCOPE_FUNCTION||!this.inModule&&scope.flags&SCOPE_TOP};pp$3.declareName=function(name,bindingType,pos){var redeclared=!1;if(bindingType===BIND_LEXICAL){var scope=this.currentScope();redeclared=scope.lexical.indexOf(name)>-1||scope.functions.indexOf(name)>-1||scope.var.indexOf(name)>-1,scope.lexical.push(name),this.inModule&&scope.flags&SCOPE_TOP&&delete this.undefinedExports[name]}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();this.treatFunctionsAsVar?redeclared=scope$2.lexical.indexOf(name)>-1:redeclared=scope$2.lexical.indexOf(name)>-1||scope$2.var.indexOf(name)>-1,scope$2.functions.push(name)}else for(var i2=this.scopeStack.length-1;i2>=0;--i2){var scope$3=this.scopeStack[i2];if(scope$3.lexical.indexOf(name)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name)>-1){redeclared=!0;break}if(scope$3.var.push(name),this.inModule&&scope$3.flags&SCOPE_TOP&&delete this.undefinedExports[name],scope$3.flags&SCOPE_VAR)break}redeclared&&this.raiseRecoverable(pos,"Identifier '"+name+"' has already been declared")};pp$3.checkLocalExport=function(id){this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1&&(this.undefinedExports[id.name]=id)};pp$3.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$3.currentVarScope=function(){for(var i2=this.scopeStack.length-1;;i2--){var scope=this.scopeStack[i2];if(scope.flags&(SCOPE_VAR|SCOPE_CLASS_FIELD_INIT|SCOPE_CLASS_STATIC_BLOCK))return scope}};pp$3.currentThisScope=function(){for(var i2=this.scopeStack.length-1;;i2--){var scope=this.scopeStack[i2];if(scope.flags&(SCOPE_VAR|SCOPE_CLASS_FIELD_INIT|SCOPE_CLASS_STATIC_BLOCK)&&!(scope.flags&SCOPE_ARROW))return scope}};Node2=function(parser,pos,loc){this.type="",this.start=pos,this.end=0,parser.options.locations&&(this.loc=new SourceLocation(parser,loc)),parser.options.directSourceFile&&(this.sourceFile=parser.options.directSourceFile),parser.options.ranges&&(this.range=[pos,0])},pp$2=Parser.prototype;pp$2.startNode=function(){return new Node2(this,this.start,this.startLoc)};pp$2.startNodeAt=function(pos,loc){return new Node2(this,pos,loc)};pp$2.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$2.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};pp$2.copyNode=function(node){var newNode=new Node2(this,node.start,this.startLoc);for(var prop in node)newNode[prop]=node[prop];return newNode};scriptValuesAddedInUnicode="Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz",ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic",ecma11BinaryProperties=ecma10BinaryProperties,ecma12BinaryProperties=ecma11BinaryProperties+" EBase EComp EMod EPres ExtPict",ecma13BinaryProperties=ecma12BinaryProperties,ecma14BinaryProperties=ecma13BinaryProperties,unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties,12:ecma12BinaryProperties,13:ecma13BinaryProperties,14:ecma14BinaryProperties},ecma14BinaryPropertiesOfStrings="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",unicodeBinaryPropertiesOfStrings={9:"",10:"",11:"",12:"",13:"",14:ecma14BinaryPropertiesOfStrings},unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",ecma9ScriptValues="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",ecma12ScriptValues=ecma11ScriptValues+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",ecma13ScriptValues=ecma12ScriptValues+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",ecma14ScriptValues=ecma13ScriptValues+" "+scriptValuesAddedInUnicode,unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues,12:ecma12ScriptValues,13:ecma13ScriptValues,14:ecma14ScriptValues},data={};for(i=0,list=[9,10,11,12,13,14];i<list.length;i+=1)ecmaVersion=list[i],buildUnicodeData(ecmaVersion);pp$1=Parser.prototype,BranchID=function(parent,base){this.parent=parent,this.base=base||this};BranchID.prototype.separatedFrom=function(alt){for(var self=this;self;self=self.parent)for(var other=alt;other;other=other.parent)if(self.base===other.base&&self!==other)return!0;return!1};BranchID.prototype.sibling=function(){return new BranchID(this.parent,this.base)};RegExpValidationState=function(parser){this.parser=parser,this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"")+(parser.options.ecmaVersion>=13?"d":"")+(parser.options.ecmaVersion>=15?"v":""),this.unicodeProperties=data[parser.options.ecmaVersion>=14?14:parser.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};RegExpValidationState.prototype.reset=function(start,pattern2,flags){var unicodeSets=flags.indexOf("v")!==-1,unicode=flags.indexOf("u")!==-1;this.start=start|0,this.source=pattern2+"",this.flags=flags,unicodeSets&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=unicode&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=unicode&&this.parser.options.ecmaVersion>=9)};RegExpValidationState.prototype.raise=function(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function(i2,forceU){forceU===void 0&&(forceU=!1);var s=this.source,l=s.length;if(i2>=l)return-1;var c=s.charCodeAt(i2);if(!(forceU||this.switchU)||c<=55295||c>=57344||i2+1>=l)return c;var next=s.charCodeAt(i2+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function(i2,forceU){forceU===void 0&&(forceU=!1);var s=this.source,l=s.length;if(i2>=l)return l;var c=s.charCodeAt(i2),next;return!(forceU||this.switchU)||c<=55295||c>=57344||i2+1>=l||(next=s.charCodeAt(i2+1))<56320||next>57343?i2+1:i2+2};RegExpValidationState.prototype.current=function(forceU){return forceU===void 0&&(forceU=!1),this.at(this.pos,forceU)};RegExpValidationState.prototype.lookahead=function(forceU){return forceU===void 0&&(forceU=!1),this.at(this.nextIndex(this.pos,forceU),forceU)};RegExpValidationState.prototype.advance=function(forceU){forceU===void 0&&(forceU=!1),this.pos=this.nextIndex(this.pos,forceU)};RegExpValidationState.prototype.eat=function(ch,forceU){return forceU===void 0&&(forceU=!1),this.current(forceU)===ch?(this.advance(forceU),!0):!1};RegExpValidationState.prototype.eatChars=function(chs,forceU){forceU===void 0&&(forceU=!1);for(var pos=this.pos,i2=0,list2=chs;i2<list2.length;i2+=1){var ch=list2[i2],current2=this.at(pos,forceU);if(current2===-1||current2!==ch)return!1;pos=this.nextIndex(pos,forceU)}return this.pos=pos,!0};pp$1.validateRegExpFlags=function(state){for(var validFlags=state.validFlags,flags=state.flags,u=!1,v=!1,i2=0;i2<flags.length;i2++){var flag=flags.charAt(i2);validFlags.indexOf(flag)===-1&&this.raise(state.start,"Invalid regular expression flag"),flags.indexOf(flag,i2+1)>-1&&this.raise(state.start,"Duplicate regular expression flag"),flag==="u"&&(u=!0),flag==="v"&&(v=!0)}this.options.ecmaVersion>=15&&u&&v&&this.raise(state.start,"Invalid regular expression flag")};pp$1.validateRegExpPattern=function(state){this.regexp_pattern(state),!state.switchN&&this.options.ecmaVersion>=9&&hasProp(state.groupNames)&&(state.switchN=!0,this.regexp_pattern(state))};pp$1.regexp_pattern=function(state){state.pos=0,state.lastIntValue=0,state.lastStringValue="",state.lastAssertionIsQuantifiable=!1,state.numCapturingParens=0,state.maxBackReference=0,state.groupNames=Object.create(null),state.backReferenceNames.length=0,state.branchID=null,this.regexp_disjunction(state),state.pos!==state.source.length&&(state.eat(41)&&state.raise("Unmatched ')'"),(state.eat(93)||state.eat(125))&&state.raise("Lone quantifier brackets")),state.maxBackReference>state.numCapturingParens&&state.raise("Invalid escape");for(var i2=0,list2=state.backReferenceNames;i2<list2.length;i2+=1){var name=list2[i2];state.groupNames[name]||state.raise("Invalid named capture referenced")}};pp$1.regexp_disjunction=function(state){var trackDisjunction=this.options.ecmaVersion>=16;for(trackDisjunction&&(state.branchID=new BranchID(state.branchID,null)),this.regexp_alternative(state);state.eat(124);)trackDisjunction&&(state.branchID=state.branchID.sibling()),this.regexp_alternative(state);trackDisjunction&&(state.branchID=state.branchID.parent),this.regexp_eatQuantifier(state,!0)&&state.raise("Nothing to repeat"),state.eat(123)&&state.raise("Lone quantifier brackets")};pp$1.regexp_alternative=function(state){for(;state.pos<state.source.length&&this.regexp_eatTerm(state););};pp$1.regexp_eatTerm=function(state){return this.regexp_eatAssertion(state)?(state.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(state)&&state.switchU&&state.raise("Invalid quantifier"),!0):(state.switchU?this.regexp_eatAtom(state):this.regexp_eatExtendedAtom(state))?(this.regexp_eatQuantifier(state),!0):!1};pp$1.regexp_eatAssertion=function(state){var start=state.pos;if(state.lastAssertionIsQuantifiable=!1,state.eat(94)||state.eat(36))return!0;if(state.eat(92)){if(state.eat(66)||state.eat(98))return!0;state.pos=start}if(state.eat(40)&&state.eat(63)){var lookbehind=!1;if(this.options.ecmaVersion>=9&&(lookbehind=state.eat(60)),state.eat(61)||state.eat(33))return this.regexp_disjunction(state),state.eat(41)||state.raise("Unterminated group"),state.lastAssertionIsQuantifiable=!lookbehind,!0}return state.pos=start,!1};pp$1.regexp_eatQuantifier=function(state,noError){return noError===void 0&&(noError=!1),this.regexp_eatQuantifierPrefix(state,noError)?(state.eat(63),!0):!1};pp$1.regexp_eatQuantifierPrefix=function(state,noError){return state.eat(42)||state.eat(43)||state.eat(63)||this.regexp_eatBracedQuantifier(state,noError)};pp$1.regexp_eatBracedQuantifier=function(state,noError){var start=state.pos;if(state.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state)&&(min=state.lastIntValue,state.eat(44)&&this.regexp_eatDecimalDigits(state)&&(max=state.lastIntValue),state.eat(125)))return max!==-1&&max<min&&!noError&&state.raise("numbers out of order in {} quantifier"),!0;state.switchU&&!noError&&state.raise("Incomplete quantifier"),state.pos=start}return!1};pp$1.regexp_eatAtom=function(state){return this.regexp_eatPatternCharacters(state)||state.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)};pp$1.regexp_eatReverseSolidusAtomEscape=function(state){var start=state.pos;if(state.eat(92)){if(this.regexp_eatAtomEscape(state))return!0;state.pos=start}return!1};pp$1.regexp_eatUncapturingGroup=function(state){var start=state.pos;if(state.eat(40)){if(state.eat(63)){if(this.options.ecmaVersion>=16){var addModifiers=this.regexp_eatModifiers(state),hasHyphen=state.eat(45);if(addModifiers||hasHyphen){for(var i2=0;i2<addModifiers.length;i2++){var modifier=addModifiers.charAt(i2);addModifiers.indexOf(modifier,i2+1)>-1&&state.raise("Duplicate regular expression modifiers")}if(hasHyphen){var removeModifiers=this.regexp_eatModifiers(state);!addModifiers&&!removeModifiers&&state.current()===58&&state.raise("Invalid regular expression modifiers");for(var i$1=0;i$1<removeModifiers.length;i$1++){var modifier$1=removeModifiers.charAt(i$1);(removeModifiers.indexOf(modifier$1,i$1+1)>-1||addModifiers.indexOf(modifier$1)>-1)&&state.raise("Duplicate regular expression modifiers")}}}}if(state.eat(58)){if(this.regexp_disjunction(state),state.eat(41))return!0;state.raise("Unterminated group")}}state.pos=start}return!1};pp$1.regexp_eatCapturingGroup=function(state){if(state.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(state):state.current()===63&&state.raise("Invalid group"),this.regexp_disjunction(state),state.eat(41))return state.numCapturingParens+=1,!0;state.raise("Unterminated group")}return!1};pp$1.regexp_eatModifiers=function(state){for(var modifiers="",ch=0;(ch=state.current())!==-1&&isRegularExpressionModifier(ch);)modifiers+=codePointToString(ch),state.advance();return modifiers};pp$1.regexp_eatExtendedAtom=function(state){return state.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)||this.regexp_eatInvalidBracedQuantifier(state)||this.regexp_eatExtendedPatternCharacter(state)};pp$1.regexp_eatInvalidBracedQuantifier=function(state){return this.regexp_eatBracedQuantifier(state,!0)&&state.raise("Nothing to repeat"),!1};pp$1.regexp_eatSyntaxCharacter=function(state){var ch=state.current();return isSyntaxCharacter(ch)?(state.lastIntValue=ch,state.advance(),!0):!1};pp$1.regexp_eatPatternCharacters=function(state){for(var start=state.pos,ch=0;(ch=state.current())!==-1&&!isSyntaxCharacter(ch);)state.advance();return state.pos!==start};pp$1.regexp_eatExtendedPatternCharacter=function(state){var ch=state.current();return ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124?(state.advance(),!0):!1};pp$1.regexp_groupSpecifier=function(state){if(state.eat(63)){this.regexp_eatGroupName(state)||state.raise("Invalid group");var trackDisjunction=this.options.ecmaVersion>=16,known=state.groupNames[state.lastStringValue];if(known)if(trackDisjunction)for(var i2=0,list2=known;i2<list2.length;i2+=1){var altID=list2[i2];altID.separatedFrom(state.branchID)||state.raise("Duplicate capture group name")}else state.raise("Duplicate capture group name");trackDisjunction?(known||(state.groupNames[state.lastStringValue]=[])).push(state.branchID):state.groupNames[state.lastStringValue]=!0}};pp$1.regexp_eatGroupName=function(state){if(state.lastStringValue="",state.eat(60)){if(this.regexp_eatRegExpIdentifierName(state)&&state.eat(62))return!0;state.raise("Invalid capture group name")}return!1};pp$1.regexp_eatRegExpIdentifierName=function(state){if(state.lastStringValue="",this.regexp_eatRegExpIdentifierStart(state)){for(state.lastStringValue+=codePointToString(state.lastIntValue);this.regexp_eatRegExpIdentifierPart(state);)state.lastStringValue+=codePointToString(state.lastIntValue);return!0}return!1};pp$1.regexp_eatRegExpIdentifierStart=function(state){var start=state.pos,forceU=this.options.ecmaVersion>=11,ch=state.current(forceU);return state.advance(forceU),ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state,forceU)&&(ch=state.lastIntValue),isRegExpIdentifierStart(ch)?(state.lastIntValue=ch,!0):(state.pos=start,!1)};pp$1.regexp_eatRegExpIdentifierPart=function(state){var start=state.pos,forceU=this.options.ecmaVersion>=11,ch=state.current(forceU);return state.advance(forceU),ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state,forceU)&&(ch=state.lastIntValue),isRegExpIdentifierPart(ch)?(state.lastIntValue=ch,!0):(state.pos=start,!1)};pp$1.regexp_eatAtomEscape=function(state){return this.regexp_eatBackReference(state)||this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)||state.switchN&&this.regexp_eatKGroupName(state)?!0:(state.switchU&&(state.current()===99&&state.raise("Invalid unicode escape"),state.raise("Invalid escape")),!1)};pp$1.regexp_eatBackReference=function(state){var start=state.pos;if(this.regexp_eatDecimalEscape(state)){var n=state.lastIntValue;if(state.switchU)return n>state.maxBackReference&&(state.maxBackReference=n),!0;if(n<=state.numCapturingParens)return!0;state.pos=start}return!1};pp$1.regexp_eatKGroupName=function(state){if(state.eat(107)){if(this.regexp_eatGroupName(state))return state.backReferenceNames.push(state.lastStringValue),!0;state.raise("Invalid named reference")}return!1};pp$1.regexp_eatCharacterEscape=function(state){return this.regexp_eatControlEscape(state)||this.regexp_eatCControlLetter(state)||this.regexp_eatZero(state)||this.regexp_eatHexEscapeSequence(state)||this.regexp_eatRegExpUnicodeEscapeSequence(state,!1)||!state.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state)||this.regexp_eatIdentityEscape(state)};pp$1.regexp_eatCControlLetter=function(state){var start=state.pos;if(state.eat(99)){if(this.regexp_eatControlLetter(state))return!0;state.pos=start}return!1};pp$1.regexp_eatZero=function(state){return state.current()===48&&!isDecimalDigit(state.lookahead())?(state.lastIntValue=0,state.advance(),!0):!1};pp$1.regexp_eatControlEscape=function(state){var ch=state.current();return ch===116?(state.lastIntValue=9,state.advance(),!0):ch===110?(state.lastIntValue=10,state.advance(),!0):ch===118?(state.lastIntValue=11,state.advance(),!0):ch===102?(state.lastIntValue=12,state.advance(),!0):ch===114?(state.lastIntValue=13,state.advance(),!0):!1};pp$1.regexp_eatControlLetter=function(state){var ch=state.current();return isControlLetter(ch)?(state.lastIntValue=ch%32,state.advance(),!0):!1};pp$1.regexp_eatRegExpUnicodeEscapeSequence=function(state,forceU){forceU===void 0&&(forceU=!1);var start=state.pos,switchU=forceU||state.switchU;if(state.eat(117)){if(this.regexp_eatFixedHexDigits(state,4)){var lead=state.lastIntValue;if(switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state.pos;if(state.eat(92)&&state.eat(117)&&this.regexp_eatFixedHexDigits(state,4)){var trail=state.lastIntValue;if(trail>=56320&&trail<=57343)return state.lastIntValue=(lead-55296)*1024+(trail-56320)+65536,!0}state.pos=leadSurrogateEnd,state.lastIntValue=lead}return!0}if(switchU&&state.eat(123)&&this.regexp_eatHexDigits(state)&&state.eat(125)&&isValidUnicode(state.lastIntValue))return!0;switchU&&state.raise("Invalid unicode escape"),state.pos=start}return!1};pp$1.regexp_eatIdentityEscape=function(state){if(state.switchU)return this.regexp_eatSyntaxCharacter(state)?!0:state.eat(47)?(state.lastIntValue=47,!0):!1;var ch=state.current();return ch!==99&&(!state.switchN||ch!==107)?(state.lastIntValue=ch,state.advance(),!0):!1};pp$1.regexp_eatDecimalEscape=function(state){state.lastIntValue=0;var ch=state.current();if(ch>=49&&ch<=57){do state.lastIntValue=10*state.lastIntValue+(ch-48),state.advance();while((ch=state.current())>=48&&ch<=57);return!0}return!1};CharSetNone=0,CharSetOk=1,CharSetString=2;pp$1.regexp_eatCharacterClassEscape=function(state){var ch=state.current();if(isCharacterClassEscape(ch))return state.lastIntValue=-1,state.advance(),CharSetOk;var negate=!1;if(state.switchU&&this.options.ecmaVersion>=9&&((negate=ch===80)||ch===112)){state.lastIntValue=-1,state.advance();var result;if(state.eat(123)&&(result=this.regexp_eatUnicodePropertyValueExpression(state))&&state.eat(125))return negate&&result===CharSetString&&state.raise("Invalid property name"),result;state.raise("Invalid property name")}return CharSetNone};pp$1.regexp_eatUnicodePropertyValueExpression=function(state){var start=state.pos;if(this.regexp_eatUnicodePropertyName(state)&&state.eat(61)){var name=state.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state)){var value=state.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(state,name,value),CharSetOk}}if(state.pos=start,this.regexp_eatLoneUnicodePropertyNameOrValue(state)){var nameOrValue=state.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(state,nameOrValue)}return CharSetNone};pp$1.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){hasOwn(state.unicodeProperties.nonBinary,name)||state.raise("Invalid property name"),state.unicodeProperties.nonBinary[name].test(value)||state.raise("Invalid property value")};pp$1.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(state.unicodeProperties.binary.test(nameOrValue))return CharSetOk;if(state.switchV&&state.unicodeProperties.binaryOfStrings.test(nameOrValue))return CharSetString;state.raise("Invalid property name")};pp$1.regexp_eatUnicodePropertyName=function(state){var ch=0;for(state.lastStringValue="";isUnicodePropertyNameCharacter(ch=state.current());)state.lastStringValue+=codePointToString(ch),state.advance();return state.lastStringValue!==""};pp$1.regexp_eatUnicodePropertyValue=function(state){var ch=0;for(state.lastStringValue="";isUnicodePropertyValueCharacter(ch=state.current());)state.lastStringValue+=codePointToString(ch),state.advance();return state.lastStringValue!==""};pp$1.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$1.regexp_eatCharacterClass=function(state){if(state.eat(91)){var negate=state.eat(94),result=this.regexp_classContents(state);return state.eat(93)||state.raise("Unterminated character class"),negate&&result===CharSetString&&state.raise("Negated character class may contain strings"),!0}return!1};pp$1.regexp_classContents=function(state){return state.current()===93?CharSetOk:state.switchV?this.regexp_classSetExpression(state):(this.regexp_nonEmptyClassRanges(state),CharSetOk)};pp$1.regexp_nonEmptyClassRanges=function(state){for(;this.regexp_eatClassAtom(state);){var left=state.lastIntValue;if(state.eat(45)&&this.regexp_eatClassAtom(state)){var right=state.lastIntValue;state.switchU&&(left===-1||right===-1)&&state.raise("Invalid character class"),left!==-1&&right!==-1&&left>right&&state.raise("Range out of order in character class")}}};pp$1.regexp_eatClassAtom=function(state){var start=state.pos;if(state.eat(92)){if(this.regexp_eatClassEscape(state))return!0;if(state.switchU){var ch$1=state.current();(ch$1===99||isOctalDigit(ch$1))&&state.raise("Invalid class escape"),state.raise("Invalid escape")}state.pos=start}var ch=state.current();return ch!==93?(state.lastIntValue=ch,state.advance(),!0):!1};pp$1.regexp_eatClassEscape=function(state){var start=state.pos;if(state.eat(98))return state.lastIntValue=8,!0;if(state.switchU&&state.eat(45))return state.lastIntValue=45,!0;if(!state.switchU&&state.eat(99)){if(this.regexp_eatClassControlLetter(state))return!0;state.pos=start}return this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)};pp$1.regexp_classSetExpression=function(state){var result=CharSetOk,subResult;if(!this.regexp_eatClassSetRange(state))if(subResult=this.regexp_eatClassSetOperand(state)){subResult===CharSetString&&(result=CharSetString);for(var start=state.pos;state.eatChars([38,38]);){if(state.current()!==38&&(subResult=this.regexp_eatClassSetOperand(state))){subResult!==CharSetString&&(result=CharSetOk);continue}state.raise("Invalid character in character class")}if(start!==state.pos)return result;for(;state.eatChars([45,45]);)this.regexp_eatClassSetOperand(state)||state.raise("Invalid character in character class");if(start!==state.pos)return result}else state.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(state)){if(subResult=this.regexp_eatClassSetOperand(state),!subResult)return result;subResult===CharSetString&&(result=CharSetString)}};pp$1.regexp_eatClassSetRange=function(state){var start=state.pos;if(this.regexp_eatClassSetCharacter(state)){var left=state.lastIntValue;if(state.eat(45)&&this.regexp_eatClassSetCharacter(state)){var right=state.lastIntValue;return left!==-1&&right!==-1&&left>right&&state.raise("Range out of order in character class"),!0}state.pos=start}return!1};pp$1.regexp_eatClassSetOperand=function(state){return this.regexp_eatClassSetCharacter(state)?CharSetOk:this.regexp_eatClassStringDisjunction(state)||this.regexp_eatNestedClass(state)};pp$1.regexp_eatNestedClass=function(state){var start=state.pos;if(state.eat(91)){var negate=state.eat(94),result=this.regexp_classContents(state);if(state.eat(93))return negate&&result===CharSetString&&state.raise("Negated character class may contain strings"),result;state.pos=start}if(state.eat(92)){var result$1=this.regexp_eatCharacterClassEscape(state);if(result$1)return result$1;state.pos=start}return null};pp$1.regexp_eatClassStringDisjunction=function(state){var start=state.pos;if(state.eatChars([92,113])){if(state.eat(123)){var result=this.regexp_classStringDisjunctionContents(state);if(state.eat(125))return result}else state.raise("Invalid escape");state.pos=start}return null};pp$1.regexp_classStringDisjunctionContents=function(state){for(var result=this.regexp_classString(state);state.eat(124);)this.regexp_classString(state)===CharSetString&&(result=CharSetString);return result};pp$1.regexp_classString=function(state){for(var count=0;this.regexp_eatClassSetCharacter(state);)count++;return count===1?CharSetOk:CharSetString};pp$1.regexp_eatClassSetCharacter=function(state){var start=state.pos;if(state.eat(92))return this.regexp_eatCharacterEscape(state)||this.regexp_eatClassSetReservedPunctuator(state)?!0:state.eat(98)?(state.lastIntValue=8,!0):(state.pos=start,!1);var ch=state.current();return ch<0||ch===state.lookahead()&&isClassSetReservedDoublePunctuatorCharacter(ch)||isClassSetSyntaxCharacter(ch)?!1:(state.advance(),state.lastIntValue=ch,!0)};pp$1.regexp_eatClassSetReservedPunctuator=function(state){var ch=state.current();return isClassSetReservedPunctuator(ch)?(state.lastIntValue=ch,state.advance(),!0):!1};pp$1.regexp_eatClassControlLetter=function(state){var ch=state.current();return isDecimalDigit(ch)||ch===95?(state.lastIntValue=ch%32,state.advance(),!0):!1};pp$1.regexp_eatHexEscapeSequence=function(state){var start=state.pos;if(state.eat(120)){if(this.regexp_eatFixedHexDigits(state,2))return!0;state.switchU&&state.raise("Invalid escape"),state.pos=start}return!1};pp$1.regexp_eatDecimalDigits=function(state){var start=state.pos,ch=0;for(state.lastIntValue=0;isDecimalDigit(ch=state.current());)state.lastIntValue=10*state.lastIntValue+(ch-48),state.advance();return state.pos!==start};pp$1.regexp_eatHexDigits=function(state){var start=state.pos,ch=0;for(state.lastIntValue=0;isHexDigit(ch=state.current());)state.lastIntValue=16*state.lastIntValue+hexToInt(ch),state.advance();return state.pos!==start};pp$1.regexp_eatLegacyOctalEscapeSequence=function(state){if(this.regexp_eatOctalDigit(state)){var n1=state.lastIntValue;if(this.regexp_eatOctalDigit(state)){var n2=state.lastIntValue;n1<=3&&this.regexp_eatOctalDigit(state)?state.lastIntValue=n1*64+n2*8+state.lastIntValue:state.lastIntValue=n1*8+n2}else state.lastIntValue=n1;return!0}return!1};pp$1.regexp_eatOctalDigit=function(state){var ch=state.current();return isOctalDigit(ch)?(state.lastIntValue=ch-48,state.advance(),!0):(state.lastIntValue=0,!1)};pp$1.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i2=0;i2<length;++i2){var ch=state.current();if(!isHexDigit(ch))return state.pos=start,!1;state.lastIntValue=16*state.lastIntValue+hexToInt(ch),state.advance()}return!0};Token=function(p){this.type=p.type,this.value=p.value,this.start=p.start,this.end=p.end,p.options.locations&&(this.loc=new SourceLocation(p,p.startLoc,p.endLoc)),p.options.ranges&&(this.range=[p.start,p.end])},pp=Parser.prototype;pp.next=function(ignoreEscapeSequenceInKeyword){!ignoreEscapeSequenceInKeyword&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new Token(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};pp.getToken=function(){return this.next(),new Token(this)};typeof Symbol<"u"&&(pp[Symbol.iterator]=function(){var this$1$1=this;return{next:function(){var token=this$1$1.getToken();return{done:token.type===types$1.eof,value:token}}}});pp.nextToken=function(){var curContext=this.curContext();if((!curContext||!curContext.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(types$1.eof);if(curContext.override)return curContext.override(this);this.readToken(this.fullCharCodeAtPos())};pp.readToken=function(code){return isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92?this.readWord():this.getTokenFromCode(code)};pp.fullCharCodeAt=function(pos){var code=this.input.charCodeAt(pos);if(code<=55295||code>=56320)return code;var next=this.input.charCodeAt(pos+1);return next<=56319||next>=57344?code:(code<<10)+next-56613888};pp.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};pp.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition(),start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=end+2,this.options.locations)for(var nextBreak=void 0,pos=start;(nextBreak=nextLineBreak(this.input,pos,this.pos))>-1;)++this.curLine,pos=this.lineStart=nextBreak;this.options.onComment&&this.options.onComment(!0,this.input.slice(start+2,end),start,this.pos,startLoc,this.curPosition())};pp.skipLineComment=function(startSkip){for(var start=this.pos,startLoc=this.options.onComment&&this.curPosition(),ch=this.input.charCodeAt(this.pos+=startSkip);this.pos<this.input.length&&!isNewLine(ch);)ch=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(start+startSkip,this.pos),start,this.pos,startLoc,this.curPosition())};pp.skipSpace=function(){loop:for(;this.pos<this.input.length;){var ch=this.input.charCodeAt(this.pos);switch(ch){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break loop}break;default:if(ch>8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch)))++this.pos;else break loop}}};pp.finishToken=function(type,val){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var prevType=this.type;this.type=type,this.value=val,this.updateContext(prevType)};pp.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57)return this.readNumber(!0);var next2=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&next===46&&next2===46?(this.pos+=3,this.finishToken(types$1.ellipsis)):(++this.pos,this.finishToken(types$1.dot))};pp.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):next===61?this.finishOp(types$1.assign,2):this.finishOp(types$1.slash,1)};pp.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1),size=1,tokentype=code===42?types$1.star:types$1.modulo;return this.options.ecmaVersion>=7&&code===42&&next===42&&(++size,tokentype=types$1.starstar,next=this.input.charCodeAt(this.pos+2)),next===61?this.finishOp(types$1.assign,size+1):this.finishOp(tokentype,size)};pp.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(this.options.ecmaVersion>=12){var next2=this.input.charCodeAt(this.pos+2);if(next2===61)return this.finishOp(types$1.assign,3)}return this.finishOp(code===124?types$1.logicalOR:types$1.logicalAND,2)}return next===61?this.finishOp(types$1.assign,2):this.finishOp(code===124?types$1.bitwiseOR:types$1.bitwiseAND,1)};pp.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);return next===61?this.finishOp(types$1.assign,2):this.finishOp(types$1.bitwiseXOR,1)};pp.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);return next===code?next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(types$1.incDec,2):next===61?this.finishOp(types$1.assign,2):this.finishOp(types$1.plusMin,1)};pp.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1),size=1;return next===code?(size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+size)===61?this.finishOp(types$1.assign,size+1):this.finishOp(types$1.bitShift,size)):next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(next===61&&(size=2),this.finishOp(types$1.relational,size))};pp.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);return next===61?this.finishOp(types$1.equality,this.input.charCodeAt(this.pos+2)===61?3:2):code===61&&next===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(types$1.arrow)):this.finishOp(code===61?types$1.eq:types$1.prefix,1)};pp.readToken_question=function(){var ecmaVersion2=this.options.ecmaVersion;if(ecmaVersion2>=11){var next=this.input.charCodeAt(this.pos+1);if(next===46){var next2=this.input.charCodeAt(this.pos+2);if(next2<48||next2>57)return this.finishOp(types$1.questionDot,2)}if(next===63){if(ecmaVersion2>=12){var next2$1=this.input.charCodeAt(this.pos+2);if(next2$1===61)return this.finishOp(types$1.assign,3)}return this.finishOp(types$1.coalesce,2)}}return this.finishOp(types$1.question,1)};pp.readToken_numberSign=function(){var ecmaVersion2=this.options.ecmaVersion,code=35;if(ecmaVersion2>=13&&(++this.pos,code=this.fullCharCodeAtPos(),isIdentifierStart(code,!0)||code===92))return this.finishToken(types$1.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'")};pp.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(types$1.parenL);case 41:return++this.pos,this.finishToken(types$1.parenR);case 59:return++this.pos,this.finishToken(types$1.semi);case 44:return++this.pos,this.finishToken(types$1.comma);case 91:return++this.pos,this.finishToken(types$1.bracketL);case 93:return++this.pos,this.finishToken(types$1.bracketR);case 123:return++this.pos,this.finishToken(types$1.braceL);case 125:return++this.pos,this.finishToken(types$1.braceR);case 58:return++this.pos,this.finishToken(types$1.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(types$1.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(next===111||next===79)return this.readRadixNumber(8);if(next===98||next===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 63:return this.readToken_question();case 126:return this.finishOp(types$1.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'")};pp.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);return this.pos+=size,this.finishToken(type,str)};pp.readRegexp=function(){for(var escaped,inClass,start=this.pos;;){this.pos>=this.input.length&&this.raise(start,"Unterminated regular expression");var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)&&this.raise(start,"Unterminated regular expression"),escaped)escaped=!1;else{if(ch==="[")inClass=!0;else if(ch==="]"&&inClass)inClass=!1;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}++this.pos}var pattern2=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos,flags=this.readWord1();this.containsEsc&&this.unexpected(flagsStart);var state=this.regexpState||(this.regexpState=new RegExpValidationState(this));state.reset(start,pattern2,flags),this.validateRegExpFlags(state),this.validateRegExpPattern(state);var value=null;try{value=new RegExp(pattern2,flags)}catch{}return this.finishToken(types$1.regexp,{pattern:pattern2,flags,value})};pp.readInt=function(radix,len,maybeLegacyOctalNumericLiteral){for(var allowSeparators=this.options.ecmaVersion>=12&&len===void 0,isLegacyOctalNumericLiteral=maybeLegacyOctalNumericLiteral&&this.input.charCodeAt(this.pos)===48,start=this.pos,total=0,lastCode=0,i2=0,e=len??1/0;i2<e;++i2,++this.pos){var code=this.input.charCodeAt(this.pos),val=void 0;if(allowSeparators&&code===95){isLegacyOctalNumericLiteral&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),lastCode===95&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),i2===0&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),lastCode=code;continue}if(code>=97?val=code-97+10:code>=65?val=code-65+10:code>=48&&code<=57?val=code-48:val=1/0,val>=radix)break;lastCode=code,total=total*radix+val}return allowSeparators&&lastCode===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===start||len!=null&&this.pos-start!==len?null:total};pp.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);return val==null&&this.raise(this.start+2,"Expected number in radix "+radix),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(val=stringToBigInt(this.input.slice(start,this.pos)),++this.pos):isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(types$1.num,val)};pp.readNumber=function(startsWithDot){var start=this.pos;!startsWithDot&&this.readInt(10,void 0,!0)===null&&this.raise(start,"Invalid number");var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;octal&&this.strict&&this.raise(start,"Invalid number");var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var val$1=stringToBigInt(this.input.slice(start,this.pos));return++this.pos,isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(types$1.num,val$1)}octal&&/[89]/.test(this.input.slice(start,this.pos))&&(octal=!1),next===46&&!octal&&(++this.pos,this.readInt(10),next=this.input.charCodeAt(this.pos)),(next===69||next===101)&&!octal&&(next=this.input.charCodeAt(++this.pos),(next===43||next===45)&&++this.pos,this.readInt(10)===null&&this.raise(start,"Invalid number")),isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var val=stringToNumber(this.input.slice(start,this.pos),octal);return this.finishToken(types$1.num,val)};pp.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){this.options.ecmaVersion<6&&this.unexpected();var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,code>1114111&&this.invalidStringToken(codePos,"Code point out of bounds")}else code=this.readHexChar(4);return code};pp.readString=function(quote){for(var out="",chunkStart=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var ch=this.input.charCodeAt(this.pos);if(ch===quote)break;ch===92?(out+=this.input.slice(chunkStart,this.pos),out+=this.readEscapedChar(!1),chunkStart=this.pos):ch===8232||ch===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(isNewLine(ch)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return out+=this.input.slice(chunkStart,this.pos++),this.finishToken(types$1.string,out)};INVALID_TEMPLATE_ESCAPE_ERROR={};pp.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR)this.readInvalidTemplateToken();else throw err}this.inTemplateElement=!1};pp.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw INVALID_TEMPLATE_ESCAPE_ERROR;this.raise(position,message)};pp.readTmplToken=function(){for(var out="",chunkStart=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===types$1.template||this.type===types$1.invalidTemplate)?ch===36?(this.pos+=2,this.finishToken(types$1.dollarBraceL)):(++this.pos,this.finishToken(types$1.backQuote)):(out+=this.input.slice(chunkStart,this.pos),this.finishToken(types$1.template,out));if(ch===92)out+=this.input.slice(chunkStart,this.pos),out+=this.readEscapedChar(!0),chunkStart=this.pos;else if(isNewLine(ch)){switch(out+=this.input.slice(chunkStart,this.pos),++this.pos,ch){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:out+=`
620
- `;break;default:out+=String.fromCharCode(ch);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),chunkStart=this.pos}else++this.pos}};pp.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if(this.input[this.pos+1]!=="{")break;case"`":return this.finishToken(types$1.invalidTemplate,this.input.slice(this.start,this.pos));case"\r":this.input[this.pos+1]===`
621
- `&&++this.pos;case`
622
- `:case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1;break}this.raise(this.start,"Unterminated template")};pp.readEscapedChar=function(inTemplate){var ch=this.input.charCodeAt(++this.pos);switch(++this.pos,ch){case 110:return`
623
- `;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return codePointToString(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),inTemplate){var codePos=this.pos-1;this.invalidStringToken(codePos,"Invalid escape sequence in template string")}default:if(ch>=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],octal=parseInt(octalStr,8);return octal>255&&(octalStr=octalStr.slice(0,-1),octal=parseInt(octalStr,8)),this.pos+=octalStr.length-1,ch=this.input.charCodeAt(this.pos),(octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)&&this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(octal)}return isNewLine(ch)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(ch)}};pp.readHexChar=function(len){var codePos=this.pos,n=this.readInt(16,len);return n===null&&this.invalidStringToken(codePos,"Bad character escape sequence"),n};pp.readWord1=function(){this.containsEsc=!1;for(var word="",first=!0,chunkStart=this.pos,astral=this.options.ecmaVersion>=6;this.pos<this.input.length;){var ch=this.fullCharCodeAtPos();if(isIdentifierChar(ch,astral))this.pos+=ch<=65535?1:2;else if(ch===92){this.containsEsc=!0,word+=this.input.slice(chunkStart,this.pos);var escStart=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var esc=this.readCodePoint();(first?isIdentifierStart:isIdentifierChar)(esc,astral)||this.invalidStringToken(escStart,"Invalid Unicode escape"),word+=codePointToString(esc),chunkStart=this.pos}else break;first=!1}return word+this.input.slice(chunkStart,this.pos)};pp.readWord=function(){var word=this.readWord1(),type=types$1.name;return this.keywords.test(word)&&(type=keywords[word]),this.finishToken(type,word)};version="8.19.0";Parser.acorn={Parser,version,defaultOptions,Position,SourceLocation,getLineInfo,Node:Node2,TokenType,tokTypes:types$1,keywordTypes:keywords,TokContext,tokContexts:types,isIdentifierChar,isIdentifierStart,Token,isNewLine,lineBreak,lineBreakG,nonASCIIwhitespace}}});import{existsSync as existsSync3,lstatSync,readFileSync as readFileSync7,renameSync as renameSync4,statSync as statSync5}from"node:fs";import{join as join8}from"node:path";function readInstalledSkillMetadata(directory){if(existsSync3(join8(directory,"SKILL.md"))&&existsSync3(join8(directory,DISABLED_SKILL_MANIFEST)))throw new Error("Conflicting installed Skill manifests");let file=skillManifestPath(directory);if(!file)return;let info=statSync5(file);if(!info.isFile()||info.size>1024*1024)throw new Error("Invalid installed Skill manifest");let frontmatter=readFileSync7(file,"utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];if(!frontmatter)return{};let scalar=key2=>{let lines=frontmatter.split(/\r?\n/).filter(line=>line.startsWith(key2+":"));if(lines.length===1)return lines[0].match(/^[\w-]+:\s*(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s#"']+))\s*(?:#.*)?$/)?.slice(1).find(value=>value!==void 0)};return{name:scalar("name"),version:scalar("version")}}function skillManifestPath(directory){for(let name of["SKILL.md",DISABLED_SKILL_MANIFEST]){let file=join8(directory,name);if(existsSync3(file))return file}}var DISABLED_SKILL_MANIFEST,init_skillManifest=__esm({"../client/src/plugins/skillManifest.ts"(){"use strict";DISABLED_SKILL_MANIFEST="SKILL.md.mearl-disabled"}});import{randomUUID as randomUUID5}from"node:crypto";import{closeSync as closeSync4,fsyncSync,mkdirSync as mkdirSync5,openSync as openSync4,renameSync as renameSync6,rmSync as rmSync6,writeFileSync as writeFileSync5}from"node:fs";import{dirname as dirname5}from"node:path";function writePluginHostFile(file,data2){mkdirSync5(dirname5(file),{recursive:!0,mode:448});let temporary=`${file}.${randomUUID5()}.tmp`,descriptor;try{descriptor=openSync4(temporary,"wx",384),writeFileSync5(descriptor,data2),fsyncSync(descriptor),closeSync4(descriptor),descriptor=void 0,renameSync6(temporary,file)}finally{descriptor!==void 0&&closeSync4(descriptor),rmSync6(temporary,{force:!0})}}var init_pluginHostFiles=__esm({"../client/src/plugins/runtime/pluginHostFiles.ts"(){"use strict"}});import{createHash as createHash7}from"node:crypto";import{closeSync as closeSync5,openSync as openSync5,opendirSync,readFileSync as readFileSync9,readSync as readSync2,readdirSync as readdirSync6,rmSync as rmSync7,statSync as statSync7}from"node:fs";import{join as join10}from"node:path";function pluginTaskExecutionUnconfirmed(record2){let owner=record2.executorOwner;return owner&&(!Number.isSafeInteger(owner.pid)||owner.pid<1)||owner&&isProcessOwnerAlive(owner)||record2.task.error?.details?.executionStopped===!1||process.platform==="win32"&&record2.task.error?.code==="PLUGIN_TASK_HOST_RESTARTED"?!0:owner&&process.platform!=="win32"?isProcessGroupAlive(owner.pid):!1}var PLUGIN_TASK_RESULT_CHUNK_BYTES,MAX_EVENT_BYTES,MAX_RESULT_BYTES,RETENTION_MS,PluginTaskStore,init_pluginTaskStore=__esm({"../client/src/plugins/runtime/pluginTaskStore.ts"(){"use strict";init_dist2();init_pluginHostFiles();init_pluginHostPaths();init_dist();PLUGIN_TASK_RESULT_CHUNK_BYTES=192*1024,MAX_EVENT_BYTES=512*1024,MAX_RESULT_BYTES=64*1024*1024,RETENTION_MS=10080*60*1e3;PluginTaskStore=class{constructor(directory=pluginHostPaths().tasks){this.directory=directory}directory;activeTaskIds;dedupeIndex;dedupeKeys=new Map;forgetDedupe(taskId){let key2=this.dedupeKeys.get(taskId);if(!key2)return;let ids=this.dedupeIndex?.get(key2);ids?.delete(taskId),ids?.size||this.dedupeIndex?.delete(key2),this.dedupeKeys.delete(taskId)}indexDedupe(record2){if(!this.dedupeIndex)return;let{dedupeKey:key2,task}=record2,keep=key2&&(!key2.startsWith("active:")||isPluginTaskActive(task.state));if(keep&&this.dedupeKeys.get(task.taskId)===key2||(this.forgetDedupe(task.taskId),!keep))return;let ids=this.dedupeIndex.get(key2)??new Set;ids.add(task.taskId),this.dedupeIndex.set(key2,ids),this.dedupeKeys.set(task.taskId,key2)}findDedupe(key2,activeOnly=!1){if(!this.dedupeIndex){this.dedupeIndex=new Map;for(let record2 of this.list())this.indexDedupe(record2)}for(let taskId of this.dedupeIndex.get(key2)??[]){let record2;try{record2=this.read(taskId)}catch(error2){if(error2.code!=="PLUGIN_TASK_NOT_FOUND")throw error2;this.forgetDedupe(taskId);continue}if(this.indexDedupe(record2),record2.dedupeKey===key2&&(!activeOnly||isPluginTaskActive(record2.task.state)))return record2}}path(taskId,file){if(!isPluginTaskId(taskId))throw Object.assign(new Error("Invalid plugin task ID"),{code:"PLUGIN_TASK_INVALID_ID"});return join10(this.directory,taskId,file)}read(taskId){let record2;try{record2=JSON.parse(readFileSync9(this.path(taskId,"task.json"),"utf8"))}catch(error2){throw error2.code==="ENOENT"?Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"}):error2}if(record2?.task?.taskId!==taskId||!Array.isArray(record2.events))throw new Error("Invalid persistent plugin task record");return record2}write(record2){writePluginHostFile(this.path(record2.task.taskId,"task.json"),JSON.stringify(record2)),this.indexDedupe(record2),this.indexActive(record2)}indexActive(record2){isPluginTaskActive(record2.task.state)?this.activeTaskIds?.add(record2.task.taskId):this.activeTaskIds?.delete(record2.task.taskId)}listActive(){if(!this.activeTaskIds){this.activeTaskIds=new Set;for(let record2 of this.list())this.indexActive(record2)}let records=[];for(let taskId of this.activeTaskIds)try{let record2=this.read(taskId);this.indexActive(record2),isPluginTaskActive(record2.task.state)&&records.push(record2)}catch(error2){if(error2.code!=="PLUGIN_TASK_NOT_FOUND")throw error2;this.activeTaskIds.delete(taskId)}return records}update(taskId,update,type="state",fields2={}){let record2=this.read(taskId);Object.assign(record2,fields2),record2.task={...record2.task,...update,sequence:record2.task.sequence+1,updatedAt:Date.now()};let event={sequence:record2.task.sequence,time:record2.task.updatedAt,type,state:record2.task.state,...type==="progress"?{progress:record2.task.progress}:{},...type==="checkpoint"?{checkpoint:record2.task.checkpoint}:{}};record2.events.push(event);let bytes=Buffer.byteLength(JSON.stringify(record2.events));for(;record2.events.length>256||bytes>MAX_EVENT_BYTES&&record2.events.length>1;)bytes-=Buffer.byteLength(JSON.stringify(record2.events.shift()))+1;return this.write(record2),record2.task}list(){let names;try{names=readdirSync6(this.directory)}catch(error2){if(error2.code==="ENOENT")return[];throw error2}return names.filter(isPluginTaskId).map(name=>this.read(name))}diagnosticRecords(taskId){let records=[],bytes=0,scanned=0,limited=!1;if(taskId){let size;try{size=statSync7(this.path(taskId,"task.json")).size}catch(error2){if(error2.code==="ENOENT")return{records,limited};throw error2}if(size>16*1024*1024)return{records,limited:!0};records.push(this.read(taskId)),bytes+=size}let directory;try{directory=opendirSync(this.directory)}catch(error2){if(error2.code==="ENOENT")return{records,limited};throw error2}try{let item;for(;(item=directory.readSync())!==null;){if(++scanned>2048){limited=!0;break}if(!(!isPluginTaskId(item.name)||item.name===taskId))try{let size=statSync7(this.path(item.name,"task.json")).size;if(records.length>=512||bytes+size>16*1024*1024){limited=!0;break}bytes+=size,records.push(this.read(item.name))}catch{limited=!0}}}finally{directory.closeSync()}return{records,limited}}events(taskId,cursor){let record2=this.read(taskId);if(!Number.isSafeInteger(cursor)||cursor<0||cursor>record2.task.sequence)throw new Error("Invalid plugin task event cursor");let first=record2.events[0]?.sequence??record2.task.sequence+1,events=[],bytes=0;for(let event of record2.events){if(event.sequence<=cursor)continue;let size=Buffer.byteLength(JSON.stringify(event));if(bytes+size>192*1024&&events.length)break;events.push(event),bytes+=size}return{task:record2.task,events,firstAvailableSequence:first,nextCursor:events.at(-1)?.sequence??cursor,gap:cursor<first-1}}saveResult(taskId,value){let bytes=Buffer.from(JSON.stringify({value}));if(bytes.length>MAX_RESULT_BYTES)throw Object.assign(new Error("Plugin task result exceeds 64 MiB"),{code:"PLUGIN_TASK_RESULT_TOO_LARGE"});return writePluginHostFile(this.path(taskId,"result.json"),bytes),{bytes:bytes.length,sha256:createHash7("sha256").update(bytes).digest("hex"),chunks:Math.ceil(bytes.length/PLUGIN_TASK_RESULT_CHUNK_BYTES)}}resultChunk(taskId,index){let task=this.read(taskId).task;if(task.state!=="success"||!task.result)throw new Error("Plugin task result is not available");if(!Number.isSafeInteger(index)||index<0||index>=task.result.chunks)throw new Error("Invalid plugin task result chunk");let file=this.path(taskId,"result.json");if(statSync7(file).size!==task.result.bytes)throw new Error("Plugin task result size does not match its record");let offset2=index*PLUGIN_TASK_RESULT_CHUNK_BYTES,buffer=Buffer.alloc(Math.min(PLUGIN_TASK_RESULT_CHUNK_BYTES,task.result.bytes-offset2)),descriptor=openSync5(file,"r");try{if(readSync2(descriptor,buffer,0,buffer.length,offset2)!==buffer.length)throw new Error("Plugin task result is incomplete")}finally{closeSync5(descriptor)}return{taskId,index,data:buffer.toString("base64"),...task.result}}recover(epoch2){this.activeTaskIds=new Set;for(let record2 of this.list()){this.indexActive(record2);let{task}=record2;isPluginTaskActive(task.state)&&task.host.epoch!==epoch2?this.update(task.taskId,{state:"interrupted",error:{code:"PLUGIN_TASK_HOST_RESTARTED",message:"The plugin execution service restarted; external operations may need reconciliation"}}):!isPluginTaskActive(task.state)&&Date.now()-task.updatedAt>RETENTION_MS&&!pluginTaskExecutionUnconfirmed(record2)&&(rmSync7(join10(this.directory,task.taskId),{recursive:!0,force:!0}),this.forgetDedupe(task.taskId))}}prune(now=Date.now()){for(let record2 of this.list()){let{task}=record2;!isPluginTaskActive(task.state)&&now-task.updatedAt>RETENTION_MS&&!pluginTaskExecutionUnconfirmed(record2)&&(rmSync7(join10(this.directory,task.taskId),{recursive:!0,force:!0}),this.forgetDedupe(task.taskId))}}}}});import{randomUUID as randomUUID6}from"node:crypto";async function invokePageEvalWithArgs(invoke2,params){if(!Number.isSafeInteger(params.tabId)||params.tabId<0)throw new Error("Invalid target tab");if(resolvePageEvalExpression({expression:params.expression,args:[]}),!Array.isArray(params.args))throw new Error("page_eval args must be an array");if(params.executionWorld!==void 0&&!["main","isolated"].includes(params.executionWorld))throw new Error("Invalid page executionWorld");params.executionWorld==="isolated"&&validatePageUserScriptParams({tabId:params.tabId,worldId:params.worldId??"",code:params.expression});let args=JSON.stringify(params.args);if(args.length>64*1024*1024)throw new Error("Page script arguments must fit within 64 MiB characters");let{args:_args,...request}=params,evaluate=async(expression,transfer=!1)=>{let payload={...request,...transfer?{observe:!1,diagnostics:!1}:{},expression},result=await(transfer?invoke2(payload,!0):invoke2(payload));if(transfer&&result?.action?.success===!1)throw new Error(result.action.error||"page_eval failed");return result};if(args.length+params.expression.length<=CHUNK_CHARACTERS)return evaluate(resolvePageEvalExpression(params));let key2=JSON.stringify("__mearlPageScriptTransfer_"+randomUUID6());try{for(let offset2=0;offset2<args.length;offset2+=CHUNK_CHARACTERS)await evaluate(`void (window[${key2}] = (window[${key2}] || '') + ${JSON.stringify(args.slice(offset2,offset2+CHUNK_CHARACTERS))})`,!0);return await evaluate(`(() => { const args = JSON.parse(window[${key2}]); delete window[${key2}]; return (${params.expression})(...args); })()`)}finally{await evaluate(`delete window[${key2}]`,!0).catch(()=>{})}}var CHUNK_CHARACTERS,init_pageEvalArguments=__esm({"../client/src/pageEvalArguments.ts"(){"use strict";init_dist2();CHUNK_CHARACTERS=48*1024}});import{open,mkdir,rename,rm,stat}from"node:fs/promises";import path2 from"node:path";import{randomUUID as randomUUID7}from"node:crypto";async function stageFile(client,filePath,options){if(!path2.isAbsolute(filePath))throw new Error("Caller-local file paths must be absolute");let source=await open(filePath,"r"),id,pinned=options;try{let metadata=await source.stat();if(!metadata.isFile()||metadata.size>256*1024*1024)throw new Error("Upload requires a regular file of at most 256 MiB");let created=await client.invoke("__artifact_init",{filename:path2.basename(filePath)},options);pinned={...options,browser:created.browserId},id=created.artifact.artifactId;let offset2=0;for await(let chunk of source.createReadStream({highWaterMark:CHUNK_BYTES,autoClose:!1}))await client.invoke("__artifact_write",{artifactId:id,offset:offset2,base64:chunk.toString("base64")},pinned),offset2+=chunk.length;return await client.invoke("__artifact_complete",{artifactId:id,bytes:offset2},pinned),{artifactId:id,options:pinned}}catch(error2){throw id&&await client.invoke("__artifact_remove",{artifactId:id},pinned).catch(()=>{}),error2}finally{await source.close()}}async function exportArtifact(client,artifact,outputPath,options={}){if(!Number.isSafeInteger(artifact.bytes)||artifact.bytes<0)throw new Error("Invalid artifact size");if(!path2.isAbsolute(outputPath))throw new Error("Artifact output paths must be absolute");if(!options.session&&!artifact.browserId&&!options.browser)throw new Error("An artifact requires its originating browser");let pinned={...options,...artifact.browserId?{browser:artifact.browserId}:{}};await mkdir(path2.dirname(outputPath),{recursive:!0});let temporary=`${outputPath}.${randomUUID7()}.part`,target=await open(temporary,"wx",384);try{let offset2=0;if(artifact.bytes===0){let empty2=await client.invoke("__artifact_read",{artifactId:artifact.artifactId,offset:0},pinned);if(empty2.totalBytes!==0||empty2.bytes!==0||empty2.base64!=="")throw new Error("Artifact export size mismatch")}for(;offset2<artifact.bytes;){let chunk=await client.invoke("__artifact_read",{artifactId:artifact.artifactId,offset:offset2},pinned),bytes=Buffer.from(chunk.base64,"base64");if(!bytes.length||bytes.length!==chunk.bytes||chunk.totalBytes!==artifact.bytes||offset2+bytes.length>artifact.bytes)throw new Error("Invalid artifact chunk or truncated transfer");await target.write(bytes),offset2+=bytes.length}if(await target.sync(),await target.close(),(await stat(temporary)).size!==artifact.bytes)throw new Error("Artifact export size mismatch");return await rename(temporary,outputPath),{outputPath,bytes:artifact.bytes}}catch(error2){throw await target.close().catch(()=>{}),await rm(temporary,{force:!0}),error2}}var CHUNK_BYTES,init_artifacts=__esm({"../client/src/artifacts.ts"(){"use strict";CHUNK_BYTES=256*1024}});function resolveCloudConnectorSelector(connectors,selector){let normalized=selector.trim().toLowerCase();if(!normalized)return{status:"not_found"};let resolveMatches=matches=>matches.length===1?{status:"matched",connector:matches[0]}:matches.length>1?{status:"ambiguous"}:null,exactId=resolveMatches(connectors.filter(connector=>connector.connectorId.toLowerCase()===normalized));if(exactId)return exactId;let exactName=resolveMatches(connectors.filter(connector=>connector.name.toLowerCase()===normalized));return exactName||(resolveMatches(connectors.filter(connector=>connector.connectorId.toLowerCase().includes(normalized)||connector.name.toLowerCase().includes(normalized)))??{status:"not_found"})}function isHeartbeatMessage(msg){return msg&&(msg.type==="ping"||msg.type==="pong")}var init_dist3=__esm({"../cloud/cloud-types/dist/index.js"(){"use strict"}});function boundedNumber(value,fallback,minimum,maximum){let numeric=Number(value);return Number.isFinite(numeric)?Math.min(Math.max(numeric,minimum),maximum):fallback}function resolveObservedActionTimeoutSec(data2){let observe=data2.observe??{},observationMs=boundedNumber(observe.timeoutMs,3e3,500,3e4),navigationGraceMs=boundedNumber(observe.navigationGraceMs,1e3,0,5e3),navigationTimeoutMs=boundedNumber(observe.navigationTimeoutMs,15e3,1e3,3e4),totalMs=observationMs+navigationGraceMs+4e3+navigationTimeoutMs+5e3;return Math.max(20,Math.ceil(totalMs/1e3))}function resolveActionTimeoutSec(action,data2,fallback=15){if(action==="send_request"){let transferTimeoutMs=data2.bodyFile!==void 0||Array.isArray(data2.files)&&data2.files.length>0?SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS:0;return Math.max(fallback,Math.ceil(((data2.timeout??3e4)+transferTimeoutMs+5e3)/1e3))}if(action==="send_mtop_request")return Math.max(fallback,Math.ceil(((data2.timeout??1e4)+5e3)/1e3));if(action==="page_download")return Math.max(fallback,Math.ceil((Number(data2.timeout??3e4)+1e4)/1e3));if(action==="page_wait"){let waitMs=data2.time??data2.timeout??1e4;return Math.max(fallback,Math.ceil((Number(waitMs)+5e3)/1e3))}if(action==="tab_open"||action==="set_cookie"&&data2.reload===!0)return Math.max(fallback,40);if(action==="browser_launch")return Math.max(fallback,90);if(action==="browser_close")return Math.max(fallback,BROWSER_CLOSE_TIMEOUT_SEC);if(action==="run_actions"){let timeoutSec=(Array.isArray(data2.actions)?data2.actions:[{}]).reduce((total,step)=>{let stepAction=String(step?.action??"");return!stepAction||stepAction==="run_actions"?total+15:total+resolveActionTimeoutSec(stepAction,step?.data??{},15)},0);return Math.max(fallback,timeoutSec)}let observedAction=OBSERVED_PAGE_ACTIONS.has(action),observationEnabled=action==="page_eval"?data2.observe!==null&&typeof data2.observe=="object"&&!Array.isArray(data2.observe):data2.observe!==!1;if(action==="page_upload"){let actionTimeoutSec=observationEnabled?resolveObservedActionTimeoutSec(data2):fallback;return Math.max(fallback,actionTimeoutSec+Math.ceil(PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS/1e3))}return observedAction&&observationEnabled?Math.max(fallback,resolveObservedActionTimeoutSec(data2)):fallback}var SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS,PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS,BROWSER_CLOSE_TIMEOUT_SEC,OBSERVED_PAGE_ACTIONS,init_actionTimeouts=__esm({"../client/src/actionTimeouts.ts"(){"use strict";init_dist2();SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS=12e4,PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS=18e4,BROWSER_CLOSE_TIMEOUT_SEC=1080;OBSERVED_PAGE_ACTIONS=new Set(PAGE_ACT_ACTIONS)}});function assertProviderProtocolVersion(actual,peer="Provider"){if(actual!==3)throw new Error(`PROVIDER_PROTOCOL_MISMATCH: ${peer} uses protocol ${String(actual??"unknown")}; expected 3. Update Mearl and the Provider package, then restart the services.`)}var init_protocol=__esm({"../provider/dist/protocol.js"(){"use strict"}});var init_types2=__esm({"../provider/dist/types.js"(){"use strict";init_protocol()}});var PROVIDER_ACTIONS,init_actions=__esm({"../provider/dist/actions.js"(){"use strict";init_browserActionProtocol();PROVIDER_ACTIONS=Object.keys(BROWSER_CAPABILITY_ACTIONS)}});var init_provider_runtime=__esm({"../provider/dist/provider-runtime.js"(){"use strict";init_types2();init_actions()}});import{existsSync as existsSync5,readFileSync as readFileSync10,renameSync as renameSync7,rmSync as rmSync8,statSync as statSync8,writeFileSync as writeFileSync6}from"node:fs";import{isAbsolute as isAbsolute4,join as join11,relative as relative3,resolve as resolve4,sep as sep3}from"node:path";function liveProviderFile(providerId){return keyedConfigFile(LIVE_PROVIDERS_SUBDIR,providerId)}function listInstalledProviders(){let manifests=[];for(let file of listRecordFiles(keyedDir(INSTALLED_PROVIDERS_SUBDIR)))try{let parsed=JSON.parse(readFileSync10(file,"utf8"));parsed&&typeof parsed.providerId=="string"&&typeof parsed.packageName=="string"&&manifests.push(parsed)}catch{}return manifests.sort((a,b)=>a.providerId.localeCompare(b.providerId))}function readLiveProvider(providerId){let record2=readRecord(liveProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}var INSTALLED_PROVIDERS_SUBDIR,LIVE_PROVIDERS_SUBDIR,init_registry2=__esm({"../provider/dist/registry.js"(){"use strict";init_dist();init_types2();init_provider_runtime();init_protocol();INSTALLED_PROVIDERS_SUBDIR="providers/installed",LIVE_PROVIDERS_SUBDIR="providers/live"}});import{spawn as spawn3}from"node:child_process";import{randomUUID as randomUUID8}from"node:crypto";import{tmpdir as tmpdir2}from"node:os";import{join as join12}from"node:path";function providerControlHostFile(){return keyedConfigFile("control","providers")}function providerControlSocketPath(pid){return process.platform==="win32"?`\\\\.\\pipe\\mearl-provider-control-${pid}`:join12(tmpdir2(),`mearl-provider-control-${pid}.sock`)}function readProviderControlHost(){let record2=readRecord(providerControlHostFile());return!record2?.ready||typeof record2.socketPath!="string"||!isAlive(record2.pid)?null:(assertProviderProtocolVersion(record2.protocolVersion,"Provider control host"),record2)}function ensureProviderControlHost(timeoutMs=1e4){if(startup)return startup;let pending=(async()=>{let file=providerControlHostFile(),deadline=Date.now()+timeoutMs;for(;Date.now()<deadline;){let ready=readProviderControlHost();if(ready)return ready;let previous=readRecord(file);if(!previous||!isAlive(previous.pid)){previous?removeRecordIfPid(file,previous.pid):removeInvalidRecord(file);let token=randomUUID8();if(claimRecord(file,{pid:process.pid,socketPath:"",token,ready:!1,protocolVersion:3}))try{let entry=process.env.MEARL_NATIVE_HOST_ENTRY,child=spawn3(entry?process.execPath:"mearl-native-host",[...entry?[entry]:[],"--provider-control",token],{detached:!0,stdio:"ignore",windowsHide:!0});if(await new Promise((resolve7,reject)=>{child.once("error",reject),child.once("spawn",resolve7)}),child.unref(),!child.pid)throw new Error("Provider control host did not report its pid");writeRecordIfPid(file,process.pid,{pid:child.pid,socketPath:providerControlSocketPath(child.pid),token,ready:!1,protocolVersion:3})}catch(error2){throw removeRecordIfPid(file,process.pid),error2}}await new Promise(resolve7=>setTimeout(resolve7,50))}throw new Error("Provider control host startup timed out")})();return startup=pending,pending.finally(()=>{startup===pending&&(startup=void 0)}).catch(()=>{}),pending}var startup,init_control_host=__esm({"../provider/dist/control-host.js"(){"use strict";init_protocol();init_dist()}});var init_host=__esm({"../provider/dist/host.js"(){"use strict";init_registry2();init_control_host()}});import net from"node:net";import{chmodSync,rmSync as rmSync9}from"node:fs";import{dirname as dirname6}from"node:path";var MAX_REQUEST_BYTES,init_server=__esm({"../provider/dist/server.js"(){"use strict";init_dist();init_actions();init_provider_runtime();init_registry2();init_types2();init_protocol();MAX_REQUEST_BYTES=16*1024*1024}});var init_dist4=__esm({"../provider/dist/index.js"(){"use strict";init_types2();init_protocol();init_actions();init_registry2();init_provider_runtime();init_server()}});import{spawn as spawn4}from"node:child_process";import{closeSync as closeSync6,existsSync as existsSync6,mkdirSync as mkdirSync6,openSync as openSync6}from"node:fs";import{join as join13}from"node:path";var init_launcher=__esm({"../provider/dist/launcher.js"(){"use strict";init_dist();init_registry2();init_protocol()}});var init_runtime=__esm({"../provider/dist/runtime.js"(){"use strict";init_launcher();init_registry2();init_provider_runtime()}});import fs2 from"node:fs";function resolveValue(value){if(typeof value!="string"||!value.startsWith(FILE_REF_PREFIX))return value;let filePath=value.slice(FILE_REF_PREFIX.length);if(!filePath)return value;let content;try{content=fs2.readFileSync(filePath,"utf-8")}catch{return value}try{return JSON.parse(content)}catch{return content}}function resolveFileRefs(data2){if(data2===null||typeof data2!="object"||Array.isArray(data2))return data2;let out={};for(let[key2,value]of Object.entries(data2))out[key2]=resolveValue(value);return out}var FILE_REF_PREFIX,init_fileRefs=__esm({"../client/src/fileRefs.ts"(){"use strict";FILE_REF_PREFIX="@"}});import fs3 from"node:fs";import os from"node:os";import path3 from"node:path";function isAlive2(pid){if(!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error2){return error2.code==="EPERM"}}function listLiveBrowsers(){let files;try{files=fs3.readdirSync(BROWSERS_DIR).filter(name=>name.endsWith(".json"))}catch{return[]}let out=[];for(let name of files){let rec;try{rec=JSON.parse(fs3.readFileSync(path3.join(BROWSERS_DIR,name),"utf-8"))}catch{continue}rec&&typeof rec.pid=="number"&&rec.socketPath&&isAlive2(rec.pid)&&out.push(rec)}return out.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0))}function findBrowser(browsers,selector){let sel=selector.trim().toLowerCase();if(!sel)return null;let byId=browsers.find(b=>b.browserId.toLowerCase()===sel);if(byId)return byId;let exactNameMatches=browsers.filter(b=>b.browserName.toLowerCase()===sel);if(exactNameMatches.length>1)throw new Error(`Browser name "${selector.trim()}" is ambiguous. Use a full browserId: ${exactNameMatches.map(browser=>browser.browserId).join(", ")}`);return exactNameMatches[0]?exactNameMatches[0]:browsers.find(b=>b.browserId.toLowerCase().includes(sel)||b.browserName.toLowerCase().includes(sel))??null}function describeBrowser(b){let idShort=b.browserId.length>12?`${b.browserId.slice(0,8)}…`:b.browserId;return`${b.browserName} [${idShort}]`}var BROWSERS_DIR,init_browserRegistry=__esm({"../client/src/browserRegistry.ts"(){"use strict";BROWSERS_DIR=path3.join(os.homedir(),".mearl","browsers")}});import net2 from"node:net";import fs4 from"node:fs";import os2 from"node:os";import path4 from"node:path";import{StringDecoder}from"node:string_decoder";function toControlSourceWireValue(source){return source==="remote"||source==="cloud"?"cloud":"local"}function setDefaultBrowser(selector){defaultBrowser=selector&&selector.trim()?selector.trim():void 0}function getDefaultBrowser(){return defaultBrowser}function findConnectedBrowser(items,selector){let normalized=selector.trim().toLowerCase(),connected=items.filter(item=>item.status==="connected"),byId=connected.find(item=>String(item.browserId).toLowerCase()===normalized);if(byId)return byId;let exactNameMatches=connected.filter(item=>String(item.name).toLowerCase()===normalized);if(exactNameMatches.length>1)throw new Error(`Browser name "${selector.trim()}" is ambiguous. Use a full browserId: ${exactNameMatches.map(item=>String(item.browserId)).join(", ")}`);return exactNameMatches[0]??connected.find(item=>String(item.browserId).toLowerCase().includes(normalized)||String(item.name).toLowerCase().includes(normalized))??null}function decorateBrowserListResult(result){let browsers=Array.isArray(result?.browsers)?result.browsers:[],selector=getDefaultBrowser()??process.env.MEARL_BROWSER,selected=selector?findConnectedBrowser(browsers,selector):browsers.find(browser=>browser.status==="connected")??null;return{...result,defaultBrowserId:selected?.browserId??null}}function browserListFromProviderRecords(browsers){let providerBrowsers=browsers.filter(browser=>browser.transport==="provider").map(browser=>({browserId:browser.browserId,name:browser.browserName,type:"managed",status:browser.status??"running_disconnected",transport:"provider",provider:browser.provider,ownership:browser.ownership,persistence:browser.persistence,operations:browser.operations,pairing:browser.pairing,references:browser.references,details:browser.details}));return{count:providerBrowsers.length,connectedCount:providerBrowsers.filter(browser=>browser.status==="connected").length,browsers:providerBrowsers}}function withDiscoveryWarning(result,error2){let detail=(error2.cause??error2)?.code??(error2 instanceof Error?error2.message.split(`
624
- `)[0]:String(error2));return{...result,warnings:[...Array.isArray(result.warnings)?result.warnings:[],`Local CDP discovery could not complete: ${detail}`]}}function cdpOnlyBrowserList(result){let cdpBrowsers=(Array.isArray(result.browsers)?result.browsers:[]).filter(browser=>browser.transport==="cdp");return{...result,count:cdpBrowsers.length,connectedCount:cdpBrowsers.filter(browser=>browser.status==="connected").length,browsers:cdpBrowsers}}function areInstalledProvidersRunning(){return listInstalledProviders().every(provider=>readLiveProvider(provider.providerId))}function isConnectedBrowser(browser){return browser.status===void 0||browser.status==="connected"}function isOrdinaryLocalBrowser(browser){return!browser.browserId.startsWith("managed:")&&(browser.transport==="extension"||browser.transport==="cdp")}function supportsAction(browser,action,data2){if(browser.transport==="provider"){if(action==="browser_control"||action==="browser_release"&&data2[SESSION_OPTION])return!0;if(action.startsWith("__artifact_"))return browser.capabilities?.actions.includes("page_upload")===!0||(action==="__artifact_read"||action==="__artifact_remove")&&browser.capabilities?.actions.includes("page_download")===!0;if(action==="run_actions"&&data2[SESSION_OPTION])return!0}if(action==="get_versions")return!0;if(action==="get_browser_access_url")return browser.transport!=="provider"||browser.operations?.includes("access")===!0;if(action==="browser_close"){if(browser.transport!=="provider")return!0;let required=data2.deleteProfile===!0?"deleteData":"close";return browser.operations?.includes(required)===!0}return action==="browser_release"?browser.transport!=="provider"||browser.operations?.includes("detach")===!0:isConnectedBrowser(browser)?browser.transport!=="provider"||browser.capabilities?.actions.some(capability=>capability===action)===!0:!1}function routableBrowsers(browsers,action,data2,transport){return browsers.filter(browser=>isConnectedBrowser(browser)&&(action!=="browser_list"||browser.transport!=="provider")&&!(transport==="cdp"&&browser.transport==="provider")&&supportsAction(browser,action,data2))}function resolveLocalActionTarget(action,data2,options={}){let selector=options.browser??defaultBrowser??process.env.MEARL_BROWSER??void 0,socketPath=options.socketPath??process.env.MEARL_SOCKET_PATH?.trim();if(socketPath&&(options.socketPath||!selector))return{socketPath};let browsers=listLiveBrowsers(),target=selector?findBrowser(browsers,selector):routableBrowsers(browsers,action,data2,options.transport)[0];return target?{browser:target.browserId}:void 0}function selectBrowserResult(data2){let selector=typeof data2.browser=="string"?data2.browser.trim():"";if(!selector)return setDefaultBrowser(void 0),{selected:null,note:"Cleared: default target is now the most-recently focused browser."};let browsers=listLiveBrowsers(),controllableBrowsers=browsers.filter(isConnectedBrowser),match=findBrowser(controllableBrowsers,selector);if(!match)throw new Error(formatNoMatchError(selector,browsers));return setDefaultBrowser(match.browserId),{selected:{browserId:match.browserId,name:match.browserName}}}function instanceSocketPath(pid){return process.platform==="win32"?`\\\\.\\pipe\\mearl-agent-${pid}`:path4.join(os2.tmpdir(),`mearl-agent-${pid}.sock`)}function discoveryCacheKey(){let browsers=listLiveBrowsers().map(browser=>[browser.browserId,browser.pid,browser.socketPath,browser.status,browser.updatedAt]).sort((a,b)=>String(a[0]).localeCompare(String(b[0]))),providers=listInstalledProviders().map(provider=>provider.providerId).sort();return JSON.stringify({browsers,providers})}async function spawnNativeHost(args){let{spawn:spawn10}=await import("node:child_process");return new Promise((resolve7,reject)=>{let child=spawn10("mearl-native-host",args,{detached:!0,stdio:"ignore",windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.unref(),resolve7(child.pid)})})}async function trySpawnNativeHost(){if(persistentSpawnPromise)return persistentSpawnPromise;let spawnPromise=(async()=>{try{return await spawnNativeHost(["--daemon"]),!0}catch{return!1}})();persistentSpawnPromise=spawnPromise;try{return await spawnPromise}finally{persistentSpawnPromise===spawnPromise&&(persistentSpawnPromise=null)}}async function discoverLocalBrowserList(timeoutSec,controlSource){if(discoveryListPromise)return discoveryListPromise;let cacheKey=discoveryCacheKey();if(discoveryListCache&&discoveryListCache.key===cacheKey&&Date.now()<discoveryListCache.until){if(discoveryListCache.error)throw discoveryListCache.error;return discoveryListCache.result}discoveryListCache=null;let request=(async()=>{let pid=await spawnNativeHost(["--daemon","--discover-cdp"]);if(pid===void 0)throw new Error("Native host did not report its process id");let socketPath=instanceSocketPath(pid),deadline=Date.now()+Math.min(timeoutSec*1e3,DISCOVERY_STARTUP_TIMEOUT_MS);for(;;)try{return await invokeOnce("browser_list",{},timeoutSec,void 0,socketPath,controlSource)}catch(error2){if(!isConnError(error2)||Date.now()>=deadline)throw error2;await new Promise(resolve7=>setTimeout(resolve7,DISCOVERY_RETRY_INTERVAL_MS))}})();discoveryListPromise=request;try{let result=await request;return result.browsers?.some(browser=>browser.transport==="cdp"&&browser.status==="connected"&&!browser.browserId?.startsWith("managed:"))||(discoveryListCache={key:cacheKey,result,until:Date.now()+DISCOVERY_MISS_CACHE_MS}),result}catch(error2){throw discoveryListCache={key:cacheKey,error:error2,until:Date.now()+DISCOVERY_MISS_CACHE_MS},error2}finally{discoveryListPromise===request&&(discoveryListPromise=null)}}function readOwnedLegacySocketIdentity(){if(process.platform==="win32")return null;try{let stat2=fs4.lstatSync(SOCKET_PATH);return!stat2.isSocket()||process.getuid&&stat2.uid!==process.getuid()?null:{dev:stat2.dev,ino:stat2.ino}}catch{return null}}function removeStaleLegacySocket(identity){if(identity)try{let current2=fs4.lstatSync(SOCKET_PATH);if(!current2.isSocket()||current2.dev!==identity.dev||current2.ino!==identity.ino)return;fs4.unlinkSync(SOCKET_PATH)}catch{}}function invoke(action,data2={},options={}){if(action==="__resolve_action_target"){if(!isBrowserCapabilityAction(data2.action))return Promise.reject(new Error("Invalid browser capability action"));let target=resolveLocalActionTarget(data2.action,data2.data??{},options),browser2=target?.browser??(target?.socketPath?listLiveBrowsers().find(item=>item.socketPath===target.socketPath&&supportsAction(item,data2.action,data2.data??{}))?.browserId:void 0);return Promise.resolve(browser2?{browser:browser2}:null)}if(action==="browser_select_browser")try{return Promise.resolve(selectBrowserResult(data2))}catch(error2){return Promise.reject(error2)}let{timeoutSec=resolveActionTimeoutSec(action,data2),transport,browser,controlSource="local"}=options;if(action==="__control_session_resolve")return resolveControlSession(data2.sessionId,timeoutSec,controlSource);let resolvedData=resolveFileRefs(data2);if(Object.defineProperty(resolvedData,SESSION_OPTION,{value:options.controlSessionId}),action==="browser_list")return dispatchInvoke(action,resolvedData,timeoutSec,transport,void 0,controlSource,options.socketPath).then(result=>decorateBrowserListResult(transport==="cdp"?cdpOnlyBrowserList(result):result));let selector=browser??defaultBrowser??process.env.MEARL_BROWSER??void 0;return dispatchInvoke(action,resolvedData,timeoutSec,transport,selector,controlSource,options.socketPath)}async function resolveControlSession(sessionId,timeoutSec,controlSource){let browsers=listLiveBrowsers(),configuredSocketPath=process.env.MEARL_SOCKET_PATH?.trim(),sockets=configuredSocketPath?[configuredSocketPath]:[...new Set(browsers.filter(browser=>browser.transport!=="provider").map(browser=>browser.socketPath))],provider=configuredSocketPath?void 0:browsers.find(browser=>browser.transport==="provider");!sockets.length&&!provider&&sockets.push(SOCKET_PATH);let requests=sockets.map(socketPath=>invokeOnce("__control_session_resolve",{sessionId},timeoutSec,void 0,socketPath,controlSource));provider&&requests.push(invokeOnce("__control_session_resolve",{sessionId},timeoutSec,void 0,provider.socketPath,controlSource,provider.browserId));let results=await Promise.allSettled(requests),sessions=results.flatMap(result=>result.status==="fulfilled"&&result.value?.session?.sessionId===sessionId?[result.value.session]:[]);if(sessions.length>1)throw new Error("CONTROL_SESSION_AMBIGUOUS: multiple hosts own this id");if(sessions.length)return{session:sessions[0]};let failure2=results.find(result=>result.status==="rejected"&&!isConnError(result.reason));if(failure2?.status==="rejected")throw failure2.reason;return{session:null}}function isConnError(error2){let code=error2?.code;return code==="ENOENT"||code==="ECONNREFUSED"}function isSocketSandboxError(error2){return error2?.code==="EPERM"}function isUnavailableConnection(error2){let cause=error2.cause??error2,code=cause?.code;return isConnError(cause)||isSocketSandboxError(cause)||code==="EACCES"}async function dispatchInvoke(action,data2,timeoutSec,transport,selector,controlSource,socketPath){let configuredSocketPath=socketPath??process.env.MEARL_SOCKET_PATH?.trim();if(configuredSocketPath&&(socketPath||!selector))try{return await invokeOnce(action,data2,timeoutSec,transport,configuredSocketPath,controlSource)}catch(error2){throw isConnError(error2)||isSocketSandboxError(error2)?new Error(formatConnectError(error2,configuredSocketPath),{cause:error2}):error2}let browsers=listLiveBrowsers(),controllableBrowsers=browsers.filter(isConnectedBrowser);if(action==="browser_list"&&transport==="cdp"){let registeredCdp=controllableBrowsers.find(browser=>browser.transport==="cdp"&&isOrdinaryLocalBrowser(browser));if(registeredCdp)try{return await invokeOnce(action,data2,timeoutSec,transport,registeredCdp.socketPath,controlSource)}catch(error2){if(!isConnError(error2))throw error2}try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}}if(action==="browser_list"&&!controllableBrowsers.some(isOrdinaryLocalBrowser))try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}if(selector){let match=findBrowser(browsers,selector);if(!match)throw new Error(formatNoMatchError(selector,browsers));if(transport==="cdp"&&match.transport==="provider")throw new Error(`Browser ${describeBrowser(match)} does not support the CDP transport`);if(match.status==="pairing"&&action!=="get_versions"&&action!=="browser_close"&&action!=="browser_release"&&action!=="browser_control")throw new Error(`Browser ${describeBrowser(match)} is waiting for device pairing`);if(!supportsAction(match,action,data2))throw new Error(`Browser ${describeBrowser(match)} does not support ${action}`);try{return await invokeOnce(action,data2,timeoutSec,transport,match.socketPath,controlSource,match.transport==="provider"?match.browserId:void 0)}catch(error2){throw isConnError(error2)||isSocketSandboxError(error2)?new Error(formatConnectError(error2,match.socketPath),{cause:error2}):error2}}let candidates=routableBrowsers(browsers,action,data2,transport);if(candidates.length>0){let target=candidates[0];try{return await invokeOnce(action,data2,timeoutSec,transport,target.socketPath,controlSource,target.transport==="provider"?target.browserId:void 0)}catch(error2){if(isSocketSandboxError(error2))throw new Error(formatConnectError(error2,target.socketPath),{cause:error2});if(!isConnError(error2))throw error2}}if(action==="browser_list")try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}return invokeViaLegacy(action,data2,timeoutSec,transport,controlSource,!1)}async function invokeViaLegacy(action,data2,timeoutSec,transport,controlSource,isRetry,localOnly=!1){let legacySocketIdentity=readOwnedLegacySocketIdentity();try{return await invokeOnce(action,data2,timeoutSec,transport,SOCKET_PATH,controlSource)}catch(error2){let err=error2;if((err.code==="ENOENT"||err.code==="ECONNREFUSED")&&!isRetry&&(err.code==="ECONNREFUSED"&&removeStaleLegacySocket(legacySocketIdentity),await trySpawnNativeHost())){await new Promise(r=>setTimeout(r,1200));let target=listLiveBrowsers().find(browser=>isConnectedBrowser(browser)&&(!localOnly||browser.transport!=="provider")&&!(transport==="cdp"&&browser.transport==="provider")&&supportsAction(browser,action,data2));return target?invokeOnce(action,data2,timeoutSec,transport,target.socketPath,controlSource,target.transport==="provider"?target.browserId:void 0):invokeViaLegacy(action,data2,timeoutSec,transport,controlSource,!0,localOnly)}throw err instanceof Error&&!isConnError(err)&&!isSocketSandboxError(err)?err:new Error(formatConnectError(err,SOCKET_PATH),{cause:error2})}}async function invokeOnce(action,data2,timeoutSec,transport,socketPath,controlSource,providerTarget){providerTarget&&(socketPath=(await ensureProviderControlHost(Math.min(timeoutSec*1e3,1e4))).socketPath);let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`,deadline=Date.now()+Math.ceil(timeoutSec*1e3);return new Promise((resolve7,reject)=>{if(process.platform!=="win32"&&fs4.existsSync(socketPath)&&process.getuid&&fs4.statSync(socketPath).uid!==process.getuid()){let error2=new Error(`拒绝连接不属于当前用户的 Socket: ${socketPath}`);Object.assign(error2,{code:"EACCES"}),reject(error2);return}let socket=net2.createConnection(socketPath),settled=!1,buffer="",decoder=new StringDecoder("utf8"),settle=(error2,result)=>{settled||(settled=!0,clearTimeout(timer),socket.removeAllListeners(),socket.end(),error2?reject(error2 instanceof Error?error2:new Error(String(error2))):resolve7(result))},timer=setTimeout(()=>{settle(new Error(`请求超时,已等待 ${timeoutSec} 秒`))},timeoutSec*1e3);socket.on("connect",()=>{let message={id,action,data:data2,version:CLIENT_VERSION,protocolVersion:3,controlSource:toControlSourceWireValue(controlSource)};data2[SESSION_OPTION]&&(message.controlSessionId=data2[SESSION_OPTION]),transport&&(message.transport=transport),providerTarget&&(message.providerTarget=providerTarget,message.deadline=deadline),socket.write(JSON.stringify(message)+`
607
+ </style>`,PLUGIN_PAGE_RUNTIME_HASH=createHash2("sha256").update(PAGE_BRIDGE_SCRIPT).update(PAGE_SECURITY_META).update(PAGE_THEME_STYLE).digest("hex")}});import{randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync3,mkdirSync as mkdirSync2,openSync as openSync3,readFileSync as readFileSync5,readSync,readdirSync as readdirSync4,renameSync as renameSync3,rmSync as rmSync3,statSync as statSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{isAbsolute as isAbsolute2,join as join5,resolve as resolve2}from"node:path";function pluginRegistrationNeedsRefresh(registration,includePage=!1){return!registration.source||pluginFileVersion(registration.entry)!==registration.source.entry||Object.entries(registration.source.profiles??{}).some(([path7,version])=>{try{return pluginFileVersion(path7)!==version}catch{return!0}})?!0:!includePage||!registration.toolbox?!1:registration.source.pageRuntime!==PLUGIN_PAGE_RUNTIME_HASH||!registration.source.page?!0:Object.entries(registration.source.page).some(([path7,version])=>pluginFileVersion(path7)!==version)}function pluginDirectory(){return resolve2(process.env.MEARL_PLUGIN_DIR||join5(homedir2(),".mearl","plugins"))}function pluginPageDirectory(){return join5(pluginDirectory(),".pages")}function pluginPageBundlePath(name,hash){return join5(pluginPageDirectory(),`${name}-${hash}.html`)}function removePluginPageBundles(name,exceptHash){let files;try{files=readdirSync4(pluginPageDirectory())}catch(error2){if(error2.code==="ENOENT")return;throw error2}let keep=exceptHash?`${name}-${exceptHash}.html`:void 0;for(let file of files)file===keep||!file.startsWith(`${name}-`)||!file.endsWith(".html")||rmSync3(join5(pluginPageDirectory(),file),{force:!0})}function normalizePageBundle(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("invalid page bundle");let candidate=value;if(typeof candidate.hash!="string"||!/^[a-f0-9]{64}$/.test(candidate.hash)||!Number.isInteger(candidate.size)||(candidate.size??0)<=0||!Number.isInteger(candidate.chunks)||candidate.chunks!==Math.ceil((candidate.size??0)/PLUGIN_PAGE_CHUNK_BYTES))throw new Error("invalid page bundle");return{hash:candidate.hash,size:candidate.size,chunks:candidate.chunks}}function persistPluginPageBundle(name,bundle){let directory=pluginPageDirectory();mkdirSync2(directory,{recursive:!0,mode:448});let target=pluginPageBundlePath(name,bundle.hash);try{if(statSync4(target).isFile())return}catch{}let temporary=`${target}.${randomUUID2()}.tmp`;try{writeFileSync2(temporary,bundle.content,{mode:384,flag:"wx"}),renameSync3(temporary,target)}finally{rmSync3(temporary,{force:!0})}}function assertPluginName(name){if(!/^[a-z][a-z0-9_-]*$/.test(name)||RESERVED_NAMES.has(name)||COMMAND_MAP.has(name))throw new PluginError("PLUGIN_INVALID_NAME",`不可用的插件名称: ${name}`)}function normalizePluginToolboxContribution(value){if(value===void 0)return;if(!value||typeof value!="object"||Array.isArray(value))throw new Error("toolbox 必须是对象");let candidate=value;if(candidate.displayMode!==void 0&&!["popup","tab","both"].includes(candidate.displayMode))throw new Error("toolbox.displayMode 必须是 popup、tab 或 both");let title=typeof candidate.title=="string"?candidate.title.trim():"",description=typeof candidate.description=="string"?candidate.description.trim():void 0,icon=typeof candidate.icon=="string"?candidate.icon.trim():void 0;if(candidate.version!==1)throw new Error("toolbox.version 必须为 1");if(!title||title.length>80)throw new Error("toolbox.title 必须是 1-80 个字符");if(description&&description.length>240)throw new Error("toolbox.description 不能超过 240 个字符");if(icon&&!parseToolboxIcon(icon))throw new Error("toolbox.icon 必须是图标名称、SVG、图片 Data URL 或 HTTP(S) 图片地址,最多 32768 个字符");let locales;if(candidate.locales!==void 0){if(!candidate.locales||typeof candidate.locales!="object"||Array.isArray(candidate.locales))throw new Error("toolbox.locales 必须是对象");let entries=Object.entries(candidate.locales);if(entries.length===0||entries.length>20)throw new Error("toolbox.locales 必须包含 1-20 个语言");locales=Object.fromEntries(entries.map(([locale,localized])=>{if(!/^[a-z]{2,3}(?:[_-][A-Za-z0-9]{2,8})*$/.test(locale))throw new Error(`toolbox.locales 包含无效语言: ${locale}`);if(!localized||typeof localized!="object"||Array.isArray(localized))throw new Error(`toolbox.locales.${locale} 必须是对象`);let localizedTitle=typeof localized.title=="string"?localized.title.trim():void 0,localizedDescription=typeof localized.description=="string"?localized.description.trim():void 0;if(localizedTitle!==void 0&&(!localizedTitle||localizedTitle.length>80))throw new Error(`toolbox.locales.${locale}.title 必须是 1-80 个字符`);if(localizedDescription!==void 0&&localizedDescription.length>240)throw new Error(`toolbox.locales.${locale}.description 不能超过 240 个字符`);if(!localizedTitle&&!localizedDescription)throw new Error(`toolbox.locales.${locale} 至少声明 title 或 description`);return[locale,{...localizedTitle?{title:localizedTitle}:{},...localizedDescription?{description:localizedDescription}:{}}]}))}if(!candidate.page||typeof candidate.page!="object"||Array.isArray(candidate.page))throw new Error("toolbox.page 必须是对象");let pageCandidate=candidate.page;if(pageCandidate.type!=="sandbox")throw new Error("toolbox.page.type 必须为 sandbox");if(pageCandidate.runtime!==void 0&&pageCandidate.runtime!=="preact")throw new Error("toolbox.page.runtime 仅支持 preact");let pageEntry=typeof pageCandidate.entry=="string"?pageCandidate.entry.trim():"";if(!pageEntry||pageEntry.length>240||isAbsolute2(pageEntry)||pageEntry.includes("\\")||pageEntry.split("/").some(segment=>!segment||segment==="."||segment===".."))throw new Error("toolbox.page.entry 必须是插件目录内的相对 HTML 路径");if(!Array.isArray(pageCandidate.commands))throw new Error("toolbox.page.commands 必须是命令名称数组");let commands=pageCandidate.commands.map(command=>typeof command=="string"?command.trim():"");if(commands.length===0||commands.length>64||new Set(commands).size!==commands.length||commands.some(command=>!/^[a-z][a-z0-9-]*$/.test(command)))throw new Error("toolbox.page.commands 必须包含 1-64 个不重复的插件命令名称");let page={type:"sandbox",...pageCandidate.runtime?{runtime:pageCandidate.runtime}:{},entry:pageEntry,commands};if("lifecycle"in pageCandidate)throw new Error("toolbox.page.lifecycle is unsupported; declare pageRuntime and activation rules");let agent;if(candidate.agent!==void 0){if(!candidate.agent||typeof candidate.agent!="object"||Array.isArray(candidate.agent))throw new Error("toolbox.agent 必须是对象");let agentCandidate=candidate.agent,skill=typeof agentCandidate.skill=="string"?agentCandidate.skill.trim():"";if(!skill||skill.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(skill))throw new Error("toolbox.agent.skill 必须是有效的 Skill 名称");let layout=agentCandidate.layout;if(layout!==void 0&&layout!=="drawer"&&layout!=="workspace")throw new Error("toolbox.agent.layout 必须是 drawer 或 workspace");agent={skill,...layout?{layout}:{}}}if(candidate.order!==void 0&&(!Number.isInteger(candidate.order)||candidate.order<0||candidate.order>1e4))throw new Error("toolbox.order 必须是 0-10000 的整数");return{version:1,title,...candidate.displayMode!==void 0?{displayMode:candidate.displayMode}:{},...description?{description}:{},...icon?{icon}:{},...locales?{locales}:{},...agent?{agent}:{},page,...candidate.order!==void 0?{order:candidate.order}:{}}}function findPluginDirectoryEntry(directory){for(let filename of["main.mjs","main.py"]){let entry=join5(directory,"scripts",filename);try{if(statSync4(entry).isFile())return entry}catch{}}}function resolvePluginEntry(target){let absolute=resolve2(target);try{let entry=statSync4(absolute).isDirectory()?findPluginDirectoryEntry(absolute):absolute;if(!entry)throw new Error("not a file");if(!statSync4(entry).isFile())throw new Error("not a file");return entry}catch{throw new PluginError("PLUGIN_ENTRY_MISSING",`入口不存在: ${absolute}(目录默认使用 scripts/main.mjs 或 scripts/main.py)`)}}function registerPlugin(name,target,description,options={}){assertPluginName(name);let entry=resolvePluginEntry(target),entryVersion=pluginFileVersion(entry),directory=pluginDirectory();mkdirSync2(directory,{recursive:!0,mode:448});let file=join5(directory,`${name}.json`),temporary=`${file}.${randomUUID2()}.tmp`,summary=description?.trim(),managedBy=options.managedBy?.trim(),toolbox;try{toolbox=normalizePluginToolboxContribution(options.toolbox)}catch(error2){throw new PluginError("PLUGIN_INVALID_TOOLBOX",error2 instanceof Error?error2.message:String(error2))}let builtPage;if(toolbox){try{builtPage=buildPluginPageBundle(entry,toolbox.page.entry)}catch(error2){throw new PluginError("PLUGIN_INVALID_TOOLBOX_PAGE",error2 instanceof Error?error2.message:String(error2))}persistPluginPageBundle(name,builtPage)}let record2={entry,...options.hasPublicCommands!==void 0?{hasPublicCommands:options.hasPublicCommands}:{},source:{entry:entryVersion,...options.profileSources?{profiles:options.profileSources}:{},...builtPage?{page:builtPage.sources,pageRuntime:PLUGIN_PAGE_RUNTIME_HASH}:{}},...summary?{description:summary}:{},...managedBy?{managedBy}:{},...toolbox?{toolbox}:{},...options.appProfiles?{appProfiles:validateAppProfileContribution(options.appProfiles)}:{},...builtPage?{pageBundle:{hash:builtPage.hash,size:builtPage.size,chunks:builtPage.chunks}}:{}};try{writeFileSync2(temporary,`${JSON.stringify(record2)}
608
+ `,{mode:384,flag:"wx"}),renameSync3(temporary,file)}finally{rmSync3(temporary,{force:!0})}return removePluginPageBundles(name,builtPage?.hash),entry}function unregisterPlugin(name){assertPluginName(name);let file=join5(pluginDirectory(),`${name}.json`);try{return rmSync3(file),rmSync3(join5(pluginDirectory(),".host","installations",`${name}.json`),{force:!0}),removePluginPageBundles(name),!0}catch(error2){if(error2.code==="ENOENT")return!1;throw new PluginError("PLUGIN_UNINSTALL_FAILED",`无法移除插件注册: ${file}`)}}function findPluginRegistration(name){if(!/^[a-z][a-z0-9_-]*$/.test(name))return;let file=join5(pluginDirectory(),`${name}.json`),content;try{content=readFileSync5(file,"utf8")}catch(error2){if(error2.code==="ENOENT")return;throw new PluginError("PLUGIN_REGISTRY_INVALID",`无法读取插件记录: ${file}`)}try{let record2=JSON.parse(content);if(typeof record2?.entry!="string"||!isAbsolute2(record2.entry))throw new Error("invalid entry");if(record2.hasPublicCommands!==void 0&&typeof record2.hasPublicCommands!="boolean")throw new Error("invalid public commands");let description=typeof record2.description=="string"&&record2.description.trim()?record2.description.trim():void 0,managedBy=typeof record2.managedBy=="string"&&record2.managedBy.trim()?record2.managedBy.trim():void 0,toolbox=normalizePluginToolboxContribution(record2.toolbox),pageBundle=toolbox?normalizePageBundle(record2.pageBundle):void 0,appProfiles=validateAppProfileContribution(record2.appProfiles),source=record2.source;if(source!==void 0&&(!source||typeof source!="object"||Array.isArray(source)||typeof source.entry!="string"||source.profiles!==void 0&&(!source.profiles||typeof source.profiles!="object"||Array.isArray(source.profiles)||Object.entries(source.profiles).some(([path7,version])=>!isAbsolute2(path7)||typeof version!="string"))||source.pageRuntime!==void 0&&(typeof source.pageRuntime!="string"||!/^[a-f0-9]{64}$/.test(source.pageRuntime))||source.page!==void 0&&(!source.page||typeof source.page!="object"||Array.isArray(source.page)||Object.entries(source.page).some(([path7,version])=>!isAbsolute2(path7)||typeof version!="string"))))throw new Error("invalid source");return{entry:record2.entry,...record2.hasPublicCommands!==void 0?{hasPublicCommands:record2.hasPublicCommands}:{},...description?{description}:{},...managedBy?{managedBy}:{},...toolbox?{toolbox}:{},...pageBundle?{pageBundle}:{},...appProfiles?{appProfiles}:{},...source?{source}:{}}}catch(cause){let reason=cause instanceof SyntaxError?"JSON 格式错误":cause instanceof Error?cause.message:"未知校验错误";throw new PluginError("PLUGIN_REGISTRY_INVALID",`无效的插件记录: ${file} (${reason})`,{cause})}}function readPluginPageBundleChunk(name,hash,index){assertPluginName(name);let bundle=findPluginRegistration(name)?.pageBundle;if(!bundle||bundle.hash!==hash)throw new PluginError("PLUGIN_PAGE_CHANGED",`插件页面已更新: ${name}`);if(!Number.isInteger(index)||index<0||index>=bundle.chunks)throw new PluginError("PLUGIN_PAGE_CHUNK_INVALID",`插件页面分块无效: ${index}`);let path7=pluginPageBundlePath(name,hash),size;try{size=statSync4(path7).size}catch{throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物不存在: ${name}`)}if(size!==bundle.size)throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物损坏: ${name}`);let start=index*PLUGIN_PAGE_CHUNK_BYTES,content=Buffer.allocUnsafe(Math.min(PLUGIN_PAGE_CHUNK_BYTES,bundle.size-start)),descriptor;try{descriptor=openSync3(path7,"r")}catch{throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物无法读取: ${name}`)}let bytesRead;try{bytesRead=readSync(descriptor,content,0,content.byteLength,start)}finally{closeSync3(descriptor)}if(bytesRead!==content.byteLength)throw new PluginError("PLUGIN_PAGE_INVALID",`插件页面产物损坏: ${name}`);return{data:content.toString("base64"),hash,index,total:bundle.chunks}}function findPluginEntry(name){return findPluginRegistration(name)?.entry}function listPluginNames(){try{return readdirSync4(pluginDirectory()).filter(file=>/^[a-z][a-z0-9_-]*\.json$/.test(file)).map(file=>file.slice(0,-5)).sort()}catch(error2){if(error2.code==="ENOENT")return[];throw new PluginError("PLUGIN_REGISTRY_INVALID","无法读取插件目录")}}var RESERVED_NAMES,PluginError,init_pluginRegistry=__esm({"../client/src/plugins/pluginRegistry.ts"(){"use strict";init_dist2();init_dist2();init_commands();init_pluginPageBundle();init_pluginSource();RESERVED_NAMES=new Set(["guide","check","run","help","connector_list","capture_checkpoint","plugin","plugins","plugin_state","plugin_model","plugin_page","plugin_invoke_child","plugin_task_checkpoint"]),PluginError=class extends Error{constructor(code,message,options){super(`${code}: ${message}`,options);this.code=code}code}}});import{createHash as createHash3}from"node:crypto";import{tmpdir}from"node:os";import{join as join6}from"node:path";function pluginHostPaths(){let registry=pluginDirectory(),key2=createHash3("sha256").update(registry).digest("hex").slice(0,16),home=join6(registry,".host");return{registry,home,lease:join6(home,"service.json"),log:join6(home,"service.log"),installations:join6(home,"installations"),revisions:join6(home,"revisions"),tasks:join6(home,"tasks"),state:join6(home,"state"),socket:process.platform==="win32"?`\\\\.\\pipe\\mearl-plugin-${key2}`:join6(tmpdir(),`mp-${key2}.sock`)}}var init_pluginHostPaths=__esm({"../client/src/plugins/runtime/pluginHostPaths.ts"(){"use strict";init_pluginRegistry()}});var CODEX_MODEL_CAPABILITY,init_capabilities=__esm({"../agent-runtime/dist/capabilities.js"(){"use strict";CODEX_MODEL_CAPABILITY={provider:"codex",modes:["agent"],permissions:["read-only"],structuredOutput:!0,streaming:!0,cancellation:!0}}});var pluginModelDefinition_exports={};__export(pluginModelDefinition_exports,{normalizePluginModel:()=>normalizePluginModel,pluginModelCapabilities:()=>pluginModelCapabilities,validatePluginModelResult:()=>validatePluginModelResult});function pluginModelCapabilities(){return{providers:[CODEX_MODEL_CAPABILITY]}}function normalizePluginModel(value){let request=value;if(!request||typeof request!="object"||Array.isArray(request)||typeof request.prompt!="string"||!request.prompt.trim()||Buffer.byteLength(JSON.stringify(request))>256*1024||request.instructions!==void 0&&typeof request.instructions!="string"||request.conversation!==void 0&&(typeof request.conversation!="string"||!/^[a-zA-Z0-9:_-]{1,80}$/.test(request.conversation))||request.model!==void 0&&(typeof request.model!="string"||!request.model.trim()||request.model.length>256)||request.reasoningEffort!==void 0&&!["none","minimal","low","medium","high","xhigh","max"].includes(request.reasoningEffort)||Object.keys(request).some(key2=>!["provider","mode","prompt","instructions","model","reasoningEffort","outputSchema","permissions","conversation"].includes(key2)))throw new Error("Invalid model execution request");let capability=pluginModelCapabilities().providers.find(item=>item.provider===request.provider);if(!capability?.modes.includes(request.mode)||request.mode==="agent"&&!capability.permissions.includes(request.permissions)||request.mode==="generate"&&request.permissions!==void 0)throw Object.assign(new Error("Requested model mode or permissions are unsupported; choose an advertised capability explicitly"),{code:"PLUGIN_MODEL_CAPABILITY_UNSUPPORTED"});if(request.outputSchema!==void 0&&(!capability.structuredOutput||!request.outputSchema||typeof request.outputSchema!="object"||Array.isArray(request.outputSchema)||request.outputSchema.$async||Buffer.byteLength(JSON.stringify(request.outputSchema))>64*1024))throw new Error("Invalid model output schema");return JSON.parse(JSON.stringify(request))}function validatePluginModelResult(request,value){let result=value;if(!result||typeof result.text!="string"||result.provider!==request.provider||result.mode!==request.mode)throw new Error("Invalid model execution result");if(request.outputSchema){let output;try{output=JSON.parse(result.text)}catch{throw Object.assign(new Error("Model returned invalid JSON"),{code:"PLUGIN_MODEL_SCHEMA_INVALID"})}return{...result,output}}return result}var init_pluginModelDefinition=__esm({"../client/src/plugins/sdk/pluginModelDefinition.ts"(){"use strict";init_capabilities()}});import{createHash as createHash4}from"node:crypto";function normalizePluginTaskRecovery(value){if(value===void 0)return;let declaration=JSON.parse(JSON.stringify(value));if(!declaration||declaration.version!==1||!declaration.commands||typeof declaration.commands!="object"||Array.isArray(declaration.commands)||Object.keys(declaration.commands).length>32||Buffer.byteLength(JSON.stringify(declaration))>128*1024)throw new Error("Invalid taskRecovery declaration");for(let[command,definition]of Object.entries(declaration.commands)){if(!/^[a-z][a-z0-9-]*$/.test(command)||!definition||!Number.isSafeInteger(definition.checkpointVersion)||definition.checkpointVersion<1||!definition.schema||typeof definition.schema!="object"||Array.isArray(definition.schema)||definition.schema.$async)throw new Error("Invalid task checkpoint definition");if(definition.migrateFrom!==void 0){if(!Array.isArray(definition.migrateFrom)||definition.migrateFrom.length<1||definition.migrateFrom.length>16)throw new Error("Invalid checkpoint migration sources");let versions=new Set;for(let source of definition.migrateFrom){if(!source||!Number.isSafeInteger(source.version)||source.version<1||source.version>=definition.checkpointVersion||versions.has(source.version)||!source.schema||typeof source.schema!="object"||Array.isArray(source.schema)||source.schema.$async)throw new Error("Checkpoint migrations require distinct older versions and schemas");versions.add(source.version)}}}return declaration}function pluginRecoverySignature(value){return createHash4("sha256").update(JSON.stringify(value,(_key,item)=>item&&typeof item=="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a<b?-1:a>b?1:0)):item)).digest("hex")}var init_pluginRecoveryDefinition=__esm({"../client/src/plugins/sdk/pluginRecoveryDefinition.ts"(){"use strict"}});import{randomUUID as randomUUID3}from"node:crypto";import{linkSync as linkSync2,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync as rmSync4,writeFileSync as writeFileSync3}from"node:fs";import{join as join7}from"node:path";function localPluginExecutionHost(){let directory=pluginDirectory(),hostId=hostIds.get(directory);if(!hostId){mkdirSync3(directory,{recursive:!0,mode:448});let file=join7(directory,".execution-host-id"),proposed=randomUUID3(),temporary=`${file}.${proposed}.tmp`;try{writeFileSync3(temporary,proposed,{flag:"wx",mode:384}),linkSync2(temporary,file)}catch(error2){if(error2.code!=="EEXIST")throw error2}finally{rmSync4(temporary,{force:!0})}if(hostId=readFileSync6(file,"utf8").trim(),!UUID.test(hostId))throw new Error("Invalid plugin execution host identity");hostIds.set(directory,hostId)}return Object.freeze({hostId,epoch})}function createPluginInvocationIdentity(plugin,source,parent){return Object.freeze({invocationId:randomUUID3(),host:parent?.host??localPluginExecutionHost(),plugin,source,...parent?{parentInvocationId:parent.invocationId}:{}})}var epoch,hostIds,UUID,init_pluginExecution2=__esm({"../client/src/plugins/runtime/pluginExecution.ts"(){"use strict";init_pluginRegistry();epoch=randomUUID3(),hostIds=new Map,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i}});function serializePluginExecutionError(error2){let value=error2,metadata=Object.fromEntries(Object.entries(value&&typeof value=="object"?value:{}).filter(([key2,field])=>!["__proto__","prototype","constructor","message","stack","code","details"].includes(key2)&&(field===null||["string","number","boolean"].includes(typeof field)))),serialized={message:typeof value?.message=="string"?value.message:String(error2),...typeof value?.code=="string"?{code:value.code}:{},...value?.details&&typeof value.details=="object"&&!Array.isArray(value.details)?{details:value.details}:{},...Object.keys(metadata).length?{metadata}:{}};try{if(Buffer.byteLength(JSON.stringify(serialized))<=64*1024)return serialized}catch{}return{message:Buffer.from(serialized.message).subarray(0,8192).toString("utf8"),...serialized.code?{code:serialized.code.slice(0,256)}:{},details:{diagnosticTruncated:!0},metadata:Object.fromEntries(Object.entries(metadata).slice(0,32).map(([key2,field])=>[key2.slice(0,128),typeof field=="string"?field.slice(0,512):field]))}}function pluginExecutionError(value){return Object.assign(new Error(value.message),{...Object.fromEntries(Object.entries(value.metadata??{}).filter(([key2])=>!["__proto__","prototype","constructor","message","stack","code","details"].includes(key2))),...value.code?{code:value.code}:{},...value.details?{details:value.details}:{}})}var init_pluginExecutorProtocol=__esm({"../client/src/plugins/runtime/pluginExecutorProtocol.ts"(){"use strict"}});import{execFile}from"node:child_process";async function stopPluginProcessTree(pid){if(!Number.isSafeInteger(pid)||pid<1)throw new Error("Invalid plugin process group");if(process.platform==="win32")return new Promise((resolve7,reject)=>{execFile("taskkill",["/PID",String(pid),"/T","/F"],{windowsHide:!0,timeout:5e3},error2=>{error2?reject(error2):resolve7()})});try{process.kill(-pid,"SIGKILL")}catch(error2){if(error2.code==="ESRCH")return;throw error2}let deadline=Date.now()+5e3;for(;isProcessGroupAlive(pid);){if(Date.now()>=deadline)throw new Error("Unable to confirm plugin process group stopped");await new Promise(resolve7=>setTimeout(resolve7,20))}}var init_pluginProcessTree=__esm({"../client/src/plugins/runtime/pluginProcessTree.ts"(){"use strict";init_dist()}});import{fork}from"node:child_process";async function executeRegisteredPlugin(plugin,invocation,context,options={},dependencies={}){let{signal,onProgress,source,access="public",executionTimeoutMs,cancellationGraceMs=1e3,workerPath,cwd,environment,describe,help,onOutput,model,recovery,migration,expectedRecovery,onExecutorStarted,onExecutorStopped,onDiagnostic,...invokeOptions}=options;for(let[name,value]of[["executionTimeoutMs",executionTimeoutMs],["cancellationGraceMs",cancellationGraceMs]])if(value!==void 0&&(!Number.isSafeInteger(value)||value<1||value>2147483647))throw new Error(`${name} must be a positive integer within the timer range`);signal?.throwIfAborted();let registration=dependencies.registration??findPluginRegistration(plugin);if(!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${plugin}`);let identity=context.invocation??createPluginInvocationIdentity(plugin,source??context.source??"sdk",context.parentInvocation),entryVersion=pluginFileVersion(registration.entry);return new Promise((resolve7,reject)=>{let child=fork(workerPath??PLUGIN_WORKER_PATH,[],{stdio:["ignore",onOutput?"pipe":"ignore","pipe","ipc"],serialization:"advanced",execArgv:[],detached:process.platform!=="win32",...cwd?{cwd}:{},...environment?{env:environment}:{}}),stderr="",outcome,stopping,cleanupError,treeStopRequested=!1,treeCleanup=Promise.resolve(),exited=!1,graceTimer,deadlineTimer,pendingActions=new Map;if(child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderr=`${stderr}${chunk}`.slice(-65536)}),onOutput)for(let stream of["stdout","stderr"])child[stream]?.on("data",chunk=>{try{onOutput(stream,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk))}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}});let send=message=>{if(!(!child.connected||exited))try{child.send(message,error2=>{error2&&!exited&&stop(error2)})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}},kill=()=>{if(!child.pid||exited||treeStopRequested)return;treeStopRequested=!0;let pid=child.pid;treeCleanup=Promise.resolve().then(()=>(dependencies.stopProcessTree??stopPluginProcessTree)(pid)).catch(()=>{cleanupError=Object.assign(new Error("Unable to confirm plugin process-tree cleanup"),{code:"PLUGIN_EXECUTOR_CLEANUP_FAILED",details:{executionStopped:!1}}),child.kill("SIGKILL")})},stop=error2=>{stopping||outcome||exited||(stopping=error2,send({type:"cancel",error:serializePluginExecutionError(error2)}),graceTimer=setTimeout(kill,cancellationGraceMs))},abort=()=>stop(Object.assign(new Error("Plugin execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"}));signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted&&abort(),executionTimeoutMs!==void 0&&(deadlineTimer=setTimeout(()=>stop(Object.assign(new Error("Plugin execution deadline exceeded"),{code:"PLUGIN_EXECUTION_DEADLINE"})),executionTimeoutMs)),child.on("message",raw=>{if(!(exited||!raw||typeof raw!="object")){if(raw.type==="result"||raw.type==="error"){if(!outcome&&!stopping)try{outcome=raw.type==="result"?{value:JSON.parse(raw.json).value}:{error:pluginExecutionError(raw.error)},raw.type==="result"&&pendingActions.size&&(outcome={error:Object.assign(new Error("Plugin returned with pending host calls"),{code:"PLUGIN_PENDING_HOST_CALLS",details:{pendingActions:[...pendingActions.values()]}})})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}kill();return}if(!(stopping||outcome))if(raw.type==="diagnostic"&&model)try{onDiagnostic?.(raw.metadata)}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}else if(raw.type==="progress")try{onProgress?.(raw.progress)}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}else raw.type==="invoke"&&(pendingActions.set(raw.id,raw.action),Promise.resolve().then(()=>{if(stopping||exited)throw stopping??new Error("Plugin execution ended");let options2={...invokeOptions,...raw.options};return raw.stream?context.invoke(raw.action,raw.payload,options2,progress=>{!stopping&&!outcome&&pendingActions.has(raw.id)&&send({type:"invoke-progress",id:raw.id,progress})}):context.invoke(raw.action,raw.payload,options2)}).then(result=>send({type:"response",id:raw.id,result}),error2=>send({type:"response",id:raw.id,error:serializePluginExecutionError(error2)})).finally(()=>pendingActions.delete(raw.id)))}});let cleanup=()=>{exited=!0,signal?.removeEventListener("abort",abort),graceTimer&&clearTimeout(graceTimer),deadlineTimer&&clearTimeout(deadlineTimer)};child.once("error",error2=>{cleanup(),reject(error2)}),child.once("exit",()=>{kill(),child.stderr?.destroy()}),child.once("close",(code,exitSignal)=>{cleanup(),treeCleanup.then(()=>{if(!cleanupError&&treeStopRequested)try{onExecutorStopped?.()}catch(error2){reject(error2);return}cleanupError?reject(cleanupError):stopping?(Object.assign(stopping,{details:{pendingActions:[...pendingActions.values()],executionStopped:!0}}),reject(stopping)):outcome?.error?reject(outcome.error):outcome?resolve7(outcome.value):reject(Object.assign(new Error(stderr.trim()||`Plugin executor exited (${code??exitSignal})`),{code:"PLUGIN_EXECUTOR_EXITED"}))})});try{child.pid&&onExecutorStarted?.({pid:child.pid,processIdentity:processIdentity(child.pid)}),send({type:"start",plugin,invocation,options:invokeOptions,identity,entry:registration.entry,entryVersion,access,describe,help,model,recovery,migration,expectedRecovery,...dependencies.registration?{registration}:{}})}catch(error2){stop(error2 instanceof Error?error2:new Error(String(error2)))}})}var init_pluginExecutor=__esm({"../client/src/plugins/runtime/pluginExecutor.ts"(){"use strict";init_runtimePaths();init_pluginRegistry();init_pluginSource();init_pluginExecution2();init_pluginExecutorProtocol();init_pluginProcessTree();init_dist()}});import{existsSync as existsSync3,lstatSync,readFileSync as readFileSync7,renameSync as renameSync4,statSync as statSync5}from"node:fs";import{join as join8}from"node:path";function readInstalledSkillMetadata(directory){if(existsSync3(join8(directory,"SKILL.md"))&&existsSync3(join8(directory,DISABLED_SKILL_MANIFEST)))throw new Error("Conflicting installed Skill manifests");let file=skillManifestPath(directory);if(!file)return;let info=statSync5(file);if(!info.isFile()||info.size>1024*1024)throw new Error("Invalid installed Skill manifest");let frontmatter=readFileSync7(file,"utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];if(!frontmatter)return{};let scalar=key2=>{let lines=frontmatter.split(/\r?\n/).filter(line=>line.startsWith(key2+":"));if(lines.length===1)return lines[0].match(/^[\w-]+:\s*(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s#"']+))\s*(?:#.*)?$/)?.slice(1).find(value=>value!==void 0)};return{name:scalar("name"),version:scalar("version")}}function skillManifestPath(directory){for(let name of["SKILL.md",DISABLED_SKILL_MANIFEST]){let file=join8(directory,name);if(existsSync3(file))return file}}var DISABLED_SKILL_MANIFEST,init_skillManifest=__esm({"../client/src/plugins/skillManifest.ts"(){"use strict";DISABLED_SKILL_MANIFEST="SKILL.md.mearl-disabled"}});import{randomUUID as randomUUID5}from"node:crypto";import{closeSync as closeSync4,fsyncSync,mkdirSync as mkdirSync5,openSync as openSync4,renameSync as renameSync6,rmSync as rmSync6,writeFileSync as writeFileSync5}from"node:fs";import{dirname as dirname5}from"node:path";function writePluginHostFile(file,data){mkdirSync5(dirname5(file),{recursive:!0,mode:448});let temporary=`${file}.${randomUUID5()}.tmp`,descriptor;try{descriptor=openSync4(temporary,"wx",384),writeFileSync5(descriptor,data),fsyncSync(descriptor),closeSync4(descriptor),descriptor=void 0,renameSync6(temporary,file)}finally{descriptor!==void 0&&closeSync4(descriptor),rmSync6(temporary,{force:!0})}}var init_pluginHostFiles=__esm({"../client/src/plugins/runtime/pluginHostFiles.ts"(){"use strict"}});import{createHash as createHash6}from"node:crypto";import{closeSync as closeSync5,openSync as openSync5,opendirSync,readFileSync as readFileSync9,readSync as readSync2,readdirSync as readdirSync6,rmSync as rmSync7,statSync as statSync7}from"node:fs";import{join as join10}from"node:path";function pluginTaskExecutionUnconfirmed(record2){let owner=record2.executorOwner;return owner&&(!Number.isSafeInteger(owner.pid)||owner.pid<1)||owner&&isProcessOwnerAlive(owner)||record2.task.error?.details?.executionStopped===!1||process.platform==="win32"&&record2.task.error?.code==="PLUGIN_TASK_HOST_RESTARTED"?!0:owner&&process.platform!=="win32"?isProcessGroupAlive(owner.pid):!1}var PLUGIN_TASK_RESULT_CHUNK_BYTES,MAX_EVENT_BYTES,MAX_RESULT_BYTES,RETENTION_MS,PluginTaskStore,init_pluginTaskStore=__esm({"../client/src/plugins/runtime/pluginTaskStore.ts"(){"use strict";init_dist2();init_pluginHostFiles();init_pluginHostPaths();init_dist();PLUGIN_TASK_RESULT_CHUNK_BYTES=192*1024,MAX_EVENT_BYTES=512*1024,MAX_RESULT_BYTES=64*1024*1024,RETENTION_MS=10080*60*1e3;PluginTaskStore=class{constructor(directory=pluginHostPaths().tasks){this.directory=directory}directory;activeTaskIds;dedupeIndex;dedupeKeys=new Map;forgetDedupe(taskId){let key2=this.dedupeKeys.get(taskId);if(!key2)return;let ids=this.dedupeIndex?.get(key2);ids?.delete(taskId),ids?.size||this.dedupeIndex?.delete(key2),this.dedupeKeys.delete(taskId)}indexDedupe(record2){if(!this.dedupeIndex)return;let{dedupeKey:key2,task}=record2,keep=key2&&(!key2.startsWith("active:")||isPluginTaskActive(task.state));if(keep&&this.dedupeKeys.get(task.taskId)===key2||(this.forgetDedupe(task.taskId),!keep))return;let ids=this.dedupeIndex.get(key2)??new Set;ids.add(task.taskId),this.dedupeIndex.set(key2,ids),this.dedupeKeys.set(task.taskId,key2)}findDedupe(key2,activeOnly=!1){if(!this.dedupeIndex){this.dedupeIndex=new Map;for(let record2 of this.list())this.indexDedupe(record2)}for(let taskId of this.dedupeIndex.get(key2)??[]){let record2;try{record2=this.read(taskId)}catch(error2){if(error2.code!=="PLUGIN_TASK_NOT_FOUND")throw error2;this.forgetDedupe(taskId);continue}if(this.indexDedupe(record2),record2.dedupeKey===key2&&(!activeOnly||isPluginTaskActive(record2.task.state)))return record2}}path(taskId,file){if(!isPluginTaskId(taskId))throw Object.assign(new Error("Invalid plugin task ID"),{code:"PLUGIN_TASK_INVALID_ID"});return join10(this.directory,taskId,file)}read(taskId){let record2;try{record2=JSON.parse(readFileSync9(this.path(taskId,"task.json"),"utf8"))}catch(error2){throw error2.code==="ENOENT"?Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"}):error2}if(record2?.task?.taskId!==taskId||!Array.isArray(record2.events))throw new Error("Invalid persistent plugin task record");return record2}write(record2){writePluginHostFile(this.path(record2.task.taskId,"task.json"),JSON.stringify(record2)),this.indexDedupe(record2),this.indexActive(record2)}indexActive(record2){isPluginTaskActive(record2.task.state)?this.activeTaskIds?.add(record2.task.taskId):this.activeTaskIds?.delete(record2.task.taskId)}listActive(){if(!this.activeTaskIds){this.activeTaskIds=new Set;for(let record2 of this.list())this.indexActive(record2)}let records=[];for(let taskId of this.activeTaskIds)try{let record2=this.read(taskId);this.indexActive(record2),isPluginTaskActive(record2.task.state)&&records.push(record2)}catch(error2){if(error2.code!=="PLUGIN_TASK_NOT_FOUND")throw error2;this.activeTaskIds.delete(taskId)}return records}update(taskId,update,type="state",fields2={}){let record2=this.read(taskId);Object.assign(record2,fields2),record2.task={...record2.task,...update,sequence:record2.task.sequence+1,updatedAt:Date.now()};let event={sequence:record2.task.sequence,time:record2.task.updatedAt,type,state:record2.task.state,...type==="progress"?{progress:record2.task.progress}:{},...type==="checkpoint"?{checkpoint:record2.task.checkpoint}:{}};record2.events.push(event);let bytes=Buffer.byteLength(JSON.stringify(record2.events));for(;record2.events.length>256||bytes>MAX_EVENT_BYTES&&record2.events.length>1;)bytes-=Buffer.byteLength(JSON.stringify(record2.events.shift()))+1;return this.write(record2),record2.task}list(){let names;try{names=readdirSync6(this.directory)}catch(error2){if(error2.code==="ENOENT")return[];throw error2}return names.filter(isPluginTaskId).map(name=>this.read(name))}diagnosticRecords(taskId){let records=[],bytes=0,scanned=0,limited=!1;if(taskId){let size;try{size=statSync7(this.path(taskId,"task.json")).size}catch(error2){if(error2.code==="ENOENT")return{records,limited};throw error2}if(size>16*1024*1024)return{records,limited:!0};records.push(this.read(taskId)),bytes+=size}let directory;try{directory=opendirSync(this.directory)}catch(error2){if(error2.code==="ENOENT")return{records,limited};throw error2}try{let item;for(;(item=directory.readSync())!==null;){if(++scanned>2048){limited=!0;break}if(!(!isPluginTaskId(item.name)||item.name===taskId))try{let size=statSync7(this.path(item.name,"task.json")).size;if(records.length>=512||bytes+size>16*1024*1024){limited=!0;break}bytes+=size,records.push(this.read(item.name))}catch{limited=!0}}}finally{directory.closeSync()}return{records,limited}}events(taskId,cursor){let record2=this.read(taskId);if(!Number.isSafeInteger(cursor)||cursor<0||cursor>record2.task.sequence)throw new Error("Invalid plugin task event cursor");let first=record2.events[0]?.sequence??record2.task.sequence+1,events=[],bytes=0;for(let event of record2.events){if(event.sequence<=cursor)continue;let size=Buffer.byteLength(JSON.stringify(event));if(bytes+size>192*1024&&events.length)break;events.push(event),bytes+=size}return{task:record2.task,events,firstAvailableSequence:first,nextCursor:events.at(-1)?.sequence??cursor,gap:cursor<first-1}}saveResult(taskId,value){let bytes=Buffer.from(JSON.stringify({value}));if(bytes.length>MAX_RESULT_BYTES)throw Object.assign(new Error("Plugin task result exceeds 64 MiB"),{code:"PLUGIN_TASK_RESULT_TOO_LARGE"});return writePluginHostFile(this.path(taskId,"result.json"),bytes),{bytes:bytes.length,sha256:createHash6("sha256").update(bytes).digest("hex"),chunks:Math.ceil(bytes.length/PLUGIN_TASK_RESULT_CHUNK_BYTES)}}resultChunk(taskId,index){let task=this.read(taskId).task;if(task.state!=="success"||!task.result)throw new Error("Plugin task result is not available");if(!Number.isSafeInteger(index)||index<0||index>=task.result.chunks)throw new Error("Invalid plugin task result chunk");let file=this.path(taskId,"result.json");if(statSync7(file).size!==task.result.bytes)throw new Error("Plugin task result size does not match its record");let offset=index*PLUGIN_TASK_RESULT_CHUNK_BYTES,buffer=Buffer.alloc(Math.min(PLUGIN_TASK_RESULT_CHUNK_BYTES,task.result.bytes-offset)),descriptor=openSync5(file,"r");try{if(readSync2(descriptor,buffer,0,buffer.length,offset)!==buffer.length)throw new Error("Plugin task result is incomplete")}finally{closeSync5(descriptor)}return{taskId,index,data:buffer.toString("base64"),...task.result}}recover(epoch2){this.activeTaskIds=new Set;for(let record2 of this.list()){this.indexActive(record2);let{task}=record2;isPluginTaskActive(task.state)&&task.host.epoch!==epoch2?this.update(task.taskId,{state:"interrupted",error:{code:"PLUGIN_TASK_HOST_RESTARTED",message:"The plugin execution service restarted; external operations may need reconciliation"}}):!isPluginTaskActive(task.state)&&Date.now()-task.updatedAt>RETENTION_MS&&!pluginTaskExecutionUnconfirmed(record2)&&(rmSync7(join10(this.directory,task.taskId),{recursive:!0,force:!0}),this.forgetDedupe(task.taskId))}}prune(now=Date.now()){for(let record2 of this.list()){let{task}=record2;!isPluginTaskActive(task.state)&&now-task.updatedAt>RETENTION_MS&&!pluginTaskExecutionUnconfirmed(record2)&&(rmSync7(join10(this.directory,task.taskId),{recursive:!0,force:!0}),this.forgetDedupe(task.taskId))}}}}});import{randomUUID as randomUUID6}from"node:crypto";async function invokePageEvalWithArgs(invoke2,params){if(!Number.isSafeInteger(params.tabId)||params.tabId<0)throw new Error("Invalid target tab");if(resolvePageEvalExpression({expression:params.expression,args:[]}),!Array.isArray(params.args))throw new Error("page_eval args must be an array");if(params.executionWorld!==void 0&&!["main","isolated"].includes(params.executionWorld))throw new Error("Invalid page executionWorld");params.executionWorld==="isolated"&&validatePageUserScriptParams({tabId:params.tabId,worldId:params.worldId??"",code:params.expression});let args=JSON.stringify(params.args);if(args.length>64*1024*1024)throw new Error("Page script arguments must fit within 64 MiB characters");let{args:_args,...request}=params,evaluate=async(expression,transfer=!1)=>{let payload={...request,...transfer?{observe:!1,diagnostics:!1}:{},expression},result=await(transfer?invoke2(payload,!0):invoke2(payload));if(transfer&&result?.action?.success===!1)throw new Error(result.action.error||"page_eval failed");return result};if(args.length+params.expression.length<=CHUNK_CHARACTERS)return evaluate(resolvePageEvalExpression(params));let key2=JSON.stringify("__mearlPageScriptTransfer_"+randomUUID6());try{for(let offset=0;offset<args.length;offset+=CHUNK_CHARACTERS)await evaluate(`void (window[${key2}] = (window[${key2}] || '') + ${JSON.stringify(args.slice(offset,offset+CHUNK_CHARACTERS))})`,!0);return await evaluate(`(() => { const args = JSON.parse(window[${key2}]); delete window[${key2}]; return (${params.expression})(...args); })()`)}finally{await evaluate(`delete window[${key2}]`,!0).catch(()=>{})}}var CHUNK_CHARACTERS,init_pageEvalArguments=__esm({"../client/src/pageEvalArguments.ts"(){"use strict";init_dist2();CHUNK_CHARACTERS=48*1024}});import{open,mkdir,rename,rm,stat}from"node:fs/promises";import path2 from"node:path";import{randomUUID as randomUUID7}from"node:crypto";async function stageFile(client,filePath,options){if(!path2.isAbsolute(filePath))throw new Error("Caller-local file paths must be absolute");let source=await open(filePath,"r"),id,pinned=options;try{let metadata=await source.stat();if(!metadata.isFile()||metadata.size>256*1024*1024)throw new Error("Upload requires a regular file of at most 256 MiB");let created=await client.invoke("__artifact_init",{filename:path2.basename(filePath)},options);pinned={...options,browser:created.browserId},id=created.artifact.artifactId;let offset=0;for await(let chunk of source.createReadStream({highWaterMark:CHUNK_BYTES,autoClose:!1}))await client.invoke("__artifact_write",{artifactId:id,offset,base64:chunk.toString("base64")},pinned),offset+=chunk.length;return await client.invoke("__artifact_complete",{artifactId:id,bytes:offset},pinned),{artifactId:id,options:pinned}}catch(error2){throw id&&await client.invoke("__artifact_remove",{artifactId:id},pinned).catch(()=>{}),error2}finally{await source.close()}}async function exportArtifact(client,artifact,outputPath,options={}){if(!Number.isSafeInteger(artifact.bytes)||artifact.bytes<0)throw new Error("Invalid artifact size");if(!path2.isAbsolute(outputPath))throw new Error("Artifact output paths must be absolute");if(!options.session&&!artifact.browserId&&!options.browser)throw new Error("An artifact requires its originating browser");let pinned={...options,...artifact.browserId?{browser:artifact.browserId}:{}};await mkdir(path2.dirname(outputPath),{recursive:!0});let temporary=`${outputPath}.${randomUUID7()}.part`,target=await open(temporary,"wx",384);try{let offset=0;if(artifact.bytes===0){let empty=await client.invoke("__artifact_read",{artifactId:artifact.artifactId,offset:0},pinned);if(empty.totalBytes!==0||empty.bytes!==0||empty.base64!=="")throw new Error("Artifact export size mismatch")}for(;offset<artifact.bytes;){let chunk=await client.invoke("__artifact_read",{artifactId:artifact.artifactId,offset},pinned),bytes=Buffer.from(chunk.base64,"base64");if(!bytes.length||bytes.length!==chunk.bytes||chunk.totalBytes!==artifact.bytes||offset+bytes.length>artifact.bytes)throw new Error("Invalid artifact chunk or truncated transfer");await target.write(bytes),offset+=bytes.length}if(await target.sync(),await target.close(),(await stat(temporary)).size!==artifact.bytes)throw new Error("Artifact export size mismatch");return await rename(temporary,outputPath),{outputPath,bytes:artifact.bytes}}catch(error2){throw await target.close().catch(()=>{}),await rm(temporary,{force:!0}),error2}}var CHUNK_BYTES,init_artifacts=__esm({"../client/src/artifacts.ts"(){"use strict";CHUNK_BYTES=256*1024}});function resolveCloudConnectorSelector(connectors,selector){let normalized=selector.trim().toLowerCase();if(!normalized)return{status:"not_found"};let resolveMatches=matches=>matches.length===1?{status:"matched",connector:matches[0]}:matches.length>1?{status:"ambiguous"}:null,exactId=resolveMatches(connectors.filter(connector=>connector.connectorId.toLowerCase()===normalized));if(exactId)return exactId;let exactName=resolveMatches(connectors.filter(connector=>connector.name.toLowerCase()===normalized));return exactName||(resolveMatches(connectors.filter(connector=>connector.connectorId.toLowerCase().includes(normalized)||connector.name.toLowerCase().includes(normalized)))??{status:"not_found"})}function isHeartbeatMessage(msg){return msg&&(msg.type==="ping"||msg.type==="pong")}var init_dist3=__esm({"../cloud/cloud-types/dist/index.js"(){"use strict"}});function boundedNumber(value,fallback,minimum,maximum){let numeric=Number(value);return Number.isFinite(numeric)?Math.min(Math.max(numeric,minimum),maximum):fallback}function resolveObservedActionTimeoutSec(data){let observe=data.observe??{},observationMs=boundedNumber(observe.timeoutMs,3e3,500,3e4),navigationGraceMs=boundedNumber(observe.navigationGraceMs,1e3,0,5e3),navigationTimeoutMs=boundedNumber(observe.navigationTimeoutMs,15e3,1e3,3e4),totalMs=observationMs+navigationGraceMs+4e3+navigationTimeoutMs+5e3;return Math.max(20,Math.ceil(totalMs/1e3))}function resolveActionTimeoutSec(action,data,fallback=15){if(action==="send_request"){let transferTimeoutMs=data.bodyFile!==void 0||Array.isArray(data.files)&&data.files.length>0?SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS:0;return Math.max(fallback,Math.ceil(((data.timeout??3e4)+transferTimeoutMs+5e3)/1e3))}if(action==="page_download")return Math.max(fallback,Math.ceil((Number(data.timeout??3e4)+1e4)/1e3));if(action==="page_wait"){let waitMs=data.time??data.timeout??1e4;return Math.max(fallback,Math.ceil((Number(waitMs)+5e3)/1e3))}if(action==="tab_open"||action==="set_cookie"&&data.reload===!0)return Math.max(fallback,40);if(action==="browser_launch")return Math.max(fallback,90);if(action==="browser_close")return Math.max(fallback,BROWSER_CLOSE_TIMEOUT_SEC);if(action==="run_actions"){let timeoutSec=(Array.isArray(data.actions)?data.actions:[{}]).reduce((total,step)=>{let stepAction=String(step?.action??"");return!stepAction||stepAction==="run_actions"?total+15:total+resolveActionTimeoutSec(stepAction,step?.data??{},15)},0);return Math.max(fallback,timeoutSec)}let observedAction=OBSERVED_PAGE_ACTIONS.has(action),observationEnabled=action==="page_eval"?data.observe!==null&&typeof data.observe=="object"&&!Array.isArray(data.observe):data.observe!==!1;if(action==="page_upload"){let actionTimeoutSec=observationEnabled?resolveObservedActionTimeoutSec(data):fallback;return Math.max(fallback,actionTimeoutSec+Math.ceil(PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS/1e3))}return observedAction&&observationEnabled?Math.max(fallback,resolveObservedActionTimeoutSec(data)):fallback}var SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS,PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS,BROWSER_CLOSE_TIMEOUT_SEC,OBSERVED_PAGE_ACTIONS,init_actionTimeouts=__esm({"../client/src/actionTimeouts.ts"(){"use strict";init_dist2();SEND_REQUEST_FILE_TRANSFER_TIMEOUT_MS=12e4,PAGE_UPLOAD_FILE_TRANSFER_TIMEOUT_MS=18e4,BROWSER_CLOSE_TIMEOUT_SEC=1080;OBSERVED_PAGE_ACTIONS=new Set(PAGE_ACT_ACTIONS)}});function isProviderControlSessionModes(value){return Array.isArray(value)&&value.length>0&&value.every(mode=>mode==="mearl"||mode==="external")&&new Set(value).size===value.length}function assertProviderProtocolVersion(actual,peer="Provider"){if(actual!==3)throw new Error(`PROVIDER_PROTOCOL_MISMATCH: ${peer} uses protocol ${String(actual??"unknown")}; expected 3. Update Mearl and the Provider package, then restart the services.`)}var init_protocol=__esm({"../provider/dist/protocol.js"(){"use strict"}});var init_types2=__esm({"../provider/dist/types.js"(){"use strict";init_protocol()}});var PROVIDER_ACTIONS,init_actions=__esm({"../provider/dist/actions.js"(){"use strict";init_browserActionProtocol();PROVIDER_ACTIONS=Object.keys(BROWSER_CAPABILITY_ACTIONS)}});function isJsonValue(value,depth=0){return depth>32?!1:value===null||["string","boolean"].includes(typeof value)?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.every(item=>isJsonValue(item,depth+1)):typeof value=="object"&&Object.values(value).every(item=>isJsonValue(item,depth+1))}function isOptionalString(value){return value===void 0||typeof value=="string"}function isOptionalFiniteNumber(value){return value===void 0||typeof value=="number"&&Number.isFinite(value)}function isOptionalCount(value){return value===void 0||Number.isInteger(value)&&Number(value)>=0}function isProviderInputSchema(value,depth=0){if(!value||typeof value!="object"||Array.isArray(value)||depth>32)return!1;let schema=value;if(!isOptionalString(schema.title)||!isOptionalString(schema.description)||schema.component!==void 0&&!["cookie-sync","switch"].includes(String(schema.component))||schema.default!==void 0&&!isJsonValue(schema.default)||schema.formDefault!==void 0&&!isJsonValue(schema.formDefault)||schema.formHidden!==void 0&&typeof schema.formHidden!="boolean"||schema.formWidth!==void 0&&!["half","full"].includes(String(schema.formWidth))||schema.formHideOptional!==void 0&&typeof schema.formHideOptional!="boolean"||schema.formVisibleWhen!==void 0&&(!schema.formVisibleWhen||typeof schema.formVisibleWhen!="object"||Array.isArray(schema.formVisibleWhen)||typeof schema.formVisibleWhen.field!="string"||!schema.formVisibleWhen.field||typeof schema.formVisibleWhen.empty!="boolean"))return!1;if(schema.type==="string"){let validPattern=!0;if(schema.pattern!==void 0)try{new RegExp(String(schema.pattern))}catch{validPattern=!1}if(!((schema.enum===void 0||Array.isArray(schema.enum)&&schema.enum.every(item=>typeof item=="string"))&&(schema.secret===void 0||typeof schema.secret=="boolean")&&isOptionalCount(schema.minLength)&&isOptionalCount(schema.maxLength)&&(schema.minLength===void 0||schema.maxLength===void 0||Number(schema.minLength)<=Number(schema.maxLength))&&isOptionalString(schema.pattern)&&validPattern&&isOptionalString(schema.placeholder)&&(schema.options===void 0||Array.isArray(schema.options)&&schema.options.every(option=>option&&typeof option=="object"&&!Array.isArray(option)&&typeof option.value=="string"&&typeof option.label=="string"&&isOptionalString(option.description)&&(option.disabled===void 0||typeof option.disabled=="boolean")&&(schema.enum===void 0||schema.enum.includes(option.value)))&&new Set(schema.options.map(option=>option.value)).size===schema.options.length)))return!1}else if(schema.type==="number"){if(!((schema.integer===void 0||typeof schema.integer=="boolean")&&isOptionalFiniteNumber(schema.minimum)&&isOptionalFiniteNumber(schema.maximum)&&(schema.minimum===void 0||schema.maximum===void 0||Number(schema.minimum)<=Number(schema.maximum))))return!1}else if(schema.type!=="boolean")if(schema.type==="array"){if(!isProviderInputSchema(schema.items,depth+1)||!isOptionalCount(schema.minItems)||!isOptionalCount(schema.maxItems)||schema.minItems!==void 0&&schema.maxItems!==void 0&&Number(schema.minItems)>Number(schema.maxItems))return!1}else{if(schema.type!=="object"||!schema.properties||typeof schema.properties!="object"||Array.isArray(schema.properties)||schema.additionalProperties!==void 0&&typeof schema.additionalProperties!="boolean")return!1;let properties=schema.properties;if(!Object.values(properties).every(item=>isProviderInputSchema(item,depth+1))||Object.values(properties).some(item=>{let condition=item.formVisibleWhen;return condition!==void 0&&!(String(condition.field)in properties)})||schema.not!==void 0&&(!isProviderInputSchema(schema.not,depth+1)||schema.not.type!=="object")||schema.oneOf!==void 0&&(!Array.isArray(schema.oneOf)||schema.oneOf.length===0||schema.oneOf.some(branch=>!isProviderInputSchema(branch,depth+1)||branch.type!=="object"))||schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(item=>typeof item!="string"||!(item in properties))||new Set(schema.required).size!==schema.required.length))return!1}if(schema.component==="cookie-sync"&&schema.type!=="object"||schema.component==="switch"&&schema.type!=="boolean")return!1;if(schema.default!==void 0)try{validateSchemaValue(value,schema.default,"default")}catch{return!1}if(schema.formDefault!==void 0)try{validateSchemaValue(value,schema.formDefault,"formDefault")}catch{return!1}return!0}function fail(path7,message){throw new Error(`${path7} ${message}`)}function validateSchemaValue(schema,value,path7){if(schema.type==="string"){typeof value!="string"&&fail(path7,"must be a string"),schema.enum&&!schema.enum.includes(value)&&fail(path7,"has an unsupported value"),schema.minLength!==void 0&&value.length<schema.minLength&&fail(path7,`must contain at least ${schema.minLength} characters`),schema.maxLength!==void 0&&value.length>schema.maxLength&&fail(path7,`must contain at most ${schema.maxLength} characters`),schema.pattern!==void 0&&!new RegExp(schema.pattern).test(value)&&fail(path7,"has an invalid format");return}if(schema.type==="number"){(typeof value!="number"||!Number.isFinite(value))&&fail(path7,"must be a number"),schema.integer&&!Number.isInteger(value)&&fail(path7,"must be an integer"),schema.minimum!==void 0&&value<schema.minimum&&fail(path7,`must be at least ${schema.minimum}`),schema.maximum!==void 0&&value>schema.maximum&&fail(path7,`must be at most ${schema.maximum}`);return}if(schema.type==="boolean"){typeof value!="boolean"&&fail(path7,"must be a boolean");return}if(schema.type==="array"){Array.isArray(value)||fail(path7,"must be an array"),schema.minItems!==void 0&&value.length<schema.minItems&&fail(path7,`must contain at least ${schema.minItems} items`),schema.maxItems!==void 0&&value.length>schema.maxItems&&fail(path7,`must contain at most ${schema.maxItems} items`),value.forEach((item,index)=>validateSchemaValue(schema.items,item,`${path7}[${index}]`));return}validateObject(schema,value,path7)}function validateObject(schema,value,path7){(!value||typeof value!="object"||Array.isArray(value))&&fail(path7,"must be an object");let input=value;for(let key2 of schema.required??[])input[key2]===void 0&&fail(`${path7}.${key2}`,"is required");if(schema.not){let matches=!1;try{validateObject(schema.not,input,path7),matches=!0}catch{}matches&&fail(path7,"matches a forbidden field combination")}if(schema.oneOf&&schema.oneOf.filter(branch=>{try{return validateObject(branch,input,path7),!0}catch{return!1}}).length!==1&&fail(path7,"must match exactly one launch form"),schema.additionalProperties!==!0)for(let key2 of Object.keys(input))schema.properties[key2]||fail(`${path7}.${key2}`,"is not supported");for(let[key2,item]of Object.entries(input)){let property=schema.properties[key2];property&&validateSchemaValue(property,item,`${path7}.${key2}`)}}function validateProviderLaunchForm(form){if(!form||!isProviderInputSchema(form.inputSchema)||form.inputSchema.type!=="object"||!isOptionalString(form.variant)||!isOptionalString(form.message)||form.blocked!==void 0&&typeof form.blocked!="boolean"||form.values!==void 0&&(!form.values||typeof form.values!="object"||Array.isArray(form.values)||!isJsonValue(form.values))||form.dynamicFields!==void 0&&(!Array.isArray(form.dynamicFields)||form.dynamicFields.some(field=>typeof field!="string"||!(field in form.inputSchema.properties)))||form.refreshOn!==void 0&&(!Array.isArray(form.refreshOn)||form.refreshOn.some(field=>typeof field!="string"||!(field in form.inputSchema.properties)))||form.variants!==void 0&&(!Array.isArray(form.variants)||!form.variants.length||form.variants.some(variant=>!variant||typeof variant.id!="string"||!variant.id||typeof variant.title!="string"||!isOptionalString(variant.description))||new Set(form.variants.map(variant=>variant.id)).size!==form.variants.length||!form.variants.some(variant=>variant.id===form.variant)))throw new Error("Provider returned an invalid launch form");for(let variant of form.variants??[])validateProviderLaunchForm({inputSchema:variant.inputSchema===void 0?form.inputSchema:variant.inputSchema,values:variant.values===void 0?form.values:variant.values,refreshOn:variant.refreshOn===void 0?form.refreshOn:variant.refreshOn,dynamicFields:variant.dynamicFields===void 0?form.dynamicFields:variant.dynamicFields})}var init_provider_runtime=__esm({"../provider/dist/provider-runtime.js"(){"use strict";init_types2();init_actions();init_protocol();init_dist2()}});import{existsSync as existsSync5,readFileSync as readFileSync10,renameSync as renameSync7,rmSync as rmSync8,statSync as statSync8,writeFileSync as writeFileSync6}from"node:fs";import{isAbsolute as isAbsolute4,join as join11,relative as relative3,resolve as resolve4,sep as sep3}from"node:path";function liveProviderFile(providerId){return keyedConfigFile(LIVE_PROVIDERS_SUBDIR,providerId)}function startingProviderFile(providerId){return keyedConfigFile(STARTING_PROVIDERS_SUBDIR,providerId)}function claimProviderStart(providerId,token,pid=process.pid){let file=startingProviderFile(providerId),existing=readRecord(file);return existing&&isAlive(existing.pid)?existing.token===token:(existing?removeRecordIfPid(file,existing.pid):removeInvalidRecord(file),claimRecord(file,{pid,providerId,token,startedAt:new Date().toISOString()}))}function readProviderStart(providerId){let record2=readRecord(startingProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function transferProviderStart(providerId,token,pid){let file=startingProviderFile(providerId),record2=readRecord(file);return!record2||record2.token!==token?!1:writeRecordIfPid(file,record2.pid,{...record2,pid})}function releaseProviderStart(providerId,token){let file=startingProviderFile(providerId),record2=readRecord(file);return record2?.token===token?removeRecordIfPid(file,record2.pid):!1}function validateInstalledProviderManifest(manifest){if(!manifest||typeof manifest.providerId!="string"||!manifest.providerId.trim()||typeof manifest.name!="string"||!manifest.name.trim()||typeof manifest.version!="string"||!manifest.version.trim())return"manifest is incomplete";try{assertProviderProtocolVersion(manifest.protocolVersion,`Installed Provider ${manifest.providerId}`)}catch(error2){return error2.message}if(RESERVED_PROVIDER_IDS.has(manifest.providerId))return`providerId ${manifest.providerId} is reserved for a built-in Provider`;if(!isProviderBrowserType(manifest.browserType))return"browserType is invalid";if(typeof manifest.packageName!="string"||!manifest.packageName.trim())return"packageName is required";if(typeof manifest.packageRoot!="string"||!isAbsolute4(manifest.packageRoot))return"packageRoot must be an absolute path";if(typeof manifest.entryPath!="string"||!isAbsolute4(manifest.entryPath))return"entryPath must be an absolute path";let entryRelative=relative3(manifest.packageRoot,manifest.entryPath);return entryRelative===""||isAbsolute4(entryRelative)||entryRelative===".."||entryRelative.startsWith(`..${sep3}`)?"entryPath must be a file inside packageRoot":isFile(manifest.entryPath)?null:"entryPath does not exist or is not a file"}function isFile(filePath){try{return statSync8(filePath).isFile()}catch{return!1}}function isProviderBrowserType(value){if(!value||typeof value!="object")return!1;let browserType=value;if(typeof browserType.name!="string"||!browserType.name.trim()||browserType.controlSessionModes!==void 0&&!isProviderControlSessionModes(browserType.controlSessionModes)||browserType.documentationUrl!==void 0&&(typeof browserType.documentationUrl!="string"||!/^https?:\/\//.test(browserType.documentationUrl))||browserType.help!==void 0&&(!Array.isArray(browserType.help)||browserType.help.some(item=>typeof item!="string"||!item.trim()))||!isProviderObjectSchema(browserType.inputSchema)||browserType.dynamicLaunchForm!==void 0&&typeof browserType.dynamicLaunchForm!="boolean")return!1;if(browserType.launchForm!==void 0)try{validateProviderLaunchForm(browserType.launchForm)}catch{return!1}return browserType.configuration===void 0||!!browserType.configuration&&typeof browserType.configuration=="object"&&isProviderObjectSchema(browserType.configuration.inputSchema)}function isProviderObjectSchema(value){return isProviderInputSchema(value)&&value.type==="object"}function listInstalledProviders(){let manifests=[];for(let file of listRecordFiles(keyedDir(INSTALLED_PROVIDERS_SUBDIR)))try{let parsed=JSON.parse(readFileSync10(file,"utf8"));parsed&&typeof parsed.providerId=="string"&&typeof parsed.packageName=="string"&&manifests.push(parsed)}catch{}return manifests.sort((a,b)=>a.providerId.localeCompare(b.providerId))}function readLiveProvider(providerId){let record2=readRecord(liveProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function listLiveProviders(){return readLiveRecords(keyedDir(LIVE_PROVIDERS_SUBDIR))}var INSTALLED_PROVIDERS_SUBDIR,LIVE_PROVIDERS_SUBDIR,STARTING_PROVIDERS_SUBDIR,PROVIDER_START_TOKEN_ENV,RESERVED_PROVIDER_IDS,init_registry2=__esm({"../provider/dist/registry.js"(){"use strict";init_dist();init_types2();init_provider_runtime();init_protocol();INSTALLED_PROVIDERS_SUBDIR="providers/installed",LIVE_PROVIDERS_SUBDIR="providers/live",STARTING_PROVIDERS_SUBDIR="providers/starting",PROVIDER_START_TOKEN_ENV="MEARL_PROVIDER_START_TOKEN",RESERVED_PROVIDER_IDS=new Set(["local"])}});import{spawn as spawn3}from"node:child_process";import{randomUUID as randomUUID8}from"node:crypto";import{tmpdir as tmpdir2}from"node:os";import{join as join12}from"node:path";function assertProviderControlSessionMode(host,mode="mearl"){if(mode==="external"&&(!Array.isArray(host?.controlSessionModes)||!host.controlSessionModes.includes("external")))throw new Error("CONTROL_SESSION_MODE_UNSUPPORTED: the Provider requires external task control. Update Mearl and restart the Provider control host.")}function providerControlHostFile(){return keyedConfigFile("control","providers")}function providerControlSocketPath(pid){return process.platform==="win32"?`\\\\.\\pipe\\mearl-provider-control-${pid}`:join12(tmpdir2(),`mearl-provider-control-${pid}.sock`)}function readProviderControlHost(){let record2=readRecord(providerControlHostFile());return!record2?.ready||typeof record2.socketPath!="string"||!isAlive(record2.pid)?null:(assertProviderProtocolVersion(record2.protocolVersion,"Provider control host"),record2)}function ensureProviderControlHost(timeoutMs=1e4){if(startup)return startup;let pending=(async()=>{let file=providerControlHostFile(),deadline=Date.now()+timeoutMs;for(;Date.now()<deadline;){let ready=readProviderControlHost();if(ready)return ready;let previous=readRecord(file);if(!previous||!isAlive(previous.pid)){previous?removeRecordIfPid(file,previous.pid):removeInvalidRecord(file);let token=randomUUID8();if(claimRecord(file,{pid:process.pid,socketPath:"",token,ready:!1,protocolVersion:3}))try{let entry=process.env.MEARL_NATIVE_HOST_ENTRY,child=spawn3(entry?process.execPath:"mearl-native-host",[...entry?[entry]:[],"--provider-control",token],{detached:!0,stdio:"ignore",windowsHide:!0});if(await new Promise((resolve7,reject)=>{child.once("error",reject),child.once("spawn",resolve7)}),child.unref(),!child.pid)throw new Error("Provider control host did not report its pid");writeRecordIfPid(file,process.pid,{pid:child.pid,socketPath:providerControlSocketPath(child.pid),token,ready:!1,protocolVersion:3})}catch(error2){throw removeRecordIfPid(file,process.pid),error2}}await new Promise(resolve7=>setTimeout(resolve7,50))}throw new Error("Provider control host startup timed out")})();return startup=pending,pending.finally(()=>{startup===pending&&(startup=void 0)}).catch(()=>{}),pending}var startup,init_control_host=__esm({"../provider/dist/control-host.js"(){"use strict";init_protocol();init_dist()}});var init_host=__esm({"../provider/dist/host.js"(){"use strict";init_registry2();init_control_host()}});import net from"node:net";var init_control_rpc=__esm({"../provider/dist/control-rpc.js"(){"use strict";init_control_host();init_protocol()}});var init_enhancements=__esm({"../provider/dist/enhancements.js"(){"use strict";init_dist2();init_control_rpc();init_registry2()}});var init_app_resources=__esm({"../provider/dist/app-resources.js"(){"use strict";init_dist2();init_registry2();init_control_rpc()}});import net2 from"node:net";import{chmodSync,rmSync as rmSync9}from"node:fs";import{dirname as dirname6}from"node:path";var MAX_REQUEST_BYTES,init_server=__esm({"../provider/dist/server.js"(){"use strict";init_dist();init_actions();init_provider_runtime();init_registry2();init_types2();init_protocol();init_control_host();MAX_REQUEST_BYTES=16*1024*1024}});var init_dist4=__esm({"../provider/dist/index.js"(){"use strict";init_types2();init_enhancements();init_app_resources();init_protocol();init_actions();init_registry2();init_provider_runtime();init_server()}});import{spawn as spawn4}from"node:child_process";import{randomUUID as randomUUID9}from"node:crypto";import{closeSync as closeSync6,existsSync as existsSync6,mkdirSync as mkdirSync6,openSync as openSync6}from"node:fs";import{join as join13}from"node:path";function providerLogFile(providerId){let hash=hashKey(providerId);return join13(keyedDir(PROVIDER_LOGS_SUBDIR),`${hash}.log`)}function hasCompatibleLiveProvider(providerId){let live=readLiveProvider(providerId);return live?(assertProviderProtocolVersion(live.providerProtocolVersion,providerId),!0):!1}function delay(ms){return new Promise(resolve7=>setTimeout(resolve7,ms))}async function spawnProvider(manifest,logFile,startToken){mkdirSync6(keyedDir(PROVIDER_LOGS_SUBDIR),{recursive:!0,mode:448}),rotateLogIfNeeded(logFile);let output=openSync6(logFile,"a");try{return await new Promise((resolve7,reject)=>{let child=spawn4(process.execPath,[manifest.entryPath],{cwd:manifest.packageRoot,env:{...process.env,[PROVIDER_START_TOKEN_ENV]:startToken},detached:!0,stdio:["ignore",output,output],windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.removeAllListeners("error"),child.on("error",()=>{}),child.unref(),child.pid?resolve7(child.pid):reject(new Error("spawned process has no pid"))})})}finally{closeSync6(output)}}async function ensureInstalledProvidersRunning(providerIds){let warnings=[],selected=providerIds?new Set(providerIds):void 0,installed=listInstalledProviders().filter(provider=>!selected||selected.has(provider.providerId)),starting2=new Map;for(let manifest of installed){let invalid2=validateInstalledProviderManifest(manifest);if(invalid2){warnings.push(`provider ${manifest.providerId||"(unknown)"}: ${invalid2}`);continue}let startToken;try{if(hasCompatibleLiveProvider(manifest.providerId))continue;if(startToken=randomUUID9(),!claimProviderStart(manifest.providerId,startToken)){if(hasCompatibleLiveProvider(manifest.providerId))continue;readProviderStart(manifest.providerId)?starting2.set(manifest.providerId,null):warnings.push(`provider ${manifest.providerId}: failed to acquire startup ownership`);continue}if(hasCompatibleLiveProvider(manifest.providerId)){releaseProviderStart(manifest.providerId,startToken);continue}let logFile=providerLogFile(manifest.providerId),childPid=await spawnProvider(manifest,logFile,startToken);transferProviderStart(manifest.providerId,startToken,childPid),starting2.set(manifest.providerId,startToken)}catch(error2){startToken&&releaseProviderStart(manifest.providerId,startToken),warnings.push(`provider ${manifest.providerId}: ${error2 instanceof Error?error2.message:String(error2)}`)}}if(starting2.size===0)return warnings;let startupTimeout=providerId=>installed.find(manifest=>manifest.providerId===providerId)?.browserType.controlSessionModes?.includes("external")?12e3:2e3,deadlines=new Map([...starting2.keys()].map(id=>[id,Date.now()+startupTimeout(id)])),remaining=new Set(starting2.keys()),waiting=new Set(starting2.keys());for(;waiting.size>0;){await delay(100);let current=new Set(listLiveProviders().map(record2=>record2.providerId));for(let providerId of waiting)current.has(providerId)?(waiting.delete(providerId),remaining.delete(providerId)):Date.now()>=deadlines.get(providerId)&&waiting.delete(providerId)}for(let[providerId,token]of starting2)if(!remaining.has(providerId)&&token&&releaseProviderStart(providerId,token),!remaining.has(providerId))try{hasCompatibleLiveProvider(providerId)}catch(error2){warnings.push(`provider ${providerId}: ${error2 instanceof Error?error2.message:String(error2)}`)}for(let providerId of remaining){let logFile=providerLogFile(providerId);warnings.push(`provider ${providerId}: did not become ready within ${startupTimeout(providerId)/1e3}s${existsSync6(logFile)?`; see ${logFile}`:""}`)}return await delay(100),warnings}var PROVIDER_LOGS_SUBDIR,init_launcher=__esm({"../provider/dist/launcher.js"(){"use strict";init_dist();init_registry2();init_protocol();PROVIDER_LOGS_SUBDIR="providers/logs"}});var init_runtime=__esm({"../provider/dist/runtime.js"(){"use strict";init_launcher();init_registry2();init_provider_runtime()}});import fs2 from"node:fs";function resolveValue(value){if(typeof value!="string"||!value.startsWith(FILE_REF_PREFIX))return value;let filePath=value.slice(FILE_REF_PREFIX.length);if(!filePath)return value;let content;try{content=fs2.readFileSync(filePath,"utf-8")}catch{return value}try{return JSON.parse(content)}catch{return content}}function resolveFileRefs(data){if(data===null||typeof data!="object"||Array.isArray(data))return data;let out={};for(let[key2,value]of Object.entries(data))out[key2]=resolveValue(value);return out}var FILE_REF_PREFIX,init_fileRefs=__esm({"../client/src/fileRefs.ts"(){"use strict";FILE_REF_PREFIX="@"}});import fs3 from"node:fs";import os from"node:os";import path3 from"node:path";function isAlive2(pid){if(!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error2){return error2.code==="EPERM"}}function listLiveBrowsers(){let files;try{files=fs3.readdirSync(BROWSERS_DIR).filter(name=>name.endsWith(".json"))}catch{return[]}let out=[];for(let name of files){let rec;try{rec=JSON.parse(fs3.readFileSync(path3.join(BROWSERS_DIR,name),"utf-8"))}catch{continue}rec&&typeof rec.pid=="number"&&rec.socketPath&&isAlive2(rec.pid)&&out.push(rec)}return out.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0))}function findBrowser(browsers,selector){let sel=selector.trim().toLowerCase();if(!sel)return null;let byId=browsers.find(b=>b.browserId.toLowerCase()===sel);if(byId)return byId;let exactNameMatches=browsers.filter(b=>b.browserName.toLowerCase()===sel);if(exactNameMatches.length>1)throw new Error(`Browser name "${selector.trim()}" is ambiguous. Use a full browserId: ${exactNameMatches.map(browser=>browser.browserId).join(", ")}`);return exactNameMatches[0]?exactNameMatches[0]:browsers.find(b=>b.browserId.toLowerCase().includes(sel)||b.browserName.toLowerCase().includes(sel))??null}function describeBrowser(b){let idShort=b.browserId.length>12?`${b.browserId.slice(0,8)}…`:b.browserId;return`${b.browserName} [${idShort}]`}var BROWSERS_DIR,init_browserRegistry=__esm({"../client/src/browserRegistry.ts"(){"use strict";BROWSERS_DIR=path3.join(os.homedir(),".mearl","browsers")}});import net3 from"node:net";import fs4 from"node:fs";import os2 from"node:os";import path4 from"node:path";import{StringDecoder}from"node:string_decoder";function toControlSourceWireValue(source){return source==="remote"||source==="cloud"?"cloud":"local"}function setDefaultBrowser(selector){defaultBrowser=selector&&selector.trim()?selector.trim():void 0}function getDefaultBrowser(){return defaultBrowser}function findConnectedBrowser(items,selector){let normalized=selector.trim().toLowerCase(),connected=items.filter(item=>item.status==="connected"),byId=connected.find(item=>String(item.browserId).toLowerCase()===normalized);if(byId)return byId;let exactNameMatches=connected.filter(item=>String(item.name).toLowerCase()===normalized);if(exactNameMatches.length>1)throw new Error(`Browser name "${selector.trim()}" is ambiguous. Use a full browserId: ${exactNameMatches.map(item=>String(item.browserId)).join(", ")}`);return exactNameMatches[0]??connected.find(item=>String(item.browserId).toLowerCase().includes(normalized)||String(item.name).toLowerCase().includes(normalized))??null}function decorateBrowserListResult(result){let browsers=Array.isArray(result?.browsers)?result.browsers:[],selector=getDefaultBrowser()??process.env.MEARL_BROWSER,selected=selector?findConnectedBrowser(browsers,selector):browsers.find(browser=>browser.status==="connected")??null;return{...result,defaultBrowserId:selected?.browserId??null}}function browserListFromProviderRecords(browsers){let providerBrowsers=browsers.filter(browser=>browser.transport==="provider").map(browser=>({browserId:browser.browserId,name:browser.browserName,type:"managed",status:browser.status??"running_disconnected",transport:"provider",provider:browser.provider,ownership:browser.ownership,persistence:browser.persistence,operations:browser.operations,pairing:browser.pairing,references:browser.references,details:browser.details}));return{count:providerBrowsers.length,connectedCount:providerBrowsers.filter(browser=>browser.status==="connected").length,browsers:providerBrowsers}}function withDiscoveryWarning(result,error2){let detail=(error2.cause??error2)?.code??(error2 instanceof Error?error2.message.split(`
609
+ `)[0]:String(error2));return{...result,warnings:[...Array.isArray(result.warnings)?result.warnings:[],`Local CDP discovery could not complete: ${detail}`]}}function cdpOnlyBrowserList(result){let cdpBrowsers=(Array.isArray(result.browsers)?result.browsers:[]).filter(browser=>browser.transport==="cdp");return{...result,count:cdpBrowsers.length,connectedCount:cdpBrowsers.filter(browser=>browser.status==="connected").length,browsers:cdpBrowsers}}function areInstalledProvidersRunning(){return listInstalledProviders().every(provider=>readLiveProvider(provider.providerId))}function isConnectedBrowser(browser){return browser.status===void 0||browser.status==="connected"}function isOrdinaryLocalBrowser(browser){return!browser.browserId.startsWith("managed:")&&(browser.transport==="extension"||browser.transport==="cdp")}function supportsAction(browser,action,data){if(browser.transport==="provider"){if(action==="browser_control"||action==="get_capabilities"&&isConnectedBrowser(browser)||action==="browser_release"&&data[SESSION_OPTION])return!0;if(action.startsWith("__artifact_"))return browser.capabilities?.actions.includes("page_upload")===!0||(action==="__artifact_read"||action==="__artifact_remove")&&browser.capabilities?.actions.includes("page_download")===!0;if(action==="run_actions"&&data[SESSION_OPTION])return!0}if(action==="get_versions")return!0;if(action==="get_browser_access_url")return browser.transport!=="provider"||browser.operations?.includes("access")===!0;if(action==="browser_close"){if(browser.transport!=="provider")return!0;let required=data.deleteProfile===!0?"deleteData":"close";return browser.operations?.includes(required)===!0}return action==="browser_release"?browser.transport!=="provider"||browser.operations?.includes("detach")===!0:isConnectedBrowser(browser)?browser.transport!=="provider"||browser.capabilities?.actions.some(capability=>capability===action)===!0:!1}function routableBrowsers(browsers,action,data,transport){return browsers.filter(browser=>isConnectedBrowser(browser)&&(action!=="browser_list"||browser.transport!=="provider")&&!(transport==="cdp"&&browser.transport==="provider")&&supportsAction(browser,action,data))}function resolveLocalActionTarget(action,data,options={}){let selector=options.browser??defaultBrowser??process.env.MEARL_BROWSER??void 0,socketPath=options.socketPath??process.env.MEARL_SOCKET_PATH?.trim();if(socketPath&&(options.socketPath||!selector))return{socketPath};let browsers=listLiveBrowsers(),target=selector?findBrowser(browsers,selector):routableBrowsers(browsers,action,data,options.transport)[0];return target?{browser:target.browserId}:void 0}function selectBrowserResult(data){let selector=typeof data.browser=="string"?data.browser.trim():"";if(!selector)return setDefaultBrowser(void 0),{selected:null,note:"Cleared: default target is now the most-recently focused browser."};let browsers=listLiveBrowsers(),controllableBrowsers=browsers.filter(isConnectedBrowser),match=findBrowser(controllableBrowsers,selector);if(!match)throw new Error(formatNoMatchError(selector,browsers));return setDefaultBrowser(match.browserId),{selected:{browserId:match.browserId,name:match.browserName}}}function instanceSocketPath(pid){return process.platform==="win32"?`\\\\.\\pipe\\mearl-agent-${pid}`:path4.join(os2.tmpdir(),`mearl-agent-${pid}.sock`)}function discoveryCacheKey(){let browsers=listLiveBrowsers().map(browser=>[browser.browserId,browser.pid,browser.socketPath,browser.status,browser.updatedAt]).sort((a,b)=>String(a[0]).localeCompare(String(b[0]))),providers=listInstalledProviders().map(provider=>provider.providerId).sort();return JSON.stringify({browsers,providers})}async function spawnNativeHost(args){let{spawn:spawn10}=await import("node:child_process");return new Promise((resolve7,reject)=>{let child=spawn10("mearl-native-host",args,{detached:!0,stdio:"ignore",windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.unref(),resolve7(child.pid)})})}async function trySpawnNativeHost(){if(persistentSpawnPromise)return persistentSpawnPromise;let spawnPromise=(async()=>{try{return await spawnNativeHost(["--daemon"]),!0}catch{return!1}})();persistentSpawnPromise=spawnPromise;try{return await spawnPromise}finally{persistentSpawnPromise===spawnPromise&&(persistentSpawnPromise=null)}}async function discoverLocalBrowserList(timeoutSec,controlSource){if(discoveryListPromise)return discoveryListPromise;let cacheKey=discoveryCacheKey();if(discoveryListCache&&discoveryListCache.key===cacheKey&&Date.now()<discoveryListCache.until){if(discoveryListCache.error)throw discoveryListCache.error;return discoveryListCache.result}discoveryListCache=null;let request=(async()=>{let pid=await spawnNativeHost(["--daemon","--discover-cdp"]);if(pid===void 0)throw new Error("Native host did not report its process id");let socketPath=instanceSocketPath(pid),deadline=Date.now()+Math.min(timeoutSec*1e3,DISCOVERY_STARTUP_TIMEOUT_MS);for(;;)try{return await invokeOnce("browser_list",{},timeoutSec,void 0,socketPath,controlSource)}catch(error2){if(!isConnError(error2)||Date.now()>=deadline)throw error2;await new Promise(resolve7=>setTimeout(resolve7,DISCOVERY_RETRY_INTERVAL_MS))}})();discoveryListPromise=request;try{let result=await request;return result.browsers?.some(browser=>browser.transport==="cdp"&&browser.status==="connected"&&!browser.browserId?.startsWith("managed:"))||(discoveryListCache={key:cacheKey,result,until:Date.now()+DISCOVERY_MISS_CACHE_MS}),result}catch(error2){throw discoveryListCache={key:cacheKey,error:error2,until:Date.now()+DISCOVERY_MISS_CACHE_MS},error2}finally{discoveryListPromise===request&&(discoveryListPromise=null)}}function readOwnedLegacySocketIdentity(){if(process.platform==="win32")return null;try{let stat2=fs4.lstatSync(SOCKET_PATH);return!stat2.isSocket()||process.getuid&&stat2.uid!==process.getuid()?null:{dev:stat2.dev,ino:stat2.ino}}catch{return null}}function removeStaleLegacySocket(identity){if(identity)try{let current=fs4.lstatSync(SOCKET_PATH);if(!current.isSocket()||current.dev!==identity.dev||current.ino!==identity.ino)return;fs4.unlinkSync(SOCKET_PATH)}catch{}}function invoke(action,data={},options={}){if(action==="__resolve_action_target"){if(!isBrowserCapabilityAction(data.action))return Promise.reject(new Error("Invalid browser capability action"));let target=resolveLocalActionTarget(data.action,data.data??{},options),browser2=target?.browser??(target?.socketPath?listLiveBrowsers().find(item=>item.socketPath===target.socketPath&&supportsAction(item,data.action,data.data??{}))?.browserId:void 0);return Promise.resolve(browser2?{browser:browser2}:null)}if(action==="browser_select_browser")try{return Promise.resolve(selectBrowserResult(data))}catch(error2){return Promise.reject(error2)}let{timeoutSec=resolveActionTimeoutSec(action,data),transport,browser,controlSource="local"}=options;if(action==="__control_session_resolve")return resolveControlSession(data.sessionId,timeoutSec,controlSource);let resolvedData=resolveFileRefs(data);if(Object.defineProperty(resolvedData,SESSION_OPTION,{value:options.controlSessionId}),action==="browser_list"){let discovery=parseBrowserListParams(resolvedData);return discovery?(async()=>{if(transport||options.socketPath||controlSource!=="local"||options.controlSessionId)throw new Error("Provider discovery requires the local source without a transport, socket or session override");if(!listInstalledProviders().find(provider2=>provider2.providerId===discovery.provider)?.browserType.dynamicLaunchForm)throw new Error(`Provider does not support dynamic launch forms: ${discovery.provider}`);let warnings=await ensureInstalledProvidersRunning([discovery.provider]);if(warnings.length)throw new Error(warnings.join("; "));let live=readLiveProvider(discovery.provider);if(!live)throw new Error(`Provider did not start: ${discovery.provider}`);assertProviderProtocolVersion(live.providerProtocolVersion,discovery.provider);let form=await invokeOnce("browser_providers",{operation:"launch_form",...discovery.launchForm},timeoutSec,void 0,live.socketPath,"local");return validateProviderLaunchForm(form),decorateBrowserListResult({...browserListFromProviderRecords(listLiveBrowsers().filter(browser2=>browser2.provider?.id===discovery.provider)),discovery:{provider:discovery.provider,launchForm:form}})})():dispatchInvoke(action,resolvedData,timeoutSec,transport,void 0,controlSource,options.socketPath).then(result=>decorateBrowserListResult(transport==="cdp"?cdpOnlyBrowserList(result):result))}let selector=browser??defaultBrowser??process.env.MEARL_BROWSER??void 0;return dispatchInvoke(action,resolvedData,timeoutSec,transport,selector,controlSource,options.socketPath)}async function resolveControlSession(sessionId,timeoutSec,controlSource){let browsers=listLiveBrowsers(),configuredSocketPath=process.env.MEARL_SOCKET_PATH?.trim(),sockets=configuredSocketPath?[configuredSocketPath]:[...new Set(browsers.filter(browser=>browser.transport!=="provider").map(browser=>browser.socketPath))],provider=configuredSocketPath?void 0:browsers.find(browser=>browser.transport==="provider");!sockets.length&&!provider&&sockets.push(SOCKET_PATH);let requests=sockets.map(socketPath=>invokeOnce("__control_session_resolve",{sessionId},timeoutSec,void 0,socketPath,controlSource));provider&&requests.push(invokeOnce("__control_session_resolve",{sessionId},timeoutSec,void 0,provider.socketPath,controlSource,provider.browserId));let results=await Promise.allSettled(requests),sessions=results.flatMap(result=>result.status==="fulfilled"&&result.value?.session?.sessionId===sessionId?[result.value.session]:[]);if(sessions.length>1)throw new Error("CONTROL_SESSION_AMBIGUOUS: multiple hosts own this id");if(sessions.length)return{session:sessions[0]};let failure2=results.find(result=>result.status==="rejected"&&!isConnError(result.reason));if(failure2?.status==="rejected")throw failure2.reason;return{session:null}}function isConnError(error2){let code=error2?.code;return code==="ENOENT"||code==="ECONNREFUSED"}function isSocketSandboxError(error2){return error2?.code==="EPERM"}function isUnavailableConnection(error2){let cause=error2.cause??error2,code=cause?.code;return isConnError(cause)||isSocketSandboxError(cause)||code==="EACCES"}async function dispatchInvoke(action,data,timeoutSec,transport,selector,controlSource,socketPath){let configuredSocketPath=socketPath??process.env.MEARL_SOCKET_PATH?.trim();if(configuredSocketPath&&(socketPath||!selector))try{return await invokeOnce(action,data,timeoutSec,transport,configuredSocketPath,controlSource)}catch(error2){throw isConnError(error2)||isSocketSandboxError(error2)?new Error(formatConnectError(error2,configuredSocketPath),{cause:error2}):error2}let browsers=listLiveBrowsers(),controllableBrowsers=browsers.filter(isConnectedBrowser);if(action==="browser_list"&&transport==="cdp"){let registeredCdp=controllableBrowsers.find(browser=>browser.transport==="cdp"&&isOrdinaryLocalBrowser(browser));if(registeredCdp)try{return await invokeOnce(action,data,timeoutSec,transport,registeredCdp.socketPath,controlSource)}catch(error2){if(!isConnError(error2))throw error2}try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}}if(action==="browser_list"&&!controllableBrowsers.some(isOrdinaryLocalBrowser))try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}if(selector){let match=findBrowser(browsers,selector);if(!match)throw new Error(formatNoMatchError(selector,browsers));if(transport==="cdp"&&match.transport==="provider")throw new Error(`Browser ${describeBrowser(match)} does not support the CDP transport`);if(match.status==="pairing"&&action!=="get_versions"&&action!=="browser_close"&&action!=="browser_release"&&action!=="browser_control")throw new Error(`Browser ${describeBrowser(match)} is waiting for device pairing`);if(!supportsAction(match,action,data))throw new Error(`Browser ${describeBrowser(match)} does not support ${action}`);try{return await invokeOnce(action,data,timeoutSec,transport,match.socketPath,controlSource,match.transport==="provider"?match.browserId:void 0,match.capabilities?.controlSessionMode)}catch(error2){throw isConnError(error2)||isSocketSandboxError(error2)?new Error(formatConnectError(error2,match.socketPath),{cause:error2}):error2}}let candidates=routableBrowsers(browsers,action,data,transport);if(candidates.length>0){let target=candidates[0];try{return await invokeOnce(action,data,timeoutSec,transport,target.socketPath,controlSource,target.transport==="provider"?target.browserId:void 0,target.capabilities?.controlSessionMode)}catch(error2){if(isSocketSandboxError(error2))throw new Error(formatConnectError(error2,target.socketPath),{cause:error2});if(!isConnError(error2))throw error2}}if(action==="browser_list")try{return await discoverLocalBrowserList(timeoutSec,controlSource)}catch(error2){if(isUnavailableConnection(error2)&&browsers.some(browser=>browser.transport==="provider")&&areInstalledProvidersRunning())return withDiscoveryWarning(browserListFromProviderRecords(browsers),error2);throw error2}return invokeViaLegacy(action,data,timeoutSec,transport,controlSource,!1)}async function invokeViaLegacy(action,data,timeoutSec,transport,controlSource,isRetry,localOnly=!1){let legacySocketIdentity=readOwnedLegacySocketIdentity();try{return await invokeOnce(action,data,timeoutSec,transport,SOCKET_PATH,controlSource)}catch(error2){let err=error2;if((err.code==="ENOENT"||err.code==="ECONNREFUSED")&&!isRetry&&(err.code==="ECONNREFUSED"&&removeStaleLegacySocket(legacySocketIdentity),await trySpawnNativeHost())){await new Promise(r=>setTimeout(r,1200));let target=listLiveBrowsers().find(browser=>isConnectedBrowser(browser)&&(!localOnly||browser.transport!=="provider")&&!(transport==="cdp"&&browser.transport==="provider")&&supportsAction(browser,action,data));return target?invokeOnce(action,data,timeoutSec,transport,target.socketPath,controlSource,target.transport==="provider"?target.browserId:void 0,target.capabilities?.controlSessionMode):invokeViaLegacy(action,data,timeoutSec,transport,controlSource,!0,localOnly)}throw err instanceof Error&&!isConnError(err)&&!isSocketSandboxError(err)?err:new Error(formatConnectError(err,SOCKET_PATH),{cause:error2})}}async function invokeOnce(action,data,timeoutSec,transport,socketPath,controlSource,providerTarget,controlSessionMode){if(providerTarget){let host=await ensureProviderControlHost(Math.min(timeoutSec*1e3,1e4));assertProviderControlSessionMode(host,controlSessionMode),socketPath=host.socketPath}let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`,deadline=Date.now()+Math.ceil(timeoutSec*1e3);return new Promise((resolve7,reject)=>{if(process.platform!=="win32"&&fs4.existsSync(socketPath)&&process.getuid&&fs4.statSync(socketPath).uid!==process.getuid()){let error2=new Error(`拒绝连接不属于当前用户的 Socket: ${socketPath}`);Object.assign(error2,{code:"EACCES"}),reject(error2);return}let socket=net3.createConnection(socketPath),settled=!1,buffer="",decoder=new StringDecoder("utf8"),settle=(error2,result)=>{settled||(settled=!0,clearTimeout(timer),socket.removeAllListeners(),socket.end(),error2?reject(error2 instanceof Error?error2:new Error(String(error2))):resolve7(result))},timer=setTimeout(()=>{settle(new Error(`请求超时,已等待 ${timeoutSec} 秒`))},timeoutSec*1e3);socket.on("connect",()=>{let message={id,action,data,version:CLIENT_VERSION,protocolVersion:3,controlSource:toControlSourceWireValue(controlSource)};data[SESSION_OPTION]&&(message.controlSessionId=data[SESSION_OPTION]),transport&&(message.transport=transport),providerTarget&&(message.providerTarget=providerTarget,message.deadline=deadline),socket.write(JSON.stringify(message)+`
625
610
  `)}),socket.on("data",chunk=>{if(buffer+=decoder.write(chunk),Buffer.byteLength(buffer,"utf-8")>MAX_SOCKET_BUFFER_SIZE){settle(new Error(`Socket 响应超过 ${MAX_SOCKET_BUFFER_SIZE} 字节限制`));return}let newlineIndex;for(;(newlineIndex=buffer.indexOf(`
626
611
  `))!==-1;){let line=buffer.slice(0,newlineIndex);if(buffer=buffer.slice(newlineIndex+1),!!line.trim())try{let response=JSON.parse(line);if(response.id!==id)continue;response.versionWarning&&console.warn(response.versionWarning),response.success?settle(null,response.data):settle(new Error(response.error||"Socket 服务端返回未知错误"));return}catch{settle(new Error(`无效的 JSON 响应: ${line}`));return}}}),socket.on("error",error2=>settle(error2)),socket.on("end",()=>{settled||settle(new Error("在收到响应前 Socket 已关闭"))})})}function formatConnectError(error2,socketPath){let installHint=`如果尚未安装浏览器插件,请先前往: ${EXTENSION_INSTALL_URL}`;return error2.code==="ENOENT"?[`未找到 Socket: ${socketPath}`,"native host 自动拉起失败。先运行 mearl check --local;缺少命令时运行 npx @mearl/setup --local --yes。","自动拉起只使用默认 daemon 参数;自定义 CDP/Profile/浏览器参数需手工启动,参见 mearl-native-host --help。","","【方式一:浏览器插件模式】",`1. 确认已安装 Mearl 浏览器插件(${EXTENSION_INSTALL_URL})`,"2. 确认已执行 Native Messaging 初始化(安装 @mearl/native-host 时会自动完成)","3. 确认 Chrome 浏览器正在运行,如仍无法连接可在 chrome://extensions 重新加载插件","","【方式二:CDP 远程调试模式(Chrome 145+,无需插件)】",' 访问 chrome://inspect/#remote-debugging,勾选 "Allow remote debugging for this browser instance"'," Chrome 会弹出授权提示,点击允许,native host 自动读取 DevToolsActivePort 文件连接"," 确认有普通网页已打开(非 chrome:// 页面)"].join(`
627
612
  `):error2.code==="ECONNREFUSED"?[`Socket 连接被拒绝: ${socketPath}`,"已尝试处理 stale socket,但 native host 自动恢复仍失败。请运行 mearl check --local 定位故障。","请确认 Chrome 浏览器正在运行,可尝试在 chrome://extensions 重新加载插件。","",installHint].join(`
@@ -629,34 +614,34 @@ Defaulting to 2020, but this will stop working in the future.`)),options.ecmaVer
629
614
  `):[`Socket 连接失败: ${error2.message}`,"",installHint].join(`
630
615
  `)}function formatNoMatchError(selector,browsers){let available=browsers.length?browsers.map(b=>` - ${describeBrowser(b)}`).join(`
631
616
  `):" (当前没有已连接的浏览器)";return[`未找到匹配 "${selector}" 的浏览器。`,"当前已连接的浏览器:",available,"","用 `mearl browser_list` 查看完整列表;可用 browserId 或名称匹配。"].join(`
632
- `)}var MAX_SOCKET_BUFFER_SIZE,SOCKET_PATH,SESSION_OPTION,defaultBrowser,persistentSpawnPromise,discoveryListPromise,discoveryListCache,DISCOVERY_STARTUP_TIMEOUT_MS,DISCOVERY_RETRY_INTERVAL_MS,DISCOVERY_MISS_CACHE_MS,EXTENSION_INSTALL_URL,init_socket=__esm({"../client/src/socket.ts"(){"use strict";init_runtimePaths();init_host();init_dist4();init_runtime();init_fileRefs();init_browserRegistry();init_actionTimeouts();init_dist2();MAX_SOCKET_BUFFER_SIZE=64*1024*1024,SOCKET_PATH=process.platform==="win32"?"\\\\.\\pipe\\mearl-agent":path4.join(os2.tmpdir(),"mearl-agent.sock");SESSION_OPTION=Symbol("control-session");persistentSpawnPromise=null,discoveryListPromise=null,discoveryListCache=null,DISCOVERY_STARTUP_TIMEOUT_MS=3e3,DISCOVERY_RETRY_INTERVAL_MS=50,DISCOVERY_MISS_CACHE_MS=2e3;EXTENSION_INSTALL_URL="https://chromewebstore.google.com/detail/mearl/aoehhjnofngknnjefamjbplchbolghkm"}});import{existsSync as existsSync7,readFileSync as readFileSync11}from"node:fs";import{homedir as homedir3}from"node:os";import{join as join14}from"node:path";function loadLocalConnectorId(){let explicit=process.env.MEARL_CONNECTOR_ID?.trim();if(explicit)return explicit;try{let config=JSON.parse(readFileSync11(join14(MEARL_CONFIG_DIR,"cloud-connector-identity.json"),"utf8"));return typeof config.connectorId=="string"&&config.connectorId.trim()?config.connectorId:null}catch{return null}}var MEARL_CONFIG_DIR,init_unifiedConfig=__esm({"../client/src/unifiedConfig.ts"(){"use strict";MEARL_CONFIG_DIR=join14(homedir3(),".mearl")}});function normalizePluginPageRuntime(value){if(value===void 0)return;let runtime=value;if(!runtime||runtime.version!==1||!Array.isArray(runtime.matches)||!runtime.matches.length||runtime.matches.length>64||!runtime.matches.every(isPluginPageMatchPattern)||typeof runtime.code!="string"||Buffer.byteLength(runtime.code)>384*1024||Buffer.byteLength(JSON.stringify(runtime))>448*1024)throw new Error("Invalid plugin pageRuntime declaration");let program2=parse3(`(${runtime.code}
633
- )`,{ecmaVersion:"latest"}),statement=program2.body[0];if(program2.body.length!==1||statement.type!=="ExpressionStatement"||!["ArrowFunctionExpression","FunctionExpression"].includes(statement.expression?.type??""))throw new Error("pageRuntime.code must be a self-contained function expression");if(runtime.events!==void 0&&(!runtime.events||typeof runtime.events!="object"||Array.isArray(runtime.events)||Object.keys(runtime.events).length>32))throw new Error("Invalid page runtime events");for(let[name,event]of Object.entries(runtime.events??{})){if(!/^[a-z][a-z0-9-]{0,63}$/.test(name)||!event||!/^[a-z][a-z0-9-]*$/.test(event.command)||!event.schema||typeof event.schema!="object"||Array.isArray(event.schema)||event.policy!==void 0&&!["serial","latest","parallel"].includes(event.policy)||event.concurrency!==void 0&&(!Number.isSafeInteger(event.concurrency)||event.concurrency<1||event.concurrency>8)||event.maxPending!==void 0&&(!Number.isSafeInteger(event.maxPending)||event.maxPending<1||event.maxPending>64)||event.schema.$async)throw new Error(`Invalid page event binding: ${name}`);compilePluginPageSchema(event.schema)}if(runtime.initialize!==void 0&&!/^[a-z][a-z0-9-]*$/.test(runtime.initialize))throw new Error("Invalid page runtime initialize command");return JSON.parse(JSON.stringify(runtime))}function compilePluginPageSchema(schema){let validate=validators2.get(schema);return validate||(validate=new import_ajv2.Ajv({strict:!0,allErrors:!1}).compile(schema),validators2.set(schema,validate)),validate}var import_ajv2,validators2,init_pluginPageDefinition=__esm({"../client/src/plugins/sdk/pluginPageDefinition.ts"(){"use strict";init_acorn();import_ajv2=__toESM(require_ajv(),1);init_dist2();validators2=new WeakMap}});import{readFileSync as readFileSync12,realpathSync as realpathSync3}from"node:fs";import{basename as basename4,dirname as dirname7,isAbsolute as isAbsolute5,relative as relative4,resolve as resolve5}from"node:path";function loadPluginAppProfiles(entry,value){if(value===void 0)return{};if(!value||typeof value!="object"||Array.isArray(value))throw new Error("appProfiles must be an object");let declaration=value;if(!Array.isArray(declaration.profiles))throw new Error("appProfiles.profiles must be an array");let root=realpathSync3(basename4(dirname7(entry))==="scripts"?dirname7(dirname7(entry)):dirname7(entry)),sources={},profiles=declaration.profiles.map(profile=>{if(typeof profile!="string")return profile;if(isAbsolute5(profile)||!profile.endsWith(".json"))throw new Error("Profile resource must be a relative JSON path");let reference=resolve5(root,profile),file=realpathSync3(reference),inside=relative4(root,file);if(inside.startsWith("..")||isAbsolute5(inside))throw new Error("Profile resource must stay inside the Skill directory");let version2=pluginFileVersion(file),content=readFileSync12(file,"utf8");if(content.length>65536)throw new Error("Profile resource exceeds 64 KiB");let parsed=JSON.parse(content);if(pluginFileVersion(reference)!==version2)throw new Error("Profile resource changed during registration");return sources[reference]=version2,parsed});return{appProfiles:validateAppProfileContribution({...declaration,profiles}),profileSources:sources}}var init_pluginAppProfiles=__esm({"../client/src/plugins/sdk/pluginAppProfiles.ts"(){"use strict";init_dist2();init_pluginSource()}});var CommanderError,InvalidArgumentError,init_error=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js"(){CommanderError=class extends Error{constructor(exitCode,code,message){super(message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=code,this.exitCode=exitCode,this.nestedError=void 0}},InvalidArgumentError=class extends CommanderError{constructor(message){super(1,"commander.invalidArgument",message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}}});function humanReadableArgName(arg){let nameOutput=arg.name()+(arg.variadic===!0?"...":"");return arg.required?"<"+nameOutput+">":"["+nameOutput+"]"}var Argument,init_argument=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js"(){init_error();Argument=class{constructor(name,description){switch(this.description=description||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,name[0]){case"<":this.required=!0,this._name=name.slice(1,-1);break;case"[":this.required=!1,this._name=name.slice(1,-1);break;default:this.required=!0,this._name=name;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}argParser(fn){return this.parseArg=fn,this}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}}});import{stripVTControlCharacters}from"node:util";var Help,init_help=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js"(){init_argument();Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(contextOptions){this.helpWidth=this.helpWidth??contextOptions.helpWidth??80}visibleCommands(cmd){let visibleCommands=cmd.commands.filter(cmd2=>!cmd2._hidden),helpCommand=cmd._getHelpCommand();return helpCommand&&!helpCommand._hidden&&visibleCommands.push(helpCommand),this.sortSubcommands&&visibleCommands.sort((a,b)=>a.name().localeCompare(b.name())),visibleCommands}compareOptions(a,b){let getSortKey=option=>option.short?option.short.replace(/^-/,""):option.long.replace(/^--/,"");return getSortKey(a).localeCompare(getSortKey(b))}visibleOptions(cmd){let visibleOptions=cmd.options.filter(option=>!option.hidden),helpOption=cmd._getHelpOption();if(helpOption&&!helpOption.hidden){let removeShort=helpOption.short&&cmd._findOption(helpOption.short),removeLong=helpOption.long&&cmd._findOption(helpOption.long);!removeShort&&!removeLong?visibleOptions.push(helpOption):helpOption.long&&!removeLong?visibleOptions.push(cmd.createOption(helpOption.long,helpOption.description)):helpOption.short&&!removeShort&&visibleOptions.push(cmd.createOption(helpOption.short,helpOption.description))}return this.sortOptions&&visibleOptions.sort(this.compareOptions),visibleOptions}visibleGlobalOptions(cmd){if(!this.showGlobalOptions)return[];let globalOptions=[];for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent){let visibleOptions=ancestorCmd.options.filter(option=>!option.hidden);globalOptions.push(...visibleOptions)}return this.sortOptions&&globalOptions.sort(this.compareOptions),globalOptions}visibleArguments(cmd){return cmd._argsDescription&&cmd.registeredArguments.forEach(argument=>{argument.description=argument.description||cmd._argsDescription[argument.name()]||""}),cmd.registeredArguments.find(argument=>argument.description)?cmd.registeredArguments:[]}subcommandTerm(cmd){let args=cmd.registeredArguments.map(arg=>humanReadableArgName(arg)).join(" ");return cmd._name+(cmd._aliases[0]?"|"+cmd._aliases[0]:"")+(cmd.options.length?" [options]":"")+(args?" "+args:"")}optionTerm(option){return option.flags}argumentTerm(argument){return argument.name()}longestSubcommandTermLength(cmd,helper){return helper.visibleCommands(cmd).reduce((max,command)=>Math.max(max,this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command)))),0)}longestOptionTermLength(cmd,helper){return helper.visibleOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestGlobalOptionTermLength(cmd,helper){return helper.visibleGlobalOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestArgumentTermLength(cmd,helper){return helper.visibleArguments(cmd).reduce((max,argument)=>Math.max(max,this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument)))),0)}commandUsage(cmd){let cmdName=cmd._name;cmd._aliases[0]&&(cmdName=cmdName+"|"+cmd._aliases[0]);let ancestorCmdNames="";for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent)ancestorCmdNames=ancestorCmd.name()+" "+ancestorCmdNames;return ancestorCmdNames+cmdName+" "+cmd.usage()}commandDescription(cmd){return cmd.description()}subcommandDescription(cmd){return cmd.summary()||cmd.description()}optionDescription(option){let extraInfo=[];if(option.argChoices&&extraInfo.push(`choices: ${option.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),option.defaultValue!==void 0&&(option.required||option.optional||option.isBoolean()&&typeof option.defaultValue=="boolean")&&extraInfo.push(`default: ${option.defaultValueDescription||JSON.stringify(option.defaultValue)}`),option.presetArg!==void 0&&option.optional&&extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`),option.envVar!==void 0&&extraInfo.push(`env: ${option.envVar}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return option.description?`${option.description} ${extraDescription}`:extraDescription}return option.description}argumentDescription(argument){let extraInfo=[];if(argument.argChoices&&extraInfo.push(`choices: ${argument.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),argument.defaultValue!==void 0&&extraInfo.push(`default: ${argument.defaultValueDescription||JSON.stringify(argument.defaultValue)}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return argument.description?`${argument.description} ${extraDescription}`:extraDescription}return argument.description}formatItemList(heading,items,helper){return items.length===0?[]:[helper.styleTitle(heading),...items,""]}groupItems(unsortedItems,visibleItems,getGroup){let result=new Map;return unsortedItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[])}),visibleItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[]),result.get(group).push(item)}),result}formatHelp(cmd,helper){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80;function callFormatItem(term,description){return helper.formatItem(term,termWidth,description,helper)}let output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));if(output=output.concat(this.formatItemList("Arguments:",argumentList,helper)),this.groupItems(cmd.options,helper.visibleOptions(cmd),option=>option.helpGroupHeading??"Options:").forEach((options,group)=>{let optionList=options.map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList(group,optionList,helper))}),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList("Global Options:",globalOptionList,helper))}return this.groupItems(cmd.commands,helper.visibleCommands(cmd),sub=>sub.helpGroup()||"Commands:").forEach((commands,group)=>{let commandList=commands.map(sub=>callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)),helper.styleSubcommandDescription(helper.subcommandDescription(sub))));output=output.concat(this.formatItemList(group,commandList,helper))}),output.join(`
634
- `)}displayWidth(str){return stripVTControlCharacters(str).length}styleTitle(str){return str}styleUsage(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word==="[command]"?this.styleSubcommandText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleCommandText(word)).join(" ")}styleCommandDescription(str){return this.styleDescriptionText(str)}styleOptionDescription(str){return this.styleDescriptionText(str)}styleSubcommandDescription(str){return this.styleDescriptionText(str)}styleArgumentDescription(str){return this.styleDescriptionText(str)}styleDescriptionText(str){return str}styleOptionTerm(str){return this.styleOptionText(str)}styleSubcommandTerm(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleSubcommandText(word)).join(" ")}styleArgumentTerm(str){return this.styleArgumentText(str)}styleOptionText(str){return str}styleArgumentText(str){return str}styleSubcommandText(str){return str}styleCommandText(str){return str}padWidth(cmd,helper){return Math.max(helper.longestOptionTermLength(cmd,helper),helper.longestGlobalOptionTermLength(cmd,helper),helper.longestSubcommandTermLength(cmd,helper),helper.longestArgumentTermLength(cmd,helper))}preformatted(str){return/\n[^\S\r\n]/.test(str)}formatItem(term,termWidth,description,helper){let itemIndentStr=" ".repeat(2);if(!description)return itemIndentStr+term;let paddedTerm=term.padEnd(termWidth+term.length-helper.displayWidth(term)),spacerWidth=2,remainingWidth=(this.helpWidth??80)-termWidth-spacerWidth-2,formattedDescription;return remainingWidth<this.minWidthToWrap||helper.preformatted(description)?formattedDescription=description:formattedDescription=helper.boxWrap(description,remainingWidth).replace(/\n/g,`
617
+ `)}var MAX_SOCKET_BUFFER_SIZE,SOCKET_PATH,SESSION_OPTION,defaultBrowser,persistentSpawnPromise,discoveryListPromise,discoveryListCache,DISCOVERY_STARTUP_TIMEOUT_MS,DISCOVERY_RETRY_INTERVAL_MS,DISCOVERY_MISS_CACHE_MS,EXTENSION_INSTALL_URL,init_socket=__esm({"../client/src/socket.ts"(){"use strict";init_runtimePaths();init_host();init_dist4();init_runtime();init_fileRefs();init_browserRegistry();init_actionTimeouts();init_dist2();MAX_SOCKET_BUFFER_SIZE=64*1024*1024,SOCKET_PATH=process.platform==="win32"?"\\\\.\\pipe\\mearl-agent":path4.join(os2.tmpdir(),"mearl-agent.sock");SESSION_OPTION=Symbol("control-session");persistentSpawnPromise=null,discoveryListPromise=null,discoveryListCache=null,DISCOVERY_STARTUP_TIMEOUT_MS=3e3,DISCOVERY_RETRY_INTERVAL_MS=50,DISCOVERY_MISS_CACHE_MS=2e3;EXTENSION_INSTALL_URL="https://chromewebstore.google.com/detail/mearl/aoehhjnofngknnjefamjbplchbolghkm"}});import{existsSync as existsSync7,readFileSync as readFileSync11}from"node:fs";import{homedir as homedir3}from"node:os";import{join as join14}from"node:path";function loadLocalConnectorId(){let explicit=process.env.MEARL_CONNECTOR_ID?.trim();if(explicit)return explicit;try{let config=JSON.parse(readFileSync11(join14(MEARL_CONFIG_DIR,"cloud-connector-identity.json"),"utf8"));return typeof config.connectorId=="string"&&config.connectorId.trim()?config.connectorId:null}catch{return null}}var MEARL_CONFIG_DIR,init_unifiedConfig=__esm({"../client/src/unifiedConfig.ts"(){"use strict";MEARL_CONFIG_DIR=join14(homedir3(),".mearl")}});import{createHash as createHash7}from"node:crypto";function normalizePluginState(value){if(value===void 0)return;let declaration=JSON.parse(JSON.stringify(value));if(!declaration||declaration.version!==1||!declaration.collections||Array.isArray(declaration.collections)||Object.keys(declaration.collections).length>32||Buffer.byteLength(JSON.stringify(declaration))>128*1024)throw new Error("Invalid stateStorage declaration");for(let[name,collection]of Object.entries(declaration.collections)){if(!/^[a-z][a-z0-9-]{0,63}$/.test(name)||!collection||!["installation","host","browser-session","instance"].includes(collection.scope)||!["persistent","cache","memory"].includes(collection.storage)||!Number.isSafeInteger(collection.schemaVersion)||collection.schemaVersion<1||!collection.schema||typeof collection.schema!="object"||Array.isArray(collection.schema)||collection.schema.$async)throw new Error(`Invalid state collection: ${name}`);if(["browser-session","instance"].includes(collection.scope)&&!["cache","memory"].includes(collection.storage))throw new Error("Document state requires cache or memory storage");if(collection.storage==="memory"&&!["browser-session","instance"].includes(collection.scope))throw new Error("Memory state requires a browser session or instance scope");if(collection.maxEntries!==void 0&&(!Number.isSafeInteger(collection.maxEntries)||collection.maxEntries<1||collection.maxEntries>4096))throw new Error("State maxEntries must be between 1 and 4096");if(collection.maxBytes!==void 0&&(!Number.isSafeInteger(collection.maxBytes)||collection.maxBytes<1||collection.maxBytes>(collection.storage==="memory"?128:16)*1024*1024))throw new Error("State maxBytes exceeds its storage limit");if(collection.ttlMs!==void 0&&(!Number.isSafeInteger(collection.ttlMs)||collection.ttlMs<1||collection.ttlMs>7*864e5))throw new Error("State TTL must be between 1 ms and 7 days");if(collection.storage==="persistent"&&collection.ttlMs!==void 0)throw new Error("Persistent state does not accept TTL")}return declaration}function pluginStateSignature(collection){return createHash7("sha256").update(JSON.stringify(collection,(_key,value)=>value&&typeof value=="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0)):value)).digest("hex")}var init_pluginStateDefinition=__esm({"../client/src/plugins/sdk/pluginStateDefinition.ts"(){"use strict"}});import{Script}from"node:vm";function normalizePluginPageRuntime(value){if(value===void 0)return;let runtime=value;if(!runtime||runtime.version!==1||!Array.isArray(runtime.matches)||!runtime.matches.length||runtime.matches.length>64||!runtime.matches.every(isPluginPageMatchPattern)||typeof runtime.code!="string"||Buffer.byteLength(runtime.code)>384*1024||Buffer.byteLength(JSON.stringify(runtime))>448*1024)throw new Error("Invalid plugin pageRuntime declaration");if(new Script(`(${runtime.code}
618
+ )`,{filename:"plugin-page-runtime.js"}),runtime.events!==void 0&&(!runtime.events||typeof runtime.events!="object"||Array.isArray(runtime.events)||Object.keys(runtime.events).length>32))throw new Error("Invalid page runtime events");for(let[name,event]of Object.entries(runtime.events??{}))if(!/^[a-z][a-z0-9-]{0,63}$/.test(name)||!event||!/^[a-z][a-z0-9-]*$/.test(event.command)||!event.schema||typeof event.schema!="object"||Array.isArray(event.schema)||event.policy!==void 0&&!["serial","latest","parallel"].includes(event.policy)||event.concurrency!==void 0&&(!Number.isSafeInteger(event.concurrency)||event.concurrency<1||event.concurrency>8)||event.maxPending!==void 0&&(!Number.isSafeInteger(event.maxPending)||event.maxPending<1||event.maxPending>64)||event.schema.$async)throw new Error(`Invalid page event binding: ${name}`);if(runtime.initialize!==void 0&&!/^[a-z][a-z0-9-]*$/.test(runtime.initialize))throw new Error("Invalid page runtime initialize command");return JSON.parse(JSON.stringify(runtime))}var init_pluginPageDefinition=__esm({"../client/src/plugins/sdk/pluginPageDefinition.ts"(){"use strict";init_dist2()}});import{readFileSync as readFileSync12,realpathSync as realpathSync3}from"node:fs";import{basename as basename4,dirname as dirname7,isAbsolute as isAbsolute5,relative as relative4,resolve as resolve5}from"node:path";function loadPluginAppProfiles(entry,value){if(value===void 0)return{};if(!value||typeof value!="object"||Array.isArray(value))throw new Error("appProfiles must be an object");let declaration=value;if(!Array.isArray(declaration.profiles))throw new Error("appProfiles.profiles must be an array");let root=realpathSync3(basename4(dirname7(entry))==="scripts"?dirname7(dirname7(entry)):dirname7(entry)),sources={},profiles=declaration.profiles.map(profile=>{if(typeof profile!="string")return profile;if(isAbsolute5(profile)||!profile.endsWith(".json"))throw new Error("Profile resource must be a relative JSON path");let reference=resolve5(root,profile),file=realpathSync3(reference),inside=relative4(root,file);if(inside.startsWith("..")||isAbsolute5(inside))throw new Error("Profile resource must stay inside the Skill directory");let version=pluginFileVersion(file),content=readFileSync12(file,"utf8");if(content.length>65536)throw new Error("Profile resource exceeds 64 KiB");let parsed=JSON.parse(content);if(pluginFileVersion(reference)!==version)throw new Error("Profile resource changed during registration");return sources[reference]=version,parsed});return{appProfiles:validateAppProfileContribution({...declaration,profiles}),profileSources:sources}}var init_pluginAppProfiles=__esm({"../client/src/plugins/sdk/pluginAppProfiles.ts"(){"use strict";init_dist2();init_pluginSource()}});var require_error=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js"(exports){var CommanderError2=class extends Error{constructor(exitCode,code,message){super(message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=code,this.exitCode=exitCode,this.nestedError=void 0}},InvalidArgumentError2=class extends CommanderError2{constructor(message){super(1,"commander.invalidArgument",message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};exports.CommanderError=CommanderError2;exports.InvalidArgumentError=InvalidArgumentError2}});var require_argument=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js"(exports){var{InvalidArgumentError:InvalidArgumentError2}=require_error(),Argument2=class{constructor(name,description){switch(this.description=description||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,name[0]){case"<":this.required=!0,this._name=name.slice(1,-1);break;case"[":this.required=!1,this._name=name.slice(1,-1);break;default:this.required=!0,this._name=name;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}argParser(fn){return this.parseArg=fn,this}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function humanReadableArgName(arg){let nameOutput=arg.name()+(arg.variadic===!0?"...":"");return arg.required?"<"+nameOutput+">":"["+nameOutput+"]"}exports.Argument=Argument2;exports.humanReadableArgName=humanReadableArgName}});var require_help=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js"(exports){var{humanReadableArgName}=require_argument(),Help2=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(contextOptions){this.helpWidth=this.helpWidth??contextOptions.helpWidth??80}visibleCommands(cmd){let visibleCommands=cmd.commands.filter(cmd2=>!cmd2._hidden),helpCommand=cmd._getHelpCommand();return helpCommand&&!helpCommand._hidden&&visibleCommands.push(helpCommand),this.sortSubcommands&&visibleCommands.sort((a,b)=>a.name().localeCompare(b.name())),visibleCommands}compareOptions(a,b){let getSortKey=option=>option.short?option.short.replace(/^-/,""):option.long.replace(/^--/,"");return getSortKey(a).localeCompare(getSortKey(b))}visibleOptions(cmd){let visibleOptions=cmd.options.filter(option=>!option.hidden),helpOption=cmd._getHelpOption();if(helpOption&&!helpOption.hidden){let removeShort=helpOption.short&&cmd._findOption(helpOption.short),removeLong=helpOption.long&&cmd._findOption(helpOption.long);!removeShort&&!removeLong?visibleOptions.push(helpOption):helpOption.long&&!removeLong?visibleOptions.push(cmd.createOption(helpOption.long,helpOption.description)):helpOption.short&&!removeShort&&visibleOptions.push(cmd.createOption(helpOption.short,helpOption.description))}return this.sortOptions&&visibleOptions.sort(this.compareOptions),visibleOptions}visibleGlobalOptions(cmd){if(!this.showGlobalOptions)return[];let globalOptions=[];for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent){let visibleOptions=ancestorCmd.options.filter(option=>!option.hidden);globalOptions.push(...visibleOptions)}return this.sortOptions&&globalOptions.sort(this.compareOptions),globalOptions}visibleArguments(cmd){return cmd._argsDescription&&cmd.registeredArguments.forEach(argument=>{argument.description=argument.description||cmd._argsDescription[argument.name()]||""}),cmd.registeredArguments.find(argument=>argument.description)?cmd.registeredArguments:[]}subcommandTerm(cmd){let args=cmd.registeredArguments.map(arg=>humanReadableArgName(arg)).join(" ");return cmd._name+(cmd._aliases[0]?"|"+cmd._aliases[0]:"")+(cmd.options.length?" [options]":"")+(args?" "+args:"")}optionTerm(option){return option.flags}argumentTerm(argument){return argument.name()}longestSubcommandTermLength(cmd,helper){return helper.visibleCommands(cmd).reduce((max,command)=>Math.max(max,this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command)))),0)}longestOptionTermLength(cmd,helper){return helper.visibleOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestGlobalOptionTermLength(cmd,helper){return helper.visibleGlobalOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestArgumentTermLength(cmd,helper){return helper.visibleArguments(cmd).reduce((max,argument)=>Math.max(max,this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument)))),0)}commandUsage(cmd){let cmdName=cmd._name;cmd._aliases[0]&&(cmdName=cmdName+"|"+cmd._aliases[0]);let ancestorCmdNames="";for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent)ancestorCmdNames=ancestorCmd.name()+" "+ancestorCmdNames;return ancestorCmdNames+cmdName+" "+cmd.usage()}commandDescription(cmd){return cmd.description()}subcommandDescription(cmd){return cmd.summary()||cmd.description()}optionDescription(option){let extraInfo=[];if(option.argChoices&&extraInfo.push(`choices: ${option.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),option.defaultValue!==void 0&&(option.required||option.optional||option.isBoolean()&&typeof option.defaultValue=="boolean")&&extraInfo.push(`default: ${option.defaultValueDescription||JSON.stringify(option.defaultValue)}`),option.presetArg!==void 0&&option.optional&&extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`),option.envVar!==void 0&&extraInfo.push(`env: ${option.envVar}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return option.description?`${option.description} ${extraDescription}`:extraDescription}return option.description}argumentDescription(argument){let extraInfo=[];if(argument.argChoices&&extraInfo.push(`choices: ${argument.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),argument.defaultValue!==void 0&&extraInfo.push(`default: ${argument.defaultValueDescription||JSON.stringify(argument.defaultValue)}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return argument.description?`${argument.description} ${extraDescription}`:extraDescription}return argument.description}formatItemList(heading,items,helper){return items.length===0?[]:[helper.styleTitle(heading),...items,""]}groupItems(unsortedItems,visibleItems,getGroup){let result=new Map;return unsortedItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[])}),visibleItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[]),result.get(group).push(item)}),result}formatHelp(cmd,helper){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80;function callFormatItem(term,description){return helper.formatItem(term,termWidth,description,helper)}let output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));if(output=output.concat(this.formatItemList("Arguments:",argumentList,helper)),this.groupItems(cmd.options,helper.visibleOptions(cmd),option=>option.helpGroupHeading??"Options:").forEach((options,group)=>{let optionList=options.map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList(group,optionList,helper))}),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList("Global Options:",globalOptionList,helper))}return this.groupItems(cmd.commands,helper.visibleCommands(cmd),sub=>sub.helpGroup()||"Commands:").forEach((commands,group)=>{let commandList=commands.map(sub=>callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)),helper.styleSubcommandDescription(helper.subcommandDescription(sub))));output=output.concat(this.formatItemList(group,commandList,helper))}),output.join(`
619
+ `)}displayWidth(str){return stripColor(str).length}styleTitle(str){return str}styleUsage(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word==="[command]"?this.styleSubcommandText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleCommandText(word)).join(" ")}styleCommandDescription(str){return this.styleDescriptionText(str)}styleOptionDescription(str){return this.styleDescriptionText(str)}styleSubcommandDescription(str){return this.styleDescriptionText(str)}styleArgumentDescription(str){return this.styleDescriptionText(str)}styleDescriptionText(str){return str}styleOptionTerm(str){return this.styleOptionText(str)}styleSubcommandTerm(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleSubcommandText(word)).join(" ")}styleArgumentTerm(str){return this.styleArgumentText(str)}styleOptionText(str){return str}styleArgumentText(str){return str}styleSubcommandText(str){return str}styleCommandText(str){return str}padWidth(cmd,helper){return Math.max(helper.longestOptionTermLength(cmd,helper),helper.longestGlobalOptionTermLength(cmd,helper),helper.longestSubcommandTermLength(cmd,helper),helper.longestArgumentTermLength(cmd,helper))}preformatted(str){return/\n[^\S\r\n]/.test(str)}formatItem(term,termWidth,description,helper){let itemIndentStr=" ".repeat(2);if(!description)return itemIndentStr+term;let paddedTerm=term.padEnd(termWidth+term.length-helper.displayWidth(term)),spacerWidth=2,remainingWidth=(this.helpWidth??80)-termWidth-spacerWidth-2,formattedDescription;return remainingWidth<this.minWidthToWrap||helper.preformatted(description)?formattedDescription=description:formattedDescription=helper.boxWrap(description,remainingWidth).replace(/\n/g,`
635
620
  `+" ".repeat(termWidth+spacerWidth)),itemIndentStr+paddedTerm+" ".repeat(spacerWidth)+formattedDescription.replace(/\n/g,`
636
621
  ${itemIndentStr}`)}boxWrap(str,width){if(width<this.minWidthToWrap)return str;let rawLines=str.split(/\r\n|\n/),chunkPattern=/[\s]*[^\s]+/g,wrappedLines=[];return rawLines.forEach(line=>{let chunks=line.match(chunkPattern);if(chunks===null){wrappedLines.push("");return}let sumChunks=[chunks.shift()],sumWidth=this.displayWidth(sumChunks[0]);chunks.forEach(chunk=>{let visibleWidth=this.displayWidth(chunk);if(sumWidth+visibleWidth<=width){sumChunks.push(chunk),sumWidth+=visibleWidth;return}wrappedLines.push(sumChunks.join(""));let nextChunk=chunk.trimStart();sumChunks=[nextChunk],sumWidth=this.displayWidth(nextChunk)}),wrappedLines.push(sumChunks.join(""))}),wrappedLines.join(`
637
- `)}}}});function camelcase(str){return str.split("-").reduce((str2,word)=>str2+word[0].toUpperCase()+word.slice(1))}function splitOptionFlags(flags){let shortFlag,longFlag,shortFlagExp=/^-[^-]$/,longFlagExp=/^--[^-]/,flagParts=flags.split(/[ |,]+/).concat("guard");if(shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),longFlagExp.test(flagParts[0])&&(longFlag=flagParts.shift()),!shortFlag&&shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),!shortFlag&&longFlagExp.test(flagParts[0])&&(shortFlag=longFlag,longFlag=flagParts.shift()),flagParts[0].startsWith("-")){let unsupportedFlag=flagParts[0],baseError=`option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;throw/^-[^-][^-]/.test(unsupportedFlag)?new Error(`${baseError}
622
+ `)}};function stripColor(str){let sgrPattern=/\x1b\[\d*(;\d*)*m/g;return str.replace(sgrPattern,"")}exports.Help=Help2;exports.stripColor=stripColor}});var require_option=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js"(exports){var{InvalidArgumentError:InvalidArgumentError2}=require_error(),Option2=class{constructor(flags,description){this.flags=flags,this.description=description||"",this.required=flags.includes("<"),this.optional=flags.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(flags),this.mandatory=!1;let optionFlags=splitOptionFlags(flags);this.short=optionFlags.shortFlag,this.long=optionFlags.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}preset(arg){return this.presetArg=arg,this}conflicts(names){return this.conflictsWith=this.conflictsWith.concat(names),this}implies(impliedOptionValues){let newImplied=impliedOptionValues;return typeof impliedOptionValues=="string"&&(newImplied={[impliedOptionValues]:!0}),this.implied=Object.assign(this.implied||{},newImplied),this}env(name){return this.envVar=name,this}argParser(fn){return this.parseArg=fn,this}makeOptionMandatory(mandatory=!0){return this.mandatory=!!mandatory,this}hideHelp(hide=!0){return this.hidden=!!hide,this}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?camelcase(this.name().replace(/^no-/,"")):camelcase(this.name())}helpGroup(heading){return this.helpGroupHeading=heading,this}is(arg){return this.short===arg||this.long===arg}isBoolean(){return!this.required&&!this.optional&&!this.negate}},DualOptions=class{constructor(options){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,options.forEach(option=>{option.negate?this.negativeOptions.set(option.attributeName(),option):this.positiveOptions.set(option.attributeName(),option)}),this.negativeOptions.forEach((value,key2)=>{this.positiveOptions.has(key2)&&this.dualOptions.add(key2)})}valueFromOption(value,option){let optionKey=option.attributeName();if(!this.dualOptions.has(optionKey))return!0;let preset=this.negativeOptions.get(optionKey).presetArg,negativeValue=preset!==void 0?preset:!1;return option.negate===(negativeValue===value)}};function camelcase(str){return str.split("-").reduce((str2,word)=>str2+word[0].toUpperCase()+word.slice(1))}function splitOptionFlags(flags){let shortFlag,longFlag,shortFlagExp=/^-[^-]$/,longFlagExp=/^--[^-]/,flagParts=flags.split(/[ |,]+/).concat("guard");if(shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),longFlagExp.test(flagParts[0])&&(longFlag=flagParts.shift()),!shortFlag&&shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),!shortFlag&&longFlagExp.test(flagParts[0])&&(shortFlag=longFlag,longFlag=flagParts.shift()),flagParts[0].startsWith("-")){let unsupportedFlag=flagParts[0],baseError=`option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;throw/^-[^-][^-]/.test(unsupportedFlag)?new Error(`${baseError}
638
623
  - a short flag is a single dash and a single character
639
624
  - either use a single dash and a single character (for a short flag)
640
625
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):shortFlagExp.test(unsupportedFlag)?new Error(`${baseError}
641
626
  - too many short flags`):longFlagExp.test(unsupportedFlag)?new Error(`${baseError}
642
627
  - too many long flags`):new Error(`${baseError}
643
- - unrecognised flag format`)}if(shortFlag===void 0&&longFlag===void 0)throw new Error(`option creation failed due to no flags found in '${flags}'.`);return{shortFlag,longFlag}}var Option,DualOptions,init_option=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js"(){init_error();Option=class{constructor(flags,description){this.flags=flags,this.description=description||"",this.required=flags.includes("<"),this.optional=flags.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(flags),this.mandatory=!1;let optionFlags=splitOptionFlags(flags);this.short=optionFlags.shortFlag,this.long=optionFlags.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}preset(arg){return this.presetArg=arg,this}conflicts(names){return this.conflictsWith=this.conflictsWith.concat(names),this}implies(impliedOptionValues){let newImplied=impliedOptionValues;return typeof impliedOptionValues=="string"&&(newImplied={[impliedOptionValues]:!0}),this.implied=Object.assign(this.implied||{},newImplied),this}env(name){return this.envVar=name,this}argParser(fn){return this.parseArg=fn,this}makeOptionMandatory(mandatory=!0){return this.mandatory=!!mandatory,this}hideHelp(hide=!0){return this.hidden=!!hide,this}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?camelcase(this.name().replace(/^no-/,"")):camelcase(this.name())}helpGroup(heading){return this.helpGroupHeading=heading,this}is(arg){return this.short===arg||this.long===arg}isBoolean(){return!this.required&&!this.optional&&!this.negate}},DualOptions=class{constructor(options){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,options.forEach(option=>{option.negate?this.negativeOptions.set(option.attributeName(),option):this.positiveOptions.set(option.attributeName(),option)}),this.negativeOptions.forEach((value,key2)=>{this.positiveOptions.has(key2)&&this.dualOptions.add(key2)})}valueFromOption(value,option){let optionKey=option.attributeName();if(!this.dualOptions.has(optionKey))return!0;let preset=this.negativeOptions.get(optionKey).presetArg,negativeValue=preset!==void 0?preset:!1;return option.negate===(negativeValue===value)}}}});function editDistance(a,b){if(Math.abs(a.length-b.length)>3)return Math.max(a.length,b.length);let d=[];for(let i2=0;i2<=a.length;i2++)d[i2]=[i2];for(let j=0;j<=b.length;j++)d[0][j]=j;for(let j=1;j<=b.length;j++)for(let i2=1;i2<=a.length;i2++){let cost;a[i2-1]===b[j-1]?cost=0:cost=1,d[i2][j]=Math.min(d[i2-1][j]+1,d[i2][j-1]+1,d[i2-1][j-1]+cost),i2>1&&j>1&&a[i2-1]===b[j-2]&&a[i2-2]===b[j-1]&&(d[i2][j]=Math.min(d[i2][j],d[i2-2][j-2]+1))}return d[a.length][b.length]}function suggestSimilar(word,candidates){if(!candidates||candidates.length===0)return"";candidates=Array.from(new Set(candidates));let searchingOptions=word.startsWith("--");searchingOptions&&(word=word.slice(2),candidates=candidates.map(candidate=>candidate.slice(2)));let similar=[],bestDistance=3,minSimilarity=.4;return candidates.forEach(candidate=>{if(candidate.length<=1)return;let distance=editDistance(word,candidate),length=Math.max(word.length,candidate.length);(length-distance)/length>minSimilarity&&(distance<bestDistance?(bestDistance=distance,similar=[candidate]):distance===bestDistance&&similar.push(candidate))}),similar.sort((a,b)=>a.localeCompare(b)),searchingOptions&&(similar=similar.map(candidate=>`--${candidate}`)),similar.length>1?`
628
+ - unrecognised flag format`)}if(shortFlag===void 0&&longFlag===void 0)throw new Error(`option creation failed due to no flags found in '${flags}'.`);return{shortFlag,longFlag}}exports.Option=Option2;exports.DualOptions=DualOptions}});var require_suggestSimilar=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js"(exports){function editDistance(a,b){if(Math.abs(a.length-b.length)>3)return Math.max(a.length,b.length);let d=[];for(let i=0;i<=a.length;i++)d[i]=[i];for(let j=0;j<=b.length;j++)d[0][j]=j;for(let j=1;j<=b.length;j++)for(let i=1;i<=a.length;i++){let cost=1;a[i-1]===b[j-1]?cost=0:cost=1,d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+cost),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(d[i][j]=Math.min(d[i][j],d[i-2][j-2]+1))}return d[a.length][b.length]}function suggestSimilar(word,candidates){if(!candidates||candidates.length===0)return"";candidates=Array.from(new Set(candidates));let searchingOptions=word.startsWith("--");searchingOptions&&(word=word.slice(2),candidates=candidates.map(candidate=>candidate.slice(2)));let similar=[],bestDistance=3,minSimilarity=.4;return candidates.forEach(candidate=>{if(candidate.length<=1)return;let distance=editDistance(word,candidate),length=Math.max(word.length,candidate.length);(length-distance)/length>minSimilarity&&(distance<bestDistance?(bestDistance=distance,similar=[candidate]):distance===bestDistance&&similar.push(candidate))}),similar.sort((a,b)=>a.localeCompare(b)),searchingOptions&&(similar=similar.map(candidate=>`--${candidate}`)),similar.length>1?`
644
629
  (Did you mean one of ${similar.join(", ")}?)`:similar.length===1?`
645
- (Did you mean ${similar[0]}?)`:""}var init_suggestSimilar=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js"(){}});import{EventEmitter}from"node:events";import childProcess from"node:child_process";import path5 from"node:path";import fs5 from"node:fs";import process2 from"node:process";import{stripVTControlCharacters as stripVTControlCharacters2}from"node:util";function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process2.env.NO_COLOR||process2.env.FORCE_COLOR==="0"||process2.env.FORCE_COLOR==="false")return!1;if(process2.env.FORCE_COLOR||process2.env.CLICOLOR_FORCE!==void 0)return!0}var Command,init_command2=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js"(){init_argument();init_error();init_help();init_option();init_suggestSimilar();Command=class _Command extends EventEmitter{constructor(name){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=name||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:str=>process2.stdout.write(str),writeErr:str=>process2.stderr.write(str),outputError:(str,write)=>write(str),getOutHelpWidth:()=>process2.stdout.isTTY?process2.stdout.columns:void 0,getErrHelpWidth:()=>process2.stderr.isTTY?process2.stderr.columns:void 0,getOutHasColors:()=>useColor()??(process2.stdout.isTTY&&process2.stdout.hasColors?.()),getErrHasColors:()=>useColor()??(process2.stderr.isTTY&&process2.stderr.hasColors?.()),stripColor:str=>stripVTControlCharacters2(str)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(sourceCommand){return this._outputConfiguration=sourceCommand._outputConfiguration,this._helpOption=sourceCommand._helpOption,this._helpCommand=sourceCommand._helpCommand,this._helpConfiguration=sourceCommand._helpConfiguration,this._exitCallback=sourceCommand._exitCallback,this._storeOptionsAsProperties=sourceCommand._storeOptionsAsProperties,this._combineFlagAndOptionalValue=sourceCommand._combineFlagAndOptionalValue,this._allowExcessArguments=sourceCommand._allowExcessArguments,this._enablePositionalOptions=sourceCommand._enablePositionalOptions,this._showHelpAfterError=sourceCommand._showHelpAfterError,this._showSuggestionAfterError=sourceCommand._showSuggestionAfterError,this}_getCommandAndAncestors(){let result=[];for(let command=this;command;command=command.parent)result.push(command);return result}command(nameAndArgs,actionOptsOrExecDesc,execOpts){let desc=actionOptsOrExecDesc,opts=execOpts;typeof desc=="object"&&desc!==null&&(opts=desc,desc=null),opts=opts||{};let[,name,args]=nameAndArgs.match(/([^ ]+) *(.*)/),cmd=this.createCommand(name);return desc&&(cmd.description(desc),cmd._executableHandler=!0),opts.isDefault&&(this._defaultCommandName=cmd._name),cmd._hidden=!!(opts.noHelp||opts.hidden),cmd._executableFile=opts.executableFile||null,args&&cmd.arguments(args),this._registerCommand(cmd),cmd.parent=this,cmd.copyInheritedSettings(this),desc?this:cmd}createCommand(name){return new _Command(name)}createHelp(){return Object.assign(new Help,this.configureHelp())}configureHelp(configuration){return configuration===void 0?this._helpConfiguration:(this._helpConfiguration=configuration,this)}configureOutput(configuration){return configuration===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...configuration},this)}showHelpAfterError(displayHelp=!0){return typeof displayHelp!="string"&&(displayHelp=!!displayHelp),this._showHelpAfterError=displayHelp,this}showSuggestionAfterError(displaySuggestion=!0){return this._showSuggestionAfterError=!!displaySuggestion,this}addCommand(cmd,opts){if(!cmd._name)throw new Error(`Command passed to .addCommand() must have a name
646
- - specify the name in Command constructor or using .name()`);return opts=opts||{},opts.isDefault&&(this._defaultCommandName=cmd._name),(opts.noHelp||opts.hidden)&&(cmd._hidden=!0),this._registerCommand(cmd),cmd.parent=this,cmd._checkForBrokenPassThrough(),this}createArgument(name,description){return new Argument(name,description)}argument(name,description,parseArg,defaultValue){let argument=this.createArgument(name,description);return typeof parseArg=="function"?argument.default(defaultValue).argParser(parseArg):argument.default(parseArg),this.addArgument(argument),this}arguments(names){return names.trim().split(/ +/).forEach(detail=>{this.argument(detail)}),this}addArgument(argument){let previousArgument=this.registeredArguments.slice(-1)[0];if(previousArgument?.variadic)throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);if(argument.required&&argument.defaultValue!==void 0&&argument.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);return this.registeredArguments.push(argument),this}helpCommand(enableOrNameAndArgs,description){if(typeof enableOrNameAndArgs=="boolean")return this._addImplicitHelpCommand=enableOrNameAndArgs,enableOrNameAndArgs&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let nameAndArgs=enableOrNameAndArgs??"help [command]",[,helpName,helpArgs]=nameAndArgs.match(/([^ ]+) *(.*)/),helpDescription=description??"display help for command",helpCommand=this.createCommand(helpName);return helpCommand.helpOption(!1),helpArgs&&helpCommand.arguments(helpArgs),helpDescription&&helpCommand.description(helpDescription),this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,(enableOrNameAndArgs||description)&&this._initCommandGroup(helpCommand),this}addHelpCommand(helpCommand,deprecatedDescription){return typeof helpCommand!="object"?(this.helpCommand(helpCommand,deprecatedDescription),this):(this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,this._initCommandGroup(helpCommand),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(event,listener){let allowedValues=["preSubcommand","preAction","postAction"];if(!allowedValues.includes(event))throw new Error(`Unexpected value for event passed to hook : '${event}'.
647
- Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[event]?this._lifeCycleHooks[event].push(listener):this._lifeCycleHooks[event]=[listener],this}exitOverride(fn){return fn?this._exitCallback=fn:this._exitCallback=err=>{if(err.code!=="commander.executeSubCommandAsync")throw err},this}_exit(exitCode,code,message){this._exitCallback&&this._exitCallback(new CommanderError(exitCode,code,message)),process2.exit(exitCode)}action(fn){let listener=args=>{let expectedArgsCount=this.registeredArguments.length,actionArgs=args.slice(0,expectedArgsCount);return this._storeOptionsAsProperties?actionArgs[expectedArgsCount]=this:actionArgs[expectedArgsCount]=this.opts(),actionArgs.push(this),fn.apply(this,actionArgs)};return this._actionHandler=listener,this}createOption(flags,description){return new Option(flags,description)}_callParseArg(target,value,previous,invalidArgumentMessage){try{return target.parseArg(value,previous)}catch(err){if(err.code==="commander.invalidArgument"){let message=`${invalidArgumentMessage} ${err.message}`;this.error(message,{exitCode:err.exitCode,code:err.code})}throw err}}_registerOption(option){let matchingOption=option.short&&this._findOption(option.short)||option.long&&this._findOption(option.long);if(matchingOption){let matchingFlag=option.long&&this._findOption(option.long)?option.long:option.short;throw new Error(`Cannot add option '${option.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
648
- - already used by option '${matchingOption.flags}'`)}this._initOptionGroup(option),this.options.push(option)}_registerCommand(command){let knownBy=cmd=>[cmd.name()].concat(cmd.aliases()),alreadyUsed=knownBy(command).find(name=>this._findCommand(name));if(alreadyUsed){let existingCmd=knownBy(this._findCommand(alreadyUsed)).join("|"),newCmd=knownBy(command).join("|");throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`)}this._initCommandGroup(command),this.commands.push(command)}addOption(option){this._registerOption(option);let oname=option.name(),name=option.attributeName();option.defaultValue!==void 0&&this.setOptionValueWithSource(name,option.defaultValue,"default");let handleOptionValue=(val,invalidValueMessage,valueSource)=>{val==null&&option.presetArg!==void 0&&(val=option.presetArg);let oldValue=this.getOptionValue(name);val!==null&&option.parseArg?val=this._callParseArg(option,val,oldValue,invalidValueMessage):val!==null&&option.variadic&&(val=option._collectValue(val,oldValue)),val==null&&(option.negate?val=!1:option.isBoolean()||option.optional?val=!0:val=""),this.setOptionValueWithSource(name,val,valueSource)};return this.on("option:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' argument '${val}' is invalid.`;handleOptionValue(val,invalidValueMessage,"cli")}),option.envVar&&this.on("optionEnv:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;handleOptionValue(val,invalidValueMessage,"env")}),this}_optionEx(config,flags,description,fn,defaultValue){if(typeof flags=="object"&&flags instanceof Option)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let option=this.createOption(flags,description);if(option.makeOptionMandatory(!!config.mandatory),typeof fn=="function")option.default(defaultValue).argParser(fn);else if(fn instanceof RegExp){let regex=fn;fn=(val,def)=>{let m=regex.exec(val);return m?m[0]:def},option.default(defaultValue).argParser(fn)}else option.default(fn);return this.addOption(option)}option(flags,description,parseArg,defaultValue){return this._optionEx({},flags,description,parseArg,defaultValue)}requiredOption(flags,description,parseArg,defaultValue){return this._optionEx({mandatory:!0},flags,description,parseArg,defaultValue)}combineFlagAndOptionalValue(combine=!0){return this._combineFlagAndOptionalValue=!!combine,this}allowUnknownOption(allowUnknown=!0){return this._allowUnknownOption=!!allowUnknown,this}allowExcessArguments(allowExcess=!0){return this._allowExcessArguments=!!allowExcess,this}enablePositionalOptions(positional=!0){return this._enablePositionalOptions=!!positional,this}passThroughOptions(passThrough=!0){return this._passThroughOptions=!!passThrough,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(storeAsProperties=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!storeAsProperties,this}getOptionValue(key2){return this._storeOptionsAsProperties?this[key2]:this._optionValues[key2]}setOptionValue(key2,value){return this.setOptionValueWithSource(key2,value,void 0)}setOptionValueWithSource(key2,value,source){return this._storeOptionsAsProperties?this[key2]=value:this._optionValues[key2]=value,this._optionValueSources[key2]=source,this}getOptionValueSource(key2){return this._optionValueSources[key2]}getOptionValueSourceWithGlobals(key2){let source;return this._getCommandAndAncestors().forEach(cmd=>{cmd.getOptionValueSource(key2)!==void 0&&(source=cmd.getOptionValueSource(key2))}),source}_prepareUserArgs(argv,parseOptions){if(argv!==void 0&&!Array.isArray(argv))throw new Error("first parameter to parse must be array or undefined");if(parseOptions=parseOptions||{},argv===void 0&&parseOptions.from===void 0){process2.versions?.electron&&(parseOptions.from="electron");let execArgv=process2.execArgv??[];(execArgv.includes("-e")||execArgv.includes("--eval")||execArgv.includes("-p")||execArgv.includes("--print"))&&(parseOptions.from="eval")}argv===void 0&&(argv=process2.argv),this.rawArgs=argv.slice();let userArgs;switch(parseOptions.from){case void 0:case"node":this._scriptPath=argv[1],userArgs=argv.slice(2);break;case"electron":process2.defaultApp?(this._scriptPath=argv[1],userArgs=argv.slice(2)):userArgs=argv.slice(1);break;case"user":userArgs=argv.slice(0);break;case"eval":userArgs=argv.slice(1);break;default:throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",userArgs}parse(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return this._parseCommand([],userArgs),this}async parseAsync(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return await this._parseCommand([],userArgs),this}_prepareForParse(){this._savedState===null?(this.options.filter(option=>option.negate&&option.defaultValue===void 0&&this.getOptionValue(option.attributeName())===void 0).forEach(option=>{let positiveLongFlag=option.long.replace(/^--no-/,"--");this._findOption(positiveLongFlag)||this.setOptionValueWithSource(option.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
649
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(executableFile,executableDir,subcommandName){if(fs5.existsSync(executableFile))return;let executableDirMessage=executableDir?`searched for local subcommand relative to directory '${executableDir}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",executableMissing=`'${executableFile}' does not exist
630
+ (Did you mean ${similar[0]}?)`:""}exports.suggestSimilar=suggestSimilar}});var require_command=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js"(exports){var EventEmitter3=__require("node:events").EventEmitter,childProcess=__require("node:child_process"),path7=__require("node:path"),fs7=__require("node:fs"),process2=__require("node:process"),{Argument:Argument2,humanReadableArgName}=require_argument(),{CommanderError:CommanderError2}=require_error(),{Help:Help2,stripColor}=require_help(),{Option:Option2,DualOptions}=require_option(),{suggestSimilar}=require_suggestSimilar(),Command2=class _Command extends EventEmitter3{constructor(name){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=name||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:str=>process2.stdout.write(str),writeErr:str=>process2.stderr.write(str),outputError:(str,write)=>write(str),getOutHelpWidth:()=>process2.stdout.isTTY?process2.stdout.columns:void 0,getErrHelpWidth:()=>process2.stderr.isTTY?process2.stderr.columns:void 0,getOutHasColors:()=>useColor()??(process2.stdout.isTTY&&process2.stdout.hasColors?.()),getErrHasColors:()=>useColor()??(process2.stderr.isTTY&&process2.stderr.hasColors?.()),stripColor:str=>stripColor(str)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(sourceCommand){return this._outputConfiguration=sourceCommand._outputConfiguration,this._helpOption=sourceCommand._helpOption,this._helpCommand=sourceCommand._helpCommand,this._helpConfiguration=sourceCommand._helpConfiguration,this._exitCallback=sourceCommand._exitCallback,this._storeOptionsAsProperties=sourceCommand._storeOptionsAsProperties,this._combineFlagAndOptionalValue=sourceCommand._combineFlagAndOptionalValue,this._allowExcessArguments=sourceCommand._allowExcessArguments,this._enablePositionalOptions=sourceCommand._enablePositionalOptions,this._showHelpAfterError=sourceCommand._showHelpAfterError,this._showSuggestionAfterError=sourceCommand._showSuggestionAfterError,this}_getCommandAndAncestors(){let result=[];for(let command=this;command;command=command.parent)result.push(command);return result}command(nameAndArgs,actionOptsOrExecDesc,execOpts){let desc=actionOptsOrExecDesc,opts=execOpts;typeof desc=="object"&&desc!==null&&(opts=desc,desc=null),opts=opts||{};let[,name,args]=nameAndArgs.match(/([^ ]+) *(.*)/),cmd=this.createCommand(name);return desc&&(cmd.description(desc),cmd._executableHandler=!0),opts.isDefault&&(this._defaultCommandName=cmd._name),cmd._hidden=!!(opts.noHelp||opts.hidden),cmd._executableFile=opts.executableFile||null,args&&cmd.arguments(args),this._registerCommand(cmd),cmd.parent=this,cmd.copyInheritedSettings(this),desc?this:cmd}createCommand(name){return new _Command(name)}createHelp(){return Object.assign(new Help2,this.configureHelp())}configureHelp(configuration){return configuration===void 0?this._helpConfiguration:(this._helpConfiguration=configuration,this)}configureOutput(configuration){return configuration===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...configuration},this)}showHelpAfterError(displayHelp=!0){return typeof displayHelp!="string"&&(displayHelp=!!displayHelp),this._showHelpAfterError=displayHelp,this}showSuggestionAfterError(displaySuggestion=!0){return this._showSuggestionAfterError=!!displaySuggestion,this}addCommand(cmd,opts){if(!cmd._name)throw new Error(`Command passed to .addCommand() must have a name
631
+ - specify the name in Command constructor or using .name()`);return opts=opts||{},opts.isDefault&&(this._defaultCommandName=cmd._name),(opts.noHelp||opts.hidden)&&(cmd._hidden=!0),this._registerCommand(cmd),cmd.parent=this,cmd._checkForBrokenPassThrough(),this}createArgument(name,description){return new Argument2(name,description)}argument(name,description,parseArg,defaultValue){let argument=this.createArgument(name,description);return typeof parseArg=="function"?argument.default(defaultValue).argParser(parseArg):argument.default(parseArg),this.addArgument(argument),this}arguments(names){return names.trim().split(/ +/).forEach(detail=>{this.argument(detail)}),this}addArgument(argument){let previousArgument=this.registeredArguments.slice(-1)[0];if(previousArgument?.variadic)throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);if(argument.required&&argument.defaultValue!==void 0&&argument.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);return this.registeredArguments.push(argument),this}helpCommand(enableOrNameAndArgs,description){if(typeof enableOrNameAndArgs=="boolean")return this._addImplicitHelpCommand=enableOrNameAndArgs,enableOrNameAndArgs&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let nameAndArgs=enableOrNameAndArgs??"help [command]",[,helpName,helpArgs]=nameAndArgs.match(/([^ ]+) *(.*)/),helpDescription=description??"display help for command",helpCommand=this.createCommand(helpName);return helpCommand.helpOption(!1),helpArgs&&helpCommand.arguments(helpArgs),helpDescription&&helpCommand.description(helpDescription),this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,(enableOrNameAndArgs||description)&&this._initCommandGroup(helpCommand),this}addHelpCommand(helpCommand,deprecatedDescription){return typeof helpCommand!="object"?(this.helpCommand(helpCommand,deprecatedDescription),this):(this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,this._initCommandGroup(helpCommand),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(event,listener){let allowedValues=["preSubcommand","preAction","postAction"];if(!allowedValues.includes(event))throw new Error(`Unexpected value for event passed to hook : '${event}'.
632
+ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[event]?this._lifeCycleHooks[event].push(listener):this._lifeCycleHooks[event]=[listener],this}exitOverride(fn){return fn?this._exitCallback=fn:this._exitCallback=err=>{if(err.code!=="commander.executeSubCommandAsync")throw err},this}_exit(exitCode,code,message){this._exitCallback&&this._exitCallback(new CommanderError2(exitCode,code,message)),process2.exit(exitCode)}action(fn){let listener=args=>{let expectedArgsCount=this.registeredArguments.length,actionArgs=args.slice(0,expectedArgsCount);return this._storeOptionsAsProperties?actionArgs[expectedArgsCount]=this:actionArgs[expectedArgsCount]=this.opts(),actionArgs.push(this),fn.apply(this,actionArgs)};return this._actionHandler=listener,this}createOption(flags,description){return new Option2(flags,description)}_callParseArg(target,value,previous,invalidArgumentMessage){try{return target.parseArg(value,previous)}catch(err){if(err.code==="commander.invalidArgument"){let message=`${invalidArgumentMessage} ${err.message}`;this.error(message,{exitCode:err.exitCode,code:err.code})}throw err}}_registerOption(option){let matchingOption=option.short&&this._findOption(option.short)||option.long&&this._findOption(option.long);if(matchingOption){let matchingFlag=option.long&&this._findOption(option.long)?option.long:option.short;throw new Error(`Cannot add option '${option.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
633
+ - already used by option '${matchingOption.flags}'`)}this._initOptionGroup(option),this.options.push(option)}_registerCommand(command){let knownBy=cmd=>[cmd.name()].concat(cmd.aliases()),alreadyUsed=knownBy(command).find(name=>this._findCommand(name));if(alreadyUsed){let existingCmd=knownBy(this._findCommand(alreadyUsed)).join("|"),newCmd=knownBy(command).join("|");throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`)}this._initCommandGroup(command),this.commands.push(command)}addOption(option){this._registerOption(option);let oname=option.name(),name=option.attributeName();if(option.negate){let positiveLongFlag=option.long.replace(/^--no-/,"--");this._findOption(positiveLongFlag)||this.setOptionValueWithSource(name,option.defaultValue===void 0?!0:option.defaultValue,"default")}else option.defaultValue!==void 0&&this.setOptionValueWithSource(name,option.defaultValue,"default");let handleOptionValue=(val,invalidValueMessage,valueSource)=>{val==null&&option.presetArg!==void 0&&(val=option.presetArg);let oldValue=this.getOptionValue(name);val!==null&&option.parseArg?val=this._callParseArg(option,val,oldValue,invalidValueMessage):val!==null&&option.variadic&&(val=option._collectValue(val,oldValue)),val==null&&(option.negate?val=!1:option.isBoolean()||option.optional?val=!0:val=""),this.setOptionValueWithSource(name,val,valueSource)};return this.on("option:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' argument '${val}' is invalid.`;handleOptionValue(val,invalidValueMessage,"cli")}),option.envVar&&this.on("optionEnv:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;handleOptionValue(val,invalidValueMessage,"env")}),this}_optionEx(config,flags,description,fn,defaultValue){if(typeof flags=="object"&&flags instanceof Option2)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let option=this.createOption(flags,description);if(option.makeOptionMandatory(!!config.mandatory),typeof fn=="function")option.default(defaultValue).argParser(fn);else if(fn instanceof RegExp){let regex=fn;fn=(val,def)=>{let m=regex.exec(val);return m?m[0]:def},option.default(defaultValue).argParser(fn)}else option.default(fn);return this.addOption(option)}option(flags,description,parseArg,defaultValue){return this._optionEx({},flags,description,parseArg,defaultValue)}requiredOption(flags,description,parseArg,defaultValue){return this._optionEx({mandatory:!0},flags,description,parseArg,defaultValue)}combineFlagAndOptionalValue(combine=!0){return this._combineFlagAndOptionalValue=!!combine,this}allowUnknownOption(allowUnknown=!0){return this._allowUnknownOption=!!allowUnknown,this}allowExcessArguments(allowExcess=!0){return this._allowExcessArguments=!!allowExcess,this}enablePositionalOptions(positional=!0){return this._enablePositionalOptions=!!positional,this}passThroughOptions(passThrough=!0){return this._passThroughOptions=!!passThrough,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(storeAsProperties=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!storeAsProperties,this}getOptionValue(key2){return this._storeOptionsAsProperties?this[key2]:this._optionValues[key2]}setOptionValue(key2,value){return this.setOptionValueWithSource(key2,value,void 0)}setOptionValueWithSource(key2,value,source){return this._storeOptionsAsProperties?this[key2]=value:this._optionValues[key2]=value,this._optionValueSources[key2]=source,this}getOptionValueSource(key2){return this._optionValueSources[key2]}getOptionValueSourceWithGlobals(key2){let source;return this._getCommandAndAncestors().forEach(cmd=>{cmd.getOptionValueSource(key2)!==void 0&&(source=cmd.getOptionValueSource(key2))}),source}_prepareUserArgs(argv,parseOptions){if(argv!==void 0&&!Array.isArray(argv))throw new Error("first parameter to parse must be array or undefined");if(parseOptions=parseOptions||{},argv===void 0&&parseOptions.from===void 0){process2.versions?.electron&&(parseOptions.from="electron");let execArgv=process2.execArgv??[];(execArgv.includes("-e")||execArgv.includes("--eval")||execArgv.includes("-p")||execArgv.includes("--print"))&&(parseOptions.from="eval")}argv===void 0&&(argv=process2.argv),this.rawArgs=argv.slice();let userArgs;switch(parseOptions.from){case void 0:case"node":this._scriptPath=argv[1],userArgs=argv.slice(2);break;case"electron":process2.defaultApp?(this._scriptPath=argv[1],userArgs=argv.slice(2)):userArgs=argv.slice(1);break;case"user":userArgs=argv.slice(0);break;case"eval":userArgs=argv.slice(1);break;default:throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",userArgs}parse(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return this._parseCommand([],userArgs),this}async parseAsync(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return await this._parseCommand([],userArgs),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
634
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(executableFile,executableDir,subcommandName){if(fs7.existsSync(executableFile))return;let executableDirMessage=executableDir?`searched for local subcommand relative to directory '${executableDir}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",executableMissing=`'${executableFile}' does not exist
650
635
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
651
636
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
652
- - ${executableDirMessage}`;throw new Error(executableMissing)}_executeSubCommand(subcommand,args){args=args.slice();let sourceExt=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(baseDir,baseName){let localBin=path5.resolve(baseDir,baseName);if(fs5.existsSync(localBin))return localBin;if(sourceExt.includes(path5.extname(baseName)))return;let foundExt=sourceExt.find(ext=>fs5.existsSync(`${localBin}${ext}`));if(foundExt)return`${localBin}${foundExt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let executableFile=subcommand._executableFile||`${this._name}-${subcommand._name}`,executableDir=this._executableDir||"";if(this._scriptPath){let resolvedScriptPath;try{resolvedScriptPath=fs5.realpathSync(this._scriptPath)}catch{resolvedScriptPath=this._scriptPath}executableDir=path5.resolve(path5.dirname(resolvedScriptPath),executableDir)}if(executableDir){let localFile=findFile(executableDir,executableFile);if(!localFile&&!subcommand._executableFile&&this._scriptPath){let legacyName=path5.basename(this._scriptPath,path5.extname(this._scriptPath));legacyName!==this._name&&(localFile=findFile(executableDir,`${legacyName}-${subcommand._name}`))}executableFile=localFile||executableFile}let launchWithNode=sourceExt.includes(path5.extname(executableFile)),proc;process2.platform!=="win32"?launchWithNode?(args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.argv[0],args,{stdio:"inherit"})):proc=childProcess.spawn(executableFile,args,{stdio:"inherit"}):(this._checkForMissingExecutable(executableFile,executableDir,subcommand._name),args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.execPath,args,{stdio:"inherit"})),proc.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(signal=>{process2.on(signal,()=>{proc.killed===!1&&proc.exitCode===null&&proc.kill(signal)})});let exitCallback=this._exitCallback;proc.on("close",code=>{code=code??1,exitCallback?exitCallback(new CommanderError(code,"commander.executeSubCommandAsync","(close)")):process2.exit(code)}),proc.on("error",err=>{if(err.code==="ENOENT")this._checkForMissingExecutable(executableFile,executableDir,subcommand._name);else if(err.code==="EACCES")throw new Error(`'${executableFile}' not executable`);if(!exitCallback)process2.exit(1);else{let wrappedError=new CommanderError(1,"commander.executeSubCommandAsync","(error)");wrappedError.nestedError=err,exitCallback(wrappedError)}}),this.runningCommand=proc}_dispatchSubcommand(commandName,operands,unknown){let subCommand=this._findCommand(commandName);subCommand||this.help({error:!0}),subCommand._prepareForParse();let promiseChain;return promiseChain=this._chainOrCallSubCommandHook(promiseChain,subCommand,"preSubcommand"),promiseChain=this._chainOrCall(promiseChain,()=>{if(subCommand._executableHandler)this._executeSubCommand(subCommand,operands.concat(unknown));else return subCommand._parseCommand(operands,unknown)}),promiseChain}_dispatchHelpCommand(subcommandName){subcommandName||this.help();let subCommand=this._findCommand(subcommandName);return subCommand&&!subCommand._executableHandler&&subCommand.help(),this._dispatchSubcommand(subcommandName,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((arg,i2)=>{arg.required&&this.args[i2]==null&&this.missingArgument(arg.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let myParseArg=(argument,value,previous)=>{let parsedValue=value;if(value!==null&&argument.parseArg){let invalidValueMessage=`error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;parsedValue=this._callParseArg(argument,value,previous,invalidValueMessage)}return parsedValue};this._checkNumberOfArguments();let processedArgs=[];this.registeredArguments.forEach((declaredArg,index)=>{let value=declaredArg.defaultValue;declaredArg.variadic?index<this.args.length?(value=this.args.slice(index),declaredArg.parseArg&&(value=value.reduce((processed,v)=>myParseArg(declaredArg,v,processed),declaredArg.defaultValue))):value===void 0&&(value=[]):index<this.args.length&&(value=this.args[index],declaredArg.parseArg&&(value=myParseArg(declaredArg,value,declaredArg.defaultValue))),processedArgs[index]=value}),this.processedArgs=processedArgs}_chainOrCall(promise,fn){return promise?.then&&typeof promise.then=="function"?promise.then(()=>fn()):fn()}_chainOrCallHooks(promise,event){let result=promise,hooks=[];return this._getCommandAndAncestors().reverse().filter(cmd=>cmd._lifeCycleHooks[event]!==void 0).forEach(hookedCommand=>{hookedCommand._lifeCycleHooks[event].forEach(callback=>{hooks.push({hookedCommand,callback})})}),event==="postAction"&&hooks.reverse(),hooks.forEach(hookDetail=>{result=this._chainOrCall(result,()=>hookDetail.callback(hookDetail.hookedCommand,this))}),result}_chainOrCallSubCommandHook(promise,subCommand,event){let result=promise;return this._lifeCycleHooks[event]!==void 0&&this._lifeCycleHooks[event].forEach(hook=>{result=this._chainOrCall(result,()=>hook(this,subCommand))}),result}_parseCommand(operands,unknown){let parsed=this.parseOptions(unknown);if(this._parseOptionsEnv(),this._parseOptionsImplied(),operands=operands.concat(parsed.operands),unknown=parsed.unknown,this.args=operands.concat(unknown),operands&&this._findCommand(operands[0]))return this._dispatchSubcommand(operands[0],operands.slice(1),unknown);if(this._getHelpCommand()&&operands[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(operands[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(unknown),this._dispatchSubcommand(this._defaultCommandName,operands,unknown);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(parsed.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let checkForUnknownOptions=()=>{parsed.unknown.length>0&&this.unknownOption(parsed.unknown[0])},commandEvent=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions(),this._processArguments();let promiseChain;return promiseChain=this._chainOrCallHooks(promiseChain,"preAction"),promiseChain=this._chainOrCall(promiseChain,()=>this._actionHandler(this.processedArgs)),this.parent&&(promiseChain=this._chainOrCall(promiseChain,()=>{this.parent.emit(commandEvent,operands,unknown)})),promiseChain=this._chainOrCallHooks(promiseChain,"postAction"),promiseChain}if(this.parent?.listenerCount(commandEvent))checkForUnknownOptions(),this._processArguments(),this.parent.emit(commandEvent,operands,unknown);else if(operands.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",operands,unknown);this.listenerCount("command:*")?this.emit("command:*",operands,unknown):this.commands.length?this.unknownCommand():(checkForUnknownOptions(),this._processArguments())}else this.commands.length?(checkForUnknownOptions(),this.help({error:!0})):(checkForUnknownOptions(),this._processArguments())}_findCommand(name){if(name)return this.commands.find(cmd=>cmd._name===name||cmd._aliases.includes(name))}_findOption(arg){return this.options.find(option=>option.is(arg))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd.options.forEach(anOption=>{anOption.mandatory&&cmd.getOptionValue(anOption.attributeName())===void 0&&cmd.missingMandatoryOptionValue(anOption)})})}_checkForConflictingLocalOptions(){let definedNonDefaultOptions=this.options.filter(option=>{let optionKey=option.attributeName();return this.getOptionValue(optionKey)===void 0?!1:this.getOptionValueSource(optionKey)!=="default"});definedNonDefaultOptions.filter(option=>option.conflictsWith.length>0).forEach(option=>{let conflictingAndDefined=definedNonDefaultOptions.find(defined=>option.conflictsWith.includes(defined.attributeName()));conflictingAndDefined&&this._conflictingOption(option,conflictingAndDefined)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd._checkForConflictingLocalOptions()})}parseOptions(args){let operands=[],unknown=[],dest=operands;function maybeOption(arg){return arg.length>1&&arg[0]==="-"}let negativeNumberArg=arg=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)?!this._getCommandAndAncestors().some(cmd=>cmd.options.map(opt=>opt.short).some(short=>/^-\d$/.test(short))):!1,activeVariadicOption=null,activeGroup=null,i2=0;for(;i2<args.length||activeGroup;){let arg=activeGroup??args[i2++];if(activeGroup=null,arg==="--"){dest===unknown&&dest.push(arg),dest.push(...args.slice(i2));break}if(activeVariadicOption&&(!maybeOption(arg)||negativeNumberArg(arg))){this.emit(`option:${activeVariadicOption.name()}`,arg);continue}if(activeVariadicOption=null,maybeOption(arg)){let option=this._findOption(arg);if(option){if(option.required){let value=args[i2++];value===void 0&&this.optionMissingArgument(option),this.emit(`option:${option.name()}`,value)}else if(option.optional){let value=null;i2<args.length&&(!maybeOption(args[i2])||negativeNumberArg(args[i2]))&&(value=args[i2++]),this.emit(`option:${option.name()}`,value)}else this.emit(`option:${option.name()}`);activeVariadicOption=option.variadic?option:null;continue}}if(arg.length>2&&arg[0]==="-"&&arg[1]!=="-"){let option=this._findOption(`-${arg[1]}`);if(option){option.required||option.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${option.name()}`,arg.slice(2)):(this.emit(`option:${option.name()}`),activeGroup=`-${arg.slice(2)}`);continue}}if(/^--[^=]+=/.test(arg)){let index=arg.indexOf("="),option=this._findOption(arg.slice(0,index));if(option&&(option.required||option.optional)){this.emit(`option:${option.name()}`,arg.slice(index+1));continue}}if(dest===operands&&maybeOption(arg)&&!(this.commands.length===0&&negativeNumberArg(arg))&&(dest=unknown),(this._enablePositionalOptions||this._passThroughOptions)&&operands.length===0&&unknown.length===0){if(this._findCommand(arg)){operands.push(arg),unknown.push(...args.slice(i2));break}else if(this._getHelpCommand()&&arg===this._getHelpCommand().name()){operands.push(arg,...args.slice(i2));break}else if(this._defaultCommandName){unknown.push(arg,...args.slice(i2));break}}if(this._passThroughOptions){dest.push(arg,...args.slice(i2));break}dest.push(arg)}return{operands,unknown}}opts(){if(this._storeOptionsAsProperties){let result={},len=this.options.length;for(let i2=0;i2<len;i2++){let key2=this.options[i2].attributeName();result[key2]=key2===this._versionOptionName?this._version:this[key2]}return result}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((combinedOptions,cmd)=>Object.assign(combinedOptions,cmd.opts()),{})}error(message,errorOptions){this._outputConfiguration.outputError(`${message}
637
+ - ${executableDirMessage}`;throw new Error(executableMissing)}_executeSubCommand(subcommand,args){args=args.slice();let launchWithNode=!1,sourceExt=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(baseDir,baseName){let localBin=path7.resolve(baseDir,baseName);if(fs7.existsSync(localBin))return localBin;if(sourceExt.includes(path7.extname(baseName)))return;let foundExt=sourceExt.find(ext=>fs7.existsSync(`${localBin}${ext}`));if(foundExt)return`${localBin}${foundExt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let executableFile=subcommand._executableFile||`${this._name}-${subcommand._name}`,executableDir=this._executableDir||"";if(this._scriptPath){let resolvedScriptPath;try{resolvedScriptPath=fs7.realpathSync(this._scriptPath)}catch{resolvedScriptPath=this._scriptPath}executableDir=path7.resolve(path7.dirname(resolvedScriptPath),executableDir)}if(executableDir){let localFile=findFile(executableDir,executableFile);if(!localFile&&!subcommand._executableFile&&this._scriptPath){let legacyName=path7.basename(this._scriptPath,path7.extname(this._scriptPath));legacyName!==this._name&&(localFile=findFile(executableDir,`${legacyName}-${subcommand._name}`))}executableFile=localFile||executableFile}launchWithNode=sourceExt.includes(path7.extname(executableFile));let proc;process2.platform!=="win32"?launchWithNode?(args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.argv[0],args,{stdio:"inherit"})):proc=childProcess.spawn(executableFile,args,{stdio:"inherit"}):(this._checkForMissingExecutable(executableFile,executableDir,subcommand._name),args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.execPath,args,{stdio:"inherit"})),proc.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(signal=>{process2.on(signal,()=>{proc.killed===!1&&proc.exitCode===null&&proc.kill(signal)})});let exitCallback=this._exitCallback;proc.on("close",code=>{code=code??1,exitCallback?exitCallback(new CommanderError2(code,"commander.executeSubCommandAsync","(close)")):process2.exit(code)}),proc.on("error",err=>{if(err.code==="ENOENT")this._checkForMissingExecutable(executableFile,executableDir,subcommand._name);else if(err.code==="EACCES")throw new Error(`'${executableFile}' not executable`);if(!exitCallback)process2.exit(1);else{let wrappedError=new CommanderError2(1,"commander.executeSubCommandAsync","(error)");wrappedError.nestedError=err,exitCallback(wrappedError)}}),this.runningCommand=proc}_dispatchSubcommand(commandName,operands,unknown){let subCommand=this._findCommand(commandName);subCommand||this.help({error:!0}),subCommand._prepareForParse();let promiseChain;return promiseChain=this._chainOrCallSubCommandHook(promiseChain,subCommand,"preSubcommand"),promiseChain=this._chainOrCall(promiseChain,()=>{if(subCommand._executableHandler)this._executeSubCommand(subCommand,operands.concat(unknown));else return subCommand._parseCommand(operands,unknown)}),promiseChain}_dispatchHelpCommand(subcommandName){subcommandName||this.help();let subCommand=this._findCommand(subcommandName);return subCommand&&!subCommand._executableHandler&&subCommand.help(),this._dispatchSubcommand(subcommandName,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((arg,i)=>{arg.required&&this.args[i]==null&&this.missingArgument(arg.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let myParseArg=(argument,value,previous)=>{let parsedValue=value;if(value!==null&&argument.parseArg){let invalidValueMessage=`error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;parsedValue=this._callParseArg(argument,value,previous,invalidValueMessage)}return parsedValue};this._checkNumberOfArguments();let processedArgs=[];this.registeredArguments.forEach((declaredArg,index)=>{let value=declaredArg.defaultValue;declaredArg.variadic?index<this.args.length?(value=this.args.slice(index),declaredArg.parseArg&&(value=value.reduce((processed,v)=>myParseArg(declaredArg,v,processed),declaredArg.defaultValue))):value===void 0&&(value=[]):index<this.args.length&&(value=this.args[index],declaredArg.parseArg&&(value=myParseArg(declaredArg,value,declaredArg.defaultValue))),processedArgs[index]=value}),this.processedArgs=processedArgs}_chainOrCall(promise,fn){return promise?.then&&typeof promise.then=="function"?promise.then(()=>fn()):fn()}_chainOrCallHooks(promise,event){let result=promise,hooks=[];return this._getCommandAndAncestors().reverse().filter(cmd=>cmd._lifeCycleHooks[event]!==void 0).forEach(hookedCommand=>{hookedCommand._lifeCycleHooks[event].forEach(callback=>{hooks.push({hookedCommand,callback})})}),event==="postAction"&&hooks.reverse(),hooks.forEach(hookDetail=>{result=this._chainOrCall(result,()=>hookDetail.callback(hookDetail.hookedCommand,this))}),result}_chainOrCallSubCommandHook(promise,subCommand,event){let result=promise;return this._lifeCycleHooks[event]!==void 0&&this._lifeCycleHooks[event].forEach(hook=>{result=this._chainOrCall(result,()=>hook(this,subCommand))}),result}_parseCommand(operands,unknown){let parsed=this.parseOptions(unknown);if(this._parseOptionsEnv(),this._parseOptionsImplied(),operands=operands.concat(parsed.operands),unknown=parsed.unknown,this.args=operands.concat(unknown),operands&&this._findCommand(operands[0]))return this._dispatchSubcommand(operands[0],operands.slice(1),unknown);if(this._getHelpCommand()&&operands[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(operands[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(unknown),this._dispatchSubcommand(this._defaultCommandName,operands,unknown);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(parsed.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let checkForUnknownOptions=()=>{parsed.unknown.length>0&&this.unknownOption(parsed.unknown[0])},commandEvent=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions(),this._processArguments();let promiseChain;return promiseChain=this._chainOrCallHooks(promiseChain,"preAction"),promiseChain=this._chainOrCall(promiseChain,()=>this._actionHandler(this.processedArgs)),this.parent&&(promiseChain=this._chainOrCall(promiseChain,()=>{this.parent.emit(commandEvent,operands,unknown)})),promiseChain=this._chainOrCallHooks(promiseChain,"postAction"),promiseChain}if(this.parent?.listenerCount(commandEvent))checkForUnknownOptions(),this._processArguments(),this.parent.emit(commandEvent,operands,unknown);else if(operands.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",operands,unknown);this.listenerCount("command:*")?this.emit("command:*",operands,unknown):this.commands.length?this.unknownCommand():(checkForUnknownOptions(),this._processArguments())}else this.commands.length?(checkForUnknownOptions(),this.help({error:!0})):(checkForUnknownOptions(),this._processArguments())}_findCommand(name){if(name)return this.commands.find(cmd=>cmd._name===name||cmd._aliases.includes(name))}_findOption(arg){return this.options.find(option=>option.is(arg))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd.options.forEach(anOption=>{anOption.mandatory&&cmd.getOptionValue(anOption.attributeName())===void 0&&cmd.missingMandatoryOptionValue(anOption)})})}_checkForConflictingLocalOptions(){let definedNonDefaultOptions=this.options.filter(option=>{let optionKey=option.attributeName();return this.getOptionValue(optionKey)===void 0?!1:this.getOptionValueSource(optionKey)!=="default"});definedNonDefaultOptions.filter(option=>option.conflictsWith.length>0).forEach(option=>{let conflictingAndDefined=definedNonDefaultOptions.find(defined=>option.conflictsWith.includes(defined.attributeName()));conflictingAndDefined&&this._conflictingOption(option,conflictingAndDefined)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd._checkForConflictingLocalOptions()})}parseOptions(args){let operands=[],unknown=[],dest=operands;function maybeOption(arg){return arg.length>1&&arg[0]==="-"}let negativeNumberArg=arg=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)?!this._getCommandAndAncestors().some(cmd=>cmd.options.map(opt=>opt.short).some(short=>/^-\d$/.test(short))):!1,activeVariadicOption=null,activeGroup=null,i=0;for(;i<args.length||activeGroup;){let arg=activeGroup??args[i++];if(activeGroup=null,arg==="--"){dest===unknown&&dest.push(arg),dest.push(...args.slice(i));break}if(activeVariadicOption&&(!maybeOption(arg)||negativeNumberArg(arg))){this.emit(`option:${activeVariadicOption.name()}`,arg);continue}if(activeVariadicOption=null,maybeOption(arg)){let option=this._findOption(arg);if(option){if(option.required){let value=args[i++];value===void 0&&this.optionMissingArgument(option),this.emit(`option:${option.name()}`,value)}else if(option.optional){let value=null;i<args.length&&(!maybeOption(args[i])||negativeNumberArg(args[i]))&&(value=args[i++]),this.emit(`option:${option.name()}`,value)}else this.emit(`option:${option.name()}`);activeVariadicOption=option.variadic?option:null;continue}}if(arg.length>2&&arg[0]==="-"&&arg[1]!=="-"){let option=this._findOption(`-${arg[1]}`);if(option){option.required||option.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${option.name()}`,arg.slice(2)):(this.emit(`option:${option.name()}`),activeGroup=`-${arg.slice(2)}`);continue}}if(/^--[^=]+=/.test(arg)){let index=arg.indexOf("="),option=this._findOption(arg.slice(0,index));if(option&&(option.required||option.optional)){this.emit(`option:${option.name()}`,arg.slice(index+1));continue}}if(dest===operands&&maybeOption(arg)&&!(this.commands.length===0&&negativeNumberArg(arg))&&(dest=unknown),(this._enablePositionalOptions||this._passThroughOptions)&&operands.length===0&&unknown.length===0){if(this._findCommand(arg)){operands.push(arg),unknown.push(...args.slice(i));break}else if(this._getHelpCommand()&&arg===this._getHelpCommand().name()){operands.push(arg,...args.slice(i));break}else if(this._defaultCommandName){unknown.push(arg,...args.slice(i));break}}if(this._passThroughOptions){dest.push(arg,...args.slice(i));break}dest.push(arg)}return{operands,unknown}}opts(){if(this._storeOptionsAsProperties){let result={},len=this.options.length;for(let i=0;i<len;i++){let key2=this.options[i].attributeName();result[key2]=key2===this._versionOptionName?this._version:this[key2]}return result}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((combinedOptions,cmd)=>Object.assign(combinedOptions,cmd.opts()),{})}error(message,errorOptions){this._outputConfiguration.outputError(`${message}
653
638
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
654
639
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
655
- `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code=config.code||"commander.error";this._exit(exitCode,code,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process2.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process2.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey));this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},getErrorMessage=option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion="";if(flag.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}let message=`error: unknown option '${flag}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",received=receivedArgs.length,forSubcommand=this.parent?` for '${this.name()}'`:"",details=receivedArgs.join(", "),message=`error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
656
- `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}helpGroup(heading){return heading===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=heading,this)}commandsGroup(heading){return heading===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=heading,this)}optionsGroup(heading){return heading===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=heading,this)}_initOptionGroup(option){this._defaultOptionGroup&&!option.helpGroupHeading&&option.helpGroup(this._defaultOptionGroup)}_initCommandGroup(cmd){this._defaultCommandGroup&&!cmd.helpGroup()&&cmd.helpGroup(this._defaultCommandGroup)}nameFromFilename(filename){return this._name=path5.basename(filename,path5.extname(filename)),this}executableDir(path8){return path8===void 0?this._executableDir:(this._executableDir=path8,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error2=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error2?(baseWrite=str=>this._outputConfiguration.writeErr(str),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=str=>this._outputConfiguration.writeOut(str),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error:error2,write:str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(flags??"-h, --help",description??"display help for command"),(flags||description)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this._initOptionGroup(option),this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process2.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
640
+ `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code=config.code||"commander.error";this._exit(exitCode,code,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process2.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process2.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey));this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},getErrorMessage=option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion="";if(flag.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}let message=`error: unknown option '${flag}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
641
+ `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}helpGroup(heading){return heading===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=heading,this)}commandsGroup(heading){return heading===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=heading,this)}optionsGroup(heading){return heading===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=heading,this)}_initOptionGroup(option){this._defaultOptionGroup&&!option.helpGroupHeading&&option.helpGroup(this._defaultOptionGroup)}_initCommandGroup(cmd){this._defaultCommandGroup&&!cmd.helpGroup()&&cmd.helpGroup(this._defaultCommandGroup)}nameFromFilename(filename){return this._name=path7.basename(filename,path7.extname(filename)),this}executableDir(path8){return path8===void 0?this._executableDir:(this._executableDir=path8,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error2=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error2?(baseWrite=str=>this._outputConfiguration.writeErr(str),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=str=>this._outputConfiguration.writeOut(str),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error:error2,write:str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(flags??"-h, --help",description??"display help for command"),(flags||description)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this._initOptionGroup(option),this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process2.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
657
642
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
658
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}}});var program,init_commander=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js"(){init_argument();init_command2();init_error();init_help();init_option();program=new Command}});import{constants,closeSync as closeSync7,fstatSync,lstatSync as lstatSync2,mkdirSync as mkdirSync7,openSync as openSync7,readSync as readSync3,readFileSync as readFileSync13,renameSync as renameSync8,rmSync as rmSync10,writeFileSync as writeFileSync7}from"node:fs";import{createHash as createHash8,randomUUID as randomUUID9}from"node:crypto";import{isAbsolute as isAbsolute6,join as join15}from"node:path";function validateOfficialPluginCatalog(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid managed plugin catalog");let input=value;if(input.schemaVersion!==1||typeof input.revision!="string"||!/^[a-f0-9]{64}$/.test(input.revision)||!input.plugins||typeof input.plugins!="object"||Array.isArray(input.plugins)||Object.keys(input).some(key2=>!["schemaVersion","revision","plugins","selection"].includes(key2))||Object.keys(input.plugins).length>200)throw new Error("Invalid managed plugin catalog");let selection=input.selection;if(selection!==void 0&&(!selection||typeof selection!="object"||Array.isArray(selection)||Object.keys(selection).some(key2=>!["path","sha256"].includes(key2))||typeof selection.path!="string"||!isAbsolute6(selection.path)||selection.path.length>4096||/[\0\r\n]/.test(selection.path)||typeof selection.sha256!="string"||!/^[a-f0-9]{64}$/.test(selection.sha256)))throw new Error("Invalid plugin catalog selection");let plugins={};for(let[name,value2]of Object.entries(input.plugins)){if(assertPluginName(name),!value2||typeof value2!="object"||Array.isArray(value2))throw new Error("Invalid managed plugin declaration");let item=value2;if(Object.keys(item).some(key2=>!["description","installArgs","setup","skill"].includes(key2))||typeof item.description!="string"||item.description.length>1e3||typeof item.skill!="string"||!/^[a-z][a-z0-9-]*$/.test(item.skill)||!Array.isArray(item.installArgs)||item.installArgs.length===0||item.installArgs.length>32||item.installArgs.some(arg=>typeof arg!="string"||arg.length>2048||/[\0\r\n]/.test(arg))||item.setup!==void 0&&(typeof item.setup!="string"||!/^[a-z][a-z0-9-]*$/.test(item.setup)))throw new Error("Invalid managed plugin declaration");plugins[name]={description:item.description,skill:item.skill,installArgs:[...item.installArgs],...item.setup!==void 0&&{setup:item.setup}}}let catalog={schemaVersion:1,revision:input.revision,plugins,...selection?{selection:{path:selection.path,sha256:selection.sha256}}:{}};if(Buffer.byteLength(JSON.stringify(catalog))>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");return catalog}function selectionMatches(selection){try{let before=lstatSync2(selection.path);if(!before.isFile()||before.isSymbolicLink()||before.size>1024*1024)return!1;let fd=openSync7(selection.path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat2=fstatSync(fd);if(!stat2.isFile()||stat2.size>1024*1024)return!1;let bytes=Buffer.alloc(stat2.size+1),size=0;for(;size<bytes.length;){let count=readSync3(fd,bytes,size,bytes.length-size,null);if(!count)break;size+=count}return size===stat2.size&&createHash8("sha256").update(bytes.subarray(0,size)).digest("hex")===selection.sha256}finally{closeSync7(fd)}}catch(error2){if(error2.code==="ENOENT")return!1;throw error2}}function readOfficialPluginCatalog(){let source;try{source=readFileSync13(catalogPath(),"utf8")}catch(error2){if(error2.code==="ENOENT")return;throw error2}if(Buffer.byteLength(source)>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");let catalog=validateOfficialPluginCatalog(JSON.parse(source));return catalog.selection&&!selectionMatches(catalog.selection)?void 0:catalog}function replaceOfficialPluginCatalog(revision,plugins,selection){let catalog=validateOfficialPluginCatalog({schemaVersion:1,revision,plugins,...selection?{selection}:{}}),content=JSON.stringify(catalog);if(Buffer.byteLength(content)>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");if(catalog.selection&&!selectionMatches(catalog.selection))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");mkdirSync7(pluginDirectory(),{recursive:!0,mode:448});let file=catalogPath(),temporary=`${file}.${randomUUID9()}.tmp`;try{if(writeFileSync7(temporary,content,{mode:384,flag:"wx"}),catalog.selection&&!selectionMatches(catalog.selection))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");renameSync8(temporary,file)}finally{rmSync10(temporary,{force:!0})}refreshOfficialPlugins()}function refreshOfficialPlugins(){let plugins={};try{plugins=readOfficialPluginCatalog()?.plugins??{}}catch{}for(let name of Object.keys(OFFICIAL_PLUGINS))delete OFFICIAL_PLUGINS[name];return Object.assign(OFFICIAL_PLUGINS,plugins),OFFICIAL_PLUGINS}function findOfficialPlugin(name){let plugins=refreshOfficialPlugins();return Object.hasOwn(plugins,name)?plugins[name]:void 0}function listOfficialPluginNames(setup){return Object.entries(refreshOfficialPlugins()).filter(([,item])=>setup===void 0||item.setup===setup).map(([name])=>name)}var OFFICIAL_PLUGIN_MANAGER,OFFICIAL_PLUGINS,MAX_CATALOG_BYTES,catalogPath,init_officialPluginCatalog=__esm({"../client/src/plugins/officialPluginCatalog.ts"(){"use strict";init_pluginRegistry();OFFICIAL_PLUGIN_MANAGER="@mearl/setup:official",OFFICIAL_PLUGINS={},MAX_CATALOG_BYTES=256*1024,catalogPath=()=>join15(pluginDirectory(),".official-catalog.json");refreshOfficialPlugins()}});import{closeSync as closeSync8,mkdirSync as mkdirSync8,openSync as openSync8,rmSync as rmSync11,statSync as statSync9,writeFileSync as writeFileSync8}from"node:fs";import{join as join16}from"node:path";import{spawn as spawn5}from"node:child_process";function delay(milliseconds){return new Promise(resolve7=>setTimeout(resolve7,milliseconds))}function installLockPath(name){return join16(pluginDirectory(),`.official-${name}.install.lock`)}async function acquireInstallLock(name){let directory=pluginDirectory();mkdirSync8(directory,{recursive:!0,mode:448});let lockPath=installLockPath(name),deadline=Date.now()+INSTALL_TIMEOUT_MS;for(;;){let descriptor;try{return descriptor=openSync8(lockPath,"wx",384),writeFileSync8(descriptor,`${process.pid}
659
- `),closeSync8(descriptor),()=>rmSync11(lockPath,{force:!0})}catch(error2){if(descriptor!==void 0&&closeSync8(descriptor),error2.code!=="EEXIST")throw error2}if(findPluginRegistration(name))return()=>{};try{if(Date.now()-statSync9(lockPath).mtimeMs>INSTALL_LOCK_STALE_MS){rmSync11(lockPath,{force:!0});continue}}catch(error2){if(error2.code==="ENOENT")continue;throw error2}if(Date.now()>=deadline)throw new Error(`等待安装官方插件 ${name} 超时`);await delay(250)}}function appendOutput(current2,chunk){return current2.length>=MAX_INSTALL_OUTPUT?current2:(current2+chunk.toString("utf8")).slice(0,MAX_INSTALL_OUTPUT)}function installWithSetup(name){return new Promise((resolve7,reject)=>{let command=process.platform==="win32"?"npx.cmd":"npx",child=spawn5(command,["-y",`@mearl/setup@${CLIENT_VERSION}`,"plugin","ensure",name],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),stdout="",stderr="",settled=!1,finish=error2=>{settled||(settled=!0,clearTimeout(timer),error2?reject(error2):resolve7())},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(new Error(`安装官方插件 ${name} 超时`))},INSTALL_TIMEOUT_MS);child.stdout.on("data",chunk=>stdout=appendOutput(stdout,chunk)),child.stderr.on("data",chunk=>stderr=appendOutput(stderr,chunk)),child.once("error",error2=>finish(error2)),child.once("exit",code=>{if(code===0){finish();return}let detail=(stderr||stdout).replace(/[\r\n]+/g," ").trim().slice(-1e3);finish(new Error(detail?`安装官方插件 ${name} 失败 (exit ${code}): ${detail}`:`安装官方插件 ${name} 失败 (exit ${code})`))})})}async function installOfficialPlugin(name,progress){if(findPluginRegistration(name))return;if(!findOfficialPlugin(name))throw new Error(`未知官方插件: ${name}`);let releaseLock=await acquireInstallLock(name);try{if(findPluginRegistration(name))return;let accepted=JSON.stringify(readOfficialPluginCatalog());if(!findOfficialPlugin(name))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");if(progress?.(`正在安装官方插件 ${name}...`),await installWithSetup(name),JSON.stringify(readOfficialPluginCatalog())!==accepted)throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");if(!findPluginRegistration(name))throw new Error(`官方插件 ${name} 安装完成后仍未注册`);progress?.(`官方插件 ${name} 已安装。`)}finally{releaseLock()}}var INSTALL_TIMEOUT_MS,INSTALL_LOCK_STALE_MS,MAX_INSTALL_OUTPUT,activeInstallations,ensureOfficialPluginRegistered,init_officialPluginInstaller=__esm({"../client/src/plugins/officialPluginInstaller.ts"(){"use strict";init_runtimePaths();init_officialPluginCatalog();init_pluginRegistry();INSTALL_TIMEOUT_MS=18e4,INSTALL_LOCK_STALE_MS=5*6e4,MAX_INSTALL_OUTPUT=1024*1024,activeInstallations=new Map;ensureOfficialPluginRegistered=(name,progress)=>{let active=activeInstallations.get(name);if(active)return active;let installation=installOfficialPlugin(name,progress).finally(()=>{activeInstallations.delete(name)});return activeInstallations.set(name,installation),installation}}});import{spawn as spawn6}from"node:child_process";import{createInterface}from"node:readline";function pythonExecutable(){return process.env.MEARL_PYTHON?.trim()||"python3"}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseDescriptor(message){if(!Array.isArray(message.commands))throw new Error("Python 插件未返回命令列表");let commands=message.commands.map(value=>{if(!isObject(value)||typeof value.signature!="string"||typeof value.description!="string"||typeof value.toolboxOnly!="boolean"||typeof value.runtimeOnly!="boolean")throw new Error("Python 插件返回了无效的命令描述");return{signature:value.signature,description:value.description,toolboxOnly:value.toolboxOnly,runtimeOnly:value.runtimeOnly,recoveryOnly:value.recoveryOnly===!0,migrationOnly:value.migrationOnly===!0}});if(message.name!==void 0&&typeof message.name!="string")throw new Error("Python 插件返回了无效的 name");if(message.description!==void 0&&typeof message.description!="string")throw new Error("Python 插件返回了无效的 description");return{commands,...typeof message.name=="string"?{name:message.name}:{},...typeof message.description=="string"?{description:message.description}:{},...message.toolbox!==void 0?{toolbox:message.toolbox}:{},...message.pageRuntime!==void 0?{pageRuntime:message.pageRuntime}:{},...message.stateStorage!==void 0?{stateStorage:message.stateStorage}:{},...message.taskRecovery!==void 0?{taskRecovery:message.taskRecovery}:{},...message.appProfiles!==void 0?{appProfiles:message.appProfiles}:{}}}function bridgedError(message){let detail=typeof message.message=="string"?message.message:"Python 插件执行失败",restored=pluginExecutionError({message:detail,...typeof message.code=="string"?{code:message.code}:{},...isObject(message.details)?{details:message.details}:{},...isObject(message.metadata)?{metadata:message.metadata}:{}});return typeof message.code=="string"&&/^PLUGIN_[A-Z0-9_]+$/.test(message.code)?Object.assign(new PluginError(message.code,detail),restored):restored}function errorResponse(error2){let serialized=serializePluginExecutionError(error2);if(error2 instanceof PluginError){let prefix=`${error2.code}: `;return{...serialized,code:error2.code,message:error2.message.startsWith(prefix)?error2.message.slice(prefix.length):error2.message}}return serialized}async function runPythonWorker(entry,initial,app,signal,expectedDescriptor){return new Promise((resolve7,reject)=>{let executable=pythonExecutable(),child=spawn6(executable,["-u","-c",PYTHON_BOOTSTRAP,entry],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),lines=createInterface({input:child.stdout}),descriptor,outcome,protocolError,stderr="",failProtocol=error2=>{protocolError||(protocolError=error2 instanceof Error?error2:new Error(String(error2)),cancel())},write=message=>{try{child.stdin.write(`${JSON.stringify(message)}
643
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process2.env.NO_COLOR||process2.env.FORCE_COLOR==="0"||process2.env.FORCE_COLOR==="false")return!1;if(process2.env.FORCE_COLOR||process2.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=Command2;exports.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js"(exports){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports.program=new Command2;exports.createCommand=name=>new Command2(name);exports.createOption=(flags,description)=>new Option2(flags,description);exports.createArgument=(name,description)=>new Argument2(name,description);exports.Command=Command2;exports.Option=Option2;exports.Argument=Argument2;exports.Help=Help2;exports.CommanderError=CommanderError2;exports.InvalidArgumentError=InvalidArgumentError2;exports.InvalidOptionArgumentError=InvalidArgumentError2}});var import_index,program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help,init_esm=__esm({"../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs"(){import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default}});import{constants,closeSync as closeSync7,fstatSync,lstatSync as lstatSync2,mkdirSync as mkdirSync7,openSync as openSync7,readSync as readSync3,readFileSync as readFileSync13,renameSync as renameSync8,rmSync as rmSync10,writeFileSync as writeFileSync7}from"node:fs";import{createHash as createHash8,randomUUID as randomUUID10}from"node:crypto";import{isAbsolute as isAbsolute6,join as join15}from"node:path";function validateOfficialPluginCatalog(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid managed plugin catalog");let input=value;if(input.schemaVersion!==1||typeof input.revision!="string"||!/^[a-f0-9]{64}$/.test(input.revision)||!input.plugins||typeof input.plugins!="object"||Array.isArray(input.plugins)||Object.keys(input).some(key2=>!["schemaVersion","revision","plugins","selection"].includes(key2))||Object.keys(input.plugins).length>200)throw new Error("Invalid managed plugin catalog");let selection=input.selection;if(selection!==void 0&&(!selection||typeof selection!="object"||Array.isArray(selection)||Object.keys(selection).some(key2=>!["path","sha256"].includes(key2))||typeof selection.path!="string"||!isAbsolute6(selection.path)||selection.path.length>4096||/[\0\r\n]/.test(selection.path)||typeof selection.sha256!="string"||!/^[a-f0-9]{64}$/.test(selection.sha256)))throw new Error("Invalid plugin catalog selection");let plugins={};for(let[name,value2]of Object.entries(input.plugins)){if(assertPluginName(name),!value2||typeof value2!="object"||Array.isArray(value2))throw new Error("Invalid managed plugin declaration");let item=value2;if(Object.keys(item).some(key2=>!["description","installArgs","setup","skill"].includes(key2))||typeof item.description!="string"||item.description.length>1e3||typeof item.skill!="string"||!/^[a-z][a-z0-9-]*$/.test(item.skill)||!Array.isArray(item.installArgs)||item.installArgs.length===0||item.installArgs.length>32||item.installArgs.some(arg=>typeof arg!="string"||arg.length>2048||/[\0\r\n]/.test(arg))||item.setup!==void 0&&(typeof item.setup!="string"||!/^[a-z][a-z0-9-]*$/.test(item.setup)))throw new Error("Invalid managed plugin declaration");plugins[name]={description:item.description,skill:item.skill,installArgs:[...item.installArgs],...item.setup!==void 0&&{setup:item.setup}}}let catalog={schemaVersion:1,revision:input.revision,plugins,...selection?{selection:{path:selection.path,sha256:selection.sha256}}:{}};if(Buffer.byteLength(JSON.stringify(catalog))>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");return catalog}function selectionMatches(selection){try{let before=lstatSync2(selection.path);if(!before.isFile()||before.isSymbolicLink()||before.size>1024*1024)return!1;let fd=openSync7(selection.path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat2=fstatSync(fd);if(!stat2.isFile()||stat2.size>1024*1024)return!1;let bytes=Buffer.alloc(stat2.size+1),size=0;for(;size<bytes.length;){let count=readSync3(fd,bytes,size,bytes.length-size,null);if(!count)break;size+=count}return size===stat2.size&&createHash8("sha256").update(bytes.subarray(0,size)).digest("hex")===selection.sha256}finally{closeSync7(fd)}}catch(error2){if(error2.code==="ENOENT")return!1;throw error2}}function readOfficialPluginCatalog(){let source;try{source=readFileSync13(catalogPath(),"utf8")}catch(error2){if(error2.code==="ENOENT")return;throw error2}if(Buffer.byteLength(source)>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");let catalog=validateOfficialPluginCatalog(JSON.parse(source));return catalog.selection&&!selectionMatches(catalog.selection)?void 0:catalog}function replaceOfficialPluginCatalog(revision,plugins,selection){let catalog=validateOfficialPluginCatalog({schemaVersion:1,revision,plugins,...selection?{selection}:{}}),content=JSON.stringify(catalog);if(Buffer.byteLength(content)>MAX_CATALOG_BYTES)throw new Error("Managed plugin catalog exceeds 256 KiB");if(catalog.selection&&!selectionMatches(catalog.selection))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");mkdirSync7(pluginDirectory(),{recursive:!0,mode:448});let file=catalogPath(),temporary=`${file}.${randomUUID10()}.tmp`;try{if(writeFileSync7(temporary,content,{mode:384,flag:"wx"}),catalog.selection&&!selectionMatches(catalog.selection))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");renameSync8(temporary,file)}finally{rmSync10(temporary,{force:!0})}refreshOfficialPlugins()}function refreshOfficialPlugins(){let plugins={};try{plugins=readOfficialPluginCatalog()?.plugins??{}}catch{}for(let name of Object.keys(OFFICIAL_PLUGINS))delete OFFICIAL_PLUGINS[name];return Object.assign(OFFICIAL_PLUGINS,plugins),OFFICIAL_PLUGINS}function findOfficialPlugin(name){let plugins=refreshOfficialPlugins();return Object.hasOwn(plugins,name)?plugins[name]:void 0}function listOfficialPluginNames(setup){return Object.entries(refreshOfficialPlugins()).filter(([,item])=>setup===void 0||item.setup===setup).map(([name])=>name)}var OFFICIAL_PLUGIN_MANAGER,OFFICIAL_PLUGINS,MAX_CATALOG_BYTES,catalogPath,init_officialPluginCatalog=__esm({"../client/src/plugins/officialPluginCatalog.ts"(){"use strict";init_pluginRegistry();OFFICIAL_PLUGIN_MANAGER="@mearl/setup:official",OFFICIAL_PLUGINS={},MAX_CATALOG_BYTES=256*1024,catalogPath=()=>join15(pluginDirectory(),".official-catalog.json");refreshOfficialPlugins()}});import{closeSync as closeSync8,mkdirSync as mkdirSync8,openSync as openSync8,rmSync as rmSync11,statSync as statSync9,writeFileSync as writeFileSync8}from"node:fs";import{join as join16}from"node:path";import{spawn as spawn5}from"node:child_process";function delay2(milliseconds){return new Promise(resolve7=>setTimeout(resolve7,milliseconds))}function installLockPath(name){return join16(pluginDirectory(),`.official-${name}.install.lock`)}async function acquireInstallLock(name){let directory=pluginDirectory();mkdirSync8(directory,{recursive:!0,mode:448});let lockPath=installLockPath(name),deadline=Date.now()+INSTALL_TIMEOUT_MS;for(;;){let descriptor;try{return descriptor=openSync8(lockPath,"wx",384),writeFileSync8(descriptor,`${process.pid}
644
+ `),closeSync8(descriptor),()=>rmSync11(lockPath,{force:!0})}catch(error2){if(descriptor!==void 0&&closeSync8(descriptor),error2.code!=="EEXIST")throw error2}if(findPluginRegistration(name))return()=>{};try{if(Date.now()-statSync9(lockPath).mtimeMs>INSTALL_LOCK_STALE_MS){rmSync11(lockPath,{force:!0});continue}}catch(error2){if(error2.code==="ENOENT")continue;throw error2}if(Date.now()>=deadline)throw new Error(`等待安装官方插件 ${name} 超时`);await delay2(250)}}function appendOutput(current,chunk){return current.length>=MAX_INSTALL_OUTPUT?current:(current+chunk.toString("utf8")).slice(0,MAX_INSTALL_OUTPUT)}function installWithSetup(name){return new Promise((resolve7,reject)=>{let command=process.platform==="win32"?"npx.cmd":"npx",child=spawn5(command,["-y","--@mearl:registry=https://registry.npmjs.org",`@mearl/setup@${CLIENT_VERSION}`,"plugin","ensure",name],{env:npmExecEnvironment(),stdio:["ignore","pipe","pipe"],windowsHide:!0}),stdout="",stderr="",settled=!1,finish=error2=>{settled||(settled=!0,clearTimeout(timer),error2?reject(error2):resolve7())},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(new Error(`安装官方插件 ${name} 超时`))},INSTALL_TIMEOUT_MS);child.stdout.on("data",chunk=>stdout=appendOutput(stdout,chunk)),child.stderr.on("data",chunk=>stderr=appendOutput(stderr,chunk)),child.once("error",error2=>finish(error2)),child.once("exit",code=>{if(code===0){finish();return}let detail=(stderr||stdout).replace(/[\r\n]+/g," ").trim().slice(-1e3);finish(new Error(detail?`安装官方插件 ${name} 失败 (exit ${code}): ${detail}`:`安装官方插件 ${name} 失败 (exit ${code})`))})})}async function installOfficialPlugin(name,progress){if(findPluginRegistration(name))return;if(!findOfficialPlugin(name))throw new Error(`未知官方插件: ${name}`);let releaseLock=await acquireInstallLock(name);try{if(findPluginRegistration(name))return;let accepted=JSON.stringify(readOfficialPluginCatalog());if(!findOfficialPlugin(name))throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");if(progress?.(`正在安装官方插件 ${name}...`),await installWithSetup(name),JSON.stringify(readOfficialPluginCatalog())!==accepted)throw new Error("PLUGIN_CATALOG_SELECTION_CHANGED");if(!findPluginRegistration(name))throw new Error(`官方插件 ${name} 安装完成后仍未注册`);progress?.(`官方插件 ${name} 已安装。`)}finally{releaseLock()}}var INSTALL_TIMEOUT_MS,INSTALL_LOCK_STALE_MS,MAX_INSTALL_OUTPUT,activeInstallations,ensureOfficialPluginRegistered,init_officialPluginInstaller=__esm({"../client/src/plugins/officialPluginInstaller.ts"(){"use strict";init_runtimePaths();init_dist();init_officialPluginCatalog();init_pluginRegistry();INSTALL_TIMEOUT_MS=18e4,INSTALL_LOCK_STALE_MS=5*6e4,MAX_INSTALL_OUTPUT=1024*1024,activeInstallations=new Map;ensureOfficialPluginRegistered=(name,progress)=>{let active=activeInstallations.get(name);if(active)return active;let installation=installOfficialPlugin(name,progress).finally(()=>{activeInstallations.delete(name)});return activeInstallations.set(name,installation),installation}}});import{spawn as spawn6}from"node:child_process";import{createInterface}from"node:readline";function pythonExecutable(){return process.env.MEARL_PYTHON?.trim()||"python3"}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseDescriptor(message){if(!Array.isArray(message.commands))throw new Error("Python 插件未返回命令列表");let commands=message.commands.map(value=>{if(!isObject(value)||typeof value.signature!="string"||typeof value.description!="string"||typeof value.toolboxOnly!="boolean"||typeof value.runtimeOnly!="boolean")throw new Error("Python 插件返回了无效的命令描述");return{signature:value.signature,description:value.description,toolboxOnly:value.toolboxOnly,runtimeOnly:value.runtimeOnly,recoveryOnly:value.recoveryOnly===!0,migrationOnly:value.migrationOnly===!0}});if(message.name!==void 0&&typeof message.name!="string")throw new Error("Python 插件返回了无效的 name");if(message.description!==void 0&&typeof message.description!="string")throw new Error("Python 插件返回了无效的 description");return{commands,...typeof message.name=="string"?{name:message.name}:{},...typeof message.description=="string"?{description:message.description}:{},...message.toolbox!==void 0?{toolbox:message.toolbox}:{},...message.pageRuntime!==void 0?{pageRuntime:message.pageRuntime}:{},...message.stateStorage!==void 0?{stateStorage:message.stateStorage}:{},...message.taskRecovery!==void 0?{taskRecovery:message.taskRecovery}:{},...message.appProfiles!==void 0?{appProfiles:message.appProfiles}:{}}}function bridgedError(message){let detail=typeof message.message=="string"?message.message:"Python 插件执行失败",restored=pluginExecutionError({message:detail,...typeof message.code=="string"?{code:message.code}:{},...isObject(message.details)?{details:message.details}:{},...isObject(message.metadata)?{metadata:message.metadata}:{}});return typeof message.code=="string"&&/^PLUGIN_[A-Z0-9_]+$/.test(message.code)?Object.assign(new PluginError(message.code,detail),restored):restored}function errorResponse(error2){let serialized=serializePluginExecutionError(error2);if(error2 instanceof PluginError){let prefix=`${error2.code}: `;return{...serialized,code:error2.code,message:error2.message.startsWith(prefix)?error2.message.slice(prefix.length):error2.message}}return serialized}async function runPythonWorker(entry,initial,app,signal,expectedDescriptor){return new Promise((resolve7,reject)=>{let executable=pythonExecutable(),child=spawn6(executable,["-u","-c",PYTHON_BOOTSTRAP,entry],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),lines=createInterface({input:child.stdout}),descriptor,outcome,protocolError,stderr="",failProtocol=error2=>{protocolError||(protocolError=error2 instanceof Error?error2:new Error(String(error2)),cancel())},write=message=>{try{child.stdin.write(`${JSON.stringify(message)}
660
645
  `)}catch(error2){failProtocol(error2)}};child.stderr.setEncoding("utf8"),child.stderr.on("data",chunk=>{stderr=`${stderr}${chunk}`.slice(-STDERR_LIMIT)}),child.stdin.on("error",()=>{});let killTimer,terminalStopRequested=!1,armKill=()=>{killTimer||(killTimer=setTimeout(()=>{terminalStopRequested=!protocolError&&!signal?.aborted&&!!(outcome||initial.mode==="describe"&&descriptor),child.kill("SIGKILL")},1e3),killTimer.unref())},cancel=()=>{child.kill("SIGTERM"),armKill()};signal?.addEventListener("abort",cancel,{once:!0}),signal?.aborted&&cancel(),child.once("error",error2=>{error2.code==="ENOENT"?reject(new Error(`未找到 ${executable},Python 插件需要 Python 3.9 或更高版本(可通过 MEARL_PYTHON 指定解释器)`)):reject(error2)}),lines.on("line",line=>{if(protocolError)return;let message;try{let value=JSON.parse(line);if(!isObject(value)||typeof value.type!="string")throw new Error("消息不是对象");message=value}catch(error2){failProtocol(new Error(`Python 插件输出了无效协议消息: ${line.slice(0,200)}`,error2 instanceof Error?{cause:error2}:void 0));return}if(message.type==="ready"){try{if(descriptor)throw new Error("Python 插件重复发送 ready");if(descriptor=parseDescriptor(message),initial.mode==="run"&&expectedDescriptor&&pluginRecoverySignature(descriptor)!==pluginRecoverySignature(expectedDescriptor))throw new PluginError("PLUGIN_DECLARATION_CHANGED","Python execution declaration differs from its loaded metadata");write({type:"ready_ack"}),initial.mode==="describe"&&armKill()}catch(error2){failProtocol(error2)}return}if(message.type==="progress"){if(!app||typeof message.message!="string"){failProtocol(new Error("Python 插件发送了无效的 progress 消息"));return}try{app.progress(message.message)}catch(error2){failProtocol(error2)}return}if(message.type==="invoke"){if(!app||typeof message.id!="number"||typeof message.action!="string"||!isObject(message.payload)||!isObject(message.options)){failProtocol(new Error("Python 插件发送了无效的 invoke 消息"));return}let{action,payload,options}=message;Promise.resolve().then(()=>action==="plugin_task_checkpoint"&&app.checkpoint?app.checkpoint(payload.data,payload.expectedSequence):action==="plugin_model"&&payload.operation==="run"&&app.model?app.model(payload.request,message.stream?{onProgress:progress=>{!signal?.aborted&&!outcome&&write({type:"invoke-progress",id:message.id,progress})}}:void 0):action==="plugin_state"&&app.state?app.state(payload.collection,payload.operation,payload):action==="plugin_page"&&app.page?app.page(payload.operation,payload):app.invoke(action,payload,options)).then(result=>{write({type:"response",id:message.id,result:result===void 0?null:result})}).catch(error2=>{write({type:"response",id:message.id,error:errorResponse(error2)})});return}if(message.type==="result"){outcome||(outcome={hasResult:!0,result:message.result}),write({type:"terminal_ack"}),armKill();return}if(message.type==="error"){outcome||(outcome={error:bridgedError(message)}),write({type:"terminal_ack"}),armKill();return}failProtocol(new Error(`Python 插件发送了未知消息类型: ${message.type}`))});let finished=!1,finish=code=>{if(!finished){if(finished=!0,signal?.removeEventListener("abort",cancel),killTimer&&clearTimeout(killTimer),lines.close(),child.stdin.destroy(),child.stdout.destroy(),child.stderr.destroy(),signal?.aborted){reject(signal.reason??new Error("Plugin command cancelled"));return}if(protocolError){reject(protocolError);return}if(outcome?.error){reject(outcome.error);return}if(code!==0&&!terminalStopRequested){reject(new Error(stderr.trim()||`Python 插件进程异常退出${code===null?"":` (exit ${code})`}`));return}if(!descriptor){reject(new Error("Python 插件未返回注册信息"));return}if(initial.mode==="run"&&!outcome?.hasResult){reject(new Error("Python 插件未返回执行结果"));return}resolve7({descriptor,...outcome?.hasResult?{result:outcome.result}:{}})}};child.once("exit",finish),child.once("close",finish),write(initial)})}async function describePythonPlugin(entry,options){let{descriptor}=await runPythonWorker(entry,{mode:"describe",options});return descriptor}async function runPythonPluginCommand(entry,command,input,app,context,recovery=!1,expectedDescriptor,runtimeOnly=!1){let{result}=await runPythonWorker(entry,{mode:"run",command,input,options:app.options,identity:context.identity,recovery,runtime:runtimeOnly},app,context.signal,expectedDescriptor);return result}var STDERR_LIMIT,PYTHON_BOOTSTRAP,init_pythonPlugin=__esm({"../client/src/plugins/runtime/pythonPlugin.ts"(){"use strict";init_pluginRecoveryDefinition();init_pluginRegistry();init_pluginExecutorProtocol();STDERR_LIMIT=64*1024,PYTHON_BOOTSTRAP=String.raw`
661
646
  import asyncio
662
647
  import importlib.util
@@ -989,15 +974,15 @@ except BaseException as error:
989
974
  sys.exit(1)
990
975
  `}});import{StringDecoder as StringDecoder2}from"node:string_decoder";function readPluginTaskMessages(socket,receive){let decoder=new StringDecoder2("utf8"),buffer="";socket.on("data",chunk=>{try{buffer+=decoder.write(chunk);let end;for(;(end=buffer.indexOf(`
991
976
  `))>=0;){let line=buffer.slice(0,end);if(buffer=buffer.slice(end+1),Buffer.byteLength(line)>MAX_MESSAGE_BYTES)throw new Error("Plugin host message is too large");let message=JSON.parse(line);if(!message||typeof message!="object"||!Number.isSafeInteger(message.id))throw new Error("Invalid plugin host message");receive(message)}if(Buffer.byteLength(buffer)>MAX_MESSAGE_BYTES)throw new Error("Plugin host message buffer exceeded its limit")}catch(error2){socket.destroy(error2 instanceof Error?error2:new Error(String(error2)))}})}function writePluginTaskMessage(socket,message){return new Promise((resolve7,reject)=>{try{let text3=JSON.stringify(message)+`
992
- `;if(Buffer.byteLength(text3)>MAX_MESSAGE_BYTES)throw new Error("Plugin host message is too large");if(socket.destroyed)throw new Error("Plugin host connection is closed");socket.write(text3,error2=>error2?reject(error2):resolve7())}catch(error2){reject(error2)}})}var MAX_MESSAGE_BYTES,init_pluginTaskWire=__esm({"../client/src/plugins/pluginTaskWire.ts"(){"use strict";MAX_MESSAGE_BYTES=96*1024*1024}});var pluginHostConnection_exports={};__export(pluginHostConnection_exports,{PluginHostConnection:()=>PluginHostConnection});import{spawn as spawn7}from"node:child_process";import{closeSync as closeSync9,mkdirSync as mkdirSync9,openSync as openSync9}from"node:fs";import{createConnection}from"node:net";async function ensureHost(runtimePath){let paths=pluginHostPaths(),work=starting.get(paths.registry);work||(work=(async()=>{let lease=readRecord(paths.lease);if(lease&&isProcessOwnerAlive(lease)){if(lease.protocolVersion!==5)throw new Error("Plugin execution service protocol differs; stop the service before updating");return}let lock=`${paths.lease}.start`,existing=readRecord(lock);if(!(existing&&isProcessOwnerAlive(existing))&&(existing?removeRecordIfPid(lock,existing.pid):removeInvalidRecord(lock),!!claimRecord(lock,{pid:process.pid,processIdentity:processIdentity(process.pid)})))try{let owner=readRecord(paths.lease);if(owner&&isProcessOwnerAlive(owner))return;mkdirSync9(paths.home,{recursive:!0,mode:448}),rotateLogIfNeeded(paths.log);let log=openSync9(paths.log,"a",384);try{let child=spawn7(process.execPath,[runtimePath],{detached:!0,stdio:["ignore",log,log],windowsHide:!0});await new Promise((resolve7,reject)=>{child.once("spawn",resolve7),child.once("error",reject)}),child.unref()}finally{closeSync9(log)}let deadline=Date.now()+1e4;for(;Date.now()<deadline;){if(await new Promise(resolve7=>{let probe=createConnection(paths.socket),finish=value=>{probe.destroy(),resolve7(value)};probe.once("connect",()=>finish(!0)),probe.once("error",()=>finish(!1)),probe.setTimeout(200,()=>finish(!1))}))return;await new Promise(resolve7=>setTimeout(resolve7,50))}throw new Error("Plugin execution service startup timed out")}finally{removeRecordIfPid(lock,process.pid)}})().finally(()=>starting.delete(paths.registry)),starting.set(paths.registry,work)),await work}var starting,PluginHostConnection,init_pluginHostConnection=__esm({"../client/src/plugins/clients/pluginHostConnection.ts"(){"use strict";init_runtimePaths();init_dist();init_pluginHostPaths();init_dist2();init_pluginTaskWire();init_pluginExecutorProtocol();starting=new Map;PluginHostConnection=class{constructor(configuration={}){this.configuration=configuration}configuration;get hasInvocationBridge(){return!!this.configuration.invoke}connection;socket;opening=new Set;generation=0;async connect(generation){let check=()=>{if(generation!==this.generation)throw Object.assign(new Error("Plugin task client was disconnected"),{code:"PLUGIN_TASK_CLIENT_DISCONNECTED"})},connectOnce=()=>(check(),this.open(this.configuration.socketPath??pluginHostPaths().socket,generation));try{return await connectOnce()}catch(error2){if(check(),this.configuration.autoStart===!1||this.configuration.socketPath)throw error2;let code=error2.code;if(!["ENOENT","ECONNREFUSED","PLUGIN_TASK_CONNECTION_LOST"].includes(code??""))throw error2}await ensureHost(this.configuration.runtimePath??PLUGIN_TASK_HOST_PATH);let deadline=Date.now()+1e4,failure2;do{check();try{return await connectOnce()}catch(error2){failure2=error2,await new Promise(resolve7=>setTimeout(resolve7,100))}}while(Date.now()<deadline);throw new Error("Plugin execution service did not become ready; inspect its service.log",{cause:failure2})}async open(socketPath,generation){let socket=createConnection(socketPath);this.opening.add(socket);let pending=new Map,sequence=0,fail2=error2=>{for(let request2 of pending.values())clearTimeout(request2.timer),request2.reject(error2);pending.clear()};socket.on("error",fail2),socket.once("close",()=>{fail2(Object.assign(new Error("Plugin execution service connection was lost"),{code:"PLUGIN_TASK_CONNECTION_LOST"})),this.socket===socket&&(this.connection=void 0,this.socket=void 0)});let request=(method,input={},timeoutMs=15e3)=>new Promise((resolve7,reject)=>{let id=++sequence,timer=setTimeout(()=>{pending.delete(id),reject(Object.assign(new Error("Plugin task request timed out; the task may still be running"),{code:"PLUGIN_TASK_REQUEST_TIMEOUT"}))},timeoutMs);pending.set(id,{resolve:resolve7,reject,timer}),writePluginTaskMessage(socket,{type:"request",id,method,input}).catch(error2=>{clearTimeout(timer),pending.delete(id),reject(error2)})});readPluginTaskMessages(socket,message=>{if(message.type==="response"){let call=pending.get(message.id);if(!call)return;clearTimeout(call.timer),pending.delete(message.id),message.error?call.reject(pluginExecutionError(message.error)):call.resolve(message.result)}else message.type==="invoke"?Promise.resolve().then(()=>{if(!this.configuration.invoke)throw new Error("Plugin task client has no invocation bridge");return this.configuration.invoke(message.action,message.payload,message.options)}).then(result=>writePluginTaskMessage(socket,{type:"invoke-result",id:message.id,result}),error2=>writePluginTaskMessage(socket,{type:"invoke-result",id:message.id,error:serializePluginExecutionError(error2)})).catch(()=>{}):socket.destroy(new Error("Invalid plugin task response direction"))});try{await new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{socket.destroy(),reject(new Error("Plugin task connection timed out"))},2e3);socket.once("connect",()=>{clearTimeout(timer),resolve7()}),socket.once("error",error2=>{clearTimeout(timer),reject(error2)})});let scope={access:this.configuration.access??"public",source:this.configuration.source??"sdk",bridge:this.configuration.invoke?"caller":"service",...this.configuration.plugin?{plugin:this.configuration.plugin}:{},...this.configuration.scopeId?{scopeId:this.configuration.scopeId}:{}},status=await request("hello",{...scope,protocolVersion:5});if(status.protocolVersion!==5)throw new Error("Plugin task protocol version mismatch");if(generation!==this.generation||socket.destroyed)throw new Error("Plugin task client was disconnected");return this.socket=socket,{socket,request,status}}catch(error2){throw socket.destroy(),error2}finally{this.opening.delete(socket)}}async request(method,input={},timeoutMs){if(!this.connection){let attempt=this.connect(this.generation);this.connection=attempt,attempt.catch(()=>{this.connection===attempt&&(this.connection=void 0)})}return(await this.connection).request(method,input,timeoutMs)}disconnect(){this.generation++,this.socket?.destroy();for(let socket of this.opening)socket.destroy();this.socket=void 0,this.connection=void 0}}}});import{createHash as createHash9}from"node:crypto";function localWait(promise,signal,timeoutMs=1/0){return new Promise((resolve7,reject)=>{let abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin task wait aborted"))},timer=Number.isFinite(timeoutMs)?setTimeout(()=>{cleanup(),reject(Object.assign(new Error("Waiting for the plugin task timed out; execution continues"),{code:"PLUGIN_TASK_WAIT_TIMEOUT"}))},Math.max(0,timeoutMs)):void 0,cleanup=()=>{clearTimeout(timer),signal?.removeEventListener("abort",abort)};signal?.addEventListener("abort",abort,{once:!0}),promise.then(value=>{cleanup(),resolve7(value)},error2=>{cleanup(),reject(error2)}),signal?.aborted&&abort()})}var PluginTaskClient,init_pluginTasks2=__esm({"../client/src/plugins/clients/pluginTasks.ts"(){"use strict";init_pluginHostConnection();init_dist();init_pluginHostPaths();init_unified();init_dist2();init_pluginExecutorProtocol();PluginTaskClient=class{constructor(configuration={}){this.configuration=configuration;this.connection=configuration.connection??new PluginHostConnection(configuration)}configuration;connection;request(method,input={},timeoutMs){return this.connection.request(method,input,timeoutMs)}status(){return this.request("status")}diagnose(options={}){return this.request("diagnose",{...options})}checkpoint(taskId){return this.request("checkpoint",{taskId})}resume(taskId,options={}){return this.request("resume",{taskId,revision:options.revision,environment:Object.fromEntries(Object.entries(options.environment??process.env).filter(entry=>entry[1]!==void 0))},45e3)}async start(plugin,invocation,options={}){let{cwd=process.cwd(),environment=process.env,executionTimeoutMs,idempotencyKey,...routing}=options;if(!this.connection.hasInvocationBridge&&routing.browser&&!decodeBrowserTarget(routing.browser)){let client=new UnifiedClient;try{let selection=await client.invoke("browser_select_browser",{browser:routing.browser},routing);if(!selection?.selected?.browserId)throw new Error("Cannot resolve plugin task browser target");routing.browser=selection.selected.browserId}finally{client.disconnect()}}return this.request("start",{plugin,command:invocation.command,input:invocation.input,cwd,environment:Object.fromEntries(Object.entries(environment).filter(entry=>entry[1]!==void 0)),options:routing,executionTimeoutMs,idempotencyKey})}get(taskId){return this.request("get",{taskId})}list(activeOnly=!1,page={}){return this.request("list",{activeOnly,...page})}cancel(taskId){return this.request("cancel",{taskId})}events(taskId,cursor=0,waitMs=0){return this.request("events",{taskId,cursor,waitMs},waitMs+15e3)}resultChunk(taskId,index){return this.request("result",{taskId,index})}async result(taskId){let task=await this.get(taskId);if(task.state!=="success"||!task.result)throw new Error("Plugin task has no successful result");let parts=[];for(let index=0;index<task.result.chunks;index++){let chunk=await this.resultChunk(taskId,index);if(chunk.taskId!==taskId||chunk.index!==index||chunk.sha256!==task.result.sha256||chunk.bytes!==task.result.bytes||chunk.chunks!==task.result.chunks)throw new Error("Plugin task result chunk identity mismatch");parts.push(Buffer.from(chunk.data,"base64"))}let bytes=Buffer.concat(parts);if(bytes.length!==task.result.bytes||createHash9("sha256").update(bytes).digest("hex")!==task.result.sha256)throw new Error("Plugin task result integrity check failed");return JSON.parse(bytes.toString("utf8")).value}async*subscribe(taskId,options={}){let cursor=options.cursor??0;for(;;){options.signal?.throwIfAborted();let page=await localWait(this.events(taskId,cursor,25e3),options.signal);if(options.signal?.throwIfAborted(),yield page,cursor=page.nextCursor,!isPluginTaskActive(page.task.state)&&cursor>=page.task.sequence)return}}async wait(taskId,options={}){if(options.timeoutMs!==void 0&&(!Number.isSafeInteger(options.timeoutMs)||options.timeoutMs<1))throw new Error("Invalid plugin task wait timeout");let deadline=options.timeoutMs===void 0?1/0:Date.now()+options.timeoutMs,cursor=0,lastSequence=-1;for(;;){if(options.signal?.throwIfAborted(),Date.now()>=deadline)throw Object.assign(new Error("Waiting for the plugin task timed out; execution continues"),{code:"PLUGIN_TASK_WAIT_TIMEOUT"});let page=await localWait(this.events(taskId,cursor,Math.min(1e3,Math.max(0,deadline-Date.now()))),options.signal,deadline-Date.now());if(options.signal?.throwIfAborted(),cursor=page.nextCursor,page.task.progress&&page.task.sequence!==lastSequence&&options.onProgress?.(page.task.progress,page.task),lastSequence=page.task.sequence,page.task.state==="success")return options.readResult===!1?page.task:localWait(this.result(taskId),options.signal,deadline-Date.now());if(!isPluginTaskActive(page.task.state))throw pluginExecutionError(page.task.error??{message:`Plugin task ended with ${page.task.state}`})}}async stopHost(){let original=await this.status();await this.request("shutdown"),this.disconnect();let deadline=Date.now()+15e3;for(;;){let lease=readRecord(pluginHostPaths().lease);if(!lease||lease.epoch!==original.host.epoch||!isProcessOwnerAlive(lease))return;if(Date.now()>=deadline)throw new Error("Plugin execution service did not finish stopping");await new Promise(resolve7=>setTimeout(resolve7,50))}}disconnect(){this.configuration.connection||this.connection.disconnect()}}}});import{rmSync as rmSync12}from"node:fs";import{randomUUID as randomUUID10}from"node:crypto";async function cleanupPluginRuntime(){let paths=pluginHostPaths();if(listPluginNames().length)throw new Error("Registered plugins still use the execution service");let lock=`${paths.lease}.start`,starter=readRecord(lock);if(starter&&!isProcessOwnerAlive(starter)?removeRecordIfPid(lock,starter.pid):starter||removeInvalidRecord(lock),!claimRecord(lock,{pid:process.pid,processIdentity:processIdentity(process.pid)}))throw new Error("Plugin execution service is starting; caches were retained");try{let lease=readRecord(paths.lease);if(lease&&isProcessOwnerAlive(lease)){let client=new PluginTaskClient({autoStart:!1});try{await client.stopHost()}finally{client.disconnect()}}let current2=readRecord(paths.lease);if(current2&&isProcessOwnerAlive(current2)||listPluginNames().length)throw new Error("Plugin execution service restarted during cleanup; caches were retained");let store=new PluginTaskStore;if(store.list().some(pluginTaskExecutionUnconfirmed))throw new Error("Plugin execution is not confirmed stopped; task records were retained");if(store.recover(randomUUID10()),store.list().some(pluginTaskExecutionUnconfirmed))throw new Error("Plugin execution is not confirmed stopped; task records were retained");let replacement=readRecord(paths.lease);if(replacement&&isProcessOwnerAlive(replacement)||listPluginNames().length)throw new Error("Plugin execution service restarted during cleanup; caches were retained");for(let file of[paths.tasks,paths.revisions,paths.log,`${paths.log}.1`])rmSync12(file,{recursive:!0,force:!0});current2&&removeRecordIfPid(paths.lease,current2.pid),process.platform!=="win32"&&rmSync12(paths.socket,{force:!0})}finally{removeRecordIfPid(lock,process.pid)}}var init_pluginRuntimeCleanup=__esm({"../client/src/plugins/runtime/pluginRuntimeCleanup.ts"(){"use strict";init_dist();init_pluginHostPaths();init_pluginRegistry();init_pluginTasks2();init_pluginTaskStore()}});var pluginPages_exports={};__export(pluginPages_exports,{PluginPageClient:()=>PluginPageClient});var PluginPageClient,init_pluginPages2=__esm({"../client/src/plugins/clients/pluginPages.ts"(){"use strict";init_unified();PluginPageClient=class{constructor(configuration={},connection){this.connection=connection;connection||(this.client=new UnifiedClient(configuration))}connection;client;call(plugin,operation,input={},options={}){return this.connection?this.connection.request("page.call",{plugin,input:{...input,operation},options,execution:{cwd:process.cwd(),environment:Object.fromEntries(Object.entries(process.env).filter(entry=>entry[1]!==void 0))}},Math.max(12e4,typeof input.timeoutSec=="number"&&Number.isFinite(input.timeoutSec)?(Math.min(300,input.timeoutSec)+5)*1e3:0)):this.client.invoke("plugin_page",{...input,plugin,operation},options)}attach(plugin,input,options={}){return this.call(plugin,"attach",input,options)}get(plugin,instanceId){return this.call(plugin,"get",{instanceId})}list(plugin){return this.call(plugin,"list")}send(plugin,instanceId,message,options={}){return this.call(plugin,"send",{instanceId,message,...options},options)}detach(plugin,instanceId){return this.call(plugin,"detach",{instanceId})}events(plugin,instanceId,cursor=0,waitMs=0){return this.call(plugin,"events",{instanceId,cursor,waitMs})}disconnect(){this.client?.disconnect()}}}});var pluginState_exports={};__export(pluginState_exports,{PluginStateClient:()=>PluginStateClient});var PluginStateClient,init_pluginState2=__esm({"../client/src/plugins/clients/pluginState.ts"(){"use strict";init_pluginHostConnection();PluginStateClient=class{constructor(options={}){this.options=options;this.connection=options.connection??new PluginHostConnection(options)}options;connection;call(plugin,collection,operation,input={},options={}){return this.connection.request("state.call",{plugin,input:{...input,collection,operation},options},3e4)}get(plugin,collection,key2,input={}){return this.call(plugin,collection,"get",{...input,key:key2})}getMany(plugin,collection,keys,input={}){return this.call(plugin,collection,"get-many",{...input,keys})}list(plugin,collection,input={}){return this.call(plugin,collection,"list",input)}transact(plugin,collection,transaction,input={}){return this.call(plugin,collection,"transact",{...input,transaction})}disconnect(){this.options.connection||this.connection.disconnect()}}}});var pluginModels_exports={};__export(pluginModels_exports,{PluginModelClient:()=>PluginModelClient});var PluginModelClient,init_pluginModels2=__esm({"../client/src/plugins/clients/pluginModels.ts"(){"use strict";init_pluginTasks2();PluginModelClient=class{tasks;constructor(options={}){this.tasks=new PluginTaskClient(options)}capabilities(){return this.tasks.connection.request("model.capabilities")}list(provider="codex"){return this.tasks.connection.request("model.list",{provider},2e4)}async start(plugin,request,options={}){let{cwd=process.cwd(),environment=process.env,executionTimeoutMs,idempotencyKey,...routing}=options;return this.tasks.connection.request("start",{kind:"model",plugin,command:"model",input:{request},cwd,environment:Object.fromEntries(Object.entries(environment).filter(entry=>entry[1]!==void 0)),options:routing,executionTimeoutMs,idempotencyKey})}async run(plugin,request,options={}){let{signal,onProgress,...execution}=options;signal?.throwIfAborted();let started=await this.start(plugin,request,execution),cancel=()=>{this.tasks.cancel(started.taskId).catch(()=>{})};signal?.addEventListener("abort",cancel,{once:!0});try{return signal?.aborted&&cancel(),await this.tasks.wait(started.taskId,{onProgress})}finally{signal?.removeEventListener("abort",cancel)}}disconnect(){this.tasks.disconnect()}}}});var plugin_exports={};__export(plugin_exports,{OFFICIAL_PLUGINS:()=>OFFICIAL_PLUGINS,OFFICIAL_PLUGIN_MANAGER:()=>OFFICIAL_PLUGIN_MANAGER,PluginError:()=>PluginError,PluginModelClient:()=>PluginModelClient,PluginPageClient:()=>PluginPageClient,PluginStateClient:()=>PluginStateClient,PluginTaskClient:()=>PluginTaskClient,assertPluginName:()=>assertPluginName,cleanupPluginRuntime:()=>cleanupPluginRuntime,executeRegisteredPlugin:()=>executeRegisteredPlugin,findOfficialPlugin:()=>findOfficialPlugin,findPluginDirectoryEntry:()=>findPluginDirectoryEntry,findPluginEntry:()=>findPluginEntry,findPluginRegistration:()=>findPluginRegistration,invokePageEvalWithArgs:()=>invokePageEvalWithArgs,invokeRegisteredPlugin:()=>invokeRegisteredPlugin,invokeRegisteredRecoveryPlugin:()=>invokeRegisteredRecoveryPlugin,invokeRegisteredRuntimePlugin:()=>invokeRegisteredRuntimePlugin,invokeRegisteredToolboxPlugin:()=>invokeRegisteredToolboxPlugin,listOfficialPluginNames:()=>listOfficialPluginNames,listPluginNames:()=>listPluginNames,loadPlugin:()=>loadPlugin,loadRegisteredPlugin:()=>loadRegisteredPlugin,pluginDirectory:()=>pluginDirectory,pluginRegistrationNeedsRefresh:()=>pluginRegistrationNeedsRefresh,readOfficialPluginCatalog:()=>readOfficialPluginCatalog,readPluginPageBundleChunk:()=>readPluginPageBundleChunk,refreshRegisteredPlugin:()=>refreshRegisteredPlugin,registerPlugin:()=>registerPlugin,replaceOfficialPluginCatalog:()=>replaceOfficialPluginCatalog,resolvePluginEntry:()=>resolvePluginEntry,unregisterPlugin:()=>unregisterPlugin,validateOfficialPluginCatalog:()=>validateOfficialPluginCatalog});import{dirname as dirname8,extname as extname2,resolve as resolve6}from"node:path";import{pathToFileURL}from"node:url";function readPluginVersion(entry){try{return readInstalledSkillMetadata(resolve6(dirname8(entry),".."))?.version}catch{return}}function isObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPluginInvocation(value){return isObject2(value)&&typeof value.command=="string"&&isObject2(value.input)}function normalizePluginProgress(progress){if(typeof progress=="string"){if(!progress)throw new Error("app.progress 需要非空消息");return progress}if(!isObject2(progress)||typeof progress.message!="string"||!progress.message)throw new Error("app.progress 需要非空消息");if(progress.data!==void 0&&!isObject2(progress.data))throw new Error("app.progress data 必须是对象");let data2;if(progress.data)try{let serialized=JSON.stringify(progress.data),parsed=serialized===void 0?void 0:JSON.parse(serialized);if(!isObject2(parsed))throw new Error("invalid object");data2=Object.freeze(parsed)}catch{throw new Error("app.progress data 必须是可 JSON 序列化的对象")}return Object.freeze({message:progress.message,...data2?{data:data2}:{}})}function missingPluginEntryMessage(entry,pluginName){let name=pluginName??"<name>";return["插件入口已失效","",`插件:${name}`,`入口:${entry}`,"",`卸载命令:npx @mearl/setup plugin uninstall ${name}`].join(`
993
- `)}async function refreshRegisteredPlugin(name,includePage=!1){let key2=`${pluginDirectory()}/${name}`,pending=registrationRefreshes.get(key2);if(pending)return await pending,refreshRegisteredPlugin(name,includePage);let registration=findPluginRegistration(name);if(!registration)return;let entryChanged=pluginRegistrationNeedsRefresh(registration);if(!entryChanged&&(!includePage||!pluginRegistrationNeedsRefresh(registration,!0)))return registration;let refresh=(async()=>{let entryVersion=pluginFileVersion(registration.entry),loaded=entryChanged?await loadPlugin(registration.entry,{options:{},invoke:async()=>{throw new Error("注册时不能执行浏览器操作")},progress:()=>{throw new Error("注册时不能报告执行进度")}},name):registration,current2=findPluginRegistration(name);if(JSON.stringify(current2)!==JSON.stringify(registration))return current2;if(pluginFileVersion(registration.entry)!==entryVersion)throw new PluginError("PLUGIN_SOURCE_CHANGED",`插件更新进行中,请重新打开工具: ${name}`);return registerPlugin(name,registration.entry,loaded.description,{hasPublicCommands:"commandHelp"in loaded?!!loaded.commandHelp(name):loaded.hasPublicCommands,toolbox:loaded.toolbox,appProfiles:loaded.appProfiles,profileSources:"profileSources"in loaded?loaded.profileSources:loaded.source?.profiles,...registration.managedBy?{managedBy:registration.managedBy}:{}}),findPluginRegistration(name)})();registrationRefreshes.set(key2,refresh);try{return await refresh}finally{registrationRefreshes.delete(key2)}}async function loadPlugin(entry,context,pluginName){let entryVersion;try{entryVersion=pluginFileVersion(entry)}catch{throw new PluginError("PLUGIN_ENTRY_MISSING",missingPluginEntryMessage(entry,pluginName))}let commands=new Map,recoveries=new Map,migrations=new Map,executing=!1,checkpointDeclaration,invocationGeneration=0,registering=!0,name,description,toolbox,pageRuntime,stateStorage,taskRecovery,appProfiles,profileSources,registerCommand=(signature,handler,description2="",examples=[],toolboxOnly=!1,runtimeOnly=!1)=>{if(!registering)throw new Error("命令只能在入口注册阶段声明");let[name2,...args]=signature.trim().split(/\s+/);if(!/^[a-z][a-z0-9-]*$/.test(name2)||commands.has(name2)||typeof handler!="function"||!Array.isArray(examples)||examples.some(example=>typeof example!="string"||!example.trim()))throw new Error(`无效或重复的命令: ${signature}`);let command=new Command(name2).description(description2);for(let argument of args){if(!/^(?:<[a-zA-Z][\w-]*(?:\.\.\.)?>|\[[a-zA-Z][\w-]*(?:\.\.\.)?\])$/.test(argument))throw new Error(`无效的位置参数: ${argument}`);command.argument(argument)}let names=command.registeredArguments.map(argument=>argument.name());if(new Set(names).size!==names.length)throw new Error(`参数名称重复: ${signature}`);commands.set(name2,{command,signature,handler,examples:[...examples],toolboxOnly,runtimeOnly})},app=Object.freeze({options:Object.freeze({...context.options}),command:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples),runtimeCommand:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples,!1,!0),recoveryCommand(command,handler){if(!registering||!/^[a-z][a-z0-9-]*$/.test(command)||typeof handler!="function"||recoveries.has(command))throw new Error("Invalid or duplicate recovery command");recoveries.set(command,handler)},checkpointMigration(command,handler){if(!registering||!/^[a-z][a-z0-9-]*$/.test(command)||typeof handler!="function"||migrations.has(command))throw new Error("Invalid or duplicate checkpoint migration");migrations.set(command,(input,commandContext)=>handler(input,commandContext))},checkpoint(data2,expectedSequence){if(!executing||!context.invocation?.taskId)throw new PluginError("PLUGIN_TASK_REQUIRED","Checkpoints require a managed task");return context.signal?.throwIfAborted(),context.invoke("plugin_task_checkpoint",{plugin:pluginName??name,data:data2,expectedSequence,expectedDeclaration:checkpointDeclaration})},state(collection,operation,input={}){if(!executing)throw new Error("app.state is only available during command execution");if(context.signal?.throwIfAborted(),!stateStorage||!Object.hasOwn(stateStorage.collections,collection))throw new PluginError("PLUGIN_STATE_NOT_DECLARED","Plugin state collection is not declared");return context.invoke("plugin_state",{...input,plugin:pluginName??name,collection,operation,expectedDeclaration:pluginStateSignature(stateStorage.collections[collection])})},model(request,options={}){if(!executing)throw new Error("app.model is only available during command execution");context.signal?.throwIfAborted();let generation=invocationGeneration,observing=()=>executing&&generation===invocationGeneration&&!context.signal?.aborted;if(context.runModel)return context.runModel(pluginName??name,request,{signal:context.signal,onProgress:progress=>{observing()&&(context.progress(progress),options.onProgress?.(progress))}});let payload={plugin:pluginName??name,operation:"run",request};return options.onProgress?context.invoke("plugin_model",payload,{},progress=>{observing()&&options.onProgress?.(progress)}):context.invoke("plugin_model",payload)},page(operation,input={}){if(!executing)throw new Error("app.page is only available during command execution");return context.signal?.throwIfAborted(),context.invoke("plugin_page",{...input,plugin:pluginName??name,operation})},toolboxCommand:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples,!0),invoke(action,payload={},options={}){if(!executing)throw new Error("app.invoke 只能在命令执行期间调用");return context.signal?.throwIfAborted(),context.invoke(action,payload,options)},progress(progress){if(!executing)throw new Error("app.progress 只能在命令执行期间调用");context.progress(normalizePluginProgress(progress))}});try{if(extname2(entry).toLowerCase()===".py"){let descriptor=await describePythonPlugin(entry,app.options);name=descriptor.name,description=descriptor.description,toolbox=normalizePluginToolboxContribution(descriptor.toolbox),pageRuntime=normalizePluginPageRuntime(descriptor.pageRuntime),stateStorage=normalizePluginState(descriptor.stateStorage),taskRecovery=normalizePluginTaskRecovery(descriptor.taskRecovery),{appProfiles,profileSources}=loadPluginAppProfiles(entry,descriptor.appProfiles);for(let command of descriptor.commands){let commandName=command.signature.trim().split(/\s+/)[0];if(command.migrationOnly){app.checkpointMigration(commandName,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,"migration",descriptor));continue}if(command.recoveryOnly){app.recoveryCommand(commandName,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,!0,descriptor));continue}(command.runtimeOnly?app.runtimeCommand:command.toolboxOnly?app.toolboxCommand:app.command)(command.signature,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,!1,descriptor,command.runtimeOnly),command.description)}}else{let moduleUrl=pathToFileURL(entry);moduleUrl.searchParams.set("mearl-version",entryVersion);let module=await import(moduleUrl.href);if(module.name!==void 0&&typeof module.name!="string")throw new Error("入口的 name 导出必须为字符串");if(name=module.name,module.description!==void 0&&typeof module.description!="string")throw new Error("入口的 description 导出必须为字符串");if(description=module.description,toolbox=normalizePluginToolboxContribution(module.toolbox),pageRuntime=normalizePluginPageRuntime(module.pageRuntime),stateStorage=normalizePluginState(module.stateStorage),taskRecovery=normalizePluginTaskRecovery(module.taskRecovery),{appProfiles,profileSources}=loadPluginAppProfiles(entry,module.appProfiles),module.default!==void 0&&typeof module.default!="function")throw new Error("入口必须默认导出 register(app) 函数");if(typeof module.default=="function")await module.default(app);else if(!appProfiles)throw new Error("入口必须默认导出 register(app) 函数")}if(commands.size===0&&!appProfiles)throw new Error("入口未注册任何命令");for(let command of Object.keys(taskRecovery?.commands??{}))if(!commands.has(command)||commands.get(command)?.runtimeOnly||commands.get(command)?.toolboxOnly||!recoveries.has(command))throw new Error(`Recovery requires a command and recoveryCommand: ${command}`);for(let command of recoveries.keys())if(!Object.hasOwn(taskRecovery?.commands??{},command))throw new Error(`Undeclared recovery command: ${command}`);for(let[command,definition]of Object.entries(taskRecovery?.commands??{}))if(!!definition.migrateFrom?.length!==migrations.has(command))throw new Error(`Checkpoint migrations require a declaration and checkpointMigration: ${command}`);for(let command of migrations.keys())if(!Object.hasOwn(taskRecovery?.commands??{},command))throw new Error(`Undeclared checkpoint migration: ${command}`);let runtimeCommands=new Set(Object.values(pageRuntime?.events??{}).map(event=>event.command));pageRuntime?.initialize&&runtimeCommands.add(pageRuntime.initialize);for(let[name2,command]of commands)if(command.runtimeOnly&&!runtimeCommands.has(name2))throw new Error(`runtimeCommand is not declared in pageRuntime.events: ${name2}`);for(let name2 of runtimeCommands)if(!commands.has(name2)||commands.get(name2)?.toolboxOnly)throw new Error(`Invalid page runtime command: ${name2}`);let toolboxCommands=toolbox?.page.commands??[];for(let[name2,command]of commands)if(command.toolboxOnly&&!toolboxCommands.includes(name2))throw new Error(`toolboxCommand 未声明在 toolbox.page.commands 中: ${name2}`);for(let command of toolboxCommands)if(!commands.has(command))throw new Error(`toolbox 命令未注册: ${command}`)}catch(error2){throw new PluginError("PLUGIN_LOAD_FAILED",`${entry}: ${error2 instanceof Error?error2.message:String(error2)}`)}finally{registering=!1}let find=(name2,toolboxPage=!1)=>{let command=commands.get(name2);if(!command)throw new PluginError("PLUGIN_COMMAND_NOT_FOUND",`未知子命令: ${name2}`);if(toolboxPage==="runtime"){if(!(pageRuntime?.initialize===name2||Object.values(pageRuntime?.events??{}).some(event=>event.command===name2))||command.toolboxOnly)throw new PluginError("PLUGIN_COMMAND_NOT_ALLOWED","Page runtime command is not declared")}else{if(command.runtimeOnly)throw new PluginError("PLUGIN_COMMAND_RUNTIME_ONLY",`命令仅供页面运行时调用: ${name2}`);if(toolboxPage){if(!toolbox?.page.commands.includes(name2))throw new PluginError("PLUGIN_COMMAND_NOT_ALLOWED",`工具页面不允许调用命令: ${name2}`)}else if(command.toolboxOnly)throw new PluginError("PLUGIN_COMMAND_TOOLBOX_ONLY",`命令仅供工具页面调用: ${name2}`)}return command},publicCommands=()=>[...commands.values()].filter(command=>!command.toolboxOnly&&!command.runtimeOnly),run=async(positionals,payload,namedInput={},toolboxPage=!1)=>{if(payload!==void 0&&positionals.length>0)throw new PluginError("PLUGIN_INVALID_INPUT","位置参数调用与 --payload 调用不能混用");if(payload!==void 0&&Object.keys(namedInput).length>0)throw new PluginError("PLUGIN_INVALID_INPUT","插件业务选项与 --payload 调用不能混用");if(payload!==void 0&&(!isObject2(payload)||typeof payload.command!="string"||!isObject2(payload.input)))throw new PluginError("PLUGIN_INVALID_INPUT",'--payload 必须为 {"command":"...","input":{...}}');let envelope=payload,commandName=envelope?.command??positionals[0]??"",hidden=toolboxPage==="recovery"||toolboxPage==="migration",selected=find(commandName,hidden?!1:toolboxPage),command=selected.command,handler=toolboxPage==="recovery"?recoveries.get(commandName):toolboxPage==="migration"?migrations.get(commandName):selected.handler;if(!handler||toolboxPage==="recovery"&&!context.invocation?.recovery)throw new PluginError("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery handler requires a managed recovery attempt");if(toolboxPage==="recovery"&&context.invocation?.recovery?.declarationHash!==pluginRecoverySignature(taskRecovery.commands[commandName]))throw new PluginError("PLUGIN_RECOVERY_DECLARATION_CHANGED","Recovery declaration differs from the admitted format");let positionalInput=envelope?{...envelope.input}:Object.fromEntries(command.registeredArguments.map((argument,index)=>[argument.name(),argument.variadic?positionals.slice(index+1):positionals[index+1]]).filter(([,value])=>value!==void 0));for(let name2 of Object.keys(namedInput))if(Object.hasOwn(positionalInput,name2))throw new PluginError("PLUGIN_INVALID_INPUT",`参数不能重复传入: ${name2}`);let input={...positionalInput,...namedInput};if(!envelope&&!command.registeredArguments.some(argument=>argument.variadic)&&positionals.length-1>command.registeredArguments.length)throw new PluginError("PLUGIN_INVALID_INPUT","位置参数过多");for(let argument of hidden?[]:command.registeredArguments){let value=Object.hasOwn(input,argument.name())?input[argument.name()]:void 0;if(argument.required&&(value==null||value===""||Array.isArray(value)&&value.length===0))throw new PluginError("PLUGIN_INVALID_INPUT",`缺少必填参数: ${argument.name()}`);if(argument.variadic&&value!==void 0&&!Array.isArray(value))throw new PluginError("PLUGIN_INVALID_INPUT",`${argument.name()} 必须为数组`)}if(executing)throw new PluginError("PLUGIN_BUSY","同一命令实例不能并发执行");let signal=context.signal??new AbortController().signal;signal.throwIfAborted();let identity=context.invocation??createPluginInvocationIdentity(pluginName??name??"unregistered",context.source??"sdk",context.parentInvocation),generation=++invocationGeneration,assertActive=()=>{if(!executing||generation!==invocationGeneration)throw new PluginError("PLUGIN_INVOCATION_ENDED","命令调用已结束");signal.throwIfAborted()},commandContext=Object.freeze({identity,signal,...identity.recovery?{recovery:structuredClone(identity.recovery)}:{},checkpoint:(data2,expectedSequence)=>(assertActive(),app.checkpoint(data2,expectedSequence)),...identity.page?{page:Object.freeze({send:(message,options={})=>(assertActive(),app.page("send",{instanceId:identity.page.instanceId,message,...options.timeoutSec!==void 0?{timeoutSec:options.timeoutSec}:{}})),get:()=>(assertActive(),app.page("get",{instanceId:identity.page.instanceId}))})}:{},invoke:(action,payload2,options)=>(assertActive(),app.invoke(action,payload2,options)),state:(collection,operation,input2)=>(assertActive(),app.state(collection,operation,{...identity.page?{instanceId:identity.page.instanceId}:{},...input2})),model:(request,options)=>(assertActive(),app.model(request,options)),progress:progress=>{assertActive(),app.progress(progress)}});checkpointDeclaration=taskRecovery&&Object.hasOwn(taskRecovery.commands,commandName)?pluginRecoverySignature(taskRecovery.commands[commandName]):void 0,executing=!0,context.onInvocation?.(identity);try{return await handler(input,commandContext)}finally{executing=!1,checkpointDeclaration=void 0,context.onInvocation?.(void 0)}};return{name,description,toolbox,pageRuntime,stateStorage,taskRecovery,appProfiles,profileSources,version:readPluginVersion(entry),commandHelp(namespace){return publicCommands().map(({command,signature})=>` ${namespace} ${signature} ${command.description()}`).join(`
994
- `)},help(namespace,name2){let selected=name2?[find(name2)]:publicCommands();if(!selected.length){let location2=toolbox?`请在 Mearl ${toolbox.displayMode==="popup"?"Popup":"工具箱"} 中打开「${toolbox.title}」使用。`:"此插件未提供公开 CLI 命令。";return`${namespace} 未提供 CLI 命令。
995
- ${location2}`}let examples=selected.flatMap(({examples:examples2})=>examples2);return["用法:",...selected.map(({command,signature})=>` ${namespace} ${signature} ${command.description()}`),...examples.length?["","示例:",...examples.map(example=>` ${namespace} ${example}`)]:[]].join(`
996
- `)},run(positionals,payload,namedInput={}){return run(positionals,payload,namedInput)},runRuntime(invocation){return run([],invocation,{},"runtime")},runRecovery(invocation){return run([],invocation,{},"recovery")},runMigration(invocation){return run([],invocation,{},"migration")},runToolbox(invocation){return run([],invocation,{},!0)}}}async function loadRegisteredPluginWithState(name,context,options={},state={stack:[]}){if(state.stack.includes(name))throw new PluginError("PLUGIN_INVOCATION_CYCLE",`插件调用形成循环: ${[...state.stack,name].join(" -> ")}`);let registration=context.resolveRegistration?context.resolveRegistration(name):findPluginRegistration(name);if(!registration&&findOfficialPlugin(name)&&(await(context.ensurePlugin??ensureOfficialPluginRegistered)(name,options.onProgress?message=>options.onProgress?.(message):void 0),registration=findPluginRegistration(name)),!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${name}`);let{onProgress,signal,source,...invokeOptions}=options,childState={stack:[...state.stack,name]},activeInvocation;return loadPlugin(registration.entry,{options:invokeOptions,source:source??context.source,parentInvocation:context.parentInvocation,invocation:context.invocation,signal,runModel:context.runModel,onInvocation:identity=>{activeInvocation=identity},progress:onProgress??(()=>{}),async invoke(action,payload,overrides,progress){let nestedOptions={...invokeOptions,...overrides};if(COMMAND_MAP.has(action)||action==="connector_list"){let result2=await context.invoke(action,payload,nestedOptions);if(result2?.action?.success===!1)throw new Error(result2.action.error||`${action} failed`);return result2}let pluginInvocation=isPluginInvocation(payload);if(findPluginRegistration(action)||findOfficialPlugin(action)||pluginInvocation){if(!pluginInvocation)throw new PluginError("PLUGIN_INVALID_INPUT",`调用插件 ${action} 需要 {"command":"...","input":{...}}`);return activeInvocation?.taskId?(!findPluginRegistration(action)&&findOfficialPlugin(action)&&await(context.ensurePlugin??ensureOfficialPluginRegistered)(action),context.invoke("plugin_invoke_child",{plugin:action,invocation:payload},nestedOptions)):invokeRegisteredPluginWithState(action,payload,{...context,invocation:void 0,parentInvocation:activeInvocation},{...nestedOptions,...onProgress?{onProgress}:{},...signal?{signal}:{},...source?{source}:{}},childState)}let result=await(progress?context.invoke(action,payload,nestedOptions,progress):context.invoke(action,payload,nestedOptions));if(result?.action?.success===!1)throw new Error(result.action.error||`${action} failed`);return result}},name)}function loadRegisteredPlugin(name,context,options={}){return loadRegisteredPluginWithState(name,context,options)}async function invokeRegisteredPluginWithState(name,invocation,context,options={},state={stack:[]}){return(await loadRegisteredPluginWithState(name,context,options,state)).run([],invocation)}function invokeRegisteredPlugin(name,invocation,context,options={}){return invokeRegisteredPluginWithState(name,invocation,context,options)}async function invokeRegisteredToolboxPlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runToolbox(invocation)}async function invokeRegisteredRuntimePlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runRuntime(invocation)}async function invokeRegisteredRecoveryPlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runRecovery(invocation)}var registrationRefreshes,init_plugin=__esm({"../client/src/plugins/sdk/plugin.ts"(){"use strict";init_pluginStateDefinition();init_pluginRecoveryDefinition();init_pluginPageDefinition();init_pluginAppProfiles();init_pageEvalArguments();init_skillManifest();init_commander();init_commands();init_officialPluginCatalog();init_officialPluginInstaller();init_pluginRegistry();init_pluginSource();init_pythonPlugin();init_pluginExecution2();init_pluginExecutor();init_pluginTasks2();init_pluginRuntimeCleanup();init_pluginPages2();init_pluginRegistry();init_officialPluginCatalog();init_pluginState2();init_pluginModels2();registrationRefreshes=new Map}});import WebSocket from"ws";function encodeBrowserTarget(target){let browser=encodeURIComponent(target.browser).replace(/%3A/g,":");return target.connector?`${GLOBAL_BROWSER_PREFIX}remote:${encodeURIComponent(target.connector)}:${browser}`:`${GLOBAL_BROWSER_PREFIX}local:${browser}`}function omitTransientBrowserSecrets(browser){let safeBrowser={...browser};for(let key2 of Object.keys(safeBrowser))/accessUrl$/i.test(key2)&&delete safeBrowser[key2];return safeBrowser}function decodeBrowserTarget(selector){if(selector?.startsWith(GLOBAL_BROWSER_PREFIX))try{let target=selector.slice(GLOBAL_BROWSER_PREFIX.length);if(target.startsWith("local:")){let browser=decodeURIComponent(target.slice(6));return browser?{browser}:void 0}if(target.startsWith("remote:")){let remoteTarget=target.slice(7),separator=remoteTarget.indexOf(":");if(separator<0)return;let connector=decodeURIComponent(remoteTarget.slice(0,separator)),browser=decodeURIComponent(remoteTarget.slice(separator+1));return connector&&browser?{connector,browser}:void 0}}catch{return}}function normalizeBrowserSelector(selector){let decodedTarget=decodeBrowserTarget(selector);return(decodedTarget?encodeBrowserTarget(decodedTarget):selector.trim()).toLowerCase()}function decorateBrowser(browser,source){let safeBrowser=omitTransientBrowserSecrets(browser),originalBrowserId=String(browser.browserId),originalName=String(browser.name);return{...safeBrowser,browserId:encodeBrowserTarget({browser:originalBrowserId,...source.connectorId?{connector:source.connectorId}:{}}),name:source.kind==="local"?`[this machine] ${originalName}`:`[${source.connectorName}] ${originalName}`,originalBrowserId,originalName,status:typeof browser.status=="string"?browser.status:"disconnected",source}}function browserMatches(browser,selector){let normalized=normalizeBrowserSelector(selector);return browser.browserId.toLowerCase()===normalized||browser.originalBrowserId?.toLowerCase()===normalized||browser.name.toLowerCase()===normalized||browser.originalName?.toLowerCase()===normalized}function findBrowsers(browsers,selector,connectedOnly=!0){let candidates=connectedOnly?browsers.filter(browser=>browser.status==="connected"):browsers,exact=candidates.filter(browser=>browserMatches(browser,selector));if(exact.length>0)return exact;let normalized=normalizeBrowserSelector(selector);return candidates.filter(browser=>browser.browserId.toLowerCase().includes(normalized)||browser.originalBrowserId?.toLowerCase().includes(normalized)||browser.name.toLowerCase().includes(normalized)||browser.originalName?.toLowerCase().includes(normalized))}function errorMessage(error2){return error2 instanceof Error?error2.message:String(error2)}var RESPONSE_GRACE_MS,GLOBAL_BROWSER_PREFIX,UnifiedClient,init_unified=__esm({"../client/src/unified.ts"(){"use strict";init_pageEvalArguments();init_artifacts();init_dist3();init_actionTimeouts();init_dist2();init_socket();init_unifiedConfig();RESPONSE_GRACE_MS=1e3,GLOBAL_BROWSER_PREFIX="mearl:";UnifiedClient=class{controlSessions=new Map;options;defaultBrowser;defaultConnector;ws=null;connectPromise=null;messageBuffer="";pendingRequests=new Map;heartbeatTimer=null;closing=!1;constructor(options={}){this.options={...options.serverUrl?{serverUrl:options.serverUrl}:{},connectTimeoutSec:options.connectTimeoutSec??30,requestTimeoutSec:options.requestTimeoutSec??60,heartbeatInterval:options.heartbeatInterval??30},this.defaultBrowser=options.defaultBrowser??(process.env.MEARL_BROWSER?.trim()||void 0),this.defaultConnector=options.defaultConnector}disconnect(){this.closing=!0,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.rejectAllPending(new Error("Connection closed by user")),this.ws?.close(),this.ws=null}async invokePlugin(name,invocation,options={}){let{invokeRegisteredPlugin:invokeRegisteredPlugin2}=await Promise.resolve().then(()=>(init_plugin(),plugin_exports));return invokeRegisteredPlugin2(name,invocation,{invoke:(action,payload,invokeOptions)=>this.invoke(action,payload,invokeOptions),runModel:async(plugin,request,execution)=>{let{PluginModelClient:PluginModelClient2}=await Promise.resolve().then(()=>(init_pluginModels2(),pluginModels_exports)),models=new PluginModelClient2({source:options.source??"sdk"});try{return await models.run(plugin,request,{signal:execution.signal,onProgress:progress=>{progress!==void 0&&execution.onProgress?.(progress)}})}finally{models.disconnect()}}},options)}async invoke(action,data2={},options={}){if(action==="plugin_state"){let{PluginStateClient:PluginStateClient2}=await Promise.resolve().then(()=>(init_pluginState2(),pluginState_exports)),state=new PluginStateClient2;try{return await state.call(String(data2.plugin??""),data2.collection,data2.operation,data2,options)}finally{state.disconnect()}}if(action==="plugin_model"){let{PluginModelClient:PluginModelClient2}=await Promise.resolve().then(()=>(init_pluginModels2(),pluginModels_exports)),models=new PluginModelClient2;try{if(data2.operation==="capabilities")return await models.capabilities();if(data2.operation==="list")return await models.list(data2.provider);if(data2.operation==="start")return await models.start(String(data2.plugin??""),data2.request,data2.taskOptions??{});if(data2.operation==="run")return await models.run(String(data2.plugin??""),data2.request,data2.taskOptions??{});throw new Error("Invalid model operation")}finally{models.disconnect()}}if(action==="plugin_page"){let{PluginHostConnection:PluginHostConnection2}=await Promise.resolve().then(()=>(init_pluginHostConnection(),pluginHostConnection_exports)),{PluginPageClient:PluginPageClient2}=await Promise.resolve().then(()=>(init_pluginPages2(),pluginPages_exports)),connection=new PluginHostConnection2,pages=new PluginPageClient2({},connection);try{let pinned=["attach","activation"].includes(data2.operation)?await this.pinBrowserTarget(options):options;return await pages.call(String(data2.plugin??""),data2.operation,data2,pinned)}finally{pages.disconnect(),connection.disconnect()}}if(options.session&&options.session!=="new"){let session=await this.resolveControlSession(options.session,options),selected=decodeBrowserTarget(options.browser),pinned=decodeBrowserTarget(session.browser);if(options.browser&&(!selected||selected.browser!==pinned?.browser||selected.connector!==pinned?.connector))throw new Error("The selected browser does not match the control session");if(options.transport&&session.transport!==options.transport)throw new Error("A control session cannot change transport");options={...options,browser:session.browser,controlSessionId:session.id,...session.transport==="cdp"&&!pinned?.connector?{transport:"cdp"}:{}}}else if(options.session==="new"){if(!["tab_open","page_snapshot","page_screenshot"].includes(action))throw new Error("--session new requires tab_open, page_snapshot or page_screenshot");options={...options,controlSessionId:"new"}}if(action==="page_eval"&&data2.args!==void 0){let pinnedOptions={...options,...options.browser||!this.defaultBrowser?{}:{browser:this.defaultBrowser},...options.connector||!this.defaultConnector||decodeBrowserTarget(options.browser??this.defaultBrowser)?{}:{connector:this.defaultConnector}},targetPinned=!1;return invokePageEvalWithArgs(async(request,transfer)=>(transfer&&!targetPinned&&(pinnedOptions=await this.pinPageEvalTarget(pinnedOptions,request),targetPinned=!0),this.invokeRouted(action,request,pinnedOptions)),data2)}if(action==="page_upload"&&data2.files!==void 0&&(!Array.isArray(data2.files)||!data2.files.length||data2.files.some(file=>!file||typeof file.filePath=="string"==(typeof file.artifactId=="string"))))throw new Error("files requires exactly one filePath or artifactId per entry");if(action==="page_upload"&&Array.isArray(data2.files)&&data2.files.some(file=>file.filePath)){if(data2.filePaths)throw new Error("Use files or filePaths, not both");let staged=[],temporary=[];try{for(let file of data2.files)if(file.filePath){let uploaded=await stageFile(this,file.filePath,options);options=uploaded.options,temporary.push(uploaded.artifactId),staged.push({artifactId:uploaded.artifactId})}else staged.push(file);return await this.invokeRouted(action,{...data2,files:staged},options)}finally{for(let id of temporary)await this.invoke("__artifact_remove",{artifactId:id},options).catch(()=>{})}}return this.invokeRouted(action,data2,options)}saveArtifact(artifact,outputPath,options={}){return exportArtifact(this,artifact,outputPath,options)}async pinBrowserTarget(options={}){let selector=options.browser??this.defaultBrowser;if(decodeBrowserTarget(selector))return{...options,browser:selector};let listing=await this.invoke("browser_list",{},{...options,...options.connector||!this.defaultConnector?{}:{connector:this.defaultConnector}}),connected=listing.browsers.filter(browser=>browser.status==="connected"),matches=selector?findBrowsers(connected,selector):connected.filter(browser=>browser.browserId===listing.defaultBrowserId),target=matches.length?matches:selector?[]:connected;if(target.length!==1)throw new Error("Plugin pages require an explicit, connected and unambiguous browser target");let pinned={...options,browser:target[0].browserId};return delete pinned.connector,pinned}async pinPageEvalTarget(options,data2){if(decodeBrowserTarget(options.browser)&&!options.connector)return options;let local=options.local||options.transport==="cdp"||!this.options.serverUrl&&!options.connector;if(local){let resolved=resolveLocalActionTarget("page_eval",data2,{browser:options.browser,transport:options.transport});if(resolved?.socketPath)return{...options,socketPath:resolved.socketPath};if(resolved?.browser)return{...options,browser:encodeBrowserTarget({browser:resolved.browser})}}if(options.connector&&!options.browser){let timeoutSec=options.timeoutSec??this.options.requestTimeoutSec,connector=await this.resolveConnector(options.connector,timeoutSec),resolved=await this.requestRemote("__resolve_action_target",{action:"page_eval",data:data2},timeoutSec,void 0,connector.connectorId);if(!resolved?.browser)throw new Error("Cannot pin the connector browser for large page_eval arguments. Pass --browser <global-id>.");let pinned2={...options,browser:encodeBrowserTarget({browser:resolved.browser,connector:connector.connectorId})};return delete pinned2.connector,pinned2}let listing=await this.invokeRouted("browser_list",{},options),connected=listing.browsers.filter(browser2=>browser2.status==="connected"&&(!local||browser2.transport!=="provider")),implicitHost=options.local||options.transport==="cdp"||options.connector||!this.options.serverUrl,automatic=connected.find(browser2=>browser2.browserId===listing.defaultBrowserId)??(implicitHost||connected.length===1?connected[0]:void 0),candidates=options.browser?findBrowsers(listing.browsers,options.browser):automatic?[automatic]:[];if(candidates.length!==1)throw new Error("Large page_eval arguments require a unique connected browser. Pass --browser <global-id>.");let browser=candidates[0],pinned={...options,browser:browser.browserId};return delete pinned.connector,browser.transport==="cdp"&&!decodeBrowserTarget(browser.browserId)?.connector&&(pinned.transport="cdp"),pinned}async invokeRouted(action,data2={},options={}){validateRequiredActionTabId(action,data2);let timeoutSec=options.timeoutSec??resolveActionTimeoutSec(action,data2,this.options.requestTimeoutSec);if(options.socketPath)return this.invokeLocal(action,data2,timeoutSec,void 0,options.transport,options.controlSessionId,options.socketPath);if(action==="connector_list")return this.listConnectors(timeoutSec);if(action==="browser_list"){if(options.local||options.transport==="cdp")return this.listLocalBrowsers(timeoutSec,options.transport);let connector2=options.connector??this.defaultConnector;return connector2?this.listConnectorBrowsers(connector2,timeoutSec):this.listAllBrowsers(timeoutSec)}if(action==="browser_select_browser")return this.selectDefaultBrowser(data2,options,timeoutSec);if(options.local||options.transport==="cdp")return this.invokeExplicitLocal(action,data2,options,timeoutSec);let optionTarget=decodeBrowserTarget(options.browser),defaultTarget=options.browser?void 0:decodeBrowserTarget(this.defaultBrowser),closeTarget=action==="browser_close"&&typeof data2.browser=="string"?decodeBrowserTarget(data2.browser):void 0,target=optionTarget??closeTarget??defaultTarget,connector=target?.connector??options.connector??this.defaultConnector,browser=optionTarget?.browser??defaultTarget?.browser??(options.browser&&!optionTarget?options.browser:void 0)??(this.defaultBrowser&&!defaultTarget?this.defaultBrowser:void 0),requestData=closeTarget?{...data2,browser:closeTarget.browser}:data2;if(target&&!target.connector){if(options.connector)throw new Error("A local browser cannot be used together with --connector.");return this.invokeLocal(action,requestData,timeoutSec,target.browser,void 0,options.controlSessionId)}if(connector){let selected=target?.connector&&!options.connector&&!this.defaultConnector?{connectorId:target.connector,name:target.connector}:await this.resolveConnector(connector,timeoutSec);if(target?.connector&&selected.connectorId!==target.connector)throw new Error("The selected browser belongs to a different cloud connector.");return this.invokeRemote(action,requestData,timeoutSec,browser,selected,options.controlSessionId)}if(!this.options.serverUrl)return this.invokeLocal(action,requestData,timeoutSec,options.browser??this.defaultBrowser,void 0,options.controlSessionId);let selector=options.browser??this.defaultBrowser??(action==="browser_close"&&typeof data2.browser=="string"?data2.browser:void 0),resolved=await this.resolveUnifiedBrowser(selector,timeoutSec,action==="browser_close");if(resolved){if(action==="browser_close"){let nextOptions={...options};return delete nextOptions.browser,this.invoke(action,{...data2,browser:resolved},nextOptions)}return this.invoke(action,data2,{...options,browser:resolved})}if(action==="browser_launch")return this.invokeLaunchWithoutControlBrowser(data2,timeoutSec);throw new Error("No connected browser is available. Run `mearl browser_list` to inspect all sources.")}async invokeExplicitLocal(action,data2,options,timeoutSec){let optionTarget=decodeBrowserTarget(options.browser),defaultTarget=options.browser?void 0:decodeBrowserTarget(this.defaultBrowser),closeTarget=action==="browser_close"&&typeof data2.browser=="string"?decodeBrowserTarget(data2.browser):void 0;if(optionTarget?.connector||defaultTarget?.connector||closeTarget?.connector)throw new Error("A remote browser cannot be used together with --local or --cdp.");let browser=optionTarget?.browser??defaultTarget?.browser??options.browser??this.defaultBrowser,requestData=closeTarget?{...data2,browser:closeTarget.browser}:data2;return this.invokeLocal(action,requestData,timeoutSec,browser,options.transport,options.controlSessionId)}async invokeLaunchWithoutControlBrowser(data2,timeoutSec){let local=await this.tryLocalBrowserList(timeoutSec),discoveredConnectors=await this.listConnectors(timeoutSec).then(result=>result.connectors),localAvailable=local!==null,localConnectorId=localAvailable?loadLocalConnectorId():null,connectors=localConnectorId?discoveredConnectors.filter(connector=>connector.connectorId!==localConnectorId):discoveredConnectors;if(localAvailable&&connectors.length===0)return this.invokeLocal("browser_launch",data2,timeoutSec,void 0);if(!localAvailable&&connectors.length===1)return this.invokeRemote("browser_launch",data2,timeoutSec,void 0,connectors[0]);if(!localAvailable&&connectors.length===0)throw new Error("No browser host is available. Install @mearl/native-host locally or connect a cloud connector.");let availableHosts=[...localAvailable?["this machine [--local]"]:[],...connectors.map(connector=>`${connector.name} [${connector.connectorId}]`)].join(", ");throw new Error(`The browser host for browser_launch is ambiguous. Pass --local, --connector <id|name>, or --browser <global-id>. Available: ${availableHosts}`)}async selectDefaultBrowser(data2,options,timeoutSec){let selector=typeof data2.browser=="string"?data2.browser.trim():"";if(!selector)return this.defaultBrowser=void 0,this.defaultConnector=void 0,{selected:null,note:"Cleared the process-wide default browser."};let listing=await this.invoke("browser_list",{},{timeoutSec,...options.local?{local:!0}:{},...options.transport?{transport:options.transport}:{},...options.connector?{connector:options.connector}:{}}),matches=findBrowsers(listing.browsers,selector);if(matches.length>1)throw new Error(`Browser selector "${selector}" is ambiguous. Use an exact global browserId.`);let match=matches[0];if(!match)throw new Error(`No connected browser matches "${selector}".`);return this.defaultBrowser=match.browserId,this.defaultConnector=void 0,{selected:{browserId:match.browserId,name:match.name}}}async resolveUnifiedBrowser(selector,timeoutSec,includeDisconnected){let listing=await this.listAllBrowsers(timeoutSec);if(selector){let matches=findBrowsers(listing.browsers,selector,!includeDisconnected);if(matches.length>1)throw new Error(`Browser selector "${selector}" is ambiguous. Use an exact global browserId from browser_list.`);if(matches.length===0)throw new Error(`No browser matches "${selector}". Run \`mearl browser_list\`.`);return matches[0].browserId}if(listing.defaultBrowserId)return listing.defaultBrowserId;let connected=listing.browsers.filter(browser=>browser.status==="connected");if(connected.length===1)return connected[0].browserId;if(connected.length>1)throw new Error("Multiple browsers are connected and there is no unique default. Pass --browser <global-id>.")}async listConnectors(timeoutSec=this.options.requestTimeoutSec){return this.options.serverUrl?this.requestRemote("connector_list",{},timeoutSec,void 0,void 0):{count:0,connectors:[]}}async resolveConnector(selector,timeoutSec){let connectors=(await this.listConnectors(timeoutSec)).connectors,selection=resolveCloudConnectorSelector(connectors,selector),available=connectors.map(connector=>`${connector.name} [${connector.connectorId}]`).join(", ");if(selection.status==="ambiguous")throw new Error(`Cloud connector selector "${selector}" is ambiguous. Use an exact connectorId. Available: ${available}`);if(selection.status!=="matched")throw new Error(`No cloud connector matches "${selector}". Available: ${available}`);return selection.connector}async listLocalBrowsers(timeoutSec,transport){let result=await invoke("browser_list",{},{timeoutSec,...transport?{transport}:{},controlSource:"local"});return this.applyConfiguredDefault(this.decorateListing(result,{kind:"local"}))}async tryLocalBrowserList(timeoutSec){try{return await invoke("browser_list",{},{timeoutSec,controlSource:"local"})}catch{return null}}decorateListing(result,source){let browsers=(Array.isArray(result?.browsers)?result.browsers:[]).map(browser=>decorateBrowser(browser,source)),resultWarnings=Array.isArray(result?.warnings)?result.warnings.filter(warning=>typeof warning=="string"):[];return{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,defaultBrowserId:typeof result?.defaultBrowserId=="string"?encodeBrowserTarget({browser:result.defaultBrowserId,...source.connectorId?{connector:source.connectorId}:{}}):null,browsers,...resultWarnings.length>0?{warnings:resultWarnings}:{}}}applyConfiguredDefault(listing){if(!this.defaultBrowser)return listing;let matches=findBrowsers(listing.browsers,this.defaultBrowser);return{...listing,defaultBrowserId:matches.length===1?matches[0].browserId:null}}async listConnectorBrowsers(selector,timeoutSec){let connector=await this.resolveConnector(selector,timeoutSec),result=await this.requestRemote("browser_list",{},timeoutSec,void 0,connector.connectorId);return this.applyConfiguredDefault(this.decorateListing(result,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name}))}async listAllBrowsers(timeoutSec){let warnings=[],localPromise=this.tryLocalBrowserList(timeoutSec),connectors=[];if(this.options.serverUrl)try{connectors=(await this.listConnectors(timeoutSec)).connectors}catch(error2){warnings.push(`cloud-server: ${errorMessage(error2)}`)}let localResult=await localPromise;localResult||warnings.push("this machine: local browser runtime is unavailable");let localConnectorId=localResult?loadLocalConnectorId():null,remoteConnectors=localConnectorId?connectors.filter(connector=>connector.connectorId!==localConnectorId):connectors,settled=await Promise.allSettled(remoteConnectors.map(async connector=>({connector,listing:await this.requestRemote("browser_list",{},timeoutSec,void 0,connector.connectorId)}))),remoteListings=[];for(let index=0;index<settled.length;index+=1){let result=settled[index],connector=remoteConnectors[index];result.status==="fulfilled"?remoteListings.push(result.value):warnings.push(`${connector.name}: ${errorMessage(result.reason)}`)}let listings=[];localResult&&listings.push(this.decorateListing(localResult,{kind:"local"}));for(let{connector,listing}of remoteListings)listings.push(this.decorateListing(listing,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name}));for(let listing of listings)warnings.push(...listing.warnings??[]);let browsers=listings.flatMap(listing=>listing.browsers),defaults=listings.map(listing=>listing.defaultBrowserId).filter(browserId=>typeof browserId=="string"),defaultBrowserId=null;return this.defaultBrowser&&browsers.some(browser=>browser.browserId===this.defaultBrowser)?defaultBrowserId=this.defaultBrowser:defaults.length===1&&(defaultBrowserId=defaults[0]),this.applyConfiguredDefault({count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,defaultBrowserId,browsers,...warnings.length>0?{warnings}:{}})}async invokeLocal(action,data2,timeoutSec,browser,transport,controlSessionId,socketPath){let result=await invoke(action,data2,{timeoutSec,...browser?{browser}:{},...transport?{transport}:{},...socketPath?{socketPath}:{},controlSource:"local",...controlSessionId?{controlSessionId}:{}});return this.decorateActionResult(action,result,{kind:"local"})}async invokeRemote(action,data2,timeoutSec,browser,connector,controlSessionId){let result=await this.requestRemote(action,data2,timeoutSec,browser,connector.connectorId,controlSessionId);return this.decorateActionResult(action,result,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name})}decorateActionResult(action,result,source){if(result?.session?.sessionId){let browserId=encodeBrowserTarget({browser:result.session.browserId,...source.connectorId?{connector:source.connectorId}:{}});action!=="__control_session_resolve"&&this.controlSessions.set(result.session.sessionId,{browser:browserId,id:result.session.sessionId,transport:result.session.transport}),result={...result,session:{...result.session,browserId}}}return typeof result?.browserId=="string"&&action.startsWith("__artifact_")?{...result,browserId:encodeBrowserTarget({browser:result.browserId,...source.connectorId?{connector:source.connectorId}:{}})}:(result?.download?.browserId&&(result={...result,download:{...result.download,browserId:encodeBrowserTarget({browser:result.download.browserId,...source.connectorId?{connector:source.connectorId}:{}})}}),action!=="browser_launch"||typeof result?.browserId!="string"?result:decorateBrowser(result,source))}async resolveControlSession(id,options){if(!/^s_[A-Za-z0-9_-]{8}$/.test(id))throw new Error("Invalid session id; reuse session.sessionId from the first response");let cached=this.controlSessions.get(id);if(cached)return cached;let timeoutSec=options.timeoutSec??15,localLookup=this.invokeLocal("__control_session_resolve",{sessionId:id},timeoutSec,void 0),discover=async()=>{let{connectors}=await this.listConnectors(timeoutSec);return Promise.allSettled(connectors.map(connector=>this.invokeRemote("__control_session_resolve",{sessionId:id},timeoutSec,void 0,connector)))},[local,remote]=await Promise.allSettled([localLookup,this.options.serverUrl&&!options.local&&!options.transport?discover():Promise.resolve([])]),localSession=local.status==="fulfilled"?local.value?.session:void 0,localTarget=decodeBrowserTarget(localSession?.browserId),localConnectorId=localSession?.sessionId===id?loadLocalConnectorId():null,results=[local,...remote.status==="fulfilled"?remote.value:[remote]].filter(result=>{if(result===local||result.status==="rejected")return!0;let session2=result.value?.session,target2=decodeBrowserTarget(session2?.browserId);return!(localConnectorId&&target2?.connector===localConnectorId&&target2.browser===localTarget?.browser&&session2?.sessionId===id&&session2.transport===localSession.transport)}),sessions=results.flatMap(result=>result.status==="fulfilled"&&result.value?.session?.sessionId===id?[result.value.session]:[]),ambiguous=results.some(result=>result.status==="rejected"&&errorMessage(result.reason).startsWith("CONTROL_SESSION_AMBIGUOUS"));if(sessions.length>1||ambiguous)throw this.controlSessions.delete(id),new Error("CONTROL_SESSION_AMBIGUOUS: multiple hosts own this id");let session=sessions[0];if(!session){let errors=results.flatMap(result=>result.status==="rejected"?[errorMessage(result.reason)]:[]);throw new Error(`CONTROL_SESSION_NOT_FOUND: ${id}${errors.length?` (${errors.join("; ")})`:""}`)}let target={browser:session.browserId,id,transport:session.transport};return this.controlSessions.set(id,target),target}async ensureConnected(){if(this.ws?.readyState!==WebSocket.OPEN){if(this.connectPromise)return this.connectPromise;this.closing=!1,this.connectPromise=this.connect();try{await this.connectPromise}finally{this.connectPromise=null}}}connect(){return new Promise((resolve7,reject)=>{if(!this.options.serverUrl){reject(new Error("Cloud server URL is required. Run mearl-cloud-server status on the Agent machine. Resolution order: --server > MEARL_SERVER_URL > ~/.mearl/cloud-server.json."));return}let ws=new WebSocket(this.options.serverUrl);this.ws=ws;let settled=!1,timer=setTimeout(()=>{ws.close(),settled||reject(new Error(`Connection timeout after ${this.options.connectTimeoutSec}s`))},this.options.connectTimeoutSec*1e3);ws.on("open",()=>{settled=!0,clearTimeout(timer),ws.send(JSON.stringify({type:"agent_hello"})+`
997
- `),this.startHeartbeat(),resolve7()}),ws.on("message",data2=>this.handleMessage(data2)),ws.on("close",(code,reason)=>{clearTimeout(timer),this.rejectAllPending(new Error(`Connection closed (${code}: ${reason.toString()})`)),this.closing||(this.ws=null)}),ws.on("error",error2=>{clearTimeout(timer),settled||reject(error2)})})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping",timestamp:Date.now()})+`
998
- `)},this.options.heartbeatInterval*1e3)}handleMessage(data2){if(this.messageBuffer+=data2.toString("utf8"),this.messageBuffer.length>10485760){this.disconnect();return}let newlineIndex;for(;(newlineIndex=this.messageBuffer.indexOf(`
999
- `))!==-1;){let line=this.messageBuffer.slice(0,newlineIndex);if(this.messageBuffer=this.messageBuffer.slice(newlineIndex+1),!!line.trim())try{let message=JSON.parse(line);isHeartbeatMessage(message)||this.handleResponse(message)}catch{}}}handleResponse(response){let pending=this.pendingRequests.get(response.id);pending&&(this.pendingRequests.delete(response.id),clearTimeout(pending.timer),response.versionWarning&&console.warn(response.versionWarning),response.success?pending.resolve(response.data):pending.reject(new Error(response.error||"Unknown error from cloud-server")))}async requestRemote(action,data2,timeoutSec,browser,connector,controlSessionId){await this.ensureConnected();let ws=this.ws;if(!ws||ws.readyState!==WebSocket.OPEN)throw new Error("Connection is not open");let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`,message={id,action,data:data2,timeoutSec};browser&&(message.browser=browser),connector&&(message.connector=connector),controlSessionId&&(message.controlSessionId=controlSessionId);let serialized=`${JSON.stringify(message)}
1000
- `,bytes=Buffer.byteLength(serialized,"utf8");if(bytes>10485760)throw new Error(`Cloud request exceeds ${10485760} byte message limit (${bytes} bytes)`);return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{this.pendingRequests.delete(id),reject(new Error(`Request timeout after ${timeoutSec}s`))},timeoutSec*1e3+RESPONSE_GRACE_MS);this.pendingRequests.set(id,{resolve:resolve7,reject,timer}),ws.send(serialized)})}rejectAllPending(error2){for(let pending of this.pendingRequests.values())clearTimeout(pending.timer),pending.reject(error2);this.pendingRequests.clear()}}}});var init_process_env=__esm({"../agent-runtime/dist/process-env.js"(){"use strict";init_dist()}});import fs6 from"node:fs";import{spawn as spawn8}from"node:child_process";import path6 from"node:path";function agentExecutableCandidatePaths({executableNames,configuredPath,env=process.env,extraUserCandidates=[],home,platform=process.platform,processExecPath=process.execPath,readdirSync:readdirSync8}){let pathKey=Object.keys(env).find(key2=>key2.toLowerCase()==="path")||"PATH",pathCandidates=(env[pathKey]||"").split(path6.delimiter).filter(Boolean).flatMap(directory=>executableNames.map(name=>path6.join(directory,name))),commonUserDirectories=[path6.join(home,".local","bin"),path6.join(home,".npm-global","bin"),path6.join(home,".volta","bin"),path6.join(home,".local","share","pnpm"),path6.join(home,"Library","pnpm"),path6.join(home,".bun","bin"),...platform==="win32"&&env.APPDATA?[path6.join(env.APPDATA,"npm")]:[]],systemDirectories=platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"];return[configuredPath,...executableNames.map(name=>path6.join(path6.dirname(processExecPath),name)),...commonUserDirectories.flatMap(directory=>executableNames.map(name=>path6.join(directory,name))),...extraUserCandidates,...versionManagerExecutableCandidates(home,executableNames,{env,platform,readdirSync:readdirSync8}),...systemDirectories.flatMap(directory=>executableNames.map(name=>path6.join(directory,name))),...pathCandidates].filter(candidate=>typeof candidate=="string")}function executableFileCandidates(candidates){let seen=new Set,executableCandidates=[];for(let candidate of candidates)!candidate||seen.has(candidate)||(seen.add(candidate),isExecutableFile(candidate)&&executableCandidates.push(candidate));return executableCandidates}function probeAgentExecutable(executable,options){return new Promise(resolve7=>{let settled=!1,stderr="",launch=resolveSpawnCommand(executable,options.args),child=spawn8(launch.command,launch.args,{stdio:["ignore","ignore","pipe"],windowsHide:!0,env:prependNodePath()}),finish=error2=>{settled||(settled=!0,clearTimeout(timer),resolve7(error2))},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(options.timeoutError)},options.timeoutMs);child.stderr?.on("data",chunk=>{stderr.length<4e3&&(stderr+=chunk.toString("utf8"))}),child.once("error",error2=>finish(options.startError(error2))),child.once("exit",code=>{if(code===0){finish(null);return}finish(stderr.trim()||options.exitError(code))})})}function isExecutableFile(candidate){try{return fs6.accessSync(candidate,process.platform==="win32"?fs6.constants.F_OK:fs6.constants.X_OK),fs6.statSync(candidate).isFile()}catch{return!1}}var AgentExecutableResolver,init_executable_resolver=__esm({"../agent-runtime/dist/executable-resolver.js"(){"use strict";init_process_env();AgentExecutableResolver=class{options;resolvedExecutable=null;resolutionPromise=null;generation=0;constructor(options){this.options=options}async resolve(){if(this.resolvedExecutable){if(isExecutableFile(this.resolvedExecutable))return{executable:this.resolvedExecutable,error:null};this.resolvedExecutable=null}if(this.resolutionPromise)return this.resolutionPromise;let generation=this.generation,resolution=this.probeCandidates(generation);this.resolutionPromise=resolution;try{return await resolution}finally{this.resolutionPromise===resolution&&(this.resolutionPromise=null)}}reset(){this.generation+=1,this.resolvedExecutable=null,this.resolutionPromise=null}async probeCandidates(generation){let candidates=this.options.candidates();if(candidates.length===0)return{executable:null,error:this.options.notFoundError};let failures=[],recordFailure=(executable,error2)=>{failures.push({executable,error:error2}),this.options.onFailure?.(executable,error2)},select=(executable,version2)=>(this.generation===generation&&(this.resolvedExecutable=executable,this.options.onSelection?.(executable,version2)),{executable,error:null}),preferredCandidates=this.options.preferred?candidates.filter(executable=>this.options.preferred?.(executable)):[],automaticCandidates=candidates.filter(executable=>!preferredCandidates.includes(executable));for(let executable of preferredCandidates){let error2=await this.options.probe(executable);if(error2===null)return select(executable,null);recordFailure(executable,error2)}let getVersion=this.options.getVersion;if(getVersion){let inspected=await Promise.all(automaticCandidates.map(async(executable,index)=>{let[error2,version2]=await Promise.all([this.options.probe(executable),getVersion(executable).catch(()=>null)]);return{executable,error:error2,index,version:version2}})),usable=inspected.filter(candidate=>candidate.error===null);for(let candidate of inspected)candidate.error!==null&&recordFailure(candidate.executable,candidate.error);usable.sort((left,right)=>{if(left.version&&right.version&&this.options.compareVersions){let comparison=this.options.compareVersions(left.version,right.version);if(comparison!==0)return-comparison}else{if(left.version)return-1;if(right.version)return 1}return left.index-right.index});let selected=usable[0];if(selected)return select(selected.executable,selected.version)}else for(let executable of automaticCandidates){let error2=await this.options.probe(executable);if(error2===null)return select(executable,null);recordFailure(executable,error2)}let detail=failures.map(({executable,error:error2})=>{let compactError=error2.replace(/\s+/g," ").trim().slice(0,300);return`${executable}: ${compactError}`}).join("; ");return{executable:null,error:`${this.options.unusableError} ${detail}`}}}}});import fs7 from"node:fs";import os3 from"node:os";import path7 from"node:path";import readline from"node:readline";import{spawn as spawn9}from"node:child_process";function configOverride(value){return Array.isArray(value)?value.map(configOverride):value&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([,field])=>field!=null).map(([key2,field])=>[key2,configOverride(field)])):value}function normalizeCodexVersion(value){return typeof value!="string"||value.length>MAX_VERSION_OUTPUT_CHARS?null:CODEX_VERSION_PATTERN.exec(value.trim())?.[1]??null}function parsedCodexVersion(value){let normalized=normalizeCodexVersion(value);if(!normalized)return null;let withoutBuild=normalized.split("+",1)[0],prereleaseSeparator=withoutBuild.indexOf("-"),coreValue=prereleaseSeparator===-1?withoutBuild:withoutBuild.slice(0,prereleaseSeparator),prereleaseValue=prereleaseSeparator===-1?void 0:withoutBuild.slice(prereleaseSeparator+1),core=coreValue?.split(".").map(Number);return core?.length!==3||core.some(component=>!Number.isSafeInteger(component)||component<0)?null:{core,prerelease:prereleaseValue?prereleaseValue.split("."):[]}}function compareCodexVersions(leftValue,rightValue){let left=parsedCodexVersion(leftValue),right=parsedCodexVersion(rightValue);if(!left||!right)return leftValue.localeCompare(rightValue,void 0,{numeric:!0});for(let index=0;index<left.core.length;index+=1){let difference=left.core[index]-right.core[index];if(difference!==0)return difference}if(left.prerelease.length===0||right.prerelease.length===0)return left.prerelease.length===right.prerelease.length?0:left.prerelease.length===0?1:-1;let identifierCount=Math.max(left.prerelease.length,right.prerelease.length);for(let index=0;index<identifierCount;index+=1){let leftIdentifier=left.prerelease[index],rightIdentifier=right.prerelease[index];if(leftIdentifier===void 0||rightIdentifier===void 0)return leftIdentifier===rightIdentifier?0:leftIdentifier===void 0?-1:1;if(leftIdentifier===rightIdentifier)continue;let leftNumeric=/^\d+$/.test(leftIdentifier),rightNumeric=/^\d+$/.test(rightIdentifier);return leftNumeric&&rightNumeric?Number(leftIdentifier)-Number(rightIdentifier):leftNumeric!==rightNumeric?leftNumeric?-1:1:leftIdentifier.localeCompare(rightIdentifier)}return 0}function codexAppExecutableCandidatePaths(options={}){let env=options.env??process.env,home=(options.homedir??os3.homedir)(),platform=options.platform??process.platform;return platform==="darwin"?["/Applications",path7.join(home,"Applications")].flatMap(root=>["ChatGPT.app","Codex.app"].flatMap(app=>{let resources=path7.join(root,app,"Contents","Resources");return[path7.join(resources,"codex-cli","CodexCLI.app","Contents","MacOS","codex"),path7.join(resources,"codex")]})):platform==="win32"?[path7.join(env.LOCALAPPDATA||path7.join(home,"AppData","Local"),"Programs"),env.ProgramFiles,env["ProgramFiles(x86)"]].filter(root=>typeof root=="string"&&root.length>0).flatMap(root=>["ChatGPT","Codex"].map(app=>path7.join(root,app,"resources","codex.exe"))):[]}function isIdeBundledCodexPath(candidate,home){let resolvedCandidates=[path7.resolve(candidate)];try{resolvedCandidates.push(fs7.realpathSync(candidate))}catch{}return[".vscode",".vscode-insiders",".cursor",".windsurf"].some(directory=>{let extensionsRoot=`${path7.join(home,directory,"extensions")}${path7.sep}`;return resolvedCandidates.some(resolved=>resolved.startsWith(extensionsRoot))})}function codexExecutableCandidatePaths(options={}){let env=options.env??process.env,home=(options.homedir??os3.homedir)(),platform=options.platform??process.platform;return agentExecutableCandidatePaths({executableNames:[platform==="win32"?"codex.cmd":"codex"],configuredPath:env.MEARL_CODEX_PATH,env,home,platform,processExecPath:options.processExecPath,readdirSync:options.readdirSync,extraUserCandidates:codexAppExecutableCandidatePaths({env,homedir:()=>home,platform})}).filter(candidate=>candidate===env.MEARL_CODEX_PATH||!isIdeBundledCodexPath(candidate,home))}function codexPackageVersion(executable){let packageFiles=[];try{let resolved=fs7.realpathSync(executable);if(resolved.split(path7.sep).includes("node_modules")){let directory=path7.dirname(resolved);for(let depth=0;depth<6;depth+=1){packageFiles.push(path7.join(directory,"package.json"));let parent=path7.dirname(directory);if(parent===directory)break;directory=parent}}}catch{}/\.(?:cmd|bat)$/i.test(executable)&&packageFiles.push(path7.join(path7.dirname(executable),"node_modules","@openai","codex","package.json"));for(let packageFile of packageFiles)try{let manifest=JSON.parse(fs7.readFileSync(packageFile,"utf8"));if(manifest.name==="@openai/codex"){let version2=normalizeCodexVersion(manifest.version);if(version2)return version2}}catch{}return null}function codexExecutableVersion(executable){let packageVersion=codexPackageVersion(executable);return packageVersion?Promise.resolve(packageVersion):new Promise(resolve7=>{let settled=!1,output="",launch=resolveSpawnCommand(executable,["--version"]),child=spawn9(launch.command,launch.args,{stdio:["ignore","pipe","pipe"],windowsHide:!0,env:prependNodePath()}),finish=version2=>{settled||(settled=!0,clearTimeout(timer),resolve7(version2))},capture=chunk=>{let remaining=MAX_VERSION_OUTPUT_CHARS-output.length;remaining>0&&(output+=chunk.toString("utf8").slice(0,remaining))};child.stdout.on("data",capture),child.stderr.on("data",capture),child.once("error",()=>finish(null)),child.once("exit",code=>finish(code===0?normalizeCodexVersion(output):null));let timer=setTimeout(()=>{child.kill("SIGTERM"),finish(null)},PROBE_TIMEOUT_MS)})}function codexModelInfo(value){if(typeof value!="string")return;let id=value.trim().slice(0,MAX_MODEL_CHARS);return id?{id}:void 0}function fullAccessWithApprovals(){return{sandbox:"danger-full-access",approvalPolicy:"untrusted"}}function timestampMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e12?value*1e3:value;if(typeof value=="string"){let parsed=Date.parse(value);return Number.isNaN(parsed)?void 0:parsed}}function codexSkillScope(value){return value==="user"?"global":value==="repo"?"project":value==="system"||value==="admin"?value:"unknown"}function userMessageText(item){return Array.isArray(item?.content)?item.content.flatMap(part=>part?.type==="text"&&typeof part.text=="string"?[part.text]:[]).join(`
1001
- `):""}function userMessageImageCount(item){return Array.isArray(item?.content)?item.content.filter(part=>part?.type==="image"||part?.type==="localImage").length:0}function threadHistoryEvents(thread){if(!Array.isArray(thread?.turns))return[];let events=[];for(let turn of thread.turns.slice(-100)){if(!turn||typeof turn.id!="string"||!Array.isArray(turn.items))continue;let timestamp=timestampMs(turn.completedAt??turn.startedAt);for(let item of turn.items)if(!(!item||typeof item.id!="string"||typeof item.type!="string")){if(item.type==="userMessage"){let text3=userMessageText(item),imageCount=userMessageImageCount(item);(text3||imageCount>0)&&events.push({kind:"lifecycle",method:"chat/userMessage",params:{text:text3,...imageCount>0?{imageCount}:{}},...timestamp!==void 0?{timestamp}:{}});continue}events.push({kind:"notification",method:"item/completed",params:{turnId:turn.id,item},...timestamp!==void 0?{timestamp}:{}})}}return events}function codexThreadUrl(providerSessionId){if(!/^[a-zA-Z0-9_-]+$/.test(providerSessionId))throw new Error("Codex returned an invalid thread id");return`codex://threads/${providerSessionId}`}function codexWorkspaceUrl(directory){return`codex://threads/new?path=${encodeURIComponent(directory)}`}function externalOpenCommand(url,platform=process.platform){return platform==="darwin"?{command:"open",args:[url]}:platform==="win32"?{command:"cmd.exe",args:["/d","/s","/c","start","",url]}:{command:"xdg-open",args:[url]}}function openExternalUrl(url){let{command,args}=externalOpenCommand(url);return new Promise((resolve7,reject)=>{let child=spawn9(command,args,{stdio:"ignore",windowsHide:!0});child.once("error",error2=>{reject(new Error(`Unable to open Codex App: ${error2.message}`))}),child.once("close",code=>{code===0?resolve7():reject(new Error("Unable to open Codex App. Make sure it is installed."))})})}var REQUEST_TIMEOUT_MS,PROBE_TIMEOUT_MS,MAX_MODEL_CHARS,MAX_VERSION_OUTPUT_CHARS,CODEX_NOT_FOUND_ERROR,CODEX_VERSION_PATTERN,CodexAgentProvider,init_codex_provider=__esm({"../agent-runtime/dist/codex-provider.js"(){"use strict";init_executable_resolver();init_process_env();REQUEST_TIMEOUT_MS=3e4,PROBE_TIMEOUT_MS=5e3,MAX_MODEL_CHARS=256,MAX_VERSION_OUTPUT_CHARS=1024,CODEX_NOT_FOUND_ERROR="Codex was not found. Install @openai/codex, install the Codex App, or set MEARL_CODEX_PATH.",CODEX_VERSION_PATTERN=/^(?:codex-cli\s+)?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/;CodexAgentProvider=class{log;clientVersion;mearlSocketPath;id="codex";process=null;initialized=!1;lifecycle=0;modelRuntime;startPromise=null;nextRequestId=1;pendingRequests=new Map;listeners=new Set;knownThreadIds=new Set;sessionModels=new Map;executableResolver;constructor(log,clientVersion,mearlSocketPath){this.log=log,this.clientVersion=clientVersion,this.mearlSocketPath=mearlSocketPath,this.executableResolver=new AgentExecutableResolver({candidates:()=>this.resolveExecutableCandidates(),probe:executable=>this.probeExecutable(executable),getVersion:executable=>this.readExecutableVersion(executable),compareVersions:compareCodexVersions,preferred:executable=>executable===process.env.MEARL_CODEX_PATH,notFoundError:CODEX_NOT_FOUND_ERROR,unusableError:"Codex candidates were found, but none supports app-server.",onFailure:(executable,error2)=>{this.log("[Codex] Skipping unusable runtime:",executable,error2)},onSelection:(executable,version2)=>{this.modelRuntime={executable,...version2?{version:version2}:{},selection:executable===process.env.MEARL_CODEX_PATH?"explicit":"automatic",started:!1},this.modelDiagnostic({runtime:this.modelRuntime}),this.log("[Codex] Selected runtime:",executable,version2?`(version ${version2})`:executable===process.env.MEARL_CODEX_PATH?"(explicitly configured)":"(version unavailable)")}})}async getDescriptor(){let{error:error2}=await this.resolveExecutable();return{id:this.id,name:"Codex",available:error2===null,capabilities:{streaming:!0,resume:!0,listSessions:!0,refreshHistory:!0,imageInput:!0,interrupt:!0,requests:!0},...error2?{error:error2}:{},setup:{installCommand:"npm install -g @openai/codex",loginCommand:"codex login",docsUrl:"https://developers.openai.com/codex/cli"}}}async prepare(){await this.ensureStarted()}async listModels(){await this.ensureStarted();let models=new Map,cursor,cursors=new Set;for(let page=0;page<4;page++){let result=await this.request("model/list",{limit:100,...cursor?{cursor}:{}});if(!Array.isArray(result?.data))throw new Error("Invalid Codex model list");for(let value of result.data){let id=value?.model??value?.id;if(value?.hidden||typeof id!="string"||!id||id.length>256||models.has(id))continue;let efforts=["none","minimal","low","medium","high","xhigh","max"],reasoningEfforts=Array.isArray(value.supportedReasoningEfforts)?efforts.filter(effort=>value.supportedReasoningEfforts.some(option=>option?.reasoningEffort===effort)):void 0;if(models.set(id,{id,displayName:typeof value.displayName=="string"?value.displayName.slice(0,256):id,...typeof value.description=="string"?{description:value.description.slice(0,2e3)}:{},isDefault:value.isDefault===!0,...reasoningEfforts?{reasoningEfforts}:{},...efforts.includes(value.defaultReasoningEffort)?{defaultReasoningEffort:value.defaultReasoningEffort}:{}}),models.size>=200)break}if(!result.nextCursor||models.size>=200)break;if(typeof result.nextCursor!="string"||cursors.has(result.nextCursor))throw new Error("Invalid Codex model cursor");cursor=result.nextCursor,cursors.add(result.nextCursor)}return[...models.values()]}onEvent(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}async listSessions(options){await this.ensureStarted();let result=await this.request("thread/list",{cursor:options.cursor??null,limit:options.limit,sortKey:"updated_at",sortDirection:"desc",archived:!1,...options.cwd?{cwd:options.cwd}:{}});return{sessions:Array.isArray(result?.data)?result.data.flatMap(thread=>{if(!thread||typeof thread.id!="string")return[];let title=typeof thread.name=="string"&&thread.name.trim()?thread.name.trim():typeof thread.preview=="string"&&thread.preview.trim()?thread.preview.trim():void 0,cwd=typeof thread.cwd=="string"?thread.cwd:void 0,updatedAt=timestampMs(thread.recencyAt??thread.updatedAt),ephemeral=typeof thread.ephemeral=="boolean"?thread.ephemeral:void 0;return[{providerSessionId:thread.id,...title?{title}:{},...cwd?{cwd}:{},...updatedAt!==void 0?{updatedAt}:{},...ephemeral!==void 0?{ephemeral}:{}}]}):[],...typeof result?.nextCursor=="string"?{nextCursor:result.nextCursor}:{}}}async listSkills(cwd){await this.ensureStarted();let result=await this.request("skills/list",{cwds:[cwd||os3.homedir()],forceReload:!0});return Array.isArray(result?.data)?result.data.flatMap(entry=>Array.isArray(entry?.skills)?entry.skills.flatMap(skill=>!skill||typeof skill.name!="string"||typeof skill.path!="string"?[]:[{name:skill.name,path:skill.path,scope:codexSkillScope(skill.scope)}]):[]):[]}async startSession(options){await this.ensureStarted();let cwd=options.cwd||process.env.MEARL_AGENT_CWD||os3.homedir(),config=options.modelExecution?await this.modelExecutionConfig():void 0,result=await this.request("thread/start",{...config?{config}:{},cwd,...options.modelId?{model:options.modelId}:{},...options.readOnly?{sandbox:"read-only",approvalPolicy:"never"}:fullAccessWithApprovals(),...options.ephemeral!==void 0?{ephemeral:options.ephemeral}:{},...options.developerInstructions?{developerInstructions:options.developerInstructions}:{}}),threadId=result?.thread?.id;if(typeof threadId!="string"||!threadId)throw new Error("Codex did not return a thread id");options.modelExecution&&this.modelDiagnostic({threadRestrictionsAccepted:!0}),this.knownThreadIds.add(threadId);let model=codexModelInfo(result?.model);return model&&this.sessionModels.set(threadId,model),threadId}async modelExecutionConfig(){let config=(await this.request("config/read",{includeLayers:!1}))?.config;if(!config||typeof config!="object")throw new Error("Codex cannot report its effective execution configuration");let home=process.env.CODEX_HOME||path7.join(os3.homedir(),".codex"),store=config.cli_auth_credentials_store;this.modelDiagnostic({configuration:{source:process.env.CODEX_HOME?"environment":"default",home,filePresent:fs7.existsSync(path7.join(home,"config.toml")),...typeof config.model_provider=="string"?{baseProvider:config.model_provider}:{},...typeof store=="string"?{credentialStore:["file","keyring","auto","ephemeral"].includes(store)?store:"unknown"}:{}}});let mcp=config.mcp_servers??{},apps=config.apps??{};if(typeof mcp!="object"||Array.isArray(mcp)||typeof apps!="object"||Array.isArray(apps))throw new Error("Invalid Codex model tool configuration");return configOverride({mcp_servers:Object.fromEntries(Object.keys(mcp).map(name=>[name,{...mcp[name],enabled:!1}])),apps:Object.fromEntries(["_default",...Object.keys(apps)].map(name=>[name,{...apps[name]??{},enabled:!1}])),web_search:"disabled",features:{apps:!1,plugins:!1,hooks:!1,codex_hooks:!1,plugin_hooks:!1,multi_agent:!1,multi_agent_v2:!1,collab:!1,computer_use:!1,browser_use:!1,image_generation:!1,imagegenext:!1,memory_tool:!1,memories:!1,skill_search:!1}})}async resumeSession(providerSessionId,options){await this.ensureStarted();let result=await this.request("thread/resume",{threadId:providerSessionId,...options.cwd?{cwd:options.cwd}:{},...fullAccessWithApprovals(),...options.developerInstructions?{developerInstructions:options.developerInstructions}:{}}),threadId=result?.thread?.id;if(typeof threadId!="string"||!threadId)throw new Error("Codex did not return a resumed thread id");this.knownThreadIds.add(threadId);let model=codexModelInfo(result?.model);return model&&this.sessionModels.set(threadId,model),{providerSessionId:threadId,history:threadHistoryEvents(result.thread),historyComplete:!0}}getSessionModel(providerSessionId){let model=this.sessionModels.get(providerSessionId);return model?{...model}:void 0}async sendMessage(providerSessionId,message,images=[],options={}){await this.ensureStarted();let turnId=(await this.request("turn/start",{threadId:providerSessionId,input:[...message?[{type:"text",text:message,text_elements:[]}]:[],...images.map(image=>({type:"image",url:`data:${image.mimeType};base64,${image.data}`}))],summary:options.reasoningSummary??"detailed",...options.outputSchema?{outputSchema:options.outputSchema}:{},...options.modelExecution?{approvalPolicy:"never",sandboxPolicy:{type:"readOnly",networkAccess:!1}}:{},...options.reasoningEffort?{effort:options.reasoningEffort}:{}}))?.turn?.id;if(typeof turnId!="string"||!turnId)throw new Error("Codex did not return a turn id");return options.modelExecution&&this.modelDiagnostic({turnRestrictionsAccepted:!0}),{turnId}}async interrupt(providerSessionId,turnId){await this.ensureStarted(),await this.request("turn/interrupt",{threadId:providerSessionId,turnId})}async closeSession(providerSessionId){this.knownThreadIds.delete(providerSessionId),this.sessionModels.delete(providerSessionId),this.initialized&&this.request("thread/unsubscribe",{threadId:providerSessionId}).catch(error2=>{this.log("[Codex] Unable to unsubscribe thread:",String(error2))})}openSession(providerSessionId){return openExternalUrl(codexThreadUrl(providerSessionId))}openWorkspace(cwd){return openExternalUrl(codexWorkspaceUrl(cwd))}respondToRequest(requestId,result){this.write({id:requestId,result})}dispose(){this.lifecycle++,this.rejectPending(new Error("Codex provider disposed"));let child=this.process;this.process=null,this.initialized=!1,this.startPromise=null,this.sessionModels.clear(),this.executableResolver.reset(),child&&!child.killed&&child.kill("SIGTERM")}async ensureStarted(){if(this.process&&!this.process.killed&&this.initialized)return;if(this.startPromise)return this.startPromise;this.process&&!this.process.killed&&(this.process.kill("SIGTERM"),this.process=null);let pending=this.start();this.startPromise=pending;try{await pending}catch(error2){throw this.startPromise===pending&&(this.startPromise=null),error2}}async start(){let lifecycle=this.lifecycle,resolution=await this.resolveExecutable();if(lifecycle!==this.lifecycle)throw new Error("Codex provider disposed during startup");if(resolution.executable===null)throw new Error(resolution.error);let{executable}=resolution,launch=resolveSpawnCommand(executable,["app-server","--listen","stdio://"]),childEnv=prependNodePath();this.mearlSocketPath&&(childEnv.MEARL_SOCKET_PATH=this.mearlSocketPath);let child=spawn9(launch.command,launch.args,{stdio:["pipe","pipe","pipe"],windowsHide:!0,env:childEnv});this.process=child,readline.createInterface({input:child.stdout}).on("line",line=>this.handleLine(line)),child.stderr.on("data",chunk=>{let message=chunk.toString("utf8").trim();message&&this.log("[Codex]",message)}),child.once("error",error2=>this.handleExit(child,error2)),child.once("exit",(code,signal)=>{this.handleExit(child,new Error(`Codex app-server exited (code=${String(code)}, signal=${String(signal)})`))});try{await this.request("initialize",{clientInfo:{name:"mearl",title:"Mearl",version:this.clientVersion},capabilities:{experimentalApi:!0}}),this.write({method:"initialized",params:{}}),this.initialized=!0,this.modelRuntime&&(this.modelRuntime={...this.modelRuntime,started:!0},this.modelDiagnostic({runtime:this.modelRuntime}))}catch(error2){let startupError=error2 instanceof Error?error2:new Error(String(error2));throw this.handleExit(child,startupError),child.killed||child.kill("SIGTERM"),startupError}}handleLine(line){let message;try{message=JSON.parse(line)}catch{this.log("[Codex] Invalid JSONL message:",line);return}if(message.method){let isRequest=message.id!==void 0,providerSessionId=this.extractThreadId(message.params);if(!isRequest&&providerSessionId&&message.method==="thread/settings/updated"){let model=codexModelInfo(message.params?.threadSettings?.model);model&&(this.sessionModels.set(providerSessionId,model),this.emit({providerSessionId,kind:"notification",method:"session/model/updated",params:{model}}))}else if(!isRequest&&providerSessionId&&message.method==="model/rerouted"){let model=codexModelInfo(message.params?.toModel);model&&this.emit({providerSessionId,kind:"notification",method:"session/activeModel/updated",params:{model}})}this.emit({providerSessionId,kind:isRequest?"request":message.method==="error"?"error":"notification",method:message.method,params:message.params??{},...isRequest?{requestId:message.id}:{}});return}if(typeof message.id!="number")return;let pending=this.pendingRequests.get(message.id);pending&&(clearTimeout(pending.timer),this.pendingRequests.delete(message.id),message.error?pending.reject(new Error(message.error.message||`Codex error ${message.error.code??""}`)):pending.resolve(message.result))}request(method,params){let id=this.nextRequestId++;return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{this.pendingRequests.delete(id),reject(new Error(`Codex request timed out: ${method}`))},REQUEST_TIMEOUT_MS);this.pendingRequests.set(id,{resolve:resolve7,reject,timer});try{this.write({id,method,params})}catch(error2){clearTimeout(timer),this.pendingRequests.delete(id),reject(error2 instanceof Error?error2:new Error(String(error2)))}})}write(message){let child=this.process;if(!child||child.killed||!child.stdin.writable)throw new Error("Codex app-server is not running");child.stdin.write(`${JSON.stringify(message)}
1002
- `)}handleExit(child,error2){if(this.process===child){this.process=null,this.initialized=!1,this.startPromise=null,this.executableResolver.reset(),this.rejectPending(error2);for(let providerSessionId of this.knownThreadIds)this.emit({providerSessionId,kind:"error",method:"provider/exited",params:{message:error2.message}})}}rejectPending(error2){for(let[id,pending]of this.pendingRequests)clearTimeout(pending.timer),pending.reject(error2),this.pendingRequests.delete(id)}modelDiagnostic(metadata){this.emit({kind:"notification",method:"provider/model/diagnostic",params:metadata})}emit(event){for(let listener of this.listeners)listener(event)}extractThreadId(params){return[params?.threadId,params?.conversationId,params?.thread?.id,params?.turn?.threadId].find(value=>typeof value=="string")}probeExecutable(executable){return probeAgentExecutable(executable,{args:["app-server","--help"],timeoutMs:PROBE_TIMEOUT_MS,timeoutError:"Timed out while checking Codex app-server availability.",startError:error2=>`Failed to start Codex: ${error2.message}`,exitError:code=>`Codex app-server check exited with code ${String(code)}`})}readExecutableVersion(executable){return codexExecutableVersion(executable)}resolveExecutable(){return this.executableResolver.resolve()}resolveExecutableCandidates(){return executableFileCandidates(codexExecutableCandidatePaths())}}}});import{readFileSync as readFileSync17}from"node:fs";async function runCodexModel(request,context,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync17(new URL("../package.json",import.meta.url),"utf8")).version)){if(request.provider!=="codex"||request.mode!=="agent"||request.permissions!=="read-only")throw Object.assign(new Error("Codex supports explicit read-only agent execution; strict tool-free generation is unavailable"),{code:"PLUGIN_MODEL_CAPABILITY_UNSUPPORTED"});context.signal.throwIfAborted();let session,turn,text3,bytes=0,index=0,retries=0,buffered="",streamItem,streamPhase,phases=new Map,flushTimer,flush=()=>{clearTimeout(flushTimer),flushTimer=void 0;try{for(let offset2=0;offset2<buffered.length;offset2+=4e3)streamItem||streamPhase?context.onDelta(buffered.slice(offset2,offset2+4e3),++index,{...streamItem?{itemId:streamItem}:{},...streamPhase?{phase:streamPhase}:{}}):context.onDelta(buffered.slice(offset2,offset2+4e3),++index)}catch(error2){fail2(error2)}buffered=""},finish,fail2,completed=new Promise((resolve7,reject)=>{finish=resolve7,fail2=reject});completed.catch(()=>{});let listener=event=>{let params=event.params;event.method==="provider/model/diagnostic"&&context.onDiagnostic?.(params),event.method==="account/updated"&&context.onDiagnostic?.({authentication:["apikey","chatgpt","chatgptAuthTokens"].includes(params?.authMode)?params.authMode:"unknown"}),event.method==="session/model/updated"&&typeof params?.model?.id=="string"&&context.onDiagnostic?.({selectedModel:params.model.id}),event.method==="session/activeModel/updated"&&typeof params?.model?.id=="string"&&context.onDiagnostic?.({activeModel:params.model.id});let relevant=event.providerSessionId===void 0||event.providerSessionId===session;if(event.kind==="request"&&relevant){try{provider.respondToRequest(event.requestId,{error:"Interactive requests are disabled for background model tasks"})}catch{}fail2(Object.assign(new Error("Model requested interactive input"),{code:"PLUGIN_MODEL_INTERACTION_REQUIRED"})),provider.dispose();return}if((event.kind==="error"||event.method==="provider/exited")&&relevant){if(event.method!=="provider/exited"&&params?.willRetry===!0){context.onDiagnostic?.({retryCount:++retries});return}fail2(Object.assign(new Error(String(params?.error?.message??params?.message??"Model provider failed")),{code:"PLUGIN_MODEL_PROVIDER_ERROR"})),provider.dispose();return}if(!(!session||event.providerSessionId!==session))if(event.method==="item/started"&&params?.item?.type==="agentMessage")flush(),streamItem=params.item.id,streamPhase=params.item.phase,streamItem&&streamPhase&&phases.set(streamItem,streamPhase);else if(event.method==="item/agentMessage/delta"&&typeof params?.delta=="string"){let itemId=params.itemId??streamItem,phase=params.phase??(itemId?phases.get(itemId):streamPhase);if((itemId!==streamItem||phase!==streamPhase)&&flush(),streamItem=itemId,streamPhase=phase,bytes+=Buffer.byteLength(params.delta),bytes>32*1024*1024){fail2(new Error("Model output exceeds 32 MiB"));return}buffered+=params.delta,buffered.length>=16e3?flush():flushTimer??=setTimeout(flush,50)}else if(event.method==="item/completed"&&params?.item?.type==="agentMessage"&&typeof params.item.text=="string"){if(flush(),Buffer.byteLength(params.item.text)>32*1024*1024){fail2(new Error("Model output exceeds 32 MiB"));return}(!params.item.phase||params.item.phase==="final_answer")&&(text3=params.item.text)}else event.method==="turn/completed"&&(params?.turn?.status!=="completed"?fail2(Object.assign(new Error(`Model turn ended with ${String(params?.turn?.status)}${params?.turn?.error?.message?`: ${params.turn.error.message}`:""}`),{code:"PLUGIN_MODEL_TURN_FAILED"})):text3===void 0?fail2(new Error("Model returned no final text")):(flush(),finish(text3)))},unsubscribe=provider.onEvent(listener),abort=()=>{fail2(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"})),session&&turn&&provider.interrupt(session,turn).catch(()=>{}),provider.dispose()};context.signal.addEventListener("abort",abort,{once:!0});try{session=context.conversation?.threadId??await provider.startSession({cwd:context.cwd,ephemeral:!0,readOnly:!0,modelExecution:!0,...request.model?{modelId:request.model}:{},...request.instructions?{developerInstructions:request.instructions}:{}}),context.conversation&&(context.conversation.threadId=session),context.onDiagnostic?.({...provider.getSessionModel(session)?.id?{selectedModel:provider.getSessionModel(session).id}:{}}),context.signal.throwIfAborted();let[,result]=await Promise.all([provider.sendMessage(session,request.prompt,[],{reasoningSummary:"none",reasoningEffort:request.reasoningEffort,outputSchema:request.outputSchema,modelExecution:!0}).then(value=>{turn=value.turnId}),completed]);return context.signal.throwIfAborted(),{text:result,provider:request.provider,mode:request.mode,...provider.getSessionModel(session)?.id?{model:provider.getSessionModel(session).id}:{}}}catch(error2){throw context.conversation&&(delete context.conversation.threadId,provider.dispose()),error2}finally{clearTimeout(flushTimer),context.signal.removeEventListener("abort",abort),unsubscribe(),context.conversation||provider.dispose()}}var init_model=__esm({"../agent-runtime/dist/model.js"(){"use strict";init_codex_provider();init_capabilities()}});import{readFileSync as readFileSync18}from"node:fs";async function listCodexModels(signal,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync18(new URL("../package.json",import.meta.url),"utf8")).version)){signal.throwIfAborted();let abort,cancelled=new Promise((_resolve,reject)=>{abort=()=>{provider.dispose(),reject(signal.reason??new Error("Model discovery cancelled"))},signal.addEventListener("abort",abort,{once:!0})});try{return await Promise.race([provider.listModels(),cancelled])}finally{signal.removeEventListener("abort",abort),provider.dispose()}}var init_model_catalog=__esm({"../agent-runtime/dist/model-catalog.js"(){"use strict";init_codex_provider()}});var codex_exports={};__export(codex_exports,{CODEX_MODEL_CAPABILITY:()=>CODEX_MODEL_CAPABILITY,CodexAgentProvider:()=>CodexAgentProvider,codexAppExecutableCandidatePaths:()=>codexAppExecutableCandidatePaths,codexExecutableCandidatePaths:()=>codexExecutableCandidatePaths,codexThreadUrl:()=>codexThreadUrl,codexWorkspaceUrl:()=>codexWorkspaceUrl,compareCodexVersions:()=>compareCodexVersions,externalOpenCommand:()=>externalOpenCommand,listCodexModels:()=>listCodexModels,normalizeCodexVersion:()=>normalizeCodexVersion,runCodexModel:()=>runCodexModel});var init_codex=__esm({"../agent-runtime/dist/codex.js"(){"use strict";init_codex_provider();init_model();init_model_catalog()}});init_dist();init_dist2();init_pluginHostPaths();import{randomUUID as randomUUID13}from"node:crypto";import{createServer}from"node:net";import{chmodSync as chmodSync2,rmSync as rmSync14}from"node:fs";init_dist();init_dist2();init_dist2();import{basename as basename2}from"node:path";var MAX_PLUGIN_DIAGNOSTIC_BYTES=256*1024;function text2(value,maximum=256){if(typeof value!="string")return;let bytes=Buffer.from(value);return bytes.length<=maximum?value:bytes.subarray(0,maximum).toString("utf8").replace(/\uFFFD$/,"")}function normalizeDiagnosticOptions(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid diagnostic options");let input=value;if(Object.keys(input).some(key2=>!["taskId","plugin","instanceId","includeErrorMessages","includeLocalPaths"].includes(key2)))throw new Error("Unknown diagnostic option");if(input.taskId!==void 0&&!isPluginTaskId(input.taskId))throw new Error("Invalid diagnostic task ID");if(input.instanceId!==void 0&&!isPluginPageInstanceId(input.instanceId))throw new Error("Invalid diagnostic instance ID");if(input.plugin!==void 0&&(typeof input.plugin!="string"||!/^[a-z][a-z0-9-]*$/.test(input.plugin)||input.plugin.length>128))throw new Error("Invalid diagnostic plugin");for(let key2 of["includeErrorMessages","includeLocalPaths"])if(input[key2]!==void 0&&typeof input[key2]!="boolean")throw new Error("Invalid diagnostic content option");return{...input.taskId?{taskId:String(input.taskId)}:{},...input.plugin?{plugin:String(input.plugin)}:{},...input.instanceId?{instanceId:String(input.instanceId)}:{},...input.includeErrorMessages!==void 0?{includeErrorMessages:input.includeErrorMessages}:{},...input.includeLocalPaths!==void 0?{includeLocalPaths:input.includeLocalPaths}:{}}}function diagnosticFailure(value,options){if(!value)return;let message=options.includeErrorMessages?text2(value.message,4096):void 0;return{code:text2(value.code)??"PLUGIN_ERROR_UNCLASSIFIED",...message!==void 0?{message,...Buffer.byteLength(value.message??"")>4096?{messageTruncated:!0}:{}}:{}}}function normalizeModelDiagnostic(value,previous={}){let result={...previous};if(!value||typeof value!="object"||Array.isArray(value))return result;let input=value;for(let key2 of["requestedModel","selectedModel","activeModel"])typeof input[key2]=="string"&&(result[key2]=text2(input[key2]));["apikey","chatgpt","chatgptAuthTokens","unknown"].includes(input.authentication)&&(result.authentication=input.authentication);for(let key2 of["threadRestrictionsAccepted","turnRestrictionsAccepted"])typeof input[key2]=="boolean"&&(result[key2]=input[key2]);Number.isSafeInteger(input.retryCount)&&input.retryCount>=0&&(result.retryCount=Math.min(input.retryCount,1e6));let runtime=input.runtime;runtime&&["explicit","automatic"].includes(runtime.selection)&&(result.runtime={...typeof runtime.executable=="string"?{executable:text2(runtime.executable,4096)}:{},...typeof runtime.version=="string"?{version:text2(runtime.version)}:{},selection:runtime.selection,...typeof runtime.started=="boolean"?{started:runtime.started}:{}});let config=input.configuration;return config&&["default","environment"].includes(config.source)&&typeof config.filePresent=="boolean"&&(result.configuration={source:config.source,filePresent:config.filePresent,...typeof config.home=="string"?{home:text2(config.home,4096)}:{},...typeof config.baseProvider=="string"?{baseProvider:text2(config.baseProvider)}:{},...["file","keyring","auto","ephemeral","unknown"].includes(config.credentialStore)?{credentialStore:config.credentialStore}:{}}),result}function diagnosticBinding(value){return{instanceId:value.instanceId,browserSessionId:value.target.browserSessionId,tabId:value.target.tabId,frameId:value.target.frameId,documentId:value.target.documentId}}function modelProjection(record2,options){if(record2.task.kind!=="model")return;let request=record2.task.input.request,metadata=normalizeModelDiagnostic(record2.diagnostics?.model,typeof request?.model=="string"?{requestedModel:text2(request.model)}:{});if(!options.includeLocalPaths&&(metadata.runtime?.executable&&(metadata.runtime={...metadata.runtime,executable:basename2(metadata.runtime.executable)}),metadata.configuration)){let{home:_home,...configuration}=metadata.configuration;metadata.configuration=configuration}return metadata}function taskProjection(record2,options,observedAt){let{task,diagnostics,execution,executorOwner:owner}=record2,events=record2.events.filter(event=>event.type!=="progress"),first=record2.events[0]?.sequence??task.sequence+1,alive=owner&&!diagnostics?.executorStoppedAt?isProcessOwnerAlive(owner):!1,stopped=diagnostics?.executorStoppedAt,state=alive?"observed-alive":stopped?"stop-confirmed":diagnostics?.executorAttempted===!1?"never-started":"unknown",routing=execution?.options;return{taskId:task.taskId,plugin:text2(task.plugin),kind:task.kind??"command",command:text2(task.command),state:task.state,source:task.source,host:{hostId:task.host.hostId,epoch:task.host.epoch},installationId:task.installationId,revision:task.revision,...diagnostics?.invocationId?{invocationId:diagnostics.invocationId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt,sequence:task.sequence,...diagnostics?.page?{page:diagnosticBinding({instanceId:diagnostics.page.instanceId,target:diagnostics.page})}:{},...routing?{routing:{...routing.browser?{browser:text2(routing.browser,1024)}:{},...routing.session?{session:text2(routing.session)}:{},...routing.connector?{connector:text2(routing.connector)}:{},...routing.local!==void 0?{local:routing.local}:{},...routing.transport?{transport:routing.transport}:{}}}:{},...execution?.executionTimeoutMs?{executionTimeoutMs:execution.executionTimeoutMs}:{},executor:{state,observedAt,...owner?{pid:owner.pid}:{},...stopped?{stoppedAt:stopped}:{}},...task.error?{failure:diagnosticFailure(task.error,options)}:{},...task.checkpoint?{checkpoint:{sequence:task.checkpoint.sequence,version:task.checkpoint.version,schemaHash:task.checkpoint.schemaHash,updatedAt:task.checkpoint.updatedAt}}:{},...task.result?{result:{bytes:task.result.bytes,chunks:task.result.chunks,sha256:task.result.sha256}}:{},...task.kind==="model"?{model:modelProjection(record2,options)}:{},metadataIncomplete:!diagnostics||!!diagnostics.updatesDropped||task.kind==="model"&&!diagnostics.model?.runtime,history:{firstRetainedSequence:first,gap:first>1,omitted:Math.max(0,events.length-8),events:events.slice(-8).map(event=>({sequence:event.sequence,time:event.time,state:event.state,type:event.type}))}}}function buildDiagnosticReport(host,scope,options,scan,snapshots){let records=scan.records.filter(record2=>(!scope.plugin||record2.task.plugin===scope.plugin)&&(scope.access!=="toolbox"||record2.access!=="public")&&(!options.plugin||record2.task.plugin===options.plugin)&&(!options.instanceId||record2.diagnostics?.page?.instanceId===options.instanceId)),visible=new Map(records.map(record2=>[record2.task.taskId,record2])),selected=records.sort((a,b)=>b.task.createdAt-a.task.createdAt||a.task.taskId.localeCompare(b.task.taskId));if(options.taskId){if(!visible.has(options.taskId))throw Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"});let ids=new Set([options.taskId]),pending=[options.taskId];for(;pending.length;){let id=pending.shift(),item=visible.get(id),candidates=[item.task.parentTaskId,item.task.resumedFrom?.taskId,...records.filter(record2=>record2.task.parentTaskId===id||record2.task.resumedFrom?.taskId===id).map(record2=>record2.task.taskId)];for(let candidate of candidates)candidate&&visible.has(candidate)&&!ids.has(candidate)&&(ids.add(candidate),pending.push(candidate))}selected=[...ids].map(id=>visible.get(id))}let generatedAt=Date.now(),tasks=selected.slice(0,128).map(record2=>taskProjection(record2,options,generatedAt)),pages=snapshots.filter(page=>(!scope.plugin||page.plugin===scope.plugin)&&(!options.plugin||page.plugin===options.plugin)&&(!options.instanceId||page.binding.instanceId===options.instanceId)&&(!options.taskId||tasks.some(task=>task.page?.instanceId===page.binding.instanceId)));for(let task of tasks)task.page&&!pages.some(page=>page.binding.instanceId===task.page.instanceId)&&pages.push({plugin:task.plugin,installationId:task.installationId,revision:task.revision,host:task.host,binding:task.page,observation:"historical-binding"});let report={version:1,generatedAt,host:{hostId:host.hostId,epoch:host.epoch},protocolVersion:5,selection:{...options.taskId?{taskId:options.taskId}:{},...options.plugin?{plugin:options.plugin}:{},...options.instanceId?{instanceId:options.instanceId}:{}},coverage:{scanLimited:scan.limited,tasksOmitted:selected.length-tasks.length,pagesOmitted:Math.max(0,pages.length-64),byteLimited:!1},tasks,pages:pages.slice(0,64),links:[]},links=()=>{let retained=new Set(report.tasks.map(task=>task.taskId));report.links=report.tasks.flatMap(task=>{let record2=visible.get(task.taskId);return[["parent",record2.task.parentTaskId],["resume",record2.task.resumedFrom?.taskId]].flatMap(([kind,from])=>from&&retained.has(from)?[{from,to:task.taskId,kind}]:[])})};for(links();Buffer.byteLength(JSON.stringify(report))>MAX_PLUGIN_DIAGNOSTIC_BYTES;)report.coverage.byteLimited=!0,report.pages.length?(report.pages.pop(),report.coverage.pagesOmitted++):(report.tasks.pop(),report.coverage.tasksOmitted++,links());return report}init_pluginModelDefinition();init_pluginRecoveryDefinition();init_pluginStateDefinition();init_pluginExecution2();init_pluginExecutor();init_pluginExecutorProtocol();import{createHash as createHash10,randomUUID as randomUUID11}from"node:crypto";import{EventEmitter as EventEmitter2}from"node:events";import{isAbsolute as isAbsolute7,join as join17,relative as relative5,sep as sep4}from"node:path";import{realpathSync as realpathSync4,statSync as statSync10}from"node:fs";init_dist();init_acorn();init_pluginHostPaths();init_skillManifest();init_pluginRegistry();import{createHash as createHash6,randomUUID as randomUUID4}from"node:crypto";import{existsSync as existsSync4,mkdirSync as mkdirSync4,readFileSync as readFileSync8,readdirSync as readdirSync5,realpathSync as realpathSync2,renameSync as renameSync5,rmSync as rmSync5,statSync as statSync6,writeFileSync as writeFileSync4}from"node:fs";import{basename as basename3,dirname as dirname4,isAbsolute as isAbsolute3,join as join9,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";import{isBuiltin}from"node:module";var MAX_REVISION_BYTES=64*1024*1024,validatedSources=new Set;function within(root,file){let path8=relative2(root,file);return path8===""||!path8.startsWith(`..${sep2}`)&&path8!==".."&&!isAbsolute3(path8)}function sourceRoot(entry){let candidate=dirname4(entry);for(let depth=0;depth<6;depth++){if(skillManifestPath(candidate))return candidate;let parent=dirname4(candidate);if(parent===candidate)break;candidate=parent}return basename3(dirname4(entry))==="scripts"?dirname4(dirname4(entry)):dirname4(entry)}function readSources(root){let files=[],registry=realpathSync2(pluginHostPaths().registry),bytes=0,visit=(directory,ancestors)=>{let real=realpathSync2(directory);if(!within(root,real)||ancestors.has(real))throw new Error("Plugin snapshot has an external or cyclic directory link");let next=new Set([...ancestors,real]);for(let item of readdirSync5(directory,{withFileTypes:!0}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0)){if([".git","__pycache__","node_modules",".DS_Store"].includes(item.name))continue;let file=join9(directory,item.name);if(within(root,registry)&&within(registry,file))continue;let target=realpathSync2(file);if(!within(root,target))throw new Error(`Plugin snapshot resource leaves the Skill directory: ${file}`);let stat2=statSync6(file);if(stat2.isDirectory()){visit(file,next);continue}if(!stat2.isFile())throw new Error(`Unsupported plugin resource: ${file}`);if(bytes+=stat2.size,bytes>MAX_REVISION_BYTES||files.length>=1e4)throw new Error("Plugin source snapshot exceeds 64 MiB or 10000 files");let content=readFileSync8(file);if(bytes+=content.length-stat2.size,bytes>MAX_REVISION_BYTES)throw new Error("Plugin source snapshot exceeds 64 MiB");files.push({path:relative2(root,file).split(sep2).join("/"),hash:createHash6("sha256").update(content).digest("hex"),bytes:content,executable:(stat2.mode&73)!==0})}};return visit(root,new Set),files}function validateDependencies(files){let paths=new Set(files.map(file=>file.path));for(let file of files){if(!/\.[cm]?js$/.test(file.path))continue;let tree=parse3(file.bytes.toString("utf8"),{ecmaVersion:"latest",sourceType:"module",allowReturnOutsideFunction:!0}),check=specifier=>{if(typeof specifier!="string"||isBuiltin(specifier))return;if(!specifier.startsWith("./")&&!specifier.startsWith("../"))throw new PluginError("PLUGIN_SOURCE_NOT_SELF_CONTAINED",`后台任务需要自包含 Skill,请先打包依赖: ${file.path}: ${specifier}`);let local=resolve3("/source",dirname4(file.path),specifier),normalized=relative2("/source",local).split(sep2).join("/");if(!within("/source",local)||![normalized,`${normalized}.js`,`${normalized}.json`,`${normalized}/index.js`].some(path8=>paths.has(path8)))throw new PluginError("PLUGIN_SOURCE_NOT_SELF_CONTAINED",`依赖不在 Skill 快照中: ${file.path}: ${specifier}`)},visit=node=>{if(!(!node||typeof node!="object")){["ImportDeclaration","ExportNamedDeclaration","ExportAllDeclaration"].includes(node.type)&&check(node.source?.value),node.type==="ImportExpression"&&check(node.source?.value),node.type==="CallExpression"&&node.callee?.type==="Identifier"&&node.callee.name==="require"&&check(node.arguments[0]?.value);for(let value of Object.values(node))Array.isArray(value)?value.forEach(visit):value&&typeof value=="object"&&visit(value)}};visit(tree)}}function fingerprint(files,entry){return createHash6("sha256").update(JSON.stringify({entry,files:files.map(file=>[file.path,file.hash,file.executable])})).digest("hex")}function capturePluginRevision(plugin){let registration=findPluginRegistration(plugin);if(!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${plugin}`);let entry=realpathSync2(registration.entry),root=realpathSync2(sourceRoot(entry)),paths=pluginHostPaths();mkdirSync4(paths.installations,{recursive:!0,mode:448});let identityFile=join9(paths.installations,`${plugin}.json`),installation=readRecord(identityFile);if(!installation||installation.root!==root){let proposed={pid:process.pid,root,installationId:randomUUID4()};installation?writeRecord(identityFile,proposed):claimRecord(identityFile,proposed),installation=readRecord(identityFile)}if(!installation||installation.root!==root)throw new Error("Plugin installation changed during capture");let relativeEntry=relative2(root,entry).split(sep2).join("/"),files=readSources(root),revision=fingerprint(files,relativeEntry);validatedSources.has(revision)||(validateDependencies(files),validatedSources.size>=64&&validatedSources.delete(validatedSources.values().next().value),validatedSources.add(revision));let revisionRoot=join9(paths.revisions,installation.installationId,revision);if(!existsSync4(revisionRoot)){let temporary=`${revisionRoot}.${randomUUID4()}.tmp`;try{mkdirSync4(temporary,{recursive:!0,mode:448});for(let file of files){let destination=resolve3(temporary,file.path);mkdirSync4(dirname4(destination),{recursive:!0,mode:448}),writeFileSync4(destination,file.bytes,{flag:"wx",mode:file.executable?365:292})}if(fingerprint(readSources(root),relativeEntry)!==revision)throw new PluginError("PLUGIN_SOURCE_CHANGED","插件源码在创建快照时发生变化");mkdirSync4(dirname4(revisionRoot),{recursive:!0,mode:448}),renameSync5(temporary,revisionRoot)}finally{rmSync5(temporary,{recursive:!0,force:!0})}}return{plugin,installationId:installation.installationId,revision,originalRoot:root,entry:join9(revisionRoot,relativeEntry),registration:{...registration,entry:join9(revisionRoot,relativeEntry),source:void 0}}}function prunePluginRevisions(references){let directory=pluginHostPaths().revisions;if(existsSync4(directory))for(let installation of readdirSync5(directory,{withFileTypes:!0})){if(!installation.isDirectory())continue;let root=join9(directory,installation.name);for(let revision of readdirSync5(root,{withFileTypes:!0}))revision.isDirectory()&&!references.has(`${installation.name}/${revision.name}`)&&rmSync5(join9(root,revision.name),{recursive:!0,force:!0});readdirSync5(root).length||rmSync5(root,{recursive:!0,force:!0})}}function restorePluginRevision(plugin,installationId,revision,entry){if(!/^[a-f0-9-]{36}$/.test(installationId)||!/^[a-f0-9]{64}$/.test(revision))throw new Error("Invalid recovery revision");let paths=pluginHostPaths(),registration=findPluginRegistration(plugin),installation=readRecord(join9(paths.installations,`${plugin}.json`));if(!registration||!installation||installation.installationId!==installationId||sourceRoot(realpathSync2(registration.entry))!==installation.root)throw new PluginError("PLUGIN_TASK_INSTALLATION_CHANGED","Task installation was removed or replaced");try{let root=realpathSync2(join9(paths.revisions,installationId,revision)),restoredEntry=resolve3(root,entry);if(!entry||isAbsolute3(entry)||!within(root,restoredEntry)||!within(root,realpathSync2(restoredEntry))||fingerprint(readSources(root),entry)!==revision)throw new Error("Snapshot identity changed");return{plugin,installationId,revision,originalRoot:installation.root,entry:restoredEntry,registration:{...registration,entry:restoredEntry,source:void 0}}}catch{throw new PluginError("PLUGIN_TASK_REVISION_UNAVAILABLE","Task source snapshot is missing or has changed")}}init_pluginHostPaths();init_pluginTaskStore();init_dist2();init_unified();init_commands();function error(code,message){return Object.assign(new Error(message),{code})}function digest(value){return createHash10("sha256").update(JSON.stringify(value,(_key,item)=>item&&typeof item=="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a<b?-1:a>b?1:0)):item)).digest("hex")}function revisionEntry(revision){return relative5(realpathSync4(join17(pluginHostPaths().revisions,revision.installationId,revision.revision)),realpathSync4(revision.entry)).split(sep4).join("/")}var PluginTaskManager=class{constructor(configuration={},services){this.configuration=configuration;this.services=services;this.store=configuration.store??new PluginTaskStore,this.store.recover(this.host.epoch),this.changes.setMaxListeners(0);let concurrency=configuration.concurrency??4;if(!Number.isInteger(configuration.modelConcurrency??2)||(configuration.modelConcurrency??2)<1||(configuration.modelConcurrency??2)>8)throw new Error("Invalid model concurrency");if(!Number.isInteger(concurrency)||concurrency<1||concurrency>32)throw new Error("Invalid plugin task concurrency");let prune=()=>{this.store.prune(),prunePluginRevisions(new Set([...this.revisionPins.keys(),...this.store.list().map(record2=>`${record2.task.installationId}/${record2.task.revision}`)]))};prune(),this.maintenance=setInterval(()=>{try{prune()}catch(error2){console.error("Plugin task retention failed:",error2)}},3600*1e3),this.maintenance.unref()}configuration;services;host=localPluginExecutionHost();store;changes=new EventEmitter2;queue=new Map;running=new Map;resuming=new Map;activeChildren=new Map;closed=!1;maintenance;descriptionsRunning=0;descriptions=new Map;descriptionBytes=0;revisionPins=new Map;recoveries=new Map;pinRevision(revision){let key2=`${revision.installationId}/${revision.revision}`;this.revisionPins.set(key2,(this.revisionPins.get(key2)??0)+1);let released=!1;return()=>{if(released)return;released=!0;let count=this.revisionPins.get(key2)??0;count>1?this.revisionPins.set(key2,count-1):this.revisionPins.delete(key2)}}async describeRevision(revision,signal,options={}){if(signal.throwIfAborted(),this.closed)throw new Error("Plugin description budget is exhausted");let key2=`${revision.installationId}/${revision.revision}`,cached=options.cache?this.descriptions.get(key2):void 0;if(cached)return this.descriptions.delete(key2),this.descriptions.set(key2,cached),structuredClone(cached.value);if(this.descriptionsRunning>=8)throw new Error("Plugin description budget is exhausted");this.descriptionsRunning++;try{let value=await(this.configuration.execute??executeRegisteredPlugin)(revision.plugin,{command:"describe",input:{}},{invoke:async()=>{throw new Error("Plugin declarations cannot invoke host actions")}},{describe:!0,signal,source:"runtime",executionTimeoutMs:1e4,workerPath:this.configuration.workerPath},{registration:revision.registration});signal.throwIfAborted();let bytes=Buffer.byteLength(JSON.stringify(value));if(options.cache&&!this.closed&&bytes<=8*1024*1024){let previous=this.descriptions.get(key2);for(previous&&(this.descriptions.delete(key2),this.descriptionBytes-=previous.bytes);this.descriptions.size>=64||this.descriptionBytes+bytes>8*1024*1024;){let oldest=this.descriptions.keys().next().value;this.descriptionBytes-=this.descriptions.get(oldest).bytes,this.descriptions.delete(oldest)}this.descriptions.set(key2,{value:structuredClone(value),bytes}),this.descriptionBytes+=bytes}return value}finally{this.descriptionsRunning--}}authorize(taskId,scope){if(!taskId.startsWith(`pt_${this.host.hostId}_`))throw error("PLUGIN_TASK_WRONG_HOST","Plugin task belongs to another execution host");let record2=this.store.read(taskId);if(scope.plugin&&record2.task.plugin!==scope.plugin||scope.access==="toolbox"&&record2.access==="public")throw error("PLUGIN_TASK_NOT_FOUND","Plugin task was not found");return record2.task}get(taskId,scope){return this.authorize(taskId,scope)}list(scope,activeOnly=!1,cursor,limit=100){if(!Number.isSafeInteger(limit)||limit<1||limit>200||cursor!==void 0&&typeof cursor!="string")throw new Error("Invalid plugin task list page");let candidates=(activeOnly?this.store.listActive():this.store.list()).filter(record2=>scope.access!=="toolbox"||record2.access!=="public").map(record2=>record2.task).filter(task=>(!scope.plugin||task.plugin===scope.plugin)&&(!activeOnly||isPluginTaskActive(task.state))).sort((a,b)=>b.createdAt-a.createdAt||b.taskId.localeCompare(a.taskId)),match=cursor?.match(/^(\d+):(pt_[0-9a-f-]{36}_[0-9a-f-]{36})$/i);if(cursor!==void 0&&(!match||!Number.isSafeInteger(Number(match[1]))))throw new Error("Invalid plugin task list cursor");let remaining=match?candidates.filter(task=>task.createdAt<Number(match[1])||task.createdAt===Number(match[1])&&task.taskId.localeCompare(match[2])<0):candidates,tasks=[],bytes=0;for(let task of remaining){let size=Buffer.byteLength(JSON.stringify(task));if(tasks.length&&(tasks.length>=limit||bytes+size>384*1024))break;tasks.push(task),bytes+=size}let last=tasks.at(-1);return{tasks,...last&&tasks.length<remaining.length?{nextCursor:`${last.createdAt}:${last.taskId}`}:{}}}start(request,bridge,binding=void 0){if(this.closed)throw error("PLUGIN_TASK_HOST_STOPPING","Plugin execution service is stopping");if(request.kind!==void 0&&!["command","model"].includes(request.kind))throw new Error("Invalid task kind");if(request.kind==="model"){let model=normalizePluginModel(request.input?.request);request={...request,command:"model",input:{request:model},executionTimeoutMs:request.executionTimeoutMs??12e4}}if(!/^[a-z][a-z0-9-]*$/.test(request.plugin)||!/^[a-z][a-z0-9-]*$/.test(request.command))throw new Error("Invalid plugin task command");if(bridge.scope.plugin&&request.plugin!==bridge.scope.plugin)throw error("PLUGIN_COMMAND_NOT_ALLOWED","Plugin task is outside the caller scope");if(!request.input||typeof request.input!="object"||Array.isArray(request.input)||Buffer.byteLength(JSON.stringify(request.input))>256*1024)throw new Error("Plugin task input must be an object within 256 KiB");if(!isAbsolute7(request.cwd)||!statSync10(request.cwd).isDirectory())throw new Error("Plugin task cwd must be an absolute directory");if(!request.environment||typeof request.environment!="object"||Array.isArray(request.environment)||Object.entries(request.environment).some(([key2,value])=>!key2||key2.includes("=")||typeof value!="string"||key2.includes("\0")||value.includes("\0"))||Buffer.byteLength(JSON.stringify(request.environment))>512*1024)throw new Error("Invalid plugin task environment");if(!request.options||typeof request.options!="object"||Array.isArray(request.options)||Object.keys(request.options).some(key2=>!["browser","session","connector","local","transport","timeoutSec"].includes(key2)))throw new Error("Invalid plugin task routing options");for(let key2 of["browser","session","connector"])if(request.options[key2]!==void 0&&(typeof request.options[key2]!="string"||!request.options[key2]))throw new Error("Invalid plugin task target");if(request.options.timeoutSec!==void 0&&(!Number.isFinite(request.options.timeoutSec)||request.options.timeoutSec<=0))throw new Error("Invalid plugin task invocation timeout");if(request.options.local!==void 0&&typeof request.options.local!="boolean")throw new Error("Invalid plugin task local routing option");if(request.options.transport!==void 0&&!["extension","cdp"].includes(request.options.transport))throw new Error("Invalid plugin task transport");if(bridge.scope.bridge==="service"&&request.options.browser&&!decodeBrowserTarget(request.options.browser))throw error("PLUGIN_TASK_TARGET_REQUIRED","Background tasks require a stable global browser ID");if(request.executionTimeoutMs!==void 0&&(!Number.isSafeInteger(request.executionTimeoutMs)||request.executionTimeoutMs<1||request.executionTimeoutMs>2147483647))throw new Error("Invalid plugin task execution deadline");if(request.idempotencyKey!==void 0&&(typeof request.idempotencyKey!="string"||!request.idempotencyKey||request.idempotencyKey.length>128))throw new Error("Invalid plugin task idempotency key");let revision=binding?.revision??(this.configuration.captureRevision??capturePluginRevision)(request.plugin);if(bridge.scope.access==="runtime"&&!binding)throw new Error("Runtime task requires a document binding");if(request.kind!=="model"&&bridge.scope.access==="toolbox"&&!revision.registration.toolbox?.page.commands.includes(request.command))throw error("PLUGIN_COMMAND_NOT_ALLOWED","Tool page cannot invoke this plugin command");request={...request,cwd:realpathSync4(request.cwd),input:JSON.parse(JSON.stringify(request.input))};let requestHash=binding?.recoveryRequestHash??digest([request.kind??"command",request.command,request.input,request.cwd,request.options,request.executionTimeoutMs,revision.revision,binding?.recovery,Object.entries(request.environment).sort(([a],[b])=>a<b?-1:a>b?1:0)]),dedupeKey=binding?.recovery?`resume:${binding.recovery.fromTaskId}`:request.idempotencyKey?`explicit:${revision.installationId}:${bridge.scope.access}:${request.idempotencyKey}`:bridge.scope.access==="toolbox"?`active:${digest(bridge.scope.scopeId??bridge.id)}:${revision.installationId}:${requestHash}`:void 0;if(dedupeKey){let existing=this.store.findDedupe(dedupeKey,request.idempotencyKey===void 0&&binding?.recovery===void 0);if(existing){if(existing.requestHash!==requestHash)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","Idempotency key refers to a different plugin task request");return{taskId:existing.task.taskId,state:existing.task.state,host:existing.task.host,reused:!0}}}if([...this.queue.values()].filter(item=>(item.request.kind??"command")===(request.kind??"command")).length>=128)throw error("PLUGIN_TASK_QUEUE_FULL","Plugin task queue is full");let now=Date.now(),task={taskId:`pt_${this.host.hostId}_${randomUUID11()}`,host:this.host,plugin:request.plugin,installationId:revision.installationId,revision:revision.revision,command:request.command,kind:request.kind??"command",...binding?.parentTaskId?{parentTaskId:binding.parentTaskId}:{},...binding?.recovery?{resumedFrom:{taskId:binding.recovery.fromTaskId,revision:binding.recovery.fromRevision,checkpointSequence:binding.recovery.sourceCheckpoint.sequence,checkpointVersion:binding.recovery.sourceCheckpoint.version},checkpoint:{sequence:0,version:binding.recovery.checkpoint.version,schemaHash:binding.recovery.checkpoint.schemaHash,updatedAt:now}}:{},input:request.input,source:bridge.scope.source,cwd:request.cwd,state:"queued",sequence:0,createdAt:now,updatedAt:now};if(this.store.write({task,events:[],diagnostics:{executorAttempted:!1,...binding?.page?{page:diagnosticBinding({instanceId:binding.page.instanceId,target:binding.page.target})}:{}},access:bridge.scope.access,...dedupeKey?{dedupeKey}:{},requestHash,execution:{entry:revisionEntry(revision),options:JSON.parse(JSON.stringify(request.options)),bridge:bridge.scope.bridge,executionTimeoutMs:request.executionTimeoutMs},...binding?.recovery?{checkpoint:{...structuredClone(binding.recovery.checkpoint),sequence:0,updatedAt:now}}:{}}),this.update(task.taskId,{state:"queued"}),task.parentTaskId){let children=this.activeChildren.get(task.parentTaskId)??new Set;children.add(task.taskId),this.activeChildren.set(task.parentTaskId,children)}return this.queue.set(task.taskId,{request,revision,bridge,controller:new AbortController,guard:binding?.guard,page:binding?.page,recovery:binding?.recovery,parentIdentity:binding?.parentIdentity,documentTarget:binding?.documentTarget}),queueMicrotask(()=>this.drain()),{taskId:task.taskId,state:"queued",host:this.host}}checkpoint(taskId,scope){return this.authorize(taskId,scope),this.store.read(taskId).checkpoint??null}resume(request,bridge){try{if(this.closed)throw error("PLUGIN_TASK_HOST_STOPPING","Plugin execution service is stopping");if(this.authorize(request.taskId,bridge.scope),bridge.scope.access!=="public"||bridge.scope.bridge!=="service")throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery requires public service-owned routing");if(request.revision!==void 0&&!["original","current"].includes(request.revision))throw new Error("Recovery revision must be original or current");if(!request.environment||typeof request.environment!="object"||Array.isArray(request.environment)||Object.entries(request.environment).some(([key2,value])=>!key2||key2.includes("=")||typeof value!="string"||key2.includes("\0")||value.includes("\0"))||Buffer.byteLength(JSON.stringify(request.environment))>512*1024)throw new Error("Invalid plugin task environment");let intent=digest([request.revision??"original",request.environment]),existing=this.recoveries.get(request.taskId);if(existing){if(existing.intent!==intent)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","A different recovery request is already in progress");return existing.promise.then(result=>({...result,reused:!0}))}let controller=new AbortController,operation={controller,intent,promise:this.resumeAttempt(request,bridge,controller.signal)};return this.recoveries.set(request.taskId,operation),operation.promise.finally(()=>this.recoveries.delete(request.taskId)).catch(()=>{}),operation.promise}catch(cause){return Promise.reject(cause)}}async resumeAttempt(request,bridge,signal){let task=this.authorize(request.taskId,bridge.scope),record2=this.store.read(task.taskId);if(!["error","cancelled","interrupted"].includes(task.state)||task.kind==="model"||task.parentTaskId||record2.access!=="public"||record2.execution?.bridge!=="service"||!record2.checkpoint)throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery requires a terminal root command with a checkpoint and service-owned routing");this.assertExecutionTreeStopped(task.taskId);let source=restorePluginRevision(task.plugin,task.installationId,task.revision,record2.execution.entry),revision=request.revision==="current"?(this.configuration.captureRevision??capturePluginRevision)(task.plugin):source;if(revision.installationId!==task.installationId)throw error("PLUGIN_TASK_INSTALLATION_CHANGED","Recovery cannot change the plugin installation");restorePluginRevision(task.plugin,task.installationId,revision.revision,revisionEntry(revision));let releaseSource=this.pinRevision(source),releaseTarget=this.pinRevision(revision);try{let requestHash=digest([request.revision??"original",task,record2.checkpoint,record2.execution,revision.revision,request.environment]),existing=this.store.findDedupe(`resume:${task.taskId}`);if(existing){if(existing.requestHash!==requestHash)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","Source task already has a different recovery attempt");return{taskId:existing.task.taskId,state:existing.task.state,host:existing.task.host,reused:!0}}let sourceCommands=(await this.describeRevision(source,signal)).taskRecovery?.commands,sourceDefinition=sourceCommands&&Object.hasOwn(sourceCommands,task.command)?sourceCommands[task.command]:void 0;if(signal.throwIfAborted(),!sourceDefinition||sourceDefinition.checkpointVersion!==record2.checkpoint.version||digest(sourceDefinition.schema)!==record2.checkpoint.schemaHash||!compilePluginStateSchema(sourceDefinition.schema)(record2.checkpoint.data))throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Checkpoint does not match the retained recovery declaration");let checkpoint=structuredClone(record2.checkpoint),declarationHash=pluginRecoverySignature(sourceDefinition);if(revision.revision!==source.revision){let targetCommands=(await this.describeRevision(revision,signal)).taskRecovery?.commands,target=targetCommands&&Object.hasOwn(targetCommands,task.command)?targetCommands[task.command]:void 0;if(signal.throwIfAborted(),!target)throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Target revision does not declare recovery for the original command");if(declarationHash=pluginRecoverySignature(target),target.checkpointVersion===checkpoint.version){if(digest(target.schema)!==digest(sourceDefinition.schema))throw error("PLUGIN_CHECKPOINT_MIGRATION_UNSUPPORTED","Checkpoint schema changed without a version increment")}else{if(!target.migrateFrom?.some(from=>from.version===checkpoint.version&&digest(from.schema)===digest(sourceDefinition.schema)))throw error("PLUGIN_CHECKPOINT_MIGRATION_UNSUPPORTED","Target revision does not declare this checkpoint format");if(this.descriptionsRunning>=8)throw error("PLUGIN_CHECKPOINT_MIGRATION_BUSY","Checkpoint migration budget is exhausted");this.descriptionsRunning++;let result;try{result=await(this.configuration.execute??executeRegisteredPlugin)(revision.plugin,{command:task.command,input:{checkpoint,fromRevision:source.revision,toRevision:revision.revision}},{invoke:async()=>{throw error("PLUGIN_CHECKPOINT_MIGRATION_HOST_CALL","Checkpoint migration cannot invoke host actions")}},{migration:!0,expectedRecovery:declarationHash,signal,source:"runtime",cwd:task.cwd,environment:request.environment,executionTimeoutMs:1e4,workerPath:this.configuration.workerPath},{registration:revision.registration})}finally{this.descriptionsRunning--}signal.throwIfAborted();let json2=JSON.stringify(result);if(json2===void 0||Buffer.byteLength(json2)>64*1024)throw error("PLUGIN_TASK_CHECKPOINT_INVALID","Migrated checkpoint must be JSON within 64 KiB");checkpoint={...checkpoint,version:target.checkpointVersion,schemaHash:digest(target.schema),data:JSON.parse(json2)}}if(!compilePluginStateSchema(target.schema)(checkpoint.data))throw error("PLUGIN_TASK_CHECKPOINT_INVALID","Migrated checkpoint does not match the target schema")}return signal.throwIfAborted(),restorePluginRevision(task.plugin,task.installationId,task.revision,record2.execution.entry),restorePluginRevision(task.plugin,task.installationId,revision.revision,revisionEntry(revision)),this.assertExecutionTreeStopped(task.taskId),this.start({plugin:task.plugin,command:task.command,input:task.input,cwd:task.cwd,environment:request.environment,options:record2.execution.options,executionTimeoutMs:record2.execution.executionTimeoutMs},bridge,{revision,recoveryRequestHash:requestHash,recovery:{fromTaskId:task.taskId,fromRevision:source.revision,declarationHash,sourceCheckpoint:{sequence:record2.checkpoint.sequence,version:record2.checkpoint.version,schemaHash:record2.checkpoint.schemaHash,updatedAt:record2.checkpoint.updatedAt},checkpoint}})}finally{releaseTarget(),releaseSource()}}assertExecutionTreeStopped(taskId){let records=this.store.list(),visited=new Set,pending=[taskId];for(;pending.length;){let id=pending.pop();if(visited.has(id))continue;visited.add(id);let record2=records.find(record3=>record3.task.taskId===id);if(!record2)throw error("PLUGIN_TASK_EXECUTION_STILL_ACTIVE","Previous execution ownership record is unavailable");if(pending.push(...records.filter(record3=>record3.task.parentTaskId===id).map(record3=>record3.task.taskId)),isPluginTaskActive(record2.task.state)||pluginTaskExecutionUnconfirmed(record2))throw error("PLUGIN_TASK_EXECUTION_STILL_ACTIVE","Previous execution or descendant cleanup cannot be confirmed")}}cancel(taskId,scope){let task=this.authorize(taskId,scope);if(task.state==="queued")return this.queue.delete(taskId),this.update(taskId,{state:"cancelled",error:{code:"PLUGIN_EXECUTION_CANCELLED",message:"Plugin task cancelled before execution"}});if(task.state==="running"){let updated=this.update(taskId,{state:"cancelling"});return this.running.get(taskId)?.controller.abort(),updated}return task}async events(taskId,scope,cursor,waitMs=0,signal){let task=this.authorize(taskId,scope);if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25e3)throw new Error("Invalid plugin task event wait");let current2=this.store.events(taskId,cursor);return waitMs&&cursor===task.sequence&&isPluginTaskActive(task.state)?(await new Promise((resolve7,reject)=>{let finish=()=>{cleanup(),resolve7()},abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin task subscription closed"))},timer=setTimeout(finish,waitMs),cleanup=()=>{clearTimeout(timer),this.changes.off(taskId,finish),signal?.removeEventListener("abort",abort)};this.changes.once(taskId,finish),signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted?abort():this.store.read(taskId).task.sequence!==cursor&&finish()}),this.store.events(taskId,cursor)):current2}resultChunk(taskId,scope,index){return this.authorize(taskId,scope),this.store.resultChunk(taskId,index)}update(taskId,update,type="state"){let task=this.store.update(taskId,update,type);if(!isPluginTaskActive(task.state)&&task.parentTaskId){let children=this.activeChildren.get(task.parentTaskId);children?.delete(taskId),children?.size||this.activeChildren.delete(task.parentTaskId)}return this.changes.emit(taskId),task}drain(){if(!this.closed){for(let[taskId,resume]of this.resuming){let parent=this.running.get(taskId);if(!parent){this.resuming.delete(taskId),resume();continue}let limit=parent.kind==="model"?this.configuration.modelConcurrency??2:this.configuration.concurrency??4;[...this.running.values()].filter(item=>item.kind===parent.kind&&!item.waiting).length<limit&&(this.resuming.delete(taskId),resume())}for(let[taskId,pending]of this.queue){let kind=pending.request.kind??"command",limit=kind==="model"?this.configuration.modelConcurrency??2:this.configuration.concurrency??4;if([...this.running.values()].filter(item=>item.kind===kind&&!item.waiting).length>=limit)continue;this.queue.delete(taskId),this.update(taskId,{state:"running"});let completed=this.execute(taskId,pending).finally(()=>{this.running.delete(taskId),this.drain()});this.running.set(taskId,{controller:pending.controller,completed,kind,waiting:0})}}}async execute(taskId,{request,revision,bridge,controller,guard,page,recovery,parentIdentity,documentTarget}){let client=bridge.scope.bridge==="service"?new UnifiedClient:void 0;try{await guard?.();let identity=Object.freeze({...createPluginInvocationIdentity(request.plugin,bridge.scope.source,parentIdentity),taskId,installationId:revision.installationId,revision:revision.revision,...page?{page}:{},...recovery?{recovery}:{}});{let record2=this.store.read(taskId);record2.diagnostics={...record2.diagnostics,invocationId:identity.invocationId,executorAttempted:!0},this.store.write(record2)}let restrictedTarget=page?.target??documentTarget,diagnosticUpdates=0,recoveryDescription,modelOwner=page?.instanceId??parentIdentity?.taskId,conversation=request.kind==="model"&&request.input.request.conversation;if(conversation&&!modelOwner)throw error("PLUGIN_MODEL_CONVERSATION_SCOPE","Model conversations require a bound document or calling command");let result=await(this.configuration.execute??(conversation&&this.services?.model?this.services.model.bind(this.services,modelOwner):executeRegisteredPlugin))(request.plugin,{command:request.command,input:request.input},{invocation:identity,source:bridge.scope.source,invoke:async(action,payload={},options={},onProgress)=>{if(controller.signal.throwIfAborted(),await guard?.(),controller.signal.throwIfAborted(),action==="plugin_invoke_child"){let name=payload.plugin,invocation=payload.invocation;if(typeof name!="string"||!invocation||typeof invocation.command!="string"||!invocation.input||typeof invocation.input!="object"||Array.isArray(invocation.input))throw new Error("Invalid nested plugin invocation");this.assertRouting(options,request.options);let ancestor=taskId,depth=0;for(;ancestor;){let task=this.store.read(ancestor).task;if(task.plugin===name)throw error("PLUGIN_INVOCATION_CYCLE","Plugin invocation forms a cycle");if(++depth>=16)throw error("PLUGIN_INVOCATION_DEPTH","Plugin invocation depth exceeds 16");ancestor=task.parentTaskId}this.assertChildBudget(taskId);let childRevision=(this.configuration.captureRevision??capturePluginRevision)(name),childBridge={...bridge,scope:{...bridge.scope,access:"public",plugin:name}},child=this.start({...request,plugin:name,kind:"command",command:invocation.command,input:invocation.input,options:{...request.options,...options},idempotencyKey:void 0},childBridge,{revision:childRevision,guard,parentTaskId:taskId,parentIdentity:identity,documentTarget:restrictedTarget});return this.awaitChild(taskId,child.taskId,childBridge.scope,controller.signal)}if(["plugin_state","plugin_model","plugin_page","plugin_task_checkpoint"].includes(action)&&payload.plugin!==request.plugin)throw error("PLUGIN_CALLER_SCOPE_MISMATCH","Plugin-owned services require the executing plugin identity");if(action==="plugin_task_checkpoint"){if(request.kind==="model"||page||bridge.scope.access!=="public"||bridge.scope.bridge!=="service")throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Checkpoints require a command with service-owned routing");let json2=JSON.stringify(payload.data);if(!Number.isSafeInteger(payload.expectedSequence)||payload.expectedSequence<0||json2===void 0||Buffer.byteLength(json2)>64*1024)throw new Error("Checkpoint must have a CAS sequence and fit within 64 KiB");let data2=JSON.parse(json2),commands=(await(recoveryDescription??=this.describeRevision(revision,controller.signal))).taskRecovery?.commands,declaration=commands&&Object.hasOwn(commands,request.command)?commands[request.command]:void 0;if(controller.signal.throwIfAborted(),declaration&&payload.expectedDeclaration!==pluginRecoverySignature(declaration))throw error("PLUGIN_RECOVERY_DECLARATION_CHANGED","Checkpoint declaration differs from the executing command");if(!declaration||!compilePluginStateSchema(declaration.schema)(data2))throw error("PLUGIN_TASK_CHECKPOINT_INVALID","Checkpoint is undeclared or does not match its schema");let current2=this.store.read(taskId);if(current2.task.state!=="running"||payload.expectedSequence!==(current2.checkpoint?.sequence??0))throw error("PLUGIN_TASK_CHECKPOINT_CONFLICT","Checkpoint sequence or execution state changed");let checkpoint={data:data2,version:declaration.checkpointVersion,schemaHash:digest(declaration.schema),sequence:payload.expectedSequence+1,updatedAt:Date.now()};return this.store.update(taskId,{checkpoint:{sequence:checkpoint.sequence,version:checkpoint.version,schemaHash:checkpoint.schemaHash,updatedAt:checkpoint.updatedAt}},"checkpoint",{checkpoint}),this.changes.emit(taskId),checkpoint}if(action==="plugin_state"){if(page&&payload.instanceId!==void 0&&payload.instanceId!==page.instanceId)throw error("PLUGIN_PAGE_TARGET_CHANGED","State access cannot change the bound page");if(!this.services)throw new Error("Plugin host services are unavailable");return this.services.state(request.plugin,{...payload,...page?{instanceId:page.instanceId}:{}},bridge,request.options,{revision,signal:controller.signal,expectedTarget:restrictedTarget})}if(action==="plugin_model"){if(payload.operation==="capabilities")return pluginModelCapabilities();if(payload.operation==="list"){if(!this.services)throw new Error("Plugin host services are unavailable");return this.services.listModels(payload.provider)}if(payload.operation!=="run")throw new Error("Plugin commands use model.run; detached model tasks require an explicit task entry");this.assertChildBudget(taskId);let model=normalizePluginModel(payload.request),started=this.start({...request,kind:"model",command:"model",input:{request:model},idempotencyKey:void 0},bridge,{revision,guard,page,parentTaskId:taskId,parentIdentity:identity,documentTarget:restrictedTarget});return this.awaitChild(taskId,started.taskId,bridge.scope,controller.signal,onProgress)}if(action==="plugin_page"){if(!this.services)throw new Error("Plugin host services are unavailable");if(page&&!(payload.operation==="activation"&&payload.enabled===void 0)&&(!["send","get","events"].includes(String(payload.operation))||payload.instanceId!==page.instanceId))throw error("PLUGIN_PAGE_TARGET_CHANGED","Runtime tasks can only access their bound document");return this.services.page(request.plugin,payload,bridge,request.options,{cwd:request.cwd,environment:request.environment,signal:controller.signal,revision,expectedTarget:restrictedTarget,parentIdentity:identity})}if(restrictedTarget&&!["send_request","send_mtop_request","browser_list","connector_list"].includes(action))throw error("PLUGIN_PAGE_TARGET_CHANGED","Runtime tasks must access the document through context.page");if(this.assertRouting(options,request.options),client){if(COMMAND_MAP.has(action)&&!["browser_list","connector_list","agent_chat_run"].includes(action)&&!request.options.browser)throw error("PLUGIN_TASK_TARGET_REQUIRED","Background browser tasks require an explicit browser target");return client.invoke(action,payload,{...request.options,...options})}return bridge.invoke(action,payload,{...request.options,...options})}},{...request.kind==="model"?{model:request.input.request}:{},recovery:recovery!==void 0,onDiagnostic:metadata=>{let record2=this.store.read(taskId);if(++diagnosticUpdates>64){record2.diagnostics?.updatesDropped||(record2.diagnostics={...record2.diagnostics,updatesDropped:!0},this.store.write(record2));return}let model=normalizeModelDiagnostic(metadata,record2.diagnostics?.model);JSON.stringify(model)!==JSON.stringify(record2.diagnostics?.model)&&(this.store.update(taskId,{},"diagnostic",{diagnostics:{...record2.diagnostics,model}}),this.changes.emit(taskId))},onExecutorStopped:()=>{let record2=this.store.read(taskId);record2.diagnostics={...record2.diagnostics,executorStoppedAt:Date.now()},this.store.write(record2)},onExecutorStarted:owner=>{let record2=this.store.read(taskId);record2.executorOwner=owner,this.store.write(record2)},...request.options,cwd:request.cwd,environment:request.environment,signal:controller.signal,source:bridge.scope.source,access:bridge.scope.access,executionTimeoutMs:request.executionTimeoutMs,workerPath:this.configuration.workerPath,onProgress:progress=>{if(Buffer.byteLength(JSON.stringify(progress))>64*1024)throw new Error("Plugin task progress exceeds 64 KiB");this.update(taskId,{progress},"progress")}},{registration:revision.registration});await guard?.(),request.kind==="model"&&(result=validatePluginModelResult(request.input.request,result)),await this.stopChildren(taskId),!page&&request.kind!=="model"&&await this.services?.releaseModels?.(taskId);let reference=this.store.saveResult(taskId,result);this.update(taskId,{state:"success",result:reference})}catch(cause){await this.stopChildren(taskId);let failureCause=cause;if(!page&&request.kind!=="model")try{await this.services?.releaseModels?.(taskId)}catch(cleanupError){failureCause=cleanupError}let failure2=serializePluginExecutionError(failureCause),interrupted=this.closed||failure2.code==="PLUGIN_TASK_BRIDGE_UNAVAILABLE";this.update(taskId,{state:interrupted?"interrupted":failure2.code==="PLUGIN_EXECUTION_CANCELLED"?"cancelled":"error",error:failure2})}finally{client?.disconnect()}}assertRouting(options,bound){if(Object.keys(options).some(key2=>!["browser","connector","session","local","transport","timeoutSec"].includes(key2)))throw error("PLUGIN_TASK_TARGET_CHANGED","Plugin task cannot override internal routing options");for(let key2 of["browser","connector","session","local","transport"])if(options[key2]!==void 0&&options[key2]!==bound[key2])throw error("PLUGIN_TASK_TARGET_CHANGED","Plugin task cannot change its bound browser routing")}assertChildBudget(parent){if(!this.running.get(parent)?.waiting&&[...this.running.values()].filter(item=>item.waiting).length>=32)throw error("PLUGIN_TASK_NESTING_BUDGET","Too many suspended plugin invocations")}async awaitChild(parent,child,scope,signal,onProgress){let running=this.running.get(parent);running&&running.waiting++,queueMicrotask(()=>this.drain());let cancel=()=>this.cancel(child,scope);signal.addEventListener("abort",cancel,{once:!0}),signal.aborted&&cancel();try{return await this.waitResult(child,scope,progress=>{progress!==void 0&&!signal.aborted&&onProgress?.(progress),isPluginTaskActive(this.store.read(parent).task.state)&&this.update(parent,{progress},"progress")})}finally{signal.removeEventListener("abort",cancel),running?.waiting===1&&!signal.aborted&&!this.closed?await new Promise(resolve7=>{let resume=()=>{this.resuming.delete(parent),signal.removeEventListener("abort",resume),running.waiting--,resolve7()};this.resuming.set(parent,resume),signal.addEventListener("abort",resume,{once:!0}),this.drain()}):running&&running.waiting--}}async stopChildren(taskId){let children=[...this.activeChildren.get(taskId)??[]];for(let child of children)this.cancel(child,{access:"public",source:"runtime",bridge:"service"});await Promise.allSettled(children.map(child=>this.running.get(child)?.completed))}async waitResult(taskId,scope,onProgress){let cursor=0;for(;;){let page=await this.events(taskId,scope,cursor,25e3);cursor=page.nextCursor;for(let event of page.events)event.type==="progress"&&onProgress?.(event.progress);if(page.task.state==="success"){let chunks=[];for(let index=0;index<page.task.result.chunks;index++)chunks.push(Buffer.from(this.resultChunk(taskId,scope,index).data,"base64"));let bytes=Buffer.concat(chunks);if(bytes.length!==page.task.result.bytes||createHash10("sha256").update(bytes).digest("hex")!==page.task.result.sha256)throw new Error("Model task result integrity check failed");return JSON.parse(bytes.toString("utf8")).value}if(!isPluginTaskActive(page.task.state))throw Object.assign(pluginExecutionError(page.task.error??{message:"Model task failed"}),{childTaskId:taskId})}}async close(){this.closed=!0,this.descriptions.clear(),this.descriptionBytes=0;for(let resume of[...this.resuming.values()])resume();for(let operation of this.recoveries.values())operation.controller.abort();clearInterval(this.maintenance),await Promise.allSettled([...this.recoveries.values()].map(operation=>operation.promise));for(let taskId of this.queue.keys())this.update(taskId,{state:"interrupted",error:{code:"PLUGIN_TASK_HOST_STOPPED",message:"Plugin execution service stopped"}});this.queue.clear();for(let{controller}of this.running.values())controller.abort();await Promise.allSettled([...[...this.running.values()].map(item=>item.completed)])}};init_pluginStateDefinition();init_pluginRegistry();init_pluginHostPaths();import{readFileSync as readFileSync15}from"node:fs";import{join as join19}from"node:path";init_pluginHostPaths();init_pluginHostFiles();init_pluginStateDefinition();import{createHash as createHash11}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync14,readdirSync as readdirSync7,statSync as statSync11,rmSync as rmSync13}from"node:fs";import{join as join18,sep as sep5}from"node:path";function fail(code,message){throw Object.assign(new Error(message),{code})}function schemaHash(definition){return createHash11("sha256").update(JSON.stringify({schema:definition.schema,storage:definition.storage},(_key,value)=>value&&typeof value=="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0)):value)).digest("hex")}function key(value){(typeof value!="string"||!value.length||Buffer.byteLength(value)>512||["__proto__","constructor","prototype"].includes(value))&&fail("PLUGIN_STATE_INVALID","Invalid state key")}var PluginStateStore=class{constructor(directory=pluginHostPaths().state,now=Date.now){this.directory=directory;this.now=now}directory;now;memory=new Map;memoryBytes=0;memoryRevisionFloor=0;clearMemory(){this.memory.clear(),this.memoryBytes=0,this.memoryRevisionFloor=0}valueBytes=new WeakMap;memorySize(document2){let bytes=Buffer.byteLength(JSON.stringify({...document2,entries:{}})),count=0;for(let[name,entry]of Object.entries(document2.entries)){let valueBytes=typeof entry.value=="object"&&entry.value!==null?this.valueBytes.get(entry.value):void 0;valueBytes===void 0&&(valueBytes=Buffer.byteLength(JSON.stringify(entry.value)),typeof entry.value=="object"&&entry.value!==null&&this.valueBytes.set(entry.value,valueBytes)),bytes+=Buffer.byteLength(JSON.stringify(name))+1+Buffer.byteLength(JSON.stringify({...entry,value:null}))-4+valueBytes+(count++?1:0)}return bytes}saveMemory(path8,document2,bytes=this.memorySize(document2)){let total=this.memoryBytes-(this.memory.get(path8)?.bytes??0)+bytes;(total>128*1024*1024||!this.memory.has(path8)&&this.memory.size>=512)&&fail("PLUGIN_STATE_QUOTA","Memory state exceeds its host limits"),this.memory.set(path8,{document:document2,bytes}),this.memoryBytes=total}path(namespace){(!/^[a-f0-9-]{36}$/i.test(namespace.installationId)||!/^[a-z][a-z0-9-]{0,63}$/.test(namespace.collection))&&fail("PLUGIN_STATE_INVALID","Invalid state namespace");let id=createHash11("sha256").update(namespace.scope).digest("hex");return join18(this.directory,namespace.installationId,`${namespace.collection}-${id}.json`)}read(namespace,definition){try{let file=this.path(namespace),saved=this.memory.get(file);if((definition.storage!=="memory"&&saved||definition.storage==="memory"&&!saved&&existsSync8(file))&&fail("PLUGIN_STATE_STORAGE_CHANGED","Switching between memory and disk state requires a new collection or namespace"),definition.storage==="memory"&&!saved){if(this.memory.size>=512){this.memoryRevisionFloor=Math.max(this.memoryRevisionFloor,...[...this.memory.values()].map(entry=>entry.document.revision))+1;for(let[path8,entry]of this.memory)Object.keys(entry.document.entries).length||(this.memory.delete(path8),this.memoryBytes-=entry.bytes)}throw Object.assign(new Error("Not found"),{code:"ENOENT"})}let document2=saved?{...saved.document,entries:{...saved.document.entries}}:JSON.parse(readFileSync14(file,"utf8"));if(!Number.isSafeInteger(document2.revision)||!Number.isSafeInteger(document2.schemaVersion)||!document2.entries||!Array.isArray(document2.commits))throw new Error("Invalid state document");if(definition.storage!=="persistent"){let entries=Object.fromEntries(Object.entries(document2.entries).filter(([,entry])=>entry.expiresAt===void 0||entry.expiresAt>this.now()));Object.keys(entries).length!==Object.keys(document2.entries).length&&(document2.entries=entries,document2.revision++,definition.storage==="memory"?this.saveMemory(file,document2):writePluginHostFile(file,JSON.stringify(document2)))}return document2}catch(error2){if(error2.code!=="ENOENT")throw error2;return{revision:definition.storage==="memory"?this.memoryRevisionFloor:0,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries:{},commits:[]}}}entry(document2,name,now){let entry=Object.hasOwn(document2.entries,name)?document2.entries[name]:void 0;return entry&&(entry.expiresAt===void 0||entry.expiresAt>now)?{key:name,exists:!0,version:`v:${entry.revision}`,value:document2.storage==="memory"?structuredClone(entry.value):entry.value,...entry.expiresAt===void 0?{}:{expiresAt:entry.expiresAt}}:{key:name,exists:!1,version:`a:${document2.revision}`}}discardScope(installationId,scope){if(!/^[a-f0-9-]{36}$/i.test(installationId)||!scope.startsWith("instance:pi_"))throw new Error("Only ended instance scopes can be discarded");let directory=join18(this.directory,installationId),memorySuffix=`-${createHash11("sha256").update(scope).digest("hex")}.json`;for(let[path8,entry]of this.memory)path8.startsWith(directory+sep5)&&path8.endsWith(memorySuffix)&&(this.memory.delete(path8),this.memoryBytes-=entry.bytes);let suffix=`-${createHash11("sha256").update(scope).digest("hex")}.json`,names;try{names=readdirSync7(directory)}catch(error2){if(error2.code==="ENOENT")return;throw error2}for(let name of names)name.endsWith(suffix)&&rmSync13(join18(directory,name),{force:!0})}prune(skipFile){for(let[path8,saved]of this.memory){let document2={...saved.document,entries:{...saved.document.entries}};for(let[key2,entry]of Object.entries(document2.entries))entry.expiresAt!==void 0&&entry.expiresAt<=this.now()&&delete document2.entries[key2];Object.keys(document2.entries).length!==Object.keys(saved.document.entries).length&&(document2.revision++,this.saveMemory(path8,document2))}let installations;try{installations=readdirSync7(this.directory)}catch(error2){if(error2.code==="ENOENT")return;throw error2}for(let installation of installations)if(/^[a-f0-9-]{36}$/i.test(installation))for(let name of readdirSync7(join18(this.directory,installation))){if(!name.endsWith(".json"))continue;let file=join18(this.directory,installation,name);if(file!==skipFile)try{let document2=JSON.parse(readFileSync14(file,"utf8"));if(document2.storage!=="cache")continue;let entries=Object.fromEntries(Object.entries(document2.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>this.now()));if(Object.keys(entries).length===Object.keys(document2.entries).length)continue;writePluginHostFile(file,JSON.stringify({...document2,revision:document2.revision+1,entries}))}catch(error2){console.error(`Cannot maintain plugin cache ${file}:`,error2)}}}get(namespace,definition,name){key(name);let document2=this.read(namespace,definition);return{...this.entry(document2,name,this.now()),revision:document2.revision,schemaVersion:document2.schemaVersion}}getMany(namespace,definition,names){(!Array.isArray(names)||names.length<1||names.length>128||new Set(names).size!==names.length)&&fail("PLUGIN_STATE_INVALID","Expected 1 to 128 unique state keys"),names.forEach(name=>key(name));let document2=this.read(namespace,definition),now=this.now(),entries=names.map(name=>this.entry(document2,name,now));return Buffer.byteLength(JSON.stringify(entries))>1024*1024&&fail("PLUGIN_STATE_RESPONSE_TOO_LARGE","State batch exceeds 1 MiB; read fewer keys"),{entries,revision:document2.revision,schemaVersion:document2.schemaVersion}}list(namespace,definition,input={}){let document2=this.read(namespace,definition),limit=input.limit??100;(!Number.isSafeInteger(limit)||limit<1||limit>200||input.cursor!==void 0&&typeof input.cursor!="string")&&fail("PLUGIN_STATE_INVALID","Invalid state list cursor or limit"),input.expectedRevision!==void 0&&input.expectedRevision!==document2.revision&&fail("PLUGIN_STATE_CONFLICT","State list changed; restart pagination");let now=this.now(),candidates=Object.keys(document2.entries).sort().filter(name=>(input.cursor===void 0||name>input.cursor)&&this.entry(document2,name,now).exists),entries=[],bytes=0;for(let name of candidates){let entry=this.entry(document2,name,now),size=Buffer.byteLength(JSON.stringify(entry));if(entries.length&&(entries.length>=limit||bytes+size>256*1024))break;entries.push(entry),bytes+=size}return{entries,revision:document2.revision,schemaVersion:document2.schemaVersion,...entries.length<candidates.length?{nextCursor:entries.at(-1).key}:{}}}transact(namespace,definition,input){(!input||!Array.isArray(input.operations)||input.operations.length>128||Buffer.byteLength(JSON.stringify(input))>512*1024)&&fail("PLUGIN_STATE_INVALID","State transaction exceeds its limits");let document2=this.read(namespace,definition),hash=createHash11("sha256").update(JSON.stringify({input,schemaVersion:definition.schemaVersion,schema:definition.schema})).digest("hex");if(input.idempotencyKey!==void 0){(typeof input.idempotencyKey!="string"||!input.idempotencyKey.length||input.idempotencyKey.length>128)&&fail("PLUGIN_STATE_INVALID","Invalid transaction idempotency key");let existing=document2.commits.find(item=>item.id===input.idempotencyKey);if(existing)return existing.hash!==hash&&fail("PLUGIN_STATE_IDEMPOTENCY_CONFLICT","Transaction key refers to different data or schema"),{revision:existing.revision,schemaVersion:document2.schemaVersion,reused:!0}}input.expectedRevision!==void 0&&input.expectedRevision!==document2.revision&&fail("PLUGIN_STATE_CONFLICT","Collection revision changed"),document2.schemaVersion===definition.schemaVersion&&document2.schemaHash!==schemaHash(definition)&&fail("PLUGIN_STATE_SCHEMA_VERSION_REQUIRED","Changing the state schema or storage policy requires a new schemaVersion"),document2.schemaVersion>definition.schemaVersion&&fail("PLUGIN_STATE_SCHEMA_DOWNGRADE","An older plugin revision cannot write a newer state schema"),document2.schemaVersion!==definition.schemaVersion&&(input.migrateFromVersion!==document2.schemaVersion||input.expectedRevision===void 0)&&fail("PLUGIN_STATE_MIGRATION_REQUIRED","Schema migration requires the previous schema version and collection revision"),input.migrateFromVersion!==void 0&&input.migrateFromVersion!==document2.schemaVersion&&fail("PLUGIN_STATE_CONFLICT","State schema changed");let now=this.now(),names=new Set,entries=Object.fromEntries(Object.entries(document2.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>now).map(([name,value])=>[name,{...value}])),revision=document2.revision+1;if(Number.isSafeInteger(revision)||fail("PLUGIN_STATE_QUOTA","State revision limit reached"),document2.storage!==definition.storage)for(let entry of Object.values(entries))entry.revision=revision,definition.storage!=="persistent"?entry.expiresAt=now+(definition.ttlMs??864e5):delete entry.expiresAt;let validate=compilePluginStateSchema(definition.schema);for(let operation of input.operations){if(key(operation.key),(names.has(operation.key)||!["put","delete"].includes(operation.type)||operation.expectedVersion!==this.entry(document2,operation.key,now).version)&&fail("PLUGIN_STATE_CONFLICT","State entry version changed or key repeated"),names.add(operation.key),operation.type==="delete"){delete entries[operation.key];continue}(!validate(operation.value)||Buffer.byteLength(JSON.stringify(operation.value))>256*1024)&&fail("PLUGIN_STATE_SCHEMA_INVALID","State value does not match the declared schema or exceeds 256 KiB");let ttl=operation.ttlMs??definition.ttlMs??864e5;definition.storage==="persistent"&&operation.ttlMs!==void 0&&fail("PLUGIN_STATE_INVALID","Persistent state does not accept TTL"),(!Number.isSafeInteger(ttl)||ttl<1||ttl>7*864e5)&&fail("PLUGIN_STATE_INVALID","Invalid cache TTL"),entries[operation.key]={revision,value:definition.storage==="memory"?structuredClone(operation.value):operation.value,...definition.storage!=="persistent"?{expiresAt:now+ttl}:{}}}for(let entry of Object.values(entries))validate(entry.value)||fail("PLUGIN_STATE_SCHEMA_INVALID","Migration leaves entries incompatible with the target schema");let commit={revision,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries,commits:[...document2.commits,...input.idempotencyKey?[{id:input.idempotencyKey,hash,revision}]:[]].slice(-64)},content=definition.storage==="memory"?"":JSON.stringify(commit),bytes=definition.storage==="memory"?this.memorySize(commit):Buffer.byteLength(content);(Object.keys(entries).length>(definition.maxEntries??1024)||bytes>(definition.maxBytes??8*1024*1024))&&fail("PLUGIN_STATE_QUOTA","State collection quota exceeded");let file=this.path(namespace);if(definition.storage==="memory")return this.saveMemory(file,commit,bytes),{revision,schemaVersion:definition.schemaVersion};let total=Buffer.byteLength(content);try{for(let name of readdirSync7(join18(this.directory,namespace.installationId))){let path8=join18(this.directory,namespace.installationId,name);path8!==file&&name.endsWith(".json")&&(total+=statSync11(path8).size)}}catch(error2){if(error2.code!=="ENOENT")throw error2}if(total>64*1024*1024){this.prune(file),total=Buffer.byteLength(content);for(let name of readdirSync7(join18(this.directory,namespace.installationId))){let path8=join18(this.directory,namespace.installationId,name);path8!==file&&name.endsWith(".json")&&(total+=statSync11(path8).size)}}return total>64*1024*1024&&fail("PLUGIN_STATE_QUOTA","Plugin state exceeds 64 MiB"),writePluginHostFile(file,content),{revision,schemaVersion:definition.schemaVersion}}};var PluginStateManager=class{constructor(tasks){this.tasks=tasks;this.store.prune(),this.maintenance=setInterval(()=>{try{this.store.prune()}catch(error2){console.error("Plugin cache maintenance failed:",error2)}},6e4),this.maintenance.unref()}tasks;store=new PluginStateStore;descriptions=new Map;pending=new Set;controller=new AbortController;resolveTarget;maintenance;async call(plugin,input,bridge,options={},binding){if(this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted(),!/^[a-z][a-z0-9-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin||!input||typeof input!="object"||Array.isArray(input))throw new Error("Invalid plugin state scope");let revision=binding?.revision??capturePluginRevision(plugin),id=`${revision.installationId}/${revision.revision}`,description=this.descriptions.get(id);if(!description){this.descriptions.size>=64&&this.descriptions.delete(this.descriptions.keys().next().value);let release=this.tasks.pinRevision(revision);description=this.tasks.describeRevision(revision,this.controller.signal,{cache:!0}).finally(release),this.descriptions.set(id,description),this.pending.add(description),description.finally(()=>this.pending.delete(description)).catch(()=>{}),description.catch(()=>{this.descriptions.get(id)===description&&this.descriptions.delete(id)})}let declaration=(await description).stateStorage;this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted();let name=String(input.collection??""),definition=declaration&&Object.hasOwn(declaration.collections,name)?declaration.collections[name]:void 0;if(!definition||!/^[a-z][a-z0-9-]{0,63}$/.test(name))throw Object.assign(new Error("Plugin state collection is not declared"),{code:"PLUGIN_STATE_NOT_DECLARED"});if(input.expectedDeclaration!==void 0&&input.expectedDeclaration!==pluginStateSignature(definition))throw Object.assign(new Error("Plugin state declaration changed during command execution"),{code:"PLUGIN_STATE_REVISION_CHANGED"});let scope=definition.scope,assertScope=()=>{};if(definition.scope==="host"&&(scope+=`:${this.tasks.host.hostId}`),definition.scope==="instance"||definition.scope==="browser-session"){if(!this.resolveTarget)throw new Error("Page state scope is unavailable");let resolved=await this.resolveTarget(plugin,input.instanceId,bridge,options),target=resolved.target,expected=binding?.expectedTarget;if(expected&&(target.browserSessionId!==expected.browserSessionId||target.tabId!==expected.tabId||target.frameId!==expected.frameId||target.documentId!==expected.documentId))throw Object.assign(new Error("State access cannot change the inherited document"),{code:"PLUGIN_PAGE_TARGET_CHANGED"});assertScope=resolved.assertActive,scope+=definition.scope==="instance"?`:${String(input.instanceId)}`:`:${target.browserSessionId}`}this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted();let installation;try{installation=JSON.parse(readFileSync15(join19(pluginHostPaths().installations,`${plugin}.json`),"utf8"))}catch{}if(!findPluginRegistration(plugin)||installation?.installationId!==revision.installationId)throw Object.assign(new Error("Plugin state installation was removed or replaced"),{code:"PLUGIN_STATE_SCOPE_ENDED"});assertScope();let namespace={installationId:revision.installationId,collection:name,scope};switch(input.operation){case"get":return this.store.get(namespace,definition,input.key);case"get-many":return this.store.getMany(namespace,definition,input.keys);case"list":return this.store.list(namespace,definition,input);case"transact":return this.store.transact(namespace,definition,input.transaction);default:throw new Error("Invalid state operation")}}async close(){clearInterval(this.maintenance),this.controller.abort(),this.descriptions.clear(),this.store.clearMemory(),await Promise.allSettled([...this.pending])}};import{createHash as createHash12,randomUUID as randomUUID12}from"node:crypto";import{EventEmitter as EventEmitter3}from"node:events";import{readFileSync as readFileSync16,statSync as statSync12}from"node:fs";import{isAbsolute as isAbsolute8,join as join20}from"node:path";init_plugin();init_pluginPageDefinition();init_unified();init_pluginHostPaths();init_pluginExecutorProtocol();init_dist2();init_dist2();function failure(code,message){return Object.assign(new Error(message),{code})}function sameTarget(a,b){return a.browserSessionId===b.browserSessionId&&a.tabId===b.tabId&&a.frameId===b.frameId&&a.documentId===b.documentId}var PluginPageManager=class{constructor(tasks,states,releaseModels){this.tasks=tasks;this.states=states;this.releaseModels=releaseModels;this.heartbeat=setInterval(()=>{this.reconcile()},1e4),this.heartbeat.unref()}tasks;states;releaseModels;instances=new Map;changes=new EventEmitter3().setMaxListeners(0);heartbeat;reconciling=new Set;closed=!1;describing=new Set;async resolveStateTarget(plugin,instanceId,bridge,options){let record2=this.own(plugin,instanceId,bridge);return await this.bind(record2,bridge,options),await this.validate(record2),{target:{...record2.value.target},assertActive:()=>{if(this.closed||record2.value.state!=="active"||this.instances.get(record2.value.instanceId)!==record2)throw failure("PLUGIN_STATE_SCOPE_ENDED","Plugin page state scope has ended")}}}diagnosticSnapshot(){return[...this.instances.values()].map(record2=>({plugin:record2.value.plugin,installationId:record2.value.installationId,revision:record2.value.revision,host:{hostId:record2.value.host.hostId,epoch:record2.value.host.epoch},binding:diagnosticBinding(record2.value),observation:"service-snapshot",state:record2.value.state,lastReceived:record2.lastReceived,queued:record2.deliveries.filter(delivery=>delivery.state==="queued").length,running:record2.running.size}))}async reconcile(){this.closed||await Promise.all([...this.instances.values()].map(async record2=>{let id=record2.value.instanceId;if(!(!record2.ready||record2.value.state!=="active"||this.reconciling.has(id))){this.reconciling.add(id);try{await this.validate(record2)}catch(error2){isPluginPageUnavailable(error2)||await this.invalidate(record2,error2)}finally{this.reconciling.delete(id)}}}))}bounded(promise,milliseconds){return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>reject(failure("PLUGIN_PAGE_TIMEOUT","Plugin page browser request timed out")),milliseconds);promise.then(resolve7,reject).finally(()=>clearTimeout(timer))})}async invoke(record2,data2,timeoutSec){let payload={...data2,tabId:record2.value.target.tabId,instanceId:record2.value.instanceId,...timeoutSec!==void 0?{timeoutSec}:{}};return record2.client?record2.client.invoke("page_runtime",payload,{...record2.options,...timeoutSec!==void 0?{timeoutSec}:{}}):record2.bridge.invoke("page_runtime",payload,{...record2.options,...timeoutSec!==void 0?{timeoutSec}:{}})}unavailable(record2,error2){return isPluginPageInvalidation(error2)?error2:(record2.unavailable=!0,Date.now()-record2.lastVerifiedAt>=3e4?failure("PLUGIN_PAGE_INVALIDATED","Plugin page host recovery lease expired"):pluginPageUnavailable(error2))}async validate(record2){if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance is no longer active");let registration=findPluginRegistration(record2.value.plugin),installation;try{installation=JSON.parse(readFileSync16(join20(pluginHostPaths().installations,`${record2.value.plugin}.json`),"utf8"))}catch{}if(!registration||installation?.installationId!==record2.value.installationId)throw failure("PLUGIN_PAGE_INVALIDATED","Plugin installation was removed or replaced");let bridge=record2.bridge,current2;try{current2=await this.bounded(this.invoke(record2,{operation:"get"}),8e3)}catch(error2){if(!record2.client&&record2.bridge!==bridge&&!this.closed&&record2.value.state==="active")return this.validate(record2);throw this.unavailable(record2,error2)}if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance ended during validation");if(current2.state!=="active"||!sameTarget(current2.target,record2.value.target)||!matchesPluginPageURL(record2.runtime.matches,current2.target.url))throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page document changed");record2.value.target.url=current2.target.url,record2.lastVerifiedAt=Date.now();let recovered=record2.unavailable;record2.unavailable=!1,recovered&&queueMicrotask(()=>this.drain(record2))}own(plugin,instanceId,bridge){if(bridge.scope.plugin&&bridge.scope.plugin!==plugin)throw failure("PLUGIN_PAGE_NOT_FOUND","Plugin page instance was not found");if(!isPluginPageInstanceId(instanceId))throw failure("PLUGIN_PAGE_NOT_FOUND","Invalid plugin page instance ID");let record2=this.instances.get(instanceId);if(!record2||record2.value.plugin!==plugin)throw failure("PLUGIN_PAGE_NOT_FOUND","Plugin page instance was not found");return record2}async bind(record2,bridge,options){if(bridge.scope.bridge!=="caller"||!record2.client&&record2.bridge.id===bridge.id||record2.value.state!=="active")return;let current2;try{current2=await this.bounded(bridge.invoke("page_runtime",{operation:"get",tabId:record2.value.target.tabId,instanceId:record2.value.instanceId},options),8e3)}catch(error2){throw this.unavailable(record2,error2)}if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance ended while binding");if(!sameTarget(current2.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Plugin page belongs to a different browser document");record2.client||(record2.bridge=bridge,record2.options=options)}append(record2,event){for(record2.history.push({...event,sequence:++record2.value.sequence,time:Date.now()});record2.history.length>256||Buffer.byteLength(JSON.stringify(record2.history))>384*1024;)record2.history.shift();this.changes.emit(record2.value.instanceId)}async waitForChange(record2,cursor,waitMs,signal){!waitMs||cursor!==record2.value.sequence||record2.value.state!=="active"||await new Promise((resolve7,reject)=>{let finish=()=>{cleanup(),resolve7()},abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin page subscription closed"))},timer=setTimeout(finish,waitMs),cleanup=()=>{clearTimeout(timer),this.changes.off(record2.value.instanceId,finish),signal?.removeEventListener("abort",abort)};this.changes.once(record2.value.instanceId,finish),signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted?abort():(record2.value.sequence!==cursor||record2.value.state!=="active")&&finish()})}async invalidate(record2,error2,state="invalidated"){if(record2.value.state==="active"){record2.value.state=state,record2.value.error=serializePluginExecutionError(error2),this.append(record2,{type:"invalidated",error:record2.value.error});for(let taskId of record2.taskIds)this.tasks.cancel(taskId,{access:"public",source:"runtime",bridge:"service"});for(let delivery of record2.deliveries)delivery.taskId&&this.tasks.cancel(delivery.taskId,{access:"public",source:"runtime",bridge:"service"}),["queued","running"].includes(delivery.state)&&(delivery.state="invalidated");try{this.states.store.discardScope(record2.value.installationId,`instance:${record2.value.instanceId}`)}catch(error3){console.error("Plugin instance cache cleanup failed:",error3)}record2.release();try{await this.releaseModels?.(record2.value.instanceId)}finally{try{await this.bounded(this.invoke(record2,{operation:"detach"}),2e3)}catch{}record2.client?.disconnect()}}}async call(plugin,input,bridge,options={},execution={cwd:process.cwd(),environment:Object.fromEntries(Object.entries(process.env).filter(entry=>entry[1]!==void 0))}){if(this.closed)throw failure("PLUGIN_PAGE_HOST_STOPPING","Plugin page service is stopping");if(execution.signal?.throwIfAborted(),!input||typeof input!="object"||Array.isArray(input))throw new Error("Invalid plugin page request");if(!/^[a-z][a-z0-9-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin)throw new Error("Invalid plugin page scope");let operation=input.operation;if(execution.expectedTarget&&operation==="activation"&&input.enabled!==void 0)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Document-bound calls cannot configure browser activation");if(operation==="attach"||operation==="activation"){if(Object.keys(options).some(key2=>!["browser","connector","session","local","transport","timeoutSec"].includes(key2)))throw new Error("Invalid plugin page routing options");if(bridge.scope.bridge==="service"&&!decodeBrowserTarget(options.browser))throw new Error("Plugin pages require a stable browser ID");if(!execution||!isAbsolute8(execution.cwd)||!statSync12(execution.cwd).isDirectory()||!execution.environment||Buffer.byteLength(JSON.stringify(execution.environment))>512*1024||Object.values(execution.environment).some(value=>typeof value!="string"))throw new Error("Invalid plugin page execution context")}if(operation==="activation"&&input.enabled!==!0){let client=bridge.scope.bridge==="service"?new UnifiedClient:void 0;try{return client?await client.invoke("page_runtime",{...input,plugin},options):await bridge.invoke("page_runtime",{...input,plugin},options)}finally{client?.disconnect()}}if(operation==="attach"||operation==="activation"){let revision=execution.revision??capturePluginRevision(plugin);if(input.installationId!==void 0&&input.installationId!==revision.installationId)throw failure("PLUGIN_PAGE_INSTALLATION_CHANGED","Page activation belongs to another plugin installation");let release=this.tasks.pinRevision(revision),retained=!1,client=bridge.scope.bridge==="service"?new UnifiedClient:void 0,invoke2=data2=>client?client.invoke("page_runtime",data2,options):bridge.invoke("page_runtime",data2,options);try{let controller=new AbortController,description={controller,promise:this.tasks.describeRevision(revision,execution.signal?AbortSignal.any([controller.signal,execution.signal]):controller.signal,{cache:!0})};this.describing.add(description);let loaded;try{loaded=await description.promise}finally{this.describing.delete(description)}if(this.closed)throw new Error("Plugin page host stopped during attachment");let runtime=loaded.pageRuntime;if(!runtime)throw failure("PLUGIN_PAGE_NOT_DECLARED","Plugin has no pageRuntime declaration");if(operation==="activation")return await invoke2({...input,operation:"activation",plugin,installationId:revision.installationId,allowedMatches:runtime.matches});if(this.instances.size>=256){for(let[id,item]of this.instances)item.value.state!=="active"&&!item.running.size&&this.instances.delete(id);if(this.instances.size>=256)throw new Error("Too many plugin page instances")}let target=await invoke2({operation:"resolve",tabId:input.tabId,frame:input.frame,expectedDocumentId:input.documentId});if(this.closed)throw failure("PLUGIN_PAGE_HOST_STOPPING","Plugin page service is stopping");if(execution.signal?.throwIfAborted(),execution.expectedTarget&&!sameTarget(target,execution.expectedTarget))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Nested plugin must use the inherited document");if(!matchesPluginPageURL(runtime.matches,target.url))throw failure("PLUGIN_PAGE_URL_NOT_ALLOWED","Plugin page URL is outside its declared matches");let existing=[...this.instances.values()].find(item=>item.value.state==="active"&&item.value.plugin===plugin&&sameTarget(item.value.target,target));if(existing&&execution.revision&&existing.value.revision!==revision.revision&&input.replace!==!0)throw failure("PLUGIN_PAGE_REVISION_CHANGED","Existing page instance uses another plugin revision");if(existing&&input.replace!==!0)try{return await existing.initialized,await this.bind(existing,bridge,options),await this.validate(existing),input.activationGeneration===void 0&&await invoke2({operation:"get",instanceId:existing.value.instanceId,tabId:target.tabId,retainManual:!0}),existing.value}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(existing,error2)}existing&&await this.invalidate(existing,new Error("Plugin page instance replaced"),"detached");let value={instanceId:`pi_${randomUUID12()}`,plugin,installationId:revision.installationId,revision:revision.revision,host:this.tasks.host,target,state:"active",sequence:0,createdAt:Date.now()},initialized,initializationFailed,initialization=new Promise((resolve7,reject)=>{initialized=resolve7,initializationFailed=reject});initialization.catch(()=>{});let record3={initialized:initialization,value,runtime,revision,release,bridge,options:{...options},client,ready:!1,lastVerifiedAt:Date.now(),unavailable:!1,taskIds:new Set,execution:{cwd:execution.cwd,environment:{...execution.environment}},history:[],deliveries:[],lastReceived:0,running:new Set};this.instances.set(value.instanceId,record3);try{let attached=await invoke2({operation:"attach",instance:value,runtime,input:input.input??{},frame:input.frame??"business",activationGeneration:input.activationGeneration});if(!sameTarget(attached.target,target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Document changed while attaching plugin page");if(await this.validate(record3),execution.signal?.throwIfAborted(),runtime.initialize){let parent=execution.parentIdentity;parent?.taskId&&this.tasks.assertChildBudget(parent.taskId);let{taskId}=this.start(record3,runtime.initialize,{input:input.input??{}},`initialize:${value.instanceId}`,parent),scope={access:"public",source:"runtime",bridge:"service"},cancel2=()=>this.tasks.cancel(taskId,scope);execution.signal?.addEventListener("abort",cancel2,{once:!0}),execution.signal?.aborted&&cancel2();try{parent?.taskId&&execution.signal?await this.tasks.awaitChild(parent.taskId,taskId,scope,execution.signal):await this.wait(record3,taskId)}finally{execution.signal?.removeEventListener("abort",cancel2),record3.taskIds.delete(taskId)}}return execution.signal?.throwIfAborted(),await this.validate(record3),execution.signal?.throwIfAborted(),record3.ready=!0,initialized(),this.drain(record3),retained=!0,value}catch(error2){throw initializationFailed(error2),await this.invalidate(record3,error2),error2}}finally{retained||(release(),client?.disconnect())}}if(operation==="list")return{instances:[...this.instances.values()].filter(item=>item.value.plugin===plugin&&(!execution.expectedTarget||sameTarget(item.value.target,execution.expectedTarget))).map(item=>item.value)};let record2=this.own(plugin,input.instanceId,bridge);if(execution.expectedTarget&&!sameTarget(record2.value.target,execution.expectedTarget))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Nested plugin must use the inherited document");if(execution.revision&&record2.value.revision!==execution.revision.revision)throw failure("PLUGIN_PAGE_REVISION_CHANGED","Page instance uses another plugin revision");if(await this.bind(record2,bridge,options),operation==="detach")return await this.invalidate(record2,new Error("Plugin page instance detached"),"detached"),record2.value;try{record2.value.state==="active"&&await this.validate(record2)}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(record2,error2)}if(operation==="get")return record2.value;if(operation==="events"){let cursor=input.cursor??0,waitMs=input.waitMs??0;if(!Number.isSafeInteger(cursor)||Number(cursor)<0||Number(cursor)>record2.value.sequence)throw new Error("Invalid plugin page event cursor");if(!Number.isSafeInteger(waitMs)||Number(waitMs)<0||Number(waitMs)>25e3)throw new Error("Invalid plugin page event wait");await this.waitForChange(record2,Number(cursor),Number(waitMs),execution.signal),execution.signal?.throwIfAborted();let first=record2.history[0]?.sequence??record2.value.sequence+1,events=[],bytes=0;for(let event of record2.history)if(event.sequence>Number(cursor)){let size=Buffer.byteLength(JSON.stringify(event));if(events.length&&bytes+size>192*1024)break;events.push(event),bytes+=size}return{instance:record2.value,events,nextCursor:events.at(-1)?.sequence??Number(cursor),firstAvailableSequence:first,gap:Number(cursor)<first-1}}if(operation!=="send")throw new Error("Unknown plugin page operation");let timeoutSec=input.timeoutSec;if(timeoutSec!==void 0&&(typeof timeoutSec!="number"||!Number.isFinite(timeoutSec)||timeoutSec<=0||timeoutSec>300))throw new Error("Page request timeoutSec must be between 0 and 300");await this.validate(record2),execution.signal?.throwIfAborted();let json2=Buffer.from(JSON.stringify(input.message??null));if(json2.length>24*1024*1024)throw new Error("Plugin page message exceeds 24 MiB");let requestId=randomUUID12(),cancel=()=>{this.invoke(record2,{operation:"cancel",requestId}).catch(()=>{})};execution.signal?.addEventListener("abort",cancel,{once:!0});try{let result;if(json2.length<=192*1024)result=await this.invoke(record2,{operation:"send",message:input.message,requestId},timeoutSec);else{let transferId=randomUUID12();try{await this.invoke(record2,{operation:"message_begin",transferId,bytes:json2.length,sha256:createHash12("sha256").update(json2).digest("hex")});for(let offset2=0,index=0;offset2<json2.length;offset2+=192*1024,index++)await this.validate(record2),execution.signal?.throwIfAborted(),await this.invoke(record2,{operation:"message_chunk",transferId,index,data:json2.subarray(offset2,offset2+192*1024).toString("base64")});await this.validate(record2),execution.signal?.throwIfAborted(),result=await this.invoke(record2,{operation:"message_commit",transferId,requestId},timeoutSec)}finally{await this.invoke(record2,{operation:"message_abort",transferId}).catch(()=>{})}}execution.signal?.throwIfAborted(),await this.validate(record2);let reply=result;if(reply?.kind==="value")return reply.value;if(reply?.kind!=="resource"||!Number.isSafeInteger(reply.bytes)||reply.bytes<1||reply.bytes>24*1024*1024||reply.chunks!==Math.ceil(reply.bytes/(192*1024)))throw new Error("Invalid page response resource");try{let parts=[];for(let index=0;index<reply.chunks;index++){await this.validate(record2);let chunk=await this.invoke(record2,{operation:"result_chunk",resultId:reply.resultId,index});if(chunk.resultId!==reply.resultId||chunk.index!==index||chunk.bytes!==reply.bytes||chunk.sha256!==reply.sha256||chunk.chunks!==reply.chunks)throw new Error("Page response chunk identity mismatch");parts.push(Buffer.from(chunk.data,"base64"))}let bytes=Buffer.concat(parts);if(bytes.length!==reply.bytes||createHash12("sha256").update(bytes).digest("hex")!==reply.sha256)throw new Error("Page response integrity check failed");return await this.validate(record2),JSON.parse(bytes.toString("utf8"))}finally{await this.invoke(record2,{operation:"result_release",resultId:reply.resultId}).catch(()=>{})}}catch(error2){throw cancel(),error2}finally{execution.signal?.removeEventListener("abort",cancel)}}async receive(plugin,input,bridge,options={}){if(input.kind==="sync"){if(this.closed||!/^[a-z][a-z0-9-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin||!Array.isArray(input.instances)||input.instances.length>32)throw new Error("Invalid page reconciliation request");let session2=await this.bounded(bridge.invoke("page_runtime",{operation:"session"},options),8e3);if(typeof input.browserSessionId!="string"||session2.browserSessionId!==input.browserSessionId)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page reconciliation came from another browser session");let instances=[];for(let value of input.instances){let proposed=value,record3=this.instances.get(proposed?.instanceId);if(!(!record3||record3.value.plugin!==plugin||record3.value.state!=="active"||!proposed.host||proposed.host.hostId!==this.tasks.host.hostId||proposed.host.epoch!==this.tasks.host.epoch||proposed.installationId!==record3.value.installationId||proposed.revision!==record3.value.revision||!proposed.target||!sameTarget(proposed.target,record3.value.target)||record3.value.target.browserSessionId!==session2.browserSessionId))try{await this.bind(record3,bridge,options),await this.validate(record3),instances.push({instance:record3.value,lastReceived:record3.lastReceived})}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(record3,error2)}}return{host:this.tasks.host,instances}}let record2=this.own(plugin,input.instanceId,bridge);if((await this.bounded(bridge.invoke("page_runtime",{operation:"session"},options),8e3)).browserSessionId!==record2.value.target.browserSessionId)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page event came from another browser");if(input.kind==="invalidated"){if(!input.target||!sameTarget(input.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Invalid document invalidation source");return await this.invalidate(record2,new Error("Browser invalidated the document")),{accepted:!0}}let source=await this.bounded(bridge.invoke("page_runtime",{operation:"get",tabId:record2.value.target.tabId,instanceId:record2.value.instanceId},options),8e3);if(!sameTarget(source.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page event came from another document");if(await this.bind(record2,bridge,options),await this.validate(record2),input.kind==="navigation")return this.append(record2,{type:"navigation",payload:{url:record2.value.target.url}}),{accepted:!0};let sequence=input.eventSequence;if(!Number.isSafeInteger(sequence)||Number(sequence)<1)throw new Error("Invalid page event sequence");let duplicate=record2.deliveries.find(item=>item.sequence===sequence);if(Number(sequence)<=record2.lastReceived)return{accepted:!0,duplicate:!0,taskId:duplicate?.taskId,gap:!duplicate};if(Number(sequence)!==record2.lastReceived+1)throw failure("PLUGIN_PAGE_EVENT_GAP","Page event stream has a gap; reattach the instance");let name=typeof input.name=="string"?input.name:"",binding=record2.runtime.events?.[name];if(!binding||Buffer.byteLength(JSON.stringify(input.payload??null))>32*1024)throw new Error("Page event is not declared or exceeds 32 KiB");if(!compilePluginPageSchema(binding.schema)(input.payload))throw failure("PLUGIN_PAGE_EVENT_INVALID","Page event payload does not match its schema");let waiting=record2.deliveries.filter(item=>item.name===name&&item.state==="queued");if(binding.policy==="latest")for(let previous of waiting)previous.state="superseded",this.append(record2,{type:"superseded",eventSequence:previous.sequence,name});else if(waiting.length>=(binding.maxPending??32))throw failure("PLUGIN_PAGE_QUEUE_FULL","Page event queue is full");if(record2.deliveries.filter(item=>["queued","running"].includes(item.state)).length>=128)throw failure("PLUGIN_PAGE_QUEUE_FULL","Page event queue is full");let delivery={sequence:Number(sequence),name,payload:input.payload,state:"queued"};for(record2.lastReceived=Number(sequence),record2.deliveries.push(delivery);record2.deliveries.length>256;){let index=record2.deliveries.findIndex(item=>!["queued","running"].includes(item.state));if(index<0)break;record2.deliveries.splice(index,1)}return this.append(record2,{type:"received",eventSequence:delivery.sequence,name,payload:input.payload}),this.drain(record2),{accepted:!0,eventSequence:delivery.sequence,taskId:delivery.taskId}}drain(record2){if(!(this.closed||!record2.ready||record2.unavailable||record2.value.state!=="active"))for(let delivery of record2.deliveries){if(delivery.state!=="queued")continue;let binding=record2.runtime.events[delivery.name];[...record2.running].filter(item=>item.name===delivery.name).length>=(binding.policy==="parallel"?binding.concurrency??2:1)||(delivery.state="running",record2.running.add(delivery),this.execute(record2,delivery).finally(()=>{record2.running.delete(delivery),this.drain(record2)}))}}async execute(record2,delivery){try{await this.validate(record2);let binding=record2.runtime.events[delivery.name],started=this.start(record2,binding.command,{event:{name:delivery.name,payload:delivery.payload,sequence:delivery.sequence}},`page:${record2.value.instanceId}:${delivery.sequence}`);delivery.taskId=started.taskId,this.append(record2,{type:"running",name:delivery.name,eventSequence:delivery.sequence,taskId:started.taskId}),await this.wait(record2,started.taskId),delivery.state="success",this.append(record2,{type:"success",name:delivery.name,eventSequence:delivery.sequence,taskId:started.taskId})}catch(error2){if(isPluginPageUnavailable(error2)&&!delivery.taskId&&record2.value.state==="active"){delivery.state="queued";return}delivery.state="error",this.append(record2,{type:"error",name:delivery.name,eventSequence:delivery.sequence,error:serializePluginExecutionError(error2)})}}start(record2,command,input,key2,parentIdentity){let bridge={get id(){return record2.bridge.id},scope:{...record2.bridge.scope,plugin:record2.value.plugin,access:"runtime",source:"runtime"},invoke:(action,payload,options)=>record2.client?record2.client.invoke(action,payload,options):record2.bridge.invoke(action,payload,options)},started=this.tasks.start({plugin:record2.value.plugin,command,input,cwd:record2.execution.cwd,environment:record2.execution.environment,options:record2.options,idempotencyKey:key2},bridge,{...parentIdentity?.taskId?{parentTaskId:parentIdentity.taskId,parentIdentity}:{},revision:record2.revision,guard:()=>this.validate(record2),page:{instanceId:record2.value.instanceId,target:{...record2.value.target}}});return record2.taskIds.add(started.taskId),started}async wait(record2,taskId){let cursor=0;for(;;){let page=await this.tasks.events(taskId,{access:"public",source:"runtime",bridge:"service"},cursor,25e3);if(cursor=page.nextCursor,!isPluginTaskActive(page.task.state)){if(record2.taskIds.delete(taskId),page.task.state!=="success")throw Object.assign(pluginExecutionError(page.task.error??{message:"Page handler failed"}),{childTaskId:taskId});return}record2.value.state!=="active"&&this.tasks.cancel(taskId,{access:"public",source:"runtime",bridge:"service"})}}async close(){this.closed=!0,clearInterval(this.heartbeat);for(let item of this.describing)item.controller.abort();await Promise.allSettled([...this.describing].map(item=>item.promise)),await Promise.allSettled([...this.instances.values()].map(record2=>this.invalidate(record2,new Error("Plugin page host stopped"))))}};var PluginModelCatalog=class{constructor(discover=async signal=>{let{listCodexModels:listCodexModels2}=await Promise.resolve().then(()=>(init_codex(),codex_exports));return listCodexModels2(signal)},now=Date.now){this.discover=discover;this.now=now}discover;now;controller=new AbortController;cached;pending;list(provider="codex"){if(this.controller.signal.throwIfAborted(),provider!=="codex")throw new Error("Unsupported model provider");return this.cached?(this.cached.expires<=this.now()&&this.refresh().catch(()=>{}),Promise.resolve(structuredClone(this.cached.value))):this.refresh().then(value=>structuredClone(value))}refresh(){return this.pending??=this.load().catch(error2=>{throw this.cached&&(this.cached.expires=this.now()+3e4),error2}).finally(()=>{this.pending=void 0}),this.pending}async load(){let signal=AbortSignal.any([this.controller.signal,AbortSignal.timeout(15e3)]),value={provider:"codex",models:await this.discover(signal)};return signal.throwIfAborted(),this.cached={value,expires:this.now()+12e4},value}async close(){this.controller.abort(),await this.pending?.catch(()=>{}),this.cached=void 0}};init_runtimePaths();init_dist();init_pluginExecutorProtocol();init_pluginProcessTree();init_pluginModelDefinition();import{fork as fork2}from"node:child_process";import{createHash as createHash13}from"node:crypto";var PluginModelSessions=class{constructor(idleMs=5*6e4,limit=2,workerPath=PLUGIN_MODEL_SESSION_WORKER_PATH){this.idleMs=idleMs;this.limit=limit;this.workerPath=workerPath}idleMs;limit;workerPath;sessions=new Map;closing=new Set;closed=!1;execute(owner,...args){let[plugin,,context,options={}]=args,request=options.model,configuration=Object.fromEntries(Object.entries(request).filter(([key3])=>!["prompt","outputSchema"].includes(key3)).sort(([a],[b])=>a.localeCompare(b))),key2=createHash13("sha256").update(JSON.stringify([owner,plugin,context.invocation?.installationId,context.invocation?.revision,options.cwd,Object.entries(options.environment??{}).sort(([a],[b])=>a.localeCompare(b)),configuration])).digest("hex");if(options.signal?.throwIfAborted(),this.closed)return Promise.reject(new Error("Model conversations are closed"));let session=this.sessions.get(key2);if(!session||session.closed){if(this.sessions.size>=this.limit){let idle=[...this.sessions.values()].find(value=>!value.queued);if(!idle)return Promise.reject(new Error("Model conversation limit reached"));this.remove(idle).catch(error2=>console.error("Model conversation cleanup failed:",error2))}let child=fork2(this.workerPath,[],{stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced",execArgv:[],detached:process.platform!=="win32",cwd:options.cwd,env:options.environment}),exited=new Promise(resolve7=>child.once("close",()=>resolve7()));session={owner,child,tail:Promise.resolve(),queued:0,closed:!1,exited};let current3=session;child.on("error",()=>{this.remove(current3).catch(error2=>console.error("Model conversation cleanup failed:",error2))}),child.once("exit",()=>{this.remove(current3).catch(error2=>console.error("Model conversation cleanup failed:",error2))}),this.sessions.set(key2,session)}this.sessions.delete(key2),this.sessions.set(key2,session),clearTimeout(session.timer);let current2=session;current2.queued++;let started=!1,operation=current2.tail.catch(()=>{}).then(async()=>{if(options.signal?.throwIfAborted(),current2.closed)throw new Error("Model conversation has ended");return started=!0,this.run(current2,args)});if(current2.tail=operation.finally(()=>{current2.queued--,!current2.queued&&!current2.closed&&(current2.timer=setTimeout(()=>{this.remove(current2).catch(error2=>console.error("Model conversation cleanup failed:",error2))},this.idleMs),current2.timer.unref())}),current2.tail.catch(()=>{}),!options.signal)return operation;let signal=options.signal;return new Promise((resolve7,reject)=>{let abort=()=>{started||reject(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"}))};signal.addEventListener("abort",abort,{once:!0}),signal.aborted&&abort(),operation.then(resolve7,reject).finally(()=>signal.removeEventListener("abort",abort))})}run(session,args){let options=args[3],request=options.model,child=session.child;return new Promise((resolve7,reject)=>{let finished=!1,stderr="",timer,finish=async(failure2,result)=>{if(!finished){finished=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",abort),child.removeListener("message",message),child.removeListener("error",failed),child.removeListener("exit",exited),child.stderr?.removeListener("data",capture);try{failure2&&await this.remove(session),options.onExecutorStopped?.(),failure2?reject(failure2):resolve7(result)}catch(error2){reject(error2)}}},failed=error2=>{finish(error2)},exited=()=>failed(new Error(stderr||"Model conversation executor exited")),abort=()=>failed(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"})),capture=chunk=>{stderr=(stderr+chunk.toString()).slice(-65536)},message=event=>{if(!finished)try{event.type==="result"?finish(void 0,validatePluginModelResult(request,event.result)):event.type==="error"?failed(pluginExecutionError(event.error)):event.type==="diagnostic"?options.onDiagnostic?.(event.metadata):event.type==="delta"&&options.onProgress?.({message:"model.delta",data:{delta:event.delta,index:event.index,...event.metadata,partial:!0}})}catch(error2){finish(error2)}};child.on("message",message),child.once("error",failed),child.once("exit",exited),child.stderr?.on("data",capture),options.signal?.addEventListener("abort",abort,{once:!0}),options.executionTimeoutMs&&(timer=setTimeout(()=>failed(Object.assign(new Error("Model execution deadline exceeded"),{code:"PLUGIN_EXECUTION_DEADLINE"})),options.executionTimeoutMs));try{if(options.signal?.aborted){abort();return}child.pid&&options.onExecutorStarted?.({pid:child.pid,processIdentity:processIdentity(child.pid)}),child.send({request},error2=>{error2&&failed(error2)})}catch(error2){finish(error2)}})}remove(session){if(session.closing)return session.closing;session.closed=!0,clearTimeout(session.timer);for(let[key2,value]of this.sessions)value===session&&this.sessions.delete(key2);return session.closing=(session.child.pid?stopPluginProcessTree(session.child.pid):Promise.resolve()).then(()=>{let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("Model conversation did not exit")),2e3)});return Promise.race([session.exited,timeout]).finally(()=>clearTimeout(timer))}).catch(cause=>{throw Object.assign(new Error("Unable to confirm model conversation cleanup",{cause}),{code:"PLUGIN_EXECUTOR_CLEANUP_FAILED",details:{executionStopped:!1}})}),this.closing.add(session),session.closing.finally(()=>this.closing.delete(session)).catch(()=>{}),session.closing}async release(owner){await Promise.all([...new Set([...this.sessions.values(),...this.closing])].filter(value=>value.owner===owner).map(value=>this.remove(value)))}async close(){this.closed=!0,await Promise.all([...new Set([...this.sessions.values(),...this.closing])].map(value=>this.remove(value)))}};import{dirname as dirname9,join as join21}from"node:path";var PluginHost=class{tasks;state;pages;models=new PluginModelCatalog;modelSessions;closing;constructor(configuration={}){this.modelSessions=new PluginModelSessions(void 0,Math.max(2,configuration.modelConcurrency??2),configuration.workerPath?join21(dirname9(configuration.workerPath),"pluginModelSessionWorker.js"):void 0),this.tasks=new PluginTaskManager(configuration,{state:(...args)=>this.state.call(...args),page:(...args)=>this.pages.call(...args),listModels:provider=>this.models.list(provider),model:(owner,...args)=>this.modelSessions.execute(owner,...args),releaseModels:owner=>this.modelSessions.release(owner)}),this.state=new PluginStateManager(this.tasks),this.pages=new PluginPageManager(this.tasks,this.state,owner=>this.modelSessions.release(owner)),this.state.resolveTarget=(...args)=>this.pages.resolveStateTarget(...args)}diagnose(value,scope){let options=normalizeDiagnosticOptions(value);if(scope.plugin&&options.plugin&&scope.plugin!==options.plugin)throw Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"});return buildDiagnosticReport(this.tasks.host,scope,options,this.tasks.store.diagnosticRecords(options.taskId),this.pages.diagnosticSnapshot())}close(){return this.closing??=Promise.allSettled([this.pages.close(),this.tasks.close(),this.state.close(),this.models.close(),this.modelSessions.close()]).then(results=>{let failures=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(failures.length)throw new AggregateError(failures,"Plugin host cleanup failed")}),this.closing}};init_pluginTaskWire();init_pluginExecutorProtocol();async function startPluginHostServer(configuration={}){let paths=pluginHostPaths(),existing=readRecord(paths.lease);existing&&!isProcessOwnerAlive(existing)?removeRecordIfPid(paths.lease,existing.pid):existing||removeInvalidRecord(paths.lease);let owner={pid:process.pid,protocolVersion:5,processIdentity:processIdentity(process.pid)};if(!claimRecord(paths.lease,owner))throw Object.assign(new Error("Plugin execution service already has an owner"),{code:"PLUGIN_TASK_HOST_OWNED"});let host;try{host=new PluginHost(configuration)}catch(error2){throw removeRecordIfPid(paths.lease,process.pid),error2}let{tasks:manager,pages,state,models}=host;if(!writeRecordIfPid(paths.lease,process.pid,{...owner,...manager.host,socketPath:paths.socket,startedAt:new Date().toISOString()}))throw new Error("Plugin host lease ownership was lost");let sessions=new Set,closing,server=createServer(socket=>{sessions.add(socket);let disconnected=new AbortController,scope,sequence=0,requests=0,pending=new Map,bridge={id:randomUUID13(),get scope(){if(!scope)throw new Error("Plugin task connection is not initialized");return scope},invoke(action,payload,options){if(socket.destroyed)return Promise.reject(Object.assign(new Error("The browser invocation bridge is unavailable"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE"}));let id=++sequence;return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{pending.delete(id),reject(Object.assign(new Error("The browser invocation bridge timed out; external operation status is unknown"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE",details:{action}}))},Math.min(Math.max(options.timeoutSec??180,1),3600)*1e3);pending.set(id,{resolve:resolve7,reject,timer}),writePluginTaskMessage(socket,{type:"invoke",id,action,payload,options}).catch(error2=>{pending.delete(id),clearTimeout(timer),reject(error2)})})}},handle=async(method,input)=>{if(method==="hello"){if(scope||input.protocolVersion!==5)throw new Error("Plugin task protocol version mismatch");if(!["public","toolbox","runtime"].includes(String(input.access))||!["service","caller"].includes(String(input.bridge))||!["cli","sdk","mcp","toolbox","runtime"].includes(String(input.source))||input.plugin!==void 0&&(typeof input.plugin!="string"||!/^[a-z][a-z0-9-]*$/.test(input.plugin))||input.scopeId!==void 0&&(typeof input.scopeId!="string"||input.scopeId.length>256)||input.access!=="public"&&(!input.plugin||input.bridge!=="caller"))throw new Error("Invalid plugin task caller scope");return scope={access:input.access,bridge:input.bridge,source:input.source,...input.plugin?{plugin:String(input.plugin)}:{},...input.scopeId?{scopeId:String(input.scopeId)}:{}},{protocolVersion:5,host:manager.host,pid:process.pid}}if(!scope)throw new Error("Plugin task connection requires a handshake");if(method==="status")return{protocolVersion:5,host:manager.host,pid:process.pid};if(method==="diagnose")return host.diagnose(input,scope);if(method==="state.call")return state.call(String(input.plugin),input.input,bridge,input.options);if(method==="model.list")return models.list(input.provider);if(method==="model.capabilities")return(await Promise.resolve().then(()=>(init_pluginModelDefinition(),pluginModelDefinition_exports))).pluginModelCapabilities();if(method==="page.call"){let execution=input.execution;return pages.call(String(input.plugin),input.input,bridge,input.options,execution?{cwd:execution.cwd,environment:execution.environment,signal:disconnected.signal}:void 0)}if(method==="page.event"){if(scope.access!=="runtime")throw new Error("Page events require the browser runtime bridge");return pages.receive(String(input.plugin),input.input,bridge,input.options)}if(method==="start")return manager.start(input,bridge);if(method==="resume")return manager.resume(input,bridge);if(method==="list")return manager.list(scope,input.activeOnly===!0,input.cursor,input.limit);if(method==="shutdown"){if(scope.access!=="public")throw new Error("Tool pages cannot stop the plugin host");return{stopped:!0}}if(typeof input.taskId!="string")throw new Error("Plugin task ID is required");switch(method){case"get":return manager.get(input.taskId,scope);case"checkpoint":return manager.checkpoint(input.taskId,scope);case"cancel":return manager.cancel(input.taskId,scope);case"events":return manager.events(input.taskId,scope,input.cursor,input.waitMs,disconnected.signal);case"result":return manager.resultChunk(input.taskId,scope,input.index);default:throw new Error(`Unknown plugin task method: ${method}`)}};readPluginTaskMessages(socket,message=>{if(message.type==="invoke-result"){let request=pending.get(message.id);if(!request)return;clearTimeout(request.timer),pending.delete(message.id),message.error?request.reject(pluginExecutionError(message.error)):request.resolve(message.result)}else if(message.type==="request"){if(++requests>64||!message.input||typeof message.input!="object"||Array.isArray(message.input)){socket.destroy(new Error("Invalid or excessive plugin task requests"));return}Promise.resolve().then(()=>handle(message.method,message.input)).then(async result=>{await writePluginTaskMessage(socket,{type:"response",id:message.id,result}),message.method==="shutdown"&&setImmediate(()=>{close().catch(()=>{})})},error2=>writePluginTaskMessage(socket,{type:"response",id:message.id,error:serializePluginExecutionError(error2)})).catch(()=>socket.destroy()).finally(()=>{requests--})}else socket.destroy(new Error("Invalid plugin task message direction"))}),socket.on("error",()=>{}),socket.once("close",()=>{disconnected.abort(),sessions.delete(socket);for(let request of pending.values())clearTimeout(request.timer),request.reject(Object.assign(new Error("The invocation bridge disconnected; external operation status may need reconciliation"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE"}));pending.clear()})});async function close(){return closing??=(async()=>{let servicesClosed=host.close();for(let socket of sessions)socket.destroy();await servicesClosed,await new Promise(resolve7=>server.close(()=>resolve7())),removeRecordIfPid(paths.lease,process.pid)&&process.platform!=="win32"&&rmSync14(paths.socket,{force:!0})})(),closing}try{process.platform!=="win32"&&rmSync14(paths.socket,{force:!0}),await new Promise((resolve7,reject)=>{server.once("error",reject),server.listen(paths.socket,()=>{server.off("error",reject),resolve7()})}),process.platform!=="win32"&&chmodSync2(paths.socket,384)}catch(error2){throw removeRecordIfPid(paths.lease,process.pid),await host.close(),error2}return{close,host,socketPath:paths.socket}}try{let server=await startPluginHostServer(),close=()=>{server.close().then(()=>process.exit(0))};process.once("SIGTERM",close),process.once("SIGINT",close)}catch(error2){error2.code!=="PLUGIN_TASK_HOST_OWNED"&&process.stderr.write(`${error2 instanceof Error?error2.stack:String(error2)}
977
+ `;if(Buffer.byteLength(text3)>MAX_MESSAGE_BYTES)throw new Error("Plugin host message is too large");if(socket.destroyed)throw new Error("Plugin host connection is closed");socket.write(text3,error2=>error2?reject(error2):resolve7())}catch(error2){reject(error2)}})}var MAX_MESSAGE_BYTES,init_pluginTaskWire=__esm({"../client/src/plugins/pluginTaskWire.ts"(){"use strict";MAX_MESSAGE_BYTES=96*1024*1024}});var pluginHostConnection_exports={};__export(pluginHostConnection_exports,{PluginHostConnection:()=>PluginHostConnection});import{spawn as spawn7}from"node:child_process";import{closeSync as closeSync9,mkdirSync as mkdirSync9,openSync as openSync9}from"node:fs";import{createConnection}from"node:net";async function ensureHost(runtimePath){let paths=pluginHostPaths(),work=starting.get(paths.registry);work||(work=(async()=>{let lease=readRecord(paths.lease);if(lease&&isProcessOwnerAlive(lease)){if(lease.protocolVersion!==5)throw new Error("Plugin execution service protocol differs; stop the service before updating");return}let lock=`${paths.lease}.start`,existing=readRecord(lock);if(!(existing&&isProcessOwnerAlive(existing))&&(existing?removeRecordIfPid(lock,existing.pid):removeInvalidRecord(lock),!!claimRecord(lock,{pid:process.pid,processIdentity:processIdentity(process.pid)})))try{let owner=readRecord(paths.lease);if(owner&&isProcessOwnerAlive(owner))return;mkdirSync9(paths.home,{recursive:!0,mode:448}),rotateLogIfNeeded(paths.log);let log=openSync9(paths.log,"a",384);try{let child=spawn7(process.execPath,[runtimePath],{detached:!0,stdio:["ignore",log,log],windowsHide:!0});await new Promise((resolve7,reject)=>{child.once("spawn",resolve7),child.once("error",reject)}),child.unref()}finally{closeSync9(log)}let deadline=Date.now()+1e4;for(;Date.now()<deadline;){if(await new Promise(resolve7=>{let probe=createConnection(paths.socket),finish=value=>{probe.destroy(),resolve7(value)};probe.once("connect",()=>finish(!0)),probe.once("error",()=>finish(!1)),probe.setTimeout(200,()=>finish(!1))}))return;await new Promise(resolve7=>setTimeout(resolve7,50))}throw new Error("Plugin execution service startup timed out")}finally{removeRecordIfPid(lock,process.pid)}})().finally(()=>starting.delete(paths.registry)),starting.set(paths.registry,work)),await work}var starting,PluginHostConnection,init_pluginHostConnection=__esm({"../client/src/plugins/clients/pluginHostConnection.ts"(){"use strict";init_runtimePaths();init_dist();init_pluginHostPaths();init_dist2();init_pluginTaskWire();init_pluginExecutorProtocol();starting=new Map;PluginHostConnection=class{constructor(configuration={}){this.configuration=configuration}configuration;get hasInvocationBridge(){return!!this.configuration.invoke}connection;socket;opening=new Set;generation=0;async connect(generation){let check=()=>{if(generation!==this.generation)throw Object.assign(new Error("Plugin task client was disconnected"),{code:"PLUGIN_TASK_CLIENT_DISCONNECTED"})},connectOnce=()=>(check(),this.open(this.configuration.socketPath??pluginHostPaths().socket,generation));try{return await connectOnce()}catch(error2){if(check(),this.configuration.autoStart===!1||this.configuration.socketPath)throw error2;let code=error2.code;if(!["ENOENT","ECONNREFUSED","PLUGIN_TASK_CONNECTION_LOST"].includes(code??""))throw error2}await ensureHost(this.configuration.runtimePath??PLUGIN_TASK_HOST_PATH);let deadline=Date.now()+1e4,failure2;do{check();try{return await connectOnce()}catch(error2){failure2=error2,await new Promise(resolve7=>setTimeout(resolve7,100))}}while(Date.now()<deadline);throw new Error("Plugin execution service did not become ready; inspect its service.log",{cause:failure2})}async open(socketPath,generation){let socket=createConnection(socketPath);this.opening.add(socket);let pending=new Map,sequence=0,fail3=error2=>{for(let request2 of pending.values())clearTimeout(request2.timer),request2.reject(error2);pending.clear()};socket.on("error",fail3),socket.once("close",()=>{fail3(Object.assign(new Error("Plugin execution service connection was lost"),{code:"PLUGIN_TASK_CONNECTION_LOST"})),this.socket===socket&&(this.connection=void 0,this.socket=void 0)});let request=(method,input={},timeoutMs=15e3)=>new Promise((resolve7,reject)=>{let id=++sequence,timer=setTimeout(()=>{pending.delete(id),reject(Object.assign(new Error("Plugin task request timed out; the task may still be running"),{code:"PLUGIN_TASK_REQUEST_TIMEOUT"}))},timeoutMs);pending.set(id,{resolve:resolve7,reject,timer}),writePluginTaskMessage(socket,{type:"request",id,method,input}).catch(error2=>{clearTimeout(timer),pending.delete(id),reject(error2)})});readPluginTaskMessages(socket,message=>{if(message.type==="response"){let call=pending.get(message.id);if(!call)return;clearTimeout(call.timer),pending.delete(message.id),message.error?call.reject(pluginExecutionError(message.error)):call.resolve(message.result)}else message.type==="invoke"?Promise.resolve().then(()=>{if(!this.configuration.invoke)throw new Error("Plugin task client has no invocation bridge");return this.configuration.invoke(message.action,message.payload,message.options)}).then(result=>writePluginTaskMessage(socket,{type:"invoke-result",id:message.id,result}),error2=>writePluginTaskMessage(socket,{type:"invoke-result",id:message.id,error:serializePluginExecutionError(error2)})).catch(()=>{}):socket.destroy(new Error("Invalid plugin task response direction"))});try{await new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{socket.destroy(),reject(new Error("Plugin task connection timed out"))},2e3);socket.once("connect",()=>{clearTimeout(timer),resolve7()}),socket.once("error",error2=>{clearTimeout(timer),reject(error2)})});let scope={access:this.configuration.access??"public",source:this.configuration.source??"sdk",bridge:this.configuration.invoke?"caller":"service",...this.configuration.plugin?{plugin:this.configuration.plugin}:{},...this.configuration.scopeId?{scopeId:this.configuration.scopeId}:{}},status=await request("hello",{...scope,protocolVersion:5});if(status.protocolVersion!==5)throw new Error("Plugin task protocol version mismatch");if(generation!==this.generation||socket.destroyed)throw new Error("Plugin task client was disconnected");return this.socket=socket,{socket,request,status}}catch(error2){throw socket.destroy(),error2}finally{this.opening.delete(socket)}}async request(method,input={},timeoutMs){if(!this.connection){let attempt=this.connect(this.generation);this.connection=attempt,attempt.catch(()=>{this.connection===attempt&&(this.connection=void 0)})}return(await this.connection).request(method,input,timeoutMs)}disconnect(){this.generation++,this.socket?.destroy();for(let socket of this.opening)socket.destroy();this.socket=void 0,this.connection=void 0}}}});import{createHash as createHash9}from"node:crypto";function localWait(promise,signal,timeoutMs=1/0){return new Promise((resolve7,reject)=>{let abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin task wait aborted"))},timer=Number.isFinite(timeoutMs)?setTimeout(()=>{cleanup(),reject(Object.assign(new Error("Waiting for the plugin task timed out; execution continues"),{code:"PLUGIN_TASK_WAIT_TIMEOUT"}))},Math.max(0,timeoutMs)):void 0,cleanup=()=>{clearTimeout(timer),signal?.removeEventListener("abort",abort)};signal?.addEventListener("abort",abort,{once:!0}),promise.then(value=>{cleanup(),resolve7(value)},error2=>{cleanup(),reject(error2)}),signal?.aborted&&abort()})}var PluginTaskClient,init_pluginTasks2=__esm({"../client/src/plugins/clients/pluginTasks.ts"(){"use strict";init_pluginHostConnection();init_dist();init_pluginHostPaths();init_unified();init_dist2();init_pluginExecutorProtocol();PluginTaskClient=class{constructor(configuration={}){this.configuration=configuration;this.connection=configuration.connection??new PluginHostConnection(configuration)}configuration;connection;request(method,input={},timeoutMs){return this.connection.request(method,input,timeoutMs)}status(){return this.request("status")}diagnose(options={}){return this.request("diagnose",{...options})}checkpoint(taskId){return this.request("checkpoint",{taskId})}resume(taskId,options={}){return this.request("resume",{taskId,revision:options.revision,environment:Object.fromEntries(Object.entries(options.environment??process.env).filter(entry=>entry[1]!==void 0))},45e3)}async start(plugin,invocation,options={}){let{cwd=process.cwd(),environment=process.env,executionTimeoutMs,idempotencyKey,...routing}=options;if(!this.connection.hasInvocationBridge&&routing.browser&&!decodeBrowserTarget(routing.browser)){let client=new UnifiedClient;try{let selection=await client.invoke("browser_select_browser",{browser:routing.browser},routing);if(!selection?.selected?.browserId)throw new Error("Cannot resolve plugin task browser target");routing.browser=selection.selected.browserId}finally{client.disconnect()}}return this.request("start",{plugin,command:invocation.command,input:invocation.input,cwd,environment:Object.fromEntries(Object.entries(environment).filter(entry=>entry[1]!==void 0)),options:routing,executionTimeoutMs,idempotencyKey})}get(taskId){return this.request("get",{taskId})}list(activeOnly=!1,page={}){return this.request("list",{activeOnly,...page})}cancel(taskId){return this.request("cancel",{taskId})}events(taskId,cursor=0,waitMs=0){return this.request("events",{taskId,cursor,waitMs},waitMs+15e3)}resultChunk(taskId,index){return this.request("result",{taskId,index})}async result(taskId){let task=await this.get(taskId);if(task.state!=="success"||!task.result)throw new Error("Plugin task has no successful result");let parts=[];for(let index=0;index<task.result.chunks;index++){let chunk=await this.resultChunk(taskId,index);if(chunk.taskId!==taskId||chunk.index!==index||chunk.sha256!==task.result.sha256||chunk.bytes!==task.result.bytes||chunk.chunks!==task.result.chunks)throw new Error("Plugin task result chunk identity mismatch");parts.push(Buffer.from(chunk.data,"base64"))}let bytes=Buffer.concat(parts);if(bytes.length!==task.result.bytes||createHash9("sha256").update(bytes).digest("hex")!==task.result.sha256)throw new Error("Plugin task result integrity check failed");return JSON.parse(bytes.toString("utf8")).value}async*subscribe(taskId,options={}){let cursor=options.cursor??0;for(;;){options.signal?.throwIfAborted();let page=await localWait(this.events(taskId,cursor,25e3),options.signal);if(options.signal?.throwIfAborted(),yield page,cursor=page.nextCursor,!isPluginTaskActive(page.task.state)&&cursor>=page.task.sequence)return}}async wait(taskId,options={}){if(options.timeoutMs!==void 0&&(!Number.isSafeInteger(options.timeoutMs)||options.timeoutMs<1))throw new Error("Invalid plugin task wait timeout");let deadline=options.timeoutMs===void 0?1/0:Date.now()+options.timeoutMs,cursor=0,lastSequence=-1;for(;;){if(options.signal?.throwIfAborted(),Date.now()>=deadline)throw Object.assign(new Error("Waiting for the plugin task timed out; execution continues"),{code:"PLUGIN_TASK_WAIT_TIMEOUT"});let page=await localWait(this.events(taskId,cursor,Math.min(1e3,Math.max(0,deadline-Date.now()))),options.signal,deadline-Date.now());if(options.signal?.throwIfAborted(),cursor=page.nextCursor,page.task.progress&&page.task.sequence!==lastSequence&&options.onProgress?.(page.task.progress,page.task),lastSequence=page.task.sequence,page.task.state==="success")return options.readResult===!1?page.task:localWait(this.result(taskId),options.signal,deadline-Date.now());if(!isPluginTaskActive(page.task.state))throw pluginExecutionError(page.task.error??{message:`Plugin task ended with ${page.task.state}`})}}async stopHost(){let original=await this.status();await this.request("shutdown"),this.disconnect();let deadline=Date.now()+15e3;for(;;){let lease=readRecord(pluginHostPaths().lease);if(!lease||lease.epoch!==original.host.epoch||!isProcessOwnerAlive(lease))return;if(Date.now()>=deadline)throw new Error("Plugin execution service did not finish stopping");await new Promise(resolve7=>setTimeout(resolve7,50))}}disconnect(){this.configuration.connection||this.connection.disconnect()}}}});import{rmSync as rmSync12}from"node:fs";import{randomUUID as randomUUID11}from"node:crypto";async function cleanupPluginRuntime(){let paths=pluginHostPaths();if(listPluginNames().length)throw new Error("Registered plugins still use the execution service");let lock=`${paths.lease}.start`,starter=readRecord(lock);if(starter&&!isProcessOwnerAlive(starter)?removeRecordIfPid(lock,starter.pid):starter||removeInvalidRecord(lock),!claimRecord(lock,{pid:process.pid,processIdentity:processIdentity(process.pid)}))throw new Error("Plugin execution service is starting; caches were retained");try{let lease=readRecord(paths.lease);if(lease&&isProcessOwnerAlive(lease)){let client=new PluginTaskClient({autoStart:!1});try{await client.stopHost()}finally{client.disconnect()}}let current=readRecord(paths.lease);if(current&&isProcessOwnerAlive(current)||listPluginNames().length)throw new Error("Plugin execution service restarted during cleanup; caches were retained");let store=new PluginTaskStore;if(store.list().some(pluginTaskExecutionUnconfirmed))throw new Error("Plugin execution is not confirmed stopped; task records were retained");if(store.recover(randomUUID11()),store.list().some(pluginTaskExecutionUnconfirmed))throw new Error("Plugin execution is not confirmed stopped; task records were retained");let replacement=readRecord(paths.lease);if(replacement&&isProcessOwnerAlive(replacement)||listPluginNames().length)throw new Error("Plugin execution service restarted during cleanup; caches were retained");for(let file of[paths.tasks,paths.revisions,paths.log,`${paths.log}.1`])rmSync12(file,{recursive:!0,force:!0});current&&removeRecordIfPid(paths.lease,current.pid),process.platform!=="win32"&&rmSync12(paths.socket,{force:!0})}finally{removeRecordIfPid(lock,process.pid)}}var init_pluginRuntimeCleanup=__esm({"../client/src/plugins/runtime/pluginRuntimeCleanup.ts"(){"use strict";init_dist();init_pluginHostPaths();init_pluginRegistry();init_pluginTasks2();init_pluginTaskStore()}});var pluginPages_exports={};__export(pluginPages_exports,{PluginPageClient:()=>PluginPageClient});var PluginPageClient,init_pluginPages2=__esm({"../client/src/plugins/clients/pluginPages.ts"(){"use strict";init_unified();PluginPageClient=class{constructor(configuration={},connection){this.connection=connection;connection||(this.client=new UnifiedClient(configuration))}connection;client;call(plugin,operation,input={},options={}){return this.connection?this.connection.request("page.call",{plugin,input:{...input,operation},options,execution:{cwd:process.cwd(),environment:Object.fromEntries(Object.entries(process.env).filter(entry=>entry[1]!==void 0))}},Math.max(12e4,typeof input.timeoutSec=="number"&&Number.isFinite(input.timeoutSec)?(Math.min(300,input.timeoutSec)+5)*1e3:0)):this.client.invoke("plugin_page",{...input,plugin,operation},options)}attach(plugin,input,options={}){return this.call(plugin,"attach",input,options)}get(plugin,instanceId){return this.call(plugin,"get",{instanceId})}list(plugin){return this.call(plugin,"list")}send(plugin,instanceId,message,options={}){return this.call(plugin,"send",{instanceId,message,...options},options)}detach(plugin,instanceId){return this.call(plugin,"detach",{instanceId})}events(plugin,instanceId,cursor=0,waitMs=0){return this.call(plugin,"events",{instanceId,cursor,waitMs})}disconnect(){this.client?.disconnect()}}}});var pluginState_exports={};__export(pluginState_exports,{PluginStateClient:()=>PluginStateClient});var PluginStateClient,init_pluginState2=__esm({"../client/src/plugins/clients/pluginState.ts"(){"use strict";init_pluginHostConnection();PluginStateClient=class{constructor(options={}){this.options=options;this.connection=options.connection??new PluginHostConnection(options)}options;connection;call(plugin,collection,operation,input={},options={}){return this.connection.request("state.call",{plugin,input:{...input,collection,operation},options},3e4)}get(plugin,collection,key2,input={}){return this.call(plugin,collection,"get",{...input,key:key2})}getMany(plugin,collection,keys,input={}){return this.call(plugin,collection,"get-many",{...input,keys})}list(plugin,collection,input={}){return this.call(plugin,collection,"list",input)}transact(plugin,collection,transaction,input={}){return this.call(plugin,collection,"transact",{...input,transaction})}disconnect(){this.options.connection||this.connection.disconnect()}}}});var pluginModels_exports={};__export(pluginModels_exports,{PluginModelClient:()=>PluginModelClient});var PluginModelClient,init_pluginModels2=__esm({"../client/src/plugins/clients/pluginModels.ts"(){"use strict";init_pluginTasks2();PluginModelClient=class{tasks;constructor(options={}){this.tasks=new PluginTaskClient(options)}capabilities(){return this.tasks.connection.request("model.capabilities")}list(provider="codex"){return this.tasks.connection.request("model.list",{provider},2e4)}async start(plugin,request,options={}){let{cwd=process.cwd(),environment=process.env,executionTimeoutMs,idempotencyKey,...routing}=options;return this.tasks.connection.request("start",{kind:"model",plugin,command:"model",input:{request},cwd,environment:Object.fromEntries(Object.entries(environment).filter(entry=>entry[1]!==void 0)),options:routing,executionTimeoutMs,idempotencyKey})}async run(plugin,request,options={}){let{signal,onProgress,...execution}=options;signal?.throwIfAborted();let started=await this.start(plugin,request,execution),cancel=()=>{this.tasks.cancel(started.taskId).catch(()=>{})};signal?.addEventListener("abort",cancel,{once:!0});try{return signal?.aborted&&cancel(),await this.tasks.wait(started.taskId,{onProgress})}finally{signal?.removeEventListener("abort",cancel)}}disconnect(){this.tasks.disconnect()}}}});var plugin_exports={};__export(plugin_exports,{OFFICIAL_PLUGINS:()=>OFFICIAL_PLUGINS,OFFICIAL_PLUGIN_MANAGER:()=>OFFICIAL_PLUGIN_MANAGER,PluginError:()=>PluginError,PluginModelClient:()=>PluginModelClient,PluginPageClient:()=>PluginPageClient,PluginStateClient:()=>PluginStateClient,PluginTaskClient:()=>PluginTaskClient,assertPluginName:()=>assertPluginName,cleanupPluginRuntime:()=>cleanupPluginRuntime,executeRegisteredPlugin:()=>executeRegisteredPlugin,findOfficialPlugin:()=>findOfficialPlugin,findPluginDirectoryEntry:()=>findPluginDirectoryEntry,findPluginEntry:()=>findPluginEntry,findPluginRegistration:()=>findPluginRegistration,invokePageEvalWithArgs:()=>invokePageEvalWithArgs,invokeRegisteredPlugin:()=>invokeRegisteredPlugin,invokeRegisteredRecoveryPlugin:()=>invokeRegisteredRecoveryPlugin,invokeRegisteredRuntimePlugin:()=>invokeRegisteredRuntimePlugin,invokeRegisteredToolboxPlugin:()=>invokeRegisteredToolboxPlugin,listOfficialPluginNames:()=>listOfficialPluginNames,listPluginNames:()=>listPluginNames,loadPlugin:()=>loadPlugin,loadRegisteredPlugin:()=>loadRegisteredPlugin,pluginDirectory:()=>pluginDirectory,pluginRegistrationNeedsRefresh:()=>pluginRegistrationNeedsRefresh,readOfficialPluginCatalog:()=>readOfficialPluginCatalog,readPluginPageBundleChunk:()=>readPluginPageBundleChunk,refreshRegisteredPlugin:()=>refreshRegisteredPlugin,registerPlugin:()=>registerPlugin,replaceOfficialPluginCatalog:()=>replaceOfficialPluginCatalog,resolvePluginEntry:()=>resolvePluginEntry,unregisterPlugin:()=>unregisterPlugin,validateOfficialPluginCatalog:()=>validateOfficialPluginCatalog});import{dirname as dirname8,extname as extname2,resolve as resolve6}from"node:path";import{pathToFileURL}from"node:url";function readPluginVersion(entry){try{return readInstalledSkillMetadata(resolve6(dirname8(entry),".."))?.version}catch{return}}function isObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPluginInvocation(value){return isObject2(value)&&typeof value.command=="string"&&isObject2(value.input)}function normalizePluginProgress(progress){if(typeof progress=="string"){if(!progress)throw new Error("app.progress 需要非空消息");return progress}if(!isObject2(progress)||typeof progress.message!="string"||!progress.message)throw new Error("app.progress 需要非空消息");if(progress.data!==void 0&&!isObject2(progress.data))throw new Error("app.progress data 必须是对象");let data;if(progress.data)try{let serialized=JSON.stringify(progress.data),parsed=serialized===void 0?void 0:JSON.parse(serialized);if(!isObject2(parsed))throw new Error("invalid object");data=Object.freeze(parsed)}catch{throw new Error("app.progress data 必须是可 JSON 序列化的对象")}return Object.freeze({message:progress.message,...data?{data}:{}})}function missingPluginEntryMessage(entry,pluginName){let name=pluginName??"<name>";return["插件入口已失效","",`插件:${name}`,`入口:${entry}`,"",`卸载命令:npx @mearl/setup plugin uninstall ${name}`].join(`
978
+ `)}async function refreshRegisteredPlugin(name,includePage=!1){let key2=`${pluginDirectory()}/${name}`,pending=registrationRefreshes.get(key2);if(pending)return await pending,refreshRegisteredPlugin(name,includePage);let registration=findPluginRegistration(name);if(!registration)return;let entryChanged=pluginRegistrationNeedsRefresh(registration);if(!entryChanged&&(!includePage||!pluginRegistrationNeedsRefresh(registration,!0)))return registration;let refresh=(async()=>{let entryVersion=pluginFileVersion(registration.entry),loaded=entryChanged?await loadPlugin(registration.entry,{options:{},invoke:async()=>{throw new Error("注册时不能执行浏览器操作")},progress:()=>{throw new Error("注册时不能报告执行进度")}},name):registration,current=findPluginRegistration(name);if(JSON.stringify(current)!==JSON.stringify(registration))return current;if(pluginFileVersion(registration.entry)!==entryVersion)throw new PluginError("PLUGIN_SOURCE_CHANGED",`插件更新进行中,请重新打开工具: ${name}`);return registerPlugin(name,registration.entry,loaded.description,{hasPublicCommands:"commandHelp"in loaded?!!loaded.commandHelp(name):loaded.hasPublicCommands,toolbox:loaded.toolbox,appProfiles:loaded.appProfiles,profileSources:"profileSources"in loaded?loaded.profileSources:loaded.source?.profiles,...registration.managedBy?{managedBy:registration.managedBy}:{}}),findPluginRegistration(name)})();registrationRefreshes.set(key2,refresh);try{return await refresh}finally{registrationRefreshes.delete(key2)}}async function loadPlugin(entry,context,pluginName){let entryVersion;try{entryVersion=pluginFileVersion(entry)}catch{throw new PluginError("PLUGIN_ENTRY_MISSING",missingPluginEntryMessage(entry,pluginName))}let commands=new Map,recoveries=new Map,migrations=new Map,executing=!1,checkpointDeclaration,invocationGeneration=0,registering=!0,name,description,defaultCommand,toolbox,pageRuntime,stateStorage,taskRecovery,appProfiles,profileSources,setup,registerCommand=(signature,handler,description2="",examples=[],toolboxOnly=!1,runtimeOnly=!1)=>{if(!registering)throw new Error("命令只能在入口注册阶段声明");let[name2,...args]=signature.trim().split(/\s+/);if(!/^[a-z][a-z0-9-]*$/.test(name2)||commands.has(name2)||typeof handler!="function"||!Array.isArray(examples)||examples.some(example=>typeof example!="string"||!example.trim()))throw new Error(`无效或重复的命令: ${signature}`);let command=new Command(name2).description(description2);for(let argument of args){if(!/^(?:<[a-zA-Z][\w-]*(?:\.\.\.)?>|\[[a-zA-Z][\w-]*(?:\.\.\.)?\])$/.test(argument))throw new Error(`无效的位置参数: ${argument}`);command.argument(argument)}let names=command.registeredArguments.map(argument=>argument.name());if(new Set(names).size!==names.length)throw new Error(`参数名称重复: ${signature}`);commands.set(name2,{command,signature,handler,examples:[...examples],toolboxOnly,runtimeOnly})},app=Object.freeze({options:Object.freeze({...context.options}),command:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples),runtimeCommand:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples,!1,!0),recoveryCommand(command,handler){if(!registering||!/^[a-z][a-z0-9-]*$/.test(command)||typeof handler!="function"||recoveries.has(command))throw new Error("Invalid or duplicate recovery command");recoveries.set(command,handler)},checkpointMigration(command,handler){if(!registering||!/^[a-z][a-z0-9-]*$/.test(command)||typeof handler!="function"||migrations.has(command))throw new Error("Invalid or duplicate checkpoint migration");migrations.set(command,(input,commandContext)=>handler(input,commandContext))},checkpoint(data,expectedSequence){if(!executing||!context.invocation?.taskId)throw new PluginError("PLUGIN_TASK_REQUIRED","Checkpoints require a managed task");return context.signal?.throwIfAborted(),context.invoke("plugin_task_checkpoint",{plugin:pluginName??name,data,expectedSequence,expectedDeclaration:checkpointDeclaration})},state(collection,operation,input={}){if(!executing)throw new Error("app.state is only available during command execution");if(context.signal?.throwIfAborted(),!stateStorage||!Object.hasOwn(stateStorage.collections,collection))throw new PluginError("PLUGIN_STATE_NOT_DECLARED","Plugin state collection is not declared");return context.invoke("plugin_state",{...input,plugin:pluginName??name,collection,operation,expectedDeclaration:pluginStateSignature(stateStorage.collections[collection])})},model(request,options={}){if(!executing)throw new Error("app.model is only available during command execution");context.signal?.throwIfAborted();let generation=invocationGeneration,observing=()=>executing&&generation===invocationGeneration&&!context.signal?.aborted;if(context.runModel)return context.runModel(pluginName??name,request,{signal:context.signal,onProgress:progress=>{observing()&&(context.progress(progress),options.onProgress?.(progress))}});let payload={plugin:pluginName??name,operation:"run",request};return options.onProgress?context.invoke("plugin_model",payload,{},progress=>{observing()&&options.onProgress?.(progress)}):context.invoke("plugin_model",payload)},page(operation,input={}){if(!executing)throw new Error("app.page is only available during command execution");return context.signal?.throwIfAborted(),context.invoke("plugin_page",{...input,plugin:pluginName??name,operation})},toolboxCommand:(signature,handler,description2="",examples=[])=>registerCommand(signature,handler,description2,examples,!0),invoke(action,payload={},options={}){if(!executing)throw new Error("app.invoke 只能在命令执行期间调用");return context.signal?.throwIfAborted(),context.invoke(action,payload,options)},progress(progress){if(!executing)throw new Error("app.progress 只能在命令执行期间调用");context.progress(normalizePluginProgress(progress))}});try{if(extname2(entry).toLowerCase()===".py"){let descriptor=await describePythonPlugin(entry,app.options);name=descriptor.name,description=descriptor.description,toolbox=normalizePluginToolboxContribution(descriptor.toolbox),pageRuntime=normalizePluginPageRuntime(descriptor.pageRuntime),stateStorage=normalizePluginState(descriptor.stateStorage),taskRecovery=normalizePluginTaskRecovery(descriptor.taskRecovery),{appProfiles,profileSources}=loadPluginAppProfiles(entry,descriptor.appProfiles);for(let command of descriptor.commands){let commandName=command.signature.trim().split(/\s+/)[0];if(command.migrationOnly){app.checkpointMigration(commandName,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,"migration",descriptor));continue}if(command.recoveryOnly){app.recoveryCommand(commandName,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,!0,descriptor));continue}(command.runtimeOnly?app.runtimeCommand:command.toolboxOnly?app.toolboxCommand:app.command)(command.signature,(input,commandContext)=>runPythonPluginCommand(entry,commandName,input,app,commandContext,!1,descriptor,command.runtimeOnly),command.description)}}else{let moduleUrl=pathToFileURL(entry);moduleUrl.searchParams.set("mearl-version",entryVersion);let module=await import(moduleUrl.href);if(module.name!==void 0&&typeof module.name!="string")throw new Error("入口的 name 导出必须为字符串");if(name=module.name,module.description!==void 0&&typeof module.description!="string")throw new Error("入口的 description 导出必须为字符串");if(description=module.description,module.setup!==void 0&&typeof module.setup!="function")throw new Error("入口的 setup 导出必须为函数");if(setup=module.setup,module.defaultCommand!==void 0&&typeof module.defaultCommand!="string")throw new Error("入口的 defaultCommand 导出必须为字符串");if(defaultCommand=module.defaultCommand,toolbox=normalizePluginToolboxContribution(module.toolbox),pageRuntime=normalizePluginPageRuntime(module.pageRuntime),stateStorage=normalizePluginState(module.stateStorage),taskRecovery=normalizePluginTaskRecovery(module.taskRecovery),{appProfiles,profileSources}=loadPluginAppProfiles(entry,module.appProfiles),module.default!==void 0&&typeof module.default!="function")throw new Error("入口必须默认导出 register(app) 函数");if(typeof module.default=="function")await module.default(app);else if(!appProfiles)throw new Error("入口必须默认导出 register(app) 函数")}if(commands.size===0&&!appProfiles)throw new Error("入口未注册任何命令");if(defaultCommand!==void 0&&(!commands.has(defaultCommand)||commands.get(defaultCommand)?.toolboxOnly||commands.get(defaultCommand)?.runtimeOnly))throw new Error("defaultCommand 必须指向公开命令");for(let command of Object.keys(taskRecovery?.commands??{}))if(!commands.has(command)||commands.get(command)?.runtimeOnly||commands.get(command)?.toolboxOnly||!recoveries.has(command))throw new Error(`Recovery requires a command and recoveryCommand: ${command}`);for(let command of recoveries.keys())if(!Object.hasOwn(taskRecovery?.commands??{},command))throw new Error(`Undeclared recovery command: ${command}`);for(let[command,definition]of Object.entries(taskRecovery?.commands??{}))if(!!definition.migrateFrom?.length!==migrations.has(command))throw new Error(`Checkpoint migrations require a declaration and checkpointMigration: ${command}`);for(let command of migrations.keys())if(!Object.hasOwn(taskRecovery?.commands??{},command))throw new Error(`Undeclared checkpoint migration: ${command}`);let runtimeCommands=new Set(Object.values(pageRuntime?.events??{}).map(event=>event.command));pageRuntime?.initialize&&runtimeCommands.add(pageRuntime.initialize);for(let[name2,command]of commands)if(command.runtimeOnly&&!runtimeCommands.has(name2))throw new Error(`runtimeCommand is not declared in pageRuntime.events: ${name2}`);for(let name2 of runtimeCommands)if(!commands.has(name2)||commands.get(name2)?.toolboxOnly)throw new Error(`Invalid page runtime command: ${name2}`);let toolboxCommands=toolbox?.page.commands??[];for(let[name2,command]of commands)if(command.toolboxOnly&&!toolboxCommands.includes(name2))throw new Error(`toolboxCommand 未声明在 toolbox.page.commands 中: ${name2}`);for(let command of toolboxCommands)if(!commands.has(command))throw new Error(`toolbox 命令未注册: ${command}`)}catch(error2){throw new PluginError("PLUGIN_LOAD_FAILED",`${entry}: ${error2 instanceof Error?error2.message:String(error2)}`)}finally{registering=!1}let find=(name2,toolboxPage=!1)=>{let command=commands.get(name2);if(!command)throw new PluginError("PLUGIN_COMMAND_NOT_FOUND",`未知子命令: ${name2}`);if(toolboxPage==="runtime"){if(!(pageRuntime?.initialize===name2||Object.values(pageRuntime?.events??{}).some(event=>event.command===name2))||command.toolboxOnly)throw new PluginError("PLUGIN_COMMAND_NOT_ALLOWED","Page runtime command is not declared")}else{if(command.runtimeOnly)throw new PluginError("PLUGIN_COMMAND_RUNTIME_ONLY",`命令仅供页面运行时调用: ${name2}`);if(toolboxPage){if(!toolbox?.page.commands.includes(name2))throw new PluginError("PLUGIN_COMMAND_NOT_ALLOWED",`工具页面不允许调用命令: ${name2}`)}else if(command.toolboxOnly)throw new PluginError("PLUGIN_COMMAND_TOOLBOX_ONLY",`命令仅供工具页面调用: ${name2}`)}return command},publicCommands=()=>[...commands.values()].filter(command=>!command.toolboxOnly&&!command.runtimeOnly),run=async(positionals,payload,namedInput={},toolboxPage=!1)=>{if(payload!==void 0&&positionals.length>0)throw new PluginError("PLUGIN_INVALID_INPUT","位置参数调用与 --payload 调用不能混用");if(payload!==void 0&&Object.keys(namedInput).length>0)throw new PluginError("PLUGIN_INVALID_INPUT","插件业务选项与 --payload 调用不能混用");let defaultPayload=defaultCommand&&toolboxPage===!1&&isObject2(payload)&&!Object.hasOwn(payload,"command");if(payload!==void 0&&!defaultPayload&&!isPluginInvocation(payload))throw new PluginError("PLUGIN_INVALID_INPUT",'--payload 必须为 {"command":"...","input":{...}}');let envelope=defaultPayload?{command:defaultCommand,input:payload}:payload,positionalOffset=defaultCommand&&!commands.has(positionals[0])&&toolboxPage===!1?0:1,commandName=envelope?.command??(positionalOffset===0?defaultCommand:positionals[0]??""),hidden=toolboxPage==="recovery"||toolboxPage==="migration",selected=find(commandName,hidden?!1:toolboxPage),command=selected.command,handler=toolboxPage==="recovery"?recoveries.get(commandName):toolboxPage==="migration"?migrations.get(commandName):selected.handler;if(!handler||toolboxPage==="recovery"&&!context.invocation?.recovery)throw new PluginError("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery handler requires a managed recovery attempt");if(toolboxPage==="recovery"&&context.invocation?.recovery?.declarationHash!==pluginRecoverySignature(taskRecovery.commands[commandName]))throw new PluginError("PLUGIN_RECOVERY_DECLARATION_CHANGED","Recovery declaration differs from the admitted format");let positionalInput=envelope?{...envelope.input}:Object.fromEntries(command.registeredArguments.map((argument,index)=>[argument.name(),argument.variadic?positionals.slice(index+positionalOffset):positionals[index+positionalOffset]]).filter(([,value])=>value!==void 0));for(let name2 of Object.keys(namedInput))if(Object.hasOwn(positionalInput,name2))throw new PluginError("PLUGIN_INVALID_INPUT",`参数不能重复传入: ${name2}`);let input={...positionalInput,...namedInput};if(!envelope&&!command.registeredArguments.some(argument=>argument.variadic)&&positionals.length-positionalOffset>command.registeredArguments.length)throw new PluginError("PLUGIN_INVALID_INPUT","位置参数过多");for(let argument of hidden?[]:command.registeredArguments){let value=Object.hasOwn(input,argument.name())?input[argument.name()]:void 0;if(argument.required&&(value==null||value===""||Array.isArray(value)&&value.length===0))throw new PluginError("PLUGIN_INVALID_INPUT",`缺少必填参数: ${argument.name()}`);if(argument.variadic&&value!==void 0&&!Array.isArray(value))throw new PluginError("PLUGIN_INVALID_INPUT",`${argument.name()} 必须为数组`)}if(executing)throw new PluginError("PLUGIN_BUSY","同一命令实例不能并发执行");let signal=context.signal??new AbortController().signal;signal.throwIfAborted();let identity=context.invocation??createPluginInvocationIdentity(pluginName??name??"unregistered",context.source??"sdk",context.parentInvocation),generation=++invocationGeneration,assertActive=()=>{if(!executing||generation!==invocationGeneration)throw new PluginError("PLUGIN_INVOCATION_ENDED","命令调用已结束");signal.throwIfAborted()},commandContext=Object.freeze({identity,signal,...identity.recovery?{recovery:structuredClone(identity.recovery)}:{},checkpoint:(data,expectedSequence)=>(assertActive(),app.checkpoint(data,expectedSequence)),...identity.page?{page:Object.freeze({send:(message,options={})=>(assertActive(),app.page("send",{instanceId:identity.page.instanceId,message,...options.timeoutSec!==void 0?{timeoutSec:options.timeoutSec}:{}})),get:()=>(assertActive(),app.page("get",{instanceId:identity.page.instanceId}))})}:{},invoke:(action,payload2,options)=>(assertActive(),app.invoke(action,payload2,options)),state:(collection,operation,input2)=>(assertActive(),app.state(collection,operation,{...identity.page?{instanceId:identity.page.instanceId}:{},...input2})),model:(request,options)=>(assertActive(),app.model(request,options)),progress:progress=>{assertActive(),app.progress(progress)}});checkpointDeclaration=taskRecovery&&Object.hasOwn(taskRecovery.commands,commandName)?pluginRecoverySignature(taskRecovery.commands[commandName]):void 0,executing=!0,context.onInvocation?.(identity);try{return await handler(input,commandContext)}finally{executing=!1,checkpointDeclaration=void 0,context.onInvocation?.(void 0)}};return{name,setup,description,defaultCommand,toolbox,pageRuntime,stateStorage,taskRecovery,appProfiles,profileSources,version:readPluginVersion(entry),commandHelp(namespace){return publicCommands().map(({command,signature})=>` ${namespace} ${command.name()===defaultCommand?signature.slice(defaultCommand.length).trim():signature} ${command.description()}`).join(`
979
+ `)},help(namespace,name2){let selected=name2?[find(defaultCommand&&!commands.has(name2)?defaultCommand:name2)]:publicCommands();if(!selected.length){let location2=toolbox?`请在 Mearl ${toolbox.displayMode==="popup"?"Popup":"工具箱"} 中打开「${toolbox.title}」使用。`:"此插件未提供公开 CLI 命令。";return`${namespace} 未提供 CLI 命令。
980
+ ${location2}`}let examples=selected.flatMap(({examples:examples2})=>examples2);return["用法:",...selected.map(({command,signature})=>` ${namespace} ${command.name()===defaultCommand?signature.slice(defaultCommand.length).trim():signature} ${command.description()}`),...examples.length?["","示例:",...examples.map(example=>` ${namespace} ${example}`)]:[]].join(`
981
+ `)},run(positionals,payload,namedInput={}){return run(positionals,payload,namedInput)},runRuntime(invocation){return run([],invocation,{},"runtime")},runRecovery(invocation){return run([],invocation,{},"recovery")},runMigration(invocation){return run([],invocation,{},"migration")},runToolbox(invocation){return run([],invocation,{},!0)}}}async function loadRegisteredPluginWithState(name,context,options={},state={stack:[]}){if(state.stack.includes(name))throw new PluginError("PLUGIN_INVOCATION_CYCLE",`插件调用形成循环: ${[...state.stack,name].join(" -> ")}`);let registration=context.resolveRegistration?context.resolveRegistration(name):findPluginRegistration(name);if(!registration&&findOfficialPlugin(name)&&(await(context.ensurePlugin??ensureOfficialPluginRegistered)(name,options.onProgress?message=>options.onProgress?.(message):void 0),registration=findPluginRegistration(name)),!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${name}`);let{onProgress,signal,source,...invokeOptions}=options,childState={stack:[...state.stack,name]},activeInvocation;return loadPlugin(registration.entry,{options:invokeOptions,source:source??context.source,parentInvocation:context.parentInvocation,invocation:context.invocation,signal,runModel:context.runModel,onInvocation:identity=>{activeInvocation=identity},progress:onProgress??(()=>{}),async invoke(action,payload,overrides,progress){let nestedOptions={...invokeOptions,...overrides};if(COMMAND_MAP.has(action)||action==="connector_list"){let result2=await context.invoke(action,payload,nestedOptions);if(result2?.action?.success===!1)throw new Error(result2.action.error||`${action} failed`);return result2}let pluginInvocation=isPluginInvocation(payload);if(findPluginRegistration(action)||findOfficialPlugin(action)||pluginInvocation){if(!pluginInvocation)throw new PluginError("PLUGIN_INVALID_INPUT",`调用插件 ${action} 需要 {"command":"...","input":{...}}`);return activeInvocation?.taskId?(!findPluginRegistration(action)&&findOfficialPlugin(action)&&await(context.ensurePlugin??ensureOfficialPluginRegistered)(action),context.invoke("plugin_invoke_child",{plugin:action,invocation:payload},nestedOptions)):invokeRegisteredPluginWithState(action,payload,{...context,invocation:void 0,parentInvocation:activeInvocation},{...nestedOptions,...onProgress?{onProgress}:{},...signal?{signal}:{},...source?{source}:{}},childState)}let result=await(progress?context.invoke(action,payload,nestedOptions,progress):context.invoke(action,payload,nestedOptions));if(result?.action?.success===!1)throw new Error(result.action.error||`${action} failed`);return result}},name)}function loadRegisteredPlugin(name,context,options={}){return loadRegisteredPluginWithState(name,context,options)}async function invokeRegisteredPluginWithState(name,invocation,context,options={},state={stack:[]}){return(await loadRegisteredPluginWithState(name,context,options,state)).run([],invocation)}function invokeRegisteredPlugin(name,invocation,context,options={}){return invokeRegisteredPluginWithState(name,invocation,context,options)}async function invokeRegisteredToolboxPlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runToolbox(invocation)}async function invokeRegisteredRuntimePlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runRuntime(invocation)}async function invokeRegisteredRecoveryPlugin(name,invocation,context,options={}){return(await loadRegisteredPluginWithState(name,context,options)).runRecovery(invocation)}var registrationRefreshes,init_plugin=__esm({"../client/src/plugins/sdk/plugin.ts"(){"use strict";init_pluginStateDefinition();init_pluginRecoveryDefinition();init_pluginPageDefinition();init_pluginAppProfiles();init_pageEvalArguments();init_skillManifest();init_esm();init_commands();init_officialPluginCatalog();init_officialPluginInstaller();init_pluginRegistry();init_pluginSource();init_pythonPlugin();init_pluginExecution2();init_pluginExecutor();init_pluginTasks2();init_pluginRuntimeCleanup();init_pluginPages2();init_pluginRegistry();init_officialPluginCatalog();init_pluginState2();init_pluginModels2();registrationRefreshes=new Map}});import WebSocket from"ws";function encodeBrowserTarget(target){let browser=encodeURIComponent(target.browser).replace(/%3A/g,":");return target.connector?`${GLOBAL_BROWSER_PREFIX}remote:${encodeURIComponent(target.connector)}:${browser}`:`${GLOBAL_BROWSER_PREFIX}local:${browser}`}function omitTransientBrowserSecrets(browser){let safeBrowser={...browser};for(let key2 of Object.keys(safeBrowser))/accessUrl$/i.test(key2)&&delete safeBrowser[key2];return safeBrowser}function decodeBrowserTarget(selector){if(selector?.startsWith(GLOBAL_BROWSER_PREFIX))try{let target=selector.slice(GLOBAL_BROWSER_PREFIX.length);if(target.startsWith("local:")){let browser=decodeURIComponent(target.slice(6));return browser?{browser}:void 0}if(target.startsWith("remote:")){let remoteTarget=target.slice(7),separator=remoteTarget.indexOf(":");if(separator<0)return;let connector=decodeURIComponent(remoteTarget.slice(0,separator)),browser=decodeURIComponent(remoteTarget.slice(separator+1));return connector&&browser?{connector,browser}:void 0}}catch{return}}function normalizeBrowserSelector(selector){let decodedTarget=decodeBrowserTarget(selector);return(decodedTarget?encodeBrowserTarget(decodedTarget):selector.trim()).toLowerCase()}function decorateBrowser(browser,source){let safeBrowser=omitTransientBrowserSecrets(browser),originalBrowserId=String(browser.browserId),originalName=String(browser.name);return{...safeBrowser,browserId:encodeBrowserTarget({browser:originalBrowserId,...source.connectorId?{connector:source.connectorId}:{}}),name:source.kind==="local"?`[this machine] ${originalName}`:`[${source.connectorName}] ${originalName}`,originalBrowserId,originalName,status:typeof browser.status=="string"?browser.status:"disconnected",source}}function browserMatches(browser,selector){let normalized=normalizeBrowserSelector(selector);return browser.browserId.toLowerCase()===normalized||browser.originalBrowserId?.toLowerCase()===normalized||browser.name.toLowerCase()===normalized||browser.originalName?.toLowerCase()===normalized}function findBrowsers(browsers,selector,connectedOnly=!0){let candidates=connectedOnly?browsers.filter(browser=>browser.status==="connected"):browsers,exact=candidates.filter(browser=>browserMatches(browser,selector));if(exact.length>0)return exact;let normalized=normalizeBrowserSelector(selector);return candidates.filter(browser=>browser.browserId.toLowerCase().includes(normalized)||browser.originalBrowserId?.toLowerCase().includes(normalized)||browser.name.toLowerCase().includes(normalized)||browser.originalName?.toLowerCase().includes(normalized))}function errorMessage(error2){return error2 instanceof Error?error2.message:String(error2)}var RESPONSE_GRACE_MS,GLOBAL_BROWSER_PREFIX,UnifiedClient,init_unified=__esm({"../client/src/unified.ts"(){"use strict";init_pageEvalArguments();init_artifacts();init_dist3();init_actionTimeouts();init_dist2();init_socket();init_unifiedConfig();RESPONSE_GRACE_MS=1e3,GLOBAL_BROWSER_PREFIX="mearl:";UnifiedClient=class{controlSessions=new Map;options;defaultBrowser;defaultConnector;ws=null;connectPromise=null;messageBuffer="";pendingRequests=new Map;heartbeatTimer=null;closing=!1;constructor(options={}){this.options={...options.serverUrl?{serverUrl:options.serverUrl}:{},connectTimeoutSec:options.connectTimeoutSec??30,requestTimeoutSec:options.requestTimeoutSec??60,heartbeatInterval:options.heartbeatInterval??30},this.defaultBrowser=options.defaultBrowser??(process.env.MEARL_BROWSER?.trim()||void 0),this.defaultConnector=options.defaultConnector}disconnect(){this.closing=!0,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.rejectAllPending(new Error("Connection closed by user")),this.ws?.close(),this.ws=null}async invokePlugin(name,invocation,options={}){let{invokeRegisteredPlugin:invokeRegisteredPlugin2}=await Promise.resolve().then(()=>(init_plugin(),plugin_exports));return invokeRegisteredPlugin2(name,invocation,{invoke:(action,payload,invokeOptions)=>this.invoke(action,payload,invokeOptions),runModel:async(plugin,request,execution)=>{let{PluginModelClient:PluginModelClient2}=await Promise.resolve().then(()=>(init_pluginModels2(),pluginModels_exports)),models=new PluginModelClient2({source:options.source??"sdk"});try{return await models.run(plugin,request,{signal:execution.signal,onProgress:progress=>{progress!==void 0&&execution.onProgress?.(progress)}})}finally{models.disconnect()}}},options)}async invoke(action,data={},options={}){if((action==="browser_list"?parseBrowserListParams(data):void 0)&&(!options.local||options.connector||options.transport||options.session||options.controlSessionId))throw new Error("Provider discovery requires explicit --local without connector, transport, socket or session overrides");if(action==="plugin_state"){let{PluginStateClient:PluginStateClient2}=await Promise.resolve().then(()=>(init_pluginState2(),pluginState_exports)),state=new PluginStateClient2;try{return await state.call(String(data.plugin??""),data.collection,data.operation,data,options)}finally{state.disconnect()}}if(action==="plugin_model"){let{PluginModelClient:PluginModelClient2}=await Promise.resolve().then(()=>(init_pluginModels2(),pluginModels_exports)),models=new PluginModelClient2;try{if(data.operation==="capabilities")return await models.capabilities();if(data.operation==="list")return await models.list(data.provider);if(data.operation==="start")return await models.start(String(data.plugin??""),data.request,data.taskOptions??{});if(data.operation==="run")return await models.run(String(data.plugin??""),data.request,data.taskOptions??{});throw new Error("Invalid model operation")}finally{models.disconnect()}}if(action==="plugin_page"){let{PluginHostConnection:PluginHostConnection2}=await Promise.resolve().then(()=>(init_pluginHostConnection(),pluginHostConnection_exports)),{PluginPageClient:PluginPageClient2}=await Promise.resolve().then(()=>(init_pluginPages2(),pluginPages_exports)),connection=new PluginHostConnection2,pages=new PluginPageClient2({},connection);try{let pinned=["attach","activation"].includes(data.operation)?await this.pinBrowserTarget(options):options;return await pages.call(String(data.plugin??""),data.operation,data,pinned)}finally{pages.disconnect(),connection.disconnect()}}if(options.session&&options.session!=="new"){let session=await this.resolveControlSession(options.session,options),selected=decodeBrowserTarget(options.browser),pinned=decodeBrowserTarget(session.browser);if(options.browser&&(!selected||selected.browser!==pinned?.browser||selected.connector!==pinned?.connector))throw new Error("The selected browser does not match the control session");if(options.transport&&session.transport!==options.transport)throw new Error("A control session cannot change transport");options={...options,browser:session.browser,controlSessionId:session.id,...session.transport==="cdp"&&!pinned?.connector?{transport:"cdp"}:{}}}else if(options.session==="new"){if(!["tab_open","page_snapshot","page_screenshot"].includes(action))throw new Error("--session new requires tab_open, page_snapshot or page_screenshot");options={...options,controlSessionId:"new"}}if(action==="page_eval"&&data.args!==void 0){let pinnedOptions={...options,...options.browser||!this.defaultBrowser?{}:{browser:this.defaultBrowser},...options.connector||!this.defaultConnector||decodeBrowserTarget(options.browser??this.defaultBrowser)?{}:{connector:this.defaultConnector}},targetPinned=!1;return invokePageEvalWithArgs(async(request,transfer)=>(transfer&&!targetPinned&&(pinnedOptions=await this.pinPageEvalTarget(pinnedOptions,request),targetPinned=!0),this.invokeRouted(action,request,pinnedOptions)),data)}if(action==="page_upload"&&data.files!==void 0&&(!Array.isArray(data.files)||!data.files.length||data.files.some(file=>!file||typeof file.filePath=="string"==(typeof file.artifactId=="string"))))throw new Error("files requires exactly one filePath or artifactId per entry");if(action==="page_upload"&&Array.isArray(data.files)&&data.files.some(file=>file.filePath)){if(data.filePaths)throw new Error("Use files or filePaths, not both");let staged=[],temporary=[];try{for(let file of data.files)if(file.filePath){let uploaded=await stageFile(this,file.filePath,options);options=uploaded.options,temporary.push(uploaded.artifactId),staged.push({artifactId:uploaded.artifactId})}else staged.push(file);return await this.invokeRouted(action,{...data,files:staged},options)}finally{for(let id of temporary)await this.invoke("__artifact_remove",{artifactId:id},options).catch(()=>{})}}return this.invokeRouted(action,data,options)}saveArtifact(artifact,outputPath,options={}){return exportArtifact(this,artifact,outputPath,options)}async pinBrowserTarget(options={}){let selector=options.browser??this.defaultBrowser;if(decodeBrowserTarget(selector))return{...options,browser:selector};let listing=await this.invoke("browser_list",{},{...options,...options.connector||!this.defaultConnector?{}:{connector:this.defaultConnector}}),connected=listing.browsers.filter(browser=>browser.status==="connected"),matches=selector?findBrowsers(connected,selector):connected.filter(browser=>browser.browserId===listing.defaultBrowserId),target=matches.length?matches:selector?[]:connected;if(target.length!==1)throw new Error("Plugin pages require an explicit, connected and unambiguous browser target");let pinned={...options,browser:target[0].browserId};return delete pinned.connector,pinned}async pinPageEvalTarget(options,data){if(decodeBrowserTarget(options.browser)&&!options.connector)return options;let local=options.local||options.transport==="cdp"||!this.options.serverUrl&&!options.connector;if(local){let resolved=resolveLocalActionTarget("page_eval",data,{browser:options.browser,transport:options.transport});if(resolved?.socketPath)return{...options,socketPath:resolved.socketPath};if(resolved?.browser)return{...options,browser:encodeBrowserTarget({browser:resolved.browser})}}if(options.connector&&!options.browser){let timeoutSec=options.timeoutSec??this.options.requestTimeoutSec,connector=await this.resolveConnector(options.connector,timeoutSec),resolved=await this.requestRemote("__resolve_action_target",{action:"page_eval",data},timeoutSec,void 0,connector.connectorId);if(!resolved?.browser)throw new Error("Cannot pin the connector browser for large page_eval arguments. Pass --browser <global-id>.");let pinned2={...options,browser:encodeBrowserTarget({browser:resolved.browser,connector:connector.connectorId})};return delete pinned2.connector,pinned2}let listing=await this.invokeRouted("browser_list",{},options),connected=listing.browsers.filter(browser2=>browser2.status==="connected"&&(!local||browser2.transport!=="provider")),implicitHost=options.local||options.transport==="cdp"||options.connector||!this.options.serverUrl,automatic=connected.find(browser2=>browser2.browserId===listing.defaultBrowserId)??(implicitHost||connected.length===1?connected[0]:void 0),candidates=options.browser?findBrowsers(listing.browsers,options.browser):automatic?[automatic]:[];if(candidates.length!==1)throw new Error("Large page_eval arguments require a unique connected browser. Pass --browser <global-id>.");let browser=candidates[0],pinned={...options,browser:browser.browserId};return delete pinned.connector,browser.transport==="cdp"&&!decodeBrowserTarget(browser.browserId)?.connector&&(pinned.transport="cdp"),pinned}async invokeRouted(action,data={},options={}){validateRequiredActionTabId(action,data);let timeoutSec=options.timeoutSec??resolveActionTimeoutSec(action,data,this.options.requestTimeoutSec);if(options.socketPath)return this.invokeLocal(action,data,timeoutSec,void 0,options.transport,options.controlSessionId,options.socketPath);if(action==="connector_list")return this.listConnectors(timeoutSec);if(action==="browser_list"){if(parseBrowserListParams(data)){let result=await invoke("browser_list",data,{timeoutSec,controlSource:"local"});if(!result?.discovery)throw new Error("Provider launch-form discovery is not supported by this host");return this.applyConfiguredDefault(this.decorateListing(result,{kind:"local"}))}if(options.local||options.transport==="cdp")return this.listLocalBrowsers(timeoutSec,options.transport);let connector2=options.connector??this.defaultConnector;return connector2?this.listConnectorBrowsers(connector2,timeoutSec):this.listAllBrowsers(timeoutSec)}if(action==="browser_select_browser")return this.selectDefaultBrowser(data,options,timeoutSec);if(options.local||options.transport==="cdp")return this.invokeExplicitLocal(action,data,options,timeoutSec);let optionTarget=decodeBrowserTarget(options.browser),defaultTarget=options.browser?void 0:decodeBrowserTarget(this.defaultBrowser),closeTarget=action==="browser_close"&&typeof data.browser=="string"?decodeBrowserTarget(data.browser):void 0,target=optionTarget??closeTarget??defaultTarget,connector=target?.connector??options.connector??this.defaultConnector,browser=optionTarget?.browser??defaultTarget?.browser??(options.browser&&!optionTarget?options.browser:void 0)??(this.defaultBrowser&&!defaultTarget?this.defaultBrowser:void 0),requestData=closeTarget?{...data,browser:closeTarget.browser}:data;if(target&&!target.connector){if(options.connector)throw new Error("A local browser cannot be used together with --connector.");return this.invokeLocal(action,requestData,timeoutSec,target.browser,void 0,options.controlSessionId)}if(connector){let selected=target?.connector&&!options.connector&&!this.defaultConnector?{connectorId:target.connector,name:target.connector}:await this.resolveConnector(connector,timeoutSec);if(target?.connector&&selected.connectorId!==target.connector)throw new Error("The selected browser belongs to a different cloud connector.");return this.invokeRemote(action,requestData,timeoutSec,browser,selected,options.controlSessionId)}if(!this.options.serverUrl)return this.invokeLocal(action,requestData,timeoutSec,options.browser??this.defaultBrowser,void 0,options.controlSessionId);let selector=options.browser??this.defaultBrowser??(action==="browser_close"&&typeof data.browser=="string"?data.browser:void 0),resolved=await this.resolveUnifiedBrowser(selector,timeoutSec,action==="browser_close");if(resolved){if(action==="browser_close"){let nextOptions={...options};return delete nextOptions.browser,this.invoke(action,{...data,browser:resolved},nextOptions)}return this.invoke(action,data,{...options,browser:resolved})}if(action==="browser_launch")return this.invokeLaunchWithoutControlBrowser(data,timeoutSec);throw new Error("No connected browser is available. Run `mearl browser_list` to inspect all sources.")}async invokeExplicitLocal(action,data,options,timeoutSec){let optionTarget=decodeBrowserTarget(options.browser),defaultTarget=options.browser?void 0:decodeBrowserTarget(this.defaultBrowser),closeTarget=action==="browser_close"&&typeof data.browser=="string"?decodeBrowserTarget(data.browser):void 0;if(optionTarget?.connector||defaultTarget?.connector||closeTarget?.connector)throw new Error("A remote browser cannot be used together with --local or --cdp.");let browser=optionTarget?.browser??defaultTarget?.browser??options.browser??this.defaultBrowser,requestData=closeTarget?{...data,browser:closeTarget.browser}:data;return this.invokeLocal(action,requestData,timeoutSec,browser,options.transport,options.controlSessionId)}async invokeLaunchWithoutControlBrowser(data,timeoutSec){let local=await this.tryLocalBrowserList(timeoutSec),discoveredConnectors=await this.listConnectors(timeoutSec).then(result=>result.connectors),localAvailable=local!==null,localConnectorId=localAvailable?loadLocalConnectorId():null,connectors=localConnectorId?discoveredConnectors.filter(connector=>connector.connectorId!==localConnectorId):discoveredConnectors;if(localAvailable&&connectors.length===0)return this.invokeLocal("browser_launch",data,timeoutSec,void 0);if(!localAvailable&&connectors.length===1)return this.invokeRemote("browser_launch",data,timeoutSec,void 0,connectors[0]);if(!localAvailable&&connectors.length===0)throw new Error("No browser host is available. Install @mearl/native-host locally or connect a cloud connector.");let availableHosts=[...localAvailable?["this machine [--local]"]:[],...connectors.map(connector=>`${connector.name} [${connector.connectorId}]`)].join(", ");throw new Error(`The browser host for browser_launch is ambiguous. Pass --local, --connector <id|name>, or --browser <global-id>. Available: ${availableHosts}`)}async selectDefaultBrowser(data,options,timeoutSec){let selector=typeof data.browser=="string"?data.browser.trim():"";if(!selector)return this.defaultBrowser=void 0,this.defaultConnector=void 0,{selected:null,note:"Cleared the process-wide default browser."};let listing=await this.invoke("browser_list",{},{timeoutSec,...options.local?{local:!0}:{},...options.transport?{transport:options.transport}:{},...options.connector?{connector:options.connector}:{}}),matches=findBrowsers(listing.browsers,selector);if(matches.length>1)throw new Error(`Browser selector "${selector}" is ambiguous. Use an exact global browserId.`);let match=matches[0];if(!match)throw new Error(`No connected browser matches "${selector}".`);return this.defaultBrowser=match.browserId,this.defaultConnector=void 0,{selected:{browserId:match.browserId,name:match.name}}}async resolveUnifiedBrowser(selector,timeoutSec,includeDisconnected){let listing=await this.listAllBrowsers(timeoutSec);if(selector){let matches=findBrowsers(listing.browsers,selector,!includeDisconnected);if(matches.length>1)throw new Error(`Browser selector "${selector}" is ambiguous. Use an exact global browserId from browser_list.`);if(matches.length===0)throw new Error(`No browser matches "${selector}". Run \`mearl browser_list\`.`);return matches[0].browserId}if(listing.defaultBrowserId)return listing.defaultBrowserId;let connected=listing.browsers.filter(browser=>browser.status==="connected");if(connected.length===1)return connected[0].browserId;if(connected.length>1)throw new Error("Multiple browsers are connected and there is no unique default. Pass --browser <global-id>.")}async listConnectors(timeoutSec=this.options.requestTimeoutSec){return this.options.serverUrl?this.requestRemote("connector_list",{},timeoutSec,void 0,void 0):{count:0,connectors:[]}}async resolveConnector(selector,timeoutSec){let connectors=(await this.listConnectors(timeoutSec)).connectors,selection=resolveCloudConnectorSelector(connectors,selector),available=connectors.map(connector=>`${connector.name} [${connector.connectorId}]`).join(", ");if(selection.status==="ambiguous")throw new Error(`Cloud connector selector "${selector}" is ambiguous. Use an exact connectorId. Available: ${available}`);if(selection.status!=="matched")throw new Error(`No cloud connector matches "${selector}". Available: ${available}`);return selection.connector}async listLocalBrowsers(timeoutSec,transport){let result=await invoke("browser_list",{},{timeoutSec,...transport?{transport}:{},controlSource:"local"});return this.applyConfiguredDefault(this.decorateListing(result,{kind:"local"}))}async tryLocalBrowserList(timeoutSec){try{return await invoke("browser_list",{},{timeoutSec,controlSource:"local"})}catch{return null}}decorateListing(result,source){let browsers=(Array.isArray(result?.browsers)?result.browsers:[]).map(browser=>decorateBrowser(browser,source)),resultWarnings=Array.isArray(result?.warnings)?result.warnings.filter(warning=>typeof warning=="string"):[];return{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,defaultBrowserId:typeof result?.defaultBrowserId=="string"?encodeBrowserTarget({browser:result.defaultBrowserId,...source.connectorId?{connector:source.connectorId}:{}}):null,browsers,...result?.discovery?{discovery:result.discovery}:{},...resultWarnings.length>0?{warnings:resultWarnings}:{}}}applyConfiguredDefault(listing){if(!this.defaultBrowser)return listing;let matches=findBrowsers(listing.browsers,this.defaultBrowser);return{...listing,defaultBrowserId:matches.length===1?matches[0].browserId:null}}async listConnectorBrowsers(selector,timeoutSec){let connector=await this.resolveConnector(selector,timeoutSec),result=await this.requestRemote("browser_list",{},timeoutSec,void 0,connector.connectorId);return this.applyConfiguredDefault(this.decorateListing(result,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name}))}async listAllBrowsers(timeoutSec){let warnings=[],localPromise=this.tryLocalBrowserList(timeoutSec),connectors=[];if(this.options.serverUrl)try{connectors=(await this.listConnectors(timeoutSec)).connectors}catch(error2){warnings.push(`cloud-server: ${errorMessage(error2)}`)}let localResult=await localPromise;localResult||warnings.push("this machine: local browser runtime is unavailable");let localConnectorId=localResult?loadLocalConnectorId():null,remoteConnectors=localConnectorId?connectors.filter(connector=>connector.connectorId!==localConnectorId):connectors,settled=await Promise.allSettled(remoteConnectors.map(async connector=>({connector,listing:await this.requestRemote("browser_list",{},timeoutSec,void 0,connector.connectorId)}))),remoteListings=[];for(let index=0;index<settled.length;index+=1){let result=settled[index],connector=remoteConnectors[index];result.status==="fulfilled"?remoteListings.push(result.value):warnings.push(`${connector.name}: ${errorMessage(result.reason)}`)}let listings=[];localResult&&listings.push(this.decorateListing(localResult,{kind:"local"}));for(let{connector,listing}of remoteListings)listings.push(this.decorateListing(listing,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name}));for(let listing of listings)warnings.push(...listing.warnings??[]);let browsers=listings.flatMap(listing=>listing.browsers),defaults=listings.map(listing=>listing.defaultBrowserId).filter(browserId=>typeof browserId=="string"),defaultBrowserId=null;return this.defaultBrowser&&browsers.some(browser=>browser.browserId===this.defaultBrowser)?defaultBrowserId=this.defaultBrowser:defaults.length===1&&(defaultBrowserId=defaults[0]),this.applyConfiguredDefault({count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,defaultBrowserId,browsers,...warnings.length>0?{warnings}:{}})}async invokeLocal(action,data,timeoutSec,browser,transport,controlSessionId,socketPath){let result=await invoke(action,data,{timeoutSec,...browser?{browser}:{},...transport?{transport}:{},...socketPath?{socketPath}:{},controlSource:"local",...controlSessionId?{controlSessionId}:{}});return this.decorateActionResult(action,result,{kind:"local"})}async invokeRemote(action,data,timeoutSec,browser,connector,controlSessionId){let result=await this.requestRemote(action,data,timeoutSec,browser,connector.connectorId,controlSessionId);return this.decorateActionResult(action,result,{kind:"remote",connectorId:connector.connectorId,connectorName:connector.name})}decorateActionResult(action,result,source){if(result?.session?.sessionId){let browserId=encodeBrowserTarget({browser:result.session.browserId,...source.connectorId?{connector:source.connectorId}:{}});action!=="__control_session_resolve"&&this.controlSessions.set(result.session.sessionId,{browser:browserId,id:result.session.sessionId,transport:result.session.transport}),result={...result,session:{...result.session,browserId}}}return typeof result?.browserId=="string"&&action.startsWith("__artifact_")?{...result,browserId:encodeBrowserTarget({browser:result.browserId,...source.connectorId?{connector:source.connectorId}:{}})}:(result?.download?.browserId&&(result={...result,download:{...result.download,browserId:encodeBrowserTarget({browser:result.download.browserId,...source.connectorId?{connector:source.connectorId}:{}})}}),action!=="browser_launch"||typeof result?.browserId!="string"?result:decorateBrowser(result,source))}async resolveControlSession(id,options){if(!/^s_[A-Za-z0-9_-]{8}$/.test(id))throw new Error("Invalid session id; reuse session.sessionId from the first response");let cached=this.controlSessions.get(id);if(cached)return cached;let timeoutSec=options.timeoutSec??15,localLookup=this.invokeLocal("__control_session_resolve",{sessionId:id},timeoutSec,void 0),discover=async()=>{let{connectors}=await this.listConnectors(timeoutSec);return Promise.allSettled(connectors.map(connector=>this.invokeRemote("__control_session_resolve",{sessionId:id},timeoutSec,void 0,connector)))},[local,remote]=await Promise.allSettled([localLookup,this.options.serverUrl&&!options.local&&!options.transport?discover():Promise.resolve([])]),localSession=local.status==="fulfilled"?local.value?.session:void 0,localTarget=decodeBrowserTarget(localSession?.browserId),localConnectorId=localSession?.sessionId===id?loadLocalConnectorId():null,results=[local,...remote.status==="fulfilled"?remote.value:[remote]].filter(result=>{if(result===local||result.status==="rejected")return!0;let session2=result.value?.session,target2=decodeBrowserTarget(session2?.browserId);return!(localConnectorId&&target2?.connector===localConnectorId&&target2.browser===localTarget?.browser&&session2?.sessionId===id&&session2.transport===localSession.transport)}),sessions=results.flatMap(result=>result.status==="fulfilled"&&result.value?.session?.sessionId===id?[result.value.session]:[]),ambiguous=results.some(result=>result.status==="rejected"&&errorMessage(result.reason).startsWith("CONTROL_SESSION_AMBIGUOUS"));if(sessions.length>1||ambiguous)throw this.controlSessions.delete(id),new Error("CONTROL_SESSION_AMBIGUOUS: multiple hosts own this id");let session=sessions[0];if(!session){let errors=results.flatMap(result=>result.status==="rejected"?[errorMessage(result.reason)]:[]);throw new Error(`CONTROL_SESSION_NOT_FOUND: ${id}${errors.length?` (${errors.join("; ")})`:""}`)}let target={browser:session.browserId,id,transport:session.transport};return this.controlSessions.set(id,target),target}async ensureConnected(){if(this.ws?.readyState!==WebSocket.OPEN){if(this.connectPromise)return this.connectPromise;this.closing=!1,this.connectPromise=this.connect();try{await this.connectPromise}finally{this.connectPromise=null}}}connect(){return new Promise((resolve7,reject)=>{if(!this.options.serverUrl){reject(new Error("Cloud server URL is required. Run mearl-cloud-server status on the Agent machine. Resolution order: --server > MEARL_SERVER_URL > ~/.mearl/cloud-server.json."));return}let ws=new WebSocket(this.options.serverUrl);this.ws=ws;let settled=!1,timer=setTimeout(()=>{ws.close(),settled||reject(new Error(`Connection timeout after ${this.options.connectTimeoutSec}s`))},this.options.connectTimeoutSec*1e3);ws.on("open",()=>{settled=!0,clearTimeout(timer),ws.send(JSON.stringify({type:"agent_hello"})+`
982
+ `),this.startHeartbeat(),resolve7()}),ws.on("message",data=>this.handleMessage(data)),ws.on("close",(code,reason)=>{clearTimeout(timer),this.rejectAllPending(new Error(`Connection closed (${code}: ${reason.toString()})`)),this.closing||(this.ws=null)}),ws.on("error",error2=>{clearTimeout(timer),settled||reject(error2)})})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping",timestamp:Date.now()})+`
983
+ `)},this.options.heartbeatInterval*1e3)}handleMessage(data){if(this.messageBuffer+=data.toString("utf8"),this.messageBuffer.length>10485760){this.disconnect();return}let newlineIndex;for(;(newlineIndex=this.messageBuffer.indexOf(`
984
+ `))!==-1;){let line=this.messageBuffer.slice(0,newlineIndex);if(this.messageBuffer=this.messageBuffer.slice(newlineIndex+1),!!line.trim())try{let message=JSON.parse(line);isHeartbeatMessage(message)||this.handleResponse(message)}catch{}}}handleResponse(response){let pending=this.pendingRequests.get(response.id);pending&&(this.pendingRequests.delete(response.id),clearTimeout(pending.timer),response.versionWarning&&console.warn(response.versionWarning),response.success?pending.resolve(response.data):pending.reject(new Error(response.error||"Unknown error from cloud-server")))}async requestRemote(action,data,timeoutSec,browser,connector,controlSessionId){await this.ensureConnected();let ws=this.ws;if(!ws||ws.readyState!==WebSocket.OPEN)throw new Error("Connection is not open");let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`,message={id,action,data,timeoutSec};browser&&(message.browser=browser),connector&&(message.connector=connector),controlSessionId&&(message.controlSessionId=controlSessionId);let serialized=`${JSON.stringify(message)}
985
+ `,bytes=Buffer.byteLength(serialized,"utf8");if(bytes>10485760)throw new Error(`Cloud request exceeds ${10485760} byte message limit (${bytes} bytes)`);return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{this.pendingRequests.delete(id),reject(new Error(`Request timeout after ${timeoutSec}s`))},timeoutSec*1e3+RESPONSE_GRACE_MS);this.pendingRequests.set(id,{resolve:resolve7,reject,timer}),ws.send(serialized)})}rejectAllPending(error2){for(let pending of this.pendingRequests.values())clearTimeout(pending.timer),pending.reject(error2);this.pendingRequests.clear()}}}});var init_process_env=__esm({"../agent-runtime/dist/process-env.js"(){"use strict";init_dist()}});import fs5 from"node:fs";import{spawn as spawn8}from"node:child_process";import path5 from"node:path";function agentExecutableCandidatePaths({executableNames,configuredPath,env=process.env,extraUserCandidates=[],home,platform=process.platform,processExecPath=process.execPath,readdirSync:readdirSync8}){let pathKey=Object.keys(env).find(key2=>key2.toLowerCase()==="path")||"PATH",pathCandidates=(env[pathKey]||"").split(path5.delimiter).filter(Boolean).flatMap(directory=>executableNames.map(name=>path5.join(directory,name))),commonUserDirectories=[path5.join(home,".local","bin"),path5.join(home,".npm-global","bin"),path5.join(home,".volta","bin"),path5.join(home,".local","share","pnpm"),path5.join(home,"Library","pnpm"),path5.join(home,".bun","bin"),...platform==="win32"&&env.APPDATA?[path5.join(env.APPDATA,"npm")]:[]],systemDirectories=platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"];return[configuredPath,...executableNames.map(name=>path5.join(path5.dirname(processExecPath),name)),...commonUserDirectories.flatMap(directory=>executableNames.map(name=>path5.join(directory,name))),...extraUserCandidates,...versionManagerExecutableCandidates(home,executableNames,{env,platform,readdirSync:readdirSync8}),...systemDirectories.flatMap(directory=>executableNames.map(name=>path5.join(directory,name))),...pathCandidates].filter(candidate=>typeof candidate=="string")}function executableFileCandidates(candidates){let seen=new Set,executableCandidates=[];for(let candidate of candidates)!candidate||seen.has(candidate)||(seen.add(candidate),isExecutableFile(candidate)&&executableCandidates.push(candidate));return executableCandidates}function probeAgentExecutable(executable,options){return new Promise(resolve7=>{let settled=!1,stderr="",launch=resolveSpawnCommand(executable,options.args),child=spawn8(launch.command,launch.args,{stdio:["ignore","ignore","pipe"],windowsHide:!0,env:prependNodePath()}),finish=error2=>{settled||(settled=!0,clearTimeout(timer),resolve7(error2))},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(options.timeoutError)},options.timeoutMs);child.stderr?.on("data",chunk=>{stderr.length<4e3&&(stderr+=chunk.toString("utf8"))}),child.once("error",error2=>finish(options.startError(error2))),child.once("exit",code=>{if(code===0){finish(null);return}finish(stderr.trim()||options.exitError(code))})})}function isExecutableFile(candidate){try{return fs5.accessSync(candidate,process.platform==="win32"?fs5.constants.F_OK:fs5.constants.X_OK),fs5.statSync(candidate).isFile()}catch{return!1}}var AgentExecutableResolver,init_executable_resolver=__esm({"../agent-runtime/dist/executable-resolver.js"(){"use strict";init_process_env();AgentExecutableResolver=class{options;resolvedExecutable=null;resolutionPromise=null;generation=0;constructor(options){this.options=options}async resolve(){if(this.resolvedExecutable){if(isExecutableFile(this.resolvedExecutable))return{executable:this.resolvedExecutable,error:null};this.resolvedExecutable=null}if(this.resolutionPromise)return this.resolutionPromise;let generation=this.generation,resolution=this.probeCandidates(generation);this.resolutionPromise=resolution;try{return await resolution}finally{this.resolutionPromise===resolution&&(this.resolutionPromise=null)}}reset(){this.generation+=1,this.resolvedExecutable=null,this.resolutionPromise=null}async probeCandidates(generation){let candidates=this.options.candidates();if(candidates.length===0)return{executable:null,error:this.options.notFoundError};let failures=[],recordFailure=(executable,error2)=>{failures.push({executable,error:error2}),this.options.onFailure?.(executable,error2)},select=(executable,version)=>(this.generation===generation&&(this.resolvedExecutable=executable,this.options.onSelection?.(executable,version)),{executable,error:null}),preferredCandidates=this.options.preferred?candidates.filter(executable=>this.options.preferred?.(executable)):[],automaticCandidates=candidates.filter(executable=>!preferredCandidates.includes(executable));for(let executable of preferredCandidates){let error2=await this.options.probe(executable);if(error2===null)return select(executable,null);recordFailure(executable,error2)}let getVersion=this.options.getVersion;if(getVersion){let inspected=await Promise.all(automaticCandidates.map(async(executable,index)=>{let[error2,version]=await Promise.all([this.options.probe(executable),getVersion(executable).catch(()=>null)]);return{executable,error:error2,index,version}})),usable=inspected.filter(candidate=>candidate.error===null);for(let candidate of inspected)candidate.error!==null&&recordFailure(candidate.executable,candidate.error);usable.sort((left,right)=>{if(left.version&&right.version&&this.options.compareVersions){let comparison=this.options.compareVersions(left.version,right.version);if(comparison!==0)return-comparison}else{if(left.version)return-1;if(right.version)return 1}return left.index-right.index});let selected=usable[0];if(selected)return select(selected.executable,selected.version)}else for(let executable of automaticCandidates){let error2=await this.options.probe(executable);if(error2===null)return select(executable,null);recordFailure(executable,error2)}let detail=failures.map(({executable,error:error2})=>{let compactError=error2.replace(/\s+/g," ").trim().slice(0,300);return`${executable}: ${compactError}`}).join("; ");return{executable:null,error:`${this.options.unusableError} ${detail}`}}}}});import fs6 from"node:fs";import os3 from"node:os";import path6 from"node:path";import readline from"node:readline";import{spawn as spawn9}from"node:child_process";function configOverride(value){return Array.isArray(value)?value.map(configOverride):value&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([,field])=>field!=null).map(([key2,field])=>[key2,configOverride(field)])):value}function normalizeCodexVersion(value){return typeof value!="string"||value.length>MAX_VERSION_OUTPUT_CHARS?null:CODEX_VERSION_PATTERN.exec(value.trim())?.[1]??null}function parsedCodexVersion(value){let normalized=normalizeCodexVersion(value);if(!normalized)return null;let withoutBuild=normalized.split("+",1)[0],prereleaseSeparator=withoutBuild.indexOf("-"),coreValue=prereleaseSeparator===-1?withoutBuild:withoutBuild.slice(0,prereleaseSeparator),prereleaseValue=prereleaseSeparator===-1?void 0:withoutBuild.slice(prereleaseSeparator+1),core=coreValue?.split(".").map(Number);return core?.length!==3||core.some(component=>!Number.isSafeInteger(component)||component<0)?null:{core,prerelease:prereleaseValue?prereleaseValue.split("."):[]}}function compareCodexVersions(leftValue,rightValue){let left=parsedCodexVersion(leftValue),right=parsedCodexVersion(rightValue);if(!left||!right)return leftValue.localeCompare(rightValue,void 0,{numeric:!0});for(let index=0;index<left.core.length;index+=1){let difference=left.core[index]-right.core[index];if(difference!==0)return difference}if(left.prerelease.length===0||right.prerelease.length===0)return left.prerelease.length===right.prerelease.length?0:left.prerelease.length===0?1:-1;let identifierCount=Math.max(left.prerelease.length,right.prerelease.length);for(let index=0;index<identifierCount;index+=1){let leftIdentifier=left.prerelease[index],rightIdentifier=right.prerelease[index];if(leftIdentifier===void 0||rightIdentifier===void 0)return leftIdentifier===rightIdentifier?0:leftIdentifier===void 0?-1:1;if(leftIdentifier===rightIdentifier)continue;let leftNumeric=/^\d+$/.test(leftIdentifier),rightNumeric=/^\d+$/.test(rightIdentifier);return leftNumeric&&rightNumeric?Number(leftIdentifier)-Number(rightIdentifier):leftNumeric!==rightNumeric?leftNumeric?-1:1:leftIdentifier.localeCompare(rightIdentifier)}return 0}function codexAppExecutableCandidatePaths(options={}){let env=options.env??process.env,home=(options.homedir??os3.homedir)(),platform=options.platform??process.platform;return platform==="darwin"?["/Applications",path6.join(home,"Applications")].flatMap(root=>["ChatGPT.app","Codex.app"].flatMap(app=>{let resources=path6.join(root,app,"Contents","Resources");return[path6.join(resources,"codex-cli","CodexCLI.app","Contents","MacOS","codex"),path6.join(resources,"codex")]})):platform==="win32"?[path6.join(env.LOCALAPPDATA||path6.join(home,"AppData","Local"),"Programs"),env.ProgramFiles,env["ProgramFiles(x86)"]].filter(root=>typeof root=="string"&&root.length>0).flatMap(root=>["ChatGPT","Codex"].map(app=>path6.join(root,app,"resources","codex.exe"))):[]}function isIdeBundledCodexPath(candidate,home){let resolvedCandidates=[path6.resolve(candidate)];try{resolvedCandidates.push(fs6.realpathSync(candidate))}catch{}return[".vscode",".vscode-insiders",".cursor",".windsurf"].some(directory=>{let extensionsRoot=`${path6.join(home,directory,"extensions")}${path6.sep}`;return resolvedCandidates.some(resolved=>resolved.startsWith(extensionsRoot))})}function codexExecutableCandidatePaths(options={}){let env=options.env??process.env,home=(options.homedir??os3.homedir)(),platform=options.platform??process.platform;return agentExecutableCandidatePaths({executableNames:[platform==="win32"?"codex.cmd":"codex"],configuredPath:env.MEARL_CODEX_PATH,env,home,platform,processExecPath:options.processExecPath,readdirSync:options.readdirSync,extraUserCandidates:codexAppExecutableCandidatePaths({env,homedir:()=>home,platform})}).filter(candidate=>candidate===env.MEARL_CODEX_PATH||!isIdeBundledCodexPath(candidate,home))}function codexPackageVersion(executable){let packageFiles=[];try{let resolved=fs6.realpathSync(executable);if(resolved.split(path6.sep).includes("node_modules")){let directory=path6.dirname(resolved);for(let depth=0;depth<6;depth+=1){packageFiles.push(path6.join(directory,"package.json"));let parent=path6.dirname(directory);if(parent===directory)break;directory=parent}}}catch{}/\.(?:cmd|bat)$/i.test(executable)&&packageFiles.push(path6.join(path6.dirname(executable),"node_modules","@openai","codex","package.json"));for(let packageFile of packageFiles)try{let manifest=JSON.parse(fs6.readFileSync(packageFile,"utf8"));if(manifest.name==="@openai/codex"){let version=normalizeCodexVersion(manifest.version);if(version)return version}}catch{}return null}function codexExecutableVersion(executable){let packageVersion=codexPackageVersion(executable);return packageVersion?Promise.resolve(packageVersion):new Promise(resolve7=>{let settled=!1,output="",launch=resolveSpawnCommand(executable,["--version"]),child=spawn9(launch.command,launch.args,{stdio:["ignore","pipe","pipe"],windowsHide:!0,env:prependNodePath()}),finish=version=>{settled||(settled=!0,clearTimeout(timer),resolve7(version))},capture=chunk=>{let remaining=MAX_VERSION_OUTPUT_CHARS-output.length;remaining>0&&(output+=chunk.toString("utf8").slice(0,remaining))};child.stdout.on("data",capture),child.stderr.on("data",capture),child.once("error",()=>finish(null)),child.once("exit",code=>finish(code===0?normalizeCodexVersion(output):null));let timer=setTimeout(()=>{child.kill("SIGTERM"),finish(null)},PROBE_TIMEOUT_MS)})}function codexModelInfo(value){if(typeof value!="string")return;let id=value.trim().slice(0,MAX_MODEL_CHARS);return id?{id}:void 0}function fullAccessWithApprovals(){return{sandbox:"danger-full-access",approvalPolicy:"untrusted"}}function timestampMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e12?value*1e3:value;if(typeof value=="string"){let parsed=Date.parse(value);return Number.isNaN(parsed)?void 0:parsed}}function codexSkillScope(value){return value==="user"?"global":value==="repo"?"project":value==="system"||value==="admin"?value:"unknown"}function userMessageText(item){return Array.isArray(item?.content)?item.content.flatMap(part=>part?.type==="text"&&typeof part.text=="string"?[part.text]:[]).join(`
986
+ `):""}function userMessageImageCount(item){return Array.isArray(item?.content)?item.content.filter(part=>part?.type==="image"||part?.type==="localImage").length:0}function threadHistoryEvents(thread){if(!Array.isArray(thread?.turns))return[];let events=[];for(let turn of thread.turns.slice(-100)){if(!turn||typeof turn.id!="string"||!Array.isArray(turn.items))continue;let timestamp=timestampMs(turn.completedAt??turn.startedAt);for(let item of turn.items)if(!(!item||typeof item.id!="string"||typeof item.type!="string")){if(item.type==="userMessage"){let text3=userMessageText(item),imageCount=userMessageImageCount(item);(text3||imageCount>0)&&events.push({kind:"lifecycle",method:"chat/userMessage",params:{text:text3,...imageCount>0?{imageCount}:{}},...timestamp!==void 0?{timestamp}:{}});continue}events.push({kind:"notification",method:"item/completed",params:{turnId:turn.id,item},...timestamp!==void 0?{timestamp}:{}})}}return events}function codexThreadUrl(providerSessionId){if(!/^[a-zA-Z0-9_-]+$/.test(providerSessionId))throw new Error("Codex returned an invalid thread id");return`codex://threads/${providerSessionId}`}function codexWorkspaceUrl(directory){return`codex://threads/new?path=${encodeURIComponent(directory)}`}function externalOpenCommand(url,platform=process.platform){return platform==="darwin"?{command:"open",args:[url]}:platform==="win32"?{command:"cmd.exe",args:["/d","/s","/c","start","",url]}:{command:"xdg-open",args:[url]}}function openExternalUrl(url){let{command,args}=externalOpenCommand(url);return new Promise((resolve7,reject)=>{let child=spawn9(command,args,{stdio:"ignore",windowsHide:!0});child.once("error",error2=>{reject(new Error(`Unable to open Codex App: ${error2.message}`))}),child.once("close",code=>{code===0?resolve7():reject(new Error("Unable to open Codex App. Make sure it is installed."))})})}var REQUEST_TIMEOUT_MS,PROBE_TIMEOUT_MS,MAX_MODEL_CHARS,MAX_VERSION_OUTPUT_CHARS,CODEX_NOT_FOUND_ERROR,CODEX_VERSION_PATTERN,CodexAgentProvider,init_codex_provider=__esm({"../agent-runtime/dist/codex-provider.js"(){"use strict";init_executable_resolver();init_process_env();REQUEST_TIMEOUT_MS=3e4,PROBE_TIMEOUT_MS=5e3,MAX_MODEL_CHARS=256,MAX_VERSION_OUTPUT_CHARS=1024,CODEX_NOT_FOUND_ERROR="Codex was not found. Install @openai/codex, install the Codex App, or set MEARL_CODEX_PATH.",CODEX_VERSION_PATTERN=/^(?:codex-cli\s+)?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/;CodexAgentProvider=class{log;clientVersion;mearlSocketPath;id="codex";process=null;initialized=!1;lifecycle=0;modelRuntime;startPromise=null;nextRequestId=1;pendingRequests=new Map;listeners=new Set;knownThreadIds=new Set;sessionModels=new Map;executableResolver;constructor(log,clientVersion,mearlSocketPath){this.log=log,this.clientVersion=clientVersion,this.mearlSocketPath=mearlSocketPath,this.executableResolver=new AgentExecutableResolver({candidates:()=>this.resolveExecutableCandidates(),probe:executable=>this.probeExecutable(executable),getVersion:executable=>this.readExecutableVersion(executable),compareVersions:compareCodexVersions,preferred:executable=>executable===process.env.MEARL_CODEX_PATH,notFoundError:CODEX_NOT_FOUND_ERROR,unusableError:"Codex candidates were found, but none supports app-server.",onFailure:(executable,error2)=>{this.log("[Codex] Skipping unusable runtime:",executable,error2)},onSelection:(executable,version)=>{this.modelRuntime={executable,...version?{version}:{},selection:executable===process.env.MEARL_CODEX_PATH?"explicit":"automatic",started:!1},this.modelDiagnostic({runtime:this.modelRuntime}),this.log("[Codex] Selected runtime:",executable,version?`(version ${version})`:executable===process.env.MEARL_CODEX_PATH?"(explicitly configured)":"(version unavailable)")}})}async getDescriptor(){let{error:error2}=await this.resolveExecutable();return{id:this.id,name:"Codex",available:error2===null,capabilities:{streaming:!0,resume:!0,listSessions:!0,refreshHistory:!0,imageInput:!0,interrupt:!0,requests:!0},...error2?{error:error2}:{},setup:{installCommand:"npm install -g @openai/codex",loginCommand:"codex login",docsUrl:"https://developers.openai.com/codex/cli"}}}async prepare(){await this.ensureStarted()}async listModels(){await this.ensureStarted();let models=new Map,cursor,cursors=new Set;for(let page=0;page<4;page++){let result=await this.request("model/list",{limit:100,...cursor?{cursor}:{}});if(!Array.isArray(result?.data))throw new Error("Invalid Codex model list");for(let value of result.data){let id=value?.model??value?.id;if(value?.hidden||typeof id!="string"||!id||id.length>256||models.has(id))continue;let efforts=["none","minimal","low","medium","high","xhigh","max"],reasoningEfforts=Array.isArray(value.supportedReasoningEfforts)?efforts.filter(effort=>value.supportedReasoningEfforts.some(option=>option?.reasoningEffort===effort)):void 0;if(models.set(id,{id,displayName:typeof value.displayName=="string"?value.displayName.slice(0,256):id,...typeof value.description=="string"?{description:value.description.slice(0,2e3)}:{},isDefault:value.isDefault===!0,...reasoningEfforts?{reasoningEfforts}:{},...efforts.includes(value.defaultReasoningEffort)?{defaultReasoningEffort:value.defaultReasoningEffort}:{}}),models.size>=200)break}if(!result.nextCursor||models.size>=200)break;if(typeof result.nextCursor!="string"||cursors.has(result.nextCursor))throw new Error("Invalid Codex model cursor");cursor=result.nextCursor,cursors.add(result.nextCursor)}return[...models.values()]}onEvent(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}async listSessions(options){await this.ensureStarted();let result=await this.request("thread/list",{cursor:options.cursor??null,limit:options.limit,sortKey:"updated_at",sortDirection:"desc",archived:!1,...options.cwd?{cwd:options.cwd}:{}});return{sessions:Array.isArray(result?.data)?result.data.flatMap(thread=>{if(!thread||typeof thread.id!="string")return[];let title=typeof thread.name=="string"&&thread.name.trim()?thread.name.trim():typeof thread.preview=="string"&&thread.preview.trim()?thread.preview.trim():void 0,cwd=typeof thread.cwd=="string"?thread.cwd:void 0,updatedAt=timestampMs(thread.recencyAt??thread.updatedAt),ephemeral=typeof thread.ephemeral=="boolean"?thread.ephemeral:void 0;return[{providerSessionId:thread.id,...title?{title}:{},...cwd?{cwd}:{},...updatedAt!==void 0?{updatedAt}:{},...ephemeral!==void 0?{ephemeral}:{}}]}):[],...typeof result?.nextCursor=="string"?{nextCursor:result.nextCursor}:{}}}async listSkills(cwd){await this.ensureStarted();let result=await this.request("skills/list",{cwds:[cwd||os3.homedir()],forceReload:!0});return Array.isArray(result?.data)?result.data.flatMap(entry=>Array.isArray(entry?.skills)?entry.skills.flatMap(skill=>!skill||typeof skill.name!="string"||typeof skill.path!="string"?[]:[{name:skill.name,path:skill.path,scope:codexSkillScope(skill.scope)}]):[]):[]}async startSession(options){await this.ensureStarted();let cwd=options.cwd||process.env.MEARL_AGENT_CWD||os3.homedir(),config=options.modelExecution?await this.modelExecutionConfig():void 0,result=await this.request("thread/start",{...config?{config}:{},cwd,...options.modelId?{model:options.modelId}:{},...options.readOnly?{sandbox:"read-only",approvalPolicy:"never"}:fullAccessWithApprovals(),...options.ephemeral!==void 0?{ephemeral:options.ephemeral}:{},...options.developerInstructions?{developerInstructions:options.developerInstructions}:{}}),threadId=result?.thread?.id;if(typeof threadId!="string"||!threadId)throw new Error("Codex did not return a thread id");options.modelExecution&&this.modelDiagnostic({threadRestrictionsAccepted:!0}),this.knownThreadIds.add(threadId);let model=codexModelInfo(result?.model);return model&&this.sessionModels.set(threadId,model),threadId}async modelExecutionConfig(){let config=(await this.request("config/read",{includeLayers:!1}))?.config;if(!config||typeof config!="object")throw new Error("Codex cannot report its effective execution configuration");let home=process.env.CODEX_HOME||path6.join(os3.homedir(),".codex"),store=config.cli_auth_credentials_store;this.modelDiagnostic({configuration:{source:process.env.CODEX_HOME?"environment":"default",home,filePresent:fs6.existsSync(path6.join(home,"config.toml")),...typeof config.model_provider=="string"?{baseProvider:config.model_provider}:{},...typeof store=="string"?{credentialStore:["file","keyring","auto","ephemeral"].includes(store)?store:"unknown"}:{}}});let mcp=config.mcp_servers??{},apps=config.apps??{};if(typeof mcp!="object"||Array.isArray(mcp)||typeof apps!="object"||Array.isArray(apps))throw new Error("Invalid Codex model tool configuration");return configOverride({mcp_servers:Object.fromEntries(Object.keys(mcp).map(name=>[name,{...mcp[name],enabled:!1}])),apps:Object.fromEntries(["_default",...Object.keys(apps)].map(name=>[name,{...apps[name]??{},enabled:!1}])),web_search:"disabled",features:{apps:!1,plugins:!1,hooks:!1,codex_hooks:!1,plugin_hooks:!1,multi_agent:!1,multi_agent_v2:!1,collab:!1,computer_use:!1,browser_use:!1,image_generation:!1,imagegenext:!1,memory_tool:!1,memories:!1,skill_search:!1}})}async resumeSession(providerSessionId,options){await this.ensureStarted();let result=await this.request("thread/resume",{threadId:providerSessionId,...options.cwd?{cwd:options.cwd}:{},...fullAccessWithApprovals(),...options.developerInstructions?{developerInstructions:options.developerInstructions}:{}}),threadId=result?.thread?.id;if(typeof threadId!="string"||!threadId)throw new Error("Codex did not return a resumed thread id");this.knownThreadIds.add(threadId);let model=codexModelInfo(result?.model);return model&&this.sessionModels.set(threadId,model),{providerSessionId:threadId,history:threadHistoryEvents(result.thread),historyComplete:!0}}getSessionModel(providerSessionId){let model=this.sessionModels.get(providerSessionId);return model?{...model}:void 0}async sendMessage(providerSessionId,message,images=[],options={}){await this.ensureStarted();let turnId=(await this.request("turn/start",{threadId:providerSessionId,input:[...message?[{type:"text",text:message,text_elements:[]}]:[],...images.map(image=>({type:"image",url:`data:${image.mimeType};base64,${image.data}`}))],summary:options.reasoningSummary??"detailed",...options.outputSchema?{outputSchema:options.outputSchema}:{},...options.modelExecution?{approvalPolicy:"never",sandboxPolicy:{type:"readOnly",networkAccess:!1}}:{},...options.reasoningEffort?{effort:options.reasoningEffort}:{}}))?.turn?.id;if(typeof turnId!="string"||!turnId)throw new Error("Codex did not return a turn id");return options.modelExecution&&this.modelDiagnostic({turnRestrictionsAccepted:!0}),{turnId}}async interrupt(providerSessionId,turnId){await this.ensureStarted(),await this.request("turn/interrupt",{threadId:providerSessionId,turnId})}async closeSession(providerSessionId){this.knownThreadIds.delete(providerSessionId),this.sessionModels.delete(providerSessionId),this.initialized&&this.request("thread/unsubscribe",{threadId:providerSessionId}).catch(error2=>{this.log("[Codex] Unable to unsubscribe thread:",String(error2))})}openSession(providerSessionId){return openExternalUrl(codexThreadUrl(providerSessionId))}openWorkspace(cwd){return openExternalUrl(codexWorkspaceUrl(cwd))}respondToRequest(requestId,result){this.write({id:requestId,result})}dispose(){this.lifecycle++,this.rejectPending(new Error("Codex provider disposed"));let child=this.process;this.process=null,this.initialized=!1,this.startPromise=null,this.sessionModels.clear(),this.executableResolver.reset(),child&&!child.killed&&child.kill("SIGTERM")}async ensureStarted(){if(this.process&&!this.process.killed&&this.initialized)return;if(this.startPromise)return this.startPromise;this.process&&!this.process.killed&&(this.process.kill("SIGTERM"),this.process=null);let pending=this.start();this.startPromise=pending;try{await pending}catch(error2){throw this.startPromise===pending&&(this.startPromise=null),error2}}async start(){let lifecycle=this.lifecycle,resolution=await this.resolveExecutable();if(lifecycle!==this.lifecycle)throw new Error("Codex provider disposed during startup");if(resolution.executable===null)throw new Error(resolution.error);let{executable}=resolution,launch=resolveSpawnCommand(executable,["app-server","--listen","stdio://"]),childEnv=prependNodePath();this.mearlSocketPath&&(childEnv.MEARL_SOCKET_PATH=this.mearlSocketPath);let child=spawn9(launch.command,launch.args,{stdio:["pipe","pipe","pipe"],windowsHide:!0,env:childEnv});this.process=child,readline.createInterface({input:child.stdout}).on("line",line=>this.handleLine(line)),child.stderr.on("data",chunk=>{let message=chunk.toString("utf8").trim();message&&this.log("[Codex]",message)}),child.once("error",error2=>this.handleExit(child,error2)),child.once("exit",(code,signal)=>{this.handleExit(child,new Error(`Codex app-server exited (code=${String(code)}, signal=${String(signal)})`))});try{await this.request("initialize",{clientInfo:{name:"mearl",title:"Mearl",version:this.clientVersion},capabilities:{experimentalApi:!0}}),this.write({method:"initialized",params:{}}),this.initialized=!0,this.modelRuntime&&(this.modelRuntime={...this.modelRuntime,started:!0},this.modelDiagnostic({runtime:this.modelRuntime}))}catch(error2){let startupError=error2 instanceof Error?error2:new Error(String(error2));throw this.handleExit(child,startupError),child.killed||child.kill("SIGTERM"),startupError}}handleLine(line){let message;try{message=JSON.parse(line)}catch{this.log("[Codex] Invalid JSONL message:",line);return}if(message.method){let isRequest=message.id!==void 0,providerSessionId=this.extractThreadId(message.params);if(!isRequest&&providerSessionId&&message.method==="thread/settings/updated"){let model=codexModelInfo(message.params?.threadSettings?.model);model&&(this.sessionModels.set(providerSessionId,model),this.emit({providerSessionId,kind:"notification",method:"session/model/updated",params:{model}}))}else if(!isRequest&&providerSessionId&&message.method==="model/rerouted"){let model=codexModelInfo(message.params?.toModel);model&&this.emit({providerSessionId,kind:"notification",method:"session/activeModel/updated",params:{model}})}this.emit({providerSessionId,kind:isRequest?"request":message.method==="error"?"error":"notification",method:message.method,params:message.params??{},...isRequest?{requestId:message.id}:{}});return}if(typeof message.id!="number")return;let pending=this.pendingRequests.get(message.id);pending&&(clearTimeout(pending.timer),this.pendingRequests.delete(message.id),message.error?pending.reject(new Error(message.error.message||`Codex error ${message.error.code??""}`)):pending.resolve(message.result))}request(method,params){let id=this.nextRequestId++;return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{this.pendingRequests.delete(id),reject(new Error(`Codex request timed out: ${method}`))},REQUEST_TIMEOUT_MS);this.pendingRequests.set(id,{resolve:resolve7,reject,timer});try{this.write({id,method,params})}catch(error2){clearTimeout(timer),this.pendingRequests.delete(id),reject(error2 instanceof Error?error2:new Error(String(error2)))}})}write(message){let child=this.process;if(!child||child.killed||!child.stdin.writable)throw new Error("Codex app-server is not running");child.stdin.write(`${JSON.stringify(message)}
987
+ `)}handleExit(child,error2){if(this.process===child){this.process=null,this.initialized=!1,this.startPromise=null,this.executableResolver.reset(),this.rejectPending(error2);for(let providerSessionId of this.knownThreadIds)this.emit({providerSessionId,kind:"error",method:"provider/exited",params:{message:error2.message}})}}rejectPending(error2){for(let[id,pending]of this.pendingRequests)clearTimeout(pending.timer),pending.reject(error2),this.pendingRequests.delete(id)}modelDiagnostic(metadata){this.emit({kind:"notification",method:"provider/model/diagnostic",params:metadata})}emit(event){for(let listener of this.listeners)listener(event)}extractThreadId(params){return[params?.threadId,params?.conversationId,params?.thread?.id,params?.turn?.threadId].find(value=>typeof value=="string")}probeExecutable(executable){return probeAgentExecutable(executable,{args:["app-server","--help"],timeoutMs:PROBE_TIMEOUT_MS,timeoutError:"Timed out while checking Codex app-server availability.",startError:error2=>`Failed to start Codex: ${error2.message}`,exitError:code=>`Codex app-server check exited with code ${String(code)}`})}readExecutableVersion(executable){return codexExecutableVersion(executable)}resolveExecutable(){return this.executableResolver.resolve()}resolveExecutableCandidates(){return executableFileCandidates(codexExecutableCandidatePaths())}}}});import{readFileSync as readFileSync17}from"node:fs";async function runCodexModel(request,context,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync17(new URL("../package.json",import.meta.url),"utf8")).version)){if(request.provider!=="codex"||request.mode!=="agent"||request.permissions!=="read-only")throw Object.assign(new Error("Codex supports explicit read-only agent execution; strict tool-free generation is unavailable"),{code:"PLUGIN_MODEL_CAPABILITY_UNSUPPORTED"});context.signal.throwIfAborted();let session,turn,text3,bytes=0,index=0,retries=0,buffered="",streamItem,streamPhase,phases=new Map,flushTimer,flush=()=>{clearTimeout(flushTimer),flushTimer=void 0;try{for(let offset=0;offset<buffered.length;offset+=4e3)streamItem||streamPhase?context.onDelta(buffered.slice(offset,offset+4e3),++index,{...streamItem?{itemId:streamItem}:{},...streamPhase?{phase:streamPhase}:{}}):context.onDelta(buffered.slice(offset,offset+4e3),++index)}catch(error2){fail3(error2)}buffered=""},finish,fail3,completed=new Promise((resolve7,reject)=>{finish=resolve7,fail3=reject});completed.catch(()=>{});let listener=event=>{let params=event.params;event.method==="provider/model/diagnostic"&&context.onDiagnostic?.(params),event.method==="account/updated"&&context.onDiagnostic?.({authentication:["apikey","chatgpt","chatgptAuthTokens"].includes(params?.authMode)?params.authMode:"unknown"}),event.method==="session/model/updated"&&typeof params?.model?.id=="string"&&context.onDiagnostic?.({selectedModel:params.model.id}),event.method==="session/activeModel/updated"&&typeof params?.model?.id=="string"&&context.onDiagnostic?.({activeModel:params.model.id});let relevant=event.providerSessionId===void 0||event.providerSessionId===session;if(event.kind==="request"&&relevant){try{provider.respondToRequest(event.requestId,{error:"Interactive requests are disabled for background model tasks"})}catch{}fail3(Object.assign(new Error("Model requested interactive input"),{code:"PLUGIN_MODEL_INTERACTION_REQUIRED"})),provider.dispose();return}if((event.kind==="error"||event.method==="provider/exited")&&relevant){if(event.method!=="provider/exited"&&params?.willRetry===!0){context.onDiagnostic?.({retryCount:++retries});return}fail3(Object.assign(new Error(String(params?.error?.message??params?.message??"Model provider failed")),{code:"PLUGIN_MODEL_PROVIDER_ERROR"})),provider.dispose();return}if(!(!session||event.providerSessionId!==session))if(event.method==="item/started"&&params?.item?.type==="agentMessage")flush(),streamItem=params.item.id,streamPhase=params.item.phase,streamItem&&streamPhase&&phases.set(streamItem,streamPhase);else if(event.method==="item/agentMessage/delta"&&typeof params?.delta=="string"){let itemId=params.itemId??streamItem,phase=params.phase??(itemId?phases.get(itemId):streamPhase);if((itemId!==streamItem||phase!==streamPhase)&&flush(),streamItem=itemId,streamPhase=phase,bytes+=Buffer.byteLength(params.delta),bytes>32*1024*1024){fail3(new Error("Model output exceeds 32 MiB"));return}buffered+=params.delta,buffered.length>=16e3?flush():flushTimer??=setTimeout(flush,50)}else if(event.method==="item/completed"&&params?.item?.type==="agentMessage"&&typeof params.item.text=="string"){if(flush(),Buffer.byteLength(params.item.text)>32*1024*1024){fail3(new Error("Model output exceeds 32 MiB"));return}(!params.item.phase||params.item.phase==="final_answer")&&(text3=params.item.text)}else event.method==="turn/completed"&&(params?.turn?.status!=="completed"?fail3(Object.assign(new Error(`Model turn ended with ${String(params?.turn?.status)}${params?.turn?.error?.message?`: ${params.turn.error.message}`:""}`),{code:"PLUGIN_MODEL_TURN_FAILED"})):text3===void 0?fail3(new Error("Model returned no final text")):(flush(),finish(text3)))},unsubscribe=provider.onEvent(listener),abort=()=>{fail3(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"})),session&&turn&&provider.interrupt(session,turn).catch(()=>{}),provider.dispose()};context.signal.addEventListener("abort",abort,{once:!0});try{session=context.conversation?.threadId??await provider.startSession({cwd:context.cwd,ephemeral:!0,readOnly:!0,modelExecution:!0,...request.model?{modelId:request.model}:{},...request.instructions?{developerInstructions:request.instructions}:{}}),context.conversation&&(context.conversation.threadId=session),context.onDiagnostic?.({...provider.getSessionModel(session)?.id?{selectedModel:provider.getSessionModel(session).id}:{}}),context.signal.throwIfAborted();let[,result]=await Promise.all([provider.sendMessage(session,request.prompt,[],{reasoningSummary:"none",reasoningEffort:request.reasoningEffort,outputSchema:request.outputSchema,modelExecution:!0}).then(value=>{turn=value.turnId}),completed]);return context.signal.throwIfAborted(),{text:result,provider:request.provider,mode:request.mode,...provider.getSessionModel(session)?.id?{model:provider.getSessionModel(session).id}:{}}}catch(error2){throw context.conversation&&(delete context.conversation.threadId,provider.dispose()),error2}finally{clearTimeout(flushTimer),context.signal.removeEventListener("abort",abort),unsubscribe(),context.conversation||provider.dispose()}}var init_model=__esm({"../agent-runtime/dist/model.js"(){"use strict";init_codex_provider();init_capabilities()}});import{readFileSync as readFileSync18}from"node:fs";async function listCodexModels(signal,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync18(new URL("../package.json",import.meta.url),"utf8")).version)){signal.throwIfAborted();let abort,cancelled=new Promise((_resolve,reject)=>{abort=()=>{provider.dispose(),reject(signal.reason??new Error("Model discovery cancelled"))},signal.addEventListener("abort",abort,{once:!0})});try{return await Promise.race([provider.listModels(),cancelled])}finally{signal.removeEventListener("abort",abort),provider.dispose()}}var init_model_catalog=__esm({"../agent-runtime/dist/model-catalog.js"(){"use strict";init_codex_provider()}});var codex_exports={};__export(codex_exports,{CODEX_MODEL_CAPABILITY:()=>CODEX_MODEL_CAPABILITY,CodexAgentProvider:()=>CodexAgentProvider,codexAppExecutableCandidatePaths:()=>codexAppExecutableCandidatePaths,codexExecutableCandidatePaths:()=>codexExecutableCandidatePaths,codexThreadUrl:()=>codexThreadUrl,codexWorkspaceUrl:()=>codexWorkspaceUrl,compareCodexVersions:()=>compareCodexVersions,externalOpenCommand:()=>externalOpenCommand,listCodexModels:()=>listCodexModels,normalizeCodexVersion:()=>normalizeCodexVersion,runCodexModel:()=>runCodexModel});var init_codex=__esm({"../agent-runtime/dist/codex.js"(){"use strict";init_codex_provider();init_model();init_model_catalog()}});init_runtimePaths();init_dist();init_dist2();init_pluginHostPaths();import{randomUUID as randomUUID14}from"node:crypto";import{createServer}from"node:net";import{chmodSync as chmodSync2,rmSync as rmSync14}from"node:fs";init_dist();init_dist2();init_dist2();import{basename as basename2}from"node:path";var MAX_PLUGIN_DIAGNOSTIC_BYTES=256*1024;function text2(value,maximum=256){if(typeof value!="string")return;let bytes=Buffer.from(value);return bytes.length<=maximum?value:bytes.subarray(0,maximum).toString("utf8").replace(/\uFFFD$/,"")}function normalizeDiagnosticOptions(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid diagnostic options");let input=value;if(Object.keys(input).some(key2=>!["taskId","plugin","instanceId","includeErrorMessages","includeLocalPaths"].includes(key2)))throw new Error("Unknown diagnostic option");if(input.taskId!==void 0&&!isPluginTaskId(input.taskId))throw new Error("Invalid diagnostic task ID");if(input.instanceId!==void 0&&!isPluginPageInstanceId(input.instanceId))throw new Error("Invalid diagnostic instance ID");if(input.plugin!==void 0&&(typeof input.plugin!="string"||!/^[a-z][a-z0-9_-]*$/.test(input.plugin)||input.plugin.length>128))throw new Error("Invalid diagnostic plugin");for(let key2 of["includeErrorMessages","includeLocalPaths"])if(input[key2]!==void 0&&typeof input[key2]!="boolean")throw new Error("Invalid diagnostic content option");return{...input.taskId?{taskId:String(input.taskId)}:{},...input.plugin?{plugin:String(input.plugin)}:{},...input.instanceId?{instanceId:String(input.instanceId)}:{},...input.includeErrorMessages!==void 0?{includeErrorMessages:input.includeErrorMessages}:{},...input.includeLocalPaths!==void 0?{includeLocalPaths:input.includeLocalPaths}:{}}}function diagnosticFailure(value,options){if(!value)return;let message=options.includeErrorMessages?text2(value.message,4096):void 0;return{code:text2(value.code)??"PLUGIN_ERROR_UNCLASSIFIED",...message!==void 0?{message,...Buffer.byteLength(value.message??"")>4096?{messageTruncated:!0}:{}}:{}}}function normalizeModelDiagnostic(value,previous={}){let result={...previous};if(!value||typeof value!="object"||Array.isArray(value))return result;let input=value;for(let key2 of["requestedModel","selectedModel","activeModel"])typeof input[key2]=="string"&&(result[key2]=text2(input[key2]));["apikey","chatgpt","chatgptAuthTokens","unknown"].includes(input.authentication)&&(result.authentication=input.authentication);for(let key2 of["threadRestrictionsAccepted","turnRestrictionsAccepted"])typeof input[key2]=="boolean"&&(result[key2]=input[key2]);Number.isSafeInteger(input.retryCount)&&input.retryCount>=0&&(result.retryCount=Math.min(input.retryCount,1e6));let runtime=input.runtime;runtime&&["explicit","automatic"].includes(runtime.selection)&&(result.runtime={...typeof runtime.executable=="string"?{executable:text2(runtime.executable,4096)}:{},...typeof runtime.version=="string"?{version:text2(runtime.version)}:{},selection:runtime.selection,...typeof runtime.started=="boolean"?{started:runtime.started}:{}});let config=input.configuration;return config&&["default","environment"].includes(config.source)&&typeof config.filePresent=="boolean"&&(result.configuration={source:config.source,filePresent:config.filePresent,...typeof config.home=="string"?{home:text2(config.home,4096)}:{},...typeof config.baseProvider=="string"?{baseProvider:text2(config.baseProvider)}:{},...["file","keyring","auto","ephemeral","unknown"].includes(config.credentialStore)?{credentialStore:config.credentialStore}:{}}),result}function diagnosticBinding(value){return{instanceId:value.instanceId,browserSessionId:value.target.browserSessionId,tabId:value.target.tabId,frameId:value.target.frameId,documentId:value.target.documentId}}function modelProjection(record2,options){if(record2.task.kind!=="model")return;let request=record2.task.input.request,metadata=normalizeModelDiagnostic(record2.diagnostics?.model,typeof request?.model=="string"?{requestedModel:text2(request.model)}:{});if(!options.includeLocalPaths&&(metadata.runtime?.executable&&(metadata.runtime={...metadata.runtime,executable:basename2(metadata.runtime.executable)}),metadata.configuration)){let{home:_home,...configuration}=metadata.configuration;metadata.configuration=configuration}return metadata}function taskProjection(record2,options,observedAt){let{task,diagnostics,execution,executorOwner:owner}=record2,events=record2.events.filter(event=>event.type!=="progress"),first=record2.events[0]?.sequence??task.sequence+1,alive=owner&&!diagnostics?.executorStoppedAt?isProcessOwnerAlive(owner):!1,stopped=diagnostics?.executorStoppedAt,state=alive?"observed-alive":stopped?"stop-confirmed":diagnostics?.executorAttempted===!1?"never-started":"unknown",routing=execution?.options;return{taskId:task.taskId,plugin:text2(task.plugin),kind:task.kind??"command",command:text2(task.command),state:task.state,source:task.source,host:{hostId:task.host.hostId,epoch:task.host.epoch},installationId:task.installationId,revision:task.revision,...diagnostics?.invocationId?{invocationId:diagnostics.invocationId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt,sequence:task.sequence,...diagnostics?.page?{page:diagnosticBinding({instanceId:diagnostics.page.instanceId,target:diagnostics.page})}:{},...routing?{routing:{...routing.browser?{browser:text2(routing.browser,1024)}:{},...routing.session?{session:text2(routing.session)}:{},...routing.connector?{connector:text2(routing.connector)}:{},...routing.local!==void 0?{local:routing.local}:{},...routing.transport?{transport:routing.transport}:{}}}:{},...execution?.executionTimeoutMs?{executionTimeoutMs:execution.executionTimeoutMs}:{},executor:{state,observedAt,...owner?{pid:owner.pid}:{},...stopped?{stoppedAt:stopped}:{}},...task.error?{failure:diagnosticFailure(task.error,options)}:{},...task.checkpoint?{checkpoint:{sequence:task.checkpoint.sequence,version:task.checkpoint.version,schemaHash:task.checkpoint.schemaHash,updatedAt:task.checkpoint.updatedAt}}:{},...task.result?{result:{bytes:task.result.bytes,chunks:task.result.chunks,sha256:task.result.sha256}}:{},...task.kind==="model"?{model:modelProjection(record2,options)}:{},metadataIncomplete:!diagnostics||!!diagnostics.updatesDropped||task.kind==="model"&&!diagnostics.model?.runtime,history:{firstRetainedSequence:first,gap:first>1,omitted:Math.max(0,events.length-8),events:events.slice(-8).map(event=>({sequence:event.sequence,time:event.time,state:event.state,type:event.type}))}}}function buildDiagnosticReport(host,scope,options,scan,snapshots){let records=scan.records.filter(record2=>(!scope.plugin||record2.task.plugin===scope.plugin)&&(scope.access!=="toolbox"||record2.access!=="public")&&(!options.plugin||record2.task.plugin===options.plugin)&&(!options.instanceId||record2.diagnostics?.page?.instanceId===options.instanceId)),visible=new Map(records.map(record2=>[record2.task.taskId,record2])),selected=records.sort((a,b)=>b.task.createdAt-a.task.createdAt||a.task.taskId.localeCompare(b.task.taskId));if(options.taskId){if(!visible.has(options.taskId))throw Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"});let ids=new Set([options.taskId]),pending=[options.taskId];for(;pending.length;){let id=pending.shift(),item=visible.get(id),candidates=[item.task.parentTaskId,item.task.resumedFrom?.taskId,...records.filter(record2=>record2.task.parentTaskId===id||record2.task.resumedFrom?.taskId===id).map(record2=>record2.task.taskId)];for(let candidate of candidates)candidate&&visible.has(candidate)&&!ids.has(candidate)&&(ids.add(candidate),pending.push(candidate))}selected=[...ids].map(id=>visible.get(id))}let generatedAt=Date.now(),tasks=selected.slice(0,128).map(record2=>taskProjection(record2,options,generatedAt)),pages=snapshots.filter(page=>(!scope.plugin||page.plugin===scope.plugin)&&(!options.plugin||page.plugin===options.plugin)&&(!options.instanceId||page.binding.instanceId===options.instanceId)&&(!options.taskId||tasks.some(task=>task.page?.instanceId===page.binding.instanceId)));for(let task of tasks)task.page&&!pages.some(page=>page.binding.instanceId===task.page.instanceId)&&pages.push({plugin:task.plugin,installationId:task.installationId,revision:task.revision,host:task.host,binding:task.page,observation:"historical-binding"});let report={version:1,generatedAt,host:{hostId:host.hostId,epoch:host.epoch},protocolVersion:5,selection:{...options.taskId?{taskId:options.taskId}:{},...options.plugin?{plugin:options.plugin}:{},...options.instanceId?{instanceId:options.instanceId}:{}},coverage:{scanLimited:scan.limited,tasksOmitted:selected.length-tasks.length,pagesOmitted:Math.max(0,pages.length-64),byteLimited:!1},tasks,pages:pages.slice(0,64),links:[]},links=()=>{let retained=new Set(report.tasks.map(task=>task.taskId));report.links=report.tasks.flatMap(task=>{let record2=visible.get(task.taskId);return[["parent",record2.task.parentTaskId],["resume",record2.task.resumedFrom?.taskId]].flatMap(([kind,from])=>from&&retained.has(from)?[{from,to:task.taskId,kind}]:[])})};for(links();Buffer.byteLength(JSON.stringify(report))>MAX_PLUGIN_DIAGNOSTIC_BYTES;)report.coverage.byteLimited=!0,report.pages.length?(report.pages.pop(),report.coverage.pagesOmitted++):(report.tasks.pop(),report.coverage.tasksOmitted++,links());return report}init_pluginModelDefinition();init_pluginRecoveryDefinition();init_pluginExecution2();init_pluginExecutor();init_pluginExecutorProtocol();import{createHash as createHash10,randomUUID as randomUUID12}from"node:crypto";import{EventEmitter}from"node:events";import{isAbsolute as isAbsolute7,join as join17,relative as relative5,sep as sep4}from"node:path";import{realpathSync as realpathSync4,statSync as statSync10}from"node:fs";init_dist();init_pluginHostPaths();init_skillManifest();init_pluginRegistry();import{createHash as createHash5,randomUUID as randomUUID4}from"node:crypto";import{existsSync as existsSync4,mkdirSync as mkdirSync4,readFileSync as readFileSync8,readdirSync as readdirSync5,realpathSync as realpathSync2,renameSync as renameSync5,rmSync as rmSync5,statSync as statSync6,writeFileSync as writeFileSync4}from"node:fs";import{basename as basename3,dirname as dirname4,isAbsolute as isAbsolute3,join as join9,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";var MAX_REVISION_BYTES=64*1024*1024;function within(root,file){let path7=relative2(root,file);return path7===""||!path7.startsWith(`..${sep2}`)&&path7!==".."&&!isAbsolute3(path7)}function sourceRoot(entry){let candidate=dirname4(entry);for(let depth=0;depth<6;depth++){if(skillManifestPath(candidate))return candidate;let parent=dirname4(candidate);if(parent===candidate)break;candidate=parent}return basename3(dirname4(entry))==="scripts"?dirname4(dirname4(entry)):dirname4(entry)}function readSources(root){let files=[],registry=realpathSync2(pluginHostPaths().registry),bytes=0,visit=(directory,ancestors)=>{let real=realpathSync2(directory);if(!within(root,real)||ancestors.has(real))throw new Error("Plugin snapshot has an external or cyclic directory link");let next=new Set([...ancestors,real]);for(let item of readdirSync5(directory,{withFileTypes:!0}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0)){if([".git","__pycache__","node_modules",".DS_Store"].includes(item.name))continue;let file=join9(directory,item.name);if(within(root,registry)&&within(registry,file))continue;let target=realpathSync2(file);if(!within(root,target))throw new Error(`Plugin snapshot resource leaves the Skill directory: ${file}`);let stat2=statSync6(file);if(stat2.isDirectory()){visit(file,next);continue}if(!stat2.isFile())throw new Error(`Unsupported plugin resource: ${file}`);if(bytes+=stat2.size,bytes>MAX_REVISION_BYTES||files.length>=1e4)throw new Error("Plugin source snapshot exceeds 64 MiB or 10000 files");let content=readFileSync8(file);if(bytes+=content.length-stat2.size,bytes>MAX_REVISION_BYTES)throw new Error("Plugin source snapshot exceeds 64 MiB");files.push({path:relative2(root,file).split(sep2).join("/"),hash:createHash5("sha256").update(content).digest("hex"),bytes:content,executable:(stat2.mode&73)!==0})}};return visit(root,new Set),files}function fingerprint(files,entry){return createHash5("sha256").update(JSON.stringify({entry,files:files.map(file=>[file.path,file.hash,file.executable])})).digest("hex")}function capturePluginRevision(plugin){let registration=findPluginRegistration(plugin);if(!registration)throw new PluginError("PLUGIN_NOT_REGISTERED",`插件未注册: ${plugin}`);let entry=realpathSync2(registration.entry),root=realpathSync2(sourceRoot(entry)),paths=pluginHostPaths();mkdirSync4(paths.installations,{recursive:!0,mode:448});let identityFile=join9(paths.installations,`${plugin}.json`),installation=readRecord(identityFile);if(!installation||installation.root!==root){let proposed={pid:process.pid,root,installationId:randomUUID4()};installation?writeRecord(identityFile,proposed):claimRecord(identityFile,proposed),installation=readRecord(identityFile)}if(!installation||installation.root!==root)throw new Error("Plugin installation changed during capture");let relativeEntry=relative2(root,entry).split(sep2).join("/"),files=readSources(root),revision=fingerprint(files,relativeEntry),revisionRoot=join9(paths.revisions,installation.installationId,revision);if(!existsSync4(revisionRoot)){let temporary=`${revisionRoot}.${randomUUID4()}.tmp`;try{mkdirSync4(temporary,{recursive:!0,mode:448});for(let file of files){let destination=resolve3(temporary,file.path);mkdirSync4(dirname4(destination),{recursive:!0,mode:448}),writeFileSync4(destination,file.bytes,{flag:"wx",mode:file.executable?365:292})}if(fingerprint(readSources(root),relativeEntry)!==revision)throw new PluginError("PLUGIN_SOURCE_CHANGED","插件源码在创建快照时发生变化");mkdirSync4(dirname4(revisionRoot),{recursive:!0,mode:448}),renameSync5(temporary,revisionRoot)}finally{rmSync5(temporary,{recursive:!0,force:!0})}}return{plugin,installationId:installation.installationId,revision,originalRoot:root,entry:join9(revisionRoot,relativeEntry),registration:{...registration,entry:join9(revisionRoot,relativeEntry),source:void 0}}}function prunePluginRevisions(references){let directory=pluginHostPaths().revisions;if(existsSync4(directory))for(let installation of readdirSync5(directory,{withFileTypes:!0})){if(!installation.isDirectory())continue;let root=join9(directory,installation.name);for(let revision of readdirSync5(root,{withFileTypes:!0}))revision.isDirectory()&&!references.has(`${installation.name}/${revision.name}`)&&rmSync5(join9(root,revision.name),{recursive:!0,force:!0});readdirSync5(root).length||rmSync5(root,{recursive:!0,force:!0})}}function restorePluginRevision(plugin,installationId,revision,entry){if(!/^[a-f0-9-]{36}$/.test(installationId)||!/^[a-f0-9]{64}$/.test(revision))throw new Error("Invalid recovery revision");let paths=pluginHostPaths(),registration=findPluginRegistration(plugin),installation=readRecord(join9(paths.installations,`${plugin}.json`));if(!registration||!installation||installation.installationId!==installationId||sourceRoot(realpathSync2(registration.entry))!==installation.root)throw new PluginError("PLUGIN_TASK_INSTALLATION_CHANGED","Task installation was removed or replaced");try{let root=realpathSync2(join9(paths.revisions,installationId,revision)),restoredEntry=resolve3(root,entry);if(!entry||isAbsolute3(entry)||!within(root,restoredEntry)||!within(root,realpathSync2(restoredEntry))||fingerprint(readSources(root),entry)!==revision)throw new Error("Snapshot identity changed");return{plugin,installationId,revision,originalRoot:installation.root,entry:restoredEntry,registration:{...registration,entry:restoredEntry,source:void 0}}}catch{throw new PluginError("PLUGIN_TASK_REVISION_UNAVAILABLE","Task source snapshot is missing or has changed")}}init_pluginHostPaths();init_pluginTaskStore();init_dist2();init_unified();init_commands();function error(code,message){return Object.assign(new Error(message),{code})}function digest(value){return createHash10("sha256").update(JSON.stringify(value,(_key,item)=>item&&typeof item=="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a<b?-1:a>b?1:0)):item)).digest("hex")}function revisionEntry(revision){return relative5(realpathSync4(join17(pluginHostPaths().revisions,revision.installationId,revision.revision)),realpathSync4(revision.entry)).split(sep4).join("/")}var PluginTaskManager=class{constructor(configuration={},services){this.configuration=configuration;this.services=services;this.store=configuration.store??new PluginTaskStore,this.store.recover(this.host.epoch),this.changes.setMaxListeners(0);let concurrency=configuration.concurrency??4;if(!Number.isInteger(configuration.modelConcurrency??2)||(configuration.modelConcurrency??2)<1||(configuration.modelConcurrency??2)>8)throw new Error("Invalid model concurrency");if(!Number.isInteger(concurrency)||concurrency<1||concurrency>32)throw new Error("Invalid plugin task concurrency");let prune=()=>{this.store.prune(),prunePluginRevisions(new Set([...this.revisionPins.keys(),...this.store.list().map(record2=>`${record2.task.installationId}/${record2.task.revision}`)]))};prune(),this.maintenance=setInterval(()=>{try{prune()}catch(error2){console.error("Plugin task retention failed:",error2)}},3600*1e3),this.maintenance.unref()}configuration;services;host=localPluginExecutionHost();store;changes=new EventEmitter;queue=new Map;running=new Map;resuming=new Map;activeChildren=new Map;closed=!1;maintenance;descriptionsRunning=0;descriptions=new Map;descriptionBytes=0;revisionPins=new Map;recoveries=new Map;pinRevision(revision){let key2=`${revision.installationId}/${revision.revision}`;this.revisionPins.set(key2,(this.revisionPins.get(key2)??0)+1);let released=!1;return()=>{if(released)return;released=!0;let count=this.revisionPins.get(key2)??0;count>1?this.revisionPins.set(key2,count-1):this.revisionPins.delete(key2)}}async describeRevision(revision,signal,options={}){if(signal.throwIfAborted(),this.closed)throw new Error("Plugin description budget is exhausted");let key2=`${revision.installationId}/${revision.revision}`,cached=options.cache?this.descriptions.get(key2):void 0;if(cached)return this.descriptions.delete(key2),this.descriptions.set(key2,cached),structuredClone(cached.value);if(this.descriptionsRunning>=8)throw new Error("Plugin description budget is exhausted");this.descriptionsRunning++;try{let value=await(this.configuration.execute??executeRegisteredPlugin)(revision.plugin,{command:"describe",input:{}},{invoke:async()=>{throw new Error("Plugin declarations cannot invoke host actions")}},{describe:!0,signal,source:"runtime",executionTimeoutMs:1e4,workerPath:this.configuration.workerPath},{registration:revision.registration});signal.throwIfAborted();let bytes=Buffer.byteLength(JSON.stringify(value));if(options.cache&&!this.closed&&bytes<=8*1024*1024){let previous=this.descriptions.get(key2);for(previous&&(this.descriptions.delete(key2),this.descriptionBytes-=previous.bytes);this.descriptions.size>=64||this.descriptionBytes+bytes>8*1024*1024;){let oldest=this.descriptions.keys().next().value;this.descriptionBytes-=this.descriptions.get(oldest).bytes,this.descriptions.delete(oldest)}this.descriptions.set(key2,{value:structuredClone(value),bytes}),this.descriptionBytes+=bytes}return value}finally{this.descriptionsRunning--}}authorize(taskId,scope){if(!taskId.startsWith(`pt_${this.host.hostId}_`))throw error("PLUGIN_TASK_WRONG_HOST","Plugin task belongs to another execution host");let record2=this.store.read(taskId);if(scope.plugin&&record2.task.plugin!==scope.plugin||scope.access==="toolbox"&&record2.access==="public")throw error("PLUGIN_TASK_NOT_FOUND","Plugin task was not found");return record2.task}get(taskId,scope){return this.authorize(taskId,scope)}list(scope,activeOnly=!1,cursor,limit=100){if(!Number.isSafeInteger(limit)||limit<1||limit>200||cursor!==void 0&&typeof cursor!="string")throw new Error("Invalid plugin task list page");let candidates=(activeOnly?this.store.listActive():this.store.list()).filter(record2=>scope.access!=="toolbox"||record2.access!=="public").map(record2=>record2.task).filter(task=>(!scope.plugin||task.plugin===scope.plugin)&&(!activeOnly||isPluginTaskActive(task.state))).sort((a,b)=>b.createdAt-a.createdAt||b.taskId.localeCompare(a.taskId)),match=cursor?.match(/^(\d+):(pt_[0-9a-f-]{36}_[0-9a-f-]{36})$/i);if(cursor!==void 0&&(!match||!Number.isSafeInteger(Number(match[1]))))throw new Error("Invalid plugin task list cursor");let remaining=match?candidates.filter(task=>task.createdAt<Number(match[1])||task.createdAt===Number(match[1])&&task.taskId.localeCompare(match[2])<0):candidates,tasks=[],bytes=0;for(let task of remaining){let size=Buffer.byteLength(JSON.stringify(task));if(tasks.length&&(tasks.length>=limit||bytes+size>384*1024))break;tasks.push(task),bytes+=size}let last=tasks.at(-1);return{tasks,...last&&tasks.length<remaining.length?{nextCursor:`${last.createdAt}:${last.taskId}`}:{}}}start(request,bridge,binding=void 0){if(this.closed)throw error("PLUGIN_TASK_HOST_STOPPING","Plugin execution service is stopping");if(request.kind!==void 0&&!["command","model"].includes(request.kind))throw new Error("Invalid task kind");if(request.kind==="model"){let model=normalizePluginModel(request.input?.request);request={...request,command:"model",input:{request:model},executionTimeoutMs:request.executionTimeoutMs??12e4}}if(!/^[a-z][a-z0-9_-]*$/.test(request.plugin)||!/^[a-z][a-z0-9-]*$/.test(request.command))throw new Error("Invalid plugin task command");if(bridge.scope.plugin&&request.plugin!==bridge.scope.plugin)throw error("PLUGIN_COMMAND_NOT_ALLOWED","Plugin task is outside the caller scope");if(!request.input||typeof request.input!="object"||Array.isArray(request.input)||Buffer.byteLength(JSON.stringify(request.input))>256*1024)throw new Error("Plugin task input must be an object within 256 KiB");if(!isAbsolute7(request.cwd)||!statSync10(request.cwd).isDirectory())throw new Error("Plugin task cwd must be an absolute directory");if(!request.environment||typeof request.environment!="object"||Array.isArray(request.environment)||Object.entries(request.environment).some(([key2,value])=>!key2||key2.includes("=")||typeof value!="string"||key2.includes("\0")||value.includes("\0"))||Buffer.byteLength(JSON.stringify(request.environment))>512*1024)throw new Error("Invalid plugin task environment");if(!request.options||typeof request.options!="object"||Array.isArray(request.options)||Object.keys(request.options).some(key2=>!["browser","session","connector","local","transport","timeoutSec"].includes(key2)))throw new Error("Invalid plugin task routing options");for(let key2 of["browser","session","connector"])if(request.options[key2]!==void 0&&(typeof request.options[key2]!="string"||!request.options[key2]))throw new Error("Invalid plugin task target");if(request.options.timeoutSec!==void 0&&(!Number.isFinite(request.options.timeoutSec)||request.options.timeoutSec<=0))throw new Error("Invalid plugin task invocation timeout");if(request.options.local!==void 0&&typeof request.options.local!="boolean")throw new Error("Invalid plugin task local routing option");if(request.options.transport!==void 0&&!["extension","cdp"].includes(request.options.transport))throw new Error("Invalid plugin task transport");if(bridge.scope.bridge==="service"&&request.options.browser&&!decodeBrowserTarget(request.options.browser))throw error("PLUGIN_TASK_TARGET_REQUIRED","Background tasks require a stable global browser ID");if(request.executionTimeoutMs!==void 0&&(!Number.isSafeInteger(request.executionTimeoutMs)||request.executionTimeoutMs<1||request.executionTimeoutMs>2147483647))throw new Error("Invalid plugin task execution deadline");if(request.idempotencyKey!==void 0&&(typeof request.idempotencyKey!="string"||!request.idempotencyKey||request.idempotencyKey.length>128))throw new Error("Invalid plugin task idempotency key");let revision=binding?.revision??(this.configuration.captureRevision??capturePluginRevision)(request.plugin);if(bridge.scope.access==="runtime"&&!binding)throw new Error("Runtime task requires a document binding");if(request.kind!=="model"&&bridge.scope.access==="toolbox"&&!revision.registration.toolbox?.page.commands.includes(request.command))throw error("PLUGIN_COMMAND_NOT_ALLOWED","Tool page cannot invoke this plugin command");request={...request,cwd:realpathSync4(request.cwd),input:JSON.parse(JSON.stringify(request.input))};let requestHash=binding?.recoveryRequestHash??digest([request.kind??"command",request.command,request.input,request.cwd,request.options,request.executionTimeoutMs,revision.revision,binding?.recovery,Object.entries(request.environment).sort(([a],[b])=>a<b?-1:a>b?1:0)]),dedupeKey=binding?.recovery?`resume:${binding.recovery.fromTaskId}`:request.idempotencyKey?`explicit:${revision.installationId}:${bridge.scope.access}:${request.idempotencyKey}`:bridge.scope.access==="toolbox"?`active:${digest(bridge.scope.scopeId??bridge.id)}:${revision.installationId}:${requestHash}`:void 0;if(dedupeKey){let existing=this.store.findDedupe(dedupeKey,request.idempotencyKey===void 0&&binding?.recovery===void 0);if(existing){if(existing.requestHash!==requestHash)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","Idempotency key refers to a different plugin task request");return{taskId:existing.task.taskId,state:existing.task.state,host:existing.task.host,reused:!0}}}if([...this.queue.values()].filter(item=>(item.request.kind??"command")===(request.kind??"command")).length>=128)throw error("PLUGIN_TASK_QUEUE_FULL","Plugin task queue is full");let now=Date.now(),task={taskId:`pt_${this.host.hostId}_${randomUUID12()}`,host:this.host,plugin:request.plugin,installationId:revision.installationId,revision:revision.revision,command:request.command,kind:request.kind??"command",...binding?.parentTaskId?{parentTaskId:binding.parentTaskId}:{},...binding?.recovery?{resumedFrom:{taskId:binding.recovery.fromTaskId,revision:binding.recovery.fromRevision,checkpointSequence:binding.recovery.sourceCheckpoint.sequence,checkpointVersion:binding.recovery.sourceCheckpoint.version},checkpoint:{sequence:0,version:binding.recovery.checkpoint.version,schemaHash:binding.recovery.checkpoint.schemaHash,updatedAt:now}}:{},input:request.input,source:bridge.scope.source,cwd:request.cwd,state:"queued",sequence:0,createdAt:now,updatedAt:now};if(this.store.write({task,events:[],diagnostics:{executorAttempted:!1,...binding?.page?{page:diagnosticBinding({instanceId:binding.page.instanceId,target:binding.page.target})}:{}},access:bridge.scope.access,...dedupeKey?{dedupeKey}:{},requestHash,execution:{entry:revisionEntry(revision),options:JSON.parse(JSON.stringify(request.options)),bridge:bridge.scope.bridge,executionTimeoutMs:request.executionTimeoutMs},...binding?.recovery?{checkpoint:{...structuredClone(binding.recovery.checkpoint),sequence:0,updatedAt:now}}:{}}),this.update(task.taskId,{state:"queued"}),task.parentTaskId){let children=this.activeChildren.get(task.parentTaskId)??new Set;children.add(task.taskId),this.activeChildren.set(task.parentTaskId,children)}return this.queue.set(task.taskId,{request,revision,bridge,controller:new AbortController,guard:binding?.guard,page:binding?.page,recovery:binding?.recovery,parentIdentity:binding?.parentIdentity,documentTarget:binding?.documentTarget}),queueMicrotask(()=>this.drain()),{taskId:task.taskId,state:"queued",host:this.host}}checkpoint(taskId,scope){return this.authorize(taskId,scope),this.store.read(taskId).checkpoint??null}resume(request,bridge){try{if(this.closed)throw error("PLUGIN_TASK_HOST_STOPPING","Plugin execution service is stopping");if(this.authorize(request.taskId,bridge.scope),bridge.scope.access!=="public"||bridge.scope.bridge!=="service")throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery requires public service-owned routing");if(request.revision!==void 0&&!["original","current"].includes(request.revision))throw new Error("Recovery revision must be original or current");if(!request.environment||typeof request.environment!="object"||Array.isArray(request.environment)||Object.entries(request.environment).some(([key2,value])=>!key2||key2.includes("=")||typeof value!="string"||key2.includes("\0")||value.includes("\0"))||Buffer.byteLength(JSON.stringify(request.environment))>512*1024)throw new Error("Invalid plugin task environment");let intent=digest([request.revision??"original",request.environment]),existing=this.recoveries.get(request.taskId);if(existing){if(existing.intent!==intent)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","A different recovery request is already in progress");return existing.promise.then(result=>({...result,reused:!0}))}let controller=new AbortController,operation={controller,intent,promise:this.resumeAttempt(request,bridge,controller.signal)};return this.recoveries.set(request.taskId,operation),operation.promise.finally(()=>this.recoveries.delete(request.taskId)).catch(()=>{}),operation.promise}catch(cause){return Promise.reject(cause)}}async resumeAttempt(request,bridge,signal){let task=this.authorize(request.taskId,bridge.scope),record2=this.store.read(task.taskId);if(!["error","cancelled","interrupted"].includes(task.state)||task.kind==="model"||task.parentTaskId||record2.access!=="public"||record2.execution?.bridge!=="service"||!record2.checkpoint)throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Recovery requires a terminal root command with a checkpoint and service-owned routing");this.assertExecutionTreeStopped(task.taskId);let source=restorePluginRevision(task.plugin,task.installationId,task.revision,record2.execution.entry),revision=request.revision==="current"?(this.configuration.captureRevision??capturePluginRevision)(task.plugin):source;if(revision.installationId!==task.installationId)throw error("PLUGIN_TASK_INSTALLATION_CHANGED","Recovery cannot change the plugin installation");restorePluginRevision(task.plugin,task.installationId,revision.revision,revisionEntry(revision));let releaseSource=this.pinRevision(source),releaseTarget=this.pinRevision(revision);try{let requestHash=digest([request.revision??"original",task,record2.checkpoint,record2.execution,revision.revision,request.environment]),existing=this.store.findDedupe(`resume:${task.taskId}`);if(existing){if(existing.requestHash!==requestHash)throw error("PLUGIN_TASK_IDEMPOTENCY_CONFLICT","Source task already has a different recovery attempt");return{taskId:existing.task.taskId,state:existing.task.state,host:existing.task.host,reused:!0}}let sourceCommands=(await this.describeRevision(source,signal)).taskRecovery?.commands,sourceDefinition=sourceCommands&&Object.hasOwn(sourceCommands,task.command)?sourceCommands[task.command]:void 0;if(signal.throwIfAborted(),!sourceDefinition||sourceDefinition.checkpointVersion!==record2.checkpoint.version||digest(sourceDefinition.schema)!==record2.checkpoint.schemaHash)throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Checkpoint does not match the retained recovery declaration");let checkpoint=structuredClone(record2.checkpoint),declarationHash=pluginRecoverySignature(sourceDefinition);if(revision.revision!==source.revision){let targetCommands=(await this.describeRevision(revision,signal)).taskRecovery?.commands,target=targetCommands&&Object.hasOwn(targetCommands,task.command)?targetCommands[task.command]:void 0;if(signal.throwIfAborted(),!target)throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Target revision does not declare recovery for the original command");if(declarationHash=pluginRecoverySignature(target),target.checkpointVersion===checkpoint.version){if(digest(target.schema)!==digest(sourceDefinition.schema))throw error("PLUGIN_CHECKPOINT_MIGRATION_UNSUPPORTED","Checkpoint schema changed without a version increment")}else{if(!target.migrateFrom?.some(from=>from.version===checkpoint.version&&digest(from.schema)===digest(sourceDefinition.schema)))throw error("PLUGIN_CHECKPOINT_MIGRATION_UNSUPPORTED","Target revision does not declare this checkpoint format");if(this.descriptionsRunning>=8)throw error("PLUGIN_CHECKPOINT_MIGRATION_BUSY","Checkpoint migration budget is exhausted");this.descriptionsRunning++;let result;try{result=await(this.configuration.execute??executeRegisteredPlugin)(revision.plugin,{command:task.command,input:{checkpoint,fromRevision:source.revision,toRevision:revision.revision}},{invoke:async()=>{throw error("PLUGIN_CHECKPOINT_MIGRATION_HOST_CALL","Checkpoint migration cannot invoke host actions")}},{migration:!0,expectedRecovery:declarationHash,signal,source:"runtime",cwd:task.cwd,environment:request.environment,executionTimeoutMs:1e4,workerPath:this.configuration.workerPath},{registration:revision.registration})}finally{this.descriptionsRunning--}signal.throwIfAborted();let json2=JSON.stringify(result);if(json2===void 0||Buffer.byteLength(json2)>64*1024)throw error("PLUGIN_TASK_CHECKPOINT_INVALID","Migrated checkpoint must be JSON within 64 KiB");checkpoint={...checkpoint,version:target.checkpointVersion,schemaHash:digest(target.schema),data:JSON.parse(json2)}}}return signal.throwIfAborted(),restorePluginRevision(task.plugin,task.installationId,task.revision,record2.execution.entry),restorePluginRevision(task.plugin,task.installationId,revision.revision,revisionEntry(revision)),this.assertExecutionTreeStopped(task.taskId),this.start({plugin:task.plugin,command:task.command,input:task.input,cwd:task.cwd,environment:request.environment,options:record2.execution.options,executionTimeoutMs:record2.execution.executionTimeoutMs},bridge,{revision,recoveryRequestHash:requestHash,recovery:{fromTaskId:task.taskId,fromRevision:source.revision,declarationHash,sourceCheckpoint:{sequence:record2.checkpoint.sequence,version:record2.checkpoint.version,schemaHash:record2.checkpoint.schemaHash,updatedAt:record2.checkpoint.updatedAt},checkpoint}})}finally{releaseTarget(),releaseSource()}}assertExecutionTreeStopped(taskId){let records=this.store.list(),visited=new Set,pending=[taskId];for(;pending.length;){let id=pending.pop();if(visited.has(id))continue;visited.add(id);let record2=records.find(record3=>record3.task.taskId===id);if(!record2)throw error("PLUGIN_TASK_EXECUTION_STILL_ACTIVE","Previous execution ownership record is unavailable");if(pending.push(...records.filter(record3=>record3.task.parentTaskId===id).map(record3=>record3.task.taskId)),isPluginTaskActive(record2.task.state)||pluginTaskExecutionUnconfirmed(record2))throw error("PLUGIN_TASK_EXECUTION_STILL_ACTIVE","Previous execution or descendant cleanup cannot be confirmed")}}cancel(taskId,scope){let task=this.authorize(taskId,scope);if(task.state==="queued")return this.queue.delete(taskId),this.update(taskId,{state:"cancelled",error:{code:"PLUGIN_EXECUTION_CANCELLED",message:"Plugin task cancelled before execution"}});if(task.state==="running"){let updated=this.update(taskId,{state:"cancelling"});return this.running.get(taskId)?.controller.abort(),updated}return task}async events(taskId,scope,cursor,waitMs=0,signal){let task=this.authorize(taskId,scope);if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25e3)throw new Error("Invalid plugin task event wait");let current=this.store.events(taskId,cursor);return waitMs&&cursor===task.sequence&&isPluginTaskActive(task.state)?(await new Promise((resolve7,reject)=>{let finish=()=>{cleanup(),resolve7()},abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin task subscription closed"))},timer=setTimeout(finish,waitMs),cleanup=()=>{clearTimeout(timer),this.changes.off(taskId,finish),signal?.removeEventListener("abort",abort)};this.changes.once(taskId,finish),signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted?abort():this.store.read(taskId).task.sequence!==cursor&&finish()}),this.store.events(taskId,cursor)):current}resultChunk(taskId,scope,index){return this.authorize(taskId,scope),this.store.resultChunk(taskId,index)}update(taskId,update,type="state"){let task=this.store.update(taskId,update,type);if(!isPluginTaskActive(task.state)&&task.parentTaskId){let children=this.activeChildren.get(task.parentTaskId);children?.delete(taskId),children?.size||this.activeChildren.delete(task.parentTaskId)}return this.changes.emit(taskId),task}drain(){if(!this.closed){for(let[taskId,resume]of this.resuming){let parent=this.running.get(taskId);if(!parent){this.resuming.delete(taskId),resume();continue}let limit=parent.kind==="model"?this.configuration.modelConcurrency??2:this.configuration.concurrency??4;[...this.running.values()].filter(item=>item.kind===parent.kind&&!item.waiting).length<limit&&(this.resuming.delete(taskId),resume())}for(let[taskId,pending]of this.queue){let kind=pending.request.kind??"command",limit=kind==="model"?this.configuration.modelConcurrency??2:this.configuration.concurrency??4;if([...this.running.values()].filter(item=>item.kind===kind&&!item.waiting).length>=limit)continue;this.queue.delete(taskId),this.update(taskId,{state:"running"});let completed=this.execute(taskId,pending).finally(()=>{this.running.delete(taskId),this.drain()});this.running.set(taskId,{controller:pending.controller,completed,kind,waiting:0})}}}async execute(taskId,{request,revision,bridge,controller,guard,page,recovery,parentIdentity,documentTarget}){let client=bridge.scope.bridge==="service"?new UnifiedClient:void 0;try{await guard?.();let identity=Object.freeze({...createPluginInvocationIdentity(request.plugin,bridge.scope.source,parentIdentity),taskId,installationId:revision.installationId,revision:revision.revision,...page?{page}:{},...recovery?{recovery}:{}});{let record2=this.store.read(taskId);record2.diagnostics={...record2.diagnostics,invocationId:identity.invocationId,executorAttempted:!0},this.store.write(record2)}let restrictedTarget=page?.target??documentTarget,diagnosticUpdates=0,recoveryDescription,modelOwner=page?.instanceId??parentIdentity?.taskId,conversation=request.kind==="model"&&request.input.request.conversation;if(conversation&&!modelOwner)throw error("PLUGIN_MODEL_CONVERSATION_SCOPE","Model conversations require a bound document or calling command");let result=await(this.configuration.execute??(conversation&&this.services?.model?this.services.model.bind(this.services,modelOwner):executeRegisteredPlugin))(request.plugin,{command:request.command,input:request.input},{invocation:identity,source:bridge.scope.source,invoke:async(action,payload={},options={},onProgress)=>{if(controller.signal.throwIfAborted(),await guard?.(),controller.signal.throwIfAborted(),action==="plugin_invoke_child"){let name=payload.plugin,invocation=payload.invocation;if(typeof name!="string"||!invocation||typeof invocation.command!="string"||!invocation.input||typeof invocation.input!="object"||Array.isArray(invocation.input))throw new Error("Invalid nested plugin invocation");this.assertRouting(options,request.options);let ancestor=taskId,depth=0;for(;ancestor;){let task=this.store.read(ancestor).task;if(task.plugin===name)throw error("PLUGIN_INVOCATION_CYCLE","Plugin invocation forms a cycle");if(++depth>=16)throw error("PLUGIN_INVOCATION_DEPTH","Plugin invocation depth exceeds 16");ancestor=task.parentTaskId}this.assertChildBudget(taskId);let childRevision=(this.configuration.captureRevision??capturePluginRevision)(name),childBridge={...bridge,scope:{...bridge.scope,access:"public",plugin:name}},child=this.start({...request,plugin:name,kind:"command",command:invocation.command,input:invocation.input,options:{...request.options,...options},idempotencyKey:void 0},childBridge,{revision:childRevision,guard,parentTaskId:taskId,parentIdentity:identity,documentTarget:restrictedTarget});return this.awaitChild(taskId,child.taskId,childBridge.scope,controller.signal)}if(["plugin_state","plugin_model","plugin_page","plugin_task_checkpoint"].includes(action)&&payload.plugin!==request.plugin)throw error("PLUGIN_CALLER_SCOPE_MISMATCH","Plugin-owned services require the executing plugin identity");if(action==="plugin_task_checkpoint"){if(request.kind==="model"||page||bridge.scope.access!=="public"||bridge.scope.bridge!=="service")throw error("PLUGIN_TASK_RECOVERY_UNAVAILABLE","Checkpoints require a command with service-owned routing");let json2=JSON.stringify(payload.data);if(!Number.isSafeInteger(payload.expectedSequence)||payload.expectedSequence<0||json2===void 0||Buffer.byteLength(json2)>64*1024)throw new Error("Checkpoint must have a CAS sequence and fit within 64 KiB");let data=JSON.parse(json2),commands=(await(recoveryDescription??=this.describeRevision(revision,controller.signal))).taskRecovery?.commands,declaration=commands&&Object.hasOwn(commands,request.command)?commands[request.command]:void 0;if(controller.signal.throwIfAborted(),declaration&&payload.expectedDeclaration!==pluginRecoverySignature(declaration))throw error("PLUGIN_RECOVERY_DECLARATION_CHANGED","Checkpoint declaration differs from the executing command");if(!declaration)throw error("PLUGIN_TASK_CHECKPOINT_INVALID","Checkpoint is undeclared");let current=this.store.read(taskId);if(current.task.state!=="running"||payload.expectedSequence!==(current.checkpoint?.sequence??0))throw error("PLUGIN_TASK_CHECKPOINT_CONFLICT","Checkpoint sequence or execution state changed");let checkpoint={data,version:declaration.checkpointVersion,schemaHash:digest(declaration.schema),sequence:payload.expectedSequence+1,updatedAt:Date.now()};return this.store.update(taskId,{checkpoint:{sequence:checkpoint.sequence,version:checkpoint.version,schemaHash:checkpoint.schemaHash,updatedAt:checkpoint.updatedAt}},"checkpoint",{checkpoint}),this.changes.emit(taskId),checkpoint}if(action==="plugin_state"){if(page&&payload.instanceId!==void 0&&payload.instanceId!==page.instanceId)throw error("PLUGIN_PAGE_TARGET_CHANGED","State access cannot change the bound page");if(!this.services)throw new Error("Plugin host services are unavailable");return this.services.state(request.plugin,{...payload,...page?{instanceId:page.instanceId}:{}},bridge,request.options,{revision,signal:controller.signal,expectedTarget:restrictedTarget})}if(action==="plugin_model"){if(payload.operation==="capabilities")return pluginModelCapabilities();if(payload.operation==="list"){if(!this.services)throw new Error("Plugin host services are unavailable");return this.services.listModels(payload.provider)}if(payload.operation!=="run")throw new Error("Plugin commands use model.run; detached model tasks require an explicit task entry");this.assertChildBudget(taskId);let model=normalizePluginModel(payload.request),started=this.start({...request,kind:"model",command:"model",input:{request:model},idempotencyKey:void 0},bridge,{revision,guard,page,parentTaskId:taskId,parentIdentity:identity,documentTarget:restrictedTarget});return this.awaitChild(taskId,started.taskId,bridge.scope,controller.signal,onProgress)}if(action==="plugin_page"){if(!this.services)throw new Error("Plugin host services are unavailable");if(page&&!(payload.operation==="activation"&&payload.enabled===void 0)&&(!["send","get","events"].includes(String(payload.operation))||payload.instanceId!==page.instanceId))throw error("PLUGIN_PAGE_TARGET_CHANGED","Runtime tasks can only access their bound document");return this.services.page(request.plugin,payload,bridge,request.options,{cwd:request.cwd,environment:request.environment,signal:controller.signal,revision,expectedTarget:restrictedTarget,parentIdentity:identity})}if(restrictedTarget&&!["send_request","browser_list","connector_list"].includes(action))throw error("PLUGIN_PAGE_TARGET_CHANGED","Runtime tasks must access the document through context.page");if(this.assertRouting(options,request.options),client){if(COMMAND_MAP.has(action)&&!["browser_list","connector_list","agent_chat_run"].includes(action)&&!request.options.browser)throw error("PLUGIN_TASK_TARGET_REQUIRED","Background browser tasks require an explicit browser target");return client.invoke(action,payload,{...request.options,...options})}return bridge.invoke(action,payload,{...request.options,...options})}},{...request.kind==="model"?{model:request.input.request}:{},recovery:recovery!==void 0,onDiagnostic:metadata=>{let record2=this.store.read(taskId);if(++diagnosticUpdates>64){record2.diagnostics?.updatesDropped||(record2.diagnostics={...record2.diagnostics,updatesDropped:!0},this.store.write(record2));return}let model=normalizeModelDiagnostic(metadata,record2.diagnostics?.model);JSON.stringify(model)!==JSON.stringify(record2.diagnostics?.model)&&(this.store.update(taskId,{},"diagnostic",{diagnostics:{...record2.diagnostics,model}}),this.changes.emit(taskId))},onExecutorStopped:()=>{let record2=this.store.read(taskId);record2.diagnostics={...record2.diagnostics,executorStoppedAt:Date.now()},this.store.write(record2)},onExecutorStarted:owner=>{let record2=this.store.read(taskId);record2.executorOwner=owner,this.store.write(record2)},...request.options,cwd:request.cwd,environment:request.environment,signal:controller.signal,source:bridge.scope.source,access:bridge.scope.access,executionTimeoutMs:request.executionTimeoutMs,workerPath:this.configuration.workerPath,onProgress:progress=>{if(Buffer.byteLength(JSON.stringify(progress))>64*1024)throw new Error("Plugin task progress exceeds 64 KiB");this.update(taskId,{progress},"progress")}},{registration:revision.registration});await guard?.(),request.kind==="model"&&(result=validatePluginModelResult(request.input.request,result)),await this.stopChildren(taskId),!page&&request.kind!=="model"&&await this.services?.releaseModels?.(taskId);let reference=this.store.saveResult(taskId,result);this.update(taskId,{state:"success",result:reference})}catch(cause){await this.stopChildren(taskId);let failureCause=cause;if(!page&&request.kind!=="model")try{await this.services?.releaseModels?.(taskId)}catch(cleanupError){failureCause=cleanupError}let failure2=serializePluginExecutionError(failureCause),interrupted=this.closed||failure2.code==="PLUGIN_TASK_BRIDGE_UNAVAILABLE";this.update(taskId,{state:interrupted?"interrupted":failure2.code==="PLUGIN_EXECUTION_CANCELLED"?"cancelled":"error",error:failure2})}finally{client?.disconnect()}}assertRouting(options,bound){if(Object.keys(options).some(key2=>!["browser","connector","session","local","transport","timeoutSec"].includes(key2)))throw error("PLUGIN_TASK_TARGET_CHANGED","Plugin task cannot override internal routing options");for(let key2 of["browser","connector","session","local","transport"])if(options[key2]!==void 0&&options[key2]!==bound[key2])throw error("PLUGIN_TASK_TARGET_CHANGED","Plugin task cannot change its bound browser routing")}assertChildBudget(parent){if(!this.running.get(parent)?.waiting&&[...this.running.values()].filter(item=>item.waiting).length>=32)throw error("PLUGIN_TASK_NESTING_BUDGET","Too many suspended plugin invocations")}async awaitChild(parent,child,scope,signal,onProgress){let running=this.running.get(parent);running&&running.waiting++,queueMicrotask(()=>this.drain());let cancel=()=>this.cancel(child,scope);signal.addEventListener("abort",cancel,{once:!0}),signal.aborted&&cancel();try{return await this.waitResult(child,scope,progress=>{progress!==void 0&&!signal.aborted&&onProgress?.(progress),isPluginTaskActive(this.store.read(parent).task.state)&&this.update(parent,{progress},"progress")})}finally{signal.removeEventListener("abort",cancel),running?.waiting===1&&!signal.aborted&&!this.closed?await new Promise(resolve7=>{let resume=()=>{this.resuming.delete(parent),signal.removeEventListener("abort",resume),running.waiting--,resolve7()};this.resuming.set(parent,resume),signal.addEventListener("abort",resume,{once:!0}),this.drain()}):running&&running.waiting--}}async stopChildren(taskId){let children=[...this.activeChildren.get(taskId)??[]];for(let child of children)this.cancel(child,{access:"public",source:"runtime",bridge:"service"});await Promise.allSettled(children.map(child=>this.running.get(child)?.completed))}async waitResult(taskId,scope,onProgress){let cursor=0;for(;;){let page=await this.events(taskId,scope,cursor,25e3);cursor=page.nextCursor;for(let event of page.events)event.type==="progress"&&onProgress?.(event.progress);if(page.task.state==="success"){let chunks=[];for(let index=0;index<page.task.result.chunks;index++)chunks.push(Buffer.from(this.resultChunk(taskId,scope,index).data,"base64"));let bytes=Buffer.concat(chunks);if(bytes.length!==page.task.result.bytes||createHash10("sha256").update(bytes).digest("hex")!==page.task.result.sha256)throw new Error("Model task result integrity check failed");return JSON.parse(bytes.toString("utf8")).value}if(!isPluginTaskActive(page.task.state))throw Object.assign(pluginExecutionError(page.task.error??{message:"Model task failed"}),{childTaskId:taskId})}}async close(){this.closed=!0,this.descriptions.clear(),this.descriptionBytes=0;for(let resume of[...this.resuming.values()])resume();for(let operation of this.recoveries.values())operation.controller.abort();clearInterval(this.maintenance),await Promise.allSettled([...this.recoveries.values()].map(operation=>operation.promise));for(let taskId of this.queue.keys())this.update(taskId,{state:"interrupted",error:{code:"PLUGIN_TASK_HOST_STOPPED",message:"Plugin execution service stopped"}});this.queue.clear();for(let{controller}of this.running.values())controller.abort();await Promise.allSettled([...[...this.running.values()].map(item=>item.completed)])}};init_pluginStateDefinition();init_pluginRegistry();init_pluginHostPaths();import{readFileSync as readFileSync15}from"node:fs";import{join as join19}from"node:path";init_pluginHostPaths();init_pluginHostFiles();import{createHash as createHash11}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync14,readdirSync as readdirSync7,statSync as statSync11,rmSync as rmSync13}from"node:fs";import{join as join18,sep as sep5}from"node:path";function fail2(code,message){throw Object.assign(new Error(message),{code})}function schemaHash(definition){return createHash11("sha256").update(JSON.stringify({schema:definition.schema,storage:definition.storage},(_key,value)=>value&&typeof value=="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0)):value)).digest("hex")}function key(value){(typeof value!="string"||!value.length||Buffer.byteLength(value)>512||["__proto__","constructor","prototype"].includes(value))&&fail2("PLUGIN_STATE_INVALID","Invalid state key")}var PluginStateStore=class{constructor(directory=pluginHostPaths().state,now=Date.now){this.directory=directory;this.now=now}directory;now;memory=new Map;memoryBytes=0;memoryRevisionFloor=0;clearMemory(){this.memory.clear(),this.memoryBytes=0,this.memoryRevisionFloor=0}valueBytes=new WeakMap;memorySize(document2){let bytes=Buffer.byteLength(JSON.stringify({...document2,entries:{}})),count=0;for(let[name,entry]of Object.entries(document2.entries)){let valueBytes=typeof entry.value=="object"&&entry.value!==null?this.valueBytes.get(entry.value):void 0;valueBytes===void 0&&(valueBytes=Buffer.byteLength(JSON.stringify(entry.value)),typeof entry.value=="object"&&entry.value!==null&&this.valueBytes.set(entry.value,valueBytes)),bytes+=Buffer.byteLength(JSON.stringify(name))+1+Buffer.byteLength(JSON.stringify({...entry,value:null}))-4+valueBytes+(count++?1:0)}return bytes}saveMemory(path7,document2,bytes=this.memorySize(document2)){let total=this.memoryBytes-(this.memory.get(path7)?.bytes??0)+bytes;(total>128*1024*1024||!this.memory.has(path7)&&this.memory.size>=512)&&fail2("PLUGIN_STATE_QUOTA","Memory state exceeds its host limits"),this.memory.set(path7,{document:document2,bytes}),this.memoryBytes=total}path(namespace){(!/^[a-f0-9-]{36}$/i.test(namespace.installationId)||!/^[a-z][a-z0-9-]{0,63}$/.test(namespace.collection))&&fail2("PLUGIN_STATE_INVALID","Invalid state namespace");let id=createHash11("sha256").update(namespace.scope).digest("hex");return join18(this.directory,namespace.installationId,`${namespace.collection}-${id}.json`)}read(namespace,definition){try{let file=this.path(namespace),saved=this.memory.get(file);if((definition.storage!=="memory"&&saved||definition.storage==="memory"&&!saved&&existsSync8(file))&&fail2("PLUGIN_STATE_STORAGE_CHANGED","Switching between memory and disk state requires a new collection or namespace"),definition.storage==="memory"&&!saved){if(this.memory.size>=512){this.memoryRevisionFloor=Math.max(this.memoryRevisionFloor,...[...this.memory.values()].map(entry=>entry.document.revision))+1;for(let[path7,entry]of this.memory)Object.keys(entry.document.entries).length||(this.memory.delete(path7),this.memoryBytes-=entry.bytes)}throw Object.assign(new Error("Not found"),{code:"ENOENT"})}let document2=saved?{...saved.document,entries:{...saved.document.entries}}:JSON.parse(readFileSync14(file,"utf8"));if(!Number.isSafeInteger(document2.revision)||!Number.isSafeInteger(document2.schemaVersion)||!document2.entries||!Array.isArray(document2.commits))throw new Error("Invalid state document");if(definition.storage!=="persistent"){let entries=Object.fromEntries(Object.entries(document2.entries).filter(([,entry])=>entry.expiresAt===void 0||entry.expiresAt>this.now()));Object.keys(entries).length!==Object.keys(document2.entries).length&&(document2.entries=entries,document2.revision++,definition.storage==="memory"?this.saveMemory(file,document2):writePluginHostFile(file,JSON.stringify(document2)))}return document2}catch(error2){if(error2.code!=="ENOENT")throw error2;return{revision:definition.storage==="memory"?this.memoryRevisionFloor:0,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries:{},commits:[]}}}entry(document2,name,now){let entry=Object.hasOwn(document2.entries,name)?document2.entries[name]:void 0;return entry&&(entry.expiresAt===void 0||entry.expiresAt>now)?{key:name,exists:!0,version:`v:${entry.revision}`,value:document2.storage==="memory"?structuredClone(entry.value):entry.value,...entry.expiresAt===void 0?{}:{expiresAt:entry.expiresAt}}:{key:name,exists:!1,version:`a:${document2.revision}`}}discardScope(installationId,scope){if(!/^[a-f0-9-]{36}$/i.test(installationId)||!scope.startsWith("instance:pi_"))throw new Error("Only ended instance scopes can be discarded");let directory=join18(this.directory,installationId),memorySuffix=`-${createHash11("sha256").update(scope).digest("hex")}.json`;for(let[path7,entry]of this.memory)path7.startsWith(directory+sep5)&&path7.endsWith(memorySuffix)&&(this.memory.delete(path7),this.memoryBytes-=entry.bytes);let suffix=`-${createHash11("sha256").update(scope).digest("hex")}.json`,names;try{names=readdirSync7(directory)}catch(error2){if(error2.code==="ENOENT")return;throw error2}for(let name of names)name.endsWith(suffix)&&rmSync13(join18(directory,name),{force:!0})}prune(skipFile){for(let[path7,saved]of this.memory){let document2={...saved.document,entries:{...saved.document.entries}};for(let[key2,entry]of Object.entries(document2.entries))entry.expiresAt!==void 0&&entry.expiresAt<=this.now()&&delete document2.entries[key2];Object.keys(document2.entries).length!==Object.keys(saved.document.entries).length&&(document2.revision++,this.saveMemory(path7,document2))}let installations;try{installations=readdirSync7(this.directory)}catch(error2){if(error2.code==="ENOENT")return;throw error2}for(let installation of installations)if(/^[a-f0-9-]{36}$/i.test(installation))for(let name of readdirSync7(join18(this.directory,installation))){if(!name.endsWith(".json"))continue;let file=join18(this.directory,installation,name);if(file!==skipFile)try{let document2=JSON.parse(readFileSync14(file,"utf8"));if(document2.storage!=="cache")continue;let entries=Object.fromEntries(Object.entries(document2.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>this.now()));if(Object.keys(entries).length===Object.keys(document2.entries).length)continue;writePluginHostFile(file,JSON.stringify({...document2,revision:document2.revision+1,entries}))}catch(error2){console.error(`Cannot maintain plugin cache ${file}:`,error2)}}}get(namespace,definition,name){key(name);let document2=this.read(namespace,definition);return{...this.entry(document2,name,this.now()),revision:document2.revision,schemaVersion:document2.schemaVersion}}getMany(namespace,definition,names){(!Array.isArray(names)||names.length<1||names.length>128||new Set(names).size!==names.length)&&fail2("PLUGIN_STATE_INVALID","Expected 1 to 128 unique state keys"),names.forEach(name=>key(name));let document2=this.read(namespace,definition),now=this.now(),entries=names.map(name=>this.entry(document2,name,now));return Buffer.byteLength(JSON.stringify(entries))>1024*1024&&fail2("PLUGIN_STATE_RESPONSE_TOO_LARGE","State batch exceeds 1 MiB; read fewer keys"),{entries,revision:document2.revision,schemaVersion:document2.schemaVersion}}list(namespace,definition,input={}){let document2=this.read(namespace,definition),limit=input.limit??100;(!Number.isSafeInteger(limit)||limit<1||limit>200||input.cursor!==void 0&&typeof input.cursor!="string")&&fail2("PLUGIN_STATE_INVALID","Invalid state list cursor or limit"),input.expectedRevision!==void 0&&input.expectedRevision!==document2.revision&&fail2("PLUGIN_STATE_CONFLICT","State list changed; restart pagination");let now=this.now(),candidates=Object.keys(document2.entries).sort().filter(name=>(input.cursor===void 0||name>input.cursor)&&this.entry(document2,name,now).exists),entries=[],bytes=0;for(let name of candidates){let entry=this.entry(document2,name,now),size=Buffer.byteLength(JSON.stringify(entry));if(entries.length&&(entries.length>=limit||bytes+size>256*1024))break;entries.push(entry),bytes+=size}return{entries,revision:document2.revision,schemaVersion:document2.schemaVersion,...entries.length<candidates.length?{nextCursor:entries.at(-1).key}:{}}}transact(namespace,definition,input){(!input||!Array.isArray(input.operations)||input.operations.length>128||Buffer.byteLength(JSON.stringify(input))>512*1024)&&fail2("PLUGIN_STATE_INVALID","State transaction exceeds its limits");let document2=this.read(namespace,definition),hash=createHash11("sha256").update(JSON.stringify({input,schemaVersion:definition.schemaVersion,schema:definition.schema})).digest("hex");if(input.idempotencyKey!==void 0){(typeof input.idempotencyKey!="string"||!input.idempotencyKey.length||input.idempotencyKey.length>128)&&fail2("PLUGIN_STATE_INVALID","Invalid transaction idempotency key");let existing=document2.commits.find(item=>item.id===input.idempotencyKey);if(existing)return existing.hash!==hash&&fail2("PLUGIN_STATE_IDEMPOTENCY_CONFLICT","Transaction key refers to different data or schema"),{revision:existing.revision,schemaVersion:document2.schemaVersion,reused:!0}}input.expectedRevision!==void 0&&input.expectedRevision!==document2.revision&&fail2("PLUGIN_STATE_CONFLICT","Collection revision changed"),document2.schemaVersion===definition.schemaVersion&&document2.schemaHash!==schemaHash(definition)&&fail2("PLUGIN_STATE_SCHEMA_VERSION_REQUIRED","Changing the state schema or storage policy requires a new schemaVersion"),document2.schemaVersion>definition.schemaVersion&&fail2("PLUGIN_STATE_SCHEMA_DOWNGRADE","An older plugin revision cannot write a newer state schema"),document2.schemaVersion!==definition.schemaVersion&&(input.migrateFromVersion!==document2.schemaVersion||input.expectedRevision===void 0)&&fail2("PLUGIN_STATE_MIGRATION_REQUIRED","Schema migration requires the previous schema version and collection revision"),input.migrateFromVersion!==void 0&&input.migrateFromVersion!==document2.schemaVersion&&fail2("PLUGIN_STATE_CONFLICT","State schema changed");let now=this.now(),names=new Set,entries=Object.fromEntries(Object.entries(document2.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>now).map(([name,value])=>[name,{...value}])),revision=document2.revision+1;if(Number.isSafeInteger(revision)||fail2("PLUGIN_STATE_QUOTA","State revision limit reached"),document2.storage!==definition.storage)for(let entry of Object.values(entries))entry.revision=revision,definition.storage!=="persistent"?entry.expiresAt=now+(definition.ttlMs??864e5):delete entry.expiresAt;for(let operation of input.operations){if(key(operation.key),(names.has(operation.key)||!["put","delete"].includes(operation.type)||operation.expectedVersion!==this.entry(document2,operation.key,now).version)&&fail2("PLUGIN_STATE_CONFLICT","State entry version changed or key repeated"),names.add(operation.key),operation.type==="delete"){delete entries[operation.key];continue}let json2=JSON.stringify(operation.value);(json2===void 0||Buffer.byteLength(json2)>256*1024)&&fail2("PLUGIN_STATE_INVALID","State value must be JSON within 256 KiB");let ttl=operation.ttlMs??definition.ttlMs??864e5;definition.storage==="persistent"&&operation.ttlMs!==void 0&&fail2("PLUGIN_STATE_INVALID","Persistent state does not accept TTL"),(!Number.isSafeInteger(ttl)||ttl<1||ttl>7*864e5)&&fail2("PLUGIN_STATE_INVALID","Invalid cache TTL"),entries[operation.key]={revision,value:definition.storage==="memory"?structuredClone(operation.value):operation.value,...definition.storage!=="persistent"?{expiresAt:now+ttl}:{}}}let commit={revision,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries,commits:[...document2.commits,...input.idempotencyKey?[{id:input.idempotencyKey,hash,revision}]:[]].slice(-64)},content=definition.storage==="memory"?"":JSON.stringify(commit),bytes=definition.storage==="memory"?this.memorySize(commit):Buffer.byteLength(content);(Object.keys(entries).length>(definition.maxEntries??1024)||bytes>(definition.maxBytes??8*1024*1024))&&fail2("PLUGIN_STATE_QUOTA","State collection quota exceeded");let file=this.path(namespace);if(definition.storage==="memory")return this.saveMemory(file,commit,bytes),{revision,schemaVersion:definition.schemaVersion};let total=Buffer.byteLength(content);try{for(let name of readdirSync7(join18(this.directory,namespace.installationId))){let path7=join18(this.directory,namespace.installationId,name);path7!==file&&name.endsWith(".json")&&(total+=statSync11(path7).size)}}catch(error2){if(error2.code!=="ENOENT")throw error2}if(total>64*1024*1024){this.prune(file),total=Buffer.byteLength(content);for(let name of readdirSync7(join18(this.directory,namespace.installationId))){let path7=join18(this.directory,namespace.installationId,name);path7!==file&&name.endsWith(".json")&&(total+=statSync11(path7).size)}}return total>64*1024*1024&&fail2("PLUGIN_STATE_QUOTA","Plugin state exceeds 64 MiB"),writePluginHostFile(file,content),{revision,schemaVersion:definition.schemaVersion}}};var PluginStateManager=class{constructor(tasks){this.tasks=tasks;this.store.prune(),this.maintenance=setInterval(()=>{try{this.store.prune()}catch(error2){console.error("Plugin cache maintenance failed:",error2)}},6e4),this.maintenance.unref()}tasks;store=new PluginStateStore;descriptions=new Map;pending=new Set;controller=new AbortController;resolveTarget;maintenance;async call(plugin,input,bridge,options={},binding){if(this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted(),!/^[a-z][a-z0-9_-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin||!input||typeof input!="object"||Array.isArray(input))throw new Error("Invalid plugin state scope");let revision=binding?.revision??capturePluginRevision(plugin),id=`${revision.installationId}/${revision.revision}`,description=this.descriptions.get(id);if(!description){this.descriptions.size>=64&&this.descriptions.delete(this.descriptions.keys().next().value);let release=this.tasks.pinRevision(revision);description=this.tasks.describeRevision(revision,this.controller.signal,{cache:!0}).finally(release),this.descriptions.set(id,description),this.pending.add(description),description.finally(()=>this.pending.delete(description)).catch(()=>{}),description.catch(()=>{this.descriptions.get(id)===description&&this.descriptions.delete(id)})}let declaration=(await description).stateStorage;this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted();let name=String(input.collection??""),definition=declaration&&Object.hasOwn(declaration.collections,name)?declaration.collections[name]:void 0;if(!definition||!/^[a-z][a-z0-9-]{0,63}$/.test(name))throw Object.assign(new Error("Plugin state collection is not declared"),{code:"PLUGIN_STATE_NOT_DECLARED"});if(input.expectedDeclaration!==void 0&&input.expectedDeclaration!==pluginStateSignature(definition))throw Object.assign(new Error("Plugin state declaration changed during command execution"),{code:"PLUGIN_STATE_REVISION_CHANGED"});let scope=definition.scope,assertScope=()=>{};if(definition.scope==="host"&&(scope+=`:${this.tasks.host.hostId}`),definition.scope==="instance"||definition.scope==="browser-session"){if(!this.resolveTarget)throw new Error("Page state scope is unavailable");let resolved=await this.resolveTarget(plugin,input.instanceId,bridge,options),target=resolved.target,expected=binding?.expectedTarget;if(expected&&(target.browserSessionId!==expected.browserSessionId||target.tabId!==expected.tabId||target.frameId!==expected.frameId||target.documentId!==expected.documentId))throw Object.assign(new Error("State access cannot change the inherited document"),{code:"PLUGIN_PAGE_TARGET_CHANGED"});assertScope=resolved.assertActive,scope+=definition.scope==="instance"?`:${String(input.instanceId)}`:`:${target.browserSessionId}`}this.controller.signal.throwIfAborted(),binding?.signal?.throwIfAborted();let installation;try{installation=JSON.parse(readFileSync15(join19(pluginHostPaths().installations,`${plugin}.json`),"utf8"))}catch{}if(!findPluginRegistration(plugin)||installation?.installationId!==revision.installationId)throw Object.assign(new Error("Plugin state installation was removed or replaced"),{code:"PLUGIN_STATE_SCOPE_ENDED"});assertScope();let namespace={installationId:revision.installationId,collection:name,scope};switch(input.operation){case"get":return this.store.get(namespace,definition,input.key);case"get-many":return this.store.getMany(namespace,definition,input.keys);case"list":return this.store.list(namespace,definition,input);case"transact":return this.store.transact(namespace,definition,input.transaction);default:throw new Error("Invalid state operation")}}async close(){clearInterval(this.maintenance),this.controller.abort(),this.descriptions.clear(),this.store.clearMemory(),await Promise.allSettled([...this.pending])}};import{createHash as createHash12,randomUUID as randomUUID13}from"node:crypto";import{EventEmitter as EventEmitter2}from"node:events";import{readFileSync as readFileSync16,statSync as statSync12}from"node:fs";import{isAbsolute as isAbsolute8,join as join20}from"node:path";init_plugin();init_unified();init_pluginHostPaths();init_pluginExecutorProtocol();init_dist2();init_dist2();function failure(code,message){return Object.assign(new Error(message),{code})}function sameTarget(a,b){return a.browserSessionId===b.browserSessionId&&a.tabId===b.tabId&&a.frameId===b.frameId&&a.documentId===b.documentId}var PluginPageManager=class{constructor(tasks,states,releaseModels){this.tasks=tasks;this.states=states;this.releaseModels=releaseModels;this.heartbeat=setInterval(()=>{this.reconcile()},1e4),this.heartbeat.unref()}tasks;states;releaseModels;instances=new Map;changes=new EventEmitter2().setMaxListeners(0);heartbeat;reconciling=new Set;closed=!1;describing=new Set;async resolveStateTarget(plugin,instanceId,bridge,options){let record2=this.own(plugin,instanceId,bridge);return await this.bind(record2,bridge,options),await this.validate(record2),{target:{...record2.value.target},assertActive:()=>{if(this.closed||record2.value.state!=="active"||this.instances.get(record2.value.instanceId)!==record2)throw failure("PLUGIN_STATE_SCOPE_ENDED","Plugin page state scope has ended")}}}diagnosticSnapshot(){return[...this.instances.values()].map(record2=>({plugin:record2.value.plugin,installationId:record2.value.installationId,revision:record2.value.revision,host:{hostId:record2.value.host.hostId,epoch:record2.value.host.epoch},binding:diagnosticBinding(record2.value),observation:"service-snapshot",state:record2.value.state,lastReceived:record2.lastReceived,queued:record2.deliveries.filter(delivery=>delivery.state==="queued").length,running:record2.running.size}))}async reconcile(){this.closed||await Promise.all([...this.instances.values()].map(async record2=>{let id=record2.value.instanceId;if(!(!record2.ready||record2.value.state!=="active"||this.reconciling.has(id))){this.reconciling.add(id);try{await this.validate(record2)}catch(error2){isPluginPageUnavailable(error2)||await this.invalidate(record2,error2)}finally{this.reconciling.delete(id)}}}))}bounded(promise,milliseconds){return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>reject(failure("PLUGIN_PAGE_TIMEOUT","Plugin page browser request timed out")),milliseconds);promise.then(resolve7,reject).finally(()=>clearTimeout(timer))})}async invoke(record2,data,timeoutSec){let payload={...data,tabId:record2.value.target.tabId,instanceId:record2.value.instanceId,...timeoutSec!==void 0?{timeoutSec}:{}};return record2.client?record2.client.invoke("page_runtime",payload,{...record2.options,...timeoutSec!==void 0?{timeoutSec}:{}}):record2.bridge.invoke("page_runtime",payload,{...record2.options,...timeoutSec!==void 0?{timeoutSec}:{}})}unavailable(record2,error2){return isPluginPageInvalidation(error2)?error2:(record2.unavailable=!0,Date.now()-record2.lastVerifiedAt>=3e4?failure("PLUGIN_PAGE_INVALIDATED","Plugin page host recovery lease expired"):pluginPageUnavailable(error2))}async validate(record2){if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance is no longer active");let registration=findPluginRegistration(record2.value.plugin),installation;try{installation=JSON.parse(readFileSync16(join20(pluginHostPaths().installations,`${record2.value.plugin}.json`),"utf8"))}catch{}if(!registration||installation?.installationId!==record2.value.installationId)throw failure("PLUGIN_PAGE_INVALIDATED","Plugin installation was removed or replaced");let bridge=record2.bridge,current;try{current=await this.bounded(this.invoke(record2,{operation:"get"}),8e3)}catch(error2){if(!record2.client&&record2.bridge!==bridge&&!this.closed&&record2.value.state==="active")return this.validate(record2);throw this.unavailable(record2,error2)}if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance ended during validation");if(current.state!=="active"||!sameTarget(current.target,record2.value.target)||!matchesPluginPageURL(record2.runtime.matches,current.target.url))throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page document changed");record2.value.target.url=current.target.url,record2.lastVerifiedAt=Date.now();let recovered=record2.unavailable;record2.unavailable=!1,recovered&&queueMicrotask(()=>this.drain(record2))}own(plugin,instanceId,bridge){if(bridge.scope.plugin&&bridge.scope.plugin!==plugin)throw failure("PLUGIN_PAGE_NOT_FOUND","Plugin page instance was not found");if(!isPluginPageInstanceId(instanceId))throw failure("PLUGIN_PAGE_NOT_FOUND","Invalid plugin page instance ID");let record2=this.instances.get(instanceId);if(!record2||record2.value.plugin!==plugin)throw failure("PLUGIN_PAGE_NOT_FOUND","Plugin page instance was not found");return record2}async bind(record2,bridge,options){if(bridge.scope.bridge!=="caller"||!record2.client&&record2.bridge.id===bridge.id||record2.value.state!=="active")return;let current;try{current=await this.bounded(bridge.invoke("page_runtime",{operation:"get",tabId:record2.value.target.tabId,instanceId:record2.value.instanceId},options),8e3)}catch(error2){throw this.unavailable(record2,error2)}if(this.closed||record2.value.state!=="active")throw failure("PLUGIN_PAGE_INVALIDATED","Plugin page instance ended while binding");if(!sameTarget(current.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Plugin page belongs to a different browser document");record2.client||(record2.bridge=bridge,record2.options=options)}append(record2,event){for(record2.history.push({...event,sequence:++record2.value.sequence,time:Date.now()});record2.history.length>256||Buffer.byteLength(JSON.stringify(record2.history))>384*1024;)record2.history.shift();this.changes.emit(record2.value.instanceId)}async waitForChange(record2,cursor,waitMs,signal){!waitMs||cursor!==record2.value.sequence||record2.value.state!=="active"||await new Promise((resolve7,reject)=>{let finish=()=>{cleanup(),resolve7()},abort=()=>{cleanup(),reject(signal?.reason??new Error("Plugin page subscription closed"))},timer=setTimeout(finish,waitMs),cleanup=()=>{clearTimeout(timer),this.changes.off(record2.value.instanceId,finish),signal?.removeEventListener("abort",abort)};this.changes.once(record2.value.instanceId,finish),signal?.addEventListener("abort",abort,{once:!0}),signal?.aborted?abort():(record2.value.sequence!==cursor||record2.value.state!=="active")&&finish()})}async invalidate(record2,error2,state="invalidated"){if(record2.value.state==="active"){record2.value.state=state,record2.value.error=serializePluginExecutionError(error2),this.append(record2,{type:"invalidated",error:record2.value.error});for(let taskId of record2.taskIds)this.tasks.cancel(taskId,{access:"public",source:"runtime",bridge:"service"});for(let delivery of record2.deliveries)delivery.taskId&&this.tasks.cancel(delivery.taskId,{access:"public",source:"runtime",bridge:"service"}),["queued","running"].includes(delivery.state)&&(delivery.state="invalidated");try{this.states.store.discardScope(record2.value.installationId,`instance:${record2.value.instanceId}`)}catch(error3){console.error("Plugin instance cache cleanup failed:",error3)}record2.release();try{await this.releaseModels?.(record2.value.instanceId)}finally{try{await this.bounded(this.invoke(record2,{operation:"detach"}),2e3)}catch{}record2.client?.disconnect()}}}async call(plugin,input,bridge,options={},execution={cwd:process.cwd(),environment:Object.fromEntries(Object.entries(process.env).filter(entry=>entry[1]!==void 0))}){if(this.closed)throw failure("PLUGIN_PAGE_HOST_STOPPING","Plugin page service is stopping");if(execution.signal?.throwIfAborted(),!input||typeof input!="object"||Array.isArray(input))throw new Error("Invalid plugin page request");if(!/^[a-z][a-z0-9_-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin)throw new Error("Invalid plugin page scope");let operation=input.operation;if(execution.expectedTarget&&operation==="activation"&&input.enabled!==void 0)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Document-bound calls cannot configure browser activation");if(operation==="attach"||operation==="activation"){if(Object.keys(options).some(key2=>!["browser","connector","session","local","transport","timeoutSec"].includes(key2)))throw new Error("Invalid plugin page routing options");if(bridge.scope.bridge==="service"&&!decodeBrowserTarget(options.browser))throw new Error("Plugin pages require a stable browser ID");if(!execution||!isAbsolute8(execution.cwd)||!statSync12(execution.cwd).isDirectory()||!execution.environment||Buffer.byteLength(JSON.stringify(execution.environment))>512*1024||Object.values(execution.environment).some(value=>typeof value!="string"))throw new Error("Invalid plugin page execution context")}if(operation==="activation"&&input.enabled!==!0){let client=bridge.scope.bridge==="service"?new UnifiedClient:void 0;try{return client?await client.invoke("page_runtime",{...input,plugin},options):await bridge.invoke("page_runtime",{...input,plugin},options)}finally{client?.disconnect()}}if(operation==="attach"||operation==="activation"){let revision=execution.revision??capturePluginRevision(plugin);if(input.installationId!==void 0&&input.installationId!==revision.installationId)throw failure("PLUGIN_PAGE_INSTALLATION_CHANGED","Page activation belongs to another plugin installation");let release=this.tasks.pinRevision(revision),retained=!1,client=bridge.scope.bridge==="service"?new UnifiedClient:void 0,invoke2=data=>client?client.invoke("page_runtime",data,options):bridge.invoke("page_runtime",data,options);try{let controller=new AbortController,description={controller,promise:this.tasks.describeRevision(revision,execution.signal?AbortSignal.any([controller.signal,execution.signal]):controller.signal,{cache:!0})};this.describing.add(description);let loaded;try{loaded=await description.promise}finally{this.describing.delete(description)}if(this.closed)throw new Error("Plugin page host stopped during attachment");let runtime=loaded.pageRuntime;if(!runtime)throw failure("PLUGIN_PAGE_NOT_DECLARED","Plugin has no pageRuntime declaration");if(operation==="activation")return await invoke2({...input,operation:"activation",plugin,installationId:revision.installationId,allowedMatches:runtime.matches});if(this.instances.size>=256){for(let[id,item]of this.instances)item.value.state!=="active"&&!item.running.size&&this.instances.delete(id);if(this.instances.size>=256)throw new Error("Too many plugin page instances")}let target=await invoke2({operation:"resolve",tabId:input.tabId,frame:input.frame,expectedDocumentId:input.documentId});if(this.closed)throw failure("PLUGIN_PAGE_HOST_STOPPING","Plugin page service is stopping");if(execution.signal?.throwIfAborted(),execution.expectedTarget&&!sameTarget(target,execution.expectedTarget))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Nested plugin must use the inherited document");if(!matchesPluginPageURL(runtime.matches,target.url))throw failure("PLUGIN_PAGE_URL_NOT_ALLOWED","Plugin page URL is outside its declared matches");let existing=[...this.instances.values()].find(item=>item.value.state==="active"&&item.value.plugin===plugin&&sameTarget(item.value.target,target));if(existing&&execution.revision&&existing.value.revision!==revision.revision&&input.replace!==!0)throw failure("PLUGIN_PAGE_REVISION_CHANGED","Existing page instance uses another plugin revision");if(existing&&input.replace!==!0)try{return await existing.initialized,await this.bind(existing,bridge,options),await this.validate(existing),input.activationGeneration===void 0&&await invoke2({operation:"get",instanceId:existing.value.instanceId,tabId:target.tabId,retainManual:!0}),existing.value}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(existing,error2)}existing&&await this.invalidate(existing,new Error("Plugin page instance replaced"),"detached");let value={instanceId:`pi_${randomUUID13()}`,plugin,installationId:revision.installationId,revision:revision.revision,host:this.tasks.host,target,state:"active",sequence:0,createdAt:Date.now()},initialized,initializationFailed,initialization=new Promise((resolve7,reject)=>{initialized=resolve7,initializationFailed=reject});initialization.catch(()=>{});let record3={initialized:initialization,value,runtime,revision,release,bridge,options:{...options},client,ready:!1,lastVerifiedAt:Date.now(),unavailable:!1,taskIds:new Set,execution:{cwd:execution.cwd,environment:{...execution.environment}},history:[],deliveries:[],lastReceived:0,running:new Set};this.instances.set(value.instanceId,record3);try{let attached=await invoke2({operation:"attach",instance:value,runtime,input:input.input??{},frame:input.frame??"business",activationGeneration:input.activationGeneration});if(!sameTarget(attached.target,target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Document changed while attaching plugin page");if(await this.validate(record3),execution.signal?.throwIfAborted(),runtime.initialize){let parent=execution.parentIdentity;parent?.taskId&&this.tasks.assertChildBudget(parent.taskId);let{taskId}=this.start(record3,runtime.initialize,{input:input.input??{}},`initialize:${value.instanceId}`,parent),scope={access:"public",source:"runtime",bridge:"service"},cancel2=()=>this.tasks.cancel(taskId,scope);execution.signal?.addEventListener("abort",cancel2,{once:!0}),execution.signal?.aborted&&cancel2();try{parent?.taskId&&execution.signal?await this.tasks.awaitChild(parent.taskId,taskId,scope,execution.signal):await this.wait(record3,taskId)}finally{execution.signal?.removeEventListener("abort",cancel2),record3.taskIds.delete(taskId)}}return execution.signal?.throwIfAborted(),await this.validate(record3),execution.signal?.throwIfAborted(),record3.ready=!0,initialized(),this.drain(record3),retained=!0,value}catch(error2){throw initializationFailed(error2),await this.invalidate(record3,error2),error2}}finally{retained||(release(),client?.disconnect())}}if(operation==="list")return{instances:[...this.instances.values()].filter(item=>item.value.plugin===plugin&&(!execution.expectedTarget||sameTarget(item.value.target,execution.expectedTarget))).map(item=>item.value)};let record2=this.own(plugin,input.instanceId,bridge);if(execution.expectedTarget&&!sameTarget(record2.value.target,execution.expectedTarget))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Nested plugin must use the inherited document");if(execution.revision&&record2.value.revision!==execution.revision.revision)throw failure("PLUGIN_PAGE_REVISION_CHANGED","Page instance uses another plugin revision");if(await this.bind(record2,bridge,options),operation==="detach")return await this.invalidate(record2,new Error("Plugin page instance detached"),"detached"),record2.value;try{record2.value.state==="active"&&await this.validate(record2)}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(record2,error2)}if(operation==="get")return record2.value;if(operation==="events"){let cursor=input.cursor??0,waitMs=input.waitMs??0;if(!Number.isSafeInteger(cursor)||Number(cursor)<0||Number(cursor)>record2.value.sequence)throw new Error("Invalid plugin page event cursor");if(!Number.isSafeInteger(waitMs)||Number(waitMs)<0||Number(waitMs)>25e3)throw new Error("Invalid plugin page event wait");await this.waitForChange(record2,Number(cursor),Number(waitMs),execution.signal),execution.signal?.throwIfAborted();let first=record2.history[0]?.sequence??record2.value.sequence+1,events=[],bytes=0;for(let event of record2.history)if(event.sequence>Number(cursor)){let size=Buffer.byteLength(JSON.stringify(event));if(events.length&&bytes+size>192*1024)break;events.push(event),bytes+=size}return{instance:record2.value,events,nextCursor:events.at(-1)?.sequence??Number(cursor),firstAvailableSequence:first,gap:Number(cursor)<first-1}}if(operation!=="send")throw new Error("Unknown plugin page operation");let timeoutSec=input.timeoutSec;if(timeoutSec!==void 0&&(typeof timeoutSec!="number"||!Number.isFinite(timeoutSec)||timeoutSec<=0||timeoutSec>300))throw new Error("Page request timeoutSec must be between 0 and 300");await this.validate(record2),execution.signal?.throwIfAborted();let json2=Buffer.from(JSON.stringify(input.message??null));if(json2.length>24*1024*1024)throw new Error("Plugin page message exceeds 24 MiB");let requestId=randomUUID13(),cancel=()=>{this.invoke(record2,{operation:"cancel",requestId}).catch(()=>{})};execution.signal?.addEventListener("abort",cancel,{once:!0});try{let result;if(json2.length<=192*1024)result=await this.invoke(record2,{operation:"send",message:input.message,requestId},timeoutSec);else{let transferId=randomUUID13();try{await this.invoke(record2,{operation:"message_begin",transferId,bytes:json2.length,sha256:createHash12("sha256").update(json2).digest("hex")});for(let offset=0,index=0;offset<json2.length;offset+=192*1024,index++)await this.validate(record2),execution.signal?.throwIfAborted(),await this.invoke(record2,{operation:"message_chunk",transferId,index,data:json2.subarray(offset,offset+192*1024).toString("base64")});await this.validate(record2),execution.signal?.throwIfAborted(),result=await this.invoke(record2,{operation:"message_commit",transferId,requestId},timeoutSec)}finally{await this.invoke(record2,{operation:"message_abort",transferId}).catch(()=>{})}}execution.signal?.throwIfAborted(),await this.validate(record2);let reply=result;if(reply?.kind==="value")return reply.value;if(reply?.kind!=="resource"||!Number.isSafeInteger(reply.bytes)||reply.bytes<1||reply.bytes>24*1024*1024||reply.chunks!==Math.ceil(reply.bytes/(192*1024)))throw new Error("Invalid page response resource");try{let parts=[];for(let index=0;index<reply.chunks;index++){await this.validate(record2);let chunk=await this.invoke(record2,{operation:"result_chunk",resultId:reply.resultId,index});if(chunk.resultId!==reply.resultId||chunk.index!==index||chunk.bytes!==reply.bytes||chunk.sha256!==reply.sha256||chunk.chunks!==reply.chunks)throw new Error("Page response chunk identity mismatch");parts.push(Buffer.from(chunk.data,"base64"))}let bytes=Buffer.concat(parts);if(bytes.length!==reply.bytes||createHash12("sha256").update(bytes).digest("hex")!==reply.sha256)throw new Error("Page response integrity check failed");return await this.validate(record2),JSON.parse(bytes.toString("utf8"))}finally{await this.invoke(record2,{operation:"result_release",resultId:reply.resultId}).catch(()=>{})}}catch(error2){throw cancel(),error2}finally{execution.signal?.removeEventListener("abort",cancel)}}async receive(plugin,input,bridge,options={}){if(input.kind==="sync"){if(this.closed||!/^[a-z][a-z0-9_-]*$/.test(plugin)||bridge.scope.plugin&&bridge.scope.plugin!==plugin||!Array.isArray(input.instances)||input.instances.length>32)throw new Error("Invalid page reconciliation request");let session2=await this.bounded(bridge.invoke("page_runtime",{operation:"session"},options),8e3);if(typeof input.browserSessionId!="string"||session2.browserSessionId!==input.browserSessionId)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page reconciliation came from another browser session");let instances=[];for(let value of input.instances){let proposed=value,record3=this.instances.get(proposed?.instanceId);if(!(!record3||record3.value.plugin!==plugin||record3.value.state!=="active"||!proposed.host||proposed.host.hostId!==this.tasks.host.hostId||proposed.host.epoch!==this.tasks.host.epoch||proposed.installationId!==record3.value.installationId||proposed.revision!==record3.value.revision||!proposed.target||!sameTarget(proposed.target,record3.value.target)||record3.value.target.browserSessionId!==session2.browserSessionId))try{await this.bind(record3,bridge,options),await this.validate(record3),instances.push({instance:record3.value,lastReceived:record3.lastReceived})}catch(error2){if(isPluginPageUnavailable(error2))throw error2;await this.invalidate(record3,error2)}}return{host:this.tasks.host,instances}}let record2=this.own(plugin,input.instanceId,bridge);if((await this.bounded(bridge.invoke("page_runtime",{operation:"session"},options),8e3)).browserSessionId!==record2.value.target.browserSessionId)throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page event came from another browser");if(input.kind==="invalidated"){if(!input.target||!sameTarget(input.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Invalid document invalidation source");return await this.invalidate(record2,new Error("Browser invalidated the document")),{accepted:!0}}let source=await this.bounded(bridge.invoke("page_runtime",{operation:"get",tabId:record2.value.target.tabId,instanceId:record2.value.instanceId},options),8e3);if(!sameTarget(source.target,record2.value.target))throw failure("PLUGIN_PAGE_TARGET_CHANGED","Page event came from another document");if(await this.bind(record2,bridge,options),await this.validate(record2),input.kind==="navigation")return this.append(record2,{type:"navigation",payload:{url:record2.value.target.url}}),{accepted:!0};let sequence=input.eventSequence;if(!Number.isSafeInteger(sequence)||Number(sequence)<1)throw new Error("Invalid page event sequence");let duplicate=record2.deliveries.find(item=>item.sequence===sequence);if(Number(sequence)<=record2.lastReceived)return{accepted:!0,duplicate:!0,taskId:duplicate?.taskId,gap:!duplicate};if(Number(sequence)!==record2.lastReceived+1)throw failure("PLUGIN_PAGE_EVENT_GAP","Page event stream has a gap; reattach the instance");let name=typeof input.name=="string"?input.name:"",binding=record2.runtime.events?.[name];if(!binding||Buffer.byteLength(JSON.stringify(input.payload??null))>32*1024)throw new Error("Page event is not declared or exceeds 32 KiB");let waiting=record2.deliveries.filter(item=>item.name===name&&item.state==="queued");if(binding.policy==="latest")for(let previous of waiting)previous.state="superseded",this.append(record2,{type:"superseded",eventSequence:previous.sequence,name});else if(waiting.length>=(binding.maxPending??32))throw failure("PLUGIN_PAGE_QUEUE_FULL","Page event queue is full");if(record2.deliveries.filter(item=>["queued","running"].includes(item.state)).length>=128)throw failure("PLUGIN_PAGE_QUEUE_FULL","Page event queue is full");let delivery={sequence:Number(sequence),name,payload:input.payload,state:"queued"};for(record2.lastReceived=Number(sequence),record2.deliveries.push(delivery);record2.deliveries.length>256;){let index=record2.deliveries.findIndex(item=>!["queued","running"].includes(item.state));if(index<0)break;record2.deliveries.splice(index,1)}return this.append(record2,{type:"received",eventSequence:delivery.sequence,name,payload:input.payload}),this.drain(record2),{accepted:!0,eventSequence:delivery.sequence,taskId:delivery.taskId}}drain(record2){if(!(this.closed||!record2.ready||record2.unavailable||record2.value.state!=="active"))for(let delivery of record2.deliveries){if(delivery.state!=="queued")continue;let binding=record2.runtime.events[delivery.name];[...record2.running].filter(item=>item.name===delivery.name).length>=(binding.policy==="parallel"?binding.concurrency??2:1)||(delivery.state="running",record2.running.add(delivery),this.execute(record2,delivery).finally(()=>{record2.running.delete(delivery),this.drain(record2)}))}}async execute(record2,delivery){try{await this.validate(record2);let binding=record2.runtime.events[delivery.name],started=this.start(record2,binding.command,{event:{name:delivery.name,payload:delivery.payload,sequence:delivery.sequence}},`page:${record2.value.instanceId}:${delivery.sequence}`);delivery.taskId=started.taskId,this.append(record2,{type:"running",name:delivery.name,eventSequence:delivery.sequence,taskId:started.taskId}),await this.wait(record2,started.taskId),delivery.state="success",this.append(record2,{type:"success",name:delivery.name,eventSequence:delivery.sequence,taskId:started.taskId})}catch(error2){if(isPluginPageUnavailable(error2)&&!delivery.taskId&&record2.value.state==="active"){delivery.state="queued";return}delivery.state="error",this.append(record2,{type:"error",name:delivery.name,eventSequence:delivery.sequence,error:serializePluginExecutionError(error2)})}}start(record2,command,input,key2,parentIdentity){let bridge={get id(){return record2.bridge.id},scope:{...record2.bridge.scope,plugin:record2.value.plugin,access:"runtime",source:"runtime"},invoke:(action,payload,options)=>record2.client?record2.client.invoke(action,payload,options):record2.bridge.invoke(action,payload,options)},started=this.tasks.start({plugin:record2.value.plugin,command,input,cwd:record2.execution.cwd,environment:record2.execution.environment,options:record2.options,idempotencyKey:key2},bridge,{...parentIdentity?.taskId?{parentTaskId:parentIdentity.taskId,parentIdentity}:{},revision:record2.revision,guard:()=>this.validate(record2),page:{instanceId:record2.value.instanceId,target:{...record2.value.target}}});return record2.taskIds.add(started.taskId),started}async wait(record2,taskId){let cursor=0;for(;;){let page=await this.tasks.events(taskId,{access:"public",source:"runtime",bridge:"service"},cursor,25e3);if(cursor=page.nextCursor,!isPluginTaskActive(page.task.state)){if(record2.taskIds.delete(taskId),page.task.state!=="success")throw Object.assign(pluginExecutionError(page.task.error??{message:"Page handler failed"}),{childTaskId:taskId});return}record2.value.state!=="active"&&this.tasks.cancel(taskId,{access:"public",source:"runtime",bridge:"service"})}}async close(){this.closed=!0,clearInterval(this.heartbeat);for(let item of this.describing)item.controller.abort();await Promise.allSettled([...this.describing].map(item=>item.promise)),await Promise.allSettled([...this.instances.values()].map(record2=>this.invalidate(record2,new Error("Plugin page host stopped"))))}};var PluginModelCatalog=class{constructor(discover=async signal=>{let{listCodexModels:listCodexModels2}=await Promise.resolve().then(()=>(init_codex(),codex_exports));return listCodexModels2(signal)},now=Date.now){this.discover=discover;this.now=now}discover;now;controller=new AbortController;cached;pending;list(provider="codex"){if(this.controller.signal.throwIfAborted(),provider!=="codex")throw new Error("Unsupported model provider");return this.cached?(this.cached.expires<=this.now()&&this.refresh().catch(()=>{}),Promise.resolve(structuredClone(this.cached.value))):this.refresh().then(value=>structuredClone(value))}refresh(){return this.pending??=this.load().catch(error2=>{throw this.cached&&(this.cached.expires=this.now()+3e4),error2}).finally(()=>{this.pending=void 0}),this.pending}async load(){let signal=AbortSignal.any([this.controller.signal,AbortSignal.timeout(15e3)]),value={provider:"codex",models:await this.discover(signal)};return signal.throwIfAborted(),this.cached={value,expires:this.now()+12e4},value}async close(){this.controller.abort(),await this.pending?.catch(()=>{}),this.cached=void 0}};init_runtimePaths();init_dist();init_pluginExecutorProtocol();init_pluginProcessTree();init_pluginModelDefinition();import{fork as fork2}from"node:child_process";import{createHash as createHash13}from"node:crypto";var PluginModelSessions=class{constructor(idleMs=5*6e4,limit=2,workerPath=PLUGIN_MODEL_SESSION_WORKER_PATH){this.idleMs=idleMs;this.limit=limit;this.workerPath=workerPath}idleMs;limit;workerPath;sessions=new Map;closing=new Set;closed=!1;execute(owner,...args){let[plugin,,context,options={}]=args,request=options.model,configuration=Object.fromEntries(Object.entries(request).filter(([key3])=>!["prompt","outputSchema"].includes(key3)).sort(([a],[b])=>a.localeCompare(b))),key2=createHash13("sha256").update(JSON.stringify([owner,plugin,context.invocation?.installationId,context.invocation?.revision,options.cwd,Object.entries(options.environment??{}).sort(([a],[b])=>a.localeCompare(b)),configuration])).digest("hex");if(options.signal?.throwIfAborted(),this.closed)return Promise.reject(new Error("Model conversations are closed"));let session=this.sessions.get(key2);if(!session||session.closed){if(this.sessions.size>=this.limit){let idle=[...this.sessions.values()].find(value=>!value.queued);if(!idle)return Promise.reject(new Error("Model conversation limit reached"));this.remove(idle).catch(error2=>console.error("Model conversation cleanup failed:",error2))}let child=fork2(this.workerPath,[],{stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced",execArgv:[],detached:process.platform!=="win32",cwd:options.cwd,env:options.environment}),exited=new Promise(resolve7=>child.once("close",()=>resolve7()));session={owner,child,tail:Promise.resolve(),queued:0,closed:!1,exited};let current2=session;child.on("error",()=>{this.remove(current2).catch(error2=>console.error("Model conversation cleanup failed:",error2))}),child.once("exit",()=>{this.remove(current2).catch(error2=>console.error("Model conversation cleanup failed:",error2))}),this.sessions.set(key2,session)}this.sessions.delete(key2),this.sessions.set(key2,session),clearTimeout(session.timer);let current=session;current.queued++;let started=!1,operation=current.tail.catch(()=>{}).then(async()=>{if(options.signal?.throwIfAborted(),current.closed)throw new Error("Model conversation has ended");return started=!0,this.run(current,args)});if(current.tail=operation.finally(()=>{current.queued--,!current.queued&&!current.closed&&(current.timer=setTimeout(()=>{this.remove(current).catch(error2=>console.error("Model conversation cleanup failed:",error2))},this.idleMs),current.timer.unref())}),current.tail.catch(()=>{}),!options.signal)return operation;let signal=options.signal;return new Promise((resolve7,reject)=>{let abort=()=>{started||reject(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"}))};signal.addEventListener("abort",abort,{once:!0}),signal.aborted&&abort(),operation.then(resolve7,reject).finally(()=>signal.removeEventListener("abort",abort))})}run(session,args){let options=args[3],request=options.model,child=session.child;return new Promise((resolve7,reject)=>{let finished=!1,stderr="",timer,finish=async(failure2,result)=>{if(!finished){finished=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",abort),child.removeListener("message",message),child.removeListener("error",failed),child.removeListener("exit",exited),child.stderr?.removeListener("data",capture);try{failure2&&await this.remove(session),options.onExecutorStopped?.(),failure2?reject(failure2):resolve7(result)}catch(error2){reject(error2)}}},failed=error2=>{finish(error2)},exited=()=>failed(new Error(stderr||"Model conversation executor exited")),abort=()=>failed(Object.assign(new Error("Model execution cancelled"),{code:"PLUGIN_EXECUTION_CANCELLED"})),capture=chunk=>{stderr=(stderr+chunk.toString()).slice(-65536)},message=event=>{if(!finished)try{event.type==="result"?finish(void 0,validatePluginModelResult(request,event.result)):event.type==="error"?failed(pluginExecutionError(event.error)):event.type==="diagnostic"?options.onDiagnostic?.(event.metadata):event.type==="delta"&&options.onProgress?.({message:"model.delta",data:{delta:event.delta,index:event.index,...event.metadata,partial:!0}})}catch(error2){finish(error2)}};child.on("message",message),child.once("error",failed),child.once("exit",exited),child.stderr?.on("data",capture),options.signal?.addEventListener("abort",abort,{once:!0}),options.executionTimeoutMs&&(timer=setTimeout(()=>failed(Object.assign(new Error("Model execution deadline exceeded"),{code:"PLUGIN_EXECUTION_DEADLINE"})),options.executionTimeoutMs));try{if(options.signal?.aborted){abort();return}child.pid&&options.onExecutorStarted?.({pid:child.pid,processIdentity:processIdentity(child.pid)}),child.send({request},error2=>{error2&&failed(error2)})}catch(error2){finish(error2)}})}remove(session){if(session.closing)return session.closing;session.closed=!0,clearTimeout(session.timer);for(let[key2,value]of this.sessions)value===session&&this.sessions.delete(key2);return session.closing=(session.child.pid?stopPluginProcessTree(session.child.pid):Promise.resolve()).then(()=>{let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("Model conversation did not exit")),2e3)});return Promise.race([session.exited,timeout]).finally(()=>clearTimeout(timer))}).catch(cause=>{throw Object.assign(new Error("Unable to confirm model conversation cleanup",{cause}),{code:"PLUGIN_EXECUTOR_CLEANUP_FAILED",details:{executionStopped:!1}})}),this.closing.add(session),session.closing.finally(()=>this.closing.delete(session)).catch(()=>{}),session.closing}async release(owner){await Promise.all([...new Set([...this.sessions.values(),...this.closing])].filter(value=>value.owner===owner).map(value=>this.remove(value)))}async close(){this.closed=!0,await Promise.all([...new Set([...this.sessions.values(),...this.closing])].map(value=>this.remove(value)))}};import{dirname as dirname9,join as join21}from"node:path";var PluginHost=class{tasks;state;pages;models=new PluginModelCatalog;modelSessions;closing;constructor(configuration={}){this.modelSessions=new PluginModelSessions(void 0,Math.max(2,configuration.modelConcurrency??2),configuration.workerPath?join21(dirname9(configuration.workerPath),"pluginModelSessionWorker.js"):void 0),this.tasks=new PluginTaskManager(configuration,{state:(...args)=>this.state.call(...args),page:(...args)=>this.pages.call(...args),listModels:provider=>this.models.list(provider),model:(owner,...args)=>this.modelSessions.execute(owner,...args),releaseModels:owner=>this.modelSessions.release(owner)}),this.state=new PluginStateManager(this.tasks),this.pages=new PluginPageManager(this.tasks,this.state,owner=>this.modelSessions.release(owner)),this.state.resolveTarget=(...args)=>this.pages.resolveStateTarget(...args)}diagnose(value,scope){let options=normalizeDiagnosticOptions(value);if(scope.plugin&&options.plugin&&scope.plugin!==options.plugin)throw Object.assign(new Error("Plugin task was not found"),{code:"PLUGIN_TASK_NOT_FOUND"});return buildDiagnosticReport(this.tasks.host,scope,options,this.tasks.store.diagnosticRecords(options.taskId),this.pages.diagnosticSnapshot())}close(){return this.closing??=Promise.allSettled([this.pages.close(),this.tasks.close(),this.state.close(),this.models.close(),this.modelSessions.close()]).then(results=>{let failures=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(failures.length)throw new AggregateError(failures,"Plugin host cleanup failed")}),this.closing}};init_pluginTaskWire();init_pluginExecutorProtocol();async function startPluginHostServer(configuration={}){let paths=pluginHostPaths(),existing=readRecord(paths.lease);existing&&!isProcessOwnerAlive(existing)?removeRecordIfPid(paths.lease,existing.pid):existing||removeInvalidRecord(paths.lease);let owner={pid:process.pid,protocolVersion:5,version:CLIENT_VERSION,processIdentity:processIdentity(process.pid)};if(!claimRecord(paths.lease,owner))throw Object.assign(new Error("Plugin execution service already has an owner"),{code:"PLUGIN_TASK_HOST_OWNED"});let host;try{host=new PluginHost(configuration)}catch(error2){throw removeRecordIfPid(paths.lease,process.pid),error2}let{tasks:manager,pages,state,models}=host;if(!writeRecordIfPid(paths.lease,process.pid,{...owner,...manager.host,socketPath:paths.socket,startedAt:new Date().toISOString()}))throw new Error("Plugin host lease ownership was lost");let sessions=new Set,closing,server=createServer(socket=>{sessions.add(socket);let disconnected=new AbortController,scope,sequence=0,requests=0,pending=new Map,bridge={id:randomUUID14(),get scope(){if(!scope)throw new Error("Plugin task connection is not initialized");return scope},invoke(action,payload,options){if(socket.destroyed)return Promise.reject(Object.assign(new Error("The browser invocation bridge is unavailable"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE"}));let id=++sequence;return new Promise((resolve7,reject)=>{let timer=setTimeout(()=>{pending.delete(id),reject(Object.assign(new Error("The browser invocation bridge timed out; external operation status is unknown"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE",details:{action}}))},Math.min(Math.max(options.timeoutSec??180,1),3600)*1e3);pending.set(id,{resolve:resolve7,reject,timer}),writePluginTaskMessage(socket,{type:"invoke",id,action,payload,options}).catch(error2=>{pending.delete(id),clearTimeout(timer),reject(error2)})})}},handle=async(method,input)=>{if(method==="hello"){if(scope||input.protocolVersion!==5)throw new Error("Plugin task protocol version mismatch");if(!["public","toolbox","runtime"].includes(String(input.access))||!["service","caller"].includes(String(input.bridge))||!["cli","sdk","mcp","toolbox","runtime"].includes(String(input.source))||input.plugin!==void 0&&(typeof input.plugin!="string"||!/^[a-z][a-z0-9_-]*$/.test(input.plugin))||input.scopeId!==void 0&&(typeof input.scopeId!="string"||input.scopeId.length>256)||input.access!=="public"&&(!input.plugin||input.bridge!=="caller"))throw new Error("Invalid plugin task caller scope");return scope={access:input.access,bridge:input.bridge,source:input.source,...input.plugin?{plugin:String(input.plugin)}:{},...input.scopeId?{scopeId:String(input.scopeId)}:{}},{protocolVersion:5,version:CLIENT_VERSION,host:manager.host,pid:process.pid}}if(!scope)throw new Error("Plugin task connection requires a handshake");if(method==="status")return{protocolVersion:5,version:CLIENT_VERSION,host:manager.host,pid:process.pid};if(method==="diagnose")return host.diagnose(input,scope);if(method==="state.call")return state.call(String(input.plugin),input.input,bridge,input.options);if(method==="model.list")return models.list(input.provider);if(method==="model.capabilities")return(await Promise.resolve().then(()=>(init_pluginModelDefinition(),pluginModelDefinition_exports))).pluginModelCapabilities();if(method==="page.call"){let execution=input.execution;return pages.call(String(input.plugin),input.input,bridge,input.options,execution?{cwd:execution.cwd,environment:execution.environment,signal:disconnected.signal}:void 0)}if(method==="page.event"){if(scope.access!=="runtime")throw new Error("Page events require the browser runtime bridge");return pages.receive(String(input.plugin),input.input,bridge,input.options)}if(method==="start")return manager.start(input,bridge);if(method==="resume")return manager.resume(input,bridge);if(method==="list")return manager.list(scope,input.activeOnly===!0,input.cursor,input.limit);if(method==="shutdown"){if(scope.access!=="public")throw new Error("Tool pages cannot stop the plugin host");return{stopped:!0}}if(typeof input.taskId!="string")throw new Error("Plugin task ID is required");switch(method){case"get":return manager.get(input.taskId,scope);case"checkpoint":return manager.checkpoint(input.taskId,scope);case"cancel":return manager.cancel(input.taskId,scope);case"events":return manager.events(input.taskId,scope,input.cursor,input.waitMs,disconnected.signal);case"result":return manager.resultChunk(input.taskId,scope,input.index);default:throw new Error(`Unknown plugin task method: ${method}`)}};readPluginTaskMessages(socket,message=>{if(message.type==="invoke-result"){let request=pending.get(message.id);if(!request)return;clearTimeout(request.timer),pending.delete(message.id),message.error?request.reject(pluginExecutionError(message.error)):request.resolve(message.result)}else if(message.type==="request"){if(++requests>64||!message.input||typeof message.input!="object"||Array.isArray(message.input)){socket.destroy(new Error("Invalid or excessive plugin task requests"));return}Promise.resolve().then(()=>handle(message.method,message.input)).then(async result=>{await writePluginTaskMessage(socket,{type:"response",id:message.id,result}),message.method==="shutdown"&&setImmediate(()=>{close().catch(()=>{})})},error2=>writePluginTaskMessage(socket,{type:"response",id:message.id,error:serializePluginExecutionError(error2)})).catch(()=>socket.destroy()).finally(()=>{requests--})}else socket.destroy(new Error("Invalid plugin task message direction"))}),socket.on("error",()=>{}),socket.once("close",()=>{disconnected.abort(),sessions.delete(socket);for(let request of pending.values())clearTimeout(request.timer),request.reject(Object.assign(new Error("The invocation bridge disconnected; external operation status may need reconciliation"),{code:"PLUGIN_TASK_BRIDGE_UNAVAILABLE"}));pending.clear()})});async function close(){return closing??=(async()=>{let servicesClosed=host.close();for(let socket of sessions)socket.destroy();await servicesClosed,await new Promise(resolve7=>server.close(()=>resolve7())),removeRecordIfPid(paths.lease,process.pid)&&process.platform!=="win32"&&rmSync14(paths.socket,{force:!0})})(),closing}try{process.platform!=="win32"&&rmSync14(paths.socket,{force:!0}),await new Promise((resolve7,reject)=>{server.once("error",reject),server.listen(paths.socket,()=>{server.off("error",reject),resolve7()})}),process.platform!=="win32"&&chmodSync2(paths.socket,384)}catch(error2){throw removeRecordIfPid(paths.lease,process.pid),await host.close(),error2}return{close,host,socketPath:paths.socket}}try{let server=await startPluginHostServer(),close=()=>{server.close().then(()=>process.exit(0))};process.once("SIGTERM",close),process.once("SIGINT",close)}catch(error2){error2.code!=="PLUGIN_TASK_HOST_OWNED"&&process.stderr.write(`${error2 instanceof Error?error2.stack:String(error2)}
1003
988
  `),process.exitCode=error2.code==="PLUGIN_TASK_HOST_OWNED"?0:1}