@mearl/native-host 2.22.4 → 2.22.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +58 -58
- package/dist/plugin-task-host.js +21 -21
- package/dist/plugin-worker.js +19 -19
- package/package.json +9 -9
package/dist/plugin-task-host.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __mearlCreateRequire } from 'node:module'; const require = __mearlCreateRequire(import.meta.url);
|
|
2
|
-
var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};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[]}}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";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 init_command=__esm({"../daemon-core/dist/command.js"(){"use strict"}});var init_dist=__esm({"../daemon-core/dist/index.js"(){"use strict";init_process();init_paths();init_registry();init_log();init_daemon();init_command()}});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_plugin_tasks=__esm({"../client/src/generated/plugin-tasks.ts"(){"use strict"}});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"],["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);/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)?$/.test(value.name)||invalid("name");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,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 BRIDGE_STYLES,APP_BRIDGE_BEHAVIORS,BEHAVIORS,init_app_profile_definition=__esm({"../client/src/generated/app-profile-definition.ts"(){"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)}});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_toolbox_icon=__esm({"../client/src/generated/toolbox-icon.ts"(){"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){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,APP_PROFILE_NAMES,TAB_ID_REQUIRED_ACTIONS,TAB_ID_REQUIRED_ACTION_SET,PAGE_ACT_ACTIONS,EXTENSION_BROWSER_ACTIONS,BROWSER_CAPABILITY_ACTIONS,init_browser_action_protocol=__esm({"../client/src/generated/browser-action-protocol.ts"(){"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","tmall","alipay","koubei","taobao-tj","taobao-live","xianyu","etao","eleme","damai","btrip","amap","qianwen","lingyou","didi","easybike"];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 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_browser_action_protocol();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 与可用观察或最小快照核验,避免重复提交。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:"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:["仅用于非 BUC 请求;BUC 接口使用 mearl buc,不手工传 Token、DPoP 或 Ticket。","body 不能与 formData/files 组合;bodyFile 以原始字节发送,不包 multipart boundary,不能用于 GET/HEAD。","bodyFile.filePath 属于 native-host,最大 40 MiB;base64 解码后最大 7 MiB。multipart 不手工设置 Content-Type,由 Mearl 生成 boundary。","filePath 属于 native-host 所在机器;无法引用远端路径时用 base64。BUC 上传的路径属于插件执行宿主。"],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[] | "mearl-services" | { presets?: ["mearl-services"]; domains?: string[] }',description:"从控制浏览器复制 Cookie:可传域名数组、Mearl 登录态预设,或组合预设与额外域名"}],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:'开 tab 即注入 App 客户端环境与 JSBridge;档案名同 set_app_profile,如 "fliggy"。需要 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://market.m.taobao.com/app/trip/rx-home/pages/home","appProfile":"fliggy"}'`,`tab_open --payload '{"url":"https://market.m.taobao.com/app/trip/rx-home/pages/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":"edith_switch_br.rx-vehicle-search_home","domain":"taobao.com"}'`,`get_cookie --payload '{"tabId":12345,"name":"tracknick","url":"https://www.taobao.com/","domain":"taobao.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":"edith_switch_br.rx-vehicle-search_home","value":"3.6.63","domain":"taobao.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。在非 BUC send_request 报域权限缺失,或 set_rule 提示缺少域名权限时申请;BUC 不使用浏览器域权限。","弹窗等待用户选择,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('"',""")}">${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)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};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[]}}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";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 npmExecEnvironment(env=process.env){return Object.fromEntries(Object.entries(env).filter(([key2])=>key2.toLowerCase()!=="npm_config_package"))}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 init_command=__esm({"../daemon-core/dist/command.js"(){"use strict"}});var init_dist=__esm({"../daemon-core/dist/index.js"(){"use strict";init_process();init_paths();init_registry();init_log();init_daemon();init_command()}});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_plugin_tasks=__esm({"../client/src/generated/plugin-tasks.ts"(){"use strict"}});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","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"],["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);/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)?$/.test(value.name)||invalid("name");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,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 BRIDGE_STYLES,APP_BRIDGE_BEHAVIORS,BEHAVIORS,init_app_profile_definition=__esm({"../client/src/generated/app-profile-definition.ts"(){"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)}});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_toolbox_icon=__esm({"../client/src/generated/toolbox-icon.ts"(){"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){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,APP_PROFILE_NAMES,TAB_ID_REQUIRED_ACTIONS,TAB_ID_REQUIRED_ACTION_SET,PAGE_ACT_ACTIONS,EXTENSION_BROWSER_ACTIONS,BROWSER_CAPABILITY_ACTIONS,init_browser_action_protocol=__esm({"../client/src/generated/browser-action-protocol.ts"(){"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","tmall","alipay","koubei","taobao-tj","taobao-live","xianyu","etao","eleme","damai","btrip","amap","qianwen","lingyou","didi","easybike"];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 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_browser_action_protocol();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 与可用观察或最小快照核验,避免重复提交。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:"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:["仅用于非 BUC 请求;BUC 接口使用 mearl buc,不手工传 Token、DPoP 或 Ticket。","body 不能与 formData/files 组合;bodyFile 以原始字节发送,不包 multipart boundary,不能用于 GET/HEAD。","bodyFile.filePath 属于 native-host,最大 40 MiB;base64 解码后最大 7 MiB。multipart 不手工设置 Content-Type,由 Mearl 生成 boundary。","filePath 属于 native-host 所在机器;无法引用远端路径时用 base64。BUC 上传的路径属于插件执行宿主。"],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[] | "mearl-services" | { presets?: ["mearl-services"]; domains?: string[] }',description:"从控制浏览器复制 Cookie:可传域名数组、Mearl 登录态预设,或组合预设与额外域名"}],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:'开 tab 即注入 App 客户端环境与 JSBridge;档案名同 set_app_profile,如 "fliggy"。需要 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://market.m.taobao.com/app/trip/rx-home/pages/home","appProfile":"fliggy"}'`,`tab_open --payload '{"url":"https://market.m.taobao.com/app/trip/rx-home/pages/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":"edith_switch_br.rx-vehicle-search_home","domain":"taobao.com"}'`,`get_cookie --payload '{"tabId":12345,"name":"tracknick","url":"https://www.taobao.com/","domain":"taobao.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":"edith_switch_br.rx-vehicle-search_home","value":"3.6.63","domain":"taobao.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。在非 BUC send_request 报域权限缺失,或 set_rule 提示缺少域名权限时申请;BUC 不使用浏览器域权限。","弹窗等待用户选择,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(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('"',""")}">${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,8 +604,8 @@ 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(([
|
|
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,version])=>!isAbsolute2(path8)||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(([path8,version])=>!isAbsolute2(path8)||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 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_app_profile_definition();init_toolbox_icon();init_commands();init_pluginPageBundle();init_pluginSource();RESERVED_NAMES=new Set(["check","run","help","connector_list","capture_checkpoint","plugin","plugins"]),PluginError=class extends Error{constructor(code,message,options){super(`${code}: ${message}`,options);this.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()}});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_plugin_pages=__esm({"../client/src/generated/plugin-pages.ts"(){"use strict";pattern=/^(https?|\*):\/\/(\*|\*\.[a-z0-9.-]+|[a-z0-9.-]+|localhost)(:\d+)?(\/[^#]*)$/i}});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_pluginExecution=__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_pluginExecution();init_pluginExecutorProtocol();init_pluginProcessTree();init_dist()}});import{existsSync as existsSync3,lstatSync,renameSync as renameSync4}from"node:fs";import{join as join8}from"node:path";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 readFileSync8,readSync as readSync2,readdirSync as readdirSync6,rmSync as rmSync7,statSync as statSync6}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_plugin_tasks();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}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(readFileSync8(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=statSync6(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=statSync6(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(statSync6(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_browser_action_protocol();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_dist2=__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==="send_mtop_request")return Math.max(fallback,Math.ceil(((data.timeout??1e4)+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_browser_action_protocol();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_types=__esm({"../provider/dist/types.js"(){"use strict";init_protocol()}});var PROVIDER_ACTIONS,providerActionSet,init_provider_actions=__esm({"../provider/dist/generated/provider-actions.js"(){"use strict";PROVIDER_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","set_mock","get_mocks","set_rule","get_rules","send_request","send_mtop_request","browser_release","page_screenshot","tab_open","tab_close","tab_list","tab_group","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_runtime","page_inspect","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_frames","set_device_emulation","set_app_profile","set_timezone","get_cookie","set_cookie","request_domain_permission","run_actions","page_download"],providerActionSet=new Set(PROVIDER_ACTIONS)}});var init_provider_runtime=__esm({"../provider/dist/provider-runtime.js"(){"use strict";init_types();init_provider_actions()}});import{existsSync as existsSync5,readFileSync as readFileSync9,renameSync as renameSync7,rmSync as rmSync8,statSync as statSync7,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(readFileSync9(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_types();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_provider_actions();init_provider_runtime();init_registry2();init_types();init_protocol();MAX_REQUEST_BYTES=16*1024*1024}});var init_dist3=__esm({"../provider/dist/index.js"(){"use strict";init_types();init_protocol();init_provider_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(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 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(`
|
|
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_app_profile_definition();init_toolbox_icon();init_commands();init_pluginPageBundle();init_pluginSource();RESERVED_NAMES=new Set(["check","run","help","connector_list","capture_checkpoint","plugin","plugins"]),PluginError=class extends Error{constructor(code,message,options){super(`${code}: ${message}`,options);this.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()}});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_plugin_pages=__esm({"../client/src/generated/plugin-pages.ts"(){"use strict";pattern=/^(https?|\*):\/\/(\*|\*\.[a-z0-9.-]+|[a-z0-9.-]+|localhost)(:\d+)?(\/[^#]*)$/i}});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_pluginExecution=__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_pluginExecution();init_pluginExecutorProtocol();init_pluginProcessTree();init_dist()}});import{existsSync as existsSync3,lstatSync,renameSync as renameSync4}from"node:fs";import{join as join8}from"node:path";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 readFileSync8,readSync as readSync2,readdirSync as readdirSync6,rmSync as rmSync7,statSync as statSync6}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_plugin_tasks();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}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(readFileSync8(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=statSync6(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=statSync6(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(statSync6(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_browser_action_protocol();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_dist2=__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==="send_mtop_request")return Math.max(fallback,Math.ceil(((data.timeout??1e4)+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_browser_action_protocol();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_types=__esm({"../provider/dist/types.js"(){"use strict";init_protocol()}});var PROVIDER_ACTIONS,providerActionSet,init_provider_actions=__esm({"../provider/dist/generated/provider-actions.js"(){"use strict";PROVIDER_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","set_mock","get_mocks","set_rule","get_rules","send_request","send_mtop_request","browser_release","page_screenshot","tab_open","tab_close","tab_list","tab_group","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_runtime","page_inspect","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_frames","set_device_emulation","set_app_profile","set_timezone","get_cookie","set_cookie","request_domain_permission","run_actions","page_download"],providerActionSet=new Set(PROVIDER_ACTIONS)}});var init_provider_runtime=__esm({"../provider/dist/provider-runtime.js"(){"use strict";init_types();init_provider_actions()}});import{existsSync as existsSync5,readFileSync as readFileSync9,renameSync as renameSync7,rmSync as rmSync8,statSync as statSync7,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(readFileSync9(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_types();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_provider_actions();init_provider_runtime();init_registry2();init_types();init_protocol();MAX_REQUEST_BYTES=16*1024*1024}});var init_dist3=__esm({"../provider/dist/index.js"(){"use strict";init_types();init_protocol();init_provider_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(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 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(`
|
|
609
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==="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")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,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)}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)}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){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)&&!(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):invokeViaLegacy(action,data,timeoutSec,transport,controlSource,!0)}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){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,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)+`
|
|
610
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(`
|
|
611
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(`
|
|
@@ -615,33 +615,33 @@ button, input, select, textarea { font: inherit; }
|
|
|
615
615
|
`)}function formatNoMatchError(selector,browsers){let available=browsers.length?browsers.map(b=>` - ${describeBrowser(b)}`).join(`
|
|
616
616
|
`):" (当前没有已连接的浏览器)";return[`未找到匹配 "${selector}" 的浏览器。`,"当前已连接的浏览器:",available,"","用 `mearl browser_list` 查看完整列表;可用 browserId 或名称匹配。"].join(`
|
|
617
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_dist3();init_runtime();init_fileRefs();init_browserRegistry();init_actionTimeouts();init_browser_action_protocol();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 readFileSync10}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(readFileSync10(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_plugin_pages()}});import{readFileSync as readFileSync11,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=readFileSync11(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_app_profile_definition();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(`
|
|
619
|
-
`)}displayWidth(str){return
|
|
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_plugin_pages()}});import{readFileSync as readFileSync11,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=readFileSync11(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_app_profile_definition();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,`
|
|
620
620
|
`+" ".repeat(termWidth+spacerWidth)),itemIndentStr+paddedTerm+" ".repeat(spacerWidth)+formattedDescription.replace(/\n/g,`
|
|
621
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(`
|
|
622
|
-
`)}}}});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}
|
|
623
623
|
- a short flag is a single dash and a single character
|
|
624
624
|
- either use a single dash and a single character (for a short flag)
|
|
625
625
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):shortFlagExp.test(unsupportedFlag)?new Error(`${baseError}
|
|
626
626
|
- too many short flags`):longFlagExp.test(unsupportedFlag)?new Error(`${baseError}
|
|
627
627
|
- too many long flags`):new Error(`${baseError}
|
|
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}}
|
|
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?`
|
|
629
629
|
(Did you mean one of ${similar.join(", ")}?)`:similar.length===1?`
|
|
630
|
-
(Did you mean ${similar[0]}?)`:""}var
|
|
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
|
|
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
|
|
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();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
|
|
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(
|
|
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
|
|
635
635
|
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
636
636
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
637
|
-
- ${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,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}
|
|
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}
|
|
638
638
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
639
639
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
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",
|
|
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=
|
|
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.
|
|
642
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}
|
|
643
|
-
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}}});var
|
|
644
|
-
`),closeSync7(descriptor),()=>rmSync10(lockPath,{force:!0})}catch(error2){if(descriptor!==void 0&&closeSync7(descriptor),error2.code!=="EEXIST")throw error2}if(findPluginRegistration(name))return()=>{};try{if(Date.now()-statSync8(lockPath).mtimeMs>INSTALL_LOCK_STALE_MS){rmSync10(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(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/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;if(progress?.(`正在安装官方插件 ${name}...`),await installWithSetup(name),!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}});function findOfficialPlugin(name){return Object.hasOwn(OFFICIAL_PLUGINS,name)?OFFICIAL_PLUGINS[name]:void 0}function listOfficialPluginNames(setup){return Object.entries(OFFICIAL_PLUGINS).filter(([,definition])=>setup===void 0||"setup"in definition&&definition.setup===setup).map(([name])=>name)}var OFFICIAL_PLUGIN_MANAGER,OFFICIAL_PLUGINS,init_officialPluginCatalog=__esm({"../client/src/plugins/officialPluginCatalog.ts"(){"use strict";OFFICIAL_PLUGIN_MANAGER="@mearl/setup:official",OFFICIAL_PLUGINS={buc:{description:"使用 BUC 身份请求内部服务",installArgs:["trip/mearl","--skill","buc-request","--yes"],skill:"buc-request"},authx:{description:"使用 AuthX 身份请求内部服务",installArgs:["trip/mearl","--skill","authx-request","--yes"],skill:"authx-request"},tdbank:{description:"查询、借用和切换 TDBank 测试账号",installArgs:["trip/mearl","--skill","tdbank-account","--yes"],setup:"alibaba",skill:"tdbank-account"}}}});import{closeSync as closeSync7,mkdirSync as mkdirSync7,openSync as openSync7,rmSync as rmSync10,statSync as statSync8,writeFileSync as writeFileSync7}from"node:fs";import{join as join15}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 join15(pluginDirectory(),`.official-${name}.install.lock`)}async function acquireInstallLock(name){let directory=pluginDirectory();mkdirSync7(directory,{recursive:!0,mode:448});let lockPath=installLockPath(name),deadline=Date.now()+INSTALL_TIMEOUT_MS;for(;;){let descriptor;try{return descriptor=openSync7(lockPath,"wx",384),writeFileSync7(descriptor,`${process.pid}
|
|
644
|
+
`),closeSync7(descriptor),()=>rmSync10(lockPath,{force:!0})}catch(error2){if(descriptor!==void 0&&closeSync7(descriptor),error2.code!=="EEXIST")throw error2}if(findPluginRegistration(name))return()=>{};try{if(Date.now()-statSync8(lockPath).mtimeMs>INSTALL_LOCK_STALE_MS){rmSync10(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(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/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;if(progress?.(`正在安装官方插件 ${name}...`),await installWithSetup(name),!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)}
|
|
645
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`
|
|
646
646
|
import asyncio
|
|
647
647
|
import importlib.util
|
|
@@ -978,11 +978,11 @@ except BaseException as error:
|
|
|
978
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,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(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,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:(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,description,toolbox,pageRuntime,stateStorage,taskRecovery,appProfiles,profileSources,version:readPluginVersion(entry),commandHelp(namespace){return publicCommands().map(({command,signature})=>` ${namespace} ${signature} ${command.description()}`).join(`
|
|
979
979
|
`)},help(namespace,name2){let selected=name2?[find(name2)]:publicCommands();if(!selected.length){let location=toolbox?`请在 Mearl ${toolbox.displayMode==="popup"?"Popup":"工具箱"} 中打开「${toolbox.title}」使用。`:"此插件未提供公开 CLI 命令。";return`${namespace} 未提供 CLI 命令。
|
|
980
980
|
${location}`}let examples=selected.flatMap(({examples:examples2})=>examples2);return["用法:",...selected.map(({command,signature})=>` ${namespace} ${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_commander();init_commands();init_officialPluginCatalog();init_officialPluginInstaller();init_pluginRegistry();init_pluginSource();init_pythonPlugin();init_pluginExecution();init_pluginExecutor();init_pluginTasks();init_pluginRuntimeCleanup();init_pluginPages();init_pluginRegistry();init_officialPluginCatalog();init_pluginState();init_pluginModels();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_dist2();init_actionTimeouts();init_browser_action_protocol();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_pluginModels(),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==="plugin_state"){let{PluginStateClient:PluginStateClient2}=await Promise.resolve().then(()=>(init_pluginState(),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_pluginModels(),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_pluginPages(),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(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,...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"})+`
|
|
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_pluginExecution();init_pluginExecutor();init_pluginTasks();init_pluginRuntimeCleanup();init_pluginPages();init_pluginRegistry();init_officialPluginCatalog();init_pluginState();init_pluginModels();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_dist2();init_actionTimeouts();init_browser_action_protocol();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_pluginModels(),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==="plugin_state"){let{PluginStateClient:PluginStateClient2}=await Promise.resolve().then(()=>(init_pluginState(),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_pluginModels(),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_pluginPages(),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(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,...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
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
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
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 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,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 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 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||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)}
|
|
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 readFileSync16}from"node:fs";async function runCodexModel(request,context,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync16(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){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"&¶ms?.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"&¶ms?.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"&¶ms?.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 readFileSync17}from"node:fs";async function listCodexModels(signal,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync17(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();var PLUGIN_HOST_BUILD_ID="83323695c8ac2e39755494d27cb70be47d162c502111d32a1fc6d6be71981f18";init_dist();init_plugin_tasks();init_pluginHostPaths();import{randomUUID as randomUUID12}from"node:crypto";import{createServer}from"node:net";import{chmodSync as chmodSync2,rmSync as rmSync13}from"node:fs";init_dist();init_plugin_tasks();init_plugin_pages();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_pluginExecution();init_pluginExecutor();init_pluginExecutorProtocol();import{createHash as createHash9,randomUUID as randomUUID10}from"node:crypto";import{EventEmitter as EventEmitter2}from"node:events";import{isAbsolute as isAbsolute6,join as join16,relative as relative5,sep as sep4}from"node:path";import{realpathSync as realpathSync4,statSync as statSync9}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 readFileSync7,readdirSync as readdirSync5,realpathSync as realpathSync2,renameSync as renameSync5,rmSync as rmSync5,statSync as statSync5,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 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=statSync5(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=readFileSync7(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_plugin_tasks();init_unified();init_commands();function error(code,message){return Object.assign(new Error(message),{code})}function digest(value){return createHash9("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(join16(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()}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(!isAbsolute6(request.cwd)||!statSync9(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}_${randomUUID10()}`,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","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||createHash9("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 readFileSync14}from"node:fs";import{join as join18}from"node:path";init_pluginHostPaths();init_pluginHostFiles();import{createHash as createHash10}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync13,readdirSync as readdirSync7,statSync as statSync10,rmSync as rmSync12}from"node:fs";import{join as join17,sep as sep5}from"node:path";function fail(code,message){throw Object.assign(new Error(message),{code})}function schemaHash(definition){return createHash10("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}memory=new Map;memoryBytes=0;memoryRevisionFloor=0;clearMemory(){this.memory.clear(),this.memoryBytes=0,this.memoryRevisionFloor=0}valueBytes=new WeakMap;memorySize(document){let bytes=Buffer.byteLength(JSON.stringify({...document,entries:{}})),count=0;for(let[name,entry]of Object.entries(document.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,document,bytes=this.memorySize(document)){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,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=createHash10("sha256").update(namespace.scope).digest("hex");return join17(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 document=saved?{...saved.document,entries:{...saved.document.entries}}:JSON.parse(readFileSync13(file,"utf8"));if(!Number.isSafeInteger(document.revision)||!Number.isSafeInteger(document.schemaVersion)||!document.entries||!Array.isArray(document.commits))throw new Error("Invalid state document");if(definition.storage!=="persistent"){let entries=Object.fromEntries(Object.entries(document.entries).filter(([,entry])=>entry.expiresAt===void 0||entry.expiresAt>this.now()));Object.keys(entries).length!==Object.keys(document.entries).length&&(document.entries=entries,document.revision++,definition.storage==="memory"?this.saveMemory(file,document):writePluginHostFile(file,JSON.stringify(document)))}return document}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(document,name,now){let entry=Object.hasOwn(document.entries,name)?document.entries[name]:void 0;return entry&&(entry.expiresAt===void 0||entry.expiresAt>now)?{key:name,exists:!0,version:`v:${entry.revision}`,value:document.storage==="memory"?structuredClone(entry.value):entry.value,...entry.expiresAt===void 0?{}:{expiresAt:entry.expiresAt}}:{key:name,exists:!1,version:`a:${document.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=join17(this.directory,installationId),memorySuffix=`-${createHash10("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=`-${createHash10("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)&&rmSync12(join17(directory,name),{force:!0})}prune(skipFile){for(let[path8,saved]of this.memory){let document={...saved.document,entries:{...saved.document.entries}};for(let[key2,entry]of Object.entries(document.entries))entry.expiresAt!==void 0&&entry.expiresAt<=this.now()&&delete document.entries[key2];Object.keys(document.entries).length!==Object.keys(saved.document.entries).length&&(document.revision++,this.saveMemory(path8,document))}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(join17(this.directory,installation))){if(!name.endsWith(".json"))continue;let file=join17(this.directory,installation,name);if(file!==skipFile)try{let document=JSON.parse(readFileSync13(file,"utf8"));if(document.storage!=="cache")continue;let entries=Object.fromEntries(Object.entries(document.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>this.now()));if(Object.keys(entries).length===Object.keys(document.entries).length)continue;writePluginHostFile(file,JSON.stringify({...document,revision:document.revision+1,entries}))}catch(error2){console.error(`Cannot maintain plugin cache ${file}:`,error2)}}}get(namespace,definition,name){key(name);let document=this.read(namespace,definition);return{...this.entry(document,name,this.now()),revision:document.revision,schemaVersion:document.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 document=this.read(namespace,definition),now=this.now(),entries=names.map(name=>this.entry(document,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:document.revision,schemaVersion:document.schemaVersion}}list(namespace,definition,input={}){let document=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!==document.revision&&fail("PLUGIN_STATE_CONFLICT","State list changed; restart pagination");let now=this.now(),candidates=Object.keys(document.entries).sort().filter(name=>(input.cursor===void 0||name>input.cursor)&&this.entry(document,name,now).exists),entries=[],bytes=0;for(let name of candidates){let entry=this.entry(document,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:document.revision,schemaVersion:document.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 document=this.read(namespace,definition),hash=createHash10("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=document.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:document.schemaVersion,reused:!0}}input.expectedRevision!==void 0&&input.expectedRevision!==document.revision&&fail("PLUGIN_STATE_CONFLICT","Collection revision changed"),document.schemaVersion===definition.schemaVersion&&document.schemaHash!==schemaHash(definition)&&fail("PLUGIN_STATE_SCHEMA_VERSION_REQUIRED","Changing the state schema or storage policy requires a new schemaVersion"),document.schemaVersion>definition.schemaVersion&&fail("PLUGIN_STATE_SCHEMA_DOWNGRADE","An older plugin revision cannot write a newer state schema"),document.schemaVersion!==definition.schemaVersion&&(input.migrateFromVersion!==document.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!==document.schemaVersion&&fail("PLUGIN_STATE_CONFLICT","State schema changed");let now=this.now(),names=new Set,entries=Object.fromEntries(Object.entries(document.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>now).map(([name,value])=>[name,{...value}])),revision=document.revision+1;if(Number.isSafeInteger(revision)||fail("PLUGIN_STATE_QUOTA","State revision limit reached"),document.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(document,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}let json2=JSON.stringify(operation.value);(json2===void 0||Buffer.byteLength(json2)>256*1024)&&fail("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&&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}:{}}}let commit={revision,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries,commits:[...document.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(join17(this.directory,namespace.installationId))){let path8=join17(this.directory,namespace.installationId,name);path8!==file&&name.endsWith(".json")&&(total+=statSync10(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(join17(this.directory,namespace.installationId))){let path8=join17(this.directory,namespace.installationId,name);path8!==file&&name.endsWith(".json")&&(total+=statSync10(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()}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(readFileSync14(join18(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 createHash11,randomUUID as randomUUID11}from"node:crypto";import{EventEmitter as EventEmitter3}from"node:events";import{readFileSync as readFileSync15,statSync as statSync11}from"node:fs";import{isAbsolute as isAbsolute7,join as join19}from"node:path";init_plugin();init_unified();init_pluginHostPaths();init_pluginExecutorProtocol();init_plugin_tasks();init_plugin_pages();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()}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,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(readFileSync15(join19(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||!isAbsolute7(execution.cwd)||!statSync11(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_${randomUUID11()}`,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=randomUUID11(),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=randomUUID11();try{await this.invoke(record2,{operation:"message_begin",transferId,bytes:json2.length,sha256:createHash11("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||createHash11("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}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 createHash12}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}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=createHash12("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 join20}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?join20(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,buildId:PLUGIN_HOST_BUILD_ID,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:randomUUID12(),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,buildId:PLUGIN_HOST_BUILD_ID,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,buildId:PLUGIN_HOST_BUILD_ID,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"&&rmSync13(paths.socket,{force:!0})})(),closing}try{process.platform!=="win32"&&rmSync13(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)}
|
|
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 readFileSync16}from"node:fs";async function runCodexModel(request,context,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync16(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){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"&¶ms?.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"&¶ms?.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"&¶ms?.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 readFileSync17}from"node:fs";async function listCodexModels(signal,provider=new CodexAgentProvider(()=>{},JSON.parse(readFileSync17(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();var PLUGIN_HOST_BUILD_ID="025a1d4dd51ebda523c759b5e82c3de635a9016d5680ff189ffc27f60009c405";init_dist();init_plugin_tasks();init_pluginHostPaths();import{randomUUID as randomUUID12}from"node:crypto";import{createServer}from"node:net";import{chmodSync as chmodSync2,rmSync as rmSync13}from"node:fs";init_dist();init_plugin_tasks();init_plugin_pages();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_pluginExecution();init_pluginExecutor();init_pluginExecutorProtocol();import{createHash as createHash9,randomUUID as randomUUID10}from"node:crypto";import{EventEmitter}from"node:events";import{isAbsolute as isAbsolute6,join as join16,relative as relative5,sep as sep4}from"node:path";import{realpathSync as realpathSync4,statSync as statSync9}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 readFileSync7,readdirSync as readdirSync5,realpathSync as realpathSync2,renameSync as renameSync5,rmSync as rmSync5,statSync as statSync5,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=statSync5(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=readFileSync7(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_plugin_tasks();init_unified();init_commands();function error(code,message){return Object.assign(new Error(message),{code})}function digest(value){return createHash9("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(join16(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()}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(!isAbsolute6(request.cwd)||!statSync9(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}_${randomUUID10()}`,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","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||createHash9("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 readFileSync14}from"node:fs";import{join as join18}from"node:path";init_pluginHostPaths();init_pluginHostFiles();import{createHash as createHash10}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync13,readdirSync as readdirSync7,statSync as statSync10,rmSync as rmSync12}from"node:fs";import{join as join17,sep as sep5}from"node:path";function fail(code,message){throw Object.assign(new Error(message),{code})}function schemaHash(definition){return createHash10("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}memory=new Map;memoryBytes=0;memoryRevisionFloor=0;clearMemory(){this.memory.clear(),this.memoryBytes=0,this.memoryRevisionFloor=0}valueBytes=new WeakMap;memorySize(document){let bytes=Buffer.byteLength(JSON.stringify({...document,entries:{}})),count=0;for(let[name,entry]of Object.entries(document.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,document,bytes=this.memorySize(document)){let total=this.memoryBytes-(this.memory.get(path7)?.bytes??0)+bytes;(total>128*1024*1024||!this.memory.has(path7)&&this.memory.size>=512)&&fail("PLUGIN_STATE_QUOTA","Memory state exceeds its host limits"),this.memory.set(path7,{document,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=createHash10("sha256").update(namespace.scope).digest("hex");return join17(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[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 document=saved?{...saved.document,entries:{...saved.document.entries}}:JSON.parse(readFileSync13(file,"utf8"));if(!Number.isSafeInteger(document.revision)||!Number.isSafeInteger(document.schemaVersion)||!document.entries||!Array.isArray(document.commits))throw new Error("Invalid state document");if(definition.storage!=="persistent"){let entries=Object.fromEntries(Object.entries(document.entries).filter(([,entry])=>entry.expiresAt===void 0||entry.expiresAt>this.now()));Object.keys(entries).length!==Object.keys(document.entries).length&&(document.entries=entries,document.revision++,definition.storage==="memory"?this.saveMemory(file,document):writePluginHostFile(file,JSON.stringify(document)))}return document}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(document,name,now){let entry=Object.hasOwn(document.entries,name)?document.entries[name]:void 0;return entry&&(entry.expiresAt===void 0||entry.expiresAt>now)?{key:name,exists:!0,version:`v:${entry.revision}`,value:document.storage==="memory"?structuredClone(entry.value):entry.value,...entry.expiresAt===void 0?{}:{expiresAt:entry.expiresAt}}:{key:name,exists:!1,version:`a:${document.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=join17(this.directory,installationId),memorySuffix=`-${createHash10("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=`-${createHash10("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)&&rmSync12(join17(directory,name),{force:!0})}prune(skipFile){for(let[path7,saved]of this.memory){let document={...saved.document,entries:{...saved.document.entries}};for(let[key2,entry]of Object.entries(document.entries))entry.expiresAt!==void 0&&entry.expiresAt<=this.now()&&delete document.entries[key2];Object.keys(document.entries).length!==Object.keys(saved.document.entries).length&&(document.revision++,this.saveMemory(path7,document))}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(join17(this.directory,installation))){if(!name.endsWith(".json"))continue;let file=join17(this.directory,installation,name);if(file!==skipFile)try{let document=JSON.parse(readFileSync13(file,"utf8"));if(document.storage!=="cache")continue;let entries=Object.fromEntries(Object.entries(document.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>this.now()));if(Object.keys(entries).length===Object.keys(document.entries).length)continue;writePluginHostFile(file,JSON.stringify({...document,revision:document.revision+1,entries}))}catch(error2){console.error(`Cannot maintain plugin cache ${file}:`,error2)}}}get(namespace,definition,name){key(name);let document=this.read(namespace,definition);return{...this.entry(document,name,this.now()),revision:document.revision,schemaVersion:document.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 document=this.read(namespace,definition),now=this.now(),entries=names.map(name=>this.entry(document,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:document.revision,schemaVersion:document.schemaVersion}}list(namespace,definition,input={}){let document=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!==document.revision&&fail("PLUGIN_STATE_CONFLICT","State list changed; restart pagination");let now=this.now(),candidates=Object.keys(document.entries).sort().filter(name=>(input.cursor===void 0||name>input.cursor)&&this.entry(document,name,now).exists),entries=[],bytes=0;for(let name of candidates){let entry=this.entry(document,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:document.revision,schemaVersion:document.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 document=this.read(namespace,definition),hash=createHash10("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=document.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:document.schemaVersion,reused:!0}}input.expectedRevision!==void 0&&input.expectedRevision!==document.revision&&fail("PLUGIN_STATE_CONFLICT","Collection revision changed"),document.schemaVersion===definition.schemaVersion&&document.schemaHash!==schemaHash(definition)&&fail("PLUGIN_STATE_SCHEMA_VERSION_REQUIRED","Changing the state schema or storage policy requires a new schemaVersion"),document.schemaVersion>definition.schemaVersion&&fail("PLUGIN_STATE_SCHEMA_DOWNGRADE","An older plugin revision cannot write a newer state schema"),document.schemaVersion!==definition.schemaVersion&&(input.migrateFromVersion!==document.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!==document.schemaVersion&&fail("PLUGIN_STATE_CONFLICT","State schema changed");let now=this.now(),names=new Set,entries=Object.fromEntries(Object.entries(document.entries).filter(([,value])=>value.expiresAt===void 0||value.expiresAt>now).map(([name,value])=>[name,{...value}])),revision=document.revision+1;if(Number.isSafeInteger(revision)||fail("PLUGIN_STATE_QUOTA","State revision limit reached"),document.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(document,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}let json2=JSON.stringify(operation.value);(json2===void 0||Buffer.byteLength(json2)>256*1024)&&fail("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&&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}:{}}}let commit={revision,schemaVersion:definition.schemaVersion,schemaHash:schemaHash(definition),storage:definition.storage,scope:namespace.scope,entries,commits:[...document.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(join17(this.directory,namespace.installationId))){let path7=join17(this.directory,namespace.installationId,name);path7!==file&&name.endsWith(".json")&&(total+=statSync10(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(join17(this.directory,namespace.installationId))){let path7=join17(this.directory,namespace.installationId,name);path7!==file&&name.endsWith(".json")&&(total+=statSync10(path7).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()}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(readFileSync14(join18(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 createHash11,randomUUID as randomUUID11}from"node:crypto";import{EventEmitter as EventEmitter2}from"node:events";import{readFileSync as readFileSync15,statSync as statSync11}from"node:fs";import{isAbsolute as isAbsolute7,join as join19}from"node:path";init_plugin();init_unified();init_pluginHostPaths();init_pluginExecutorProtocol();init_plugin_tasks();init_plugin_pages();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()}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(readFileSync15(join19(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||!isAbsolute7(execution.cwd)||!statSync11(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_${randomUUID11()}`,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=randomUUID11(),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=randomUUID11();try{await this.invoke(record2,{operation:"message_begin",transferId,bytes:json2.length,sha256:createHash11("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||createHash11("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}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 createHash12}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}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=createHash12("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 join20}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?join20(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,buildId:PLUGIN_HOST_BUILD_ID,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:randomUUID12(),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,buildId:PLUGIN_HOST_BUILD_ID,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,buildId:PLUGIN_HOST_BUILD_ID,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"&&rmSync13(paths.socket,{force:!0})})(),closing}try{process.platform!=="win32"&&rmSync13(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)}
|
|
988
988
|
`),process.exitCode=error2.code==="PLUGIN_TASK_HOST_OWNED"?0:1}
|