@mearl/native-host 2.22.2 → 2.22.4
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 +22 -22
- package/dist/plugin-task-host.js +5 -5
- package/dist/plugin-worker.js +4 -4
- package/package.json +8 -8
package/dist/plugin-task-host.js
CHANGED
|
@@ -615,7 +615,7 @@ 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({"../../../../../Library/pnpm/store/v10/links/@/commander/15.0.0/9bd77ae8231d200f24068f3a3c0041c8f45139e569eecf1914d5eb9201dc6e22/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({"../../../../../Library/pnpm/store/v10/links/@/commander/15.0.0/9bd77ae8231d200f24068f3a3c0041c8f45139e569eecf1914d5eb9201dc6e22/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({"../../../../../Library/pnpm/store/v10/links/@/commander/15.0.0/9bd77ae8231d200f24068f3a3c0041c8f45139e569eecf1914d5eb9201dc6e22/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(`
|
|
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
619
|
`)}displayWidth(str){return stripVTControlCharacters(str).length}styleTitle(str){return str}styleUsage(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word==="[command]"?this.styleSubcommandText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleCommandText(word)).join(" ")}styleCommandDescription(str){return this.styleDescriptionText(str)}styleOptionDescription(str){return this.styleDescriptionText(str)}styleSubcommandDescription(str){return this.styleDescriptionText(str)}styleArgumentDescription(str){return this.styleDescriptionText(str)}styleDescriptionText(str){return str}styleOptionTerm(str){return this.styleOptionText(str)}styleSubcommandTerm(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleSubcommandText(word)).join(" ")}styleArgumentTerm(str){return this.styleArgumentText(str)}styleOptionText(str){return str}styleArgumentText(str){return str}styleSubcommandText(str){return str}styleCommandText(str){return str}padWidth(cmd,helper){return Math.max(helper.longestOptionTermLength(cmd,helper),helper.longestGlobalOptionTermLength(cmd,helper),helper.longestSubcommandTermLength(cmd,helper),helper.longestArgumentTermLength(cmd,helper))}preformatted(str){return/\n[^\S\r\n]/.test(str)}formatItem(term,termWidth,description,helper){let itemIndentStr=" ".repeat(2);if(!description)return itemIndentStr+term;let paddedTerm=term.padEnd(termWidth+term.length-helper.displayWidth(term)),spacerWidth=2,remainingWidth=(this.helpWidth??80)-termWidth-spacerWidth-2,formattedDescription;return remainingWidth<this.minWidthToWrap||helper.preformatted(description)?formattedDescription=description:formattedDescription=helper.boxWrap(description,remainingWidth).replace(/\n/g,`
|
|
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(`
|
|
@@ -625,9 +625,9 @@ ${itemIndentStr}`)}boxWrap(str,width){if(width<this.minWidthToWrap)return str;le
|
|
|
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}}var Option,DualOptions,init_option=__esm({"
|
|
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}}var Option,DualOptions,init_option=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js"(){init_error();Option=class{constructor(flags,description){this.flags=flags,this.description=description||"",this.required=flags.includes("<"),this.optional=flags.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(flags),this.mandatory=!1;let optionFlags=splitOptionFlags(flags);this.short=optionFlags.shortFlag,this.long=optionFlags.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}preset(arg){return this.presetArg=arg,this}conflicts(names){return this.conflictsWith=this.conflictsWith.concat(names),this}implies(impliedOptionValues){let newImplied=impliedOptionValues;return typeof impliedOptionValues=="string"&&(newImplied={[impliedOptionValues]:!0}),this.implied=Object.assign(this.implied||{},newImplied),this}env(name){return this.envVar=name,this}argParser(fn){return this.parseArg=fn,this}makeOptionMandatory(mandatory=!0){return this.mandatory=!!mandatory,this}hideHelp(hide=!0){return this.hidden=!!hide,this}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?camelcase(this.name().replace(/^no-/,"")):camelcase(this.name())}helpGroup(heading){return this.helpGroupHeading=heading,this}is(arg){return this.short===arg||this.long===arg}isBoolean(){return!this.required&&!this.optional&&!this.negate}},DualOptions=class{constructor(options){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,options.forEach(option=>{option.negate?this.negativeOptions.set(option.attributeName(),option):this.positiveOptions.set(option.attributeName(),option)}),this.negativeOptions.forEach((value,key2)=>{this.positiveOptions.has(key2)&&this.dualOptions.add(key2)})}valueFromOption(value,option){let optionKey=option.attributeName();if(!this.dualOptions.has(optionKey))return!0;let preset=this.negativeOptions.get(optionKey).presetArg,negativeValue=preset!==void 0?preset:!1;return option.negate===(negativeValue===value)}}}});function editDistance(a,b){if(Math.abs(a.length-b.length)>3)return Math.max(a.length,b.length);let d=[];for(let 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;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 init_suggestSimilar=__esm({"
|
|
630
|
+
(Did you mean ${similar[0]}?)`:""}var init_suggestSimilar=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js"(){}});import{EventEmitter}from"node:events";import childProcess from"node:child_process";import path5 from"node:path";import fs5 from"node:fs";import process2 from"node:process";import{stripVTControlCharacters as stripVTControlCharacters2}from"node:util";function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process2.env.NO_COLOR||process2.env.FORCE_COLOR==="0"||process2.env.FORCE_COLOR==="false")return!1;if(process2.env.FORCE_COLOR||process2.env.CLICOLOR_FORCE!==void 0)return!0}var Command,init_command2=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js"(){init_argument();init_error();init_help();init_option();init_suggestSimilar();Command=class _Command extends EventEmitter{constructor(name){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=name||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:str=>process2.stdout.write(str),writeErr:str=>process2.stderr.write(str),outputError:(str,write)=>write(str),getOutHelpWidth:()=>process2.stdout.isTTY?process2.stdout.columns:void 0,getErrHelpWidth:()=>process2.stderr.isTTY?process2.stderr.columns:void 0,getOutHasColors:()=>useColor()??(process2.stdout.isTTY&&process2.stdout.hasColors?.()),getErrHasColors:()=>useColor()??(process2.stderr.isTTY&&process2.stderr.hasColors?.()),stripColor:str=>stripVTControlCharacters2(str)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(sourceCommand){return this._outputConfiguration=sourceCommand._outputConfiguration,this._helpOption=sourceCommand._helpOption,this._helpCommand=sourceCommand._helpCommand,this._helpConfiguration=sourceCommand._helpConfiguration,this._exitCallback=sourceCommand._exitCallback,this._storeOptionsAsProperties=sourceCommand._storeOptionsAsProperties,this._combineFlagAndOptionalValue=sourceCommand._combineFlagAndOptionalValue,this._allowExcessArguments=sourceCommand._allowExcessArguments,this._enablePositionalOptions=sourceCommand._enablePositionalOptions,this._showHelpAfterError=sourceCommand._showHelpAfterError,this._showSuggestionAfterError=sourceCommand._showSuggestionAfterError,this}_getCommandAndAncestors(){let result=[];for(let command=this;command;command=command.parent)result.push(command);return result}command(nameAndArgs,actionOptsOrExecDesc,execOpts){let desc=actionOptsOrExecDesc,opts=execOpts;typeof desc=="object"&&desc!==null&&(opts=desc,desc=null),opts=opts||{};let[,name,args]=nameAndArgs.match(/([^ ]+) *(.*)/),cmd=this.createCommand(name);return desc&&(cmd.description(desc),cmd._executableHandler=!0),opts.isDefault&&(this._defaultCommandName=cmd._name),cmd._hidden=!!(opts.noHelp||opts.hidden),cmd._executableFile=opts.executableFile||null,args&&cmd.arguments(args),this._registerCommand(cmd),cmd.parent=this,cmd.copyInheritedSettings(this),desc?this:cmd}createCommand(name){return new _Command(name)}createHelp(){return Object.assign(new Help,this.configureHelp())}configureHelp(configuration){return configuration===void 0?this._helpConfiguration:(this._helpConfiguration=configuration,this)}configureOutput(configuration){return configuration===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...configuration},this)}showHelpAfterError(displayHelp=!0){return typeof displayHelp!="string"&&(displayHelp=!!displayHelp),this._showHelpAfterError=displayHelp,this}showSuggestionAfterError(displaySuggestion=!0){return this._showSuggestionAfterError=!!displaySuggestion,this}addCommand(cmd,opts){if(!cmd._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
631
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 Argument(name,description)}argument(name,description,parseArg,defaultValue){let argument=this.createArgument(name,description);return typeof parseArg=="function"?argument.default(defaultValue).argParser(parseArg):argument.default(parseArg),this.addArgument(argument),this}arguments(names){return names.trim().split(/ +/).forEach(detail=>{this.argument(detail)}),this}addArgument(argument){let previousArgument=this.registeredArguments.slice(-1)[0];if(previousArgument?.variadic)throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);if(argument.required&&argument.defaultValue!==void 0&&argument.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);return this.registeredArguments.push(argument),this}helpCommand(enableOrNameAndArgs,description){if(typeof enableOrNameAndArgs=="boolean")return this._addImplicitHelpCommand=enableOrNameAndArgs,enableOrNameAndArgs&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let nameAndArgs=enableOrNameAndArgs??"help [command]",[,helpName,helpArgs]=nameAndArgs.match(/([^ ]+) *(.*)/),helpDescription=description??"display help for command",helpCommand=this.createCommand(helpName);return helpCommand.helpOption(!1),helpArgs&&helpCommand.arguments(helpArgs),helpDescription&&helpCommand.description(helpDescription),this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,(enableOrNameAndArgs||description)&&this._initCommandGroup(helpCommand),this}addHelpCommand(helpCommand,deprecatedDescription){return typeof helpCommand!="object"?(this.helpCommand(helpCommand,deprecatedDescription),this):(this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,this._initCommandGroup(helpCommand),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(event,listener){let allowedValues=["preSubcommand","preAction","postAction"];if(!allowedValues.includes(event))throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
632
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 CommanderError(exitCode,code,message)),process2.exit(exitCode)}action(fn){let listener=args=>{let expectedArgsCount=this.registeredArguments.length,actionArgs=args.slice(0,expectedArgsCount);return this._storeOptionsAsProperties?actionArgs[expectedArgsCount]=this:actionArgs[expectedArgsCount]=this.opts(),actionArgs.push(this),fn.apply(this,actionArgs)};return this._actionHandler=listener,this}createOption(flags,description){return new Option(flags,description)}_callParseArg(target,value,previous,invalidArgumentMessage){try{return target.parseArg(value,previous)}catch(err){if(err.code==="commander.invalidArgument"){let message=`${invalidArgumentMessage} ${err.message}`;this.error(message,{exitCode:err.exitCode,code:err.code})}throw err}}_registerOption(option){let matchingOption=option.short&&this._findOption(option.short)||option.long&&this._findOption(option.long);if(matchingOption){let matchingFlag=option.long&&this._findOption(option.long)?option.long:option.short;throw new Error(`Cannot add option '${option.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
633
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 Option)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let option=this.createOption(flags,description);if(option.makeOptionMandatory(!!config.mandatory),typeof fn=="function")option.default(defaultValue).argParser(fn);else if(fn instanceof RegExp){let regex=fn;fn=(val,def)=>{let m=regex.exec(val);return m?m[0]:def},option.default(defaultValue).argParser(fn)}else option.default(fn);return this.addOption(option)}option(flags,description,parseArg,defaultValue){return this._optionEx({},flags,description,parseArg,defaultValue)}requiredOption(flags,description,parseArg,defaultValue){return this._optionEx({mandatory:!0},flags,description,parseArg,defaultValue)}combineFlagAndOptionalValue(combine=!0){return this._combineFlagAndOptionalValue=!!combine,this}allowUnknownOption(allowUnknown=!0){return this._allowUnknownOption=!!allowUnknown,this}allowExcessArguments(allowExcess=!0){return this._allowExcessArguments=!!allowExcess,this}enablePositionalOptions(positional=!0){return this._enablePositionalOptions=!!positional,this}passThroughOptions(passThrough=!0){return this._passThroughOptions=!!passThrough,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(storeAsProperties=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!storeAsProperties,this}getOptionValue(key2){return this._storeOptionsAsProperties?this[key2]:this._optionValues[key2]}setOptionValue(key2,value){return this.setOptionValueWithSource(key2,value,void 0)}setOptionValueWithSource(key2,value,source){return this._storeOptionsAsProperties?this[key2]=value:this._optionValues[key2]=value,this._optionValueSources[key2]=source,this}getOptionValueSource(key2){return this._optionValueSources[key2]}getOptionValueSourceWithGlobals(key2){let source;return this._getCommandAndAncestors().forEach(cmd=>{cmd.getOptionValueSource(key2)!==void 0&&(source=cmd.getOptionValueSource(key2))}),source}_prepareUserArgs(argv,parseOptions){if(argv!==void 0&&!Array.isArray(argv))throw new Error("first parameter to parse must be array or undefined");if(parseOptions=parseOptions||{},argv===void 0&&parseOptions.from===void 0){process2.versions?.electron&&(parseOptions.from="electron");let execArgv=process2.execArgv??[];(execArgv.includes("-e")||execArgv.includes("--eval")||execArgv.includes("-p")||execArgv.includes("--print"))&&(parseOptions.from="eval")}argv===void 0&&(argv=process2.argv),this.rawArgs=argv.slice();let userArgs;switch(parseOptions.from){case void 0:case"node":this._scriptPath=argv[1],userArgs=argv.slice(2);break;case"electron":process2.defaultApp?(this._scriptPath=argv[1],userArgs=argv.slice(2)):userArgs=argv.slice(1);break;case"user":userArgs=argv.slice(0);break;case"eval":userArgs=argv.slice(1);break;default:throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",userArgs}parse(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return this._parseCommand([],userArgs),this}async parseAsync(argv,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv,parseOptions);return await this._parseCommand([],userArgs),this}_prepareForParse(){this._savedState===null?(this.options.filter(option=>option.negate&&option.defaultValue===void 0&&this.getOptionValue(option.attributeName())===void 0).forEach(option=>{let positiveLongFlag=option.long.replace(/^--no-/,"--");this._findOption(positiveLongFlag)||this.setOptionValueWithSource(option.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
@@ -640,7 +640,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
640
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",received=receivedArgs.length,forSubcommand=this.parent?` for '${this.name()}'`:"",details=receivedArgs.join(", "),message=`error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
|
|
641
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=path5.basename(filename,path5.extname(filename)),this}executableDir(path8){return path8===void 0?this._executableDir:(this._executableDir=path8,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error2=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error2?(baseWrite=str=>this._outputConfiguration.writeErr(str),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=str=>this._outputConfiguration.writeOut(str),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error:error2,write:str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(flags??"-h, --help",description??"display help for command"),(flags||description)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this._initOptionGroup(option),this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process2.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
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 program,init_commander=__esm({"
|
|
643
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}}});var program,init_commander=__esm({"../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js"(){init_argument();init_command2();init_error();init_help();init_option();program=new Command}});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
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)}
|
|
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
|
|
@@ -984,5 +984,5 @@ ${location}`}let examples=selected.flatMap(({examples:examples2})=>examples2);re
|
|
|
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
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
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="e5c7f6cfb7a597a523293c0ea2929b4970aa9eb86e7aeb672f85a37c317bc258";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)}
|
|
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)}
|
|
988
988
|
`),process.exitCode=error2.code==="PLUGIN_TASK_HOST_OWNED"?0:1}
|