@octavus/agent 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-extension-mcp.js +2 -2
- package/dist/index.js +48 -48
- package/dist/screen-publisher/index.js +2 -2
- package/package.json +1 -1
|
@@ -57,5 +57,5 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
57
57
|
`:`[${u[s]}\r
|
|
58
58
|
]`;continue}r+=u[s],u[s]==="\\"?i=!0:a&&u[s]==="]"?a=!1:!a&&u[s]==="["&&(a=!0)}try{new RegExp(r)}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 r}function Ap(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===W.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((u,r)=>({...u,[r]:Fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??dt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===W.ZodString&&e.keyType._def.checks?.length){const{type:u,...r}=xp(e.keyType._def,t);return{...n,propertyNames:r}}else{if(e.keyType?._def.typeName===W.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===W.ZodBranded&&e.keyType._def.type._def.typeName===W.ZodString&&e.keyType._def.type._def.checks?.length){const{type:u,...r}=kp(e.keyType._def,t);return{...n,propertyNames:r}}}return n}function T6(e,t){if(t.mapStrategy==="record")return Ap(e,t);const n=Fe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||dt(t),u=Fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||dt(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,u],minItems:2,maxItems:2}}}function F6(e){const t=e.values,u=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),r=Array.from(new Set(u.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:u}}function P6(e){return e.target==="openAi"?void 0:{not:dt({...e,currentPath:[...e.currentPath,"not"]})}}function j6(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ei={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function O6(e,t){if(t.target==="openApi3")return Ip(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(u=>u._def.typeName in Ei&&(!u._def.checks||!u._def.checks.length))){const u=n.reduce((r,i)=>{const a=Ei[i._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:u.length>1?u:u[0]}}else if(n.every(u=>u._def.typeName==="ZodLiteral"&&!u.description)){const u=n.reduce((r,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(i._def.value===null)return[...r,"null"];default:return r}},[]);if(u.length===n.length){const r=u.filter((i,a,o)=>o.indexOf(i)===a);return{type:r.length>1?r:r[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(u=>u._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((u,r)=>[...u,...r._def.values.filter(i=>!u.includes(i))],[])};return Ip(e,t)}var Ip=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((u,r)=>Fe(u._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(u=>!!u&&(!t.strictUnions||typeof u=="object"&&Object.keys(u).length>0));return n.length?{anyOf:n}:void 0};function z6(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:Ei[e.innerType._def.typeName],nullable:!0}:{type:[Ei[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const u=Fe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return u&&"$ref"in u?{allOf:[u],nullable:!0}:u&&{...u,nullable:!0}}const n=Fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function N6(e,t){const n={type:"number"};if(!e.checks)return n;for(const u of e.checks)switch(u.kind){case"int":n.type="integer",Cp(n,"type",u.message,t);break;case"min":t.target==="jsonSchema7"?u.inclusive?je(n,"minimum",u.value,u.message,t):je(n,"exclusiveMinimum",u.value,u.message,t):(u.inclusive||(n.exclusiveMinimum=!0),je(n,"minimum",u.value,u.message,t));break;case"max":t.target==="jsonSchema7"?u.inclusive?je(n,"maximum",u.value,u.message,t):je(n,"exclusiveMaximum",u.value,u.message,t):(u.inclusive||(n.exclusiveMaximum=!0),je(n,"maximum",u.value,u.message,t));break;case"multipleOf":je(n,"multipleOf",u.value,u.message,t);break}return n}function R6(e,t){const n=t.target==="openAi",u={type:"object",properties:{}},r=[],i=e.shape();for(const o in i){let s=i[o];if(s===void 0||s._def===void 0)continue;let c=Z6(s);c&&n&&(s._def.typeName==="ZodOptional"&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),c=!1);const l=Fe(s._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});l!==void 0&&(u.properties[o]=l,c||r.push(o))}r.length&&(u.required=r);const a=U6(e,t);return a!==void 0&&(u.additionalProperties=a),u}function U6(e,t){if(e.catchall._def.typeName!=="ZodNever")return Fe(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 Z6(e){try{return e.isOptional()}catch{return!0}}var M6=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Fe(e.innerType._def,t);const n=Fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:dt(t)},n]}:dt(t)},L6=(e,t)=>{if(t.pipeStrategy==="input")return Fe(e.in._def,t);if(t.pipeStrategy==="output")return Fe(e.out._def,t);const n=Fe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),u=Fe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,u].filter(r=>r!==void 0)}};function q6(e,t){return Fe(e.type._def,t)}function V6(e,t){const u={type:"array",uniqueItems:!0,items:Fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&je(u,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&je(u,"maxItems",e.maxSize.value,e.maxSize.message,t),u}function J6(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,u)=>Fe(n._def,{...t,currentPath:[...t.currentPath,"items",`${u}`]})).reduce((n,u)=>u===void 0?n:[...n,u],[]),additionalItems:Fe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,u)=>Fe(n._def,{...t,currentPath:[...t.currentPath,"items",`${u}`]})).reduce((n,u)=>u===void 0?n:[...n,u],[])}}function W6(e){return{not:dt(e)}}function G6(e){return dt(e)}var H6=(e,t)=>Fe(e.innerType._def,t),K6=(e,t,n)=>{switch(t){case W.ZodString:return xp(e,n);case W.ZodNumber:return N6(e,n);case W.ZodObject:return R6(e,n);case W.ZodBigInt:return E6(e,n);case W.ZodBoolean:return D6();case W.ZodDate:return Sp(e,n);case W.ZodUndefined:return W6(n);case W.ZodNull:return j6(n);case W.ZodArray:return y6(e,n);case W.ZodUnion:case W.ZodDiscriminatedUnion:return O6(e,n);case W.ZodIntersection:return x6(e,n);case W.ZodTuple:return J6(e,n);case W.ZodRecord:return Ap(e,n);case W.ZodLiteral:return B6(e,n);case W.ZodEnum:return k6(e);case W.ZodNativeEnum:return F6(e);case W.ZodNullable:return z6(e,n);case W.ZodOptional:return M6(e,n);case W.ZodMap:return T6(e,n);case W.ZodSet:return V6(e,n);case W.ZodLazy:return()=>e.getter()._def;case W.ZodPromise:return q6(e,n);case W.ZodNaN:case W.ZodNever:return P6(n);case W.ZodEffects:return w6(e,n);case W.ZodAny:return dt(n);case W.ZodUnknown:return G6(n);case W.ZodDefault:return C6(e,n);case W.ZodBranded:return kp(e,n);case W.ZodReadonly:return H6(e,n);case W.ZodCatch:return b6(e,n);case W.ZodPipeline:return L6(e,n);case W.ZodFunction:case W.ZodVoid:case W.ZodSymbol:return;default:return(u=>{})(t)}};function Fe(e,t,n=!1){const u=t.seen.get(e);if(t.override){const o=t.override?.(e,t,u,n);if(o!==v6)return o}if(u&&!n){const o=X6(u,t);if(o!==void 0)return o}const r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);const i=K6(e,e.typeName,t),a=typeof i=="function"?Fe(i(),t):i;if(a&&Y6(e,t,a),t.postProcess){const o=t.postProcess(a,e,t);return r.jsonSchema=a,o}return r.jsonSchema=a,a}var X6=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:wp(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,u)=>t.currentPath[u]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),dt(t)):t.$refStrategy==="seen"?dt(t):void 0}},Y6=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Q6=(e,t)=>{const n=_6(t);let u=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((s,[c,l])=>({...s,[c]:Fe(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??dt(n)}),{}):void 0;const r=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Fe(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??dt(n),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a),n.flags.hasReferencedOpenAiAnyType&&(u||(u={}),u[n.openAiAnyTypeName]||(u[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const o=r===void 0?u?{...i,[n.definitionPath]:u}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...u,[r]:i}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function e3(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Tp(e,t){return Pt(e)?Xa(e,{target:e3(t?.target),io:t?.pipeStrategy??"input"}):Q6(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Fp(e){const n=ln(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const u=If(n);if(typeof u!="string")throw new Error("Schema method literal must be a string");return u}function Pp(e,t){const n=cn(e,t);if(!n.success)throw n.error;return n.data}var t3=6e4,r3=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(Xo,t=>{this._oncancel(t)}),this.setNotificationHandler(Qo,t=>{this._onprogress(t)}),this.setRequestHandler(Yo,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(es,async(t,n)=>{const u=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!u)throw new oe(le.InvalidParams,"Failed to retrieve task: Task not found");return{...u}}),this.setRequestHandler(rs,async(t,n)=>{const u=async()=>{const r=t.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(r,n.sessionId);){if(a.type==="response"||a.type==="error"){const o=a.message,s=o.id,c=this._requestResolvers.get(s);if(c)if(this._requestResolvers.delete(s),a.type==="response")c(o);else{const l=o,f=new oe(l.error.code,l.error.message,l.error.data);c(f)}else{const l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${s}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(r,n.sessionId);if(!i)throw new oe(le.InvalidParams,`Task not found: ${r}`);if(!lr(i.status))return await this._waitForTaskUpdate(r,n.signal),await u();if(lr(i.status)){const a=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...a,_meta:{...a._meta,[cr]:{taskId:r}}}}return await u()};return await u()}),this.setRequestHandler(ns,async(t,n)=>{try{const{tasks:u,nextCursor:r}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:u,nextCursor:r,_meta:{}}}catch(u){throw new oe(le.InvalidParams,`Failed to list tasks: ${u instanceof Error?u.message:String(u)}`)}}),this.setRequestHandler(is,async(t,n)=>{try{const u=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!u)throw new oe(le.InvalidParams,`Task not found: ${t.params.taskId}`);if(lr(u.status))throw new oe(le.InvalidParams,`Cannot cancel task in terminal status: ${u.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);const r=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!r)throw new oe(le.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(u){throw u instanceof oe?u:new oe(le.InvalidRequest,`Failed to cancel task: ${u instanceof Error?u.message:String(u)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,u,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(u,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:u})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),oe.fromError(le.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.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;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=r=>{n?.(r),this._onerror(r)};const u=this._transport?.onmessage;this._transport.onmessage=(r,i)=>{u?.(r,i),mi(r)||U_(r)?this._onresponse(r):lp(r)?this._onrequest(r,i):R_(r)?this._onnotification(r):this._onerror(new Error(`Unknown message type: ${JSON.stringify(r)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(const n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();const t=oe.fromError(le.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,u=this._transport,r=e.params?._meta?.[cr]?.taskId;if(n===void 0){const c={jsonrpc:"2.0",id:e.id,error:{code:le.MethodNotFound,message:"Method not found"}};r&&this._taskMessageQueue?this._enqueueTaskMessage(r,{type:"error",message:c,timestamp:Date.now()},u?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):u?.send(c).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const a=N_(e.params)?e.params.task:void 0,o=this._taskStore?this.requestTaskStore(e,u?.sessionId):void 0,s={signal:i.signal,sessionId:u?.sessionId,_meta:e.params?._meta,sendNotification:async c=>{if(i.signal.aborted)return;const l={relatedRequestId:e.id};r&&(l.relatedTask={taskId:r}),await this.notification(c,l)},sendRequest:async(c,l,f)=>{if(i.signal.aborted)throw new oe(le.ConnectionClosed,"Request was cancelled");const g={...f,relatedRequestId:e.id};r&&!g.relatedTask&&(g.relatedTask={taskId:r});const D=g.relatedTask?.taskId??r;return D&&o&&await o.updateTaskStatus(D,"input_required"),await this.request(c,l,g)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:r,taskStore:o,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,s)).then(async c=>{if(i.signal.aborted)return;const l={result:c,jsonrpc:"2.0",id:e.id};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"response",message:l,timestamp:Date.now()},u?.sessionId):await u?.send(l)},async c=>{if(i.signal.aborted)return;const l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:le.InternalError,message:c.message??"Internal error",...c.data!==void 0&&{data:c.data}}};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"error",message:l,timestamp:Date.now()},u?.sessionId):await u?.send(l)}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,u=Number(t),r=this._progressHandlers.get(u);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(u),a=this._timeoutInfo.get(u);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(u)}catch(o){this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),i(o);return}r(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),mi(e))n(e);else{const i=new oe(e.error.code,e.error.message,e.error.data);n(i)}return}const u=this._responseHandlers.get(t);if(u===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(mi(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const a=i.task;typeof a.taskId=="string"&&(r=!0,this._taskProgressTokens.set(a.taskId,t))}}if(r||this._progressHandlers.delete(t),mi(e))u(e);else{const i=oe.fromError(e.error.code,e.error.message,e.error.data);u(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){const{task:u}=n??{};if(!u){try{yield{type:"result",result:await this.request(e,t,n)}}catch(i){yield{type:"error",error:i instanceof oe?i:new oe(le.InternalError,String(i))}}return}let r;try{const i=await this.request(e,pi,n);if(i.task)r=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new oe(le.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:a},lr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)}:a.status==="failed"?yield{type:"error",error:new oe(le.InternalError,`Task ${r} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new oe(le.InternalError,`Task ${r} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)};return}const o=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(s=>setTimeout(s,o)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof oe?i:new oe(le.InternalError,String(i))}}}request(e,t,n){const{relatedRequestId:u,resumptionToken:r,onresumptiontoken:i,task:a,relatedTask:o}=n??{};return new Promise((s,c)=>{const l=m=>{c(m)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(m){l(m);return}n?.signal?.throwIfAborted();const f=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),g.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(g.params={...g.params,task:a}),o&&(g.params={...g.params,_meta:{...g.params?._meta||{},[cr]:o}});const D=m=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(m)}},{relatedRequestId:u,resumptionToken:r,onresumptiontoken:i}).catch(p=>this._onerror(new Error(`Failed to send cancellation: ${p}`)));const _=m instanceof oe?m:new oe(le.RequestTimeout,String(m));c(_)};this._responseHandlers.set(f,m=>{if(!n?.signal?.aborted){if(m instanceof Error)return c(m);try{const _=cn(t,m.result);_.success?s(_.data):c(_.error)}catch(_){c(_)}}}),n?.signal?.addEventListener("abort",()=>{D(n?.signal?.reason)});const y=n?.timeout??t3,$=()=>D(oe.fromError(le.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(f,y,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);const E=o?.taskId;if(E){const m=_=>{const p=this._responseHandlers.get(f);p?p(_):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,m),this._enqueueTaskMessage(E,{type:"request",message:g,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(f),c(_)})}else this._transport.send(g,{relatedRequestId:u,resumptionToken:r,onresumptiontoken:i}).catch(m=>{this._cleanupTimeout(f),c(m)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},ts,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},us,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},ny,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[cr]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.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 a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[cr]:t.relatedTask}}}),this._transport?.send(a,t).catch(o=>this._onerror(o))});return}let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[cr]:t.relatedTask}}}),await this._transport.send(i,t)}setRequestHandler(e,t){const n=Fp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(u,r)=>{const i=Pp(e,u);return Promise.resolve(t(i,r))})}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,t){const n=Fp(e);this._notificationHandlers.set(n,u=>{const r=Pp(e,u);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const u=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,u)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const u of n)if(u.type==="request"&&lp(u.message)){const r=u.message.id,i=this._requestResolvers.get(r);i?(i(new oe(le.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const u=await this._taskStore?.getTask(e);u?.pollInterval&&(n=u.pollInterval)}catch{}return new Promise((u,r)=>{if(t.aborted){r(new oe(le.InvalidRequest,"Request cancelled"));return}const i=setTimeout(u,n);t.addEventListener("abort",()=>{clearTimeout(i),r(new oe(le.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async u=>{if(!e)throw new Error("No request provided");return await n.createTask(u,e.id,{method:e.method,params:e.params},t)},getTask:async u=>{const r=await n.getTask(u,t);if(!r)throw new oe(le.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(u,r,i)=>{await n.storeTaskResult(u,r,i,t);const a=await n.getTask(u,t);if(a){const o=hi.parse({method:"notifications/tasks/status",params:a});await this.notification(o),lr(a.status)&&this._cleanupTaskProgressHandler(u)}},getTaskResult:u=>n.getTaskResult(u,t),updateTaskStatus:async(u,r,i)=>{const a=await n.getTask(u,t);if(!a)throw new oe(le.InvalidParams,`Task "${u}" not found - it may have been cleaned up`);if(lr(a.status))throw new oe(le.InvalidParams,`Cannot update task "${u}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(u,r,i,t);const o=await n.getTask(u,t);if(o){const s=hi.parse({method:"notifications/tasks/status",params:o});await this.notification(s),lr(o.status)&&this._cleanupTaskProgressHandler(u)}},listTasks:u=>n.listTasks(u,t)}}};function jp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function n3(e,t){const n={...e};for(const u in t){const r=u,i=t[r];if(i===void 0)continue;const a=n[r];jp(a)&&jp(i)?n[r]={...a,...i}:n[r]=i}return n}var u3=It(Gs(),1),i3=It(_h(),1);function a3(){const e=new u3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0}),t=i3.default;return t(e),e}var o3=class{constructor(e){this._ajv=e??a3()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>t(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},s3=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){const n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const u=e.messages[e.messages.length-1],r=Array.isArray(u.content)?u.content:[u.content],i=r.some(c=>c.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=a?Array.isArray(a.content)?a.content:[a.content]:[],s=o.some(c=>c.type==="tool_use");if(i){if(r.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!s)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){const c=new Set(o.filter(f=>f.type==="tool_use").map(f=>f.id)),l=new Set(r.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(c.size!==l.size||![...c].every(f=>l.has(f)))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},ys,t)}elicitInputStream(e,t){const n=this._server.getClientCapabilities(),u=e.mode??"form";switch(u){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}const r=u==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:r},yi,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function c3(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function l3(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var d3=class extends r3{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(gi.options.map((n,u)=>[n,u])),this.isMessageIgnored=(n,u)=>{const r=this._loggingLevels.get(u);return r?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(r):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new o3,this.setRequestHandler(mp,n=>this._oninitialize(n)),this.setNotificationHandler(pp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ep,async(n,u)=>{const r=u.sessionId||u.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=gi.safeParse(i);return a.success&&this._loggingLevels.set(r,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new s3(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=n3(this._capabilities,e)}setRequestHandler(e,t){const u=ln(e)?.method;if(!u)throw new Error("Schema is missing a method literal");let r;if(Pt(u)){const a=u;r=a._zod?.def?.value??a.value}else{const a=u;r=a._def?.value??a.value}if(typeof r!="string")throw new Error("Schema method literal must be a string");if(r==="tools/call"){const a=async(o,s)=>{const c=cn(vi,o);if(!c.success){const D=c.error instanceof Error?c.error.message:String(c.error);throw new oe(le.InvalidParams,`Invalid tools/call request: ${D}`)}const{params:l}=c.data,f=await Promise.resolve(t(o,s));if(l.task){const D=cn(pi,f);if(!D.success){const y=D.error instanceof Error?D.error.message:String(D.error);throw new oe(le.InvalidParams,`Invalid task creation result: ${y}`)}return D.data}const g=cn(_s,f);if(!g.success){const D=g.error instanceof Error?g.error.message:String(g.error);throw new oe(le.InvalidParams,`Invalid tools/call result: ${D}`)}return g.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}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){l3(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&c3(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:j_.includes(t)?t:ap,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"},Ko)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const n=e.messages[e.messages.length-1],u=Array.isArray(n.content)?n.content:[n.content],r=u.some(s=>s.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(s=>s.type==="tool_use");if(r){if(u.some(s=>s.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!o)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(o){const s=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),c=new Set(u.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(s.size!==c.size||![...s].every(l=>c.has(l)))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},Dp,t):this.request({method:"sampling/createMessage",params:e},ys,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const u=e;return this.request({method:"elicitation/create",params:u},yi,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const u=e.mode==="form"?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:u},yi,t);if(r.action==="accept"&&r.content&&u.requestedSchema)try{const a=this._jsonSchemaValidator.getValidator(u.requestedSchema)(r.content);if(!a.valid)throw new oe(le.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof oe?i:new oe(le.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return r}}}createElicitationCompletionNotifier(e,t){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}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},bp,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))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"})}},Op=Symbol.for("mcp.completable");function zp(e){return!!e&&typeof e=="object"&&Op in e}function f3(e){return e[Op]?.complete}var Np;(function(e){e.Completable="McpCompletable"})(Np||(Np={}));var m3=/^[A-Za-z0-9._-]{1,128}$/;function p3(e){const 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"),!m3.test(e)){const n=e.split("").filter(u=>!/[A-Za-z0-9._-]/.test(u)).filter((u,r,i)=>i.indexOf(u)===r);return t.push(`Tool name contains invalid characters: ${n.map(u=>`"${u}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function h3(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const n of t)console.warn(` - ${n}`);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 Rp(e){const t=p3(e);return h3(e,t.warnings),t.isValid}var v3=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){const u={taskSupport:"required",...t.execution};if(u.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,u,t._meta,n)}},g3=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new d3(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new v3(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Qt(gs)),this.server.assertCanSetRequestHandler(Qt(vi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const u=dn(t.inputSchema);return u?Tp(u,{strictUnions:!0,pipeStrategy:"input"}):_3})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const u=dn(t.outputSchema);u&&(n.outputSchema=Tp(u,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(vi,async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new oe(le.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new oe(le.InvalidParams,`Tool ${e.params.name} disabled`);const u=!!e.params.task,r=n.execution?.taskSupport,i="createTask"in n.handler;if((r==="required"||r==="optional")&&!i)throw new oe(le.InternalError,`Tool ${e.params.name} has taskSupport '${r}' but was not registered with registerToolTask`);if(r==="required"&&!u)throw new oe(le.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(r==="optional"&&!u&&i)return await this.handleAutomaticTaskPolling(n,e,t);const a=await this.validateToolInput(n,e.params.arguments,e.params.name),o=await this.executeToolHandler(n,a,t);return u||await this.validateToolOutput(n,o,e.params.name),o}catch(n){if(n instanceof oe&&n.code===le.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const r=dn(e.inputSchema)??e.inputSchema,i=await Ya(r,t);if(!i.success){const a="error"in i?i.error:"Unknown error",o=Qa(a);throw new oe(le.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${o}`)}return i.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new oe(le.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const u=dn(e.outputSchema),r=await Ya(u,t.structuredContent);if(!r.success){const i="error"in r?r.error:"Unknown error",a=Qa(i);throw new oe(le.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,t,n){const u=e.handler;if("createTask"in u){if(!n.taskStore)throw new Error("No task store provided.");const i={...n,taskStore:n.taskStore};if(e.inputSchema){const a=u;return await Promise.resolve(a.createTask(t,i))}else{const a=u;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){const i=u;return await Promise.resolve(i(t,n))}else{const i=u;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const u=await this.validateToolInput(e,t.params.arguments,t.params.name),r=e.handler,i={...n,taskStore:n.taskStore},a=u?await Promise.resolve(r.createTask(u,i)):await Promise.resolve(r.createTask(i)),o=a.task.taskId;let s=a.task;const c=s.pollInterval??5e3;for(;s.status!=="completed"&&s.status!=="failed"&&s.status!=="cancelled";){await new Promise(f=>setTimeout(f,c));const l=await n.taskStore.getTask(o);if(!l)throw new oe(le.InternalError,`Task ${o} not found during polling`);s=l}return await n.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Qt(Es)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Es,async e=>{switch(e.params.ref.type){case"ref/prompt":return c6(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return l6(e),this.handleResourceCompletion(e,e.params.ref);default:throw new oe(le.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new oe(le.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new oe(le.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Tn;const r=ln(n.argsSchema)?.[e.params.argument.name];if(!zp(r))return Tn;const i=f3(r);if(!i)return Tn;const a=await i(e.params.argument.value,e.params.context);return Lp(a)}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Tn;throw new oe(le.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const u=n.resourceTemplate.completeCallback(e.params.argument.name);if(!u)return Tn;const r=await u(e.params.argument.value,e.params.context);return Lp(r)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Qt(os)),this.server.assertCanSetRequestHandler(Qt(ss)),this.server.assertCanSetRequestHandler(Qt(ls)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(os,async(e,t)=>{const n=Object.entries(this._registeredResources).filter(([r,i])=>i.enabled).map(([r,i])=>({uri:r,name:i.name,...i.metadata})),u=[];for(const r of Object.values(this._registeredResourceTemplates)){if(!r.resourceTemplate.listCallback)continue;const i=await r.resourceTemplate.listCallback(t);for(const a of i.resources)u.push({...r.metadata,...a})}return{resources:[...n,...u]}}),this.server.setRequestHandler(ss,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,n])=>({name:t,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ls,async(e,t)=>{const n=new URL(e.params.uri),u=this._registeredResources[n.toString()];if(u){if(!u.enabled)throw new oe(le.InvalidParams,`Resource ${n} disabled`);return u.readCallback(n,t)}for(const r of Object.values(this._registeredResourceTemplates)){const i=r.resourceTemplate.uriTemplate.match(n.toString());if(i)return r.readCallback(n,i,t)}throw new oe(le.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Qt(ds)),this.server.assertCanSetRequestHandler(Qt(fs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ds,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?y3(t.argsSchema):void 0}))})),this.server.setRequestHandler(fs,async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new oe(le.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new oe(le.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const u=dn(n.argsSchema),r=await Ya(u,e.params.arguments);if(!r.success){const o="error"in r?r.error:"Unknown error",s=Qa(o);throw new oe(le.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s}`)}const i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{const u=n.callback;return await Promise.resolve(u(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let u;typeof n[0]=="object"&&(u=n.shift());const r=n[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const i=this._createRegisteredResource(e,void 0,t,u,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const i=this._createRegisteredResourceTemplate(e,void 0,t,u,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,n,u){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const r=this._createRegisteredResource(e,n.title,t,n,u);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const r=this._createRegisteredResourceTemplate(e,n.title,t,n,u);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}_createRegisteredResource(e,t,n,u,r){const i={name:e,title:t,metadata:u,readCallback:r,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,t,n,u,r){const i={resourceTemplate:n,title:t,metadata:u,readCallback:r,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredResourceTemplates[e],s.name&&(this._registeredResourceTemplates[s.name]=i)),typeof s.title<"u"&&(i.title=s.title),typeof s.template<"u"&&(i.resourceTemplate=s.template),typeof s.metadata<"u"&&(i.metadata=s.metadata),typeof s.callback<"u"&&(i.readCallback=s.callback),typeof s.enabled<"u"&&(i.enabled=s.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;const a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(s=>!!n.completeCallback(s))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,n,u,r){const i={title:t,description:n,argsSchema:u===void 0?void 0:Br(u),callback:r,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Br(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,u&&Object.values(u).some(o=>{const s=o instanceof bn?o._def?.innerType:o;return zp(s)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,t,n,u,r,i,a,o,s){Rp(e);const c={title:t,description:n,inputSchema:Mp(u),outputSchema:Mp(r),annotations:i,execution:a,_meta:o,handler:s,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Rp(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=c)),typeof l.title<"u"&&(c.title=l.title),typeof l.description<"u"&&(c.description=l.description),typeof l.paramsSchema<"u"&&(c.inputSchema=Br(l.paramsSchema)),typeof l.outputSchema<"u"&&(c.outputSchema=Br(l.outputSchema)),typeof l.callback<"u"&&(c.handler=l.callback),typeof l.annotations<"u"&&(c.annotations=l.annotations),typeof l._meta<"u"&&(c._meta=l._meta),typeof l.enabled<"u"&&(c.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,u,r,i;if(typeof t[0]=="string"&&(n=t.shift()),t.length>1){const o=t[0];if($s(o))u=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$s(t[0])&&(i=t.shift());else if(typeof o=="object"&&o!==null){if(Object.values(o).some(s=>typeof s=="object"&&s!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}const a=t[0];return this._createRegisteredTool(e,void 0,n,u,r,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:u,description:r,inputSchema:i,outputSchema:a,annotations:o,_meta:s}=t;return this._createRegisteredTool(e,u,r,i,a,o,{taskSupport:"forbidden"},s,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof t[0]=="string"&&(n=t.shift());let u;t.length>1&&(u=t.shift());const r=t[0],i=this._createRegisteredPrompt(e,void 0,n,u,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:u,description:r,argsSchema:i}=t,a=this._createRegisteredPrompt(e,u,r,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},_3={type:"object",properties:{}};function Up(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Zp(e){return"_def"in e||"_zod"in e||Up(e)}function $s(e){return typeof e!="object"||e===null||Zp(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Up)}function Mp(e){if(e){if($s(e))return Br(e);if(!Zp(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function y3(e){const t=ln(e);return t?Object.entries(t).map(([n,u])=>{const r=E_(u),i=D_(u);return{name:n,description:r,required:!i}}):[]}function Qt(e){const n=ln(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const u=If(n);if(typeof u=="string")return u;throw new Error("Schema method literal must be a string")}function Lp(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Tn={completion:{values:[],hasMore:!1}};import qp from"process";var E3=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
59
59
|
`);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),D3(t)}clear(){this._buffer=void 0}};function D3(e){return Z_.parse(JSON.parse(e))}function b3(e){return JSON.stringify(e)+`
|
|
60
|
-
`}var $3=class{constructor(e=qp.stdin,t=qp.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new E3,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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{const 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(t=>{const n=b3(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};import{createHash as C3}from"crypto";import{cpSync as w3,mkdirSync as Vp,readFileSync as Cs,rmSync as ws,writeFileSync as ks}from"fs";import{join as dr}from"path";import{spawn as k3,spawnSync as S3}from"child_process";import{existsSync as Jp}from"fs";import{platform as Wp}from"os";var Gp={darwin:["/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing","/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["chromium","chromium-browser"
|
|
61
|
-
`)){const u=Number(n);if(u>0){e4(u);try{process.kill(u,"SIGKILL")}catch{}}}}catch{}}function xs(e){if(Yp()==="win32"){try{Di("taskkill",["/PID",String(e),"/T","/F"],{stdio:"ignore",timeout:5e3})}catch{}return}try{process.kill(-e,"SIGKILL")}catch{}e4(e);try{process.kill(e,"SIGKILL")}catch{}}function N3(e){const t=Date.now()+O3;for(;Fn(e)&&Date.now()<t;)Atomics.wait(z3,0,0,Qp)}function R3(e){return new Promise(t=>{setTimeout(t,e)})}async function U3(e,t){if(!Fn(e))return!0;if(Yp()==="win32")try{Di("taskkill",["/PID",String(e),"/T"],{stdio:"ignore",timeout:5e3})}catch{}else try{process.kill(e,"SIGTERM")}catch{return!0}const n=Date.now()+t;for(;Date.now()<n;){if(!Fn(e))return!0;await R3(Qp)}return!Fn(e)}function Z3(e){const t=ot(e,Ss);let n=null;if(fr(t)){try{n=Number(Hp(t,"utf-8").trim()),(!Number.isFinite(n)||n<=0)&&(n=null)}catch{n=null}bi(t,{force:!0})}n!==null&&Fn(n)&&(xs(n),N3(n));try{Di("pkill",["-9","-f",`user-data-dir=${e}`],{stdio:"ignore",timeout:5e3})}catch{}}function M3(e,t){Xp(ot(e,Ss),String(t))}function L3(e){bi(ot(e,Ss),{force:!0})}function q3(e,t={}){fr(e)&&(W3(e),G3(e),H3(e,t))}var V3=["GrShaderCache","ShaderCache","GraphiteDawnCache","Crashpad","Crash Reports",ot("Default","GPUCache"),ot("Default","Code Cache"),ot("Default","DawnCache"),ot("Default","DawnGraphiteCache"),ot("Default","DawnWebGPUCache")];function J3(e){if(fr(e))for(const t of V3)Bs(ot(e,t))}function W3(e){for(const t of Kp(e))(t==="SingletonLock"||t==="SingletonCookie"||t==="SingletonSocket"||t==="RunningChromeVersion"||t.startsWith("BrowserMetrics"))&&Bs(ot(e,t));t4(ot(e,"Default"))}function Bs(e){try{bi(e,{force:!0,recursive:!0,maxRetries:4,retryDelay:100})}catch{}}function t4(e){if(fr(e))for(const t of Kp(e,{withFileTypes:!0})){const n=ot(e,t.name);t.isDirectory()?t4(n):t.name==="LOCK"&&Bs(n)}}function G3(e){const t=ot(e,"Default","Sessions");fr(t)&&bi(t,{recursive:!0,force:!0})}function H3(e,t){const{resetWindowPlacement:n,downloadDir:u,durableProfile:r}=t;if(!n&&!u&&!r)return;const i=ot(e,"Default"),a=ot(i,"Preferences");if(!(!u&&!r&&!fr(a)))try{let o={};fr(a)&&(o=JSON.parse(Hp(a,"utf-8")));let s=!1;if(n){const c=Pn(o.browser);c&&"window_placement"in c&&(delete c.window_placement,s=!0)}if(r){const c=Pn(o.session)??{};c.restore_on_startup!==1&&(c.restore_on_startup=1,o.session=c,s=!0);const l=Pn(o.profile)??{};(l.exit_type!=="Normal"||l.exited_cleanly!==!0)&&(l.exit_type="Normal",l.exited_cleanly=!0,o.profile=l,s=!0)}if(u){const c=Pn(o.download)??{};c.default_directory=u,c.prompt_for_download=!1,c.directory_upgrade=!0,o.download=c;const l=Pn(o.savefile)??{};l.default_directory=u,o.savefile=l,s=!0}if(!s)return;j3(i,{recursive:!0}),Xp(a,JSON.stringify(o))}catch{}}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var K3=15e3,X3=5e3,Y3=class{constructor(e){this.opts=e,this.workDir=dr(e.profileDir,"extension-live")}chrome=null;relaunching=!1;stopped=!1;onUnexpectedExit;relaunchChain=Promise.resolve();workDir;setUnexpectedExitHandler(e){this.onUnexpectedExit=e}isRelaunching(){return this.relaunching}start(){this.stageExtension(),this.prepareProfile({clearCaches:!1}),this.spawn()}async relaunch({clearCaches:e}){if(this.stopped)throw new Error("BrowserSupervisor is stopped");const t=this.relaunchChain.then(()=>this.doRelaunch({clearCaches:e}),()=>this.doRelaunch({clearCaches:e}));this.relaunchChain=t.then(()=>{},()=>{}),await t}async doRelaunch({clearCaches:e}){if(this.stopped)throw new Error("BrowserSupervisor is stopped");this.relaunching=!0;try{const t=this.opts.bridge.generation;this.chrome=null,this.prepareProfile({clearCaches:e}),this.spawn(),await this.opts.bridge.waitForConnectionAfter(t,K3)}finally{this.relaunching=!1}}async stop(){if(this.stopped=!0,this.chrome){const{pid:e}=this.chrome;this.chrome=null,this.opts.durableProfile&&await U3(e,X3)||xs(e)}L3(this.opts.profileDir),ws(this.workDir,{recursive:!0,force:!0})}stageExtension(){ws(this.workDir,{recursive:!0,force:!0}),w3(this.opts.extensionDir,this.workDir,{recursive:!0}),ks(dr(this.workDir,"config.json"),JSON.stringify({wsPort:this.opts.wsPort}));const e=this.stampExtensionVersion();this.evictStaleServiceWorkerOnChange(e)}stampExtensionVersion(){const e=dr(this.workDir,"manifest.json");let t;try{t=JSON.parse(Cs(e,"utf-8"))}catch{return""}const n=Q3(this.opts.extensionVersion,this.workDir);return t.version=n,ks(e,JSON.stringify(t)),n}evictStaleServiceWorkerOnChange(e){if(!e)return;const t=dr(this.opts.profileDir,".octavus-extension-version");let n;try{n=Cs(t,"utf-8").trim()}catch{n=void 0}if(n!==e){for(const u of[dr(this.opts.profileDir,"Default","Service Worker"),dr(this.opts.profileDir,"Service Worker")])ws(u,{recursive:!0,force:!0});try{Vp(this.opts.profileDir,{recursive:!0}),ks(t,e)}catch{}}}prepareProfile({clearCaches:e}){Z3(this.opts.profileDir),e&&J3(this.opts.profileDir),Vp(this.opts.profileDir,{recursive:!0}),q3(this.opts.profileDir,{resetWindowPlacement:this.opts.resetWindowPlacement,downloadDir:this.opts.downloadDir,durableProfile:this.opts.durableProfile})}spawn(){this.chrome=P3({extensions:[this.workDir,...this.opts.stealthDir?[this.opts.stealthDir]:[]],profileDir:this.opts.profileDir,chromePath:this.opts.chromePath,renderer:this.opts.renderer,acceptLanguage:this.opts.acceptLanguage,extraFlags:this.opts.extraFlags}),M3(this.opts.profileDir,this.chrome.pid),this.chrome.process.on("exit",(e,t)=>{this.stopped||this.relaunching||(console.error(`[browser-extension-mcp] Chrome exited unexpectedly (code=${String(e)}, signal=${String(t)})`),this.onUnexpectedExit?.())})}};function Q3(e,t){return e&&eE(e)||tE(t)}function eE(e){const t=e.trim().split(".");if(!(t.length>4)&&t.every(n=>/^\d{1,5}$/.test(n)&&Number(n)<=65535))return t.length===1?`0.1.${t[0]}`:t.join(".")}function tE(e){let t;try{t=Cs(dr(e,"service-worker-loader.js"),"utf-8")}catch{t=String(Date.now())}const n=C3("sha256").update(t).digest();return`2.${n.readUInt16BE(0)}.${n.readUInt16BE(2)}`}import{createServer as r4}from"http";var A5=It(Dh(),1),I5=It(Ti(),1),T5=It(Zr(),1),F5=It(Hs(),1),P5=It(Ks(),1),j5=It(Xs(),1),O5=It(Fi(),1),rE=It(bh(),1),n4=3e4,nE=1e4,uE="render_wedged",As=class extends Error{constructor(e,t){super(e),this.code=t,this.name="BridgeError"}};function iE(e){return e instanceof As&&e.code===uE}var aE=class{server;wss;client=null;pending=new Map;requestCounter=0;readyPromise;readyResolve;disconnectTimer=null;onExtensionLostPermanently;connectionGeneration=0;connectionWaiters=[];recordingHandler=null;port;constructor(e){this.port=e,this.server=r4(),this.wss=new rE.default({server:this.server}),this.readyPromise=new Promise(t=>{this.readyResolve=t}),this.wss.on("connection",t=>{this.clearDisconnectTimer(),this.client=t,t.on("message",n=>{this.handleMessage(String(n))}),t.on("close",()=>{this.client===t&&(this.client=null,this.rejectAllPending("Extension disconnected"),this.scheduleDisconnectTimeout())})})}setExtensionLostHandler(e){this.onExtensionLostPermanently=e}setRecordingHandler(e){this.recordingHandler=e}async start(){await new Promise((e,t)=>{this.server.listen(this.port,"127.0.0.1",()=>{e()}),this.server.on("error",t)})}async waitForReady(e=3e4){await Promise.race([this.readyPromise,new Promise((t,n)=>{setTimeout(()=>{n(new Error("Extension did not connect within timeout"))},e)})])}get generation(){return this.connectionGeneration}async waitForConnectionAfter(e,t=3e4){this.connectionGeneration>e||await new Promise((n,u)=>{const r={},i=()=>{r.timer&&clearTimeout(r.timer),n()};r.timer=setTimeout(()=>{this.connectionWaiters=this.connectionWaiters.filter(a=>a!==i),u(new Error("Extension did not reconnect within timeout"))},t),this.connectionWaiters.push(i)})}async sendCommand(e,t){if(this.client?.readyState!==1)throw new Error("Extension not connected");this.requestCounter+=1;const n=`req_${this.requestCounter}`;return await new Promise((u,r)=>{const i=setTimeout(()=>{this.pending.delete(n),r(new Error(`Command "${e}" timed out after ${n4}ms`))},n4);this.pending.set(n,{resolve:u,reject:r,timer:i}),this.client.send(JSON.stringify({id:n,cmd:e,args:t}))})}async stop(){this.clearDisconnectTimer(),this.rejectAllPending("MCP server shutting down"),this.client&&(this.client.close(),this.client=null),await new Promise(e=>{this.wss.close(()=>{this.server.close(()=>{e()})})})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(t.type==="ready"){this.connectionGeneration+=1,this.readyResolve();const r=this.connectionWaiters;this.connectionWaiters=[];for(const i of r)i();return}if(t.type==="heartbeat")return;if(t.target==="sw-recording"){this.dispatchRecording(t);return}const n=t.id;if(typeof n!="string")return;const u=this.pending.get(n);if(u)if(this.pending.delete(n),clearTimeout(u.timer),typeof t.error=="string"){const r=typeof t.code=="string"?t.code:void 0;u.reject(new As(t.error,r))}else t.error!==void 0&&t.error!==null?u.reject(new As("Extension returned an error")):u.resolve(t.result)}dispatchRecording(e){const t=this.recordingHandler;if(!t)return;const n=typeof e.recordingId=="string"?e.recordingId:void 0;n&&(e.type==="chunk"&&typeof e.dataB64=="string"?t.onChunk(n,e.dataB64):e.type==="stopped"?t.onStopped(n,{mediaType:typeof e.mediaType=="string"?e.mediaType:"video/mp4",durationMs:typeof e.durationMs=="number"?e.durationMs:0,width:typeof e.width=="number"?e.width:0,height:typeof e.height=="number"?e.height:0}):e.type==="error"&&t.onError(n,typeof e.message=="string"?e.message:"Recording error"))}rejectAllPending(e){for(const[t,n]of this.pending)clearTimeout(n.timer),n.reject(new Error(e)),this.pending.delete(t)}scheduleDisconnectTimeout(){this.clearDisconnectTimer(),this.disconnectTimer=setTimeout(()=>{this.disconnectTimer=null,this.onExtensionLostPermanently?.()},nE)}clearDisconnectTimer(){this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null)}};function oE(){return new Promise((e,t)=>{const n=r4();n.listen(0,"127.0.0.1",()=>{const u=n.address();if(u!==null&&typeof u=="object"){const r=u.port;n.close(()=>e(r))}else n.close(()=>t(new Error("Failed to allocate port")))}),n.on("error",t)})}var u4=4,i4=[1e3,3e3,8e3],sE=12e4,a4=2e4,cE=33e4,lE=16*1024*1024,dE=class{active=new Map;finalized=new Map;begin(e){if(this.active.has(e.recordingId))throw new Error(`Recording ${e.recordingId} already started`);let t,n;const u=new Promise((r,i)=>{t=r,n=i});u.catch(()=>{}),this.active.set(e.recordingId,{recordingId:e.recordingId,sessionId:e.sessionId,controlUrl:e.controlUrl,controlToken:e.controlToken,mediaType:e.mediaType,buffer:[],bufferedBytes:0,totalBytes:0,nextPartNumber:1,parts:[],uploadChain:Promise.resolve(),failed:!1,closing:!1,stopped:u,resolveStopped:t,rejectStopped:n})}handleChunk(e,t){const n=this.active.get(e);if(!n||n.closing||n.failed)return;const u=Buffer.from(t,"base64");n.buffer.push(u),n.bufferedBytes+=u.byteLength,n.totalBytes+=u.byteLength,n.bufferedBytes>=lE&&this.flushBufferedPart(n)}handleStopped(e,t){const n=this.active.get(e);!n||n.closing||(n.closing=!0,n.resolveStopped(t),this.finalize(e).catch(u=>{console.error("[browser-extension-mcp] auto-finalize failed",u)}))}handleError(e,t){const n=this.active.get(e);n&&(n.rejectStopped(new Error(t)),this.discard(e))}discard(e){const t=this.active.get(e);t&&(t.closing=!0,t.failed=!0,this.abortUpload(t),this.active.delete(e))}finalize(e){const t=this.finalized.get(e);if(t)return t;const n=this.active.get(e);if(!n)return Promise.reject(new Error(`No active recording ${e}`));const u=(async()=>{const r=await n.stopped;this.flushBufferedPart(n),await n.uploadChain;let i=!1;return!n.failed&&n.parts.length>0?(i=await this.completeUpload(n),i||await this.abortUpload(n)):await this.abortUpload(n),this.active.delete(e),{recordingId:e,mediaType:r.mediaType||n.mediaType,size:n.totalBytes,durationMs:r.durationMs,width:r.width,height:r.height,uploaded:i,...i?{}:{note:"This recording was not delivered to the chat."}}})();return this.finalized.set(e,u),u}hasActive(){return this.active.size>0}async finalizeAll(){const e=[...this.active.keys()];await Promise.allSettled(e.map(async t=>{const n=this.active.get(t);if(n){if(n.closing){await this.finalize(t);return}n.closing=!0,n.failed=!0,await this.abortUpload(n),this.active.delete(t)}}))}flushBufferedPart(e){if(e.failed||e.bufferedBytes===0)return;const t=Buffer.concat(e.buffer,e.bufferedBytes);e.buffer=[],e.bufferedBytes=0;const n=e.nextPartNumber;e.nextPartNumber+=1,e.uploadChain=e.uploadChain.then(async()=>{if(!e.failed)try{const u=await this.uploadPart(e,n,t);e.parts.push({partNumber:n,etag:u})}catch(u){e.failed=!0,e.buffer=[],e.bufferedBytes=0,console.error("[browser-extension-mcp] recording part failed permanently",u)}}),e.uploadChain.catch(()=>{})}async uploadPart(e,t,n){let u;for(let r=0;r<u4;r++)try{const i=await this.requestPartUrl(e,t);return await fE(i,n)}catch(i){u=i,console.error(`[browser-extension-mcp] part ${t} attempt ${r} failed`,i);const a=i4[r];a!==void 0&&await o4(a)}throw u instanceof Error?u:new Error(`part ${t} upload failed`)}async requestPartUrl(e,t){const n=await fetch(`${e.controlUrl}/${e.recordingId}/parts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId,partNumber:t}),signal:AbortSignal.timeout(a4)});if(!n.ok)throw new Error(`part-url request HTTP ${n.status}`);const u=await n.json();if(typeof u.uploadUrl!="string")throw new Error("part-url response missing uploadUrl");return u.uploadUrl}async completeUpload(e){for(let t=0;t<u4;t++){try{const u=await fetch(`${e.controlUrl}/${e.recordingId}/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId,parts:e.parts}),signal:AbortSignal.timeout(cE)});if(u.ok)return!0;console.error(`[browser-extension-mcp] recording complete HTTP ${u.status}`)}catch(u){console.error("[browser-extension-mcp] recording complete attempt failed",u)}const n=i4[t];n!==void 0&&await o4(n)}return!1}async abortUpload(e){try{await fetch(`${e.controlUrl}/${e.recordingId}/abort`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId}),signal:AbortSignal.timeout(a4)})}catch(t){console.error("[browser-extension-mcp] recording abort failed",t)}}};async function fE(e,t){const n=await fetch(e,{method:"PUT",body:new Uint8Array(t),signal:AbortSignal.timeout(sE)});if(!n.ok)throw new Error(`part PUT HTTP ${n.status}`);const u=n.headers.get("etag");if(!u)throw new Error("part PUT response missing ETag");return u}function o4(e){return new Promise(t=>{setTimeout(t,e)})}var mE=12e6,pE=480*6e4;function hE(e){let t="",n,u,r,i,a,o;const s=[];let c=!1,l=!1,f,g=!1;for(const D of e)if(D.startsWith("--extension-dir="))t=D.slice(16);else if(D.startsWith("--stealth-dir="))n=D.slice(14);else if(D.startsWith("--profile-dir="))u=D.slice(14);else if(D.startsWith("--download-dir="))r=D.slice(15);else if(D.startsWith("--chrome-path="))i=D.slice(14);else if(D.startsWith("--renderer=")){const y=D.slice(11);(y==="gpu"||y==="software")&&(a=y)}else D.startsWith("--accept-lang=")?o=D.slice(14):D.startsWith("--extra-flag=")?s.push(D.slice(13)):D.startsWith("--extension-version=")?f=D.slice(20):D==="--reset-window-placement"?c=!0:D==="--enable-recording"?l=!0:D==="--durable-profile"&&(g=!0);return t||(console.error("Usage: browser-extension-mcp --extension-dir=<path> [--stealth-dir=<path>] [--profile-dir=<path>] [--download-dir=<path>] [--chrome-path=<path>] [--renderer=gpu|software] [--accept-lang=<lang>] [--extra-flag=<flag> ...] [--reset-window-placement] [--enable-recording] [--extension-version=<version>] [--durable-profile]"),process.exit(1)),{extensionDir:t,stealthDir:n,profileDir:u,downloadDir:r,chromePath:i,renderer:a,acceptLanguage:o,extraFlags:s,resetWindowPlacement:c,enableRecording:l,extensionVersion:f,durableProfile:g}}function Pr(e){const t=e;return t&&typeof t.image=="string"?{content:[{type:"image",data:t.image,mimeType:"image/jpeg"}]}:{content:[{type:"text",text:JSON.stringify(e)}]}}function qt(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}async function Ve(e,t,n={}){try{return Pr(await e.sendCommand(t,n))}catch(u){return qt(u)}}async function s4(e,t){try{return Pr(await e.sendCommand("screenshot",{}))}catch(n){if(!c4(n))return qt(n);try{return await t.relaunch({clearCaches:!1}),Pr(await e.sendCommand("screenshot",{}))}catch(u){if(!c4(u))return qt(u);try{return await t.relaunch({clearCaches:!0}),Pr(await e.sendCommand("screenshot",{}))}catch(r){return qt(r)}}}}function c4(e){return iE(e)||e instanceof Error&&/timed out/i.test(e.message)}function vE(e,t,n){e.registerTool("start_recording",{description:"Start recording a video of the current browser tab (the tab you are driving), for demos and walkthroughs. Records for as long as you need - multi-hour sessions are fine - until you call stop_recording; a generous safety cap auto-finalizes it if you forget. Returns a recordingId; the finished video is delivered to the chat and returned by stop_recording as a reference, not as frames you see.",inputSchema:{audio:Ce.boolean().optional().describe("Record tab audio as well as video. Defaults to false (silent)."),recordingId:Ce.string().optional().describe("Reserved - set by the platform."),mediaType:Ce.string().optional().describe("Reserved - set by the platform."),maxDurationMs:Ce.number().optional().describe("Reserved - set by the platform."),sessionId:Ce.string().optional().describe("Reserved - set by the platform."),controlUrl:Ce.string().optional().describe("Reserved - set by the platform."),controlToken:Ce.string().optional().describe("Reserved - set by the platform.")}},async u=>{const r=u,i=typeof r.controlUrl=="string"?r.controlUrl:void 0,a=typeof r.controlToken=="string"?r.controlToken:void 0,o=typeof r.sessionId=="string"?r.sessionId:void 0,s=typeof r.recordingId=="string"&&r.recordingId.length>0?r.recordingId:void 0;if(!i||!a||!o||!s)return qt(new Error("Recording is not available: no upload target was provisioned."));const c=typeof r.mediaType=="string"?r.mediaType:"video/mp4",l=typeof r.maxDurationMs=="number"?r.maxDurationMs:pE,f=r.audio===!0;try{n.begin({recordingId:s,sessionId:o,controlUrl:i,controlToken:a,mediaType:c})}catch(g){return qt(g)}try{return await t.sendCommand("start_recording",{recordingId:s,audio:f,videoBitsPerSecond:mE,maxDurationMs:l}),Pr({recordingId:s,status:"recording"})}catch(g){return n.discard(s),qt(g)}}),e.registerTool("stop_recording",{description:"Stop the active browser recording and finalize the video. Returns a reference to the produced file (recordingId, mediaType, size, duration, resolution); the video is delivered to the chat. You act on it by reference - you do not receive the frames.",inputSchema:{recordingId:Ce.string().describe("The recordingId returned by start_recording.")}},async u=>{const r=u.recordingId;if(typeof r!="string"||r.length===0)return qt(new Error("recordingId is required to stop a recording."));try{await t.sendCommand("stop_recording",{recordingId:r});const i=await n.finalize(r);return Pr(i)}catch(i){return qt(i)}})}function gE(e,t,n){let u=Promise.resolve();const r=()=>{const i=u.then(()=>s4(t,n),()=>s4(t,n));return u=i.then(()=>{},()=>{}),i};e.registerTool("screenshot",{description:"Capture a screenshot of the current page. Returns a base64-encoded JPEG image."},()=>r()),e.registerTool("get_accessibility_tree",{description:'Get a text representation of the page accessibility tree with ref_ids for element targeting. Use filter "interactive" to only show clickable/typeable elements.',inputSchema:{filter:Ce.enum(["all","interactive"]).optional().describe('Filter: "all" for full tree, "interactive" for actionable elements only.'),maxDepth:Ce.number().optional().describe("Maximum tree depth. Default: 15."),maxLength:Ce.number().optional().describe("Maximum output character length. Default: 50000.")}},i=>Ve(t,"get_accessibility_tree",i)),e.registerTool("click",{description:"Click an element identified by its ref_id from the accessibility tree.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to click (from get_accessibility_tree).")}},i=>Ve(t,"click",i)),e.registerTool("right_click",{description:"Right-click an element identified by its ref_id.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to right-click.")}},i=>Ve(t,"right_click",i)),e.registerTool("double_click",{description:"Double-click an element identified by its ref_id.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to double-click.")}},i=>Ve(t,"double_click",i)),e.registerTool("hover",{description:"Hover over an element identified by its ref_id from the accessibility tree.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to hover over (from get_accessibility_tree).")}},i=>Ve(t,"hover",i)),e.registerTool("drag",{description:"Drag an element onto another element, both identified by ref_id.",inputSchema:{from_ref_id:Ce.string().describe("The ref_id of the element to drag."),to_ref_id:Ce.string().describe("The ref_id of the element to drop onto.")}},i=>Ve(t,"drag",i)),e.registerTool("type",{description:"Type text into the currently focused element.",inputSchema:{text:Ce.string().describe("The text to type.")}},i=>Ve(t,"type",i)),e.registerTool("key",{description:'Press a keyboard key or combination. Supports modifiers: "Control+a", "Shift+Enter", "Meta+c".',inputSchema:{key:Ce.string().describe('Key or combo to press (e.g. "Enter", "Tab", "Control+a", "ArrowDown").')}},i=>Ve(t,"key",i)),e.registerTool("fill",{description:"Clear and type text into an input or text area identified by its ref_id. Clicks the element, selects all existing content, then types the new value.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the input element to fill (from get_accessibility_tree)."),value:Ce.string().describe("The value to fill in.")}},i=>Ve(t,"fill",i)),e.registerTool("navigate",{description:"Navigate the current tab to a URL. Waits for the page to load.",inputSchema:{url:Ce.string().describe("The URL to navigate to.")}},i=>Ve(t,"navigate",i)),e.registerTool("go_back",{description:"Navigate back in the browser history."},()=>Ve(t,"go_back")),e.registerTool("go_forward",{description:"Navigate forward in the browser history."},()=>Ve(t,"go_forward")),e.registerTool("reload",{description:"Reload the current page. Waits for the page to load."},()=>Ve(t,"reload")),e.registerTool("scroll",{description:"Scroll the page up or down.",inputSchema:{direction:Ce.enum(["up","down"]).describe("Scroll direction."),amount:Ce.number().optional().describe("Scroll amount in pixels. Default: 500.")}},i=>Ve(t,"scroll",i)),e.registerTool("select_option",{description:"Select an option in a <select> dropdown by ref_id and value.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the <select> element."),value:Ce.string().describe("The value or visible text of the option to select.")}},i=>Ve(t,"select_option",i)),e.registerTool("wait",{description:"Wait for a specified duration or for a navigation event.",inputSchema:{ms:Ce.number().optional().describe("Milliseconds to wait. Default: 1000."),for_navigation:Ce.boolean().optional().describe("If true, wait for a navigation event instead of a fixed delay.")}},i=>Ve(t,"wait",i)),e.registerTool("wait_for",{description:"Wait for any of the specified texts to appear on the page. Polls the page content until a match is found or the timeout is reached.",inputSchema:{text:Ce.array(Ce.string()).describe("Non-empty list of texts. Resolves when any value appears on the page."),timeout:Ce.number().optional().describe("Maximum wait time in milliseconds. Default: 30000.")}},i=>Ve(t,"wait_for",i)),e.registerTool("handle_dialog",{description:"Accept or dismiss a browser dialog (alert, confirm, prompt). Call this when a dialog is blocking page interaction.",inputSchema:{action:Ce.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog."),promptText:Ce.string().optional().describe("Text to enter into a prompt dialog before accepting. Only used for prompt dialogs.")}},i=>Ve(t,"handle_dialog",i)),e.registerTool("evaluate_script",{description:"Evaluate a JavaScript function in the current page. Returns the result as JSON. Use for reading page state, dismissing overlays, or any DOM operation the other tools cannot handle. Inline any arguments directly into the function body.",inputSchema:{function:Ce.string().describe(`A JavaScript function declaration with no arguments. Inline any values you need directly. Examples: "() => document.title", "() => document.querySelector('body').innerText".`)}},i=>Ve(t,"evaluate_script",i)),e.registerTool("upload_file",{description:`Upload a file by targeting the control that triggers a file upload. Works with upload buttons, drag zones, file input elements, and menu-based upload controls (e.g. OneDrive/SharePoint "Upload -> Files"): if clicking the control does not open a native file chooser, it sets the file directly on the page's hidden file input. On a menu, target the specific upload item (the "Files" option), not the menu button.`,inputSchema:{ref_id:Ce.string().describe("The ref_id of the element that triggers file upload (button, link, menu item, or file input)."),filePath:Ce.string().describe("The absolute path to the file to upload.")}},i=>Ve(t,"upload_file",i)),e.registerTool("list_tabs",{description:"List all open browser tabs with their IDs, titles, and URLs."},()=>Ve(t,"list_tabs")),e.registerTool("new_tab",{description:"Open a new browser tab, optionally with a URL.",inputSchema:{url:Ce.string().optional().describe("URL to open in the new tab. Defaults to about:blank.")}},i=>Ve(t,"new_tab",i)),e.registerTool("switch_tab",{description:"Switch to a different browser tab by its tab ID.",inputSchema:{tabId:Ce.number().describe("The Chrome tab ID to switch to.")}},i=>Ve(t,"switch_tab",i)),e.registerTool("close_tab",{description:"Close a browser tab. Defaults to the current tab.",inputSchema:{tabId:Ce.number().optional().describe("The Chrome tab ID to close. Defaults to the current tab.")}},i=>Ve(t,"close_tab",i))}var _E="pjdkhojhcdiebhpofmbooclincdfafjh";function yE(e){try{const t=JSON.parse(Ch(Ys(e,"manifest.json"),"utf8"));if(typeof t.key=="string"&&t.key.length>0)return $h("sha256").update(Buffer.from(t.key,"base64")).digest("hex").slice(0,32).replace(/[0-9a-f]/g,u=>String.fromCharCode(97+parseInt(u,16)))}catch{}return _E}async function EE(){const e=hE(process.argv.slice(2));let t=!1;const n=await oE(),u=new aE(n);await u.start();const r=e.enableRecording?new dE:null;r&&u.setRecordingHandler({onChunk:(f,g)=>r.handleChunk(f,g),onStopped:(f,g)=>r.handleStopped(f,g),onError:(f,g)=>r.handleError(f,g)});const i=e.profileDir??Ys(wh(),"browser-ext-profile"),a=e.enableRecording?[...e.extraFlags,`--allowlisted-extension-id=${yE(e.extensionDir)}`]:e.extraFlags,o=new Y3({bridge:u,wsPort:n,extensionDir:e.extensionDir,stealthDir:e.stealthDir,profileDir:i,downloadDir:e.downloadDir,chromePath:e.chromePath,renderer:e.renderer,acceptLanguage:e.acceptLanguage,extraFlags:a,resetWindowPlacement:e.resetWindowPlacement,extensionVersion:e.extensionVersion,durableProfile:e.durableProfile});async function s(){t||(t=!0,r?.hasActive()&&await Promise.race([r.finalizeAll(),new Promise(f=>{setTimeout(f,3e4)})]),await o.stop(),await u.stop(),process.exit(0))}o.setUnexpectedExitHandler(()=>{t||(console.error("[browser-extension-mcp] Chrome exited unexpectedly - shutting down"),s())}),u.setExtensionLostHandler(()=>{t||o.isRelaunching()||(console.error("[browser-extension-mcp] Extension disconnected past grace period - shutting down"),s())});try{o.start()}catch(f){throw await u.stop(),f}await u.waitForReady();const c=new g3({name:"browser-extension-mcp",version:"0.1.0"},{capabilities:{tools:{}}});gE(c,u,o),r&&vE(c,u,r);const l=new $3;await c.connect(l),process.stdin.on("end",()=>{s()}),process.on("SIGTERM",()=>{s()}),process.on("SIGINT",()=>{s()})}EE().catch(e=>{console.error("[browser-extension-mcp] Fatal:",e),process.exit(1)});
|
|
60
|
+
`}var $3=class{constructor(e=qp.stdin,t=qp.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new E3,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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{const 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(t=>{const n=b3(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};import{createHash as C3}from"crypto";import{cpSync as w3,mkdirSync as Vp,readFileSync as Cs,rmSync as ws,writeFileSync as ks}from"fs";import{join as dr}from"path";import{spawn as k3,spawnSync as S3}from"child_process";import{existsSync as Jp}from"fs";import{platform as Wp}from"os";var Gp={darwin:["/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing","/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["chromium","chromium-browser"]},x3=["--no-first-run","--no-default-browser-check","--hide-crash-restore-bubble","--disable-infobars","--silent-debugger-extension-api","--disable-background-networking","--disable-features=Prerender2,PrefetchBrowserInitiatedTriggers","--disable-sync","--no-pings","--disable-domain-reliability","--force-renderer-accessibility","--password-store=basic","--use-mock-keychain"],B3=["--no-sandbox","--disable-dev-shm-usage","--test-type","--start-maximized"],A3=["--use-gl=angle","--use-angle=swiftshader","--enable-unsafe-swiftshader","--ignore-gpu-blocklist"],I3=["--ignore-gpu-blocklist","--use-gl=angle","--use-angle=gl","--enable-gpu-rasterization","--enable-zero-copy"];function T3(){const e=Wp(),t=Gp[e]??Gp.linux;for(const n of t)if(n.startsWith("/")){if(Jp(n))return n}else if(F3(n))return n;throw new Error(`Chrome not found. Searched: ${t.join(", ")}. `+(e==="darwin"?"Install Chrome for Testing or pass chromePath.":"Install Chrome for Testing or Chromium and pass chromePath - branded Google Chrome cannot load the automation extension (--load-extension was removed in Chrome 137+)."))}function F3(e){try{return S3("which",[e],{stdio:"ignore"}).status===0}catch{return!1}}function P3(e){const t=e.chromePath??T3(),n=Wp(),u=e.extensions.filter(s=>Jp(s));if(u.length===0)throw new Error("launchChrome: no existing extension directories to load");const i=(e.renderer??"software")==="gpu"?I3:A3,a=[`--load-extension=${u.join(",")}`,`--user-data-dir=${e.profileDir}`,...x3,...e.acceptLanguage?[`--lang=${e.acceptLanguage}`,`--accept-lang=${e.acceptLanguage}`]:[],...n==="linux"?[...B3,...i]:[],...e.extraFlags??[]],o=k3(t,a,{stdio:"ignore",detached:n!=="win32"});if(o.pid===void 0)throw new Error(`Failed to launch Chrome at ${t}`);return o.on("error",()=>{}),{process:o,pid:o.pid}}import{spawnSync as Di}from"child_process";import{existsSync as fr,mkdirSync as j3,readFileSync as Hp,readdirSync as Kp,rmSync as bi,writeFileSync as Xp}from"fs";import{platform as Yp}from"os";import{join as ot}from"path";var Ss=".chrome-pid",O3=3e3,Qp=100,z3=new Int32Array(new SharedArrayBuffer(4));function Fn(e){try{return process.kill(e,0),!0}catch{return!1}}function e4(e){try{const t=Di("pgrep",["-P",String(e)],{encoding:"utf-8",timeout:5e3});if(t.stdout)for(const n of t.stdout.trim().split(`
|
|
61
|
+
`)){const u=Number(n);if(u>0){e4(u);try{process.kill(u,"SIGKILL")}catch{}}}}catch{}}function xs(e){if(Yp()==="win32"){try{Di("taskkill",["/PID",String(e),"/T","/F"],{stdio:"ignore",timeout:5e3})}catch{}return}try{process.kill(-e,"SIGKILL")}catch{}e4(e);try{process.kill(e,"SIGKILL")}catch{}}function N3(e){const t=Date.now()+O3;for(;Fn(e)&&Date.now()<t;)Atomics.wait(z3,0,0,Qp)}function R3(e){return new Promise(t=>{setTimeout(t,e)})}async function U3(e,t){if(!Fn(e))return!0;if(Yp()==="win32")try{Di("taskkill",["/PID",String(e),"/T"],{stdio:"ignore",timeout:5e3})}catch{}else try{process.kill(e,"SIGTERM")}catch{return!0}const n=Date.now()+t;for(;Date.now()<n;){if(!Fn(e))return!0;await R3(Qp)}return!Fn(e)}function Z3(e){const t=ot(e,Ss);let n=null;if(fr(t)){try{n=Number(Hp(t,"utf-8").trim()),(!Number.isFinite(n)||n<=0)&&(n=null)}catch{n=null}bi(t,{force:!0})}n!==null&&Fn(n)&&(xs(n),N3(n));try{Di("pkill",["-9","-f",`user-data-dir=${e}`],{stdio:"ignore",timeout:5e3})}catch{}}function M3(e,t){Xp(ot(e,Ss),String(t))}function L3(e){bi(ot(e,Ss),{force:!0})}function q3(e,t={}){fr(e)&&(W3(e),G3(e),H3(e,t))}var V3=["GrShaderCache","ShaderCache","GraphiteDawnCache","Crashpad","Crash Reports",ot("Default","GPUCache"),ot("Default","Code Cache"),ot("Default","DawnCache"),ot("Default","DawnGraphiteCache"),ot("Default","DawnWebGPUCache")];function J3(e){if(fr(e))for(const t of V3)Bs(ot(e,t))}function W3(e){for(const t of Kp(e))(t==="SingletonLock"||t==="SingletonCookie"||t==="SingletonSocket"||t==="RunningChromeVersion"||t.startsWith("BrowserMetrics"))&&Bs(ot(e,t));t4(ot(e,"Default"))}function Bs(e){try{bi(e,{force:!0,recursive:!0,maxRetries:4,retryDelay:100})}catch{}}function t4(e){if(fr(e))for(const t of Kp(e,{withFileTypes:!0})){const n=ot(e,t.name);t.isDirectory()?t4(n):t.name==="LOCK"&&Bs(n)}}function G3(e){const t=ot(e,"Default","Sessions");fr(t)&&bi(t,{recursive:!0,force:!0})}function H3(e,t){const{resetWindowPlacement:n,downloadDir:u,durableProfile:r}=t;if(!n&&!u&&!r)return;const i=ot(e,"Default"),a=ot(i,"Preferences");if(!(!u&&!r&&!fr(a)))try{let o={};fr(a)&&(o=JSON.parse(Hp(a,"utf-8")));let s=!1;if(n){const c=Pn(o.browser);c&&"window_placement"in c&&(delete c.window_placement,s=!0)}if(r){const c=Pn(o.session)??{};c.restore_on_startup!==1&&(c.restore_on_startup=1,o.session=c,s=!0);const l=Pn(o.profile)??{};(l.exit_type!=="Normal"||l.exited_cleanly!==!0)&&(l.exit_type="Normal",l.exited_cleanly=!0,o.profile=l,s=!0)}if(u){const c=Pn(o.download)??{};c.default_directory=u,c.prompt_for_download=!1,c.directory_upgrade=!0,o.download=c;const l=Pn(o.savefile)??{};l.default_directory=u,o.savefile=l,s=!0}if(!s)return;j3(i,{recursive:!0}),Xp(a,JSON.stringify(o))}catch{}}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var K3=15e3,X3=5e3,Y3=class{constructor(e){this.opts=e,this.workDir=dr(e.profileDir,"extension-live")}chrome=null;relaunching=!1;stopped=!1;onUnexpectedExit;relaunchChain=Promise.resolve();workDir;setUnexpectedExitHandler(e){this.onUnexpectedExit=e}isRelaunching(){return this.relaunching}start(){this.stageExtension(),this.prepareProfile({clearCaches:!1}),this.spawn()}async relaunch({clearCaches:e}){if(this.stopped)throw new Error("BrowserSupervisor is stopped");const t=this.relaunchChain.then(()=>this.doRelaunch({clearCaches:e}),()=>this.doRelaunch({clearCaches:e}));this.relaunchChain=t.then(()=>{},()=>{}),await t}async doRelaunch({clearCaches:e}){if(this.stopped)throw new Error("BrowserSupervisor is stopped");this.relaunching=!0;try{const t=this.opts.bridge.generation;this.chrome=null,this.prepareProfile({clearCaches:e}),this.spawn(),await this.opts.bridge.waitForConnectionAfter(t,K3)}finally{this.relaunching=!1}}async stop(){if(this.stopped=!0,this.chrome){const{pid:e}=this.chrome;this.chrome=null,this.opts.durableProfile&&await U3(e,X3)||xs(e)}L3(this.opts.profileDir),ws(this.workDir,{recursive:!0,force:!0})}stageExtension(){ws(this.workDir,{recursive:!0,force:!0}),w3(this.opts.extensionDir,this.workDir,{recursive:!0}),ks(dr(this.workDir,"config.json"),JSON.stringify({wsPort:this.opts.wsPort}));const e=this.stampExtensionVersion();this.evictStaleServiceWorkerOnChange(e)}stampExtensionVersion(){const e=dr(this.workDir,"manifest.json");let t;try{t=JSON.parse(Cs(e,"utf-8"))}catch{return""}const n=Q3(this.opts.extensionVersion,this.workDir);return t.version=n,ks(e,JSON.stringify(t)),n}evictStaleServiceWorkerOnChange(e){if(!e)return;const t=dr(this.opts.profileDir,".octavus-extension-version");let n;try{n=Cs(t,"utf-8").trim()}catch{n=void 0}if(n!==e){for(const u of[dr(this.opts.profileDir,"Default","Service Worker"),dr(this.opts.profileDir,"Service Worker")])ws(u,{recursive:!0,force:!0});try{Vp(this.opts.profileDir,{recursive:!0}),ks(t,e)}catch{}}}prepareProfile({clearCaches:e}){Z3(this.opts.profileDir),e&&J3(this.opts.profileDir),Vp(this.opts.profileDir,{recursive:!0}),q3(this.opts.profileDir,{resetWindowPlacement:this.opts.resetWindowPlacement,downloadDir:this.opts.downloadDir,durableProfile:this.opts.durableProfile})}spawn(){this.chrome=P3({extensions:[this.workDir,...this.opts.stealthDir?[this.opts.stealthDir]:[]],profileDir:this.opts.profileDir,chromePath:this.opts.chromePath,renderer:this.opts.renderer,acceptLanguage:this.opts.acceptLanguage,extraFlags:this.opts.extraFlags}),M3(this.opts.profileDir,this.chrome.pid),this.chrome.process.on("exit",(e,t)=>{this.stopped||this.relaunching||(console.error(`[browser-extension-mcp] Chrome exited unexpectedly (code=${String(e)}, signal=${String(t)})`),this.onUnexpectedExit?.())})}};function Q3(e,t){return e&&eE(e)||tE(t)}function eE(e){const t=e.trim().split(".");if(!(t.length>4)&&t.every(n=>/^\d{1,5}$/.test(n)&&Number(n)<=65535))return t.length===1?`0.1.${t[0]}`:t.join(".")}function tE(e){let t;try{t=Cs(dr(e,"service-worker-loader.js"),"utf-8")}catch{t=String(Date.now())}const n=C3("sha256").update(t).digest();return`2.${n.readUInt16BE(0)}.${n.readUInt16BE(2)}`}import{createServer as r4}from"http";var A5=It(Dh(),1),I5=It(Ti(),1),T5=It(Zr(),1),F5=It(Hs(),1),P5=It(Ks(),1),j5=It(Xs(),1),O5=It(Fi(),1),rE=It(bh(),1),n4=3e4,nE=1e4,uE="render_wedged",As=class extends Error{constructor(e,t){super(e),this.code=t,this.name="BridgeError"}};function iE(e){return e instanceof As&&e.code===uE}var aE=class{server;wss;client=null;pending=new Map;requestCounter=0;readyPromise;readyResolve;disconnectTimer=null;onExtensionLostPermanently;connectionGeneration=0;connectionWaiters=[];recordingHandler=null;port;constructor(e){this.port=e,this.server=r4(),this.wss=new rE.default({server:this.server}),this.readyPromise=new Promise(t=>{this.readyResolve=t}),this.wss.on("connection",t=>{this.clearDisconnectTimer(),this.client=t,t.on("message",n=>{this.handleMessage(String(n))}),t.on("close",()=>{this.client===t&&(this.client=null,this.rejectAllPending("Extension disconnected"),this.scheduleDisconnectTimeout())})})}setExtensionLostHandler(e){this.onExtensionLostPermanently=e}setRecordingHandler(e){this.recordingHandler=e}async start(){await new Promise((e,t)=>{this.server.listen(this.port,"127.0.0.1",()=>{e()}),this.server.on("error",t)})}async waitForReady(e=3e4){await Promise.race([this.readyPromise,new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Extension did not connect within ${e}ms. The browser likely cannot load the automation extension - use Chrome for Testing or Chromium (branded Google Chrome 137+ dropped --load-extension).`))},e)})])}get generation(){return this.connectionGeneration}async waitForConnectionAfter(e,t=3e4){this.connectionGeneration>e||await new Promise((n,u)=>{const r={},i=()=>{r.timer&&clearTimeout(r.timer),n()};r.timer=setTimeout(()=>{this.connectionWaiters=this.connectionWaiters.filter(a=>a!==i),u(new Error("Extension did not reconnect within timeout"))},t),this.connectionWaiters.push(i)})}async sendCommand(e,t){if(this.client?.readyState!==1)throw new Error("Extension not connected");this.requestCounter+=1;const n=`req_${this.requestCounter}`;return await new Promise((u,r)=>{const i=setTimeout(()=>{this.pending.delete(n),r(new Error(`Command "${e}" timed out after ${n4}ms`))},n4);this.pending.set(n,{resolve:u,reject:r,timer:i}),this.client.send(JSON.stringify({id:n,cmd:e,args:t}))})}async stop(){this.clearDisconnectTimer(),this.rejectAllPending("MCP server shutting down"),this.client&&(this.client.close(),this.client=null),await new Promise(e=>{this.wss.close(()=>{this.server.close(()=>{e()})})})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(t.type==="ready"){this.connectionGeneration+=1,this.readyResolve();const r=this.connectionWaiters;this.connectionWaiters=[];for(const i of r)i();return}if(t.type==="heartbeat")return;if(t.target==="sw-recording"){this.dispatchRecording(t);return}const n=t.id;if(typeof n!="string")return;const u=this.pending.get(n);if(u)if(this.pending.delete(n),clearTimeout(u.timer),typeof t.error=="string"){const r=typeof t.code=="string"?t.code:void 0;u.reject(new As(t.error,r))}else t.error!==void 0&&t.error!==null?u.reject(new As("Extension returned an error")):u.resolve(t.result)}dispatchRecording(e){const t=this.recordingHandler;if(!t)return;const n=typeof e.recordingId=="string"?e.recordingId:void 0;n&&(e.type==="chunk"&&typeof e.dataB64=="string"?t.onChunk(n,e.dataB64):e.type==="stopped"?t.onStopped(n,{mediaType:typeof e.mediaType=="string"?e.mediaType:"video/mp4",durationMs:typeof e.durationMs=="number"?e.durationMs:0,width:typeof e.width=="number"?e.width:0,height:typeof e.height=="number"?e.height:0}):e.type==="error"&&t.onError(n,typeof e.message=="string"?e.message:"Recording error"))}rejectAllPending(e){for(const[t,n]of this.pending)clearTimeout(n.timer),n.reject(new Error(e)),this.pending.delete(t)}scheduleDisconnectTimeout(){this.clearDisconnectTimer(),this.disconnectTimer=setTimeout(()=>{this.disconnectTimer=null,this.onExtensionLostPermanently?.()},nE)}clearDisconnectTimer(){this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null)}};function oE(){return new Promise((e,t)=>{const n=r4();n.listen(0,"127.0.0.1",()=>{const u=n.address();if(u!==null&&typeof u=="object"){const r=u.port;n.close(()=>e(r))}else n.close(()=>t(new Error("Failed to allocate port")))}),n.on("error",t)})}var u4=4,i4=[1e3,3e3,8e3],sE=12e4,a4=2e4,cE=33e4,lE=16*1024*1024,dE=class{active=new Map;finalized=new Map;begin(e){if(this.active.has(e.recordingId))throw new Error(`Recording ${e.recordingId} already started`);let t,n;const u=new Promise((r,i)=>{t=r,n=i});u.catch(()=>{}),this.active.set(e.recordingId,{recordingId:e.recordingId,sessionId:e.sessionId,controlUrl:e.controlUrl,controlToken:e.controlToken,mediaType:e.mediaType,buffer:[],bufferedBytes:0,totalBytes:0,nextPartNumber:1,parts:[],uploadChain:Promise.resolve(),failed:!1,closing:!1,stopped:u,resolveStopped:t,rejectStopped:n})}handleChunk(e,t){const n=this.active.get(e);if(!n||n.closing||n.failed)return;const u=Buffer.from(t,"base64");n.buffer.push(u),n.bufferedBytes+=u.byteLength,n.totalBytes+=u.byteLength,n.bufferedBytes>=lE&&this.flushBufferedPart(n)}handleStopped(e,t){const n=this.active.get(e);!n||n.closing||(n.closing=!0,n.resolveStopped(t),this.finalize(e).catch(u=>{console.error("[browser-extension-mcp] auto-finalize failed",u)}))}handleError(e,t){const n=this.active.get(e);n&&(n.rejectStopped(new Error(t)),this.discard(e))}discard(e){const t=this.active.get(e);t&&(t.closing=!0,t.failed=!0,this.abortUpload(t),this.active.delete(e))}finalize(e){const t=this.finalized.get(e);if(t)return t;const n=this.active.get(e);if(!n)return Promise.reject(new Error(`No active recording ${e}`));const u=(async()=>{const r=await n.stopped;this.flushBufferedPart(n),await n.uploadChain;let i=!1;return!n.failed&&n.parts.length>0?(i=await this.completeUpload(n),i||await this.abortUpload(n)):await this.abortUpload(n),this.active.delete(e),{recordingId:e,mediaType:r.mediaType||n.mediaType,size:n.totalBytes,durationMs:r.durationMs,width:r.width,height:r.height,uploaded:i,...i?{}:{note:"This recording was not delivered to the chat."}}})();return this.finalized.set(e,u),u}hasActive(){return this.active.size>0}async finalizeAll(){const e=[...this.active.keys()];await Promise.allSettled(e.map(async t=>{const n=this.active.get(t);if(n){if(n.closing){await this.finalize(t);return}n.closing=!0,n.failed=!0,await this.abortUpload(n),this.active.delete(t)}}))}flushBufferedPart(e){if(e.failed||e.bufferedBytes===0)return;const t=Buffer.concat(e.buffer,e.bufferedBytes);e.buffer=[],e.bufferedBytes=0;const n=e.nextPartNumber;e.nextPartNumber+=1,e.uploadChain=e.uploadChain.then(async()=>{if(!e.failed)try{const u=await this.uploadPart(e,n,t);e.parts.push({partNumber:n,etag:u})}catch(u){e.failed=!0,e.buffer=[],e.bufferedBytes=0,console.error("[browser-extension-mcp] recording part failed permanently",u)}}),e.uploadChain.catch(()=>{})}async uploadPart(e,t,n){let u;for(let r=0;r<u4;r++)try{const i=await this.requestPartUrl(e,t);return await fE(i,n)}catch(i){u=i,console.error(`[browser-extension-mcp] part ${t} attempt ${r} failed`,i);const a=i4[r];a!==void 0&&await o4(a)}throw u instanceof Error?u:new Error(`part ${t} upload failed`)}async requestPartUrl(e,t){const n=await fetch(`${e.controlUrl}/${e.recordingId}/parts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId,partNumber:t}),signal:AbortSignal.timeout(a4)});if(!n.ok)throw new Error(`part-url request HTTP ${n.status}`);const u=await n.json();if(typeof u.uploadUrl!="string")throw new Error("part-url response missing uploadUrl");return u.uploadUrl}async completeUpload(e){for(let t=0;t<u4;t++){try{const u=await fetch(`${e.controlUrl}/${e.recordingId}/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId,parts:e.parts}),signal:AbortSignal.timeout(cE)});if(u.ok)return!0;console.error(`[browser-extension-mcp] recording complete HTTP ${u.status}`)}catch(u){console.error("[browser-extension-mcp] recording complete attempt failed",u)}const n=i4[t];n!==void 0&&await o4(n)}return!1}async abortUpload(e){try{await fetch(`${e.controlUrl}/${e.recordingId}/abort`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.controlToken}`},body:JSON.stringify({sessionId:e.sessionId}),signal:AbortSignal.timeout(a4)})}catch(t){console.error("[browser-extension-mcp] recording abort failed",t)}}};async function fE(e,t){const n=await fetch(e,{method:"PUT",body:new Uint8Array(t),signal:AbortSignal.timeout(sE)});if(!n.ok)throw new Error(`part PUT HTTP ${n.status}`);const u=n.headers.get("etag");if(!u)throw new Error("part PUT response missing ETag");return u}function o4(e){return new Promise(t=>{setTimeout(t,e)})}var mE=12e6,pE=480*6e4;function hE(e){let t="",n,u,r,i,a,o;const s=[];let c=!1,l=!1,f,g=!1;for(const D of e)if(D.startsWith("--extension-dir="))t=D.slice(16);else if(D.startsWith("--stealth-dir="))n=D.slice(14);else if(D.startsWith("--profile-dir="))u=D.slice(14);else if(D.startsWith("--download-dir="))r=D.slice(15);else if(D.startsWith("--chrome-path="))i=D.slice(14);else if(D.startsWith("--renderer=")){const y=D.slice(11);(y==="gpu"||y==="software")&&(a=y)}else D.startsWith("--accept-lang=")?o=D.slice(14):D.startsWith("--extra-flag=")?s.push(D.slice(13)):D.startsWith("--extension-version=")?f=D.slice(20):D==="--reset-window-placement"?c=!0:D==="--enable-recording"?l=!0:D==="--durable-profile"&&(g=!0);return t||(console.error("Usage: browser-extension-mcp --extension-dir=<path> [--stealth-dir=<path>] [--profile-dir=<path>] [--download-dir=<path>] [--chrome-path=<path>] [--renderer=gpu|software] [--accept-lang=<lang>] [--extra-flag=<flag> ...] [--reset-window-placement] [--enable-recording] [--extension-version=<version>] [--durable-profile]"),process.exit(1)),{extensionDir:t,stealthDir:n,profileDir:u,downloadDir:r,chromePath:i,renderer:a,acceptLanguage:o,extraFlags:s,resetWindowPlacement:c,enableRecording:l,extensionVersion:f,durableProfile:g}}function Pr(e){const t=e;return t&&typeof t.image=="string"?{content:[{type:"image",data:t.image,mimeType:"image/jpeg"}]}:{content:[{type:"text",text:JSON.stringify(e)}]}}function qt(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}async function Ve(e,t,n={}){try{return Pr(await e.sendCommand(t,n))}catch(u){return qt(u)}}async function s4(e,t){try{return Pr(await e.sendCommand("screenshot",{}))}catch(n){if(!c4(n))return qt(n);try{return await t.relaunch({clearCaches:!1}),Pr(await e.sendCommand("screenshot",{}))}catch(u){if(!c4(u))return qt(u);try{return await t.relaunch({clearCaches:!0}),Pr(await e.sendCommand("screenshot",{}))}catch(r){return qt(r)}}}}function c4(e){return iE(e)||e instanceof Error&&/timed out/i.test(e.message)}function vE(e,t,n){e.registerTool("start_recording",{description:"Start recording a video of the current browser tab (the tab you are driving), for demos and walkthroughs. Records for as long as you need - multi-hour sessions are fine - until you call stop_recording; a generous safety cap auto-finalizes it if you forget. Returns a recordingId; the finished video is delivered to the chat and returned by stop_recording as a reference, not as frames you see.",inputSchema:{audio:Ce.boolean().optional().describe("Record tab audio as well as video. Defaults to false (silent)."),recordingId:Ce.string().optional().describe("Reserved - set by the platform."),mediaType:Ce.string().optional().describe("Reserved - set by the platform."),maxDurationMs:Ce.number().optional().describe("Reserved - set by the platform."),sessionId:Ce.string().optional().describe("Reserved - set by the platform."),controlUrl:Ce.string().optional().describe("Reserved - set by the platform."),controlToken:Ce.string().optional().describe("Reserved - set by the platform.")}},async u=>{const r=u,i=typeof r.controlUrl=="string"?r.controlUrl:void 0,a=typeof r.controlToken=="string"?r.controlToken:void 0,o=typeof r.sessionId=="string"?r.sessionId:void 0,s=typeof r.recordingId=="string"&&r.recordingId.length>0?r.recordingId:void 0;if(!i||!a||!o||!s)return qt(new Error("Recording is not available: no upload target was provisioned."));const c=typeof r.mediaType=="string"?r.mediaType:"video/mp4",l=typeof r.maxDurationMs=="number"?r.maxDurationMs:pE,f=r.audio===!0;try{n.begin({recordingId:s,sessionId:o,controlUrl:i,controlToken:a,mediaType:c})}catch(g){return qt(g)}try{return await t.sendCommand("start_recording",{recordingId:s,audio:f,videoBitsPerSecond:mE,maxDurationMs:l}),Pr({recordingId:s,status:"recording"})}catch(g){return n.discard(s),qt(g)}}),e.registerTool("stop_recording",{description:"Stop the active browser recording and finalize the video. Returns a reference to the produced file (recordingId, mediaType, size, duration, resolution); the video is delivered to the chat. You act on it by reference - you do not receive the frames.",inputSchema:{recordingId:Ce.string().describe("The recordingId returned by start_recording.")}},async u=>{const r=u.recordingId;if(typeof r!="string"||r.length===0)return qt(new Error("recordingId is required to stop a recording."));try{await t.sendCommand("stop_recording",{recordingId:r});const i=await n.finalize(r);return Pr(i)}catch(i){return qt(i)}})}function gE(e,t,n){let u=Promise.resolve();const r=()=>{const i=u.then(()=>s4(t,n),()=>s4(t,n));return u=i.then(()=>{},()=>{}),i};e.registerTool("screenshot",{description:"Capture a screenshot of the current page. Returns a base64-encoded JPEG image."},()=>r()),e.registerTool("get_accessibility_tree",{description:'Get a text representation of the page accessibility tree with ref_ids for element targeting. Use filter "interactive" to only show clickable/typeable elements.',inputSchema:{filter:Ce.enum(["all","interactive"]).optional().describe('Filter: "all" for full tree, "interactive" for actionable elements only.'),maxDepth:Ce.number().optional().describe("Maximum tree depth. Default: 15."),maxLength:Ce.number().optional().describe("Maximum output character length. Default: 50000.")}},i=>Ve(t,"get_accessibility_tree",i)),e.registerTool("click",{description:"Click an element identified by its ref_id from the accessibility tree.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to click (from get_accessibility_tree).")}},i=>Ve(t,"click",i)),e.registerTool("right_click",{description:"Right-click an element identified by its ref_id.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to right-click.")}},i=>Ve(t,"right_click",i)),e.registerTool("double_click",{description:"Double-click an element identified by its ref_id.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to double-click.")}},i=>Ve(t,"double_click",i)),e.registerTool("hover",{description:"Hover over an element identified by its ref_id from the accessibility tree.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the element to hover over (from get_accessibility_tree).")}},i=>Ve(t,"hover",i)),e.registerTool("drag",{description:"Drag an element onto another element, both identified by ref_id.",inputSchema:{from_ref_id:Ce.string().describe("The ref_id of the element to drag."),to_ref_id:Ce.string().describe("The ref_id of the element to drop onto.")}},i=>Ve(t,"drag",i)),e.registerTool("type",{description:"Type text into the currently focused element.",inputSchema:{text:Ce.string().describe("The text to type.")}},i=>Ve(t,"type",i)),e.registerTool("key",{description:'Press a keyboard key or combination. Supports modifiers: "Control+a", "Shift+Enter", "Meta+c".',inputSchema:{key:Ce.string().describe('Key or combo to press (e.g. "Enter", "Tab", "Control+a", "ArrowDown").')}},i=>Ve(t,"key",i)),e.registerTool("fill",{description:"Clear and type text into an input or text area identified by its ref_id. Clicks the element, selects all existing content, then types the new value.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the input element to fill (from get_accessibility_tree)."),value:Ce.string().describe("The value to fill in.")}},i=>Ve(t,"fill",i)),e.registerTool("navigate",{description:"Navigate the current tab to a URL. Waits for the page to load.",inputSchema:{url:Ce.string().describe("The URL to navigate to.")}},i=>Ve(t,"navigate",i)),e.registerTool("go_back",{description:"Navigate back in the browser history."},()=>Ve(t,"go_back")),e.registerTool("go_forward",{description:"Navigate forward in the browser history."},()=>Ve(t,"go_forward")),e.registerTool("reload",{description:"Reload the current page. Waits for the page to load."},()=>Ve(t,"reload")),e.registerTool("scroll",{description:"Scroll the page up or down.",inputSchema:{direction:Ce.enum(["up","down"]).describe("Scroll direction."),amount:Ce.number().optional().describe("Scroll amount in pixels. Default: 500.")}},i=>Ve(t,"scroll",i)),e.registerTool("select_option",{description:"Select an option in a <select> dropdown by ref_id and value.",inputSchema:{ref_id:Ce.string().describe("The ref_id of the <select> element."),value:Ce.string().describe("The value or visible text of the option to select.")}},i=>Ve(t,"select_option",i)),e.registerTool("wait",{description:"Wait for a specified duration or for a navigation event.",inputSchema:{ms:Ce.number().optional().describe("Milliseconds to wait. Default: 1000."),for_navigation:Ce.boolean().optional().describe("If true, wait for a navigation event instead of a fixed delay.")}},i=>Ve(t,"wait",i)),e.registerTool("wait_for",{description:"Wait for any of the specified texts to appear on the page. Polls the page content until a match is found or the timeout is reached.",inputSchema:{text:Ce.array(Ce.string()).describe("Non-empty list of texts. Resolves when any value appears on the page."),timeout:Ce.number().optional().describe("Maximum wait time in milliseconds. Default: 30000.")}},i=>Ve(t,"wait_for",i)),e.registerTool("handle_dialog",{description:"Accept or dismiss a browser dialog (alert, confirm, prompt). Call this when a dialog is blocking page interaction.",inputSchema:{action:Ce.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog."),promptText:Ce.string().optional().describe("Text to enter into a prompt dialog before accepting. Only used for prompt dialogs.")}},i=>Ve(t,"handle_dialog",i)),e.registerTool("evaluate_script",{description:"Evaluate a JavaScript function in the current page. Returns the result as JSON. Use for reading page state, dismissing overlays, or any DOM operation the other tools cannot handle. Inline any arguments directly into the function body.",inputSchema:{function:Ce.string().describe(`A JavaScript function declaration with no arguments. Inline any values you need directly. Examples: "() => document.title", "() => document.querySelector('body').innerText".`)}},i=>Ve(t,"evaluate_script",i)),e.registerTool("upload_file",{description:`Upload a file by targeting the control that triggers a file upload. Works with upload buttons, drag zones, file input elements, and menu-based upload controls (e.g. OneDrive/SharePoint "Upload -> Files"): if clicking the control does not open a native file chooser, it sets the file directly on the page's hidden file input. On a menu, target the specific upload item (the "Files" option), not the menu button.`,inputSchema:{ref_id:Ce.string().describe("The ref_id of the element that triggers file upload (button, link, menu item, or file input)."),filePath:Ce.string().describe("The absolute path to the file to upload.")}},i=>Ve(t,"upload_file",i)),e.registerTool("list_tabs",{description:"List all open browser tabs with their IDs, titles, and URLs."},()=>Ve(t,"list_tabs")),e.registerTool("new_tab",{description:"Open a new browser tab, optionally with a URL.",inputSchema:{url:Ce.string().optional().describe("URL to open in the new tab. Defaults to about:blank.")}},i=>Ve(t,"new_tab",i)),e.registerTool("switch_tab",{description:"Switch to a different browser tab by its tab ID.",inputSchema:{tabId:Ce.number().describe("The Chrome tab ID to switch to.")}},i=>Ve(t,"switch_tab",i)),e.registerTool("close_tab",{description:"Close a browser tab. Defaults to the current tab.",inputSchema:{tabId:Ce.number().optional().describe("The Chrome tab ID to close. Defaults to the current tab.")}},i=>Ve(t,"close_tab",i))}var _E="pjdkhojhcdiebhpofmbooclincdfafjh";function yE(e){try{const t=JSON.parse(Ch(Ys(e,"manifest.json"),"utf8"));if(typeof t.key=="string"&&t.key.length>0)return $h("sha256").update(Buffer.from(t.key,"base64")).digest("hex").slice(0,32).replace(/[0-9a-f]/g,u=>String.fromCharCode(97+parseInt(u,16)))}catch{}return _E}async function EE(){const e=hE(process.argv.slice(2));let t=!1;const n=await oE(),u=new aE(n);await u.start();const r=e.enableRecording?new dE:null;r&&u.setRecordingHandler({onChunk:(f,g)=>r.handleChunk(f,g),onStopped:(f,g)=>r.handleStopped(f,g),onError:(f,g)=>r.handleError(f,g)});const i=e.profileDir??Ys(wh(),"browser-ext-profile"),a=e.enableRecording?[...e.extraFlags,`--allowlisted-extension-id=${yE(e.extensionDir)}`]:e.extraFlags,o=new Y3({bridge:u,wsPort:n,extensionDir:e.extensionDir,stealthDir:e.stealthDir,profileDir:i,downloadDir:e.downloadDir,chromePath:e.chromePath,renderer:e.renderer,acceptLanguage:e.acceptLanguage,extraFlags:a,resetWindowPlacement:e.resetWindowPlacement,extensionVersion:e.extensionVersion,durableProfile:e.durableProfile});async function s(){t||(t=!0,r?.hasActive()&&await Promise.race([r.finalizeAll(),new Promise(f=>{setTimeout(f,3e4)})]),await o.stop(),await u.stop(),process.exit(0))}o.setUnexpectedExitHandler(()=>{t||(console.error("[browser-extension-mcp] Chrome exited unexpectedly - shutting down"),s())}),u.setExtensionLostHandler(()=>{t||o.isRelaunching()||(console.error("[browser-extension-mcp] Extension disconnected past grace period - shutting down"),s())});try{o.start()}catch(f){throw await u.stop(),f}await u.waitForReady();const c=new g3({name:"browser-extension-mcp",version:"0.1.0"},{capabilities:{tools:{}}});gE(c,u,o),r&&vE(c,u,r);const l=new $3;await c.connect(l),process.stdin.on("end",()=>{s()}),process.on("SIGTERM",()=>{s()}),process.on("SIGINT",()=>{s()})}EE().catch(e=>{console.error("[browser-extension-mcp] Fatal:",e),process.exit(1)});
|