@anthropic-ai/claude-agent-sdk 0.2.56 → 0.2.58

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.56",
3
- "buildDate": "2026-02-25T05:57:11Z",
2
+ "version": "2.1.58",
3
+ "buildDate": "2026-02-25T19:23:36Z",
4
4
  "platforms": {
5
5
  "darwin-arm64": {
6
6
  "binary": "claude",
7
- "checksum": "c79534202fd33f11f1111ee0a0fa10143187a345e095cb2dd8b6186d8dcc6f5f",
7
+ "checksum": "182c20c6080d042e4e08a6b2a2ce8258c1a50e53c01d36ddf20a82b4693395ea",
8
8
  "size": 186526736
9
9
  },
10
10
  "darwin-x64": {
11
11
  "binary": "claude",
12
- "checksum": "80bccdd96af123dd1cc7fb9b6e32a56c2965dc374a5084fb5283294609b1aff3",
12
+ "checksum": "fb2ccc6872d498fc571f302059d51aec7c89b0df4d21d247a9a249c1a3a835dc",
13
13
  "size": 191680848
14
14
  },
15
15
  "linux-arm64": {
16
16
  "binary": "claude",
17
- "checksum": "566ce5c41ac7ecbb259d46fe5d58d45c03e70323a0ff3f05a0ddc358d81f73a1",
18
- "size": 224286259
17
+ "checksum": "5edd4b6be6b9e9c00e5805f022ee924a98fdcf1bf0c04635a429d2666eccbc3f",
18
+ "size": 224288899
19
19
  },
20
20
  "linux-x64": {
21
21
  "binary": "claude",
22
- "checksum": "e139d71f9dec4d86308341b16d00c24441c789d0156852364a4c7dcf3f2e9b3e",
23
- "size": 227282768
22
+ "checksum": "10f68e45b5ff4a80ae21e6d7a95dfe673ab3391313358ccd94e827f379f6aaa0",
23
+ "size": 227285328
24
24
  },
25
25
  "linux-arm64-musl": {
26
26
  "binary": "claude",
27
- "checksum": "7ae937f8d08d31d437ef7ebffd566eb83fbf8e3b48d8a8a500ddc736bcbff9ca",
28
- "size": 216683219
27
+ "checksum": "7f0986bf7db5412dd72cd45f623a417ba7a663922d8c868044bd155a55eb3f8c",
28
+ "size": 216685859
29
29
  },
30
30
  "linux-x64-musl": {
31
31
  "binary": "claude",
32
- "checksum": "fb1d2a0be8ec24f1347a9e8ee8ad0b4c463bb00a75edbfb74c223df8f02cc1bb",
33
- "size": 218980008
32
+ "checksum": "7bd4ba6b50c63ab0e39a3db338135a1808e458b37e40ef2afa231747be567139",
33
+ "size": 218982568
34
34
  },
35
35
  "win32-x64": {
36
36
  "binary": "claude.exe",
37
- "checksum": "8a14c6d5f1fe7aa820294542392693f76927b412075d195875f322a803a994bc",
38
- "size": 235482272
37
+ "checksum": "37e012da688493c799d385e9d1aa811661a3be41e837c7d5687d010aaf5c7a35",
38
+ "size": 235484832
39
39
  },
40
40
  "win32-arm64": {
41
41
  "binary": "claude.exe",
42
- "checksum": "ff840bbd157137d33049ee1526cb87681c3b84d3f6f0c3ab686215c2077e0a4f",
43
- "size": 227691680
42
+ "checksum": "17e30cc59a3e2a8913dee20383fe5d119b1a5a1214a1a989331c7bf8fc39e522",
43
+ "size": 227694240
44
44
  }
45
45
  }
46
46
  }
package/manifest.zst.json CHANGED
@@ -1,46 +1,46 @@
1
1
  {
2
- "version": "2.1.56",
3
- "buildDate": "2026-02-25T05:57:12Z",
2
+ "version": "2.1.58",
3
+ "buildDate": "2026-02-25T19:23:37Z",
4
4
  "platforms": {
5
5
  "darwin-arm64": {
6
6
  "binary": "claude.zst",
7
- "checksum": "2ea2ad14a032155f3283067c60dc9486da6a4bcee70288023e6ff1a391b2f4f9",
8
- "size": 39450979
7
+ "checksum": "5d31443008491cfd59b76ce9de3eb5cd30109462972fe41988ac69f6e4461bf1",
8
+ "size": 39450882
9
9
  },
10
10
  "darwin-x64": {
11
11
  "binary": "claude.zst",
12
- "checksum": "cc45fbfa551767561e0635718c8155008cc6a0515d531ba51cfba91479bdad71",
13
- "size": 41642106
12
+ "checksum": "f38d9b97b1ee41be4ee8f07c578ce96e4cc13e4f82e12d862111b74477c5acd6",
13
+ "size": 41631791
14
14
  },
15
15
  "linux-arm64": {
16
16
  "binary": "claude.zst",
17
- "checksum": "126751d0658fb7fe421eed204033b9d351ae0b91596f16140506bf508188716d",
18
- "size": 50151133
17
+ "checksum": "e464198f3906307db2f03ad74695c6d7849115180d18944158c191cdab5c32ee",
18
+ "size": 50149811
19
19
  },
20
20
  "linux-x64": {
21
21
  "binary": "claude.zst",
22
- "checksum": "d685d0651d29ef64dfabc9237da623c7745ed98cba0138753cd7629636daca70",
23
- "size": 50839948
22
+ "checksum": "3ce8f073fb6e5346b190b9c0a22e70aad2f7c4da5c28ebfdf66173e9bd7b6fc9",
23
+ "size": 50863907
24
24
  },
25
25
  "linux-arm64-musl": {
26
26
  "binary": "claude.zst",
27
- "checksum": "79178df25056cc6e960ee9a8efc81726f401552e2db1141d3e5d03b471dfda98",
28
- "size": 48473008
27
+ "checksum": "781a7d389e31c303b1114c44b9f009fe464d01613c4fcde5ab2e2807d6d05666",
28
+ "size": 48466812
29
29
  },
30
30
  "linux-x64-musl": {
31
31
  "binary": "claude.zst",
32
- "checksum": "735254ea51f08e26278f4cd8c175309d834090e9aef8e0646242731968aafd13",
33
- "size": 49083600
32
+ "checksum": "ba083e65cfaf95708272470f1bbe5f75348282a865399ef493688c06ffad1dd5",
33
+ "size": 49097157
34
34
  },
35
35
  "win32-x64": {
36
36
  "binary": "claude.exe.zst",
37
- "checksum": "98c1e8f45e0110c678389352eab24f90135d5bf71fcf0cb87bc83dd29daaf782",
38
- "size": 52779749
37
+ "checksum": "9e0b5ca4dd486be664f8230004b1e85325a56a90afcd6c9f913fb3430ee68b7b",
38
+ "size": 52770528
39
39
  },
40
40
  "win32-arm64": {
41
41
  "binary": "claude.exe.zst",
42
- "checksum": "31fdac2d0ea68a9cecd6083e36a08bd3fb93eeef1e0edf8c4dab413e9e975c43",
43
- "size": 50163491
42
+ "checksum": "dc9c42213bb09c19222cfe79aae0c1e2b62d07d871dd7ec83eb60bd109ef6d72",
43
+ "size": 50149908
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.56",
3
+ "version": "0.2.58",
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.56"
41
+ "claudeCodeVersion": "2.1.58"
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.56
4
+ // Version: 0.2.58
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -55,5 +55,5 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
55
55
  ]))`;continue}else if($[B]==="$"){W+=`($|(?=[\r
56
56
  ]))`;continue}}if(Y.s&&$[B]==="."){W+=G?`${$[B]}\r
57
57
  `:`[${$[B]}\r
58
- ]`;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 x8(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}=T8(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}=v8(Q.keyType._def,X);return{...Y,propertyNames:W}}return Y}function YG(Q,X){if(X.mapStrategy==="record")return x8(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 $G(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 WG(Q){return Q.target==="openAi"?void 0:{not:K0({...Q,currentPath:[...Q.currentPath,"not"]})}}function JG(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function HG(Q,X){if(X.target==="openApi3")return GG(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 GG(Q,X)}var GG=(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 BG(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 zG(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let $ of Q.checks)switch($.kind){case"int":Y.type="integer",J$(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 KG(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=$O(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=YO(Q,X);if(G!==void 0)$.additionalProperties=G;return $}function YO(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 $O(Q){try{return Q.isOptional()}catch{return!0}}var VG=(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 qG=(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 UG(Q,X){return g(Q.type._def,X)}function LG(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 FG(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 NG(Q){return{not:K0(Q)}}function OG(Q){return K0(Q)}var DG=(Q,X)=>{return g(Q.innerType._def,X)};var wG=(Q,X,Y)=>{switch(X){case A.ZodString:return T8(Q,Y);case A.ZodNumber:return zG(Q,Y);case A.ZodObject:return KG(Q,Y);case A.ZodBigInt:return nJ(Q,Y);case A.ZodBoolean:return oJ();case A.ZodDate:return G$(Q,Y);case A.ZodUndefined:return NG(Y);case A.ZodNull:return JG(Y);case A.ZodArray:return iJ(Q,Y);case A.ZodUnion:case A.ZodDiscriminatedUnion:return HG(Q,Y);case A.ZodIntersection:return eJ(Q,Y);case A.ZodTuple:return FG(Q,Y);case A.ZodRecord:return x8(Q,Y);case A.ZodLiteral:return QG(Q,Y);case A.ZodEnum:return sJ(Q);case A.ZodNativeEnum:return $G(Q);case A.ZodNullable:return BG(Q,Y);case A.ZodOptional:return VG(Q,Y);case A.ZodMap:return YG(Q,Y);case A.ZodSet:return LG(Q,Y);case A.ZodLazy:return()=>Q.getter()._def;case A.ZodPromise:return UG(Q,Y);case A.ZodNaN:case A.ZodNever:return WG(Y);case A.ZodEffects:return aJ(Q,Y);case A.ZodAny:return K0(Y);case A.ZodUnknown:return OG(Y);case A.ZodDefault:return tJ(Q,Y);case A.ZodBranded:return v8(Q,Y);case A.ZodReadonly:return DG(Q,Y);case A.ZodCatch:return rJ(Q,Y);case A.ZodPipeline:return qG(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!==cJ)return H}if($&&!Y){let H=WO($,X);if(H!==void 0)return H}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let J=wG(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)JO(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return W.jsonSchema=G,H}return W.jsonSchema=G,G}var WO=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:k8(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}}},JO=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var z$=(Q,X)=>{let Y=dJ(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 GO(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 K$(Q,X){if(d0(Q))return kY(Q,{target:GO(X?.target),io:X?.pipeStrategy??"input"});return z$(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function V$(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=B8(Y);if(typeof $!=="string")throw Error("Schema method literal must be a string");return $}function q$(Q,X){let Y=h1(Q,X);if(!Y.success)throw Y.error;return Y.data}var HO=60000;class U${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(F8,(X)=>{this._oncancel(X)}),this.setNotificationHandler(O8,(X)=>{this._onprogress(X)}),this.setRequestHandler(N8,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(D8,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(M8,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(A8,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(R8,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)||_J(W))this._onresponse(W);else if(dY(W))this._onrequest(W,J);else if(CJ(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=PJ(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,m6,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??HO,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},w8,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},j8,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},vJ,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=V$(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,($,W)=>{let J=q$(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=V$(Q);this._notificationHandlers.set(Y,($)=>{let W=q$(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"&&dY($.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 MG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function AG(Q,X){let Y={...Q};for(let $ in X){let W=$,J=X[W];if(J===void 0)continue;let G=Y[W];if(MG(G)&&MG(J))Y[W]={...G,...J};else Y[W]=J}return Y}var WK=Z7(G7(),1),JK=Z7($K(),1);function Fb(){let Q=new WK.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return JK.default(Q),Q}class N7{constructor(Q){this._ajv=Q??Fb()}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 O7{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},d6,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 GK(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 HK(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 D7 extends U${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 N7,this.setRequestHandler(oY,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(rY,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(Y$,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 O7(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=AG(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(p6,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(m6,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(C8,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){HK(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;GK(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:IJ.includes(X)?X:cY,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"},L8)}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},$$,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:$},d6,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:$},d6,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},W$,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 zK=Symbol.for("mcp.completable");function w7(Q){return!!Q&&typeof Q==="object"&&zK in Q}function KK(Q){return Q[zK]?.complete}var BK;(function(Q){Q.Completable="McpCompletable"})(BK||(BK={}));var Nb=/^[A-Za-z0-9._-]{1,128}$/;function Ob(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(!Nb.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 Db(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 M7(Q){let X=Ob(Q);return Db(Q,X.warnings),X.isValid}class A7{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 R7{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 D7(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new A7(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(S8)),this.server.assertCanSetRequestHandler(r1(p6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(S8,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let $=u6(X.inputSchema);return $?K$($,{strictUnions:!0,pipeStrategy:"input"}):wb})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let $=u6(X.outputSchema);if($)Y.outputSchema=K$($,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(p6,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=u6(Q.inputSchema)??Q.inputSchema,J=await G8(W,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=H8(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 $=u6(Q.outputSchema),W=await G8($,X.structuredContent);if(!W.success){let J="error"in W?W.error:"Unknown error",G=H8(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(_8)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_8,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return fJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return uJ(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(!w7(W))return M9;let J=KK(W);if(!J)return M9;let G=await J(Q.params.argument.value,Q.params.context);return qK(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 qK(W)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(I8)),this.server.assertCanSetRequestHandler(r1(b8)),this.server.assertCanSetRequestHandler(r1(E8)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(I8,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(b8,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(E8,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(P8)),this.server.assertCanSetRequestHandler(r1(Z8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(P8,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?Ab(X.argsSchema):void 0}})})),this.server.setRequestHandler(Z8,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 $=u6(Y.argsSchema),W=await G8($,Q.params.arguments);if(!W.success){let H="error"in W?W.error:"Unknown error",B=H8(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:K6($),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=K6(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 w7(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,$,W,J,G,H,B){M7(Q);let z={title:X,description:Y,inputSchema:VK($),outputSchema:VK(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")M7(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=K6(K.paramsSchema);if(typeof K.outputSchema<"u")z.outputSchema=K6(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(j7(H)){if($=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!j7(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 wb={type:"object",properties:{}};function UK(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function Mb(Q){return"_def"in Q||"_zod"in Q||UK(Q)}function j7(Q){if(typeof Q!=="object"||Q===null)return!1;if(Mb(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(UK)}function VK(Q){if(!Q)return;if(j7(Q))return K6(Q);return Q}function Ab(Q){let X=f1(Q);if(!X)return[];return Object.entries(X).map(([Y,$])=>{let W=XJ($),J=YJ($);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 $=B8(Y);if(typeof $==="string")return $;throw Error("Schema method literal must be a string")}function qK(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var M9={completion:{values:[],hasMore:!1}};function jb(Q,X,Y,$,W){return{name:Q,description:X,inputSchema:Y,handler:$,annotations:W?.annotations}}function Rb(Q){let X=new R7({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 $y({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 w6=Ib(import.meta.url),M6=LK(w6,"..");B=LK(M6,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.56";let{abortController:z=A6(),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=Z6()?"bun":"node",executableArgs:c0=[],extraArgs:t1={},fallbackModel:U1,enableFileCheckpointing:a1,forkSession:Z1,hooks:s1,includePartialMessages:u,persistSession:wQ,thinking:e1,effort:$4,maxThinkingTokens:Q6,maxTurns:A9,maxBudgetUsd:j9,mcpServers:b0,model:S1,outputFormat:O6,permissionMode:FK="default",allowDangerouslySkipPermissions:NK=!1,permissionPromptToolName:OK,plugins:DK,resume:wK,resumeSessionAt:MK,sessionId:AK,stderr:jK,strictMcpConfig:RK}=J,I7=O6?.type==="json_schema"?O6.schema:void 0,D6=N0;if(!D6)D6={...process.env};if(!D6.CLAUDE_CODE_ENTRYPOINT)D6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(a1)D6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!B)throw Error("pathToClaudeCodeExecutable is required");let MQ={},b7=new Map;if(b0)for(let[w6,M6]of Object.entries(b0))if(M6.type==="sdk"&&"instance"in M6)b7.set(w6,M6.instance),MQ[w6]={type:"sdk",name:w6};else MQ[w6]=M6;let IK=typeof Q==="string",W4;if(e1)switch(e1.type){case"adaptive":W4={type:"adaptive"};break;case"enabled":W4={type:"enabled",budgetTokens:e1.budgetTokens};break;case"disabled":W4={type:"disabled"};break}else if(Q6!==void 0)W4=Q6===0?{type:"disabled"}:{type:"enabled",budgetTokens:Q6};let E7=new H4({abortController:z,additionalDirectories:K,agent:q,betas:L,cwd:D,debug:j,debugFile:I,executable:O0,executableArgs:c0,extraArgs:t1,pathToClaudeCodeExecutable:B,env:D6,forkSession:Z1,stderr:jK,thinkingConfig:W4,effort:$4,maxTurns:A9,maxBudgetUsd:j9,model:S1,fallbackModel:U1,jsonSchema:I7,permissionMode:FK,allowDangerouslySkipPermissions:NK,permissionPromptToolName:OK,continueConversation:w,resume:wK,resumeSessionAt:MK,sessionId:AK,settingSources:$??[],allowedTools:V,disallowedTools:T,tools:v,mcpServers:MQ,strictMcpConfig:RK,canUseTool:!!F,hooks:!!s1,includePartialMessages:u,persistSession:wQ,plugins:DK,sandbox:W,spawnClaudeCodeProcess:J.spawnClaudeCodeProcess}),bK={systemPrompt:G,appendSystemPrompt:H,agents:U,promptSuggestions:J.promptSuggestions},P7=new z4(E7,IK,F,s1,z,b7,I7,bK);if(typeof Q==="string")E7.write(Z0({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+`
58
+ ]`;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 x8(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}=T8(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}=v8(Q.keyType._def,X);return{...Y,propertyNames:W}}return Y}function YG(Q,X){if(X.mapStrategy==="record")return x8(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 $G(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 WG(Q){return Q.target==="openAi"?void 0:{not:K0({...Q,currentPath:[...Q.currentPath,"not"]})}}function JG(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function HG(Q,X){if(X.target==="openApi3")return GG(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 GG(Q,X)}var GG=(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 BG(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 zG(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let $ of Q.checks)switch($.kind){case"int":Y.type="integer",J$(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 KG(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=$O(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=YO(Q,X);if(G!==void 0)$.additionalProperties=G;return $}function YO(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 $O(Q){try{return Q.isOptional()}catch{return!0}}var VG=(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 qG=(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 UG(Q,X){return g(Q.type._def,X)}function LG(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 FG(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 NG(Q){return{not:K0(Q)}}function OG(Q){return K0(Q)}var DG=(Q,X)=>{return g(Q.innerType._def,X)};var wG=(Q,X,Y)=>{switch(X){case A.ZodString:return T8(Q,Y);case A.ZodNumber:return zG(Q,Y);case A.ZodObject:return KG(Q,Y);case A.ZodBigInt:return nJ(Q,Y);case A.ZodBoolean:return oJ();case A.ZodDate:return G$(Q,Y);case A.ZodUndefined:return NG(Y);case A.ZodNull:return JG(Y);case A.ZodArray:return iJ(Q,Y);case A.ZodUnion:case A.ZodDiscriminatedUnion:return HG(Q,Y);case A.ZodIntersection:return eJ(Q,Y);case A.ZodTuple:return FG(Q,Y);case A.ZodRecord:return x8(Q,Y);case A.ZodLiteral:return QG(Q,Y);case A.ZodEnum:return sJ(Q);case A.ZodNativeEnum:return $G(Q);case A.ZodNullable:return BG(Q,Y);case A.ZodOptional:return VG(Q,Y);case A.ZodMap:return YG(Q,Y);case A.ZodSet:return LG(Q,Y);case A.ZodLazy:return()=>Q.getter()._def;case A.ZodPromise:return UG(Q,Y);case A.ZodNaN:case A.ZodNever:return WG(Y);case A.ZodEffects:return aJ(Q,Y);case A.ZodAny:return K0(Y);case A.ZodUnknown:return OG(Y);case A.ZodDefault:return tJ(Q,Y);case A.ZodBranded:return v8(Q,Y);case A.ZodReadonly:return DG(Q,Y);case A.ZodCatch:return rJ(Q,Y);case A.ZodPipeline:return qG(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!==cJ)return H}if($&&!Y){let H=WO($,X);if(H!==void 0)return H}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let J=wG(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)JO(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return W.jsonSchema=G,H}return W.jsonSchema=G,G}var WO=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:k8(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}}},JO=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var z$=(Q,X)=>{let Y=dJ(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 GO(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 K$(Q,X){if(d0(Q))return kY(Q,{target:GO(X?.target),io:X?.pipeStrategy??"input"});return z$(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function V$(Q){let Y=f1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let $=B8(Y);if(typeof $!=="string")throw Error("Schema method literal must be a string");return $}function q$(Q,X){let Y=h1(Q,X);if(!Y.success)throw Y.error;return Y.data}var HO=60000;class U${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(F8,(X)=>{this._oncancel(X)}),this.setNotificationHandler(O8,(X)=>{this._onprogress(X)}),this.setRequestHandler(N8,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(D8,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(M8,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(A8,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(R8,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)||_J(W))this._onresponse(W);else if(dY(W))this._onrequest(W,J);else if(CJ(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=PJ(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,m6,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??HO,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},w8,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},j8,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},vJ,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=V$(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,($,W)=>{let J=q$(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=V$(Q);this._notificationHandlers.set(Y,($)=>{let W=q$(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"&&dY($.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 MG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function AG(Q,X){let Y={...Q};for(let $ in X){let W=$,J=X[W];if(J===void 0)continue;let G=Y[W];if(MG(G)&&MG(J))Y[W]={...G,...J};else Y[W]=J}return Y}var WK=Z7(G7(),1),JK=Z7($K(),1);function Fb(){let Q=new WK.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return JK.default(Q),Q}class N7{constructor(Q){this._ajv=Q??Fb()}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 O7{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},d6,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 GK(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 HK(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 D7 extends U${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 N7,this.setRequestHandler(oY,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(rY,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(Y$,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 O7(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=AG(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(p6,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(m6,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(C8,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){HK(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;GK(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:IJ.includes(X)?X:cY,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"},L8)}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},$$,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:$},d6,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:$},d6,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},W$,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 zK=Symbol.for("mcp.completable");function w7(Q){return!!Q&&typeof Q==="object"&&zK in Q}function KK(Q){return Q[zK]?.complete}var BK;(function(Q){Q.Completable="McpCompletable"})(BK||(BK={}));var Nb=/^[A-Za-z0-9._-]{1,128}$/;function Ob(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(!Nb.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 Db(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 M7(Q){let X=Ob(Q);return Db(Q,X.warnings),X.isValid}class A7{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 R7{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 D7(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new A7(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(S8)),this.server.assertCanSetRequestHandler(r1(p6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(S8,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let $=u6(X.inputSchema);return $?K$($,{strictUnions:!0,pipeStrategy:"input"}):wb})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let $=u6(X.outputSchema);if($)Y.outputSchema=K$($,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(p6,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=u6(Q.inputSchema)??Q.inputSchema,J=await G8(W,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=H8(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 $=u6(Q.outputSchema),W=await G8($,X.structuredContent);if(!W.success){let J="error"in W?W.error:"Unknown error",G=H8(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(_8)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_8,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return fJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return uJ(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(!w7(W))return M9;let J=KK(W);if(!J)return M9;let G=await J(Q.params.argument.value,Q.params.context);return qK(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 qK(W)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(r1(I8)),this.server.assertCanSetRequestHandler(r1(b8)),this.server.assertCanSetRequestHandler(r1(E8)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(I8,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(b8,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(E8,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(P8)),this.server.assertCanSetRequestHandler(r1(Z8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(P8,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?Ab(X.argsSchema):void 0}})})),this.server.setRequestHandler(Z8,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 $=u6(Y.argsSchema),W=await G8($,Q.params.arguments);if(!W.success){let H="error"in W?W.error:"Unknown error",B=H8(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:K6($),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=K6(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 w7(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,$,W,J,G,H,B){M7(Q);let z={title:X,description:Y,inputSchema:VK($),outputSchema:VK(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")M7(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=K6(K.paramsSchema);if(typeof K.outputSchema<"u")z.outputSchema=K6(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(j7(H)){if($=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!j7(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 wb={type:"object",properties:{}};function UK(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function Mb(Q){return"_def"in Q||"_zod"in Q||UK(Q)}function j7(Q){if(typeof Q!=="object"||Q===null)return!1;if(Mb(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(UK)}function VK(Q){if(!Q)return;if(j7(Q))return K6(Q);return Q}function Ab(Q){let X=f1(Q);if(!X)return[];return Object.entries(X).map(([Y,$])=>{let W=XJ($),J=YJ($);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 $=B8(Y);if(typeof $==="string")return $;throw Error("Schema method literal must be a string")}function qK(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var M9={completion:{values:[],hasMore:!1}};function jb(Q,X,Y,$,W){return{name:Q,description:X,inputSchema:Y,handler:$,annotations:W?.annotations}}function Rb(Q){let X=new R7({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 $y({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 w6=Ib(import.meta.url),M6=LK(w6,"..");B=LK(M6,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.58";let{abortController:z=A6(),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=Z6()?"bun":"node",executableArgs:c0=[],extraArgs:t1={},fallbackModel:U1,enableFileCheckpointing:a1,forkSession:Z1,hooks:s1,includePartialMessages:u,persistSession:wQ,thinking:e1,effort:$4,maxThinkingTokens:Q6,maxTurns:A9,maxBudgetUsd:j9,mcpServers:b0,model:S1,outputFormat:O6,permissionMode:FK="default",allowDangerouslySkipPermissions:NK=!1,permissionPromptToolName:OK,plugins:DK,resume:wK,resumeSessionAt:MK,sessionId:AK,stderr:jK,strictMcpConfig:RK}=J,I7=O6?.type==="json_schema"?O6.schema:void 0,D6=N0;if(!D6)D6={...process.env};if(!D6.CLAUDE_CODE_ENTRYPOINT)D6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(a1)D6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!B)throw Error("pathToClaudeCodeExecutable is required");let MQ={},b7=new Map;if(b0)for(let[w6,M6]of Object.entries(b0))if(M6.type==="sdk"&&"instance"in M6)b7.set(w6,M6.instance),MQ[w6]={type:"sdk",name:w6};else MQ[w6]=M6;let IK=typeof Q==="string",W4;if(e1)switch(e1.type){case"adaptive":W4={type:"adaptive"};break;case"enabled":W4={type:"enabled",budgetTokens:e1.budgetTokens};break;case"disabled":W4={type:"disabled"};break}else if(Q6!==void 0)W4=Q6===0?{type:"disabled"}:{type:"enabled",budgetTokens:Q6};let E7=new H4({abortController:z,additionalDirectories:K,agent:q,betas:L,cwd:D,debug:j,debugFile:I,executable:O0,executableArgs:c0,extraArgs:t1,pathToClaudeCodeExecutable:B,env:D6,forkSession:Z1,stderr:jK,thinkingConfig:W4,effort:$4,maxTurns:A9,maxBudgetUsd:j9,model:S1,fallbackModel:U1,jsonSchema:I7,permissionMode:FK,allowDangerouslySkipPermissions:NK,permissionPromptToolName:OK,continueConversation:w,resume:wK,resumeSessionAt:MK,sessionId:AK,settingSources:$??[],allowedTools:V,disallowedTools:T,tools:v,mcpServers:MQ,strictMcpConfig:RK,canUseTool:!!F,hooks:!!s1,includePartialMessages:u,persistSession:wQ,plugins:DK,sandbox:W,spawnClaudeCodeProcess:J.spawnClaudeCodeProcess}),bK={systemPrompt:G,appendSystemPrompt:H,agents:U,promptSuggestions:J.promptSuggestions},P7=new z4(E7,IK,F,s1,z,b7,I7,bK);if(typeof Q==="string")E7.write(Z0({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+`
59
59
  `);else P7.streamInput(Q);return P7}function Wy(Q){return PQ(Q)}function Jy(Q,X){return b5(Q,X)}async function Gy(Q,X){let $=[];try{const Y=X0($,PQ(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 Hy(Q){return k5(Q)}export{Jy as unstable_v2_resumeSession,Gy as unstable_v2_prompt,Wy as unstable_v2_createSession,jb as tool,$y as query,Hy as listSessions,Rb as createSdkMcpServer,jq as HOOK_EVENTS,Rq as EXIT_REASONS,N1 as AbortError};