@kyun.si/codex-hongguo 0.0.23 → 0.0.25

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.
@@ -81,7 +81,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
81
81
  `:`[${i[u]}\r
82
82
  ]`;continue}n+=i[u],i[u]==="\\"?o=!0:a&&i[u]==="]"?a=!1:!a&&i[u]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return n}function sp(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Pe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:i,...n}=ap(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:i,...n}=op(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function dx(e,t){if(t.mapStrategy==="record")return sp(e,t);let r=G(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Pe(t),i=G(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Pe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function fx(e){let t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function px(e){return e.target==="openAi"?void 0:{not:Pe({...e,currentPath:[...e.currentPath,"not"]})}}function mx(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var hu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gx(e,t){if(t.target==="openApi3")return hx(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in hu&&(!i._def.checks||!i._def.checks.length))){let i=r.reduce((n,o)=>{let a=hu[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=r.reduce((n,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(i.length===r.length){let n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return hx(e,t)}var hx=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>G(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function vx(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:hu[e.innerType._def.typeName],nullable:!0}:{type:[hu[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let i=G(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let r=G(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Ax(e,t){let r={type:"number"};if(!e.checks)return r;for(let i of e.checks)switch(i.kind){case"int":r.type="integer",ey(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?le(r,"minimum",i.value,i.message,t):le(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?le(r,"maximum",i.value,i.message,t):le(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",i.value,i.message,t));break;case"multipleOf":le(r,"multipleOf",i.value,i.message,t);break}return r}function yx(e,t){let r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(let s in o){let u=o[s];if(u===void 0||u._def===void 0)continue;let c=M4(u);c&&r&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);let l=G(u._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,c||n.push(s))}n.length&&(i.required=n);let a=U4(e,t);return a!==void 0&&(i.additionalProperties=a),i}function U4(e,t){if(e.catchall._def.typeName!=="ZodNever")return G(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function M4(e){try{return e.isOptional()}catch{return!0}}var _x=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return G(e.innerType._def,t);let r=G(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Pe(t)},r]}:Pe(t)};var bx=(e,t)=>{if(t.pipeStrategy==="input")return G(e.in._def,t);if(t.pipeStrategy==="output")return G(e.out._def,t);let r=G(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=G(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function $x(e,t){return G(e.type._def,t)}function Ix(e,t){let i={type:"array",uniqueItems:!0,items:G(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&le(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&le(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function wx(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>G(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:G(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>G(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Ex(e){return{not:Pe(e)}}function xx(e){return Pe(e)}var Sx=(e,t)=>G(e.innerType._def,t);var kx=(e,t,r)=>{switch(t){case T.ZodString:return ap(e,r);case T.ZodNumber:return Ax(e,r);case T.ZodObject:return yx(e,r);case T.ZodBigInt:return rx(e,r);case T.ZodBoolean:return nx();case T.ZodDate:return ty(e,r);case T.ZodUndefined:return Ex(r);case T.ZodNull:return mx(r);case T.ZodArray:return tx(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return gx(e,r);case T.ZodIntersection:return ux(e,r);case T.ZodTuple:return wx(e,r);case T.ZodRecord:return sp(e,r);case T.ZodLiteral:return cx(e,r);case T.ZodEnum:return sx(e);case T.ZodNativeEnum:return fx(e);case T.ZodNullable:return vx(e,r);case T.ZodOptional:return _x(e,r);case T.ZodMap:return dx(e,r);case T.ZodSet:return Ix(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return $x(e,r);case T.ZodNaN:case T.ZodNever:return px(r);case T.ZodEffects:return ax(e,r);case T.ZodAny:return Pe(r);case T.ZodUnknown:return xx(r);case T.ZodDefault:return ox(e,r);case T.ZodBranded:return op(e,r);case T.ZodReadonly:return Sx(e,r);case T.ZodCatch:return ix(e,r);case T.ZodPipeline:return bx(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(i=>{})(t)}};function G(e,t,r=!1){let i=t.seen.get(e);if(t.override){let s=t.override?.(e,t,i,r);if(s!==YE)return s}if(i&&!r){let s=L4(i,t);if(s!==void 0)return s}let n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);let o=kx(e,e.typeName,t),a=typeof o=="function"?G(o(),t):o;if(a&&F4(e,t,a),t.postProcess){let s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var L4=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ip(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Pe(t)):t.$refStrategy==="seen"?Pe(t):void 0}},F4=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var iy=(e,t)=>{let r=ex(t),i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,l])=>({...u,[c]:G(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Pe(r)}),{}):void 0,n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=G(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Pe(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function Z4(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function oy(e,t){return xr(e)?ri(e,{target:Z4(t?.target),io:t?.pipeStrategy??"input"}):iy(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function ay(e){let r=_n(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=Do(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function sy(e,t){let r=yn(e,t);if(!r.success)throw r.error;return r.data}var Q4=6e4,up=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Lf,r=>{this._oncancel(r)}),this.setNotificationHandler(Zf,r=>{this._onprogress(r)}),this.setRequestHandler(Ff,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qf,async(r,i)=>{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new j(L.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Vf,async(r,i)=>{let n=async()=>{let o=r.params.taskId;if(!await this._taskStore.getTask(o,i.sessionId))throw new j(L.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){let u=s.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(u);else{let d=u,m=new j(d.error.code,d.error.message,d.error.data);l(m)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new j(L.InvalidParams,`Task not found: ${o}`);if(!xn(a.status))return await this._waitForTaskUpdate(o,i.signal,i.sessionId),await n();if(xn(a.status)){let s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o,i.sessionId),{...s,_meta:{...s._meta,[En]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Hf,async(r,i)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new j(L.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Jf,async(r,i)=>{try{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new j(L.InvalidParams,`Task not found: ${r.params.taskId}`);if(xn(n.status))throw new j(L.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId,i.sessionId);let o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new j(L.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof j?n:new j(L.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),j.fromError(L.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),au(o)||ME(o)?this._onresponse(o):MA(o)?this._onrequest(o,a):UE(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let r=j.fromError(L.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of t.values())i(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){let i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[En]?.taskId,a=n?.sessionId,s=this._taskStore,u=!0,c;if(o&&s&&this._taskMessageQueue&&a!==void 0&&(u=!1,c=(async()=>{if(!await s.getTask(o,a))throw new j(L.InvalidParams,`Task not found: ${o}`);u=!0})()),i===void 0){let h={jsonrpc:"2.0",id:t.id,error:{code:L.MethodNotFound,message:"Method not found"}};if(o&&c){let f={type:"error",message:h,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,f,a),()=>n?.send(h)).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},n?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):n?.send(h).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(t.id,l);let d=RE(t.params)?t.params.task:void 0,m=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async h=>{if(l.signal.aborted)return;let f={relatedRequestId:t.id};o&&(f.relatedTask={taskId:o}),await this.notification(h,f)},sendRequest:async(h,f,g)=>{if(l.signal.aborted)throw new j(L.ConnectionClosed,"Request was cancelled");let y={...g,relatedRequestId:t.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});let v=y.relatedTask?.taskId??o;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(h,f,y)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new j(L.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,p)).then(async h=>{if(l.signal.aborted)return;let f={result:h,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},n?.sessionId):await n?.send(f)},async h=>{if(l.signal.aborted)return;let f={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(h.code)?h.code:L.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};o&&this._taskMessageQueue&&u?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},n?.sessionId):await n?.send(f)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===l&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(u){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(u);return}o(i)}_onresponse(t){let r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),au(t))i(t);else{let a=new j(t.error.code,t.error.message,t.error.data);i(a)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(au(t)&&t.result&&typeof t.result=="object"){let a=t.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),au(t))n(t);else{let a=j.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,i){let{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof j?a:new j(L.InternalError,String(a))}}return}let o;try{let a=await this.request(t,Mo,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new j(L.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},xn(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new j(L.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new j(L.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}let u=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof j?a:new j(L.InternalError,String(a))}}}request(t,r,i){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:u}=i??{};return new Promise((c,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){d(v);return}i?.signal?.throwIfAborted();let m=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(p.params={...p.params,task:s}),u&&(p.params={...p.params,_meta:{...p.params?._meta||{},[En]:u}});let h=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));let A=v instanceof j?v:new j(L.RequestTimeout,String(v));l(A)};this._responseHandlers.set(m,v=>{if(!i?.signal?.aborted){if(v instanceof Error)return l(v);try{let A=yn(r,v.result);A.success?c(A.data):l(A.error)}catch(A){l(A)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let f=i?.timeout??Q4,g=()=>h(j.fromError(L.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(m,f,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);let y=u?.taskId;if(y){let v=A=>{let w=this._responseHandlers.get(m);w?w(A):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(A=>{this._cleanupTimeout(m),l(A)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},qf,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Gf,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},ZE,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let i=r?.relatedTask?.taskId;if(i){let s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(s,r).catch(u=>this._onerror(u))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){let i=ay(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{let a=sy(t,n);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let i=ay(t);this._notificationHandlers.set(i,n=>{let o=sy(t,n);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,i??this._transport?.sessionId,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(t,r);for(let n of i)if(n.type==="request"&&MA(n.message)){let o=n.message.id,a=this._requestResolvers.get(o);a?(a(new j(L.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r,i){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t,i);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,a)=>{if(r.aborted){a(new j(L.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),a(new j(L.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{let o=await i.getTask(n,r);if(!o)throw new j(L.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);let s=await i.getTask(n,r);if(s){let u=du.parse({method:"notifications/tasks/status",params:s});await this.notification(u),xn(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{let s=await i.getTask(n,r);if(!s)throw new j(L.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(xn(s.status))throw new j(L.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);let u=await i.getTask(n,r);if(u){let c=du.parse({method:"notifications/tasks/status",params:u});await this.notification(c),xn(u.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}};function Cx(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Dx(e,t){let r={...e};for(let i in t){let n=i,o=t[n];if(o===void 0)continue;let a=r[n];Cx(a)&&Cx(o)?r[n]={...a,...o}:r[n]=o}return r}var Nk=wi(Y_(),1),zk=wi(Tk(),1);function n3(){let e=new Nk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zk.default)(e),e}var Hp=class{constructor(t){this._ajv=t??n3()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return i=>r(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Gp=class{constructor(t){this._server=t}requestStream(t,r,i){return this._server.requestStream(t,r,i)}createMessageStream(t,r){let i=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],a=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,u=s?Array.isArray(s.content)?s.content:[s.content]:[],c=u.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},mu,r)}elicitInputStream(t,r){let i=this._server.getClientCapabilities(),n=t.mode??"form";switch(n){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=n==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:o},Zo,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,i){return this._server.getTaskResult({taskId:t},r,i)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Pk(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Ok(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Jp=class extends up{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(pu.options.map((i,n)=>[i,n])),this.isMessageIgnored=(i,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hp,this.setRequestHandler(ZA,i=>this._oninitialize(i)),this.setNotificationHandler(QA,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(XA,async(i,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=pu.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Gp(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Dx(this._capabilities,t)}setRequestHandler(t,r){let n=_n(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let o=Do(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(u,c)=>{let l=yn(Fo,u);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new j(L.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,m=await Promise.resolve(r(u,c));if(d.task){let h=yn(Mo,m);if(!h.success){let f=h.error instanceof Error?h.error.message:String(h.error);throw new j(L.InvalidParams,`Invalid task creation result: ${f}`)}return h.data}let p=yn(rp,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new j(L.InvalidParams,`Invalid tools/call result: ${h}`)}return p.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Ok(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Pk(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:zE.includes(r)?r:BA,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Mf)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let i=t.messages[t.messages.length-1],n=Array.isArray(i.content)?i.content:[i.content],o=n.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],u=s.some(c=>c.type==="tool_use");if(o){if(n.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==l.size||![...c].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},YA,r):this.request({method:"sampling/createMessage",params:t},mu,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=t;return this.request({method:"elicitation/create",params:n},Zo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:n},Zo,r);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new j(L.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof j?a:new j(L.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},WA,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var jk=Symbol.for("mcp.completable");function ab(e){return!!e&&typeof e=="object"&&jk in e}function Bk(e){return e[jk]?.complete}var Rk;(function(e){e.Completable="McpCompletable"})(Rk||(Rk={}));var Kp=class e{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,i){if(t.length>r)throw new Error(`${i} exceeds maximum length of ${r} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){e.validateLength(t,1e6,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let r=[],i="",n=0,o=0;for(;n<t.length;)if(t[n]==="{"){i&&(r.push(i),i="");let a=t.indexOf("}",n);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>1e4)throw new Error("Template contains too many expressions (max 10000)");let s=t.slice(n+1,a),u=this.getOperator(s),c=s.includes("*"),l=this.getNames(s),d=l[0];for(let m of l)e.validateLength(m,1e6,"Variable name");r.push({name:d,operator:u,names:l,exploded:c}),n=a+1}else i+=t[n],n++;return i&&r.push(i),r}getOperator(t){return["+","#",".","/","?","&"].find(i=>t.startsWith(i))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(i=>i.replace("*","").trim()).filter(i=>i.length>0)}encodeValue(t,r){return e.validateLength(t,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){let a=t.names.map(u=>{let c=r[u];if(c===void 0)return"";let l=Array.isArray(c)?c.map(d=>this.encodeValue(d,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${u}=${l}`}).filter(u=>u.length>0);return a.length===0?"":(t.operator==="?"?"?":"&")+a.join("&")}if(t.names.length>1){let a=t.names.map(s=>r[s]).filter(s=>s!==void 0);return a.length===0?"":a.map(s=>Array.isArray(s)?s[0]:s).join(",")}let i=r[t.name];if(i===void 0)return"";let o=(Array.isArray(i)?i:[i]).map(a=>this.encodeValue(a,t.operator));switch(t.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(t){let r="",i=!1;for(let n of this.parts){if(typeof n=="string"){r+=n;continue}let o=this.expandPart(n,t);o&&((n.operator==="?"||n.operator==="&")&&i?r+=o.replace("?","&"):r+=o,(n.operator==="?"||n.operator==="&")&&(i=!0))}return r}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){let r=[];for(let o of t.names)e.validateLength(o,1e6,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let o=0;o<t.names.length;o++){let a=t.names[o],s=o===0?"\\"+t.operator:"&";r.push({pattern:s+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let i,n=t.name;switch(t.operator){case"":i=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":i="(.+)";break;case".":i="\\.([^/,]+)";break;case"/":i="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:i="([^/]+)"}return r.push({pattern:i,name:n}),r}match(t){e.validateLength(t,1e6,"URI");let r="^",i=[];for(let s of this.parts)if(typeof s=="string")r+=this.escapeRegExp(s);else{let u=this.partToRegExp(s);for(let{pattern:c,name:l}of u)r+=c,i.push({name:l,exploded:s.exploded})}r+="$",e.validateLength(r,1e6,"Generated regex pattern");let n=new RegExp(r),o=t.match(n);if(!o)return null;let a={};for(let s=0;s<i.length;s++){let{name:u,exploded:c}=i[s],l=o[s+1],d=u.replace("*","");c&&l.includes(",")?a[d]=l.split(","):a[d]=l}return a}};var i3=/^[A-Za-z0-9._-]{1,128}$/;function o3(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!i3.test(e)){let r=e.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,n,o)=>o.indexOf(i)===n);return t.push(`Tool name contains invalid characters: ${r.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function a3(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function sb(e){let t=o3(e);return a3(e,t.warnings),t.isValid}var Xp=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,i){let n={taskSupport:"required",...r.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,n,r._meta,i)}};function s3(e,t){let r=0,i=[e];for(;i.length>0;){let n=i.pop();if(!(n===null||typeof n!="object"))if(Array.isArray(n))for(let o of n){if(++r>t)return r;o!==null&&typeof o=="object"&&i.push(o)}else for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;if(++r>t)return r;let a=n[o];a!==null&&typeof a=="object"&&i.push(a)}}return r}function u3(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var Yp=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Jp(t,r),this._maxToolInputElements=u3(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new Xp(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(On(tp)),this.server.assertCanSetRequestHandler(On(Fo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(tp,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let i={name:t,title:r.title,description:r.description,inputSchema:(()=>{let n=Co(r.inputSchema);return n?oy(n,{strictUnions:!0,pipeStrategy:"input"}):c3})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=Co(r.outputSchema);n&&(i.outputSchema=oy(n,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Fo,async(t,r)=>{try{let i=this._registeredTools[t.params.name];if(!i)throw new j(L.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new j(L.InvalidParams,`Tool ${t.params.name} disabled`);let n=!!t.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new j(L.InternalError,`Tool ${t.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new j(L.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&a)return await this.handleAutomaticTaskPolling(i,t,r);let s=await this.validateToolInput(i,t.params.arguments,t.params.name),u=await this.executeToolHandler(i,s,r);return n||await this.validateToolOutput(i,u,t.params.name),u}catch(i){if(i instanceof j&&i.code===L.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,i){if(this._maxToolInputElements!==void 0&&s3(r,this._maxToolInputElements)>this._maxToolInputElements)throw new j(L.InvalidParams,`Invalid arguments for tool ${i}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!t.inputSchema)return;let o=Co(t.inputSchema)??t.inputSchema,a=await sf(o,r??{});if(!a.success){let s="error"in a?a.error:"Unknown error",u=uf(s);throw new j(L.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${u}`)}return a.data}async validateToolOutput(t,r,i){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new j(L.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=Co(t.outputSchema),o=await sf(n,r.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=uf(a);throw new j(L.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(t,r,i){let n=t.handler;if("createTask"in n){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(t.inputSchema){let s=n;return await Promise.resolve(s.createTask(r,a))}else{let s=n;return await Promise.resolve(s.createTask(a))}}if(t.inputSchema){let a=n;return await Promise.resolve(a(r,i))}else{let a=n;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(t,r,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(t,r.params.arguments,r.params.name),o=t.handler,a={...i,taskStore:i.taskStore},s=n?await Promise.resolve(o.createTask(n,a)):await Promise.resolve(o.createTask(a)),u=s.task.taskId,c=s.task,l=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(m=>setTimeout(m,l));let d=await i.taskStore.getTask(u);if(!d)throw new j(L.InternalError,`Task ${u} not found during polling`);c=d}return await i.taskStore.getTaskResult(u)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(On(np)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(np,async t=>{switch(t.params.ref.type){case"ref/prompt":return JE(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return KE(t),this.handleResourceCompletion(t,t.params.ref);default:throw new j(L.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let i=this._registeredPrompts[r.name];if(!i)throw new j(L.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new j(L.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return Vu;let o=_n(i.argsSchema)?.[t.params.argument.name];if(!ab(o))return Vu;let a=Bk(o);if(!a)return Vu;let s=await a(t.params.argument.value,t.params.context);return Mk(s)}async handleResourceCompletion(t,r){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!i){if(this._registeredResources[r.uri])return Vu;throw new j(L.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(t.params.argument.name);if(!n)return Vu;let o=await n(t.params.argument.value,t.params.context);return Mk(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(On(Kf)),this.server.assertCanSetRequestHandler(On(Xf)),this.server.assertCanSetRequestHandler(On(Yf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Kf,async(t,r)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(r);for(let s of a.resources)n.push({...o.metadata,...s})}return{resources:[...i,...n]}}),this.server.setRequestHandler(Xf,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,i])=>({name:r,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(Yf,async(t,r)=>{let i=new URL(t.params.uri),n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new j(L.InvalidParams,`Resource ${i} disabled`);return n.readCallback(i,r)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,r)}throw new j(L.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(On(Wf)),this.server.assertCanSetRequestHandler(On(ep)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Wf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?l3(r.argsSchema):void 0}))})),this.server.setRequestHandler(ep,async(t,r)=>{let i=this._registeredPrompts[t.params.name];if(!i)throw new j(L.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new j(L.InvalidParams,`Prompt ${t.params.name} disabled`);if(i.argsSchema){let n=Co(i.argsSchema),o=await sf(n,t.params.arguments??{});if(!o.success){let u="error"in o?o.error:"Unknown error",c=uf(u);throw new j(L.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,r))}else{let n=i.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...i){let n;typeof i[0]=="object"&&(n=i.shift());let o=i[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(t,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let a=this._createRegisteredResourceTemplate(t,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,i,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(t,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let o=this._createRegisteredResourceTemplate(t,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(t,r,i,n,o){let a={name:t,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(t,r,i,n,o){let a={resourceTemplate:i,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(c=>!!i.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,i,n,o){let a={title:r,description:i,argsSchema:n===void 0?void 0:ni(n),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==t&&(delete this._registeredPrompts[t],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=ni(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,n&&Object.values(n).some(u=>{let c=u instanceof si?u._def?.innerType:u;return ab(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,i,n,o,a,s,u,c){sb(t);let l={title:r,description:i,inputSchema:Uk(n),outputSchema:Uk(o),annotations:a,execution:s,_meta:u,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&sb(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=ni(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=ni(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let i,n,o,a;if(typeof r[0]=="string"&&(i=r.shift()),r.length>1){let u=r[0];if(ub(u))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ub(r[0])&&(a=r.shift());else if(typeof u=="object"&&u!==null){if(Object.values(u).some(c=>typeof c=="object"&&c!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(t,void 0,i,n,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(t,r,i){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:n,description:o,inputSchema:a,outputSchema:s,annotations:u,_meta:c}=r;return this._createRegisteredTool(t,n,o,a,s,u,{taskSupport:"forbidden"},c,i)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let i;typeof r[0]=="string"&&(i=r.shift());let n;r.length>1&&(n=r.shift());let o=r[0],a=this._createRegisteredPrompt(t,void 0,i,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,r,i){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:n,description:o,argsSchema:a}=r,s=this._createRegisteredPrompt(t,n,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Wp=class{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new Kp(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}},c3={type:"object",properties:{}};function Lk(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Fk(e){return"_def"in e||"_zod"in e||Lk(e)}function ub(e){return typeof e!="object"||e===null||Fk(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Lk)}function Uk(e){if(e){if(ub(e))return ni(e);if(!Fk(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function l3(e){let t=_n(e);return t?Object.entries(t).map(([r,i])=>{let n=uw(i),o=cw(i);return{name:r,description:n,required:!o}}):[]}function On(e){let r=_n(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=Do(r);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function Mk(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Vu={completion:{values:[],hasMore:!1}};import Qk from"node:process";var d3=10*1024*1024,em=class{constructor(t){this._maxBufferSize=t?.maxBufferSize??d3}append(t){if((this._buffer?.length??0)+t.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
83
83
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),f3(r)}clear(){this._buffer=void 0}};function f3(e){return LE.parse(JSON.parse(e))}function Zk(e){return JSON.stringify(e)+`
84
- `}var tm=class{constructor(t=Qk.stdin,r=Qk.stdout,i){this._stdin=t,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new em({maxBufferSize:i?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let i=Zk(t);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};import{readFileSync as lQ}from"node:fs";import{join as dQ}from"node:path";var qk={name:"@kyun.si/codex-hongguo",version:"0.0.23",private:!0,license:"MIT",type:"module",engines:{node:">=22.16"},scripts:{"version:patch":"npm version patch --no-git-tag-version",preversion:"node scripts/version.mjs --next",version:"node scripts/version.mjs --sync",prebuild:"node scripts/version.mjs",build:"node scripts/build.mjs",test:"npm run build && node scripts/prepare-media.mjs && node --test test/*.test.mjs",package:"npm run build && node scripts/package.mjs","verify:install":"node scripts/verify-install.mjs","release:publish":"node scripts/publish.mjs"},dependencies:{"@modelcontextprotocol/ext-apps":"1.7.5","@modelcontextprotocol/sdk":"1.32.2","cross-spawn":"7.0.6",fflate:"0.8.3","hls.js":"1.7.4","m3u8-parser":"7.2.1","mpd-parser":"1.4.1",openhongguo:"0.2.0","xz-decompress":"0.2.3",zod:"4.6.7"},devDependencies:{"@types/node":"22.20.5",esbuild:"0.28.2",typescript:"5.9.3"}};import{homedir as m3}from"node:os";import{posix as h3,win32 as g3}from"node:path";import{fileURLToPath as v3}from"node:url";var Rn=v3(new URL("../../",import.meta.url));function Vk({env:e=process.env,home:t=m3(),platform:r=process.platform}={}){let{join:i}=r==="win32"?g3:h3;return e.HONGGUO_DATA_DIR?e.HONGGUO_DATA_DIR:r==="darwin"?i(t,"Library","Application Support","CodexHongguo"):r==="win32"?i(e.LOCALAPPDATA||i(t,"AppData","Local"),"CodexHongguo"):i(e.XDG_DATA_HOME||i(t,".local","share"),"codex-hongguo")}import{DatabaseSync as A3}from"node:sqlite";import{mkdirSync as y3}from"node:fs";import{join as _3}from"node:path";function cb(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(e)}function rm(e={}){let t=[e.thread_id,e.threadId].filter(r=>r!==void 0);return t.length&&t.every(r=>cb(r)&&r===t[0])?t[0]:null}function Hk(e){let t=new Map;for(let{id:r,title:i}of e)if(/^hg-\d{1,32}$/.test(r)&&typeof i=="string"&&i.trim()&&!t.has(r)&&t.set(r,{id:r,title:i}),t.size===48)break;return[...t.values()]}var Hu=class{constructor(t=Vk(),r=!1){r||y3(t,{recursive:!0,mode:448}),this.persistent=!r,this.root=t,this.db=new A3(r?":memory:":_3(t,"player.sqlite")),this.db.exec(`PRAGMA busy_timeout=250; PRAGMA journal_mode=WAL;
84
+ `}var tm=class{constructor(t=Qk.stdin,r=Qk.stdout,i){this._stdin=t,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new em({maxBufferSize:i?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let i=Zk(t);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};import{readFileSync as lQ}from"node:fs";import{join as dQ}from"node:path";var qk={name:"@kyun.si/codex-hongguo",version:"0.0.25",private:!0,license:"MIT",type:"module",engines:{node:">=22.16"},scripts:{"version:patch":"npm version patch --no-git-tag-version",preversion:"node scripts/version.mjs --next",version:"node scripts/version.mjs --sync",prebuild:"node scripts/version.mjs",build:"node scripts/build.mjs",test:"npm run build && node scripts/prepare-media.mjs && node --test test/*.test.mjs",package:"npm run build && node scripts/package.mjs","verify:install":"node scripts/verify-install.mjs","release:publish":"node scripts/publish.mjs"},dependencies:{"@modelcontextprotocol/ext-apps":"1.7.5","@modelcontextprotocol/sdk":"1.32.2","cross-spawn":"7.0.6",fflate:"0.8.3","hls.js":"1.7.4","m3u8-parser":"7.2.1","mpd-parser":"1.4.1",openhongguo:"0.2.0","xz-decompress":"0.2.3",zod:"4.6.7"},devDependencies:{"@types/node":"22.20.5",esbuild:"0.28.2",typescript:"5.9.3"}};import{homedir as m3}from"node:os";import{posix as h3,win32 as g3}from"node:path";import{fileURLToPath as v3}from"node:url";var Rn=v3(new URL("../../",import.meta.url));function Vk({env:e=process.env,home:t=m3(),platform:r=process.platform}={}){let{join:i}=r==="win32"?g3:h3;return e.HONGGUO_DATA_DIR?e.HONGGUO_DATA_DIR:r==="darwin"?i(t,"Library","Application Support","CodexHongguo"):r==="win32"?i(e.LOCALAPPDATA||i(t,"AppData","Local"),"CodexHongguo"):i(e.XDG_DATA_HOME||i(t,".local","share"),"codex-hongguo")}import{DatabaseSync as A3}from"node:sqlite";import{mkdirSync as y3}from"node:fs";import{join as _3}from"node:path";function cb(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(e)}function rm(e={}){let t=[e.thread_id,e.threadId].filter(r=>r!==void 0);return t.length&&t.every(r=>cb(r)&&r===t[0])?t[0]:null}function Hk(e){let t=new Map;for(let{id:r,title:i}of e)if(/^hg-\d{1,32}$/.test(r)&&typeof i=="string"&&i.trim()&&!t.has(r)&&t.set(r,{id:r,title:i}),t.size===48)break;return[...t.values()]}var Hu=class{constructor(t=Vk(),r=!1){r||y3(t,{recursive:!0,mode:448}),this.persistent=!r,this.root=t,this.db=new A3(r?":memory:":_3(t,"player.sqlite")),this.db.exec(`PRAGMA busy_timeout=250; PRAGMA journal_mode=WAL;
85
85
  CREATE TABLE IF NOT EXISTS turn_state (
86
86
  session_id TEXT NOT NULL, turn_id TEXT NOT NULL, submitted_at INTEGER,
87
87
  stop_kind TEXT, interrupted INTEGER NOT NULL DEFAULT 0, stopped INTEGER NOT NULL DEFAULT 0,
@@ -127,7 +127,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
127
127
  WHERE rank=1 ORDER BY updated_at DESC LIMIT ?`).all(i)}removeHistory(t){return this.transaction(()=>(this.db.prepare("DELETE FROM watch_progress WHERE series_id=?").run(t),this.db.prepare("DELETE FROM watch_restart WHERE series_id=?").run(t),{removed:!0}))}writable(){if(!this.persistent)return!1;try{return this.db.exec("UPDATE watch_progress SET updated_at=updated_at WHERE 0"),!0}catch{return!1}}close(){this.db.close()}};import{randomBytes as UF}from"node:crypto";var B=class extends Error{constructor(t,r=400){super(t),this.status=r}};function nm(e){return e instanceof B?e.message:"\u672C\u673A\u670D\u52A1\u6216\u7247\u6E90\u6682\u65F6\u4E0D\u53EF\u8FBE\uFF0C\u8BF7\u91CD\u8BD5"}import{realpathSync as OF}from"node:fs";import{relative as RF,resolve as jF,isAbsolute as BF}from"node:path";var kb=wi(OC(),1);import{accessSync as DF,constants as iD,statSync as TF}from"node:fs";import{homedir as NF}from"node:os";import{posix as zF,win32 as oD}from"node:path";import{createHash as HC,randomUUID as hF}from"node:crypto";import{createReadStream as GC}from"node:fs";import{mkdir as qC,lstat as gF,open as JC,readFile as KC,writeFile as vF,rename as AF,rm as Xu,chmod as yF,stat as VC,unlink as qX,rmdir as VX}from"node:fs/promises";import{lstatSync as _F}from"node:fs";import{homedir as bF}from"node:os";import{posix as XC,win32 as YC}from"node:path";import{spawnSync as $F}from"node:child_process";import{createRequire as H3}from"module";var G3=H3("/"),la,J3,K3;try{la=G3("worker_threads"),J3=la.Worker,K3=la.isMarkedAsUntransferable}catch{}var qt=Uint8Array,ca=Uint16Array,X3=Int32Array,RC=new qt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),jC=new qt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Y3=new qt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),BC=function(e,t){for(var r=new ca(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];for(var n=new X3(r[30]),i=1;i<30;++i)for(var o=r[i];o<r[i+1];++o)n[o]=o-r[i]<<5|i;return{b:r,r:n}},la=BC(RC,2),UC=la.b,W3=la.r;UC[28]=258,W3[258]=28;var MC=BC(jC,0),eF=MC.b,UX=MC.r,$b=new ca(32768);for(ye=0;ye<32768;++ye)Jr=(ye&43690)>>1|(ye&21845)<<1,Jr=(Jr&52428)>>2|(Jr&13107)<<2,Jr=(Jr&61680)>>4|(Jr&3855)<<4,$b[ye]=((Jr&65280)>>8|(Jr&255)<<8)>>1;var Jr,ye,Gu=(function(e,t,r){for(var i=e.length,n=0,o=new ca(t);n<i;++n)e[n]&&++o[e[n]-1];var a=new ca(t);for(n=1;n<t;++n)a[n]=a[n-1]+o[n-1]<<1;var s;if(r){s=new ca(1<<t);var u=15-t;for(n=0;n<i;++n)if(e[n])for(var c=n<<4|e[n],l=t-e[n],d=a[e[n]-1]++<<l,m=d|(1<<l)-1;d<=m;++d)s[$b[d]>>u]=c}else for(s=new ca(i),n=0;n<i;++n)e[n]&&(s[n]=$b[a[e[n]-1]++]>>15-e[n]);return s}),Ju=new qt(288);for(ye=0;ye<144;++ye)Ju[ye]=8;var ye;for(ye=144;ye<256;++ye)Ju[ye]=9;var ye;for(ye=256;ye<280;++ye)Ju[ye]=7;var ye;for(ye=280;ye<288;++ye)Ju[ye]=8;var ye,LC=new qt(32);for(ye=0;ye<32;++ye)LC[ye]=5;var ye;var tF=Gu(Ju,9,1);var rF=Gu(LC,5,1),yb=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},vr=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&r},_b=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},nF=function(e){return(e+7)/8|0},wb=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new qt(e.subarray(t,r))};var iF=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Qt=function(e,t,r){var i=new Error(t||iF[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,Qt),!r)throw i;return i},oF=function(e,t,r,i){var n=e.length,o=i?i.length:0;if(!n||t.f&&!t.l)return r||new qt(0);var a=!r,s=a||t.i!=2,u=t.i;a&&(r=new qt(n*3));var c=function(g0){var v0=r.length;if(g0>v0){var A0=new qt(Math.max(v0*2,g0));A0.set(r),r=A0}},l=t.f||0,d=t.p||0,m=t.b||0,p=t.l,h=t.d,f=t.m,g=t.n,y=n*8;do{if(!p){l=vr(e,d,1);var v=vr(e,d+1,3);if(d+=3,v)if(v==1)p=tF,h=rF,f=9,g=5;else if(v==2){var N=vr(e,d,31)+257,q=vr(e,d+10,15)+4,je=N+vr(e,d+5,31)+1;d+=14;for(var X=new qt(je),Me=new qt(19),Y=0;Y<q;++Y)Me[Y3[Y]]=vr(e,d+Y*3,7);d+=q*3;for(var jt=yb(Me),nn=(1<<jt)-1,Mn=Gu(Me,jt,1),Y=0;Y<je;){var Da=Mn[vr(e,d,nn)];d+=Da&15;var A=Da>>4;if(A<16)X[Y++]=A;else{var Se=0,Je=0;for(A==16?(Je=3+vr(e,d,3),d+=2,Se=X[Y-1]):A==17?(Je=3+vr(e,d,7),d+=3):A==18&&(Je=11+vr(e,d,127),d+=7);Je--;)X[Y++]=Se}}var _c=X.subarray(0,N),on=X.subarray(N);f=yb(_c),g=yb(on),p=Gu(_c,f,1),h=Gu(on,g,1)}else Qt(1);else{var A=nF(d)+4,w=e[A-4]|e[A-3]<<8,S=A+w;if(S>n){u&&Qt(0);break}s&&c(m+w),r.set(e.subarray(A,S),m),t.b=m+=w,t.p=d=S*8,t.f=l;continue}if(d>y){u&&Qt(0);break}}s&&c(m+131072);for(var WT=(1<<f)-1,e1=(1<<g)-1,Rm=d;;Rm=d){var Se=p[_b(e,d)&WT],Ii=Se>>4;if(d+=Se&15,d>y){u&&Qt(0);break}if(Se||Qt(2),Ii<256)r[m++]=Ii;else if(Ii==256){Rm=d,p=null;break}else{var p0=Ii-254;if(Ii>264){var Y=Ii-257,Ta=RC[Y];p0=vr(e,d,(1<<Ta)-1)+UC[Y],d+=Ta}var jm=h[_b(e,d)&e1],Bm=jm>>4;jm||Qt(3),d+=jm&15;var on=eF[Bm];if(Bm>3){var Ta=jC[Bm];on+=_b(e,d)&(1<<Ta)-1,d+=Ta}if(d>y){u&&Qt(0);break}s&&c(m+131072);var m0=m+p0;if(m<on){var h0=o-on,t1=Math.min(on,m0);for(h0+m<0&&Qt(3);m<t1;++m)r[m]=i[h0+m]}for(;m<m0;++m)r[m]=r[m-on]}}t.l=p,t.p=Rm,t.b=m,t.f=l,p&&(l=1,t.m=f,t.d=h,t.n=g)}while(!l);return m!=r.length&&a?wb(r,0,m):r.subarray(0,m)};var aF=new qt(0);var zr=function(e,t){return e[t]|e[t+1]<<8},nr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},bb=function(e,t){return nr(e,t)+nr(e,t+4)*4294967296};function sF(e,t){return oF(e,{i:2},t&&t.out,t&&t.dictionary)}var Ib=typeof TextDecoder<"u"&&new TextDecoder,uF=0;try{Ib.decode(aF,{stream:!0}),uF=1}catch{}var cF=function(e){for(var t="",r=0;;){var i=e[r++],n=(i>127)+(i>223)+(i>239);if(r+n>e.length)return{s:t,r:wb(e,r-1)};n?n==3?(i=((i&15)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,t+=String.fromCharCode(55296|i>>10,56320|i&1023)):n&1?t+=String.fromCharCode((i&31)<<6|e[r++]&63):t+=String.fromCharCode((i&15)<<12|(e[r++]&63)<<6|e[r++]&63):t+=String.fromCharCode(i)}};function lF(e,t){if(t){for(var r="",i=0;i<e.length;i+=16384)r+=String.fromCharCode.apply(null,e.subarray(i,i+16384));return r}else{if(Ib)return Ib.decode(e);var n=cF(e),o=n.s,r=n.r;return r.length&&Qt(8),o}}var dF=function(e,t){return t+30+zr(e,t+26)+zr(e,t+28)},fF=function(e,t,r){var i=zr(e,t+28),n=zr(e,t+30),o=lF(e.subarray(t+46,t+46+i),!(zr(e,t+8)&2048)),a=t+46+i,s=pF(e,a,n,r,nr(e,t+20),nr(e,t+24),nr(e,t+42)),u=s[0],c=s[1],l=s[2];return[zr(e,t+10),u,c,o,a+n+zr(e,t+32),l]},pF=function(e,t,r,i,n,o,a){var s=n==4294967295,u=o==4294967295,c=a==4294967295,l=t+r,d=s+u+c;if(i&&d){for(;t+4<l;t+=4+zr(e,t+2))if(zr(e,t)==1)return[s?bb(e,t+4+8*u):n,u?bb(e,t+4):o,c?bb(e,t+4+8*(u+s)):a,1];i<2&&Qt(13)}return[n,o,a,0]};function FC(e,t){for(var r={},i=e.length-22;nr(e,i)!=101010256;--i)(!i||e.length-i>65558)&&Qt(13);var n=zr(e,i+8);if(!n)return{};var o=nr(e,i+16),a=nr(e,i-20)==117853008;if(a){var s=nr(e,i-12);a=nr(e,s)==101075792,a&&(n=nr(e,s+32),o=nr(e,s+48))}for(var u=t&&t.filter,c=0;c<n;++c){var l=fF(e,o,a),d=l[0],m=l[1],p=l[2],h=l[3],f=l[4],g=l[5],y=dF(e,g);o=f,(!u||u({name:h,size:m,originalSize:p,compression:d}))&&(d?d==8?r[h]=sF(e.subarray(y,y+m),{out:new qt(p)}):Qt(14,"unknown compression type "+d):r[h]=wb(e,y,y+m))}return r}var WC=wi(ZC(),1);var QC={"darwin-arm64":{version:"9.0.2",url:"https://www.osxexperts.net/ffmpeg902arm.zip",format:"zip",entry:"ffmpeg",archiveBytes:22665869,archiveSha256:"07e00300593799005b060c03a99fe648b1edda0f30c36b0c1adafe8e3247e586",binaryBytes:52160568,binarySha256:"762f16b2913b8d3b8fdb8092df12b691053b035b13ae9b88205513c55cb8e71e"},"darwin-x64":{version:"9.0.2",url:"https://evermeet.cx/ffmpeg/ffmpeg-9.0.2.zip",format:"zip",entry:"ffmpeg",archiveBytes:26198325,archiveSha256:"4acc0be580f9b2788029eb7bd4d645ff87968911b0a62aeeb3940d42d54558d5",binaryBytes:80827688,binarySha256:"a45b462cf91ed89148ae218c4577e30896485d7a6792c3673bcf5f823fa01b63"},"linux-x64":{version:"9.0.2-20261031",url:"https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-10-31-12-59/ffmpeg-n9.0.2-39-g7adfbe40dc-linux64-gpl-9.0.tar.xz",format:"tar.xz",entry:"ffmpeg-n9.0.2-39-g7adfbe40dc-linux64-gpl-9.0/bin/ffmpeg",archiveBytes:153175100,archiveSha256:"73e29a56974ae5a651133a04584c7483b21afe941e17dc91d79814a758b608d3"},"linux-arm64":{version:"9.0.2-20261031",url:"https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-10-31-12-59/ffmpeg-n9.0.2-39-g7adfbe40dc-linuxarm64-gpl-9.0.tar.xz",format:"tar.xz",entry:"ffmpeg-n9.0.2-39-g7adfbe40dc-linuxarm64-gpl-9.0/bin/ffmpeg",archiveBytes:128664064,archiveSha256:"6cad88ae5bcec356cfc5d7979a036cc4007128201928a0cf243df3db483276cc"},"win32-x64":{version:"9.0.2-20261031",url:"https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-10-31-12-59/ffmpeg-n9.0.2-39-g7adfbe40dc-win64-gpl-9.0.zip",format:"zip",entry:"ffmpeg-n9.0.2-39-g7adfbe40dc-win64-gpl-9.0/bin/ffmpeg.exe",archiveBytes:195110184,archiveSha256:"693f3e224bc184b40524a62ca47526cfebaf2504414021b92fe75f677ad868b9"}};var da=new Map,om=new Map,IF="@kyun.si/codex-hongguo",lt=()=>Error("\u64AD\u653E\u7EC4\u4EF6\u81EA\u52A8\u51C6\u5907\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u548C\u7F13\u5B58\u76EE\u5F55\u6743\u9650\u540E\u91CD\u8BD5\u5B89\u88C5\u3002"),wF=e=>new Promise(t=>setTimeout(t,e));function eD(e={}){let{env:t=process.env,home:r=bF(),platform:i=process.platform,arch:n=process.arch}=e,o=i==="win32"?YC:XC;if(t.HONGGUO_FFMPEG){if(!o.isAbsolute(t.HONGGUO_FFMPEG))throw lt();return{...e,env:t,platform:i,target:t.HONGGUO_FFMPEG,override:!0}}let a=(e.artifacts||QC)[i+"-"+n];if(!a)throw Error("\u5F53\u524D\u7CFB\u7EDF\u67B6\u6784\u6682\u4E0D\u652F\u6301\u81EA\u52A8\u51C6\u5907\u64AD\u653E\u7EC4\u4EF6\u3002");let s=EF({env:t,home:r,platform:i,paths:o}),u=o.join(s,"runtime","ffmpeg",a.archiveSha256.slice(0,16),i+"-"+n);return{...e,env:t,platform:i,artifact:a,directory:u,target:o.join(u,i==="win32"?"ffmpeg.exe":"ffmpeg")}}function EF({env:e,home:t,platform:r,paths:i}){return e.HONGGUO_RUNTIME_DIR?i.join(e.HONGGUO_RUNTIME_DIR,"codex-hongguo"):r==="darwin"?i.join(t,"Library","Caches","CodexHongguo"):r==="win32"?i.join(e.LOCALAPPDATA||i.join(t,"AppData","Local"),"CodexHongguo","Cache"):i.join(e.XDG_CACHE_HOME||i.join(t,".cache"),"codex-hongguo")}function Sb(e){return eD(e).target}function am(e){try{let t=_F(e);return t.isFile()&&!t.isSymbolicLink()?`${t.size}:${t.mtimeMs}:${t.ctimeMs}`:null}catch{return null}}function tD(e){try{let t=Sb(e);return!!da.get(t)&&da.get(t)===am(t)}catch{return!1}}async function rD(e){let t=HC("sha256");for await(let r of GC(e))t.update(r);return t.digest("hex")}function nD(e,t){return t.probe?t.probe(e):$F(e,["-version"],{stdio:"ignore",timeout:5e3,windowsHide:!0}).status===0}async function xb(e){let{target:t,artifact:r}=e;if(da.get(t)&&da.get(t)===am(t))return!0;try{let i=await gF(t);if(!i.isFile()||i.isSymbolicLink())return!1;if(r){let n=JSON.parse(await KC(t+".json","utf8"));if(n.archiveSha256!==r.archiveSha256||!/^[a-f0-9]{64}$/.test(n.binarySha256)||i.size!==(r.binaryBytes||n.binaryBytes)||await rD(t)!==(r.binarySha256||n.binarySha256))return!1}return nD(t,e)?(da.set(t,am(t)),!0):!1}catch{return!1}}async function xF(e,t,r){let i=new Set(["github.com","release-assets.githubusercontent.com","objects.githubusercontent.com","evermeet.cx","www.osxexperts.net"]),n=AbortSignal.timeout(3e5),o=new URL(e.url),a;for(let l=0;l<=6;l++){if(o.protocol!=="https:"||o.username||o.password||o.port||!i.has(o.hostname))throw lt();if(a=await r(o,{redirect:"manual",signal:n}),![301,302,303,307,308].includes(a.status))break;let d=a.headers.get("location");if(await a.body?.cancel(),!d||l===6)throw lt();o=new URL(d,o)}if(!a.ok||!a.body||Number(a.headers.get("content-length"))>e.archiveBytes)throw await a.body?.cancel(),lt();let s=await JC(t,"wx",384),u=HC("sha256"),c=0;try{for await(let l of a.body){if(c+=l.length,c>e.archiveBytes)throw lt();u.update(l),await s.writeFile(l)}if(c!==e.archiveBytes||u.digest("hex")!==e.archiveSha256)throw lt()}finally{await s.close()}}async function SF(e,t,r){let i=await JC(r,"wx",384);try{if(e.format==="zip"){let m=FC(await KC(t),{filter:p=>p.name===e.entry&&p.originalSize<=(e.binaryBytes||268435456)})[e.entry];if(!m||e.binaryBytes&&m.length!==e.binaryBytes)throw lt();await i.writeFile(m);return}let n=new WC.default.XzReadableStream(kF(t)),o=n.getReader(),a=Buffer.alloc(0),s=0,u=0,c=!1,l=0;try{for(;;){let{value:d,done:m}=await o.read();if(m)break;if(l+=d.length,l>1024*1024*1024)throw lt();for(a=Buffer.concat([a,d]);a.length;)if(s){let p=Math.min(s,a.length);if(c&&await i.writeFile(a.subarray(0,p)),a=a.subarray(p),s-=p,!s&&c)return}else if(u){let p=Math.min(u,a.length);a=a.subarray(p),u-=p}else{if(a.length<512)break;let p=a.subarray(0,512);a=a.subarray(512);let h=(y,v)=>p.subarray(y,v).toString("utf8").split("\0")[0],f=[h(345,500),h(0,100)].filter(Boolean).join("/"),g=parseInt(h(124,136).trim()||"0",8);if(!Number.isSafeInteger(g)||g<0||g>512*1024*1024||(c=f===e.entry,c&&(e.binaryBytes&&g!==e.binaryBytes||g>256*1024*1024||![0,48].includes(p[156]))))throw lt();s=g,u=(512-g%512)%512}}throw lt()}finally{await o.cancel().catch(()=>{})}}finally{await i.close()}}function kF(e){let t=GC(e)[Symbol.asyncIterator]();return new ReadableStream({async pull(r){let{value:i,done:n}=await t.next();n?r.close():r.enqueue(i)},async cancel(){await t.return?.()}})}async function sm(e={}){let t=eD(e);if(await xb(t))return t.target;if(t.override)throw lt();if(om.has(t.target))return om.get(t.target);let r=CF(t).finally(()=>om.delete(t.target));return om.set(t.target,r),r}async function CF(e){let{directory:t,target:r,artifact:i}=e,n=t+".lock",o=Date.now()+42e4;await qC(t,{recursive:!0,mode:448});let a=!1;for(;!a;)try{await qC(n,{mode:448}),a=!0}catch(d){if(d.code!=="EEXIST"||Date.now()>o)throw lt();if(await xb(e))return r;try{Date.now()-(await VC(n)).mtimeMs>6e5&&await Xu(n,{recursive:!0,force:!0})}catch{}await wF(200)}let s=e.platform==="win32"?YC:XC,u=s.basename(r)+"."+hF(),c=s.join(t,u+".archive"),l=s.join(t,u+".part");try{if(await xb(e))return r;await xF(i,c,e.fetchImpl||fetch),await SF(i,c,l);let d=await rD(l);if(i.binarySha256&&d!==i.binarySha256||(await yF(l,493),!nD(l,e)))throw lt();return e.platform==="win32"&&await Xu(r,{force:!0}),await AF(l,r),await vF(r+".json",JSON.stringify({owner:IF,schema:1,archiveSha256:i.archiveSha256,binarySha256:d,binaryBytes:(await VC(r)).size,version:i.version})+`
128
128
  `,{mode:384}),da.set(r,am(r)),r}catch{throw lt()}finally{await Promise.all([Xu(c,{force:!0}),Xu(l,{force:!0}),Xu(n,{recursive:!0,force:!0})])}}var aD=kb.default,PF=kb.default.sync;function sD(e){if(!(!e?.pid||e.exitCode!==null||e.signalCode!==null))if(e.stdin?.destroy(),process.platform==="win32"){let t=oD.join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe");PF(t,["/pid",String(e.pid),"/t","/f"],{stdio:"ignore",timeout:3e3,windowsHide:!0})}else e.kill()}function um(e,t,{env:r=process.env,home:i=NF(),platform:n=process.platform,arch:o=process.arch}={}){if(t)return t;if(e==="ffmpeg")return Sb({env:r,home:i,platform:n,arch:o});let{delimiter:a,dirname:s,join:u,isAbsolute:c,extname:l}=n==="win32"?oD:zF,d=Object.keys(r).find(f=>f.toUpperCase()==="PATH")||"PATH",m=[s(process.execPath),...(r[d]||"").split(a).filter(Boolean).map(f=>f.replace(/^"(.*)"$/,"$1"))];n!=="win32"?m.push("/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin",u(i,".volta/bin"),u(i,".local/bin")):m.push(u(r.APPDATA||u(i,"AppData","Roaming"),"npm"),u(i,".volta","bin"));let p=n!=="win32"||l(e)?[""]:[".exe",".com",".cmd",".bat"],h=m.filter(c).flatMap(f=>p.map(g=>u(f,e+g)));e==="codex"&&n==="darwin"&&h.push("/Applications/Codex.app/Contents/Resources/codex");for(let f of h)try{if(DF(f,n==="win32"?iD.F_OK:iD.X_OK),TF(f).isFile())return f}catch{}return e}var uD=["userPromptSubmit","stop","interrupt"],jn=()=>({status:"unknown",events:uD.map(e=>({event:e,status:"unknown"}))});function cD({command:e=um("codex",process.env.HONGGUO_CODEX),args:t=["app-server"],cwd:r=process.cwd(),timeoutMs:i=8e3,pluginRoot:n=Rn,installedId:o}={}){let a=u=>{try{return OF(u)}catch{return jF(u)}},s=a(n);return new Promise(u=>{let c,l=!1,d="",m=0,p=f=>{l||(l=!0,clearTimeout(h),sD(c),u(f))},h=setTimeout(()=>p(jn()),i);try{c=aD(e,t,{cwd:r,stdio:["pipe","pipe","ignore"],windowsHide:!0}),c.on("error",()=>p(jn())),c.on("exit",()=>p(jn())),c.stdin.on("error",()=>p(jn())),c.stdout.setEncoding("utf8");let f=g=>c.stdin.write(JSON.stringify(g)+`
129
129
  `);c.stdout.on("data",g=>{if(l)return;if(m+=Buffer.byteLength(g),m>2*1024*1024)return p(jn());d+=g;let y;for(;!l&&(y=d.indexOf(`
130
- `))>=0;){let v=d.slice(0,y);d=d.slice(y+1);let A;try{A=JSON.parse(v)}catch{continue}if(A.error&&[1,2].includes(A.id))return p(jn());if(A.id===1&&A.result&&(f({jsonrpc:"2.0",method:"initialized"}),f({jsonrpc:"2.0",id:2,method:"hooks/list",params:{cwds:[r]}})),A.id===2&&Array.isArray(A.result?.data)){let w=A.result.data.flatMap(N=>Array.isArray(N?.hooks)?N.hooks:[]).filter(N=>typeof N?.pluginId=="string"&&N.pluginId.split("@")[0]==="codex-hongguo").filter(N=>{if(typeof N.sourcePath!="string")return!1;if(o)return N.pluginId===o;let q=RF(s,a(N.sourcePath));return q&&!q.startsWith("..")&&!BF(q)});if(!w.length)return p(jn());let S=uD.map(N=>{let q=w.filter(X=>X.eventName===N),je=q.length?q.some(X=>!X.enabled)?"disabled":q.every(X=>["trusted","managed"].includes(X.trustStatus))?"ready":q.some(X=>["untrusted","modified"].includes(X.trustStatus))?"needs_review":"unknown":"missing";return{event:N,status:je}});p({status:S.every(N=>N.status==="ready")?"ready":"needs_attention",events:S})}}}),f({jsonrpc:"2.0",id:1,method:"initialize",params:{clientInfo:{name:"hongguo-setup",version:"1"},capabilities:{experimentalApi:!0}}})}catch{p(jn())}})}var Yu=()=>UF(24).toString("base64url"),Kr=Z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),Nt=Z.string().regex(/^hg-[0-9]{1,32}$/),lD=Z.string().max(4096).optional(),Cb=Z.string().min(1).max(320),dD=Z.number().int().min(0).max(24*3600*1e3),Db={get_run_state:Z.object({turnId:Kr.optional(),playerInstance:Kr.optional(),observeSession:Z.literal(!0).optional()}),set_player_visible:Z.object({instance:Kr,visible:Z.boolean()}),get_waiting_picks:Z.object({turnId:Kr.optional(),inView:Z.literal(!0).optional()}),mark_waiting_picks_shown:Z.object({turnId:Kr.optional()}),get_waiting_status:Z.object({}),dismiss_waiting_picks:Z.object({turnId:Kr.optional()}),browse_waiting_catalog:Z.object({}),select_waiting_pick:Z.object({seriesId:Nt}),activate_waiting_player:Z.object({}),confirm_waiting_playback:Z.object({playbackId:Z.number().int().positive()}),list_sessions:Z.object({}),select_session:Z.object({choice:Kr}),list_series:Z.object({source:Z.literal("hongguo").optional(),preview:Z.literal(!0).optional(),query:Z.string().max(120).optional(),cursor:lD}),get_cover:Z.object({seriesId:Nt}),get_episodes:Z.object({seriesId:Nt,cursor:lD}),get_history:Z.object({seriesId:Nt.optional(),episodeId:Nt.optional()}),save_progress:Z.object({seriesId:Nt,episodeId:Nt,title:Cb,label:Cb,positionMs:dD,durationMs:dD.positive(),reset:Z.literal(!0).optional()}),prepare_playback:Z.object({episodeId:Nt,retry:Z.boolean().optional()}),create_browser_pairing:Z.object({follow:Z.boolean().optional(),turnId:Kr.optional(),seriesId:Nt.optional(),episodeId:Nt.optional(),title:Cb.optional()}),get_health:Z.object({}),get_setup_status:Z.object({}),set_setup_dismissed:Z.object({dismissed:Z.boolean()}),get_preferences:Z.object({}),set_preferences:Z.object({autoPrompt:Z.boolean().optional(),searchTerms:Z.array(Z.string().trim().min(1).max(30)).min(1).max(6).optional(),autoplayNext:Z.boolean().optional(),autoPauseOnFinish:Z.boolean().optional(),autoPlayOnStart:Z.boolean().optional()}),read_panel_chunk:Z.object({episodeId:Nt,stream:Kr,asset:Z.string().max(32),offset:Z.number().int().nonnegative().max(32*1024*1024)}),remove_history:Z.object({seriesId:Nt})},cm=class{constructor(t,r,i=cD){this.store=t,this.catalog=r,this.checkHooks=i,this.panels=new Map}open(t){let r=Yu(),i={sessionId:rm(t),choices:new Map,lastSeen:Date.now()};for(let[n,o]of this.panels)Date.now()-o.lastSeen>12*36e5&&this.panels.delete(n);return i.caller=i.sessionId,this.panels.set(r,i),{panel:r,state:this.store.state(i.sessionId),identified:!!i.sessionId}}openWaiting(t,r){let i=rm(t);if(!i||[t?.turn_id,t?.turnId].some(o=>o!==void 0&&o!==r)||!this.store.claimCard(i,r))return null;let n=this.open(t);return this.panels.get(n.panel).waiting={turnId:r,selected:null,taken:!1},n}async resumePick(){for(let t of this.store.history(void 0,void 0,-1)){if(!Nt.safeParse(t.seriesId).success||!Nt.safeParse(t.episodeId).success)continue;let r={id:t.seriesId,title:t.title};if(t.positionMs<t.durationMs)return{...r,episodeId:t.episodeId,kind:"resume"};try{let i=await this.catalog.nextEpisode(t.seriesId,t.episodeId);if(i)return{...r,...i}}catch{continue}}return null}async waitingPicks(t,r,i,n){if(!n())return{items:[]};let o=this.store.turnPicks(t,r);if(o.length)return{items:o};let[a,s]=await Promise.all([this.catalog.waitingRecommendations().catch(()=>[]),this.resumePick()]);return{items:this.store.allocatePicks(t,r,s,a,i,n)}}panel(t,r){let i=this.panels.get(t);if(!i||Date.now()-i.lastSeen>12*36e5)throw new B("\u8BF7\u91CD\u65B0\u6253\u5F00\u77ED\u5267\u9762\u677F",401);if((r?.thread_id!==void 0||r?.threadId!==void 0)&&rm(r)!==i.caller)throw new B("\u4F1A\u8BDD\u4E0D\u5339\u914D",403);return i.lastSeen=Date.now(),i}async call(t,r,i,n=!1){let o=Db[r]?.strict().safeParse(i);if(!o?.success)throw new B("\u8BF7\u6C42\u53C2\u6570\u65E0\u6548");let a=o.data;switch(r){case"get_waiting_status":case"browse_waiting_catalog":{let s=t.waiting;if(n||!s)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return r==="get_waiting_status"?{visible:this.store.offerable(t.sessionId,s.turnId)}:(s.selected=null,s.taken=!1,s.browsing=!0,s.played=!0,{})}case"dismiss_waiting_picks":{let s=a.turnId??t.waiting?.turnId;if(!t.sessionId||!s||t.waiting&&s!==t.waiting.turnId||n&&t.fixedTurn&&s!==t.fixedTurn||!this.store.state(t.sessionId,s).turnId)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.dismissPicks(t.sessionId,s)}case"get_waiting_picks":case"mark_waiting_picks_shown":{let s=t.waiting,u=a.turnId??s?.turnId;if(!t.sessionId||!u||n&&t.fixedTurn&&u!==t.fixedTurn||s&&a.turnId&&!s.taken)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);let c=()=>a.turnId?this.store.activeTurn(t.sessionId,u)&&this.store.preferences().autoPrompt&&!this.store.picksDismissed(t.sessionId,u):this.store.offerable(t.sessionId,u);return r==="mark_waiting_picks_shown"?this.store.markPicksShown(t.sessionId,u,c):this.waitingPicks(t.sessionId,u,!!a.inView,c)}case"select_waiting_pick":case"confirm_waiting_playback":case"activate_waiting_player":{let s=t.waiting;if(n||!s)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);if(r==="confirm_waiting_playback")return s.playbackId===a.playbackId&&(s.played=!0),{};if(r==="select_waiting_pick"){if(!this.store.offerable(t.sessionId,s.turnId))throw new B("\u8FD9\u6761\u63A8\u8350\u5DF2\u7ED3\u675F");let c=this.store.turnPicks(t.sessionId,s.turnId).find(l=>l.id===a.seriesId);if(!c)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.markPicksShown(t.sessionId,s.turnId,()=>this.store.offerable(t.sessionId,s.turnId)),s.selected=c,s.taken=!1,s.browsing=!1,s.played=!1,s.playbackId=(s.playbackId||0)+1,{}}let u=!!s.selected&&!s.played&&this.store.activeTurn(t.sessionId,s.turnId)&&!this.store.picksDismissed(t.sessionId,s.turnId);return s.taken=!0,s.browsing&&(this.store.dismissPicks(t.sessionId,s.turnId),s.browsing=!1),{pick:s.selected,turnId:s.turnId,play:u,...u?{playbackId:s.playbackId}:{}}}case"set_player_visible":if(t.waiting&&!t.waiting.taken)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.playerVisible(t.sessionId,a.instance,a.visible),{};case"get_run_state":{if(!this.store.persistent)throw new B("\u672C\u673A\u4F1A\u8BDD\u72B6\u6001\u4E0D\u53EF\u8FBE",503);if(this.store.touchPlayer(t.sessionId,a.playerInstance),a.observeSession){if(a.turnId||t.waiting&&!t.waiting.taken)throw new B("\u8BF7\u5148\u6253\u5F00\u64AD\u653E\u5668",403);return{...this.store.state(t.sessionId,n?t.fixedTurn:void 0),preferences:this.store.preferences()}}let s=t.waiting?.turnId??(n?t.fixedTurn:null);if(s&&a.turnId&&a.turnId!==s)throw new B("\u64AD\u653E\u5668\u5DF2\u7ED1\u5B9A\u5176\u4ED6\u56DE\u5408",403);let u=s??a.turnId,c=this.store.state(t.sessionId,u);return t.waiting&&c.state==="submitted"&&!this.store.activeTurn(t.sessionId,u)?{...c,state:"unknown"}:c}case"list_sessions":if(n||t.sessionId)throw new B("\u5F53\u524D\u5165\u53E3\u4E0D\u5141\u8BB8\u9009\u62E9\u5176\u4ED6\u4F1A\u8BDD",403);return t.choices.clear(),{items:this.store.candidates().map(s=>{let u=Yu();return t.choices.set(u,s.session_id),{choice:u,suffix:s.session_id.slice(-8),at:s.at}})};case"select_session":if(n||t.sessionId||!t.choices.has(a.choice))throw new B("\u8BF7\u91CD\u65B0\u9009\u62E9\u4F1A\u8BDD",403);return t.sessionId=t.choices.get(a.choice),t.choices.clear(),this.store.state(t.sessionId);case"list_series":return this.catalog.list(a);case"get_cover":return this.catalog.cover(a.seriesId);case"get_episodes":{let s=await this.catalog.episodes(a);t.allowed??=new Set;for(let u of s.items)u.playable&&t.allowed.add(u.id);return s}case"get_history":return{items:this.store.history(a.seriesId,a.episodeId)};case"remove_history":return this.store.removeHistory(a.seriesId);case"read_panel_chunk":if(n||t.streams?.get(a.episodeId)!==a.stream)throw new B("\u8BF7\u5148\u51C6\u5907\u5F53\u524D\u5206\u96C6",403);return this.catalog.panelMedia.chunk(a.episodeId,a.stream,a.asset,a.offset);case"save_progress":if(!this.store.persistent)throw new B("\u672C\u673A\u8FDB\u5EA6\u76EE\u5F55\u4E0D\u53EF\u5199",503);return this.catalog.cache?.hold(a.episodeId),this.store.save(a);case"prepare_playback":{if(!t.allowed?.has(a.episodeId))throw new B("\u8BF7\u5148\u9009\u62E9\u53EF\u64AD\u653E\u7684\u5206\u96C6",403);!n&&t.playing!==a.episodeId&&(this.catalog.panelMedia?.unpin(t.playing,t),t.streams?.clear(),t.playing=a.episodeId);let s=this.catalog.prepare(a.episodeId,n,!!a.retry);return n&&s.status==="ready"&&t.grants.add(a.episodeId),!n&&s.stream&&(this.catalog.panelMedia.pin(a.episodeId,t),t.streams??=new Map,t.streams.set(a.episodeId,s.stream)),s}case"get_preferences":return this.store.preferences();case"set_preferences":{if(!this.store.persistent)throw new B("\u672C\u673A\u8BBE\u7F6E\u76EE\u5F55\u4E0D\u53EF\u5199",503);let s=this.store.preferences(),u=this.store.setPreferences(a);return JSON.stringify(s.searchTerms)!==JSON.stringify(u.searchTerms)&&(this.catalog.feed=null,this.catalog.refresh=null),u}case"get_health":return this.catalog.ffmpeg||this.catalog.prepareMediaRuntime?.().catch(()=>{}),{runtime:process.version,database:this.store.writable(),ffmpeg:this.catalog.ffmpeg};case"get_setup_status":return this.catalog.ffmpeg||this.catalog.prepareMediaRuntime?.().catch(()=>{}),this.checkingHooks??=this.checkHooks().finally(()=>{this.checkingHooks=null}),{runtime:process.version,database:this.store.writable(),ffmpeg:this.catalog.ffmpeg,dismissed:this.store.setupDismissed(),hooks:await this.checkingHooks};case"set_setup_dismissed":if(!this.store.persistent)throw new B("\u672C\u673A\u8BBE\u7F6E\u76EE\u5F55\u4E0D\u53EF\u5199",503);return this.store.setSetupDismissed(a.dismissed);case"create_browser_pairing":{if(n)throw new B("\u8BF7\u4ECE\u4F1A\u8BDD\u9762\u677F\u6253\u5F00\u5206\u5C4F",403);let s=a.follow&&this.store.state(t.sessionId,a.turnId);if(a.follow&&(!a.turnId||s.state!=="submitted"))throw new B("\u5F53\u524D\u56DE\u5408\u65E0\u6CD5\u7ED1\u5B9A\uFF0C\u8BF7\u9009\u62E9\u624B\u52A8\u64AD\u653E");return this.pair({sessionId:a.follow===!1?null:t.sessionId,fixedTurn:a.follow?a.turnId:null,selection:a.seriesId?{seriesId:a.seriesId,episodeId:a.episodeId,title:a.title}:null})}}}};import{join as qT}from"node:path";import{pathToFileURL as eQ}from"node:url";import{Writable as tQ}from"node:stream";import{pipeline as rQ}from"node:stream/promises";import{spawn as TZ}from"node:child_process";import{createWriteStream as NZ,existsSync as zZ,mkdirSync as RT,readdirSync as PZ,renameSync as OZ,rmSync as Ea,statSync as jT}from"node:fs";import{basename as RZ,dirname as jZ,join as xa}from"node:path";import{randomUUID as BZ}from"node:crypto";import{Transform as UZ}from"node:stream";import{pipeline as MZ}from"node:stream/promises";var zT=wi(yD(),1),PT=wi(TT(),1);import{open as CZ}from"node:fs/promises";import{join as DZ}from"node:path";var Vt=()=>new B("\u8BE5\u5206\u6BB5\u7247\u6E90\u6682\u4E0D\u652F\u6301\uFF0C\u53EF\u91CD\u8BD5\u5176\u4ED6\u7247\u6E90");function NT(e,t){let r=e.mediaGroups?.AUDIO?.[t.attributes?.AUDIO]||{},i=Object.values(r);return i.find(n=>n.default)||i[0]}async function c0(e,t,r=0){if(r>3)throw Vt();let i=await t(e,256*1024),n=i.bytes.toString("utf8").trimStart();if(n.startsWith("#EXTM3U")){let p=new zT.Parser;p.push(n),p.end();let h=p.manifest;if(!h.playlists?.length)return[{playlist:h,base:i.url}];let f=h.playlists[0],g=await c0(new URL(f.uri,i.url),t,r+1),y=NT(h,f);if(y?.uri&&g.length===1){let[v]=await c0(new URL(y.uri,i.url),t,r+1);g.push(v)}return g}if(!/<MPD[\s>]/.test(n)||/<!DOCTYPE|<!ENTITY|<ContentProtection|type\s*=\s*["']dynamic/i.test(n))throw Vt();let o=n.match(/mediaPresentationDuration=["']PT(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?["']/);if(!o)throw Vt();let a=(+o[1]||0)*3600+(+o[2]||0)*60+(+o[3]||0);if(!(a>0&&a<=3600))throw Vt();let s=p=>Array.from(n.matchAll(p),h=>Number(h[1])),u=s(/\btimescale\s*=\s*["'](.*?)["']/g),c=s(/\br\s*=\s*["'](.*?)["']/g);if(u.some(p=>!Number.isSafeInteger(p)||p<1||p>1e9)||c.some(p=>!Number.isSafeInteger(p)||p<0||p>2048)||c.reduce((p,h)=>p+h,0)>8192||(n.match(/<Representation\b/g)||[]).length>32||(n.match(/<S\s/g)||[]).length>4096)throw Vt();for(let p of s(/\b(?:d|duration)\s*=\s*["']([\d.]+)["']/g))if(!(p>0)||a*Math.max(1,...u)/p>8192)throw Vt();let l=(0,PT.parse)(n,{manifestUri:i.url}),d=l.playlists?.[0];if(!d?.segments?.length)throw Vt();let m=NT(l,d)?.playlists?.[0];return[d,m].filter(Boolean).map(p=>({playlist:p,base:i.url}))}async function OT(e,t,r,{cdn:i,run:n,codec:o,budget:a}){let s=Date.now()+18e4;async function u(d,m,p){let h=Math.min(m,a);if(h<=0||Date.now()>=s)throw Vt();let f=await i(d,h,Math.min(2e4,s-Date.now()),0,p),g=0,y=[];for await(let v of f.body){if(g+=v.byteLength,g>h)throw Vt();y.push(v)}if(!g||p&&g!==p.length)throw Vt();return a-=g,{bytes:Buffer.concat(y),url:f.url}}let c=await c0(e,u),l=[];for(let[d,{playlist:m,base:p}]of c.entries()){let h=m.segments;if(!m.endList||!h?.length||h.length>2048)throw Vt();let f=DZ(t,"track"+d),g=await CZ(f,"wx",384),y;try{for(let v of h){if(v.key||v.discontinuity||v.gap)throw Vt();for(let A of[v.map,v]){if(!A)continue;let w=new URL(A.resolvedUri||A.uri,p),S=JSON.stringify([w.href,A.byterange]);if(A===v.map&&y===S)continue;if(A===v.map&&y)throw Vt();let{bytes:N}=await u(w,32*1024*1024,A.byterange);await g.writeFile(N),A===v.map&&(y=S)}}}finally{await g.close()}l.push("-protocol_whitelist","file","-f",y?"mov":"mpegts","-i",f)}await n([...l,"-map","0:v:0","-map",c.length===2?"1:a:0":"0:a:0?","-c","copy",.../hevc|h265|bytevc1/i.test(o)?["-tag:v","hvc1"]:[],"-movflags","+faststart","-f","mp4",r])}var Dm=1024*1024,BT=256*Dm,LZ=/(?:^|\.)(?:qznovelvod\.com|byteimg\.com|fqnovelpic\.com|douyinvod\.com|bytecdn\.cn|ibytedtos\.com|snssdk\.com|pstatp\.com)$/i;async function Ac(e,t,r,i=0,n){let o=new URL(e);if(o.protocol==="http:"&&(o.protocol="https:"),o.protocol!=="https:"||o.port||o.username||o.password||!LZ.test(o.hostname))throw new B("\u7247\u6E90\u5730\u5740\u4E0D\u5728\u652F\u6301\u7684\u5A92\u4F53\u57DF\u540D\u5185");let a={};if(n){if(!Number.isSafeInteger(n.offset)||n.offset<0||!Number.isSafeInteger(n.length)||n.length<1||n.length>t||!Number.isSafeInteger(n.offset+n.length))throw new B("\u7247\u6E90\u5B57\u8282\u8303\u56F4\u65E0\u6548");a.Range="bytes="+n.offset+"-"+(n.offset+n.length-1)}let s=await fetch(o,{headers:a,redirect:"manual",signal:AbortSignal.timeout(r)});if([301,302,303,307,308].includes(s.status)&&i<3&&s.headers.get("location"))return await s.body?.cancel(),Ac(new URL(s.headers.get("location"),o),t,r,i+1,n);if(!(!n||s.status===206&&s.headers.get("content-range")?.split("/")[0]==="bytes "+n.offset+"-"+(n.offset+n.length-1))||!s.ok||!s.body||Number(s.headers.get("content-length"))>t)throw await s.body?.cancel(),new B("\u5A92\u4F53\u5730\u5740\u5DF2\u5931\u6548\u6216\u8D85\u8FC7\u5927\u5C0F\u9650\u5236\uFF0C\u8BF7\u91CD\u8BD5");let c=0,l=new UZ({transform(d,m,p){c+=d.length,p(c>t?new B("\u7D20\u6750\u8D85\u8FC7\u5927\u5C0F\u9650\u5236"):null,d)}});return{body:s.body,limit:l,url:o.href}}var FZ=um("ffmpeg",process.env.HONGGUO_FFMPEG);function UT(){return tD()}async function Sa(e,t=null,r=!1,i=void 0){return await sm(),new Promise((n,o)=>{let a=TZ(FZ,["-hide_banner","-loglevel","error","-nostdin",...e],{cwd:i,stdio:["pipe",r?"pipe":"ignore","ignore"],windowsHide:!0,timeout:12e4,killSignal:"SIGKILL"}),s=[],u=0;a.stdout?.on("data",c=>{u+=c.length,u<=Dm?s.push(c):a.kill()}),a.stdin.on("error",()=>{}),a.stdin.end(t),a.on("error",()=>o(new B("FFmpeg \u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u5B89\u88C5"))),a.on("close",c=>c===0&&u<=Dm?n(Buffer.concat(s)):o(new B("FFmpeg \u65E0\u6CD5\u5904\u7406\u8BE5\u7D20\u6750\u6216\u5F53\u524D\u7F16\u7801")))})}async function ZZ(e,t,r,i){let n=RZ(e);if(!/^[a-zA-Z0-9.-]+$/.test(n)||i&&!/^[0-9a-f]{32}$/i.test(i))throw new B("\u5206\u96C6\u6388\u6743\u6216\u7D20\u6750\u540D\u79F0\u65E0\u6548");let o=i?`ffconcat version 1.0
130
+ `))>=0;){let v=d.slice(0,y);d=d.slice(y+1);let A;try{A=JSON.parse(v)}catch{continue}if(A.error&&[1,2].includes(A.id))return p(jn());if(A.id===1&&A.result&&(f({jsonrpc:"2.0",method:"initialized"}),f({jsonrpc:"2.0",id:2,method:"hooks/list",params:{cwds:[r]}})),A.id===2&&Array.isArray(A.result?.data)){let w=A.result.data.flatMap(N=>Array.isArray(N?.hooks)?N.hooks:[]).filter(N=>typeof N?.pluginId=="string"&&N.pluginId.split("@")[0]==="codex-hongguo").filter(N=>{if(typeof N.sourcePath!="string")return!1;if(o)return N.pluginId===o;let q=RF(s,a(N.sourcePath));return q&&!q.startsWith("..")&&!BF(q)});if(!w.length)return p(jn());let S=uD.map(N=>{let q=w.filter(X=>X.eventName===N),je=q.length?q.some(X=>!X.enabled)?"disabled":q.every(X=>["trusted","managed"].includes(X.trustStatus))?"ready":q.some(X=>["untrusted","modified"].includes(X.trustStatus))?"needs_review":"unknown":"missing";return{event:N,status:je}});p({status:S.every(N=>N.status==="ready")?"ready":"needs_attention",events:S})}}}),f({jsonrpc:"2.0",id:1,method:"initialize",params:{clientInfo:{name:"hongguo-setup",version:"1"},capabilities:{experimentalApi:!0}}})}catch{p(jn())}})}var Yu=()=>UF(24).toString("base64url"),Kr=Z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),Nt=Z.string().regex(/^hg-[0-9]{1,32}$/),lD=Z.string().max(4096).optional(),Cb=Z.string().min(1).max(320),dD=Z.number().int().min(0).max(24*3600*1e3),Db={get_run_state:Z.object({turnId:Kr.optional(),playerInstance:Kr.optional(),observeSession:Z.literal(!0).optional()}),set_player_visible:Z.object({instance:Kr,visible:Z.boolean()}),get_waiting_picks:Z.object({turnId:Kr.optional(),inView:Z.literal(!0).optional()}),mark_waiting_picks_shown:Z.object({turnId:Kr.optional()}),get_waiting_status:Z.object({}),dismiss_waiting_picks:Z.object({turnId:Kr.optional()}),browse_waiting_catalog:Z.object({}),select_waiting_pick:Z.object({seriesId:Nt}),activate_waiting_player:Z.object({}),confirm_waiting_playback:Z.object({playbackId:Z.number().int().positive()}),list_sessions:Z.object({}),select_session:Z.object({choice:Kr}),list_series:Z.object({source:Z.literal("hongguo").optional(),preview:Z.literal(!0).optional(),query:Z.string().max(120).optional(),cursor:lD}),get_cover:Z.object({seriesId:Nt}),get_episodes:Z.object({seriesId:Nt,cursor:lD}),get_history:Z.object({seriesId:Nt.optional(),episodeId:Nt.optional()}),save_progress:Z.object({seriesId:Nt,episodeId:Nt,title:Cb,label:Cb,positionMs:dD,durationMs:dD.positive(),reset:Z.literal(!0).optional()}),prepare_playback:Z.object({episodeId:Nt,retry:Z.boolean().optional()}),create_browser_pairing:Z.object({follow:Z.boolean().optional(),turnId:Kr.optional(),seriesId:Nt.optional(),episodeId:Nt.optional(),title:Cb.optional()}),get_health:Z.object({}),get_setup_status:Z.object({}),set_setup_dismissed:Z.object({dismissed:Z.boolean()}),get_preferences:Z.object({}),set_preferences:Z.object({autoPrompt:Z.boolean().optional(),searchTerms:Z.array(Z.string().trim().min(1).max(30)).min(1).max(6).optional(),autoplayNext:Z.boolean().optional(),autoPauseOnFinish:Z.boolean().optional(),autoPlayOnStart:Z.boolean().optional()}),read_panel_chunk:Z.object({episodeId:Nt,stream:Kr,asset:Z.string().max(32),offset:Z.number().int().nonnegative().max(32*1024*1024)}),remove_history:Z.object({seriesId:Nt})},cm=class{constructor(t,r,i=cD){this.store=t,this.catalog=r,this.checkHooks=i,this.panels=new Map}open(t){let r=Yu(),i={sessionId:rm(t),choices:new Map,lastSeen:Date.now()};for(let[n,o]of this.panels)Date.now()-o.lastSeen>12*36e5&&this.panels.delete(n);return i.caller=i.sessionId,this.panels.set(r,i),{panel:r,state:this.store.state(i.sessionId),identified:!!i.sessionId}}openWaiting(t,r){let i=rm(t);if(!i||[t?.turn_id,t?.turnId].some(o=>o!==void 0&&o!==r)||!this.store.claimCard(i,r))return null;let n=this.open(t);return this.panels.get(n.panel).waiting={turnId:r,selected:null,taken:!1},n}async resumePick(){for(let t of this.store.history(void 0,void 0,-1)){if(!Nt.safeParse(t.seriesId).success||!Nt.safeParse(t.episodeId).success)continue;let r={id:t.seriesId,title:t.title};if(t.positionMs<t.durationMs)return{...r,episodeId:t.episodeId,kind:"resume"};try{let i=await this.catalog.nextEpisode(t.seriesId,t.episodeId);if(i)return{...r,...i}}catch{continue}}return null}async waitingPicks(t,r,i,n){if(!n())return{items:[]};let o=this.store.turnPicks(t,r);if(o.length)return{items:o};let[a,s]=await Promise.all([this.catalog.waitingRecommendations().catch(()=>[]),this.resumePick()]);return{items:this.store.allocatePicks(t,r,s,a,i,n)}}panel(t,r){let i=this.panels.get(t);if(!i||Date.now()-i.lastSeen>12*36e5)throw new B("\u8BF7\u91CD\u65B0\u6253\u5F00\u77ED\u5267\u9762\u677F",401);if((r?.thread_id!==void 0||r?.threadId!==void 0)&&rm(r)!==i.caller)throw new B("\u4F1A\u8BDD\u4E0D\u5339\u914D",403);return i.lastSeen=Date.now(),i}async call(t,r,i,n=!1){let o=Db[r]?.strict().safeParse(i);if(!o?.success)throw new B("\u8BF7\u6C42\u53C2\u6570\u65E0\u6548");let a=o.data;switch(r){case"get_waiting_status":case"browse_waiting_catalog":{let s=t.waiting;if(n||!s)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return r==="get_waiting_status"?{visible:this.store.offerable(t.sessionId,s.turnId)}:(s.selected=null,s.taken=!1,s.browsing=!0,s.played=!0,{})}case"dismiss_waiting_picks":{let s=a.turnId??t.waiting?.turnId;if(!t.sessionId||!s||t.waiting&&s!==t.waiting.turnId||n&&t.fixedTurn&&s!==t.fixedTurn||!this.store.state(t.sessionId,s).turnId)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.dismissPicks(t.sessionId,s)}case"get_waiting_picks":case"mark_waiting_picks_shown":{let s=t.waiting,u=a.turnId??s?.turnId;if(!t.sessionId||!u||n&&t.fixedTurn&&u!==t.fixedTurn||s&&a.turnId&&!s.taken)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);let c=()=>a.turnId?this.store.activeTurn(t.sessionId,u)&&this.store.preferences().autoPrompt&&!this.store.picksDismissed(t.sessionId,u):this.store.offerable(t.sessionId,u);return r==="mark_waiting_picks_shown"?this.store.markPicksShown(t.sessionId,u,c):this.waitingPicks(t.sessionId,u,!!a.inView,c)}case"select_waiting_pick":case"confirm_waiting_playback":case"activate_waiting_player":{let s=t.waiting;if(n||!s)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);if(r==="confirm_waiting_playback")return s.playbackId===a.playbackId&&(s.played=!0),{};if(r==="select_waiting_pick"){if(!this.store.offerable(t.sessionId,s.turnId))throw new B("\u8FD9\u6761\u63A8\u8350\u5DF2\u7ED3\u675F");let l=this.store.turnPicks(t.sessionId,s.turnId).find(d=>d.id===a.seriesId);if(!l)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.markPicksShown(t.sessionId,s.turnId,()=>this.store.offerable(t.sessionId,s.turnId)),s.selected=l,s.taken=!1,s.browsing=!1,s.played=!1,s.playbackId=(s.playbackId||0)+1,{}}let u=this.store.activeTurn(t.sessionId,s.turnId),c=!!s.selected&&!s.played&&u&&!this.store.picksDismissed(t.sessionId,s.turnId);return s.taken=!0,s.browsing&&(this.store.dismissPicks(t.sessionId,s.turnId),s.browsing=!1),{pick:s.selected,turnId:s.turnId,play:c,...c?{playbackId:s.playbackId}:{},...s.selected&&!u?{reason:"turn-ended"}:{}}}case"set_player_visible":if(t.waiting&&!t.waiting.taken)throw new B("\u8BF7\u4ECE\u672C\u8F6E\u63A8\u8350\u4E2D\u9009\u5267",403);return this.store.playerVisible(t.sessionId,a.instance,a.visible),{};case"get_run_state":{if(!this.store.persistent)throw new B("\u672C\u673A\u4F1A\u8BDD\u72B6\u6001\u4E0D\u53EF\u8FBE",503);if(this.store.touchPlayer(t.sessionId,a.playerInstance),a.observeSession){if(a.turnId||t.waiting&&!t.waiting.taken)throw new B("\u8BF7\u5148\u6253\u5F00\u64AD\u653E\u5668",403);return{...this.store.state(t.sessionId,n?t.fixedTurn:void 0),preferences:this.store.preferences()}}let s=t.waiting?.turnId??(n?t.fixedTurn:null);if(s&&a.turnId&&a.turnId!==s)throw new B("\u64AD\u653E\u5668\u5DF2\u7ED1\u5B9A\u5176\u4ED6\u56DE\u5408",403);let u=s??a.turnId,c=this.store.state(t.sessionId,u);return t.waiting&&c.state==="submitted"&&!this.store.activeTurn(t.sessionId,u)?{...c,state:"unknown"}:c}case"list_sessions":if(n||t.sessionId)throw new B("\u5F53\u524D\u5165\u53E3\u4E0D\u5141\u8BB8\u9009\u62E9\u5176\u4ED6\u4F1A\u8BDD",403);return t.choices.clear(),{items:this.store.candidates().map(s=>{let u=Yu();return t.choices.set(u,s.session_id),{choice:u,suffix:s.session_id.slice(-8),at:s.at}})};case"select_session":if(n||t.sessionId||!t.choices.has(a.choice))throw new B("\u8BF7\u91CD\u65B0\u9009\u62E9\u4F1A\u8BDD",403);return t.sessionId=t.choices.get(a.choice),t.choices.clear(),this.store.state(t.sessionId);case"list_series":return this.catalog.list(a);case"get_cover":return this.catalog.cover(a.seriesId);case"get_episodes":{let s=await this.catalog.episodes(a);t.allowed??=new Set;for(let u of s.items)u.playable&&t.allowed.add(u.id);return s}case"get_history":return{items:this.store.history(a.seriesId,a.episodeId)};case"remove_history":return this.store.removeHistory(a.seriesId);case"read_panel_chunk":if(n||t.streams?.get(a.episodeId)!==a.stream)throw new B("\u8BF7\u5148\u51C6\u5907\u5F53\u524D\u5206\u96C6",403);return this.catalog.panelMedia.chunk(a.episodeId,a.stream,a.asset,a.offset);case"save_progress":if(!this.store.persistent)throw new B("\u672C\u673A\u8FDB\u5EA6\u76EE\u5F55\u4E0D\u53EF\u5199",503);return this.catalog.cache?.hold(a.episodeId),this.store.save(a);case"prepare_playback":{if(!t.allowed?.has(a.episodeId))throw new B("\u8BF7\u5148\u9009\u62E9\u53EF\u64AD\u653E\u7684\u5206\u96C6",403);!n&&t.playing!==a.episodeId&&(this.catalog.panelMedia?.unpin(t.playing,t),t.streams?.clear(),t.playing=a.episodeId);let s=this.catalog.prepare(a.episodeId,n,!!a.retry);return n&&s.status==="ready"&&t.grants.add(a.episodeId),!n&&s.stream&&(this.catalog.panelMedia.pin(a.episodeId,t),t.streams??=new Map,t.streams.set(a.episodeId,s.stream)),s}case"get_preferences":return this.store.preferences();case"set_preferences":{if(!this.store.persistent)throw new B("\u672C\u673A\u8BBE\u7F6E\u76EE\u5F55\u4E0D\u53EF\u5199",503);let s=this.store.preferences(),u=this.store.setPreferences(a);return JSON.stringify(s.searchTerms)!==JSON.stringify(u.searchTerms)&&(this.catalog.feed=null,this.catalog.refresh=null),u}case"get_health":return this.catalog.ffmpeg||this.catalog.prepareMediaRuntime?.().catch(()=>{}),{runtime:process.version,database:this.store.writable(),ffmpeg:this.catalog.ffmpeg};case"get_setup_status":return this.catalog.ffmpeg||this.catalog.prepareMediaRuntime?.().catch(()=>{}),this.checkingHooks??=this.checkHooks().finally(()=>{this.checkingHooks=null}),{runtime:process.version,database:this.store.writable(),ffmpeg:this.catalog.ffmpeg,dismissed:this.store.setupDismissed(),hooks:await this.checkingHooks};case"set_setup_dismissed":if(!this.store.persistent)throw new B("\u672C\u673A\u8BBE\u7F6E\u76EE\u5F55\u4E0D\u53EF\u5199",503);return this.store.setSetupDismissed(a.dismissed);case"create_browser_pairing":{if(n)throw new B("\u8BF7\u4ECE\u4F1A\u8BDD\u9762\u677F\u6253\u5F00\u5206\u5C4F",403);let s=a.follow&&this.store.state(t.sessionId,a.turnId);if(a.follow&&(!a.turnId||s.state!=="submitted"))throw new B("\u5F53\u524D\u56DE\u5408\u65E0\u6CD5\u7ED1\u5B9A\uFF0C\u8BF7\u9009\u62E9\u624B\u52A8\u64AD\u653E");return this.pair({sessionId:a.follow===!1?null:t.sessionId,fixedTurn:a.follow?a.turnId:null,selection:a.seriesId?{seriesId:a.seriesId,episodeId:a.episodeId,title:a.title}:null})}}}};import{join as qT}from"node:path";import{pathToFileURL as eQ}from"node:url";import{Writable as tQ}from"node:stream";import{pipeline as rQ}from"node:stream/promises";import{spawn as TZ}from"node:child_process";import{createWriteStream as NZ,existsSync as zZ,mkdirSync as RT,readdirSync as PZ,renameSync as OZ,rmSync as Ea,statSync as jT}from"node:fs";import{basename as RZ,dirname as jZ,join as xa}from"node:path";import{randomUUID as BZ}from"node:crypto";import{Transform as UZ}from"node:stream";import{pipeline as MZ}from"node:stream/promises";var zT=wi(yD(),1),PT=wi(TT(),1);import{open as CZ}from"node:fs/promises";import{join as DZ}from"node:path";var Vt=()=>new B("\u8BE5\u5206\u6BB5\u7247\u6E90\u6682\u4E0D\u652F\u6301\uFF0C\u53EF\u91CD\u8BD5\u5176\u4ED6\u7247\u6E90");function NT(e,t){let r=e.mediaGroups?.AUDIO?.[t.attributes?.AUDIO]||{},i=Object.values(r);return i.find(n=>n.default)||i[0]}async function c0(e,t,r=0){if(r>3)throw Vt();let i=await t(e,256*1024),n=i.bytes.toString("utf8").trimStart();if(n.startsWith("#EXTM3U")){let p=new zT.Parser;p.push(n),p.end();let h=p.manifest;if(!h.playlists?.length)return[{playlist:h,base:i.url}];let f=h.playlists[0],g=await c0(new URL(f.uri,i.url),t,r+1),y=NT(h,f);if(y?.uri&&g.length===1){let[v]=await c0(new URL(y.uri,i.url),t,r+1);g.push(v)}return g}if(!/<MPD[\s>]/.test(n)||/<!DOCTYPE|<!ENTITY|<ContentProtection|type\s*=\s*["']dynamic/i.test(n))throw Vt();let o=n.match(/mediaPresentationDuration=["']PT(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?["']/);if(!o)throw Vt();let a=(+o[1]||0)*3600+(+o[2]||0)*60+(+o[3]||0);if(!(a>0&&a<=3600))throw Vt();let s=p=>Array.from(n.matchAll(p),h=>Number(h[1])),u=s(/\btimescale\s*=\s*["'](.*?)["']/g),c=s(/\br\s*=\s*["'](.*?)["']/g);if(u.some(p=>!Number.isSafeInteger(p)||p<1||p>1e9)||c.some(p=>!Number.isSafeInteger(p)||p<0||p>2048)||c.reduce((p,h)=>p+h,0)>8192||(n.match(/<Representation\b/g)||[]).length>32||(n.match(/<S\s/g)||[]).length>4096)throw Vt();for(let p of s(/\b(?:d|duration)\s*=\s*["']([\d.]+)["']/g))if(!(p>0)||a*Math.max(1,...u)/p>8192)throw Vt();let l=(0,PT.parse)(n,{manifestUri:i.url}),d=l.playlists?.[0];if(!d?.segments?.length)throw Vt();let m=NT(l,d)?.playlists?.[0];return[d,m].filter(Boolean).map(p=>({playlist:p,base:i.url}))}async function OT(e,t,r,{cdn:i,run:n,codec:o,budget:a}){let s=Date.now()+18e4;async function u(d,m,p){let h=Math.min(m,a);if(h<=0||Date.now()>=s)throw Vt();let f=await i(d,h,Math.min(2e4,s-Date.now()),0,p),g=0,y=[];for await(let v of f.body){if(g+=v.byteLength,g>h)throw Vt();y.push(v)}if(!g||p&&g!==p.length)throw Vt();return a-=g,{bytes:Buffer.concat(y),url:f.url}}let c=await c0(e,u),l=[];for(let[d,{playlist:m,base:p}]of c.entries()){let h=m.segments;if(!m.endList||!h?.length||h.length>2048)throw Vt();let f=DZ(t,"track"+d),g=await CZ(f,"wx",384),y;try{for(let v of h){if(v.key||v.discontinuity||v.gap)throw Vt();for(let A of[v.map,v]){if(!A)continue;let w=new URL(A.resolvedUri||A.uri,p),S=JSON.stringify([w.href,A.byterange]);if(A===v.map&&y===S)continue;if(A===v.map&&y)throw Vt();let{bytes:N}=await u(w,32*1024*1024,A.byterange);await g.writeFile(N),A===v.map&&(y=S)}}}finally{await g.close()}l.push("-protocol_whitelist","file","-f",y?"mov":"mpegts","-i",f)}await n([...l,"-map","0:v:0","-map",c.length===2?"1:a:0":"0:a:0?","-c","copy",.../hevc|h265|bytevc1/i.test(o)?["-tag:v","hvc1"]:[],"-movflags","+faststart","-f","mp4",r])}var Dm=1024*1024,BT=256*Dm,LZ=/(?:^|\.)(?:qznovelvod\.com|byteimg\.com|fqnovelpic\.com|douyinvod\.com|bytecdn\.cn|ibytedtos\.com|snssdk\.com|pstatp\.com)$/i;async function Ac(e,t,r,i=0,n){let o=new URL(e);if(o.protocol==="http:"&&(o.protocol="https:"),o.protocol!=="https:"||o.port||o.username||o.password||!LZ.test(o.hostname))throw new B("\u7247\u6E90\u5730\u5740\u4E0D\u5728\u652F\u6301\u7684\u5A92\u4F53\u57DF\u540D\u5185");let a={};if(n){if(!Number.isSafeInteger(n.offset)||n.offset<0||!Number.isSafeInteger(n.length)||n.length<1||n.length>t||!Number.isSafeInteger(n.offset+n.length))throw new B("\u7247\u6E90\u5B57\u8282\u8303\u56F4\u65E0\u6548");a.Range="bytes="+n.offset+"-"+(n.offset+n.length-1)}let s=await fetch(o,{headers:a,redirect:"manual",signal:AbortSignal.timeout(r)});if([301,302,303,307,308].includes(s.status)&&i<3&&s.headers.get("location"))return await s.body?.cancel(),Ac(new URL(s.headers.get("location"),o),t,r,i+1,n);if(!(!n||s.status===206&&s.headers.get("content-range")?.split("/")[0]==="bytes "+n.offset+"-"+(n.offset+n.length-1))||!s.ok||!s.body||Number(s.headers.get("content-length"))>t)throw await s.body?.cancel(),new B("\u5A92\u4F53\u5730\u5740\u5DF2\u5931\u6548\u6216\u8D85\u8FC7\u5927\u5C0F\u9650\u5236\uFF0C\u8BF7\u91CD\u8BD5");let c=0,l=new UZ({transform(d,m,p){c+=d.length,p(c>t?new B("\u7D20\u6750\u8D85\u8FC7\u5927\u5C0F\u9650\u5236"):null,d)}});return{body:s.body,limit:l,url:o.href}}var FZ=um("ffmpeg",process.env.HONGGUO_FFMPEG);function UT(){return tD()}async function Sa(e,t=null,r=!1,i=void 0){return await sm(),new Promise((n,o)=>{let a=TZ(FZ,["-hide_banner","-loglevel","error","-nostdin",...e],{cwd:i,stdio:["pipe",r?"pipe":"ignore","ignore"],windowsHide:!0,timeout:12e4,killSignal:"SIGKILL"}),s=[],u=0;a.stdout?.on("data",c=>{u+=c.length,u<=Dm?s.push(c):a.kill()}),a.stdin.on("error",()=>{}),a.stdin.end(t),a.on("error",()=>o(new B("FFmpeg \u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u5B89\u88C5"))),a.on("close",c=>c===0&&u<=Dm?n(Buffer.concat(s)):o(new B("FFmpeg \u65E0\u6CD5\u5904\u7406\u8BE5\u7D20\u6750\u6216\u5F53\u524D\u7F16\u7801")))})}async function ZZ(e,t,r,i){let n=RZ(e);if(!/^[a-zA-Z0-9.-]+$/.test(n)||i&&!/^[0-9a-f]{32}$/i.test(i))throw new B("\u5206\u96C6\u6388\u6743\u6216\u7D20\u6750\u540D\u79F0\u65E0\u6548");let o=i?`ffconcat version 1.0
131
131
  file 'file:`+n+`'
132
132
  option decryption_key `+i+`
133
133
  `:null;await Sa(["-protocol_whitelist","file,pipe",...i?["-format_whitelist","concat,mov","-safe","0","-f","concat","-i","pipe:0"]:["-f","mov","-i",e],"-map","0:v:0","-map","0:a:0?","-c","copy",.../hevc|h265|bytevc1/i.test(r)?["-tag:v","hvc1"]:[],"-movflags","+faststart","-f","mp4",t],o,!1,jZ(e))}var Tm=class{constructor(t,r,{maxFiles:i=40,maxBytes:n=1024*Dm}={}){this.db=t.db,this.resolve=r,this.dir=xa(t.root,"media"),this.maxFiles=i,this.maxBytes=n,RT(this.dir,{recursive:!0,mode:448}),this.db.exec(`CREATE TABLE IF NOT EXISTS media (
@@ -137,7 +137,7 @@ option decryption_key `+i+`
137
137
  (async()=>{const ticket=location.hash.slice(1);history.replaceState(null,'','/pair');
138
138
  try {const r=await fetch('/exchange',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ticket})});
139
139
  if(!r.ok)throw Error();location.replace((await r.json()).page);}catch{document.querySelector('p').textContent='\u5206\u5C4F\u94FE\u63A5\u5DF2\u8FC7\u671F\u6216\u5DF2\u4F7F\u7528\u3002\u8BF7\u56DE\u5230\u77ED\u5267\u9762\u677F\u91CD\u65B0\u83B7\u53D6\u3002';}})()
140
- </script></html>`,Pm=class{constructor(t){this.service=t,this.tickets=new Map,this.sessions=new Map}async listen(){return this.starting||(this.server=nQ((t,r)=>this.request(t,r).catch(i=>{if(r.headersSent){r.destroy();return}r.writeHead(i instanceof B?i.status:503,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:nm(i)}))})),this.server.headersTimeout=1e4,this.server.requestTimeout=15e3,this.starting=new Promise((t,r)=>{this.server.once("error",r),this.server.listen(0,"127.0.0.1",()=>{this.origin="http://127.0.0.1:"+this.server.address().port,t()})}).catch(t=>{throw this.starting=null,t})),this.starting}prune(){for(let t of[this.sessions,this.tickets])for(let[r,i]of t)i.expires<Date.now()&&t.delete(r)}async pair(t){await this.listen(),this.prune();let r=Yu();return this.tickets.set(r,{scope:t,expires:Date.now()+6e4}),{url:this.origin+"/pair#"+r,expiresIn:60}}async request(t,r){if(r.setHeader("Cache-Control","no-store"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("X-Content-Type-Options","nosniff"),t.headers.host!==new URL(this.origin).host)throw new B("\u4E3B\u673A\u65E0\u6548",403);if(t.method==="POST"&&t.headers.origin!==this.origin)throw new B("\u8BF7\u6C42\u6765\u6E90\u65E0\u6548",403);let i=t.url,n=HT(16).toString("base64");r.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${n}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`);let o=l=>{r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(l.replaceAll("__NONCE__",n))},a=l=>{r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l))};if(i==="/pair"&&t.method==="GET")return o(cQ);if(this.prune(),i==="/exchange"&&t.method==="POST"){let l=await GT(t),d=this.tickets.get(l?.ticket);if(!d||d.expires<Date.now())throw new B("\u5206\u5C4F\u94FE\u63A5\u65E0\u6548",403);this.tickets.delete(l.ticket);let m=HT(12).toString("hex"),p=Yu(),h="/p/"+m+"/";return this.sessions.set(m,{...d.scope,key:p,grants:new Set,expires:Date.now()+12*36e5}),r.setHeader("Set-Cookie","hg="+p+"; Path="+h+"; HttpOnly; SameSite=Strict"),a({page:h})}let s=/^\/p\/([a-f0-9]{24})\/(.*)$/.exec(i),u=s&&this.sessions.get(s[1]);if(!u||!(t.headers.cookie||"").split(/;\s*/).includes("hg="+u.key))throw new B("\u8BF7\u4ECE\u4F1A\u8BDD\u9762\u677F\u91CD\u65B0\u6253\u5F00\u5206\u5C4F",401);u.expires=Date.now()+12*36e5;let c=s[2];if(!c&&t.method==="GET")return o(aQ(sQ(Rn,"dist/ui/player.html"),"utf8").replace('data-host="panel"','data-host="browser"'));if(c==="context"&&t.method==="GET")return a({identified:!!u.sessionId,turnId:u.fixedTurn,selection:u.selection});if(c.startsWith("api/")&&t.method==="POST")return a(await this.service.call(u,c.slice(4),await GT(t),!0));if(c.startsWith("media/")&&["GET","HEAD"].includes(t.method)){let l=c.slice(6);if(!u.grants.has(l))throw new B("\u8BF7\u5148\u9009\u62E9\u8BE5\u96C6",403);let d=this.service.catalog.cache?.path(l);if(!d)throw new B("\u7D20\u6750\u5F85\u91CD\u65B0\u51C6\u5907",404);let m=oQ(d,{throwIfNoEntry:!1})?.size;if(!m)throw new B("\u7F13\u5B58\u5DF2\u6E05\u7406\uFF0C\u8BF7\u91CD\u65B0\u51C6\u5907\u8BE5\u96C6",404);this.service.catalog.cache?.hold(l);let p=uQ(t.headers.range,m);if(r.setHeader("Accept-Ranges","bytes"),r.setHeader("Content-Type","video/mp4"),p===!1)return r.writeHead(416,{"Content-Range":"bytes */"+m}),r.end();let[h,f]=p||[0,m-1];if(p&&r.setHeader("Content-Range",`bytes ${h}-${f}/${m}`),r.writeHead(p?206:200,{"Content-Length":f-h+1}),t.method==="HEAD")return r.end();let g=iQ(d,{start:h,end:f}),y=setInterval(()=>this.service.catalog.cache?.hold(l),3e4);r.on("close",()=>{clearInterval(y),g.destroy()}),g.on("error",()=>r.destroy()),g.pipe(r);return}throw new B("\u627E\u4E0D\u5230\u8BE5\u9875\u9762",404)}close(){this.server?.closeAllConnections(),this.server?.close()}};process.umask(63);var yc;try{yc=new Hu}catch{yc=new Hu(void 0,!0)}var f0=new zm(yc),Ca=new cm(yc,f0),KT=new Pm(Ca);Ca.pair=e=>KT.pair(e);var $i=new Yp({name:"codex-hongguo",version:qk.version}),XT="ui://hongguo/v14/player",Om="ui://hongguo/v14/waiting",d0="text/html;profile=mcp-app",YT={visibility:["app"]},JT={ui:{csp:{connectDomains:[],resourceDomains:["blob:"]},prefersBorder:!1}};for(let[e,t]of[[XT,"\u7EA2\u679C\u77ED\u5267"],[Om,"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6"]]){let r=e===Om,i=r?{...JT,"openai/widgetShowCodexWidgetInline":!0,"openai/widgetHeightHint":96,"openai/widgetMinFrameHeight":1,"openai/ui":{availableDisplayModes:["inline","fullscreen"],preferredDisplayMode:"inline"}}:JT,n=o=>{let a=lQ(dQ(Rn,"dist/ui/player.html"),"utf8");return{contents:[{uri:o.href,mimeType:d0,_meta:i,text:r?a.replace('data-surface="player"','data-surface="waiting"'):a}]}};$i.registerResource(t,e,{mimeType:d0,_meta:i},n);for(let o of["ui://hongguo/","ui://hongguo/v2/","ui://hongguo/v3/","ui://hongguo/v4/","ui://hongguo/v5/","ui://hongguo/v6/","ui://hongguo/v7/","ui://hongguo/v8/","ui://hongguo/v9/","ui://hongguo/v10/","ui://hongguo/v11/","ui://hongguo/v12/","ui://hongguo/v13/"]){let a=o+(r?"waiting":"player");if(a===e)continue;let s=new Wp(a,{list:void 0});$i.registerResource(t+"\uFF08"+o+"\uFF09",s,{mimeType:d0,_meta:i},n)}}$i.registerTool("show_waiting_picks",{title:"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6",description:"Show optional Hongguo titles inline when requested by the Hongguo turn-start hook. Returns immediately.",inputSchema:{turnId:Z.string().regex(/^[A-Za-z0-9_-]{1,128}$/)},annotations:{readOnlyHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["model"],resourceUri:Om},"openai/ui":{preferredModelDisplayMode:"inline"}}},({turnId:e},t)=>{let r=Ca.openWaiting(t._meta,e);return{content:[],structuredContent:{shown:!!r},_meta:r?{panel:r.panel,waitingTurn:e,ui:{resourceUri:Om}}:{}}});$i.registerTool("open_drama_panel",{title:"\u7EA2\u679C\u77ED\u5267",description:"\u5728\u5F53\u524D\u4F1A\u8BDD\u9009\u5267\u4E0E\u7EED\u64AD",inputSchema:{},_meta:{ui:{...YT,resourceUri:XT},"openai/ui":{entrypoints:[{type:"thread"},{type:"global"}]}}},(e,t)=>{let r=Ca.open(t._meta);return f0.recommendations().catch(()=>{}),{content:[],structuredContent:{state:r.state,identified:r.identified},_meta:{panel:r.panel}}});for(let[e,t]of Object.entries(Db))$i.registerTool(e,{inputSchema:{...t.shape,panel:Z.string().max(80)},_meta:{ui:YT}},async({panel:r,...i},n)=>{try{let o=await Ca.call(Ca.panel(r,n._meta),e,i);return{content:[],_meta:{data:o}}}catch(o){return{isError:!0,content:[{type:"text",text:nm(o)}]}}});$i.server.onclose=()=>{f0.panelMedia?.close(),KT.close(),yc.close()};await $i.connect(new tm);
140
+ </script></html>`,Pm=class{constructor(t){this.service=t,this.tickets=new Map,this.sessions=new Map}async listen(){return this.starting||(this.server=nQ((t,r)=>this.request(t,r).catch(i=>{if(r.headersSent){r.destroy();return}r.writeHead(i instanceof B?i.status:503,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:nm(i)}))})),this.server.headersTimeout=1e4,this.server.requestTimeout=15e3,this.starting=new Promise((t,r)=>{this.server.once("error",r),this.server.listen(0,"127.0.0.1",()=>{this.origin="http://127.0.0.1:"+this.server.address().port,t()})}).catch(t=>{throw this.starting=null,t})),this.starting}prune(){for(let t of[this.sessions,this.tickets])for(let[r,i]of t)i.expires<Date.now()&&t.delete(r)}async pair(t){await this.listen(),this.prune();let r=Yu();return this.tickets.set(r,{scope:t,expires:Date.now()+6e4}),{url:this.origin+"/pair#"+r,expiresIn:60}}async request(t,r){if(r.setHeader("Cache-Control","no-store"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("X-Content-Type-Options","nosniff"),t.headers.host!==new URL(this.origin).host)throw new B("\u4E3B\u673A\u65E0\u6548",403);if(t.method==="POST"&&t.headers.origin!==this.origin)throw new B("\u8BF7\u6C42\u6765\u6E90\u65E0\u6548",403);let i=t.url,n=HT(16).toString("base64");r.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${n}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`);let o=l=>{r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(l.replaceAll("__NONCE__",n))},a=l=>{r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l))};if(i==="/pair"&&t.method==="GET")return o(cQ);if(this.prune(),i==="/exchange"&&t.method==="POST"){let l=await GT(t),d=this.tickets.get(l?.ticket);if(!d||d.expires<Date.now())throw new B("\u5206\u5C4F\u94FE\u63A5\u65E0\u6548",403);this.tickets.delete(l.ticket);let m=HT(12).toString("hex"),p=Yu(),h="/p/"+m+"/";return this.sessions.set(m,{...d.scope,key:p,grants:new Set,expires:Date.now()+12*36e5}),r.setHeader("Set-Cookie","hg="+p+"; Path="+h+"; HttpOnly; SameSite=Strict"),a({page:h})}let s=/^\/p\/([a-f0-9]{24})\/(.*)$/.exec(i),u=s&&this.sessions.get(s[1]);if(!u||!(t.headers.cookie||"").split(/;\s*/).includes("hg="+u.key))throw new B("\u8BF7\u4ECE\u4F1A\u8BDD\u9762\u677F\u91CD\u65B0\u6253\u5F00\u5206\u5C4F",401);u.expires=Date.now()+12*36e5;let c=s[2];if(!c&&t.method==="GET")return o(aQ(sQ(Rn,"dist/ui/player.html"),"utf8").replace('data-host="panel"','data-host="browser"'));if(c==="context"&&t.method==="GET")return a({identified:!!u.sessionId,turnId:u.fixedTurn,selection:u.selection});if(c.startsWith("api/")&&t.method==="POST")return a(await this.service.call(u,c.slice(4),await GT(t),!0));if(c.startsWith("media/")&&["GET","HEAD"].includes(t.method)){let l=c.slice(6);if(!u.grants.has(l))throw new B("\u8BF7\u5148\u9009\u62E9\u8BE5\u96C6",403);let d=this.service.catalog.cache?.path(l);if(!d)throw new B("\u7D20\u6750\u5F85\u91CD\u65B0\u51C6\u5907",404);let m=oQ(d,{throwIfNoEntry:!1})?.size;if(!m)throw new B("\u7F13\u5B58\u5DF2\u6E05\u7406\uFF0C\u8BF7\u91CD\u65B0\u51C6\u5907\u8BE5\u96C6",404);this.service.catalog.cache?.hold(l);let p=uQ(t.headers.range,m);if(r.setHeader("Accept-Ranges","bytes"),r.setHeader("Content-Type","video/mp4"),p===!1)return r.writeHead(416,{"Content-Range":"bytes */"+m}),r.end();let[h,f]=p||[0,m-1];if(p&&r.setHeader("Content-Range",`bytes ${h}-${f}/${m}`),r.writeHead(p?206:200,{"Content-Length":f-h+1}),t.method==="HEAD")return r.end();let g=iQ(d,{start:h,end:f}),y=setInterval(()=>this.service.catalog.cache?.hold(l),3e4);r.on("close",()=>{clearInterval(y),g.destroy()}),g.on("error",()=>r.destroy()),g.pipe(r);return}throw new B("\u627E\u4E0D\u5230\u8BE5\u9875\u9762",404)}close(){this.server?.closeAllConnections(),this.server?.close()}};process.umask(63);var yc;try{yc=new Hu}catch{yc=new Hu(void 0,!0)}var f0=new zm(yc),Ca=new cm(yc,f0),KT=new Pm(Ca);Ca.pair=e=>KT.pair(e);var $i=new Yp({name:"codex-hongguo",version:qk.version}),XT="ui://hongguo/v15/player",Om="ui://hongguo/v15/waiting",d0="text/html;profile=mcp-app",YT={visibility:["app"]},JT={ui:{csp:{connectDomains:[],resourceDomains:["blob:"]},prefersBorder:!1}};for(let[e,t]of[[XT,"\u7EA2\u679C\u77ED\u5267"],[Om,"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6"]]){let r=e===Om,i=r?{...JT,"openai/widgetShowCodexWidgetInline":!0,"openai/widgetHeightHint":96,"openai/widgetMinFrameHeight":1,"openai/ui":{availableDisplayModes:["inline","fullscreen"],preferredDisplayMode:"inline"}}:JT,n=o=>{let a=lQ(dQ(Rn,"dist/ui/player.html"),"utf8");return{contents:[{uri:o.href,mimeType:d0,_meta:i,text:r?a.replace('data-surface="player"','data-surface="waiting"'):a}]}};$i.registerResource(t,e,{mimeType:d0,_meta:i},n);for(let o of["ui://hongguo/","ui://hongguo/v2/","ui://hongguo/v3/","ui://hongguo/v4/","ui://hongguo/v5/","ui://hongguo/v6/","ui://hongguo/v7/","ui://hongguo/v8/","ui://hongguo/v9/","ui://hongguo/v10/","ui://hongguo/v11/","ui://hongguo/v12/","ui://hongguo/v13/"]){let a=o+(r?"waiting":"player");if(a===e)continue;let s=new Wp(a,{list:void 0});$i.registerResource(t+"\uFF08"+o+"\uFF09",s,{mimeType:d0,_meta:i},n)}}$i.registerTool("show_waiting_picks",{title:"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6",description:"Show optional Hongguo titles inline when requested by the Hongguo turn-start hook. Returns immediately.",inputSchema:{turnId:Z.string().regex(/^[A-Za-z0-9_-]{1,128}$/)},annotations:{readOnlyHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["model"],resourceUri:Om},"openai/ui":{preferredModelDisplayMode:"inline"}}},({turnId:e},t)=>{let r=Ca.openWaiting(t._meta,e);return{content:[],structuredContent:{shown:!!r},_meta:r?{panel:r.panel,waitingTurn:e,ui:{resourceUri:Om}}:{}}});$i.registerTool("open_drama_panel",{title:"\u7EA2\u679C\u77ED\u5267",description:"\u5728\u5F53\u524D\u4F1A\u8BDD\u9009\u5267\u4E0E\u7EED\u64AD",inputSchema:{},_meta:{ui:{...YT,resourceUri:XT},"openai/ui":{entrypoints:[{type:"thread"},{type:"global"}]}}},(e,t)=>{let r=Ca.open(t._meta);return f0.recommendations().catch(()=>{}),{content:[],structuredContent:{state:r.state,identified:r.identified},_meta:{panel:r.panel}}});for(let[e,t]of Object.entries(Db))$i.registerTool(e,{inputSchema:{...t.shape,panel:Z.string().max(80)},_meta:{ui:YT}},async({panel:r,...i},n)=>{try{let o=await Ca.call(Ca.panel(r,n._meta),e,i);return{content:[],_meta:{data:o}}}catch(o){return{isError:!0,content:[{type:"text",text:nm(o)}]}}});$i.server.onclose=()=>{f0.panelMedia?.close(),KT.close(),yc.close()};await $i.connect(new tm);
141
141
  /*! Bundled license information:
142
142
 
143
143
  xz-decompress/dist/package/xz-decompress.js: