@anthropic-ai/claude-agent-sdk 0.2.59 → 0.2.62

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/manifest.json CHANGED
@@ -1,46 +1,46 @@
1
1
  {
2
- "version": "2.1.59",
3
- "buildDate": "2026-02-25T23:40:08Z",
2
+ "version": "2.1.62",
3
+ "buildDate": "2026-02-27T01:26:05Z",
4
4
  "platforms": {
5
5
  "darwin-arm64": {
6
6
  "binary": "claude",
7
- "checksum": "ef70dae6ed08b5538f6d157a8c8591f72c262fb8e570c94711bad3ae4ee44afa",
7
+ "checksum": "94f813561519676a95135e3d3631cbc74a14883222af20def6d5040d193cd5e7",
8
8
  "size": 187104656
9
9
  },
10
10
  "darwin-x64": {
11
11
  "binary": "claude",
12
- "checksum": "b3b69beae466ac1b7659bf5710ec1d5e7b20c848418cc701019462e0923ff0e0",
13
- "size": 192258768
12
+ "checksum": "4a9d619cde93101dd3279211cf1053db942f97d6a323cec1b570d52f43f1f3a9",
13
+ "size": 192275280
14
14
  },
15
15
  "linux-arm64": {
16
16
  "binary": "claude",
17
- "checksum": "78b0ea5a64793149f550ad3ddcfcbc7147128a600243839f703fb5b6a2194859",
18
- "size": 224884646
17
+ "checksum": "696c2f2a22a23375e9d7ee26af0aff417cd4a3a8cb704f24e4ba9c74a4c78d37",
18
+ "size": 224885165
19
19
  },
20
20
  "linux-x64": {
21
21
  "binary": "claude",
22
- "checksum": "7a4a653982b07e0a8157f8d3b2c2f8e442520ab07b2fa2e692ba054dbba210c9",
23
- "size": 227880817
22
+ "checksum": "d6f0726cb8e94b7a30c243964529ba9135e642c40d2134ca09f5f845071471b4",
23
+ "size": 227881448
24
24
  },
25
25
  "linux-arm64-musl": {
26
26
  "binary": "claude",
27
- "checksum": "4f16635c098b8302d5eaf83fe726c3582e00d91cf56a37d18d0c91efbcac6cd9",
28
- "size": 217281606
27
+ "checksum": "fc1c63993e96876adbf21358d50f55974f305fe55ab6d6fc81328a1d3e09553a",
28
+ "size": 217282125
29
29
  },
30
30
  "linux-x64-musl": {
31
31
  "binary": "claude",
32
- "checksum": "3adaebe59f10524bd9d19ebb3d090c3207b67143c0f40ec1cfc544409f8ded60",
33
- "size": 219578057
32
+ "checksum": "81ab92bd940e41a7a3083164b18da3e1e8314659c229231fb7693fc9fc15f10a",
33
+ "size": 219578688
34
34
  },
35
35
  "win32-x64": {
36
36
  "binary": "claude.exe",
37
- "checksum": "6dfdfa45ce01928317abb6c3774e0c533952c471002e468dd254022acd39e268",
38
- "size": 236043424
37
+ "checksum": "236a1c134b9e2b634e82e8749a3079fb2786e5fa81b44c2803fd070bd761ade8",
38
+ "size": 236044448
39
39
  },
40
40
  "win32-arm64": {
41
41
  "binary": "claude.exe",
42
- "checksum": "aadd9629f391a76e23bab6d06f8a6fe38f01137831012c96356cac178820e960",
43
- "size": 228253856
42
+ "checksum": "26fab9425f37a9cc113add6c9d9efc4f92a376feec138f181a4a87241736b50d",
43
+ "size": 228254368
44
44
  }
45
45
  }
46
46
  }
package/manifest.zst.json CHANGED
@@ -1,46 +1,46 @@
1
1
  {
2
- "version": "2.1.59",
3
- "buildDate": "2026-02-25T23:40:09Z",
2
+ "version": "2.1.62",
3
+ "buildDate": "2026-02-27T01:26:06Z",
4
4
  "platforms": {
5
5
  "darwin-arm64": {
6
6
  "binary": "claude.zst",
7
- "checksum": "2c7b6b64ff84b32137f4ec9192ad123e1a4307ff8c87a39bcee976f972edadc8",
8
- "size": 39568329
7
+ "checksum": "5efe9b5900c72bf63ca282328c4c31982498ac567456d397d85cb0b0e050f252",
8
+ "size": 39560421
9
9
  },
10
10
  "darwin-x64": {
11
11
  "binary": "claude.zst",
12
- "checksum": "a3fddc9042a929ffec3c85afb44c5e6c463e0e09ee3b52744bd48b550e34fe5d",
13
- "size": 41753192
12
+ "checksum": "4d650b2ad039fe24ab718f6412c96ed2ec7fcebe449d4146a5695b5558c5e6dc",
13
+ "size": 41751514
14
14
  },
15
15
  "linux-arm64": {
16
16
  "binary": "claude.zst",
17
- "checksum": "d88c9ccdedcaa028f9d777f5f5dfced4bc8b8f1f16fe6ccf984d4cda67d18fc4",
18
- "size": 50268125
17
+ "checksum": "9d4baec191387c582b30b18cd1e72d08db281b75caad11a410300446968824c9",
18
+ "size": 50259857
19
19
  },
20
20
  "linux-x64": {
21
21
  "binary": "claude.zst",
22
- "checksum": "f736b36fcd7cd43aa4f9d49b90ade42772d93d6b0d79392febd2b403e993b0bb",
23
- "size": 50988214
22
+ "checksum": "cfe0c4d5d531d8311a4c801bfb996adfa6308f1cc8ad10de45384f731d90629d",
23
+ "size": 50981280
24
24
  },
25
25
  "linux-arm64-musl": {
26
26
  "binary": "claude.zst",
27
- "checksum": "e365ca494621cc22ab1f0a6529313c60fd61545864bb5125b345422a8914d385",
28
- "size": 48590016
27
+ "checksum": "8a14aae2b88d49041abf4611c8dc2cc4ad578ff33bb5c9c914425847331cbba0",
28
+ "size": 48577466
29
29
  },
30
30
  "linux-x64-musl": {
31
31
  "binary": "claude.zst",
32
- "checksum": "8c542251bb243ffdf49edd102268a669759a064a232e44c321f5492e5e2328dd",
33
- "size": 49199121
32
+ "checksum": "b076b0adfe03e077e0af5837bb8582940470f75971ae0f1295fb11569c1bda10",
33
+ "size": 49194482
34
34
  },
35
35
  "win32-x64": {
36
36
  "binary": "claude.exe.zst",
37
- "checksum": "6d67ce0325ddc4540a454974fab51d265cdefeaa221deb5e9d2797eb7937e8bc",
38
- "size": 52890200
37
+ "checksum": "6d21f4563e416f1df76b3f644eabfd193730d3af366a3fc98df814389e7cfaed",
38
+ "size": 52889856
39
39
  },
40
40
  "win32-arm64": {
41
41
  "binary": "claude.exe.zst",
42
- "checksum": "a4fcfd2c60fed9b75d2c5d26f49c749a46477759533e558d7f2c616d5491746b",
43
- "size": 50267589
42
+ "checksum": "c5b08edcd0134aa795b372d1e0077d1e33c40ede7c91a4bb02e315e238fc611a",
43
+ "size": 50258748
44
44
  }
45
45
  }
46
46
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anthropic-ai/claude-agent-sdk",
3
- "version": "0.2.59",
3
+ "version": "0.2.62",
4
4
  "main": "sdk.mjs",
5
5
  "types": "sdk.d.ts",
6
6
  "engines": {
@@ -38,5 +38,5 @@
38
38
  "@img/sharp-win32-arm64": "^0.34.2",
39
39
  "@img/sharp-win32-x64": "^0.34.2"
40
40
  },
41
- "claudeCodeVersion": "2.1.59"
41
+ "claudeCodeVersion": "2.1.62"
42
42
  }
package/sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
3
3
 
4
- // Version: 0.2.59
4
+ // Version: 0.2.62
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -56,5 +56,5 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
56
56
  ]))`;continue}else if($[B]==="$"){W+=`($|(?=[\r
57
57
  ]))`;continue}}if(Y.s&&$[B]==="."){W+=G?`${$[B]}\r
58
58
  `:`[${$[B]}\r
59
- ]`;continue}if(W+=$[B],$[B]==="\\")J=!0;else if(G&&$[B]==="]")G=!1;else if(!G&&$[B]==="[")G=!0}try{new RegExp(W)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return W}function g8(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce(($,W)=>({...$,[W]:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",W]})??K0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Y;if(Q.keyType?._def.typeName===A.ZodString&&Q.keyType._def.checks?.length){let{type:$,...W}=y8(Q.keyType._def,X);return{...Y,propertyNames:W}}else if(Q.keyType?._def.typeName===A.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===A.ZodBranded&&Q.keyType._def.type._def.typeName===A.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:$,...W}=x8(Q.keyType._def,X);return{...Y,propertyNames:W}}return Y}function BG(Q,X){if(X.mapStrategy==="record")return g8(Q,X);let Y=g(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||K0(X),$=g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||K0(X);return{type:"array",maxItems:125,items:{type:"array",items:[Y,$],minItems:2,maxItems:2}}}function zG(Q){let X=Q.values,$=Object.keys(Q.values).filter((J)=>{return typeof X[X[J]]!=="number"}).map((J)=>X[J]),W=Array.from(new Set($.map((J)=>typeof J)));return{type:W.length===1?W[0]==="string"?"string":"number":["string","number"],enum:$}}function KG(Q){return Q.target==="openAi"?void 0:{not:K0({...Q,currentPath:[...Q.currentPath,"not"]})}}function VG(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UG(Q,X){if(X.target==="openApi3")return qG(Q,X);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every(($)=>($._def.typeName in t4)&&(!$._def.checks||!$._def.checks.length))){let $=Y.reduce((W,J)=>{let G=t4[J._def.typeName];return G&&!W.includes(G)?[...W,G]:W},[]);return{type:$.length>1?$:$[0]}}else if(Y.every(($)=>$._def.typeName==="ZodLiteral"&&!$.description)){let $=Y.reduce((W,J)=>{let G=typeof J._def.value;switch(G){case"string":case"number":case"boolean":return[...W,G];case"bigint":return[...W,"integer"];case"object":if(J._def.value===null)return[...W,"null"];case"symbol":case"undefined":case"function":default:return W}},[]);if($.length===Y.length){let W=$.filter((J,G,H)=>H.indexOf(J)===G);return{type:W.length>1?W:W[0],enum:Y.reduce((J,G)=>{return J.includes(G._def.value)?J:[...J,G._def.value]},[])}}}else if(Y.every(($)=>$._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce(($,W)=>[...$,...W._def.values.filter((J)=>!$.includes(J))],[])};return qG(Q,X)}var qG=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map(($,W)=>g($._def,{...X,currentPath:[...X.currentPath,"anyOf",`${W}`]})).filter(($)=>!!$&&(!X.strictUnions||typeof $==="object"&&Object.keys($).length>0));return Y.length?{anyOf:Y}:void 0};function LG(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:t4[Q.innerType._def.typeName],nullable:!0};return{type:[t4[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let $=g(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if($&&"$ref"in $)return{allOf:[$],nullable:!0};return $&&{...$,nullable:!0}}let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function FG(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let $ of Q.checks)switch($.kind){case"int":Y.type="integer",K$(Y,"type",$.message,X);break;case"min":if(X.target==="jsonSchema7")if($.inclusive)o(Y,"minimum",$.value,$.message,X);else o(Y,"exclusiveMinimum",$.value,$.message,X);else{if(!$.inclusive)Y.exclusiveMinimum=!0;o(Y,"minimum",$.value,$.message,X)}break;case"max":if(X.target==="jsonSchema7")if($.inclusive)o(Y,"maximum",$.value,$.message,X);else o(Y,"exclusiveMaximum",$.value,$.message,X);else{if(!$.inclusive)Y.exclusiveMaximum=!0;o(Y,"maximum",$.value,$.message,X)}break;case"multipleOf":o(Y,"multipleOf",$.value,$.message,X);break}return Y}function NG(Q,X){let Y=X.target==="openAi",$={type:"object",properties:{}},W=[],J=Q.shape();for(let H in J){let B=J[H];if(B===void 0||B._def===void 0)continue;let z=LO(B);if(z&&Y){if(B._def.typeName==="ZodOptional")B=B._def.innerType;if(!B.isNullable())B=B.nullable();z=!1}let K=g(B._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(K===void 0)continue;if($.properties[H]=K,!z)W.push(H)}if(W.length)$.required=W;let G=UO(Q,X);if(G!==void 0)$.additionalProperties=G;return $}function UO(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return g(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function LO(Q){try{return Q.isOptional()}catch{return!0}}var OG=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return g(Q.innerType._def,X);let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:K0(X)},Y]}:K0(X)};var DG=(Q,X)=>{if(X.pipeStrategy==="input")return g(Q.in._def,X);else if(X.pipeStrategy==="output")return g(Q.out._def,X);let Y=g(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),$=g(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,$].filter((W)=>W!==void 0)}};function wG(Q,X){return g(Q.type._def,X)}function MG(Q,X){let $={type:"array",uniqueItems:!0,items:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)o($,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)o($,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return $}function AG(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,$)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${$}`]})).reduce((Y,$)=>$===void 0?Y:[...Y,$],[]),additionalItems:g(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,$)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${$}`]})).reduce((Y,$)=>$===void 0?Y:[...Y,$],[])}}function jG(Q){return{not:K0(Q)}}function RG(Q){return K0(Q)}var IG=(Q,X)=>{return g(Q.innerType._def,X)};var bG=(Q,X,Y)=>{switch(X){case A.ZodString:return y8(Q,Y);case A.ZodNumber:return FG(Q,Y);case A.ZodObject:return NG(Q,Y);case A.ZodBigInt:return eJ(Q,Y);case A.ZodBoolean:return QG();case A.ZodDate:return V$(Q,Y);case A.ZodUndefined:return jG(Y);case A.ZodNull:return VG(Y);case A.ZodArray:return sJ(Q,Y);case A.ZodUnion:case A.ZodDiscriminatedUnion:return UG(Q,Y);case A.ZodIntersection:return JG(Q,Y);case A.ZodTuple:return AG(Q,Y);case A.ZodRecord:return g8(Q,Y);case A.ZodLiteral:return GG(Q,Y);case A.ZodEnum:return WG(Q);case A.ZodNativeEnum:return zG(Q);case A.ZodNullable:return LG(Q,Y);case A.ZodOptional:return OG(Q,Y);case A.ZodMap:return BG(Q,Y);case A.ZodSet:return MG(Q,Y);case A.ZodLazy:return()=>Q.getter()._def;case A.ZodPromise:return wG(Q,Y);case A.ZodNaN:case A.ZodNever:return KG(Y);case A.ZodEffects:return $G(Q,Y);case A.ZodAny:return K0(Y);case A.ZodUnknown:return RG(Y);case A.ZodDefault:return YG(Q,Y);case A.ZodBranded:return x8(Q,Y);case A.ZodReadonly:return IG(Q,Y);case A.ZodCatch:return XG(Q,Y);case A.ZodPipeline:return DG(Q,Y);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(($)=>{return})(X)}};function g(Q,X,Y=!1){let $=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,$,Y);if(H!==rJ)return H}if($&&!Y){let H=FO($,X);if(H!==void 0)return H}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let J=bG(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)NO(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return W.jsonSchema=G,H}return W.jsonSchema=G,G}var FO=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:T8(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,$)=>X.currentPath[$]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),K0(X);return X.$refStrategy==="seen"?K0(X):void 0}}},NO=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var L$=(Q,X)=>{let Y=aJ(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((B,[z,K])=>({...B,[z]:g(K._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,z]},!0)??K0(Y)}),{}):void 0,W=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,J=g(Q._def,W===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,W]},!1)??K0(Y),G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)J.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!$)$={};if(!$[Y.openAiAnyTypeName])$[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let H=W===void 0?$?{...J,[Y.definitionPath]:$}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,W].join("/"),[Y.definitionPath]:{...$,[W]:J}};if(Y.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function OO(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function F$(Q,X){if(d0(Q))return gY(Q,{target:OO(X?.target),io:X?.pipeStrategy??"input"});return L$(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function N$(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=K8(Y);if(typeof $!=="string")throw Error("Schema method literal must be a string");return $}function O$(Q,X){let Y=h1(Q,X);if(!Y.success)throw Y.error;return Y.data}var DO=60000;class D${constructor(Q){if(this._options=Q,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(O8,(X)=>{this._oncancel(X)}),this.setNotificationHandler(w8,(X)=>{this._onprogress(X)}),this.setRequestHandler(D8,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(M8,async(X,Y)=>{let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return{...$}}),this.setRequestHandler(j8,async(X,Y)=>{let $=async()=>{let W=X.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue(W,Y.sessionId)){if(G.type==="response"||G.type==="error"){let H=G.message,B=H.id,z=this._requestResolvers.get(B);if(z)if(this._requestResolvers.delete(B),G.type==="response")z(H);else{let K=H,q=new S(K.error.code,K.error.message,K.error.data);z(q)}else{let K=G.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${B}`))}continue}await this._transport?.send(G.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask(W,Y.sessionId);if(!J)throw new S(k.InvalidParams,`Task not found: ${W}`);if(!l1(J.status))return await this._waitForTaskUpdate(W,Y.signal),await $();if(l1(J.status)){let G=await this._taskStore.getTaskResult(W,Y.sessionId);return this._clearTaskQueue(W),{...G,_meta:{...G._meta,[u1]:{taskId:W}}}}return await $()};return await $()}),this.setRequestHandler(R8,async(X,Y)=>{try{let{tasks:$,nextCursor:W}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:$,nextCursor:W,_meta:{}}}catch($){throw new S(k.InvalidParams,`Failed to list tasks: ${$ instanceof Error?$.message:String($)}`)}}),this.setRequestHandler(b8,async(X,Y)=>{try{let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new S(k.InvalidParams,`Task not found: ${X.params.taskId}`);if(l1($.status))throw new S(k.InvalidParams,`Cannot cancel task in terminal status: ${$.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new S(k.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...W}}catch($){if($ instanceof S)throw $;throw new S(k.InvalidRequest,`Failed to cancel task: ${$ instanceof Error?$.message:String($)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,$,W=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout($,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:W,onTimeout:$})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),S.fromError(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=(W)=>{Y?.(W),this._onerror(W)};let $=this._transport?.onmessage;this._transport.onmessage=(W,J)=>{if($?.(W,J),l4(W)||gJ(W))this._onresponse(W);else if(tY(W))this._onrequest(W,J);else if(yJ(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Y of this._requestHandlerAbortControllers.values())Y.abort();this._requestHandlerAbortControllers.clear();let X=S.fromError(k.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,$=this._transport,W=Q.params?._meta?.[u1]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:k.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:z,timestamp:Date.now()},$?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else $?.send(z).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let G=vJ(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,$?.sessionId):void 0,B={signal:J.signal,sessionId:$?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{if(J.signal.aborted)return;let K={relatedRequestId:Q.id};if(W)K.relatedTask={taskId:W};await this.notification(z,K)},sendRequest:async(z,K,q)=>{if(J.signal.aborted)throw new S(k.ConnectionClosed,"Request was cancelled");let U={...q,relatedRequestId:Q.id};if(W&&!U.relatedTask)U.relatedTask={taskId:W};let V=U.relatedTask?.taskId??W;if(V&&H)await H.updateTaskStatus(V,"input_required");return await this.request(z,K,U)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:W,taskStore:H,taskRequestedTtl:G?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,B)).then(async(z)=>{if(J.signal.aborted)return;let K={result:z,jsonrpc:"2.0",id:Q.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:K,timestamp:Date.now()},$?.sessionId);else await $?.send(K)},async(z)=>{if(J.signal.aborted)return;let K={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:k.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:K,timestamp:Date.now()},$?.sessionId);else await $?.send(K)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,$=Number(X),W=this._progressHandlers.get($);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get($),G=this._timeoutInfo.get($);if(G&&J&&G.resetTimeoutOnProgress)try{this._resetTimeout($)}catch(H){this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),J(H);return}W(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),l4(Q))Y(Q);else{let J=new S(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let $=this._responseHandlers.get(X);if($===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let W=!1;if(l4(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let G=J.task;if(typeof G.taskId==="string")W=!0,this._taskProgressTokens.set(G.taskId,X)}}if(!W)this._progressHandlers.delete(X);if(l4(Q))$(Q);else{let J=S.fromError(Q.error.code,Q.error.message,Q.error.data);$(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:$}=Y??{};if(!$){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}return}let W;try{let J=await this.request(Q,p6,Y);if(J.task)W=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new S(k.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:W},Y);if(yield{type:"taskStatus",task:G},l1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},X,Y)};else if(G.status==="failed")yield{type:"error",error:new S(k.InternalError,`Task ${W} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new S(k.InternalError,`Task ${W} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},X,Y)};return}let H=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,H)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J,task:G,relatedTask:H}=Y??{};return new Promise((B,z)=>{let K=(D)=>{z(D)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),G)this.assertTaskCapability(Q.method)}catch(D){K(D);return}Y?.signal?.throwIfAborted();let q=this._requestMessageId++,U={...Q,jsonrpc:"2.0",id:q};if(Y?.onprogress)this._progressHandlers.set(q,Y.onprogress),U.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:q}};if(G)U.params={...U.params,task:G};if(H)U.params={...U.params,_meta:{...U.params?._meta||{},[u1]:H}};let V=(D)=>{this._responseHandlers.delete(q),this._progressHandlers.delete(q),this._cleanupTimeout(q),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:q,reason:String(D)}},{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let j=D instanceof S?D:new S(k.RequestTimeout,String(D));z(j)};this._responseHandlers.set(q,(D)=>{if(Y?.signal?.aborted)return;if(D instanceof Error)return z(D);try{let j=h1(X,D.result);if(!j.success)z(j.error);else B(j.data)}catch(j){z(j)}}),Y?.signal?.addEventListener("abort",()=>{V(Y?.signal?.reason)});let L=Y?.timeout??DO,F=()=>V(S.fromError(k.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(q,L,Y?.maxTotalTimeout,F,Y?.resetTimeoutOnProgress??!1);let w=H?.taskId;if(w){let D=(j)=>{let I=this._responseHandlers.get(q);if(I)I(j);else this._onerror(Error(`Response handler missing for side-channeled request ${q}`))};this._requestResolvers.set(q,D),this._enqueueTaskMessage(w,{type:"request",message:U,timestamp:Date.now()}).catch((j)=>{this._cleanupTimeout(q),z(j)})}else this._transport.send(U,{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J}).catch((D)=>{this._cleanupTimeout(q),z(D)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},A8,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},I8,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},fJ,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let G={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[u1]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[u1]:X.relatedTask}}};this._transport?.send(G,X).catch((H)=>this._onerror(H))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[u1]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=N$(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,($,W)=>{let J=O$(Q,$);return Promise.resolve(X(J,W))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=N$(Q);this._notificationHandlers.set(Y,($)=>{let W=O$(Q,$);return Promise.resolve(X(W))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let $=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,$)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let $ of Y)if($.type==="request"&&tY($.message)){let W=$.message.id,J=this._requestResolvers.get(W);if(J)J(new S(k.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let $=await this._taskStore?.getTask(Q);if($?.pollInterval)Y=$.pollInterval}catch{}return new Promise(($,W)=>{if(X.aborted){W(new S(k.InvalidRequest,"Request cancelled"));return}let J=setTimeout($,Y);X.addEventListener("abort",()=>{clearTimeout(J),W(new S(k.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async($)=>{if(!Q)throw Error("No request provided");return await Y.createTask($,Q.id,{method:Q.method,params:Q.params},X)},getTask:async($)=>{let W=await Y.getTask($,X);if(!W)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async($,W,J)=>{await Y.storeTaskResult($,W,J,X);let G=await Y.getTask($,X);if(G){let H=i4.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),l1(G.status))this._cleanupTaskProgressHandler($)}},getTaskResult:($)=>{return Y.getTaskResult($,X)},updateTaskStatus:async($,W,J)=>{let G=await Y.getTask($,X);if(!G)throw new S(k.InvalidParams,`Task "${$}" not found - it may have been cleaned up`);if(l1(G.status))throw new S(k.InvalidParams,`Cannot update task "${$}" from terminal status "${G.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus($,W,J,X);let H=await Y.getTask($,X);if(H){let B=i4.parse({method:"notifications/tasks/status",params:H});if(await this.notification(B),l1(H.status))this._cleanupTaskProgressHandler($)}},listTasks:($)=>{return Y.listTasks($,X)}}}}function EG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function PG(Q,X){let Y={...Q};for(let $ in X){let W=$,J=X[W];if(J===void 0)continue;let G=Y[W];if(EG(G)&&EG(J))Y[W]={...G,...J};else Y[W]=J}return Y}var KK=v7(V7(),1),VK=v7(zK(),1);function Eb(){let Q=new KK.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return VK.default(Q),Q}class A7{constructor(Q){this._ajv=Q??Eb()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class j7{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}createMessageStream(Q,X){let Y=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!Y?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let $=Q.messages[Q.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],J=W.some((z)=>z.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=G?Array.isArray(G.content)?G.content:[G.content]:[],B=H.some((z)=>z.type==="tool_use");if(J){if(W.some((z)=>z.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!B)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(B){let z=new Set(H.filter((q)=>q.type==="tool_use").map((q)=>q.id)),K=new Set(W.filter((q)=>q.type==="tool_result").map((q)=>q.toolUseId));if(z.size!==K.size||![...z].every((q)=>K.has(q)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},r4,X)}elicitInputStream(Q,X){let Y=this._server.getClientCapabilities(),$=Q.mode??"form";switch($){case"url":{if(!Y?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Y?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let W=$==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:W},n6,X)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function qK(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function UK(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class R7 extends D${constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(o4.options.map((Y,$)=>[Y,$])),this.isMessageIgnored=(Y,$)=>{let W=this._loggingLevels.get($);return W?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get(W):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new A7,this.setRequestHandler(eY,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(Q$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(H$,async(Y,$)=>{let W=$.sessionId||$.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,G=o4.safeParse(J);if(G.success)this._loggingLevels.set(W,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new j7(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=PG(this._capabilities,Q)}setRequestHandler(Q,X){let $=f1(Q)?.method;if(!$)throw Error("Schema is missing a method literal");let W;if(d0($)){let G=$;W=G._zod?.def?.value??G.value}else{let G=$;W=G._def?.value??G.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="tools/call"){let G=async(H,B)=>{let z=h1(i6,H);if(!z.success){let V=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid tools/call request: ${V}`)}let{params:K}=z.data,q=await Promise.resolve(X(H,B));if(K.task){let V=h1(p6,q);if(!V.success){let L=V.error instanceof Error?V.error.message:String(V.error);throw new S(k.InvalidParams,`Invalid task creation result: ${L}`)}return V.data}let U=h1(k8,q);if(!U.success){let V=U.error instanceof Error?U.error.message:String(U.error);throw new S(k.InvalidParams,`Invalid tools/call result: ${V}`)}return U.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){UK(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;qK(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:CJ.includes(X)?X:oY,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"},N8)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],$=Array.isArray(Y.content)?Y.content:[Y.content],W=$.some((B)=>B.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,G=J?Array.isArray(J.content)?J.content:[J.content]:[],H=G.some((B)=>B.type==="tool_use");if(W){if($.some((B)=>B.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let B=new Set(G.filter((K)=>K.type==="tool_use").map((K)=>K.id)),z=new Set($.filter((K)=>K.type==="tool_result").map((K)=>K.toolUseId));if(B.size!==z.size||![...B].every((K)=>z.has(K)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},B$,X);return this.request({method:"sampling/createMessage",params:Q},r4,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let $=Q;return this.request({method:"elicitation/create",params:$},n6,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let $=Q.mode==="form"?Q:{...Q,mode:"form"},W=await this.request({method:"elicitation/create",params:$},n6,X);if(W.action==="accept"&&W.content&&$.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator($.requestedSchema)(W.content);if(!G.valid)throw new S(k.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(J){if(J instanceof S)throw J;throw new S(k.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return W}}}createElicitationCompletionNotifier(Q,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},z$,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var FK=Symbol.for("mcp.completable");function I7(Q){return!!Q&&typeof Q==="object"&&FK in Q}function NK(Q){return Q[FK]?.complete}var LK;(function(Q){Q.Completable="McpCompletable"})(LK||(LK={}));var Pb=/^[A-Za-z0-9._-]{1,128}$/;function Zb(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Pb.test(Q)){let Y=Q.split("").filter(($)=>!/[A-Za-z0-9._-]/.test($)).filter(($,W,J)=>J.indexOf($)===W);return X.push(`Tool name contains invalid characters: ${Y.map(($)=>`"${$}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function Sb(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let Y of X)console.warn(` - ${Y}`);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 b7(Q){let X=Zb(Q);return Sb(Q,X.warnings),X.isValid}class E7{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,Y){let $={taskSupport:"required",...X.execution};if($.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,$,X._meta,Y)}}class Z7{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new R7(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new E7(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(_8)),this.server.assertCanSetRequestHandler(r1(i6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_8,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let $=m6(X.inputSchema);return $?F$($,{strictUnions:!0,pipeStrategy:"input"}):Cb})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let $=m6(X.outputSchema);if($)Y.outputSchema=F$($,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(i6,async(Q,X)=>{try{let Y=this._registeredTools[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Tool ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Tool ${Q.params.name} disabled`);let $=!!Q.params.task,W=Y.execution?.taskSupport,J="createTask"in Y.handler;if((W==="required"||W==="optional")&&!J)throw new S(k.InternalError,`Tool ${Q.params.name} has taskSupport '${W}' but was not registered with registerToolTask`);if(W==="required"&&!$)throw new S(k.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if(W==="optional"&&!$&&J)return await this.handleAutomaticTaskPolling(Y,Q,X);let G=await this.validateToolInput(Y,Q.params.arguments,Q.params.name),H=await this.executeToolHandler(Y,G,X);if($)return H;return await this.validateToolOutput(Y,H,Q.params.name),H}catch(Y){if(Y instanceof S){if(Y.code===k.UrlElicitationRequired)throw Y}return this.createToolError(Y instanceof Error?Y.message:String(Y))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,Y){if(!Q.inputSchema)return;let W=m6(Q.inputSchema)??Q.inputSchema,J=await B8(W,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=z8(G);throw new S(k.InvalidParams,`Input validation error: Invalid arguments for tool ${Y}: ${H}`)}return J.data}async validateToolOutput(Q,X,Y){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new S(k.InvalidParams,`Output validation error: Tool ${Y} has an output schema but no structured content was provided`);let $=m6(Q.outputSchema),W=await B8($,X.structuredContent);if(!W.success){let J="error"in W?W.error:"Unknown error",G=z8(J);throw new S(k.InvalidParams,`Output validation error: Invalid structured content for tool ${Y}: ${G}`)}}async executeToolHandler(Q,X,Y){let $=Q.handler;if("createTask"in $){if(!Y.taskStore)throw Error("No task store provided.");let J={...Y,taskStore:Y.taskStore};if(Q.inputSchema)return await Promise.resolve($.createTask(X,J));else return await Promise.resolve($.createTask(J))}if(Q.inputSchema)return await Promise.resolve($(X,Y));else return await Promise.resolve($(Y))}async handleAutomaticTaskPolling(Q,X,Y){if(!Y.taskStore)throw Error("No task store provided for task-capable tool.");let $=await this.validateToolInput(Q,X.params.arguments,X.params.name),W=Q.handler,J={...Y,taskStore:Y.taskStore},G=$?await Promise.resolve(W.createTask($,J)):await Promise.resolve(W.createTask(J)),H=G.task.taskId,B=G.task,z=B.pollInterval??5000;while(B.status!=="completed"&&B.status!=="failed"&&B.status!=="cancelled"){await new Promise((q)=>setTimeout(q,z));let K=await Y.taskStore.getTask(H);if(!K)throw new S(k.InternalError,`Task ${H} not found during polling`);B=K}return await Y.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(r1(v8)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(v8,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return dJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return iJ(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new S(k.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let Y=this._registeredPrompts[X.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${X.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${X.name} disabled`);if(!Y.argsSchema)return M9;let W=f1(Y.argsSchema)?.[Q.params.argument.name];if(!I7(W))return M9;let J=NK(W);if(!J)return M9;let G=await J(Q.params.argument.value,Q.params.context);return DK(G)}async handleResourceCompletion(Q,X){let Y=Object.values(this._registeredResourceTemplates).find((J)=>J.resourceTemplate.uriTemplate.toString()===X.uri);if(!Y){if(this._registeredResources[X.uri])return M9;throw new S(k.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let $=Y.resourceTemplate.completeCallback(Q.params.argument.name);if(!$)return M9;let W=await $(Q.params.argument.value,Q.params.context);return DK(W)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(E8)),this.server.assertCanSetRequestHandler(r1(P8)),this.server.assertCanSetRequestHandler(r1(Z8)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(E8,async(Q,X)=>{let Y=Object.entries(this._registeredResources).filter(([W,J])=>J.enabled).map(([W,J])=>({uri:W,name:J.name,...J.metadata})),$=[];for(let W of Object.values(this._registeredResourceTemplates)){if(!W.resourceTemplate.listCallback)continue;let J=await W.resourceTemplate.listCallback(X);for(let G of J.resources)$.push({...W.metadata,...G})}return{resources:[...Y,...$]}}),this.server.setRequestHandler(P8,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(Z8,async(Q,X)=>{let Y=new URL(Q.params.uri),$=this._registeredResources[Y.toString()];if($){if(!$.enabled)throw new S(k.InvalidParams,`Resource ${Y} disabled`);return $.readCallback(Y,X)}for(let W of Object.values(this._registeredResourceTemplates)){let J=W.resourceTemplate.uriTemplate.match(Y.toString());if(J)return W.readCallback(Y,J,X)}throw new S(k.InvalidParams,`Resource ${Y} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(S8)),this.server.assertCanSetRequestHandler(r1(C8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S8,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?kb(X.argsSchema):void 0}})})),this.server.setRequestHandler(C8,async(Q,X)=>{let Y=this._registeredPrompts[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${Q.params.name} disabled`);if(Y.argsSchema){let $=m6(Y.argsSchema),W=await B8($,Q.params.arguments);if(!W.success){let H="error"in W?W.error:"Unknown error",B=z8(H);throw new S(k.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${B}`)}let J=W.data,G=Y.callback;return await Promise.resolve(G(J,X))}else{let $=Y.callback;return await Promise.resolve($(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...Y){let $;if(typeof Y[0]==="object")$=Y.shift();let W=Y[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let J=this._createRegisteredResource(Q,void 0,X,$,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let J=this._createRegisteredResourceTemplate(Q,void 0,X,$,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}}registerResource(Q,X,Y,$){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let W=this._createRegisteredResource(Q,Y.title,X,Y,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let W=this._createRegisteredResourceTemplate(Q,Y.title,X,Y,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}}_createRegisteredResource(Q,X,Y,$,W){let J={name:Q,title:X,metadata:$,readCallback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({uri:null}),update:(G)=>{if(typeof G.uri<"u"&&G.uri!==Y){if(delete this._registeredResources[Y],G.uri)this._registeredResources[G.uri]=J}if(typeof G.name<"u")J.name=G.name;if(typeof G.title<"u")J.title=G.title;if(typeof G.metadata<"u")J.metadata=G.metadata;if(typeof G.callback<"u")J.readCallback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendResourceListChanged()}};return this._registeredResources[Y]=J,J}_createRegisteredResourceTemplate(Q,X,Y,$,W){let J={resourceTemplate:Y,title:X,metadata:$,readCallback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(B)=>{if(typeof B.name<"u"&&B.name!==Q){if(delete this._registeredResourceTemplates[Q],B.name)this._registeredResourceTemplates[B.name]=J}if(typeof B.title<"u")J.title=B.title;if(typeof B.template<"u")J.resourceTemplate=B.template;if(typeof B.metadata<"u")J.metadata=B.metadata;if(typeof B.callback<"u")J.readCallback=B.callback;if(typeof B.enabled<"u")J.enabled=B.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=J;let G=Y.uriTemplate.variableNames;if(Array.isArray(G)&&G.some((B)=>!!Y.completeCallback(B)))this.setCompletionRequestHandler();return J}_createRegisteredPrompt(Q,X,Y,$,W){let J={title:X,description:Y,argsSchema:$===void 0?void 0:q6($),callback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(G)=>{if(typeof G.name<"u"&&G.name!==Q){if(delete this._registeredPrompts[Q],G.name)this._registeredPrompts[G.name]=J}if(typeof G.title<"u")J.title=G.title;if(typeof G.description<"u")J.description=G.description;if(typeof G.argsSchema<"u")J.argsSchema=q6(G.argsSchema);if(typeof G.callback<"u")J.callback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=J,$){if(Object.values($).some((H)=>{let B=H instanceof p0?H._def?.innerType:H;return I7(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,$,W,J,G,H,B){b7(Q);let z={title:X,description:Y,inputSchema:OK($),outputSchema:OK(W),annotations:J,execution:G,_meta:H,handler:B,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(K)=>{if(typeof K.name<"u"&&K.name!==Q){if(typeof K.name==="string")b7(K.name);if(delete this._registeredTools[Q],K.name)this._registeredTools[K.name]=z}if(typeof K.title<"u")z.title=K.title;if(typeof K.description<"u")z.description=K.description;if(typeof K.paramsSchema<"u")z.inputSchema=q6(K.paramsSchema);if(typeof K.outputSchema<"u")z.outputSchema=q6(K.outputSchema);if(typeof K.callback<"u")z.handler=K.callback;if(typeof K.annotations<"u")z.annotations=K.annotations;if(typeof K._meta<"u")z._meta=K._meta;if(typeof K.enabled<"u")z.enabled=K.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=z,this.setToolRequestHandlers(),this.sendToolListChanged(),z}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let Y,$,W,J;if(typeof X[0]==="string")Y=X.shift();if(X.length>1){let H=X[0];if(P7(H)){if($=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!P7(X[0]))J=X.shift()}else if(typeof H==="object"&&H!==null)J=X.shift()}let G=X[0];return this._createRegisteredTool(Q,void 0,Y,$,W,J,{taskSupport:"forbidden"},void 0,G)}registerTool(Q,X,Y){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:$,description:W,inputSchema:J,outputSchema:G,annotations:H,_meta:B}=X;return this._createRegisteredTool(Q,$,W,J,G,H,{taskSupport:"forbidden"},B,Y)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let Y;if(typeof X[0]==="string")Y=X.shift();let $;if(X.length>1)$=X.shift();let W=X[0],J=this._createRegisteredPrompt(Q,void 0,Y,$,W);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}registerPrompt(Q,X,Y){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:$,description:W,argsSchema:J}=X,G=this._createRegisteredPrompt(Q,$,W,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Cb={type:"object",properties:{}};function wK(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function _b(Q){return"_def"in Q||"_zod"in Q||wK(Q)}function P7(Q){if(typeof Q!=="object"||Q===null)return!1;if(_b(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(wK)}function OK(Q){if(!Q)return;if(P7(Q))return q6(Q);return Q}function kb(Q){let X=f1(Q);if(!X)return[];return Object.entries(X).map(([Y,$])=>{let W=HJ($),J=BJ($);return{name:Y,description:W,required:!J}})}function r1(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=K8(Y);if(typeof $==="string")return $;throw Error("Schema method literal must be a string")}function DK(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var M9={completion:{values:[],hasMore:!1}};function vb(Q,X,Y,$,W){return{name:Q,description:X,inputSchema:Y,handler:$,annotations:W?.annotations}}function Tb(Q){let X=new Z7({name:Q.name,version:Q.version??"1.0.0"},{capabilities:{tools:Q.tools?{}:void 0}});if(Q.tools)Q.tools.forEach((Y)=>{X.registerTool(Y.name,{description:Y.description,inputSchema:Y.inputSchema,annotations:Y.annotations},Y.handler)});return{type:"sdk",name:Q.name,instance:X}}function Ay({prompt:Q,options:X}){let{systemPrompt:Y,settingSources:$,sandbox:W,...J}=X??{},G,H;if(Y===void 0)G="";else if(typeof Y==="string")G=Y;else if(Y.type==="preset")H=Y.append;let B=J.pathToClaudeCodeExecutable;if(!B){let A6=xb(import.meta.url),j6=MK(A6,"..");B=MK(j6,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.59";let{abortController:z=R6(),additionalDirectories:K=[],agent:q,agents:U,allowedTools:V=[],betas:L,canUseTool:F,continue:w,cwd:D,debug:j,debugFile:I,disallowedTools:T=[],tools:v,env:N0,executable:O0=_6()?"bun":"node",executableArgs:c0=[],extraArgs:t1={},fallbackModel:q1,enableFileCheckpointing:a1,forkSession:P1,hooks:s1,includePartialMessages:u,persistSession:AQ,thinking:e1,effort:J4,maxThinkingTokens:Q6,maxTurns:A9,maxBudgetUsd:j9,mcpServers:b0,model:Z1,outputFormat:w6,permissionMode:AK="default",allowDangerouslySkipPermissions:jK=!1,permissionPromptToolName:RK,plugins:IK,resume:bK,resumeSessionAt:EK,sessionId:PK,stderr:ZK,strictMcpConfig:SK}=J,S7=w6?.type==="json_schema"?w6.schema:void 0,M6=N0;if(!M6)M6={...process.env};if(!M6.CLAUDE_CODE_ENTRYPOINT)M6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(a1)M6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!B)throw Error("pathToClaudeCodeExecutable is required");let jQ={},C7=new Map;if(b0)for(let[A6,j6]of Object.entries(b0))if(j6.type==="sdk"&&"instance"in j6)C7.set(A6,j6.instance),jQ[A6]={type:"sdk",name:A6};else jQ[A6]=j6;let CK=typeof Q==="string",G4;if(e1)switch(e1.type){case"adaptive":G4={type:"adaptive"};break;case"enabled":G4={type:"enabled",budgetTokens:e1.budgetTokens};break;case"disabled":G4={type:"disabled"};break}else if(Q6!==void 0)G4=Q6===0?{type:"disabled"}:{type:"enabled",budgetTokens:Q6};let _7=new B4({abortController:z,additionalDirectories:K,agent:q,betas:L,cwd:D,debug:j,debugFile:I,executable:O0,executableArgs:c0,extraArgs:t1,pathToClaudeCodeExecutable:B,env:M6,forkSession:P1,stderr:ZK,thinkingConfig:G4,effort:J4,maxTurns:A9,maxBudgetUsd:j9,model:Z1,fallbackModel:q1,jsonSchema:S7,permissionMode:AK,allowDangerouslySkipPermissions:jK,permissionPromptToolName:RK,continueConversation:w,resume:bK,resumeSessionAt:EK,sessionId:PK,settingSources:$??[],allowedTools:V,disallowedTools:T,tools:v,mcpServers:jQ,strictMcpConfig:SK,canUseTool:!!F,hooks:!!s1,includePartialMessages:u,persistSession:AQ,plugins:IK,sandbox:W,spawnClaudeCodeProcess:J.spawnClaudeCodeProcess}),_K={systemPrompt:G,appendSystemPrompt:H,agents:U,promptSuggestions:J.promptSuggestions},k7=new K4(_7,CK,F,s1,z,C7,S7,_K);if(typeof Q==="string")_7.write(Z0({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+`
59
+ ]`;continue}if(W+=$[B],$[B]==="\\")J=!0;else if(G&&$[B]==="]")G=!1;else if(!G&&$[B]==="[")G=!0}try{new RegExp(W)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return W}function g8(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce(($,W)=>({...$,[W]:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",W]})??K0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Y;if(Q.keyType?._def.typeName===A.ZodString&&Q.keyType._def.checks?.length){let{type:$,...W}=y8(Q.keyType._def,X);return{...Y,propertyNames:W}}else if(Q.keyType?._def.typeName===A.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===A.ZodBranded&&Q.keyType._def.type._def.typeName===A.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:$,...W}=x8(Q.keyType._def,X);return{...Y,propertyNames:W}}return Y}function BG(Q,X){if(X.mapStrategy==="record")return g8(Q,X);let Y=g(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||K0(X),$=g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||K0(X);return{type:"array",maxItems:125,items:{type:"array",items:[Y,$],minItems:2,maxItems:2}}}function zG(Q){let X=Q.values,$=Object.keys(Q.values).filter((J)=>{return typeof X[X[J]]!=="number"}).map((J)=>X[J]),W=Array.from(new Set($.map((J)=>typeof J)));return{type:W.length===1?W[0]==="string"?"string":"number":["string","number"],enum:$}}function KG(Q){return Q.target==="openAi"?void 0:{not:K0({...Q,currentPath:[...Q.currentPath,"not"]})}}function VG(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UG(Q,X){if(X.target==="openApi3")return qG(Q,X);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every(($)=>($._def.typeName in t4)&&(!$._def.checks||!$._def.checks.length))){let $=Y.reduce((W,J)=>{let G=t4[J._def.typeName];return G&&!W.includes(G)?[...W,G]:W},[]);return{type:$.length>1?$:$[0]}}else if(Y.every(($)=>$._def.typeName==="ZodLiteral"&&!$.description)){let $=Y.reduce((W,J)=>{let G=typeof J._def.value;switch(G){case"string":case"number":case"boolean":return[...W,G];case"bigint":return[...W,"integer"];case"object":if(J._def.value===null)return[...W,"null"];case"symbol":case"undefined":case"function":default:return W}},[]);if($.length===Y.length){let W=$.filter((J,G,H)=>H.indexOf(J)===G);return{type:W.length>1?W:W[0],enum:Y.reduce((J,G)=>{return J.includes(G._def.value)?J:[...J,G._def.value]},[])}}}else if(Y.every(($)=>$._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce(($,W)=>[...$,...W._def.values.filter((J)=>!$.includes(J))],[])};return qG(Q,X)}var qG=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map(($,W)=>g($._def,{...X,currentPath:[...X.currentPath,"anyOf",`${W}`]})).filter(($)=>!!$&&(!X.strictUnions||typeof $==="object"&&Object.keys($).length>0));return Y.length?{anyOf:Y}:void 0};function LG(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:t4[Q.innerType._def.typeName],nullable:!0};return{type:[t4[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let $=g(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if($&&"$ref"in $)return{allOf:[$],nullable:!0};return $&&{...$,nullable:!0}}let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function FG(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let $ of Q.checks)switch($.kind){case"int":Y.type="integer",K$(Y,"type",$.message,X);break;case"min":if(X.target==="jsonSchema7")if($.inclusive)o(Y,"minimum",$.value,$.message,X);else o(Y,"exclusiveMinimum",$.value,$.message,X);else{if(!$.inclusive)Y.exclusiveMinimum=!0;o(Y,"minimum",$.value,$.message,X)}break;case"max":if(X.target==="jsonSchema7")if($.inclusive)o(Y,"maximum",$.value,$.message,X);else o(Y,"exclusiveMaximum",$.value,$.message,X);else{if(!$.inclusive)Y.exclusiveMaximum=!0;o(Y,"maximum",$.value,$.message,X)}break;case"multipleOf":o(Y,"multipleOf",$.value,$.message,X);break}return Y}function NG(Q,X){let Y=X.target==="openAi",$={type:"object",properties:{}},W=[],J=Q.shape();for(let H in J){let B=J[H];if(B===void 0||B._def===void 0)continue;let z=LO(B);if(z&&Y){if(B._def.typeName==="ZodOptional")B=B._def.innerType;if(!B.isNullable())B=B.nullable();z=!1}let K=g(B._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(K===void 0)continue;if($.properties[H]=K,!z)W.push(H)}if(W.length)$.required=W;let G=UO(Q,X);if(G!==void 0)$.additionalProperties=G;return $}function UO(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return g(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function LO(Q){try{return Q.isOptional()}catch{return!0}}var OG=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return g(Q.innerType._def,X);let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:K0(X)},Y]}:K0(X)};var DG=(Q,X)=>{if(X.pipeStrategy==="input")return g(Q.in._def,X);else if(X.pipeStrategy==="output")return g(Q.out._def,X);let Y=g(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),$=g(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,$].filter((W)=>W!==void 0)}};function wG(Q,X){return g(Q.type._def,X)}function MG(Q,X){let $={type:"array",uniqueItems:!0,items:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)o($,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)o($,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return $}function AG(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,$)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${$}`]})).reduce((Y,$)=>$===void 0?Y:[...Y,$],[]),additionalItems:g(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,$)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${$}`]})).reduce((Y,$)=>$===void 0?Y:[...Y,$],[])}}function jG(Q){return{not:K0(Q)}}function RG(Q){return K0(Q)}var IG=(Q,X)=>{return g(Q.innerType._def,X)};var bG=(Q,X,Y)=>{switch(X){case A.ZodString:return y8(Q,Y);case A.ZodNumber:return FG(Q,Y);case A.ZodObject:return NG(Q,Y);case A.ZodBigInt:return eJ(Q,Y);case A.ZodBoolean:return QG();case A.ZodDate:return V$(Q,Y);case A.ZodUndefined:return jG(Y);case A.ZodNull:return VG(Y);case A.ZodArray:return sJ(Q,Y);case A.ZodUnion:case A.ZodDiscriminatedUnion:return UG(Q,Y);case A.ZodIntersection:return JG(Q,Y);case A.ZodTuple:return AG(Q,Y);case A.ZodRecord:return g8(Q,Y);case A.ZodLiteral:return GG(Q,Y);case A.ZodEnum:return WG(Q);case A.ZodNativeEnum:return zG(Q);case A.ZodNullable:return LG(Q,Y);case A.ZodOptional:return OG(Q,Y);case A.ZodMap:return BG(Q,Y);case A.ZodSet:return MG(Q,Y);case A.ZodLazy:return()=>Q.getter()._def;case A.ZodPromise:return wG(Q,Y);case A.ZodNaN:case A.ZodNever:return KG(Y);case A.ZodEffects:return $G(Q,Y);case A.ZodAny:return K0(Y);case A.ZodUnknown:return RG(Y);case A.ZodDefault:return YG(Q,Y);case A.ZodBranded:return x8(Q,Y);case A.ZodReadonly:return IG(Q,Y);case A.ZodCatch:return XG(Q,Y);case A.ZodPipeline:return DG(Q,Y);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(($)=>{return})(X)}};function g(Q,X,Y=!1){let $=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,$,Y);if(H!==rJ)return H}if($&&!Y){let H=FO($,X);if(H!==void 0)return H}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let J=bG(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)NO(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return W.jsonSchema=G,H}return W.jsonSchema=G,G}var FO=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:T8(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,$)=>X.currentPath[$]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),K0(X);return X.$refStrategy==="seen"?K0(X):void 0}}},NO=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var L$=(Q,X)=>{let Y=aJ(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((B,[z,K])=>({...B,[z]:g(K._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,z]},!0)??K0(Y)}),{}):void 0,W=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,J=g(Q._def,W===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,W]},!1)??K0(Y),G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)J.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!$)$={};if(!$[Y.openAiAnyTypeName])$[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let H=W===void 0?$?{...J,[Y.definitionPath]:$}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,W].join("/"),[Y.definitionPath]:{...$,[W]:J}};if(Y.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function OO(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function F$(Q,X){if(d0(Q))return gY(Q,{target:OO(X?.target),io:X?.pipeStrategy??"input"});return L$(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function N$(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=K8(Y);if(typeof $!=="string")throw Error("Schema method literal must be a string");return $}function O$(Q,X){let Y=h1(Q,X);if(!Y.success)throw Y.error;return Y.data}var DO=60000;class D${constructor(Q){if(this._options=Q,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(O8,(X)=>{this._oncancel(X)}),this.setNotificationHandler(w8,(X)=>{this._onprogress(X)}),this.setRequestHandler(D8,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(M8,async(X,Y)=>{let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return{...$}}),this.setRequestHandler(j8,async(X,Y)=>{let $=async()=>{let W=X.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue(W,Y.sessionId)){if(G.type==="response"||G.type==="error"){let H=G.message,B=H.id,z=this._requestResolvers.get(B);if(z)if(this._requestResolvers.delete(B),G.type==="response")z(H);else{let K=H,q=new S(K.error.code,K.error.message,K.error.data);z(q)}else{let K=G.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${B}`))}continue}await this._transport?.send(G.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask(W,Y.sessionId);if(!J)throw new S(k.InvalidParams,`Task not found: ${W}`);if(!l1(J.status))return await this._waitForTaskUpdate(W,Y.signal),await $();if(l1(J.status)){let G=await this._taskStore.getTaskResult(W,Y.sessionId);return this._clearTaskQueue(W),{...G,_meta:{...G._meta,[u1]:{taskId:W}}}}return await $()};return await $()}),this.setRequestHandler(R8,async(X,Y)=>{try{let{tasks:$,nextCursor:W}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:$,nextCursor:W,_meta:{}}}catch($){throw new S(k.InvalidParams,`Failed to list tasks: ${$ instanceof Error?$.message:String($)}`)}}),this.setRequestHandler(b8,async(X,Y)=>{try{let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new S(k.InvalidParams,`Task not found: ${X.params.taskId}`);if(l1($.status))throw new S(k.InvalidParams,`Cannot cancel task in terminal status: ${$.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new S(k.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...W}}catch($){if($ instanceof S)throw $;throw new S(k.InvalidRequest,`Failed to cancel task: ${$ instanceof Error?$.message:String($)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,$,W=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout($,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:W,onTimeout:$})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),S.fromError(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=(W)=>{Y?.(W),this._onerror(W)};let $=this._transport?.onmessage;this._transport.onmessage=(W,J)=>{if($?.(W,J),l4(W)||gJ(W))this._onresponse(W);else if(tY(W))this._onrequest(W,J);else if(yJ(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Y of this._requestHandlerAbortControllers.values())Y.abort();this._requestHandlerAbortControllers.clear();let X=S.fromError(k.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,$=this._transport,W=Q.params?._meta?.[u1]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:k.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:z,timestamp:Date.now()},$?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else $?.send(z).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let G=vJ(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,$?.sessionId):void 0,B={signal:J.signal,sessionId:$?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{if(J.signal.aborted)return;let K={relatedRequestId:Q.id};if(W)K.relatedTask={taskId:W};await this.notification(z,K)},sendRequest:async(z,K,q)=>{if(J.signal.aborted)throw new S(k.ConnectionClosed,"Request was cancelled");let U={...q,relatedRequestId:Q.id};if(W&&!U.relatedTask)U.relatedTask={taskId:W};let V=U.relatedTask?.taskId??W;if(V&&H)await H.updateTaskStatus(V,"input_required");return await this.request(z,K,U)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:W,taskStore:H,taskRequestedTtl:G?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,B)).then(async(z)=>{if(J.signal.aborted)return;let K={result:z,jsonrpc:"2.0",id:Q.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:K,timestamp:Date.now()},$?.sessionId);else await $?.send(K)},async(z)=>{if(J.signal.aborted)return;let K={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:k.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:K,timestamp:Date.now()},$?.sessionId);else await $?.send(K)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,$=Number(X),W=this._progressHandlers.get($);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get($),G=this._timeoutInfo.get($);if(G&&J&&G.resetTimeoutOnProgress)try{this._resetTimeout($)}catch(H){this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),J(H);return}W(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),l4(Q))Y(Q);else{let J=new S(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let $=this._responseHandlers.get(X);if($===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let W=!1;if(l4(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let G=J.task;if(typeof G.taskId==="string")W=!0,this._taskProgressTokens.set(G.taskId,X)}}if(!W)this._progressHandlers.delete(X);if(l4(Q))$(Q);else{let J=S.fromError(Q.error.code,Q.error.message,Q.error.data);$(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:$}=Y??{};if(!$){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}return}let W;try{let J=await this.request(Q,p6,Y);if(J.task)W=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new S(k.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:W},Y);if(yield{type:"taskStatus",task:G},l1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},X,Y)};else if(G.status==="failed")yield{type:"error",error:new S(k.InternalError,`Task ${W} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new S(k.InternalError,`Task ${W} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},X,Y)};return}let H=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,H)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof S?J:new S(k.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J,task:G,relatedTask:H}=Y??{};return new Promise((B,z)=>{let K=(D)=>{z(D)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),G)this.assertTaskCapability(Q.method)}catch(D){K(D);return}Y?.signal?.throwIfAborted();let q=this._requestMessageId++,U={...Q,jsonrpc:"2.0",id:q};if(Y?.onprogress)this._progressHandlers.set(q,Y.onprogress),U.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:q}};if(G)U.params={...U.params,task:G};if(H)U.params={...U.params,_meta:{...U.params?._meta||{},[u1]:H}};let V=(D)=>{this._responseHandlers.delete(q),this._progressHandlers.delete(q),this._cleanupTimeout(q),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:q,reason:String(D)}},{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let j=D instanceof S?D:new S(k.RequestTimeout,String(D));z(j)};this._responseHandlers.set(q,(D)=>{if(Y?.signal?.aborted)return;if(D instanceof Error)return z(D);try{let j=h1(X,D.result);if(!j.success)z(j.error);else B(j.data)}catch(j){z(j)}}),Y?.signal?.addEventListener("abort",()=>{V(Y?.signal?.reason)});let L=Y?.timeout??DO,F=()=>V(S.fromError(k.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(q,L,Y?.maxTotalTimeout,F,Y?.resetTimeoutOnProgress??!1);let w=H?.taskId;if(w){let D=(j)=>{let I=this._responseHandlers.get(q);if(I)I(j);else this._onerror(Error(`Response handler missing for side-channeled request ${q}`))};this._requestResolvers.set(q,D),this._enqueueTaskMessage(w,{type:"request",message:U,timestamp:Date.now()}).catch((j)=>{this._cleanupTimeout(q),z(j)})}else this._transport.send(U,{relatedRequestId:$,resumptionToken:W,onresumptiontoken:J}).catch((D)=>{this._cleanupTimeout(q),z(D)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},A8,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},I8,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},fJ,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let G={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[u1]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[u1]:X.relatedTask}}};this._transport?.send(G,X).catch((H)=>this._onerror(H))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[u1]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=N$(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,($,W)=>{let J=O$(Q,$);return Promise.resolve(X(J,W))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=N$(Q);this._notificationHandlers.set(Y,($)=>{let W=O$(Q,$);return Promise.resolve(X(W))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let $=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,$)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let $ of Y)if($.type==="request"&&tY($.message)){let W=$.message.id,J=this._requestResolvers.get(W);if(J)J(new S(k.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let $=await this._taskStore?.getTask(Q);if($?.pollInterval)Y=$.pollInterval}catch{}return new Promise(($,W)=>{if(X.aborted){W(new S(k.InvalidRequest,"Request cancelled"));return}let J=setTimeout($,Y);X.addEventListener("abort",()=>{clearTimeout(J),W(new S(k.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async($)=>{if(!Q)throw Error("No request provided");return await Y.createTask($,Q.id,{method:Q.method,params:Q.params},X)},getTask:async($)=>{let W=await Y.getTask($,X);if(!W)throw new S(k.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async($,W,J)=>{await Y.storeTaskResult($,W,J,X);let G=await Y.getTask($,X);if(G){let H=i4.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),l1(G.status))this._cleanupTaskProgressHandler($)}},getTaskResult:($)=>{return Y.getTaskResult($,X)},updateTaskStatus:async($,W,J)=>{let G=await Y.getTask($,X);if(!G)throw new S(k.InvalidParams,`Task "${$}" not found - it may have been cleaned up`);if(l1(G.status))throw new S(k.InvalidParams,`Cannot update task "${$}" from terminal status "${G.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus($,W,J,X);let H=await Y.getTask($,X);if(H){let B=i4.parse({method:"notifications/tasks/status",params:H});if(await this.notification(B),l1(H.status))this._cleanupTaskProgressHandler($)}},listTasks:($)=>{return Y.listTasks($,X)}}}}function EG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function PG(Q,X){let Y={...Q};for(let $ in X){let W=$,J=X[W];if(J===void 0)continue;let G=Y[W];if(EG(G)&&EG(J))Y[W]={...G,...J};else Y[W]=J}return Y}var KK=v7(V7(),1),VK=v7(zK(),1);function Eb(){let Q=new KK.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return VK.default(Q),Q}class A7{constructor(Q){this._ajv=Q??Eb()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class j7{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}createMessageStream(Q,X){let Y=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!Y?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let $=Q.messages[Q.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],J=W.some((z)=>z.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=G?Array.isArray(G.content)?G.content:[G.content]:[],B=H.some((z)=>z.type==="tool_use");if(J){if(W.some((z)=>z.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!B)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(B){let z=new Set(H.filter((q)=>q.type==="tool_use").map((q)=>q.id)),K=new Set(W.filter((q)=>q.type==="tool_result").map((q)=>q.toolUseId));if(z.size!==K.size||![...z].every((q)=>K.has(q)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},r4,X)}elicitInputStream(Q,X){let Y=this._server.getClientCapabilities(),$=Q.mode??"form";switch($){case"url":{if(!Y?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Y?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let W=$==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:W},n6,X)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function qK(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function UK(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class R7 extends D${constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(o4.options.map((Y,$)=>[Y,$])),this.isMessageIgnored=(Y,$)=>{let W=this._loggingLevels.get($);return W?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get(W):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new A7,this.setRequestHandler(eY,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(Q$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(H$,async(Y,$)=>{let W=$.sessionId||$.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,G=o4.safeParse(J);if(G.success)this._loggingLevels.set(W,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new j7(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=PG(this._capabilities,Q)}setRequestHandler(Q,X){let $=f1(Q)?.method;if(!$)throw Error("Schema is missing a method literal");let W;if(d0($)){let G=$;W=G._zod?.def?.value??G.value}else{let G=$;W=G._def?.value??G.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="tools/call"){let G=async(H,B)=>{let z=h1(i6,H);if(!z.success){let V=z.error instanceof Error?z.error.message:String(z.error);throw new S(k.InvalidParams,`Invalid tools/call request: ${V}`)}let{params:K}=z.data,q=await Promise.resolve(X(H,B));if(K.task){let V=h1(p6,q);if(!V.success){let L=V.error instanceof Error?V.error.message:String(V.error);throw new S(k.InvalidParams,`Invalid task creation result: ${L}`)}return V.data}let U=h1(k8,q);if(!U.success){let V=U.error instanceof Error?U.error.message:String(U.error);throw new S(k.InvalidParams,`Invalid tools/call result: ${V}`)}return U.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){UK(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;qK(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:CJ.includes(X)?X:oY,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"},N8)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],$=Array.isArray(Y.content)?Y.content:[Y.content],W=$.some((B)=>B.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,G=J?Array.isArray(J.content)?J.content:[J.content]:[],H=G.some((B)=>B.type==="tool_use");if(W){if($.some((B)=>B.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let B=new Set(G.filter((K)=>K.type==="tool_use").map((K)=>K.id)),z=new Set($.filter((K)=>K.type==="tool_result").map((K)=>K.toolUseId));if(B.size!==z.size||![...B].every((K)=>z.has(K)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},B$,X);return this.request({method:"sampling/createMessage",params:Q},r4,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let $=Q;return this.request({method:"elicitation/create",params:$},n6,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let $=Q.mode==="form"?Q:{...Q,mode:"form"},W=await this.request({method:"elicitation/create",params:$},n6,X);if(W.action==="accept"&&W.content&&$.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator($.requestedSchema)(W.content);if(!G.valid)throw new S(k.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(J){if(J instanceof S)throw J;throw new S(k.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return W}}}createElicitationCompletionNotifier(Q,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},z$,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var FK=Symbol.for("mcp.completable");function I7(Q){return!!Q&&typeof Q==="object"&&FK in Q}function NK(Q){return Q[FK]?.complete}var LK;(function(Q){Q.Completable="McpCompletable"})(LK||(LK={}));var Pb=/^[A-Za-z0-9._-]{1,128}$/;function Zb(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Pb.test(Q)){let Y=Q.split("").filter(($)=>!/[A-Za-z0-9._-]/.test($)).filter(($,W,J)=>J.indexOf($)===W);return X.push(`Tool name contains invalid characters: ${Y.map(($)=>`"${$}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function Sb(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let Y of X)console.warn(` - ${Y}`);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 b7(Q){let X=Zb(Q);return Sb(Q,X.warnings),X.isValid}class E7{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,Y){let $={taskSupport:"required",...X.execution};if($.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,$,X._meta,Y)}}class Z7{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new R7(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new E7(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(_8)),this.server.assertCanSetRequestHandler(r1(i6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_8,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let $=m6(X.inputSchema);return $?F$($,{strictUnions:!0,pipeStrategy:"input"}):Cb})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let $=m6(X.outputSchema);if($)Y.outputSchema=F$($,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(i6,async(Q,X)=>{try{let Y=this._registeredTools[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Tool ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Tool ${Q.params.name} disabled`);let $=!!Q.params.task,W=Y.execution?.taskSupport,J="createTask"in Y.handler;if((W==="required"||W==="optional")&&!J)throw new S(k.InternalError,`Tool ${Q.params.name} has taskSupport '${W}' but was not registered with registerToolTask`);if(W==="required"&&!$)throw new S(k.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if(W==="optional"&&!$&&J)return await this.handleAutomaticTaskPolling(Y,Q,X);let G=await this.validateToolInput(Y,Q.params.arguments,Q.params.name),H=await this.executeToolHandler(Y,G,X);if($)return H;return await this.validateToolOutput(Y,H,Q.params.name),H}catch(Y){if(Y instanceof S){if(Y.code===k.UrlElicitationRequired)throw Y}return this.createToolError(Y instanceof Error?Y.message:String(Y))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,Y){if(!Q.inputSchema)return;let W=m6(Q.inputSchema)??Q.inputSchema,J=await B8(W,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=z8(G);throw new S(k.InvalidParams,`Input validation error: Invalid arguments for tool ${Y}: ${H}`)}return J.data}async validateToolOutput(Q,X,Y){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new S(k.InvalidParams,`Output validation error: Tool ${Y} has an output schema but no structured content was provided`);let $=m6(Q.outputSchema),W=await B8($,X.structuredContent);if(!W.success){let J="error"in W?W.error:"Unknown error",G=z8(J);throw new S(k.InvalidParams,`Output validation error: Invalid structured content for tool ${Y}: ${G}`)}}async executeToolHandler(Q,X,Y){let $=Q.handler;if("createTask"in $){if(!Y.taskStore)throw Error("No task store provided.");let J={...Y,taskStore:Y.taskStore};if(Q.inputSchema)return await Promise.resolve($.createTask(X,J));else return await Promise.resolve($.createTask(J))}if(Q.inputSchema)return await Promise.resolve($(X,Y));else return await Promise.resolve($(Y))}async handleAutomaticTaskPolling(Q,X,Y){if(!Y.taskStore)throw Error("No task store provided for task-capable tool.");let $=await this.validateToolInput(Q,X.params.arguments,X.params.name),W=Q.handler,J={...Y,taskStore:Y.taskStore},G=$?await Promise.resolve(W.createTask($,J)):await Promise.resolve(W.createTask(J)),H=G.task.taskId,B=G.task,z=B.pollInterval??5000;while(B.status!=="completed"&&B.status!=="failed"&&B.status!=="cancelled"){await new Promise((q)=>setTimeout(q,z));let K=await Y.taskStore.getTask(H);if(!K)throw new S(k.InternalError,`Task ${H} not found during polling`);B=K}return await Y.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(r1(v8)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(v8,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return dJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return iJ(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new S(k.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let Y=this._registeredPrompts[X.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${X.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${X.name} disabled`);if(!Y.argsSchema)return M9;let W=f1(Y.argsSchema)?.[Q.params.argument.name];if(!I7(W))return M9;let J=NK(W);if(!J)return M9;let G=await J(Q.params.argument.value,Q.params.context);return DK(G)}async handleResourceCompletion(Q,X){let Y=Object.values(this._registeredResourceTemplates).find((J)=>J.resourceTemplate.uriTemplate.toString()===X.uri);if(!Y){if(this._registeredResources[X.uri])return M9;throw new S(k.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let $=Y.resourceTemplate.completeCallback(Q.params.argument.name);if(!$)return M9;let W=await $(Q.params.argument.value,Q.params.context);return DK(W)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(E8)),this.server.assertCanSetRequestHandler(r1(P8)),this.server.assertCanSetRequestHandler(r1(Z8)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(E8,async(Q,X)=>{let Y=Object.entries(this._registeredResources).filter(([W,J])=>J.enabled).map(([W,J])=>({uri:W,name:J.name,...J.metadata})),$=[];for(let W of Object.values(this._registeredResourceTemplates)){if(!W.resourceTemplate.listCallback)continue;let J=await W.resourceTemplate.listCallback(X);for(let G of J.resources)$.push({...W.metadata,...G})}return{resources:[...Y,...$]}}),this.server.setRequestHandler(P8,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(Z8,async(Q,X)=>{let Y=new URL(Q.params.uri),$=this._registeredResources[Y.toString()];if($){if(!$.enabled)throw new S(k.InvalidParams,`Resource ${Y} disabled`);return $.readCallback(Y,X)}for(let W of Object.values(this._registeredResourceTemplates)){let J=W.resourceTemplate.uriTemplate.match(Y.toString());if(J)return W.readCallback(Y,J,X)}throw new S(k.InvalidParams,`Resource ${Y} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(S8)),this.server.assertCanSetRequestHandler(r1(C8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S8,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?kb(X.argsSchema):void 0}})})),this.server.setRequestHandler(C8,async(Q,X)=>{let Y=this._registeredPrompts[Q.params.name];if(!Y)throw new S(k.InvalidParams,`Prompt ${Q.params.name} not found`);if(!Y.enabled)throw new S(k.InvalidParams,`Prompt ${Q.params.name} disabled`);if(Y.argsSchema){let $=m6(Y.argsSchema),W=await B8($,Q.params.arguments);if(!W.success){let H="error"in W?W.error:"Unknown error",B=z8(H);throw new S(k.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${B}`)}let J=W.data,G=Y.callback;return await Promise.resolve(G(J,X))}else{let $=Y.callback;return await Promise.resolve($(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...Y){let $;if(typeof Y[0]==="object")$=Y.shift();let W=Y[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let J=this._createRegisteredResource(Q,void 0,X,$,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let J=this._createRegisteredResourceTemplate(Q,void 0,X,$,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}}registerResource(Q,X,Y,$){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let W=this._createRegisteredResource(Q,Y.title,X,Y,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let W=this._createRegisteredResourceTemplate(Q,Y.title,X,Y,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),W}}_createRegisteredResource(Q,X,Y,$,W){let J={name:Q,title:X,metadata:$,readCallback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({uri:null}),update:(G)=>{if(typeof G.uri<"u"&&G.uri!==Y){if(delete this._registeredResources[Y],G.uri)this._registeredResources[G.uri]=J}if(typeof G.name<"u")J.name=G.name;if(typeof G.title<"u")J.title=G.title;if(typeof G.metadata<"u")J.metadata=G.metadata;if(typeof G.callback<"u")J.readCallback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendResourceListChanged()}};return this._registeredResources[Y]=J,J}_createRegisteredResourceTemplate(Q,X,Y,$,W){let J={resourceTemplate:Y,title:X,metadata:$,readCallback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(B)=>{if(typeof B.name<"u"&&B.name!==Q){if(delete this._registeredResourceTemplates[Q],B.name)this._registeredResourceTemplates[B.name]=J}if(typeof B.title<"u")J.title=B.title;if(typeof B.template<"u")J.resourceTemplate=B.template;if(typeof B.metadata<"u")J.metadata=B.metadata;if(typeof B.callback<"u")J.readCallback=B.callback;if(typeof B.enabled<"u")J.enabled=B.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=J;let G=Y.uriTemplate.variableNames;if(Array.isArray(G)&&G.some((B)=>!!Y.completeCallback(B)))this.setCompletionRequestHandler();return J}_createRegisteredPrompt(Q,X,Y,$,W){let J={title:X,description:Y,argsSchema:$===void 0?void 0:q6($),callback:W,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(G)=>{if(typeof G.name<"u"&&G.name!==Q){if(delete this._registeredPrompts[Q],G.name)this._registeredPrompts[G.name]=J}if(typeof G.title<"u")J.title=G.title;if(typeof G.description<"u")J.description=G.description;if(typeof G.argsSchema<"u")J.argsSchema=q6(G.argsSchema);if(typeof G.callback<"u")J.callback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=J,$){if(Object.values($).some((H)=>{let B=H instanceof p0?H._def?.innerType:H;return I7(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,$,W,J,G,H,B){b7(Q);let z={title:X,description:Y,inputSchema:OK($),outputSchema:OK(W),annotations:J,execution:G,_meta:H,handler:B,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(K)=>{if(typeof K.name<"u"&&K.name!==Q){if(typeof K.name==="string")b7(K.name);if(delete this._registeredTools[Q],K.name)this._registeredTools[K.name]=z}if(typeof K.title<"u")z.title=K.title;if(typeof K.description<"u")z.description=K.description;if(typeof K.paramsSchema<"u")z.inputSchema=q6(K.paramsSchema);if(typeof K.outputSchema<"u")z.outputSchema=q6(K.outputSchema);if(typeof K.callback<"u")z.handler=K.callback;if(typeof K.annotations<"u")z.annotations=K.annotations;if(typeof K._meta<"u")z._meta=K._meta;if(typeof K.enabled<"u")z.enabled=K.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=z,this.setToolRequestHandlers(),this.sendToolListChanged(),z}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let Y,$,W,J;if(typeof X[0]==="string")Y=X.shift();if(X.length>1){let H=X[0];if(P7(H)){if($=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!P7(X[0]))J=X.shift()}else if(typeof H==="object"&&H!==null)J=X.shift()}let G=X[0];return this._createRegisteredTool(Q,void 0,Y,$,W,J,{taskSupport:"forbidden"},void 0,G)}registerTool(Q,X,Y){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:$,description:W,inputSchema:J,outputSchema:G,annotations:H,_meta:B}=X;return this._createRegisteredTool(Q,$,W,J,G,H,{taskSupport:"forbidden"},B,Y)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let Y;if(typeof X[0]==="string")Y=X.shift();let $;if(X.length>1)$=X.shift();let W=X[0],J=this._createRegisteredPrompt(Q,void 0,Y,$,W);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}registerPrompt(Q,X,Y){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:$,description:W,argsSchema:J}=X,G=this._createRegisteredPrompt(Q,$,W,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Cb={type:"object",properties:{}};function wK(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function _b(Q){return"_def"in Q||"_zod"in Q||wK(Q)}function P7(Q){if(typeof Q!=="object"||Q===null)return!1;if(_b(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(wK)}function OK(Q){if(!Q)return;if(P7(Q))return q6(Q);return Q}function kb(Q){let X=f1(Q);if(!X)return[];return Object.entries(X).map(([Y,$])=>{let W=HJ($),J=BJ($);return{name:Y,description:W,required:!J}})}function r1(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=K8(Y);if(typeof $==="string")return $;throw Error("Schema method literal must be a string")}function DK(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var M9={completion:{values:[],hasMore:!1}};function vb(Q,X,Y,$,W){return{name:Q,description:X,inputSchema:Y,handler:$,annotations:W?.annotations}}function Tb(Q){let X=new Z7({name:Q.name,version:Q.version??"1.0.0"},{capabilities:{tools:Q.tools?{}:void 0}});if(Q.tools)Q.tools.forEach((Y)=>{X.registerTool(Y.name,{description:Y.description,inputSchema:Y.inputSchema,annotations:Y.annotations},Y.handler)});return{type:"sdk",name:Q.name,instance:X}}function Ay({prompt:Q,options:X}){let{systemPrompt:Y,settingSources:$,sandbox:W,...J}=X??{},G,H;if(Y===void 0)G="";else if(typeof Y==="string")G=Y;else if(Y.type==="preset")H=Y.append;let B=J.pathToClaudeCodeExecutable;if(!B){let A6=xb(import.meta.url),j6=MK(A6,"..");B=MK(j6,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.62";let{abortController:z=R6(),additionalDirectories:K=[],agent:q,agents:U,allowedTools:V=[],betas:L,canUseTool:F,continue:w,cwd:D,debug:j,debugFile:I,disallowedTools:T=[],tools:v,env:N0,executable:O0=_6()?"bun":"node",executableArgs:c0=[],extraArgs:t1={},fallbackModel:q1,enableFileCheckpointing:a1,forkSession:P1,hooks:s1,includePartialMessages:u,persistSession:AQ,thinking:e1,effort:J4,maxThinkingTokens:Q6,maxTurns:A9,maxBudgetUsd:j9,mcpServers:b0,model:Z1,outputFormat:w6,permissionMode:AK="default",allowDangerouslySkipPermissions:jK=!1,permissionPromptToolName:RK,plugins:IK,resume:bK,resumeSessionAt:EK,sessionId:PK,stderr:ZK,strictMcpConfig:SK}=J,S7=w6?.type==="json_schema"?w6.schema:void 0,M6=N0;if(!M6)M6={...process.env};if(!M6.CLAUDE_CODE_ENTRYPOINT)M6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(a1)M6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!B)throw Error("pathToClaudeCodeExecutable is required");let jQ={},C7=new Map;if(b0)for(let[A6,j6]of Object.entries(b0))if(j6.type==="sdk"&&"instance"in j6)C7.set(A6,j6.instance),jQ[A6]={type:"sdk",name:A6};else jQ[A6]=j6;let CK=typeof Q==="string",G4;if(e1)switch(e1.type){case"adaptive":G4={type:"adaptive"};break;case"enabled":G4={type:"enabled",budgetTokens:e1.budgetTokens};break;case"disabled":G4={type:"disabled"};break}else if(Q6!==void 0)G4=Q6===0?{type:"disabled"}:{type:"enabled",budgetTokens:Q6};let _7=new B4({abortController:z,additionalDirectories:K,agent:q,betas:L,cwd:D,debug:j,debugFile:I,executable:O0,executableArgs:c0,extraArgs:t1,pathToClaudeCodeExecutable:B,env:M6,forkSession:P1,stderr:ZK,thinkingConfig:G4,effort:J4,maxTurns:A9,maxBudgetUsd:j9,model:Z1,fallbackModel:q1,jsonSchema:S7,permissionMode:AK,allowDangerouslySkipPermissions:jK,permissionPromptToolName:RK,continueConversation:w,resume:bK,resumeSessionAt:EK,sessionId:PK,settingSources:$??[],allowedTools:V,disallowedTools:T,tools:v,mcpServers:jQ,strictMcpConfig:SK,canUseTool:!!F,hooks:!!s1,includePartialMessages:u,persistSession:AQ,plugins:IK,sandbox:W,spawnClaudeCodeProcess:J.spawnClaudeCodeProcess}),_K={systemPrompt:G,appendSystemPrompt:H,agents:U,promptSuggestions:J.promptSuggestions},k7=new K4(_7,CK,F,s1,z,C7,S7,_K);if(typeof Q==="string")_7.write(Z0({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+`
60
60
  `);else k7.streamInput(Q);return k7}function jy(Q){return SQ(Q)}function Ry(Q,X){return C5(Q,X)}async function Iy(Q,X){let $=[];try{const Y=X0($,SQ(X),1);await Y.send(Q);for await(let B of Y.stream())if(B.type==="result")return B;throw Error("Session ended without result message")}catch(W){var J=W,G=1}finally{var H=Y0($,J,G);H&&await H}}async function by(Q,X){return y5(Q,X)}async function Ey(Q){return h5(Q)}export{Ry as unstable_v2_resumeSession,Iy as unstable_v2_prompt,jy as unstable_v2_createSession,vb as tool,Ay as query,Ey as listSessions,by as getSessionMessages,Tb as createSdkMcpServer,Zq as HOOK_EVENTS,Sq as EXIT_REASONS,F1 as AbortError};