@kyun.si/codex-hongguo 0.0.26 → 0.0.27

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 ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function sp(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??Pe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:i,...n}=ap(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...n}=op(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function px(t,e){if(e.mapStrategy==="record")return sp(t,e);let r=G(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Pe(e),i=G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Pe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function mx(t){let e=t.values,i=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[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 hx(t){return t.target==="openAi"?void 0:{not:Pe({...t,currentPath:[...t.currentPath,"not"]})}}function gx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var hu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ax(t,e){if(e.target==="openApi3")return vx(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.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 vx(t,e)}var vx=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,n)=>G(i._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!e.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function yx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:hu[t.innerType._def.typeName],nullable:!0}:{type:[hu[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let i=G(t.innerType._def,{...e,currentPath:[...e.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function _x(t,e){let r={type:"number"};if(!t.checks)return r;for(let i of t.checks)switch(i.kind){case"int":r.type="integer",ry(r,"type",i.message,e);break;case"min":e.target==="jsonSchema7"?i.inclusive?le(r,"minimum",i.value,i.message,e):le(r,"exclusiveMinimum",i.value,i.message,e):(i.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",i.value,i.message,e));break;case"max":e.target==="jsonSchema7"?i.inclusive?le(r,"maximum",i.value,i.message,e):le(r,"exclusiveMaximum",i.value,i.message,e):(i.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",i.value,i.message,e));break;case"multipleOf":le(r,"multipleOf",i.value,i.message,e);break}return r}function bx(t,e){let r=e.target==="openAi",i={type:"object",properties:{}},n=[],o=t.shape();for(let s in o){let u=o[s];if(u===void 0||u._def===void 0)continue;let c=Z4(u);c&&r&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);let l=G(u._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,c||n.push(s))}n.length&&(i.required=n);let a=F4(t,e);return a!==void 0&&(i.additionalProperties=a),i}function F4(t,e){if(t.catchall._def.typeName!=="ZodNever")return G(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Z4(t){try{return t.isOptional()}catch{return!0}}var $x=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(t.innerType._def,e);let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Pe(e)},r]}:Pe(e)};var Ix=(t,e)=>{if(e.pipeStrategy==="input")return G(t.in._def,e);if(e.pipeStrategy==="output")return G(t.out._def,e);let r=G(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),i=G(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function wx(t,e){return G(t.type._def,e)}function Ex(t,e){let i={type:"array",uniqueItems:!0,items:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(i,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(i,"maxItems",t.maxSize.value,t.maxSize.message,e),i}function xx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,i)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:G(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,i)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Sx(t){return{not:Pe(t)}}function kx(t){return Pe(t)}var Cx=(t,e)=>G(t.innerType._def,e);var Dx=(t,e,r)=>{switch(e){case T.ZodString:return ap(t,r);case T.ZodNumber:return _x(t,r);case T.ZodObject:return bx(t,r);case T.ZodBigInt:return ix(t,r);case T.ZodBoolean:return ox();case T.ZodDate:return ny(t,r);case T.ZodUndefined:return Sx(r);case T.ZodNull:return gx(r);case T.ZodArray:return nx(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return Ax(t,r);case T.ZodIntersection:return lx(t,r);case T.ZodTuple:return xx(t,r);case T.ZodRecord:return sp(t,r);case T.ZodLiteral:return dx(t,r);case T.ZodEnum:return cx(t);case T.ZodNativeEnum:return mx(t);case T.ZodNullable:return yx(t,r);case T.ZodOptional:return $x(t,r);case T.ZodMap:return px(t,r);case T.ZodSet:return Ex(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return wx(t,r);case T.ZodNaN:case T.ZodNever:return hx(r);case T.ZodEffects:return ux(t,r);case T.ZodAny:return Pe(r);case T.ZodUnknown:return kx(r);case T.ZodDefault:return sx(t,r);case T.ZodBranded:return op(t,r);case T.ZodReadonly:return Cx(t,r);case T.ZodCatch:return ax(t,r);case T.ZodPipeline:return Ix(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(i=>{})(e)}};function G(t,e,r=!1){let i=e.seen.get(t);if(e.override){let s=e.override?.(t,e,i,r);if(s!==ex)return s}if(i&&!r){let s=Q4(i,e);if(s!==void 0)return s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let o=Dx(t,t.typeName,e),a=typeof o=="function"?G(o(),e):o;if(a&&q4(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var Q4=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ip(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,i)=>e.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Pe(e)):e.$refStrategy==="seen"?Pe(e):void 0}},q4=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ay=(t,e)=>{let r=rx(e),i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[c,l])=>({...u,[c]:G(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Pe(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=G(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Pe(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.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 V4(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function sy(t,e){return xr(t)?ri(t,{target:V4(e?.target),io:e?.pipeStrategy??"input"}):ay(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function uy(t){let r=_n(t)?.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 cy(t,e){let r=yn(t,e);if(!r.success)throw r.error;return r.data}var H4=6e4,up=class{constructor(e){this._options=e,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=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qf,async(r,i)=>{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new B(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 B(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 B(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 B(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 B(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 B(L.InvalidParams,`Task not found: ${r.params.taskId}`);if(xn(n.status))throw new B(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 B(L.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof B?n:new B(L.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,i,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.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(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){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=e;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)||FE(o)?this._onresponse(o):FA(o)?this._onrequest(o,a):LE(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=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=B.fromError(L.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of e.values())i(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){let i=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.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 B(L.InvalidParams,`Task not found: ${o}`);u=!0})()),i===void 0){let h={jsonrpc:"2.0",id:e.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(e.id,l);let d=BE(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(l.signal.aborted)return;let f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(h,f)},sendRequest:async(h,f,g)=>{if(l.signal.aborted)throw new B(L.ConnectionClosed,"Request was cancelled");let y={...g,relatedRequestId:e.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:e.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 B(L.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>i(e,p)).then(async h=>{if(l.signal.aborted)return;let f={result:h,jsonrpc:"2.0",id:e.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:e.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(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...i}=e.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(e)}`));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(e){let r=Number(e.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),au(e))i(e);else{let a=new B(e.error.code,e.error.message,e.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(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(au(e)&&e.result&&typeof e.result=="object"){let a=e.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(e))n(e);else{let a=B.fromError(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,i){let{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(e,r,i)}}catch(a){yield{type:"error",error:a instanceof B?a:new B(L.InternalError,String(a))}}return}let o;try{let a=await this.request(e,Mo,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new B(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 B(L.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new B(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 B?a:new B(L.InternalError,String(a))}}}request(e,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(e.method),s&&this.assertTaskCapability(e.method)}catch(v){d(v);return}i?.signal?.throwIfAborted();let m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),p.params={...e.params,_meta:{...e.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 B?v:new B(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??H4,g=()=>h(B.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(e,r){return this.request({method:"tasks/get",params:e},qf,r)}async getTaskResult(e,r,i){return this.request({method:"tasks/result",params:e},r,i)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Gf,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},qE,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let i=r?.relatedTask?.taskId;if(i){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,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={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let i=uy(e);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{let a=cy(e,n);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let i=uy(e);this._notificationHandlers.set(i,n=>{let o=cy(e,n);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,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(e,r,i??this._transport?.sessionId,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(e,r);for(let n of i)if(n.type==="request"&&FA(n.message)){let o=n.message.id,a=this._requestResolvers.get(o);a?(a(new B(L.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r,i){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e,i);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,a)=>{if(r.aborted){a(new B(L.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),a(new B(L.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await i.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let o=await i.getTask(n,r);if(!o)throw new B(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 B(L.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(xn(s.status))throw new B(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 Tx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Nx(t,e){let r={...t};for(let i in e){let n=i,o=e[n];if(o===void 0)continue;let a=r[n];Tx(a)&&Tx(o)?r[n]={...a,...o}:r[n]=o}return r}var Pk=wi(eb(),1),Ok=wi(zk(),1);function a3(){let t=new Pk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ok.default)(t),t}var Hp=class{constructor(e){this._ajv=e??a3()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);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(e){this._server=e}requestStream(e,r,i){return this._server.requestStream(e,r,i)}createMessageStream(e,r){let i=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],a=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.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:e},mu,r)}elicitInputStream(e,r){let i=this._server.getClientCapabilities(),n=e.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"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Zo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,i){return this._server.getTaskResult({taskId:e},r,i)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Rk(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function jk(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Jp=class extends up{constructor(e,r){super(r),this._serverInfo=e,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(qA,i=>this._oninitialize(i)),this.setNotificationHandler(VA,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(WA,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(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Nx(this._capabilities,e)}setRequestHandler(e,r){let n=_n(e)?.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 B(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 B(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 B(L.InvalidParams,`Invalid tools/call result: ${h}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);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 ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);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 ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){jk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Rk(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:OE.includes(r)?r:MA,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(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],n=Array.isArray(i.content)?i.content:[i.content],o=n.some(c=>c.type==="tool_result"),a=e.messages.length>1?e.messages[e.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 e.tools?this.request({method:"sampling/createMessage",params:e},ey,r):this.request({method:"sampling/createMessage",params:e},mu,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=e;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=e.mode==="form"?e:{...e,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 B(L.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof B?a:new B(L.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,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:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},ty,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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 Uk=Symbol.for("mcp.completable");function ub(t){return!!t&&typeof t=="object"&&Uk in t}function Mk(t){return t[Uk]?.complete}var Bk;(function(t){t.Completable="McpCompletable"})(Bk||(Bk={}));var Kp=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,i){if(e.length>r)throw new Error(`${i} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],i="",n=0,o=0;for(;n<e.length;)if(e[n]==="{"){i&&(r.push(i),i="");let a=e.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=e.slice(n+1,a),u=this.getOperator(s),c=s.includes("*"),l=this.getNames(s),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:u,names:l,exploded:c}),n=a+1}else i+=e[n],n++;return i&&r.push(i),r}getOperator(e){return["+","#",".","/","?","&"].find(i=>e.startsWith(i))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(i=>i.replace("*","").trim()).filter(i=>i.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let a=e.names.map(u=>{let c=r[u];if(c===void 0)return"";let l=Array.isArray(c)?c.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${u}=${l}`}).filter(u=>u.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){let a=e.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[e.name];if(i===void 0)return"";let o=(Array.isArray(i)?i:[i]).map(a=>this.encodeValue(a,e.operator));switch(e.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(e){let r="",i=!1;for(let n of this.parts){if(typeof n=="string"){r+=n;continue}let o=this.expandPart(n,e);o&&((n.operator==="?"||n.operator==="&")&&i?r+=o.replace("?","&"):r+=o,(n.operator==="?"||n.operator==="&")&&(i=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let o of e.names)t.validateLength(o,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){let a=e.names[o],s=o===0?"\\"+e.operator:"&";r.push({pattern:s+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let i,n=e.name;switch(e.operator){case"":i=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":i="(.+)";break;case".":i="\\.([^/,]+)";break;case"/":i="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:i="([^/]+)"}return r.push({pattern:i,name:n}),r}match(e){t.validateLength(e,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+="$",t.validateLength(r,1e6,"Generated regex pattern");let n=new RegExp(r),o=e.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 s3=/^[A-Za-z0-9._-]{1,128}$/;function u3(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!s3.test(t)){let r=t.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,n,o)=>o.indexOf(i)===n);return e.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:e}}return{isValid:!0,warnings:e}}function c3(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)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 cb(t){let e=u3(t);return c3(t,e.warnings),e.isValid}var Xp=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,i){let n={taskSupport:"required",...r.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,n,r._meta,i)}};function l3(t,e){let r=0,i=[t];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>e)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>e)return r;let a=n[o];a!==null&&typeof a=="object"&&i.push(a)}}return r}function d3(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var Yp=class{constructor(e,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(e,r),this._maxToolInputElements=d3(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(e){return await this.server.connect(e)}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(([,e])=>e.enabled).map(([e,r])=>{let i={name:e,title:r.title,description:r.description,inputSchema:(()=>{let n=Co(r.inputSchema);return n?sy(n,{strictUnions:!0,pipeStrategy:"input"}):f3})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=Co(r.outputSchema);n&&(i.outputSchema=sy(n,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Fo,async(e,r)=>{try{let i=this._registeredTools[e.params.name];if(!i)throw new B(L.InvalidParams,`Tool ${e.params.name} not found`);if(!i.enabled)throw new B(L.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new B(L.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new B(L.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&a)return await this.handleAutomaticTaskPolling(i,e,r);let s=await this.validateToolInput(i,e.params.arguments,e.params.name),u=await this.executeToolHandler(i,s,r);return n||await this.validateToolOutput(i,u,e.params.name),u}catch(i){if(i instanceof B&&i.code===L.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,i){if(this._maxToolInputElements!==void 0&&l3(r,this._maxToolInputElements)>this._maxToolInputElements)throw new B(L.InvalidParams,`Invalid arguments for tool ${i}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=Co(e.inputSchema)??e.inputSchema,a=await sf(o,r??{});if(!a.success){let s="error"in a?a.error:"Unknown error",u=uf(s);throw new B(L.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${u}`)}return a.data}async validateToolOutput(e,r,i){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(L.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=Co(e.outputSchema),o=await sf(n,r.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=uf(a);throw new B(L.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(e,r,i){let n=e.handler;if("createTask"in n){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(e.inputSchema){let s=n;return await Promise.resolve(s.createTask(r,a))}else{let s=n;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=n;return await Promise.resolve(a(r,i))}else{let a=n;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(e,r,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.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 B(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 e=>{switch(e.params.ref.type){case"ref/prompt":return XE(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return YE(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(L.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let i=this._registeredPrompts[r.name];if(!i)throw new B(L.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new B(L.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return Vu;let o=_n(i.argsSchema)?.[e.params.argument.name];if(!ub(o))return Vu;let a=Mk(o);if(!a)return Vu;let s=await a(e.params.argument.value,e.params.context);return Fk(s)}async handleResourceCompletion(e,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 B(L.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Vu;let o=await n(e.params.argument.value,e.params.context);return Fk(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(e,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(e,r)=>{let i=new URL(e.params.uri),n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new B(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 B(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(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?p3(r.argsSchema):void 0}))})),this.server.setRequestHandler(ep,async(e,r)=>{let i=this._registeredPrompts[e.params.name];if(!i)throw new B(L.InvalidParams,`Prompt ${e.params.name} not found`);if(!i.enabled)throw new B(L.InvalidParams,`Prompt ${e.params.name} disabled`);if(i.argsSchema){let n=Co(i.argsSchema),o=await sf(n,e.params.arguments??{});if(!o.success){let u="error"in o?o.error:"Unknown error",c=uf(u);throw new B(L.InvalidParams,`Invalid arguments for prompt ${e.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(e,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(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,i,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,i,n,o){let a={name:e,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(e,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!==e&&(delete this._registeredResourceTemplates[e],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[e]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(c=>!!i.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,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!==e&&(delete this._registeredPrompts[e],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[e]=a,n&&Object.values(n).some(u=>{let c=u instanceof si?u._def?.innerType:u;return ub(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,i,n,o,a,s,u,c){cb(e);let l={title:r,description:i,inputSchema:Lk(n),outputSchema:Lk(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!==e&&(typeof d.name=="string"&&cb(d.name),delete this._registeredTools[e],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[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let i,n,o,a;if(typeof r[0]=="string"&&(i=r.shift()),r.length>1){let u=r[0];if(lb(u))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!lb(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 ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,i,n,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:a,outputSchema:s,annotations:u,_meta:c}=r;return this._createRegisteredTool(e,n,o,a,s,u,{taskSupport:"forbidden"},c,i)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} 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(e,void 0,i,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:a}=r,s=this._createRegisteredPrompt(e,n,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Wp=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Kp(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},f3={type:"object",properties:{}};function Zk(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Qk(t){return"_def"in t||"_zod"in t||Zk(t)}function lb(t){return typeof t!="object"||t===null||Qk(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Zk)}function Lk(t){if(t){if(lb(t))return ni(t);if(!Qk(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function p3(t){let e=_n(t);return e?Object.entries(e).map(([r,i])=>{let n=lw(i),o=dw(i);return{name:r,description:n,required:!o}}):[]}function On(t){let r=_n(t)?.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 Fk(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Vu={completion:{values:[],hasMore:!1}};import Vk from"node:process";var m3=10*1024*1024,em=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??m3}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
83
83
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),h3(r)}clear(){this._buffer=void 0}};function h3(t){return ZE.parse(JSON.parse(t))}function qk(t){return JSON.stringify(t)+`
84
- `}var tm=class{constructor(e=Vk.stdin,r=Vk.stdout,i){this._stdin=e,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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise(r=>{let i=qk(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};import{readFileSync as gQ}from"node:fs";import{join as vQ}from"node:path";var Hk={name:"@kyun.si/codex-hongguo",version:"0.0.26",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 v3}from"node:os";import{posix as A3,win32 as y3}from"node:path";import{fileURLToPath as _3}from"node:url";var Rn=_3(new URL("../../",import.meta.url));function Gk({env:t=process.env,home:e=v3(),platform:r=process.platform}={}){let{join:i}=r==="win32"?y3:A3;return t.HONGGUO_DATA_DIR?t.HONGGUO_DATA_DIR:r==="darwin"?i(e,"Library","Application Support","CodexHongguo"):r==="win32"?i(t.LOCALAPPDATA||i(e,"AppData","Local"),"CodexHongguo"):i(t.XDG_DATA_HOME||i(e,".local","share"),"codex-hongguo")}import{DatabaseSync as b3}from"node:sqlite";import{mkdirSync as $3}from"node:fs";import{join as I3}from"node:path";function db(t){return typeof t=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t)}function rm(t={}){let e=[t.thread_id,t.threadId].filter(r=>r!==void 0);return e.length&&e.every(r=>db(r)&&r===e[0])?e[0]:null}function Jk(t){let e=new Map;for(let{id:r,title:i}of t)if(/^hg-\d{1,32}$/.test(r)&&typeof i=="string"&&i.trim()&&!e.has(r)&&e.set(r,{id:r,title:i}),e.size===48)break;return[...e.values()]}var Hu=class{constructor(e=Gk(),r=!1){r||$3(e,{recursive:!0,mode:448}),this.persistent=!r,this.root=e,this.db=new b3(r?":memory:":I3(e,"player.sqlite")),this.db.exec(`PRAGMA busy_timeout=250; PRAGMA journal_mode=WAL;
84
+ `}var tm=class{constructor(e=Vk.stdin,r=Vk.stdout,i){this._stdin=e,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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise(r=>{let i=qk(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};import{readFileSync as gQ}from"node:fs";import{join as vQ}from"node:path";var Hk={name:"@kyun.si/codex-hongguo",version:"0.0.27",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 v3}from"node:os";import{posix as A3,win32 as y3}from"node:path";import{fileURLToPath as _3}from"node:url";var Rn=_3(new URL("../../",import.meta.url));function Gk({env:t=process.env,home:e=v3(),platform:r=process.platform}={}){let{join:i}=r==="win32"?y3:A3;return t.HONGGUO_DATA_DIR?t.HONGGUO_DATA_DIR:r==="darwin"?i(e,"Library","Application Support","CodexHongguo"):r==="win32"?i(t.LOCALAPPDATA||i(e,"AppData","Local"),"CodexHongguo"):i(t.XDG_DATA_HOME||i(e,".local","share"),"codex-hongguo")}import{DatabaseSync as b3}from"node:sqlite";import{mkdirSync as $3}from"node:fs";import{join as I3}from"node:path";function db(t){return typeof t=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(t)}function rm(t={}){let e=[t.thread_id,t.threadId].filter(r=>r!==void 0);return e.length&&e.every(r=>db(r)&&r===e[0])?e[0]:null}function Jk(t){let e=new Map;for(let{id:r,title:i}of t)if(/^hg-\d{1,32}$/.test(r)&&typeof i=="string"&&i.trim()&&!e.has(r)&&e.set(r,{id:r,title:i}),e.size===48)break;return[...e.values()]}var Hu=class{constructor(e=Gk(),r=!1){r||$3(e,{recursive:!0,mode:448}),this.persistent=!r,this.root=e,this.db=new b3(r?":memory:":I3(e,"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,
@@ -145,7 +145,7 @@ option decryption_key `+i+`
145
145
  (async()=>{const ticket=location.hash.slice(1);history.replaceState(null,'','/pair');
146
146
  try {const r=await fetch('/exchange',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ticket})});
147
147
  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';}})()
148
- </script></html>`,Rm=class{constructor(e){this.service=e,this.tickets=new Map,this.sessions=new Map}async listen(){return this.starting||(this.server=cQ((e,r)=>this.request(e,r).catch(i=>{if(r.headersSent){r.destroy();return}r.writeHead(i instanceof j?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((e,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,e()})}).catch(e=>{throw this.starting=null,e})),this.starting}prune(){for(let e of[this.sessions,this.tickets])for(let[r,i]of e)i.expires<Date.now()&&e.delete(r)}async pair(e){await this.listen(),this.prune();let r=Yu();return this.tickets.set(r,{scope:e,expires:Date.now()+6e4}),{url:this.origin+"/pair#"+r,expiresIn:60}}async request(e,r){if(r.setHeader("Cache-Control","no-store"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("X-Content-Type-Options","nosniff"),e.headers.host!==new URL(this.origin).host)throw new j("\u4E3B\u673A\u65E0\u6548",403);if(e.method==="POST"&&e.headers.origin!==this.origin)throw new j("\u8BF7\u6C42\u6765\u6E90\u65E0\u6548",403);let i=e.url,n=KT(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"&&e.method==="GET")return o(hQ);if(this.prune(),i==="/exchange"&&e.method==="POST"){let l=await XT(e),d=this.tickets.get(l?.ticket);if(!d||d.expires<Date.now())throw new j("\u5206\u5C4F\u94FE\u63A5\u65E0\u6548",403);this.tickets.delete(l.ticket);let m=KT(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||!(e.headers.cookie||"").split(/;\s*/).includes("hg="+u.key))throw new j("\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&&e.method==="GET")return o(fQ(pQ(Rn,"dist/ui/player.html"),"utf8").replace('data-host="panel"','data-host="browser"'));if(c==="context"&&e.method==="GET")return a({identified:!!u.sessionId,turnId:u.fixedTurn,selection:u.selection});if(c.startsWith("api/")&&e.method==="POST")return a(await this.service.call(u,c.slice(4),await XT(e),!0));if(c.startsWith("media/")&&["GET","HEAD"].includes(e.method)){let l=c.slice(6);if(!u.grants.has(l))throw new j("\u8BF7\u5148\u9009\u62E9\u8BE5\u96C6",403);let d=this.service.catalog.cache?.path(l);if(!d)throw new j("\u7D20\u6750\u5F85\u91CD\u65B0\u51C6\u5907",404);let m=dQ(d,{throwIfNoEntry:!1})?.size;if(!m)throw new j("\u7F13\u5B58\u5DF2\u6E05\u7406\uFF0C\u8BF7\u91CD\u65B0\u51C6\u5907\u8BE5\u96C6",404);this.service.catalog.cache?.hold(l);let p=mQ(e.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}),e.method==="HEAD")return r.end();let g=lQ(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 j("\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 m0=new Om(yc),Ca=new cm(yc,m0),WT=new Rm(Ca);Ca.pair=t=>WT.pair(t);var $i=new Yp({name:"codex-hongguo",version:Hk.version}),e1="ui://hongguo/v15/player",jm="ui://hongguo/v15/waiting",p0="text/html;profile=mcp-app",t1={visibility:["app"]},YT={ui:{csp:{connectDomains:[],resourceDomains:["blob:"]},prefersBorder:!1}};for(let[t,e]of[[e1,"\u7EA2\u679C\u77ED\u5267"],[jm,"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6"]]){let r=t===jm,i=r?{...YT,"openai/widgetShowCodexWidgetInline":!0,"openai/widgetHeightHint":96,"openai/widgetMinFrameHeight":1,"openai/ui":{availableDisplayModes:["inline","fullscreen"],preferredDisplayMode:"inline"}}:YT,n=o=>{let a=gQ(vQ(Rn,"dist/ui/player.html"),"utf8");return{contents:[{uri:o.href,mimeType:p0,_meta:i,text:r?a.replace('data-surface="player"','data-surface="waiting"'):a}]}};$i.registerResource(e,t,{mimeType:p0,_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===t)continue;let s=new Wp(a,{list:void 0});$i.registerResource(e+"\uFF08"+o+"\uFF09",s,{mimeType:p0,_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:jm},"openai/ui":{preferredModelDisplayMode:"inline"}}},({turnId:t},e)=>{let r=Ca.openWaiting(e._meta,t);return{content:[],structuredContent:{shown:!!r},_meta:r?{panel:r.panel,waitingTurn:t,ui:{resourceUri:jm}}:{}}});$i.registerTool("open_drama_panel",{title:"\u7EA2\u679C\u77ED\u5267",description:"\u5728\u5F53\u524D\u4F1A\u8BDD\u9009\u5267\u4E0E\u7EED\u64AD",inputSchema:{},_meta:{ui:{...t1,resourceUri:e1},"openai/ui":{entrypoints:[{type:"thread"},{type:"global"}]}}},(t,e)=>{let r=Ca.open(e._meta);return m0.recommendations().catch(()=>{}),{content:[],structuredContent:{state:r.state,identified:r.identified},_meta:{panel:r.panel}}});for(let[t,e]of Object.entries(Nb))$i.registerTool(t,{inputSchema:{...e.shape,panel:Z.string().max(80)},_meta:{ui:t1}},async({panel:r,...i},n)=>{try{let o=await Ca.call(Ca.panel(r,n._meta),t,i);return{content:[],_meta:{data:o}}}catch(o){return{isError:!0,content:[{type:"text",text:nm(o)}]}}});$i.server.onclose=()=>{m0.panelMedia?.close(),WT.close(),yc.close()};await $i.connect(new tm);
148
+ </script></html>`,Rm=class{constructor(e){this.service=e,this.tickets=new Map,this.sessions=new Map}async listen(){return this.starting||(this.server=cQ((e,r)=>this.request(e,r).catch(i=>{if(r.headersSent){r.destroy();return}r.writeHead(i instanceof j?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((e,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,e()})}).catch(e=>{throw this.starting=null,e})),this.starting}prune(){for(let e of[this.sessions,this.tickets])for(let[r,i]of e)i.expires<Date.now()&&e.delete(r)}async pair(e){await this.listen(),this.prune();let r=Yu();return this.tickets.set(r,{scope:e,expires:Date.now()+6e4}),{url:this.origin+"/pair#"+r,expiresIn:60}}async request(e,r){if(r.setHeader("Cache-Control","no-store"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("X-Content-Type-Options","nosniff"),e.headers.host!==new URL(this.origin).host)throw new j("\u4E3B\u673A\u65E0\u6548",403);if(e.method==="POST"&&e.headers.origin!==this.origin)throw new j("\u8BF7\u6C42\u6765\u6E90\u65E0\u6548",403);let i=e.url,n=KT(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"&&e.method==="GET")return o(hQ);if(this.prune(),i==="/exchange"&&e.method==="POST"){let l=await XT(e),d=this.tickets.get(l?.ticket);if(!d||d.expires<Date.now())throw new j("\u5206\u5C4F\u94FE\u63A5\u65E0\u6548",403);this.tickets.delete(l.ticket);let m=KT(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||!(e.headers.cookie||"").split(/;\s*/).includes("hg="+u.key))throw new j("\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&&e.method==="GET")return o(fQ(pQ(Rn,"dist/ui/player.html"),"utf8").replace('data-host="panel"','data-host="browser"'));if(c==="context"&&e.method==="GET")return a({identified:!!u.sessionId,turnId:u.fixedTurn,selection:u.selection});if(c.startsWith("api/")&&e.method==="POST")return a(await this.service.call(u,c.slice(4),await XT(e),!0));if(c.startsWith("media/")&&["GET","HEAD"].includes(e.method)){let l=c.slice(6);if(!u.grants.has(l))throw new j("\u8BF7\u5148\u9009\u62E9\u8BE5\u96C6",403);let d=this.service.catalog.cache?.path(l);if(!d)throw new j("\u7D20\u6750\u5F85\u91CD\u65B0\u51C6\u5907",404);let m=dQ(d,{throwIfNoEntry:!1})?.size;if(!m)throw new j("\u7F13\u5B58\u5DF2\u6E05\u7406\uFF0C\u8BF7\u91CD\u65B0\u51C6\u5907\u8BE5\u96C6",404);this.service.catalog.cache?.hold(l);let p=mQ(e.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}),e.method==="HEAD")return r.end();let g=lQ(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 j("\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 m0=new Om(yc),Ca=new cm(yc,m0),WT=new Rm(Ca);Ca.pair=t=>WT.pair(t);var $i=new Yp({name:"codex-hongguo",version:Hk.version}),e1="ui://hongguo/v16/player",jm="ui://hongguo/v16/waiting",p0="text/html;profile=mcp-app",t1={visibility:["app"]},YT={ui:{csp:{connectDomains:[],resourceDomains:["blob:"]},prefersBorder:!1}};for(let[t,e]of[[e1,"\u7EA2\u679C\u77ED\u5267"],[jm,"\u7B49\u5F85\u65F6\u770B\u4E00\u96C6"]]){let r=t===jm,i=r?{...YT,"openai/widgetShowCodexWidgetInline":!0,"openai/widgetHeightHint":96,"openai/widgetMinFrameHeight":1,"openai/ui":{availableDisplayModes:["inline","fullscreen"],preferredDisplayMode:"inline"}}:YT,n=o=>{let a=gQ(vQ(Rn,"dist/ui/player.html"),"utf8");return{contents:[{uri:o.href,mimeType:p0,_meta:i,text:r?a.replace('data-surface="player"','data-surface="waiting"'):a}]}};$i.registerResource(e,t,{mimeType:p0,_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===t)continue;let s=new Wp(a,{list:void 0});$i.registerResource(e+"\uFF08"+o+"\uFF09",s,{mimeType:p0,_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:jm},"openai/ui":{preferredModelDisplayMode:"inline"}}},({turnId:t},e)=>{let r=Ca.openWaiting(e._meta,t);return{content:[],structuredContent:{shown:!!r},_meta:r?{panel:r.panel,waitingTurn:t,ui:{resourceUri:jm}}:{}}});$i.registerTool("open_drama_panel",{title:"\u7EA2\u679C\u77ED\u5267",description:"\u5728\u5F53\u524D\u4F1A\u8BDD\u9009\u5267\u4E0E\u7EED\u64AD",inputSchema:{},_meta:{ui:{...t1,resourceUri:e1},"openai/ui":{entrypoints:[{type:"thread"},{type:"global"}]}}},(t,e)=>{let r=Ca.open(e._meta);return m0.recommendations().catch(()=>{}),{content:[],structuredContent:{state:r.state,identified:r.identified},_meta:{panel:r.panel}}});for(let[t,e]of Object.entries(Nb))$i.registerTool(t,{inputSchema:{...e.shape,panel:Z.string().max(80)},_meta:{ui:t1}},async({panel:r,...i},n)=>{try{let o=await Ca.call(Ca.panel(r,n._meta),t,i);return{content:[],_meta:{data:o}}}catch(o){return{isError:!0,content:[{type:"text",text:nm(o)}]}}});$i.server.onclose=()=>{m0.panelMedia?.close(),WT.close(),yc.close()};await $i.connect(new tm);
149
149
  /*! Bundled license information:
150
150
 
151
151
  xz-decompress/dist/package/xz-decompress.js: