@tencent-ai/agent-harness 0.1.0 → 0.1.1
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/README.md +19 -7
- package/bin/native/darwin-arm64/agent-harness-process-snapshot.node +0 -0
- package/bin/native/darwin-x64/agent-harness-process-snapshot.node +0 -0
- package/cli/dist/codebuddy-headless.js +1 -1
- package/cli/dist/codebuddy-server.js +1 -1
- package/cli/product.cloudhosted.json +2 -2
- package/cli/product.internal.json +2 -2
- package/cli/product.ioa.json +2 -2
- package/cli/product.json +2 -2
- package/cli/product.selfhosted.json +2 -2
- package/docs/authentication-guide.md +4 -2
- package/executor/lib/capsule/entry.mjs +2 -2
- package/lib/integration/executor-supervisor.d.ts +4 -1
- package/lib/integration/executor-supervisor.js +7 -3
- package/lib/integration/stdio-guardian-child.js +11 -21
- package/lib/integration/stdio-guardian.d.ts +2 -1
- package/lib/integration/stdio-guardian.js +7 -5
- package/lib/runtime/agent-harness.d.ts +3 -1
- package/lib/runtime/agent-harness.js +12 -3
- package/lib/runtime/codebuddy-code.d.ts +5 -1
- package/lib/runtime/codebuddy-code.js +13 -3
- package/lib/runtime/codebuddy-prewarm-pool.d.ts +2 -0
- package/lib/runtime/codebuddy-prewarm-pool.js +9 -1
- package/lib/runtime/codebuddy-process.d.ts +2 -1
- package/lib/runtime/codebuddy-process.js +5 -22
- package/lib/runtime/codebuddy-resource-management.d.ts +2 -0
- package/lib/runtime/codebuddy-resource-management.js +13 -1
- package/lib/runtime/codebuddy-resource-process.d.ts +5 -2
- package/lib/runtime/codebuddy-resource-process.js +28 -8
- package/lib/runtime/codebuddy-v2-private-child.js +14 -1
- package/lib/runtime/node-runtime.d.ts +35 -0
- package/lib/runtime/node-runtime.js +46 -0
- package/lib/runtime/posix-contained-process.d.ts +3 -0
- package/lib/runtime/posix-contained-process.js +5 -3
- package/lib/runtime/posix-process-snapshot.d.ts +28 -0
- package/lib/runtime/posix-process-snapshot.js +183 -0
- package/lib/runtime/process-tree.d.ts +6 -8
- package/lib/runtime/process-tree.js +9 -37
- package/lib/transport/network.d.ts +7 -1
- package/lib/transport/network.js +15 -1
- package/package.json +5 -3
|
@@ -816,6 +816,6 @@
|
|
|
816
816
|
"SelectImage": true,
|
|
817
817
|
"SkipToolCallSupportCheck": true
|
|
818
818
|
},
|
|
819
|
-
"commit": "
|
|
820
|
-
"date": "2026-08-
|
|
819
|
+
"commit": "40227b2e396ead219ceb0993b1fa90793b055d2e",
|
|
820
|
+
"date": "2026-08-20T09:37:43.058Z"
|
|
821
821
|
}
|
package/cli/product.ioa.json
CHANGED
package/cli/product.json
CHANGED
|
@@ -1824,6 +1824,6 @@
|
|
|
1824
1824
|
"description": "tool-repl-description"
|
|
1825
1825
|
}
|
|
1826
1826
|
],
|
|
1827
|
-
"commit": "
|
|
1828
|
-
"date": "2026-08-
|
|
1827
|
+
"commit": "40227b2e396ead219ceb0993b1fa90793b055d2e",
|
|
1828
|
+
"date": "2026-08-20T09:37:43.073Z"
|
|
1829
1829
|
}
|
|
@@ -353,6 +353,6 @@
|
|
|
353
353
|
"ScheduledTasks": true,
|
|
354
354
|
"SkipToolCallSupportCheck": true
|
|
355
355
|
},
|
|
356
|
-
"commit": "
|
|
357
|
-
"date": "2026-08-
|
|
356
|
+
"commit": "40227b2e396ead219ceb0993b1fa90793b055d2e",
|
|
357
|
+
"date": "2026-08-20T09:37:43.042Z"
|
|
358
358
|
}
|
|
@@ -449,8 +449,10 @@ agent-harness --stdio \
|
|
|
449
449
|
--user-agent "CLI/$BUNDLED_AGENT_CLI_VERSION"
|
|
450
450
|
```
|
|
451
451
|
|
|
452
|
-
Harness 当前要求 Node.js 22 至 24。IDE launcher 必须使用随产品交付并验证过的 Node
|
|
453
|
-
|
|
452
|
+
Harness 当前要求 Node.js 22 至 24。IDE launcher 必须使用随产品交付并验证过的 Node runtime:
|
|
453
|
+
可以是独立 Node executable,也可以是开启 run-as-node fuse 的 Electron executable。后一种情况下
|
|
454
|
+
launcher 必须把 `process.execPath` 和 `ELECTRON_RUN_AS_NODE=1` 当作一个不可拆分的启动契约传入;
|
|
455
|
+
不能只传 executable,也不能默认使用系统 PATH 中版本未知的 Node。使用 stdio 时
|
|
454
456
|
broker 直接拥有 child stdin/stdout;选择 loopback HTTP/WebSocket 时也必须生成独立 transport bearer,
|
|
455
457
|
不能把 loopback 地址本身当作授权凭据。
|
|
456
458
|
|
|
@@ -70,5 +70,5 @@ ${jI(n)}`,requestedSchema:{type:`object`,properties:{}}})});if(s.action!==`accep
|
|
|
70
70
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Hz(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
71
71
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
72
72
|
`&&r++}}return[t,n]}var Uz=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Kz(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Kz(this),t)}};function Wz(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Gz(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Gz).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Gz(e.cause)}`:e.message:`${e}`}function Kz(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var qz=e=>{throw TypeError(e)},Jz=(e,t,n)=>t.has(e)||qz(`Cannot `+n),$=(e,t,n)=>(Jz(e,t,`read from private field`),n?n.call(e):t.get(e)),Yz=(e,t,n)=>t.has(e)?qz(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),Xz=(e,t,n,r)=>(Jz(e,t,`write to private field`),t.set(e,n),n),Zz=(e,t,n)=>(Jz(e,t,`access private method`),n),Qz,$z,eB,tB,nB,rB,iB,aB,oB,sB,cB,lB,uB,dB,fB,pB,mB,hB,gB,_B,vB,yB,bB,xB=class extends EventTarget{constructor(e,t){super(),Yz(this,dB),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Yz(this,Qz),Yz(this,$z),Yz(this,eB),Yz(this,tB),Yz(this,nB),Yz(this,rB),Yz(this,iB),Yz(this,aB,null),Yz(this,oB),Yz(this,sB),Yz(this,cB,null),Yz(this,lB,null),Yz(this,uB,null),Yz(this,pB,async e=>{var t;$(this,sB).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Zz(this,dB,vB).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?Xz(this,eB,new URL(e.url)):Xz(this,eB,void 0),i!==200){Zz(this,dB,vB).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Zz(this,dB,vB).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if($(this,Qz)===this.CLOSED)return;Xz(this,Qz,this.OPEN);let o=new Event(`open`);if((t=$(this,uB))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Zz(this,dB,vB).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&$(this,sB).feed(s.decode(t,{stream:!e})),e&&(l=!1,$(this,sB).reset(),Zz(this,dB,yB).call(this))}while(l)}),Yz(this,mB,e=>{Xz(this,oB,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Zz(this,dB,yB).call(this,Gz(e))}),Yz(this,gB,e=>{typeof e.id==`string`&&Xz(this,aB,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:$(this,eB)?$(this,eB).origin:$(this,$z).origin,lastEventId:e.id||``});$(this,lB)&&(!e.event||e.event===`message`)&&$(this,lB).call(this,t),this.dispatchEvent(t)}),Yz(this,_B,e=>{Xz(this,rB,e)}),Yz(this,bB,()=>{Xz(this,iB,void 0),$(this,Qz)===this.CONNECTING&&Zz(this,dB,fB).call(this)});try{if(e instanceof URL)Xz(this,$z,e);else if(typeof e==`string`)Xz(this,$z,new URL(e,SB()));else throw Error(`Invalid URL`)}catch{throw Wz(`An invalid or illegal string was specified`)}Xz(this,sB,Vz({onEvent:$(this,gB),onRetry:$(this,_B)})),Xz(this,Qz,this.CONNECTING),Xz(this,rB,3e3),Xz(this,nB,t?.fetch??globalThis.fetch),Xz(this,tB,t?.withCredentials??!1),Zz(this,dB,fB).call(this)}get readyState(){return $(this,Qz)}get url(){return $(this,$z).href}get withCredentials(){return $(this,tB)}get onerror(){return $(this,cB)}set onerror(e){Xz(this,cB,e)}get onmessage(){return $(this,lB)}set onmessage(e){Xz(this,lB,e)}get onopen(){return $(this,uB)}set onopen(e){Xz(this,uB,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){$(this,iB)&&clearTimeout($(this,iB)),$(this,Qz)!==this.CLOSED&&($(this,oB)&&$(this,oB).abort(),Xz(this,Qz,this.CLOSED),Xz(this,oB,void 0))}};Qz=new WeakMap,$z=new WeakMap,eB=new WeakMap,tB=new WeakMap,nB=new WeakMap,rB=new WeakMap,iB=new WeakMap,aB=new WeakMap,oB=new WeakMap,sB=new WeakMap,cB=new WeakMap,lB=new WeakMap,uB=new WeakMap,dB=new WeakSet,fB=function(){Xz(this,Qz,this.CONNECTING),Xz(this,oB,new AbortController),$(this,nB)($(this,$z),Zz(this,dB,hB).call(this)).then($(this,pB)).catch($(this,mB))},pB=new WeakMap,mB=new WeakMap,hB=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...$(this,aB)?{"Last-Event-ID":$(this,aB)}:void 0},cache:`no-store`,signal:$(this,oB)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},gB=new WeakMap,_B=new WeakMap,vB=function(e,t){var n;$(this,Qz)!==this.CLOSED&&Xz(this,Qz,this.CLOSED);let r=new Uz(`error`,{code:t,message:e});(n=$(this,cB))==null||n.call(this,r),this.dispatchEvent(r)},yB=function(e,t){var n;if($(this,Qz)===this.CLOSED)return;Xz(this,Qz,this.CONNECTING);let r=new Uz(`error`,{code:t,message:e});(n=$(this,cB))==null||n.call(this,r),this.dispatchEvent(r),Xz(this,iB,setTimeout($(this,bB),$(this,rB)))},bB=new WeakMap,xB.CONNECTING=0,xB.OPEN=1,xB.CLOSED=2;function SB(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}function CB(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function wB(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...CB(t.headers),...CB(r.headers)}:t.headers}):e}var TB=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function EB(e){return(await TB).getRandomValues(new Uint8Array(e))}async function DB(e){let t=``,n=await EB(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function OB(e){return await DB(e)}async function kB(e){let t=await(await TB).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function AB(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await OB(e);return{code_verifier:t,code_challenge:await kB(t)}}var jB=e().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:zL.custom,message:`URL must be parseable`,fatal:!0}),we}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),MB=te({resource:_().url(),authorization_servers:d(jB).optional(),jwks_uri:_().url().optional(),scopes_supported:d(_()).optional(),bearer_methods_supported:d(_()).optional(),resource_signing_alg_values_supported:d(_()).optional(),resource_name:_().optional(),resource_documentation:_().optional(),resource_policy_uri:_().url().optional(),resource_tos_uri:_().url().optional(),tls_client_certificate_bound_access_tokens:Se().optional(),authorization_details_types_supported:d(_()).optional(),dpop_signing_alg_values_supported:d(_()).optional(),dpop_bound_access_tokens_required:Se().optional()}),NB=te({issuer:_(),authorization_endpoint:jB,token_endpoint:jB,registration_endpoint:jB.optional(),scopes_supported:d(_()).optional(),response_types_supported:d(_()),response_modes_supported:d(_()).optional(),grant_types_supported:d(_()).optional(),token_endpoint_auth_methods_supported:d(_()).optional(),token_endpoint_auth_signing_alg_values_supported:d(_()).optional(),service_documentation:jB.optional(),revocation_endpoint:jB.optional(),revocation_endpoint_auth_methods_supported:d(_()).optional(),revocation_endpoint_auth_signing_alg_values_supported:d(_()).optional(),introspection_endpoint:_().optional(),introspection_endpoint_auth_methods_supported:d(_()).optional(),introspection_endpoint_auth_signing_alg_values_supported:d(_()).optional(),code_challenge_methods_supported:d(_()).optional(),client_id_metadata_document_supported:Se().optional()}),PB=ne({...te({issuer:_(),authorization_endpoint:jB,token_endpoint:jB,userinfo_endpoint:jB.optional(),jwks_uri:jB,registration_endpoint:jB.optional(),scopes_supported:d(_()).optional(),response_types_supported:d(_()),response_modes_supported:d(_()).optional(),grant_types_supported:d(_()).optional(),acr_values_supported:d(_()).optional(),subject_types_supported:d(_()),id_token_signing_alg_values_supported:d(_()),id_token_encryption_alg_values_supported:d(_()).optional(),id_token_encryption_enc_values_supported:d(_()).optional(),userinfo_signing_alg_values_supported:d(_()).optional(),userinfo_encryption_alg_values_supported:d(_()).optional(),userinfo_encryption_enc_values_supported:d(_()).optional(),request_object_signing_alg_values_supported:d(_()).optional(),request_object_encryption_alg_values_supported:d(_()).optional(),request_object_encryption_enc_values_supported:d(_()).optional(),token_endpoint_auth_methods_supported:d(_()).optional(),token_endpoint_auth_signing_alg_values_supported:d(_()).optional(),display_values_supported:d(_()).optional(),claim_types_supported:d(_()).optional(),claims_supported:d(_()).optional(),service_documentation:_().optional(),claims_locales_supported:d(_()).optional(),ui_locales_supported:d(_()).optional(),claims_parameter_supported:Se().optional(),request_parameter_supported:Se().optional(),request_uri_parameter_supported:Se().optional(),require_request_uri_registration:Se().optional(),op_policy_uri:jB.optional(),op_tos_uri:jB.optional(),client_id_metadata_document_supported:Se().optional()}).shape,...NB.pick({code_challenge_methods_supported:!0}).shape}),FB=ne({access_token:_(),id_token:_().optional(),token_type:_(),expires_in:VL().optional(),scope:_().optional(),refresh_token:_().optional()}).strip(),IB=ne({error:_(),error_description:_().optional(),error_uri:_().optional()}),LB=jB.optional().or(u(``).transform(()=>void 0)),RB=ne({redirect_uris:d(jB),token_endpoint_auth_method:_().optional(),grant_types:d(_()).optional(),response_types:d(_()).optional(),client_name:_().optional(),client_uri:jB.optional(),logo_uri:LB,scope:_().optional(),contacts:d(_()).optional(),tos_uri:LB,policy_uri:_().optional(),jwks_uri:jB.optional(),jwks:s().optional(),software_id:_().optional(),software_version:_().optional(),software_statement:_().optional()}).strip(),zB=ne({client_id:_(),client_secret:_().optional(),client_id_issued_at:ee().optional(),client_secret_expires_at:ee().optional()}).strip(),BB=RB.merge(zB);ne({error:_(),error_description:_().optional()}).strip(),ne({token:_(),token_type_hint:_().optional()}).strip();function VB(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function HB({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var UB=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},WB=class extends UB{};WB.errorCode=`invalid_request`;var GB=class extends UB{};GB.errorCode=`invalid_client`;var KB=class extends UB{};KB.errorCode=`invalid_grant`;var qB=class extends UB{};qB.errorCode=`unauthorized_client`;var JB=class extends UB{};JB.errorCode=`unsupported_grant_type`;var YB=class extends UB{};YB.errorCode=`invalid_scope`;var XB=class extends UB{};XB.errorCode=`access_denied`;var ZB=class extends UB{};ZB.errorCode=`server_error`;var QB=class extends UB{};QB.errorCode=`temporarily_unavailable`;var $B=class extends UB{};$B.errorCode=`unsupported_response_type`;var eV=class extends UB{};eV.errorCode=`unsupported_token_type`;var tV=class extends UB{};tV.errorCode=`invalid_token`;var nV=class extends UB{};nV.errorCode=`method_not_allowed`;var rV=class extends UB{};rV.errorCode=`too_many_requests`;var iV=class extends UB{};iV.errorCode=`invalid_client_metadata`;var aV=class extends UB{};aV.errorCode=`insufficient_scope`;var oV=class extends UB{};oV.errorCode=`invalid_target`;var sV={[WB.errorCode]:WB,[GB.errorCode]:GB,[KB.errorCode]:KB,[qB.errorCode]:qB,[JB.errorCode]:JB,[YB.errorCode]:YB,[XB.errorCode]:XB,[ZB.errorCode]:ZB,[QB.errorCode]:QB,[$B.errorCode]:$B,[eV.errorCode]:eV,[tV.errorCode]:tV,[nV.errorCode]:nV,[rV.errorCode]:rV,[iV.errorCode]:iV,[aV.errorCode]:aV,[oV.errorCode]:oV},cV=class extends Error{constructor(e){super(e??`Unauthorized`)}};function lV(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var uV=`code`,dV=`S256`;function fV(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&lV(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function pV(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:mV(i,a,n);return;case`client_secret_post`:hV(i,a,r);return;case`none`:gV(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function mV(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function hV(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function gV(e,t){t.set(`client_id`,e)}async function _V(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=IB.parse(JSON.parse(n));return new(sV[e]||ZB)(t||``,r)}catch(e){return new ZB(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function vV(e,t){try{return await yV(e,t)}catch(n){if(n instanceof GB||n instanceof qB)return await e.invalidateCredentials?.(`all`),await yV(e,t);if(n instanceof KB)return await e.invalidateCredentials?.(`tokens`),await yV(e,t);throw n}}async function yV(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await jV(c,{fetchFn:a}),!s)try{s=await wV(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await MV(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await xV(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!bV(r))throw new iV(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await RV(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await LV(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await IV(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof UB)||e instanceof ZB))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await NV(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function bV(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function xV(e,t,n){let r=VB(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!HB({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function SV(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=CV(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=CV(e,`scope`)||void 0,s=CV(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function CV(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function wV(e,t,n=fetch){let r=await kV(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return MB.parse(await r.json())}async function TV(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?TV(e,void 0,n):void 0;throw r}}function EV(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function DV(e,t,n=fetch){return await TV(e,{"MCP-Protocol-Version":t},n)}function OV(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function kV(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=EV(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await DV(o,a,n);return!r?.metadataUrl&&OV(s,i.pathname)&&(s=await DV(new URL(`/.well-known/${t}`,i),a,n)),s}function AV(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function jV(e,{fetchFn:t=fetch,protocolVersion:n=ae}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=AV(e);for(let{url:e,type:n}of i){let i=await TV(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?NB.parse(await i.json()):PB.parse(await i.json())}}}async function MV(e,t){let n,r;try{n=await wV(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await jV(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function NV(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(uV))throw Error(`Incompatible auth server: does not support response type ${uV}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(dV))throw Error(`Incompatible auth server: does not support code challenge method ${dV}`)}else s=new URL(`/authorize`,e);let c=await AB(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,uV),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,dV),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function PV(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function FV(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&pV(fV(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await _V(l);return FB.parse(await l.json())}async function IV(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await FV(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function LV(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=PV(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return FV(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function RV(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await _V(o);return BB.parse(await o.json())}var zV=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},BV=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=wB(t?.fetch,t?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new cV(`No auth provider`);let e;try{e=await vV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new cV;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=CB(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new xB(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});if(i.status===401&&i.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=SV(i);this._resourceMetadataUrl=e,this._scope=t}return i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(e.code===401&&this._authProvider){this._authThenStart().then(t,n);return}let r=new zV(e.code,e.message,e);n(r),this.onerror?.(r)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{let r=e;try{if(this._endpoint=new URL(r.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t=e,n;try{n=je.parse(JSON.parse(t.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(n)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new cV(`No auth provider`);if(await vV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new cV(`Failed to authorize`)}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._endpoint,n);if(!r.ok){let t=await r.text().catch(()=>null);if(r.status===401&&this._authProvider){let{resourceMetadataUrl:t,scope:n}=SV(r);if(this._resourceMetadataUrl=t,this._scope=n,await vV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new cV;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${t}`)}await r.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}},VV=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Vz({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},HV={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},UV=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},WV=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=wB(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??HV}async _authThenStart(){if(!this._authProvider)throw new cV(`No auth provider`);let e;try{e=await vV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new cV;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=CB(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new UV(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new VV({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=je.parse(JSON.parse(e.data));c(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new cV(`No auth provider`);if(await vV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new cV(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:S(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new UV(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=SV(o);if(this._resourceMetadataUrl=t,this._scope=n,await vV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new cV;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=SV(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new UV(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await vV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new cV;return this.send(e)}}throw new UV(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),v(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>je.parse(e)):[je.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new UV(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new UV(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function GV(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!GV(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!GV(e[r],t[r]))return!1;return!0}return e===t}function KV(e){return encodeURI(qV(e))}function qV(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var JV={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},YV={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},XV={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},ZV=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function QV(e,t=Object.create(null),n=ZV,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:QV(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(XV[i])continue;let a=`${r}/${KV(i)}`,o=e[i];if(Array.isArray(o)){if(JV[i]){let e=o.length;for(let r=0;r<e;r++)QV(o[r],t,n,`${a}/${r}`)}}else if(YV[i])for(let e in o)QV(o[e],t,n,`${a}/${KV(e)}`);else QV(o,t,n,a)}return t}var $V=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eH=[0,31,28,31,30,31,30,31,31,30,31,30,31],tH=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,nH=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,rH=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,iH=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,aH=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,oH=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,sH=/^(?:\/(?:[^~/]|~0|~1)*)*$/,cH=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,lH=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,uH=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},dH=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fH=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,pH=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function mH(e){return e.test.bind(e)}var hH={date:_H,time:vH.bind(void 0,!1),"date-time":bH,duration:pH,uri:CH,"uri-reference":mH(rH),"uri-template":mH(iH),url:mH(aH),email:uH,hostname:mH(nH),ipv4:mH(dH),ipv6:mH(fH),regex:TH,uuid:mH(oH),"json-pointer":mH(sH),"json-pointer-uri-fragment":mH(cH),"relative-json-pointer":mH(lH)};function gH(e){return e%4==0&&(e%100!=0||e%400==0)}function _H(e){let t=e.match($V);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&gH(n)?29:eH[r])}function vH(e,t){let n=t.match(tH);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var yH=/t|\s/i;function bH(e){let t=e.split(yH);return t.length==2&&_H(t[0])&&vH(!0,t[1])}var xH=/\/|:/,SH=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function CH(e){return xH.test(e)&&SH.test(e)}var wH=/[^\\]\\Z/;function TH(e){if(wH.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function EH(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function DH(e,t,n=`2019-09`,r=QV(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:ee,format:te,properties:ne,patternProperties:re,additionalProperties:ie,unevaluatedProperties:w,minProperties:ae,maxProperties:T,propertyNames:oe,dependentRequired:se,dependentSchemas:ce,dependencies:le,prefixItems:ue,items:de,additionalItems:fe,unevaluatedItems:E,contains:pe,minContains:me,maxContains:he,minItems:ge,maxItems:_e,uniqueItems:ve,minimum:ye,maximum:be,exclusiveMinimum:xe,exclusiveMaximum:D,multipleOf:Se,minLength:Ce,maxLength:we,pattern:Te,__absolute_ref__:Ee,__absolute_recursive_ref__:De}=t,O=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[De]:a,u=`${s}/$recursiveRef`,d=DH(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||O.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Ee||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Ee&&Ee!==d&&(e+=` Absolute URI "${Ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
73
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=DH(e,t,n,r,i,a,o,l,c);if(u.valid||O.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:O.length===0,errors:O}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?GV(e,h)||O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>GV(e,t))||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;DH(e,v,n,r,i,a,o,t).valid&&O.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Oe=[];if(y!==void 0){let t=`${s}/anyOf`,l=O.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=DH(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u||=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=O.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=DH(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u&&=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=O.length,u=x.filter((s,l)=>{let u=Object.create(c),d=DH(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return O.push(...d.errors),d.valid&&Oe.push(u),d.valid}).length;u===1?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Oe),S!==void 0){let t=`${s}/if`;if(DH(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=DH(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(ee!==void 0){let l=DH(e,ee,n,r,i,a,o,`${s}/else`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||O.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ae!==void 0&&t.length<ae&&O.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ae} properties.`}),T!==void 0&&t.length>T&&O.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${T} properties.`}),oe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${KV(s)}`,c=DH(s,oe,n,r,i,a,e,t);c.valid||O.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(se!==void 0){let t=`${s}/dependantRequired`;for(let n in se)if(n in e){let r=se[n];for(let i of r)i in e||O.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(ce!==void 0)for(let t in ce){let l=`${s}/dependentSchemas`;if(t in e){let s=DH(e,ce[t],n,r,i,a,o,`${l}/${KV(t)}`,c);s.valid||O.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(le!==void 0){let t=`${s}/dependencies`;for(let s in le)if(s in e){let c=le[s];if(Array.isArray(c))for(let n of c)n in e||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=DH(e,c,n,r,i,a,o,`${t}/${KV(s)}`);l.valid||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ne!==void 0){let t=`${s}/properties`;for(let s in ne){if(!(s in e))continue;let d=`${o}/${KV(s)}`,f=DH(e[s],ne[s],n,r,i,a,d,`${t}/${KV(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,O.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&re!==void 0){let t=`${s}/patternProperties`;for(let s in re){let d=new RegExp(s,`u`),f=re[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${KV(p)}`,h=DH(e[p],f,n,r,i,a,m,`${t}/${KV(s)}`);h.valid?c[p]=l[p]=!0:(u=i,O.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&ie!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${KV(s)}`,f=DH(e[s],ie,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,O.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&w!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${KV(s)}`,u=DH(e[s],w,n,r,i,a,l,t);u.valid?c[s]=!0:O.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){_e!==void 0&&e.length>_e&&O.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${_e}).`}),ge!==void 0&&e.length<ge&&O.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ge}).`});let t=e.length,l=0,u=!1;if(ue!==void 0){let d=`${s}/prefixItems`,f=Math.min(ue.length,t);for(;l<f;l++){let t=DH(e[l],ue[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(de!==void 0){let d=`${s}/items`;if(Array.isArray(de)){let s=Math.min(de.length,t);for(;l<s;l++){let t=DH(e[l],de[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=DH(e[l],de,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&fe!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=DH(e[l],fe,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,O.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(pe!==void 0)if(t===0&&me===void 0)O.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(me!==void 0&&t<me)O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${me}).`});else{let l=`${s}/contains`,u=O.length,d=0;for(let s=0;s<t;s++){let t=DH(e[s],pe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):O.push(...t.errors)}d>=(me||0)&&(O.length=u),me===void 0&&he===void 0&&d===0?O.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):me!==void 0&&d<me?O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${me} items matching schema. Only ${d} items were found.`}):he!==void 0&&d>he&&O.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${he} items matching schema. ${d} items were found.`})}if(!u&&E!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=DH(e[l],E,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||O.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ve)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&GV(r,t))&&(O.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(ye!==void 0&&(xe===!0&&e<=ye||e<ye)&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${xe?`or equal to `:``} ${ye}.`}),be!==void 0&&(D===!0&&e>=be||e>be)&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${D?`or equal to `:``} ${be}.`})):(ye!==void 0&&e<ye&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ye}.`}),be!==void 0&&e>be&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${be}.`}),xe!==void 0&&e<=xe&&O.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${xe}.`}),D!==void 0&&e>=D&&O.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${D}.`})),Se!==void 0){let t=e%Se;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Se-t)>=1.1920929e-7&&O.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Se}.`})}}else if(u===`string`){let t=Ce===void 0&&we===void 0?0:EH(e);Ce!==void 0&&t<Ce&&O.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Ce}).`}),we!==void 0&&t>we&&O.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${we}).`}),Te!==void 0&&!new RegExp(Te,`u`).test(e)&&O.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),te!==void 0&&hH[te]&&!hH[te](e)&&O.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${te}".`})}return{valid:O.length===0,errors:O}}var OH=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=QV(e)}validate(e){return DH(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),QV(e,this.lookup)}},kH=class{constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new OH(e,this.draft,this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}},AH=W({tools:G(W({name:U,description:V(K(U)),inputSchema:V(Lv),parameters:V(Lv),outputSchema:V(Lv),annotations:V(RL)}))}),jH=W({tools:G(Lv),nextCursor:V(K(U))}),MH=W({name:V(U),version:V(U)}),NH=B(AH),PH=B(jH),FH=B(MH),IH=e=>PH(e),LH=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`tool`,RH=(e,t)=>{let n=LH(e),r=(t.get(n)??0)+1;return t.set(n,r),r===1?n:`${n}_${r}`},zH=(e,t)=>{let n=new Map,r=NH(e).pipe(fi(e=>e.tools),ci(()=>[]));return{server:FH(t?.serverInfo).pipe(fi(e=>({name:e.name??null,version:e.version??null,instructions:t?.instructions??null})),ui),tools:r.flatMap(e=>{let t=e.name.trim();return t?[{toolId:RH(t,n),toolName:t,description:e.description??null,inputSchema:e.inputSchema??e.parameters,outputSchema:e.outputSchema,annotations:e.annotations}]:[]})}},BH=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``),VH=e=>URL.canParse(e)?new URL(e).hostname:null,HH=e=>e.trim().split(/[\\/]/).pop()??e.trim(),UH=e=>{if(e.name?.trim())return BH(e.name)||`mcp`;let t=e.endpoint?.trim()?VH(e.endpoint):null;return t?BH(t)||`mcp`:e.command?.trim()&&BH(HH(e.command))||`mcp`},WH=B(W({message:U})),GH=e=>si(WH(e),{onNone:()=>void 0,onSome:({message:e})=>{let t=/^Error POSTing to endpoint \(HTTP ([1-5][0-9]{2})\):/.exec(e);if(t)return Number(t[1])}}),KH=e=>{if(!(e instanceof UV))return;let t=e.code;return t!==void 0&&t>=100&&t<=599?t:void 0},qH=e=>KH(e)??GH(e),JH=/Server returned 403 after trying upscoping/,YH=e=>si(WH(e),{onNone:()=>!1,onSome:({message:e})=>$I(e)||JH.test(e)}),XH=(e,t)=>{let n=new URL(e);for(let[e,r]of Object.entries(t))n.searchParams.set(e,r);return n},ZH=new Set([`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`]),QH=e=>{let t=(e??`GET`).toUpperCase();return ZH.has(t)?t:`POST`},$H=e=>e?new Headers(e):new Headers,eU=e=>Object.fromEntries(e.entries()),tU=async(e,t,n)=>{if(n==null)return e;let r=t.get(`content-type`)??void 0;return typeof n==`string`?tk(e,n,r):n instanceof URLSearchParams?tk(e,n.toString(),r??`application/x-www-form-urlencoded;charset=UTF-8`):n instanceof Uint8Array?ek(e,n,r):n instanceof ArrayBuffer?ek(e,new Uint8Array(n),r):ek(e,new Uint8Array(await new Response(n).arrayBuffer()),r)},nU=e=>{if(e.reason!==void 0)return e.reason;let t=Error(`The operation was aborted`);return t.name=`AbortError`,t},rU=e=>async(t,n)=>{let r=$H(n?.headers),i=await tU(VO(QH(n?.method))(t,{headers:eU(r)}),r,n?.body),a=Np(F(function*(){let e=yield*(yield*uk).execute(i),t=new Headers;for(let[n,r]of Object.entries(e.headers))r!==void 0&&t.set(n,r);let n=e.status===204||e.status===205||e.status===304?null:Py(e.stream);return new Response(n,{status:e.status,headers:t})}).pipe(lp(e))).then(e=>{if(e.status===403){let t=e.headers.get(`www-authenticate`);if(t!==null&&eL({headers:{"www-authenticate":t}})!==null)throw new EL({message:`MCP server rejected the call: the OAuth grant does not cover the required scope`})}return e});if(a.catch(()=>void 0),!n?.signal)return a;if(n.signal.aborted)return Promise.reject(nU(n.signal));let o=new Promise((e,t)=>{n.signal?.addEventListener(`abort`,()=>t(nU(n.signal)),{once:!0})});return Promise.race([a,o])},iU=()=>new Rz({name:`executor-mcp`,version:`0.1.0`},{capabilities:{elicitation:{form:{},url:{}}},jsonSchemaValidator:new kH}),aU=e=>({client:e,close:()=>e.close()}),oU=(e,t,n)=>{if(yt(n,`McpOAuthReauthorizationRequired`))return new TL({message:`MCP OAuth re-authorization required`});if(yt(n,`McpInsufficientScopeError`))return new SL({transport:e,message:`${t} (HTTP 403: insufficient scope)`,httpStatus:403,insufficientScope:!0});let r=qH(n);return new SL({transport:e,message:r===void 0?t:`${t} (HTTP ${r})`,...r===void 0?{}:{httpStatus:r}})},sU=e=>F(function*(){let t=iU(),n=e.createTransport();return yield*Of({try:()=>t.connect(n),catch:t=>oU(e.transport,`Failed connecting via ${e.transport}`,t)}).pipe(z(`plugin.mcp.connection.handshake`,{attributes:{"plugin.mcp.transport":e.transport}})),aU(t)}),cU=e=>{if(e.transport===`stdio`){let t=e.command.trim();return t?F(function*(){let{createStdioTransport:n}=yield*Of({try:()=>import(`./stdio-connector-AA5S6UUJ.mjs`),catch:()=>new SL({transport:`stdio`,message:`Failed to load stdio transport module`})});return yield*sU({transport:`stdio`,createTransport:()=>n({command:t,args:e.args,env:e.env,cwd:e.cwd?.trim().length?e.cwd.trim():void 0})})}):I(new SL({transport:`stdio`,message:`MCP stdio transport requires a command`}))}let t=e.headers??{},n=e.remoteTransport??`auto`,r=Object.keys(t).length>0?{headers:t}:void 0,i=e.httpClientLayer?rU(e.httpClientLayer):void 0,a=XH(e.endpoint,e.queryParams??{}),o=sU({transport:`streamable-http`,createTransport:()=>new WV(a,{requestInit:r,authProvider:e.authProvider,fetch:i})}),s=sU({transport:`sse`,createTransport:()=>new BV(a,{requestInit:r,authProvider:e.authProvider,fetch:i})});return n===`streamable-http`?o:n===`sse`?s:o.pipe(qf(e=>yt(e,`McpOAuthReauthorizationRequired`)||e.httpStatus===401||e.httpStatus===403?I(e):s))},lU=300*1e3,uU=e=>Of(()=>e.close()).pipe($f),dU=e=>yt(e,`McpInvocationError`),fU=e=>yt(e,`McpConnectionError`)?!0:dU(e)?e.transportFailure===!0||e.status===400||e.status===401||e.status===404||e.status===408:!1,pU=e=>{if(ld(e))return!1;let t=e.cause.reasons.filter(Xu);return t.length===0?!0:t.some(e=>fU(e.error))},mU=()=>{let e=new Map,t=(t,n,r)=>F(function*(){if(r)return{connection:yield*n,reused:!1};let i=yield*Mf(()=>{let n=e.get(t);return n?(e.delete(t),Date.now()-n.idleSince>=lU?{connection:void 0,expired:n.connection}:{connection:n.connection,expired:void 0}):{connection:void 0,expired:void 0}});return i.expired&&(yield*uU(i.expired)),i.connection?{connection:i.connection,reused:!0}:{connection:yield*n,reused:!1}}),n=(t,n,r)=>F(function*(){if(pU(r)){yield*uU(n.connection);return}let i=yield*Mf(()=>{if(e.has(t))return n.connection;e.set(t,{connection:n.connection,idleSince:Date.now()})});i&&(yield*uU(i))});return{withConnection:(e,r,i)=>{let a=!1,o=o=>gp(t(e,r,o),e=>(o||(a=e.reused),i(e.connection)),(t,r)=>n(e,t,r));return o(!1).pipe(qf(e=>a&&dU(e)&&e.status===404?o(!0):I(e)))},close:()=>F(function*(){yield*Ef(yield*Mf(()=>{let t=[...e.values()].map(e=>e.connection);return e.clear(),t}),uU,{concurrency:`unbounded`,discard:!0})})}},hU=100,gU=Za(15),_U=e=>F(function*(){let t=[],n;for(let r=0;r<hU;r++){let r=n===void 0?void 0:{cursor:n},i=IH(yield*Of({try:()=>e.client.listTools(r),catch:()=>new CL({stage:`list_tools`,message:`Failed listing MCP tools`})}));if(ai(i))return yield*new CL({stage:`list_tools`,message:`MCP listTools response did not match the expected schema`});t.push(...i.value.tools);let a=i.value.nextCursor;if(a==null||a===``)break;n=a}return zH({tools:t},{serverInfo:e.client.getServerVersion?.(),instructions:e.client.getInstructions?.()})}),vU=(e,t=no(gU))=>F(function*(){let t=yield*e.pipe(R(e=>{let t=yt(e,`McpConnectionError`)?e.httpStatus:void 0;return new CL({stage:`connect`,message:`Failed connecting to MCP server: ${e.message}`,...t===void 0?{}:{httpStatus:t}})}));return yield*_U(t).pipe(yp(()=>yU(t)))}).pipe(rp({duration:Xa(t),orElse:()=>I(new CL({stage:`connect`,message:`MCP discovery timed out after ${t}ms`}))})),yU=e=>$f(Of({try:()=>e.close(),catch:()=>new CL({stage:`list_tools`,message:`Failed closing MCP connection`})})),bU=B(Uv(U,Lv)),xU=e=>ci(bU(e),()=>({})),SU=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),CU=(e,t)=>{let n=SU(t);return RegExp(`(?:unknown tool:?\\s*"?${n}"?|tool\\s+"?${n}"?\\s+(?:not found|is not available|does not exist))`,`i`).test(e)},wU=(e,t)=>e instanceof h&&(e.code===D.InvalidParams||e.code===D.MethodNotFound)&&CU(e.message,t),TU=kv(Kv([W({mode:H(`url`),message:U,url:U,elicitationId:V(U),id:V(U)}),W({mode:V(H(`form`)),message:U,requestedSchema:Uv(U,Lv)})])),EU=e=>e.mode===`url`?mx.make({message:e.message,url:e.url,elicitationId:Mb.make(e.elicitationId??e.id??``)}):px.make({message:e.message,requestedSchema:e.requestedSchema}),DU=(e,t)=>{e.setRequestHandler(O,async e=>{let n=await Fp(t(EU(TU(e.params))));if(ld(n)){let e=n.value;return{action:e.action,...e.action===`accept`&&e.content?{content:e.content}:{}}}let r=n.cause.reasons.find(Xu);if(r){let e=r.error;if(yt(e,`ElicitationDeclinedError`))return{action:j(e,`action`)&&e.action===`cancel`?`cancel`:`decline`}}throw Zu(n.cause)})},OU=(e,t)=>{t&&e.setNotificationHandler(f,()=>{t()})},kU=(e,t,n,r,i)=>F(function*(){return DU(e.client,r),OU(e.client,i),yield*Of({try:()=>e.client.callTool({name:t,arguments:n}),catch:e=>{if(yt(e,`McpOAuthReauthorizationRequired`))return new TL({message:`MCP OAuth re-authorization required`});if(yt(e,`McpInsufficientScopeError`))return new wL({toolName:t,message:`MCP tool call failed for ${t}`,status:403,insufficientScope:!0,transportFailure:!0});let n=qH(e),r=e instanceof h;return new wL({toolName:t,message:`MCP tool call failed for ${t}`,...n===void 0?{}:{status:n},...r?{}:{transportFailure:!0},...wU(e,t)?{unknownTool:!0}:{},...n===403&&YH(e)?{insufficientScope:!0}:{}})}}).pipe(z(`plugin.mcp.client.call_tool`,{attributes:{"mcp.tool.name":t}}))}),AU=e=>F(function*(){let t=xU(e.args),n=n=>kU(n,e.toolName,t,e.elicit,e.onToolListChanged);return e.connectionPool&&e.connectionPoolKey?yield*e.connectionPool.withConnection(e.connectionPoolKey,e.connector.pipe(z(`plugin.mcp.connection.acquire`,{attributes:{"plugin.mcp.transport":e.transport}})),n):yield*n(yield*hp(e.connector.pipe(z(`plugin.mcp.connection.acquire`,{attributes:{"plugin.mcp.transport":e.transport}})),t=>$f(Of({try:()=>t.close(),catch:()=>new SL({transport:e.transport,message:`Failed to close MCP connection`})}))))}).pipe(mp,z(`plugin.mcp.invoke`,{attributes:{"mcp.tool.name":e.toolName,"plugin.mcp.tool_id":e.toolId,"plugin.mcp.transport":e.transport}})),jU=JSON.stringify({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2025-06-18`,capabilities:{},clientInfo:{name:`executor-probe`,version:`0`}}}),MU=(e,t)=>{let n=e[t];if(n!==void 0)return n;let r=t.toLowerCase();for(let[t,n]of Object.entries(e))if(t.toLowerCase()===r)return n;return null},NU=class extends Gd(`ProbeTransportError`){},PU=B(ly(Lv)),FU=e=>{if(!e)return null;let t=PU(e);if(ai(t))return null;let n=t.value;return typeof n!=`object`||!n||Array.isArray(n)?null:n},IU=e=>{let t=FU(e);return!t||t.jsonrpc!==`2.0`?!1:`result`in t||`error`in t||`method`in t},LU=e=>{let t=FU(e);return!t||Array.isArray(t.errors)?!1:typeof t.error==`string`},RU=B(ly(W({resource:U,authorization_servers:G(U)}))),zU=e=>{let t=e.pathname===`/`?``:e.pathname;return`${e.origin}/.well-known/oauth-protected-resource${t}`},BU=(e,t)=>{if(!URL.canParse(e))return!1;let n=new URL(e);if(n.origin!==t.origin)return!1;let r=n.pathname.replace(/\/+$/,``),i=t.pathname.replace(/\/+$/,``);return i===r||i.startsWith(`${r}/`)},VU=(e,t,n)=>F(function*(){let r=yield*e.execute(HO(zU(t)).pipe(KO(`accept`,`application/json`))).pipe(np(Xa(n)));if(r.status<200||r.status>=300)return!1;let i=RU(yield*r.text.pipe(np(Xa(n)),qf(()=>P(``))));return ai(i)||i.value.authorization_servers.length===0?!1:BU(i.value.resource,t)}).pipe(qf(()=>P(!1))),HU=B(W({message:U})),UU=e=>{let t=HU(e);return oi(t)?t.value.message:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:typeof e==`symbol`?e.description??`symbol`:e===null?`null`:e===void 0?`undefined`:`fetch failed`},WU=(e,t={})=>F(function*(){let n=t.timeoutMs??8e3;return yield*F(function*(){let r=yield*uk,i=e=>e.text.pipe(np(Xa(n)),qf(()=>P(``))),a=(e,t)=>F(function*(){let a=MU(e.headers,`content-type`)??``,s=/^\s*text\/event-stream\b/i.test(a);if(e.status===401){let t=MU(e.headers,`www-authenticate`);if(!t||!/^\s*bearer\b/i.test(t))return(yield*VU(r,o,n))?{kind:`mcp`,requiresAuth:!0}:{kind:`not-mcp`,category:`auth-required`,reason:`401 without Bearer WWW-Authenticate — not an MCP auth challenge`};if(/(?:^|[\s,])resource_metadata\s*=/i.test(t)||/(?:^|[\s,])error\s*=/i.test(t)||s)return{kind:`mcp`,requiresAuth:!0};let a=yield*i(e);return!IU(a)&&!LU(a)?(yield*VU(r,o,n))?{kind:`mcp`,requiresAuth:!0}:{kind:`not-mcp`,category:`auth-required`,reason:`401 + Bearer without resource_metadata, JSON-RPC body, or OAuth error body`}:{kind:`mcp`,requiresAuth:!0}}return e.status>=200&&e.status<300?t===`GET`?s?{kind:`mcp`,requiresAuth:!1}:{kind:`not-mcp`,category:`wrong-shape`,reason:`GET response is not an SSE stream`}:s||IU(yield*i(e))?{kind:`mcp`,requiresAuth:!1}:{kind:`not-mcp`,category:`wrong-shape`,reason:`2xx POST body is not a JSON-RPC envelope`}:null}),o=new URL(e);for(let[e,n]of Object.entries(t.queryParams??{}))o.searchParams.set(e,n);let s=UO(o.toString()).pipe(KO(`content-type`,`application/json`),KO(`accept`,`application/json, text/event-stream`),tk(jU,`application/json`));for(let[e,n]of Object.entries(t.headers??{}))s=KO(s,e,n);let c=yield*r.execute(s).pipe(np(Xa(n))),l=yield*a(c,`POST`);if(l)return l;if([404,405,406,415].includes(c.status)){let e=HO(o.toString()).pipe(KO(`accept`,`text/event-stream`));for(let[n,r]of Object.entries(t.headers??{}))e=KO(e,n,r);let i=yield*a(yield*r.execute(e).pipe(np(Xa(n))),`GET`);if(i)return i}return{kind:`not-mcp`,category:`wrong-shape`,reason:`unexpected status ${c.status} for initialize`}}).pipe(lp(t.httpClientLayer??wk),R(e=>new NU({reason:UU(e),cause:e})),qf(e=>P({kind:`unreachable`,reason:e.reason})))}).pipe(z(`mcp.plugin.probe_shape`)),GU=`mcp`,KU=e=>{if(e.httpStatus!==void 0)return $b(e.httpStatus)===`expired`?`expired`:`degraded`;let t=e.message.toLowerCase();return t.includes(`oauth re-authorization`)||t.includes(`unauthorized`)||t.includes(`forbidden`)?`expired`:`degraded`},qU=e=>{let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:null},JU=(e,t)=>{let n=new Set,r=qU(e);r&&n.add(r);let i=t==null?null:qU(t.description);return i&&n.add(i),n},YU=(e,t)=>`${e}:${String(t)}`,XU=(e,t,n)=>!t.has(String(e.slug))||!n||n.transport!==`remote`||!n.authenticationTemplate.some(e=>e.kind===`oauth2`)?!1:e.grant===`authorization_code`&&(e.resource??null)===n.endpoint,ZU=B(W({mcp:W({toolName:U,upstream:V(W({title:V(U),readOnlyHint:V(Vv),destructiveHint:V(Vv),idempotentHint:V(Vv),openWorldHint:V(Vv)}))})})),QU=e=>si(ZU(e),{onNone:()=>null,onSome:e=>e.mcp}),$U=Kv([W({transport:V(H(`remote`)),name:U,description:V(U),endpoint:U,remoteTransport:V(DL),headers:V(Uv(U,U)),queryParams:V(Uv(U,U)),slug:V(U),authenticationTemplate:V(G(jL)),auth:V(kL)}),W({transport:H(`stdio`),name:U,description:V(U),command:U,args:V(G(U)),envVars:V(G(U)),env:V(Uv(U,U)),cwd:V(U),slug:V(U)})]),eW=W({slug:U});W({authenticationTemplate:G(jL),mode:V(qv([`merge`,`replace`]))});var tW=W({endpoint:U,headers:V(Uv(U,U)),queryParams:V(Uv(U,U))}),nW=W({connected:Vv,requiresAuthentication:Vv,requiresOAuth:Vv,supportsDynamicRegistration:Vv,name:U,slug:U,toolCount:K(Bv),serverName:K(U),instructions:K(U)}),rW=W({slug:U}),iW=W({integration:K(Lv)}),aW=e=>wv(Ev(e)),oW=aW($U),sW=aW(eW),cW=aW(tW),lW=aW(nW),uW=aW(rW),dW=aW(iW),fW=(e,t,n)=>$M.fail({code:e,message:t,...n===void 0?{}:{details:n}}),pW=e=>e.status===403&&e.insufficientScope===!0?iN({code:`oauth_scope_insufficient`,message:`MCP server rejected connection "${e.connection}" with HTTP 403: the connection's OAuth grant does not cover the scope this tool requires. Re-authenticating with the same grant will return the same error; reconnect with broader access.`,integration:{id:e.integration},credential:{kind:`oauth`,label:e.connection},status:e.status,upstream:{status:e.status}}):iN({code:`connection_rejected`,message:e.status===403?`MCP server rejected connection "${e.connection}" with HTTP 403. The credential may lack access or required scope; re-authenticate or update the connection before retrying this tool.`:`MCP server rejected connection "${e.connection}" with HTTP 401. Re-authenticate or update the connection before retrying this tool.`,integration:{id:e.integration},credential:{kind:`upstream`,label:e.connection},status:e.status,upstream:{status:e.status}}),mW=e=>iN({code:`oauth_reauth_required`,message:`OAuth connection "${e.connection}" requires reauthorization before retrying this MCP tool.`,integration:{id:e.integration},credential:{kind:`oauth`,label:e.connection}}),hW=e=>xb.make(e),gW=e=>e.slug??UH({name:e.name,endpoint:e.transport===`stdio`?void 0:e.endpoint,command:e.transport===`stdio`?e.command:void 0}),_W=`env`,vW=e=>{let t=new Set(e.envVars??[]);for(let n of Object.keys(e.env??{}))t.add(n);return[...t]},yW=e=>{if(e.transport===`stdio`){let t=vW(e);return{transport:`stdio`,command:e.command,args:e.args?[...e.args]:void 0,cwd:e.cwd,authenticationTemplate:t.length>0?[{slug:_W,kind:`stdio_env`,vars:t}]:[{slug:`none`,kind:`none`}]}}return{transport:`remote`,endpoint:e.endpoint,remoteTransport:e.remoteTransport??`auto`,queryParams:e.queryParams,headers:e.headers,authenticationTemplate:e.authenticationTemplate?PL(e.authenticationTemplate):[AL(e.auth??{kind:`none`})]}},bW=ce(Ee),xW=e=>{let t=bW.properties?.structuredContent??{};return{...bW,properties:{...bW.properties,structuredContent:e===void 0?t:e,isError:{const:!1}},required:e===void 0?[`content`]:[`content`,`structuredContent`]}},SW=e=>{let t=e.annotations?.destructiveHint===!0,n={toolName:e.toolName,...e.annotations?{upstream:e.annotations}:{}},r={requiresApproval:t,...t?{approvalDescription:e.annotations?.title??e.toolName}:{},mcp:n};return{name:jb.make(e.toolId),description:e.description??`MCP tool: ${e.toolName}`,inputSchema:e.inputSchema,outputSchema:xW(e.outputSchema),annotations:r}},CW=W({type:H(`text`),text:U}),wW=W({isError:V(Vv),content:V(G(Lv))}),TW=B(CW),EW=B(wW),DW=e=>{if(Array.isArray(e))for(let t of e){let e=di(TW(t));if(e!==void 0&&e.text.length>0)return e.text}return`MCP tool returned an error`},OW=(e,t)=>$M.fail({code:`mcp_tool_unknown`,message:`The MCP server no longer provides tool "${e}". Its tool catalog changed; list tools again for the current set.`,details:{integration:String(t.integration),connection:String(t.connection)}}),kW=(e,t)=>{let n=RegExp(`(?:^|[^a-z0-9])${t}(?:$|[^a-z0-9])`,`i`);return n.test(e.hostname)||n.test(e.pathname)},AW=e=>e.kind===`unreachable`?`Couldn't reach this URL. Check the address, your network, and that the server is running.`:`This URL doesn't appear to host an MCP server. Double-check the address, including the path.`,jW=e=>({get redirectUrl(){return`http://localhost/oauth/callback`},get clientMetadata(){return{redirect_uris:[`http://localhost/oauth/callback`],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`,client_name:`Executor`}},clientInformation:()=>void 0,saveClientInformation:()=>void 0,tokens:()=>({access_token:e,token_type:`Bearer`}),saveTokens:()=>void 0,redirectToAuthorization:async()=>{throw new TL({message:`MCP OAuth re-authorization required`})},saveCodeVerifier:()=>void 0,codeVerifier:()=>{throw Error(`No active PKCE verifier`)},saveDiscoveryState:()=>void 0,discoveryState:()=>void 0}),MW=(e,t)=>{let n=e.authenticationTemplate??[];if(t!==null){let e=n.find(e=>e.slug===t);if(e)return e}return n.length===1?n[0]:void 0},NW=(e,t,n,r,i)=>{if(e.transport===`stdio`){if(!r)return I(new SL({transport:`stdio`,message:"MCP stdio transport is disabled. Enable it by passing `dangerouslyAllowStdioMCP: true` to mcpPlugin() — only safe for trusted local contexts."}));let i=MW(e,n),a={...e.env??{}};if(i?.kind===`stdio_env`)for(let e of i.vars){let n=t[e];n!=null&&(a[e]=n)}return P({transport:`stdio`,command:e.command,args:e.args,env:Object.keys(a).length>0?a:void 0,cwd:e.cwd})}let a={...e.headers??{}},o={...e.queryParams??{}},s,c=MW(e,n);if(c?.kind===`apikey`){let e=sL(c.placements,t);Object.assign(a,e.headers),Object.assign(o,e.queryParams)}else if(c?.kind===`oauth2`){let e=t[nL];e!=null&&(s=jW(e))}return P({transport:`remote`,endpoint:e.endpoint,remoteTransport:e.remoteTransport??`auto`,queryParams:Object.keys(o).length>0?o:void 0,headers:Object.keys(a).length>0?a:void 0,authProvider:s,httpClientLayer:i})},PW=e=>Object.fromEntries(Object.entries(e??{}).filter(e=>e[1]!==void 0).sort(([e],[t])=>e<t?-1:+(e>t))),FW=(e,t,n)=>JSON.stringify({endpoint:e.endpoint,transport:e.transport,remoteTransport:e.remoteTransport,headers:PW(e.headers),queryParams:PW(e.queryParams),template:t,values:PW(n)}),IW=e=>({id:e.slug,label:`Environment variables`,kind:`apikey`,template:e.slug,placements:e.vars.map(e=>({carrier:`env`,name:e,prefix:``,variable:e}))}),LW=e=>{let t=LL(e.config);return t?(t.authenticationTemplate??[]).map(e=>e.kind===`stdio_env`?IW(e):e.kind===`apikey`?fL(e):e.kind===`oauth2`?{id:e.slug,label:`OAuth`,kind:`oauth`,template:e.slug,oauth:{discoveryUrl:t.transport===`remote`?t.endpoint:void 0,supportsDynamicRegistration:!0}}:pL(e.slug)):[]},RW=e=>{let t=LL(e.config);return!t||t.transport===`stdio`?{}:{url:t.endpoint}},zW=Xk(e=>{let t=e?.dangerouslyAllowStdioMCP??!1,n=mU();return{id:GU,packageName:`@executor-js/plugin-mcp`,remoteToolCatalog:!0,integrationPresets:(t?tL:tL.filter(e=>!(`transport`in e&&e.transport===`stdio`))).map(e=>({id:e.id,name:e.name,summary:e.summary,...`url`in e&&e.url?{url:e.url}:{},...`endpoint`in e&&e.endpoint?{endpoint:e.endpoint}:{},...e.icon?{icon:e.icon}:{},...e.featured?{featured:e.featured}:{},transport:`transport`in e&&e.transport===`stdio`?`stdio`:`remote`,...`command`in e?{command:e.command}:{},...`args`in e&&e.args?{args:[...e.args]}:{},...`env`in e&&e.env?{env:e.env}:{}})),clientConfig:{allowStdio:t},storage:()=>({}),close:()=>n.close(),extension:t=>{let n=e?.httpClientLayer??t.httpClientLayer;return{probeEndpoint:e=>F(function*(){let r=(typeof e==`string`?e:e.endpoint).trim();if(!r)return yield*new SL({transport:`remote`,message:`Endpoint URL is required`});let i=yield*If({try:()=>new URL(r).hostname,catch:()=>`mcp`}).pipe(tp(()=>`mcp`)),a=UH({endpoint:r}),o=typeof e==`string`?void 0:e.headers,s=typeof e==`string`?void 0:e.queryParams,c=yield*vU(cU({transport:`remote`,endpoint:r,headers:o,queryParams:s,httpClientLayer:n})).pipe(L(e=>({ok:!0,manifest:e})),qf(()=>P({ok:!1,manifest:null})),z(`mcp.plugin.discover_tools`));if(c.ok&&c.manifest)return{connected:!0,requiresAuthentication:!1,requiresOAuth:!1,supportsDynamicRegistration:!1,name:c.manifest.server?.name??i,slug:a,toolCount:c.manifest.tools.length,serverName:c.manifest.server?.name??null,instructions:c.manifest.server?.instructions??null};let l=yield*WU(r,{httpClientLayer:n,headers:o,queryParams:s});if(l.kind===`unreachable`)return yield*new SL({transport:`remote`,message:AW(l)});if(l.kind===`not-mcp`)return l.category===`wrong-shape`?yield*new SL({transport:`remote`,message:AW(l)}):{connected:!1,requiresAuthentication:!0,requiresOAuth:!1,supportsDynamicRegistration:!1,name:i,slug:a,toolCount:null,serverName:null,instructions:null};let u=yield*t.oauth.probe({url:r}).pipe(L(e=>({ok:!0,oauth:e})),qf(()=>P({ok:!1,oauth:null})),z(`mcp.plugin.probe_oauth`));return u.ok?{connected:!1,requiresAuthentication:!0,requiresOAuth:!0,supportsDynamicRegistration:u.oauth.registrationEndpoint!=null,name:i,slug:a,toolCount:null,serverName:null,instructions:null}:l.requiresAuth?{connected:!1,requiresAuthentication:!0,requiresOAuth:!1,supportsDynamicRegistration:!1,name:i,slug:a,toolCount:null,serverName:null,instructions:null}:yield*new SL({transport:`remote`,message:`This endpoint looks like MCP, but Executor couldn't discover tools from it. Check the URL and try again.`})}).pipe(z(`mcp.plugin.probe_endpoint`,{attributes:{"mcp.endpoint":typeof e==`string`?e:e.endpoint}})),addServer:e=>F(function*(){let n=gW(e),r=yW(e);if(yield*t.core.integrations.get(hW(n)))return yield*new Ax({slug:hW(n)});if(yield*t.core.integrations.register({slug:hW(n),name:e.name,description:e.description?.trim()||e.name,config:r,canRemove:!0,canRefresh:!0}).pipe(z(`mcp.plugin.register_integration`,{attributes:{"mcp.integration.slug":n}})),e.transport===`stdio`){let r=e.env!=null&&Object.keys(e.env).length>0,i=vW(e).length>0;(r||!i)&&(yield*t.connections.create({owner:`org`,name:wb.make(`default`),integration:hW(n),template:Sb.make(r?_W:`none`),values:r?{...e.env}:{}}).pipe(Yf({IntegrationNotFoundError:e=>I(new SL({transport:`stdio`,message:e.message})),CredentialProviderNotRegisteredError:e=>I(new SL({transport:`stdio`,message:e.message})),InvalidConnectionInputError:e=>I(new SL({transport:`stdio`,message:e.message}))}),z(`mcp.plugin.bootstrap_stdio_connection`,{attributes:{"mcp.integration.slug":n}})))}return{slug:n}}).pipe(z(`mcp.plugin.add_server`,{attributes:{"mcp.server.transport":e.transport??`remote`,"mcp.server.name":e.name}})),removeServer:e=>F(function*(){let n=hW(e),r=yield*t.core.integrations.get(n),i=r?LL(r.config):null,a=JU(e,r),o=yield*t.connections.list({integration:n}),s=yield*t.connections.list(),c=yield*t.oauth.listClients(),l=new Set(s.filter(e=>String(e.integration)!==String(n)).flatMap(e=>e.oauthClient==null?[]:[YU(e.oauthClientOwner??e.owner,e.oauthClient)])),u=new Map(c.map(e=>[YU(e.owner,e.slug),e])),d=new Map;for(let e of o){if(e.oauthClient==null)continue;let t=e.oauthClientOwner??e.owner,n=YU(t,e.oauthClient);u.get(n)?.origin.kind===`dynamic_client_registration`&&d.set(n,{owner:t,slug:e.oauthClient})}for(let t of c){let n=YU(t.owner,t.slug);if(!l.has(n)){if(t.origin.kind===`dynamic_client_registration`&&(t.origin.integration==null||String(t.origin.integration)===e)){d.set(n,{owner:t.owner,slug:t.slug});continue}XU(t,a,i)&&d.set(n,{owner:t.owner,slug:t.slug})}}yield*t.core.integrations.remove(n).pipe(Jf(`IntegrationRemovalNotAllowedError`,()=>Nf)),yield*Ef(d.values(),e=>t.oauth.removeClient(e.owner,e.slug),{discard:!0})}).pipe(z(`mcp.plugin.remove_server`,{attributes:{"mcp.integration.slug":e}})),reconcileStdioConnections:()=>F(function*(){let e=yield*t.core.integrations.list();for(let n of e)n.kind===GU&&(yield*F(function*(){let e=yield*t.core.integrations.get(n.slug),r=e?LL(e.config):null;if(!r||r.transport!==`stdio`||r.authenticationTemplate!==void 0||(yield*t.connections.list({integration:n.slug})).length>0)return;let i=r.env??{},a=Object.keys(i),o=a.length>0;yield*t.connections.create({owner:`org`,name:wb.make(`default`),integration:n.slug,template:Sb.make(o?_W:`none`),values:o?{...i}:{}});let s={transport:`stdio`,command:r.command,args:r.args,cwd:r.cwd,authenticationTemplate:o?[{slug:_W,kind:`stdio_env`,vars:a}]:[{slug:`none`,kind:`none`}]};yield*t.core.integrations.update(n.slug,{config:s})}).pipe(qf(e=>Hp(`mcp: failed healing stdio connection for "${n.slug}"`,e)),z(`mcp.plugin.reconcile_stdio_connection`,{attributes:{"mcp.integration.slug":String(n.slug)}})))}).pipe(z(`mcp.plugin.reconcile_stdio_connections`)),getServer:e=>t.core.integrations.get(hW(e)).pipe(z(`mcp.plugin.get_server`,{attributes:{"mcp.integration.slug":e}})),configureServer:(e,n)=>t.core.integrations.update(hW(e),{config:n}).pipe(z(`mcp.plugin.configure_server`,{attributes:{"mcp.integration.slug":e}})),configureAuth:(e,n)=>F(function*(){let r=yield*t.core.integrations.get(hW(e)),i=r?LL(r.config):null;if(!i||i.transport===`stdio`)return[];let a=n.mode===`replace`?PL(n.authenticationTemplate):zI(i.authenticationTemplate,NL(n.authenticationTemplate));return yield*t.core.integrations.update(hW(e),{config:{...i,authenticationTemplate:a}}),a}).pipe(z(`mcp.plugin.configure_auth`,{attributes:{"mcp.integration.slug":e}}))}},resolveTools:({config:e,connection:n,template:r,getValues:i,httpClientLayer:a})=>F(function*(){let o=LL(e);if(!o)return{tools:[],incomplete:!0};let s=yield*NW(o,yield*i().pipe(tp(()=>({}))),r===null?null:String(r),t,a).pipe(L(e=>cU(e)),Hf),c=yi(s)?yield*vU(s.success).pipe(L(e=>({ok:!0,manifest:e})),qf(()=>P({ok:!1,manifest:null})),z(`mcp.plugin.discover_tools`,{attributes:{"mcp.connection.name":String(n.name)}})):{ok:!1,manifest:null};return!c.ok||!c.manifest?{tools:[],incomplete:!0}:{tools:c.manifest.tools.map(SW)}}).pipe(z(`mcp.plugin.resolve_tools`,{attributes:{"mcp.connection.name":String(n.name)}})),invokeTool:({ctx:r,toolRow:i,credential:a,args:o,elicit:s})=>F(function*(){let c=LL(a.config);if(!c)return yield*new SL({transport:`auto`,message:`MCP integration "${i.integration}" has no usable config`});let l=QU(i.annotations);if(!l)return yield*new CL({stage:`list_tools`,message:`Tool "${i.name}" is missing its MCP binding \u2014 refresh the connection`});let u=c.transport===`stdio`?`stdio`:c.remoteTransport??`auto`;if(c.transport===`remote`){let e=MW(c,String(a.template));if(e?.kind===`apikey`){let t=cL(e.placements).filter(e=>a.values[e]==null);if(t.length>0)return iN({code:`connection_value_missing`,message:`Connection has no resolvable credential value for input(s): ${t.join(`, `)}. Re-create the connection with the required value(s).`,integration:{id:String(a.integration)},credential:{kind:`upstream`,label:String(a.connection)}})}}let d=yield*NW(c,a.values,String(a.template),t,e?.httpClientLayer??r.httpClientLayer),f=cU(d),p=d.transport===`remote`?FW(d,String(a.template),a.values):void 0,m={owner:a.owner,integration:a.integration,name:a.connection},h=!1,g=yield*AU({toolId:String(i.name),toolName:l.toolName,args:o,transport:u,connector:f,...p===void 0?{}:{connectionPool:n,connectionPoolKey:p},elicit:s,onToolListChanged:()=>{h=!0}}).pipe(yp(()=>h?r.connections.markToolsStale(m).pipe($f):Nf)),_=di(EW(g));if(_?.isError===!0){let e=DW(_.content);return CU(e,l.toolName)?yield*r.connections.markToolsStale(m).pipe($f,Gf(OW(String(i.name),a))):$M.fail({code:`mcp_tool_error`,message:e,details:{content:_.content}})}return $M.ok(g)}).pipe(Jf(`McpOAuthReauthorizationRequired`,()=>P(mW({integration:String(a.integration),connection:String(a.connection)}))),Jf(`McpConnectionError`,e=>e.httpStatus===401||e.httpStatus===403?P(pW({status:e.httpStatus,integration:String(a.integration),connection:String(a.connection),...e.insufficientScope===!0?{insufficientScope:!0}:{}})):P(iN({code:`connection_rejected`,message:e.message,integration:{id:String(a.integration)},credential:{kind:`upstream`,label:String(a.connection)}}))),Jf(`McpInvocationError`,e=>e.status===401||e.status===403?P(pW({status:e.status,integration:String(a.integration),connection:String(a.connection),...e.insufficientScope===!0?{insufficientScope:!0}:{}})):e.unknownTool===!0?r.connections.markToolsStale({owner:a.owner,integration:a.integration,name:a.connection}).pipe($f,Gf(OW(String(i.name),a))):I(e)),z(`mcp.plugin.invoke_tool`,{attributes:{"mcp.tool.name":String(i.name),"mcp.integration.slug":String(i.integration)}})),detect:({ctx:t,url:n})=>F(function*(){let r=e?.httpClientLayer??t.httpClientLayer,i=n.trim();if(!i)return null;let a=yield*If({try:()=>new URL(i),catch:e=>e}).pipe(Uf);if(ai(a))return null;let o=a.value.hostname||`mcp`,s=UH({endpoint:i});return(yield*vU(cU({transport:`remote`,endpoint:i,httpClientLayer:r})).pipe(L(()=>!0),qf(()=>P(!1)),z(`mcp.plugin.discover_tools`)))||(yield*WU(i,{httpClientLayer:r})).kind===`mcp`?{kind:GU,confidence:`high`,endpoint:i,name:o,slug:s}:kW(a.value,`mcp`)?{kind:GU,confidence:`low`,endpoint:i,name:o,slug:s}:null}).pipe(qf(()=>P(null)),z(`mcp.plugin.detect`,{attributes:{"mcp.endpoint":n}})),resolveAnnotations:({toolRows:e})=>Mf(()=>{let t={};for(let n of e){let e=QU(n.annotations),r=e?.upstream;r?.destructiveHint===!0?t[String(n.name)]={requiresApproval:!0,approvalDescription:r.title??e?.toolName??String(n.name)}:t[String(n.name)]={requiresApproval:!1}}return t}),checkHealth:({ctx:n,credential:r})=>F(function*(){let i=LL(r.config);return i?yield*vU(yield*NW(i,r.values,r.template===null?null:String(r.template),t,e?.httpClientLayer??n.httpClientLayer).pipe(L(e=>cU(e)))).pipe(L(()=>({status:`healthy`,checkedAt:Date.now()})),Jf(`McpToolDiscoveryError`,e=>P({status:KU(e),checkedAt:Date.now(),...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},detail:e.message}))):{status:`unknown`,checkedAt:Date.now()}}).pipe(Jf(`McpConnectionError`,e=>P({status:KU(e),checkedAt:Date.now(),...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},detail:e.message})),Vf(e=>Tp({"mcp.health.status":e.status,...`httpStatus`in e&&e.httpStatus!==void 0?{"mcp.health.http_status":e.httpStatus}:{}})),z(`mcp.plugin.check_health`,{attributes:{"executor.integration":String(r.integration),"mcp.connection.name":String(r.connection)}})),describeAuthMethods:LW,describeIntegrationDisplay:RW,integrationConfigure:{type:`mcp`,configure:({ctx:e,integration:t,config:n})=>F(function*(){let r=LL(n);r&&(yield*e.core.integrations.update(t,{config:r}))})},staticIntegrations:e=>[{id:`mcp`,kind:`executor`,name:`MCP`,tools:[Yk({name:`probeEndpoint`,description:"Probe a remote MCP endpoint before adding it. If the result requires OAuth, run the core OAuth handoff (`oauth.probe`, `oauth.start`) to mint a connection; otherwise create a connection with `connections.create` carrying the API key or header value.",inputSchema:cW,outputSchema:lW,execute:t=>e.probeEndpoint(t).pipe(L($M.ok),Jf(`McpConnectionError`,({message:e,transport:t})=>P(fW(`mcp_connection_failed`,e,{transport:t}))))}),Yk({name:`getServer`,description:"Inspect a registered MCP integration, including transport, endpoint/command, and auth template. Use this before creating a connection (`connections.create` / `oauth.start`).",inputSchema:uW,outputSchema:dW,execute:t=>{let n=t;return L(e.getServer(n.slug),e=>$M.ok({integration:e}))}}),Yk({name:`addServer`,description:"Register an MCP server in the catalog as an integration. Returns its `slug`. Then create a connection against it: for header/API-key auth call `connections.create` with the value; for OAuth-protected servers run `oauth.probe` + `oauth.start`. Tools are produced per-connection at connection create / refresh.",annotations:{requiresApproval:!0,approvalDescription:`Add an MCP server`},inputSchema:oW,outputSchema:sW,execute:t=>{let n=t;return e.addServer(n).pipe(L($M.ok),Jf(`IntegrationAlreadyExistsError`,({slug:e})=>P(fW(`integration_already_exists`,`Integration ${e} already exists; update it instead of re-adding.`))))}})]}]}});B(Kv([W({kind:H(`none`)}),W({kind:H(`header`),headerName:U,prefix:V(U)}),W({kind:H(`query`),paramName:U,prefix:V(U)}),W({kind:H(`oauth2`)})]));var BW=W({slug:U,kind:H(`header`),headerName:U,prefix:V(U)}),VW=W({slug:U,kind:H(`query`),paramName:U,prefix:V(U)}),HW=W({slug:U,type:H(`oauth`)});B(BW),B(VW),B(HW),B(Kv([W({slug:U,kind:qv([`none`,`oauth2`])}),W({slug:U,kind:H(`apikey`),label:V(U),placements:G(Lv)})]));var UW=`harness.executor.runtime`,WW=new Set([`close`,`dispatch`,`initialize`,`reconcile`,`refresh`,`release`,`update`]);function GW(e,t){try{e?.(t)}catch{}}function KW(e){let t={},n=e instanceof Map?e.entries():Object.entries(e);for(let[e,r]of n)(e===`component`&&r===`executor`||e===`runtime.role`&&r===`executor`||e===`operation`&&typeof r==`string`&&WW.has(r)||e===`outcome`&&(r===`cancelled`||r===`error`||r===`success`||r===`timeout`))&&(t[e]=r);return Object.freeze(t)}function qW(e,t){return/^[0-9a-f]{32}$/.test(e)&&e!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/.test(t)&&t!==`0000000000000000`?{spanId:t,traceId:e}:void 0}function JW(e,t){let n=t>=e?t-e:0n,r=Number(n)/1e6;return Number.isFinite(r)?Math.round(r*1e3)/1e3:0}function YW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XW(e){return YW(e)&&typeof e._tag==`string`?e._tag.slice(0,128):e instanceof Error&&e.name?e.name.slice(0,128):`mcp_unavailable`}function ZW(e,t,n,r){return{error:{code:XW(r),message:`MCP server is unavailable`,retryable:!0},generation:n,registrationId:t,runtimeEpoch:e,status:`unavailable`,tools:[]}}function QW(e){return YW(e)?e:void 0}function $W(e){if(!YW(e)||!YW(e.mcp)||!YW(e.mcp.upstream))return;let t=e.mcp.upstream,n={...typeof t.destructiveHint==`boolean`?{destructiveHint:t.destructiveHint}:{},...typeof t.idempotentHint==`boolean`?{idempotentHint:t.idempotentHint}:{},...typeof t.openWorldHint==`boolean`?{openWorldHint:t.openWorldHint}:{},...typeof t.readOnlyHint==`boolean`?{readOnlyHint:t.readOnlyHint}:{},...typeof t.title==`string`?{title:t.title}:{}};return Object.keys(n).length>0?n:void 0}function eG(e){let t=QW(QW(e.annotations)?.mcp);return typeof t?.toolName==`string`?t.toolName:String(e.name)}function tG(e){if(YW(e)&&!(!Array.isArray(e.required)||!e.required.includes(`structuredContent`)))return QW(QW(e.properties)?.structuredContent)}function nG(e){let t=tG(e.outputSchema);return{...$W(e.annotations)===void 0?{}:{annotations:$W(e.annotations)},...e.description?{description:e.description}:{},executorAddress:String(e.address),inputSchema:QW(e.inputSchema)??{additionalProperties:!0,type:`object`},...t===void 0?{}:{outputSchema:t},upstreamToolName:eG(e)}}function rG(e){return[{text:e,type:`text`}]}function iG(e,t=!1){if(!YW(e))return{content:rG(JSON.stringify(e)??String(e)),...t?{isError:!0}:{}};let n=Array.isArray(e.content)?e.content:rG(JSON.stringify(e)),r=QW(e.structuredContent),i=QW(e._meta);return{...i===void 0?{}:{_meta:i},content:n,...t||e.isError===!0?{isError:!0}:{},...r===void 0?{}:{structuredContent:r}}}function aG(e){if(!tN(e))return iG(e);if(e.ok)return iG(e.data);let t=QW(e.error.details)?.content;return{content:Array.isArray(t)?t:rG(e.error.message),isError:!0}}function oG(e){return e.request._tag===`FormElicitation`?{message:e.request.message,mode:`form`,requestedSchema:e.request.requestedSchema}:{elicitationId:String(e.request.elicitationId),message:e.request.message,mode:`url`,url:e.request.url}}function sG(e){return{action:e.action,...e.content===void 0?{}:{content:e.content}}}var cG=class{constructor(){this.key=Db.make(`agent-harness-ephemeral`),this.values=ib(new Map),this.provider={delete:e=>this.deleteValue(String(e)),get:e=>ab(this.values).pipe(L(t=>t.get(String(e))??null)),has:e=>ab(this.values).pipe(L(t=>t.has(String(e)))),key:this.key,list:()=>ab(this.values).pipe(L(e=>[...e.keys()].map(e=>({id:Ob.make(e),name:e})))),set:(e,t)=>this.setValue(String(e),t),writable:!0}}clear(){return ob(this.values,new Map)}deleteValue(e){return cb(this.values,t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})}setValue(e,t){return cb(this.values,n=>{let r=new Map(n);return r.set(e,t),r})}},lG=class extends Error{constructor(e,t,n=`Executor operation failed at ${e}`){super(n),this.stage=e,this.upstreamCode=t,this._tag=`ExecutorRuntimeFailure`,this.name=this._tag}},uG=class extends Error{constructor(){super(`Executor runtime is closed`),this._tag=`ExecutorRuntimeClosed`,this.name=this._tag}},dG=class extends Error{constructor(e){super(`Duplicate Executor invocation id "${e}"`),this.invocationId=e,this._tag=`ExecutorInvocationConflict`,this.name=this._tag}},fG=class extends Error{constructor(e){super(`Unknown Executor registration "${e}"`),this.registrationId=e,this._tag=`ExecutorRegistrationNotFound`,this.name=this._tag}},pG=class extends Error{constructor(){super(`Executor tool address is not present in the registration`),this._tag=`ExecutorToolAddressNotFound`,this.name=this._tag}},mG=class extends Error{constructor(){super(`Executor invocation was interrupted`),this._tag=`ExecutorInvocationInterrupted`,this.name=this._tag}},hG=class extends Error{constructor(){super(`Private Executor runtime encountered a fatal defect`),this._tag=`ExecutorRuntimeDefect`,this.name=this._tag}};function gG(e,t){return new lG(e,XW(t))}function _G(e){if(ed(e))return new hG;let t=$u(e),n=oi(t)?t.value:Zu(e);return n instanceof dG||n instanceof mG||n instanceof fG||n instanceof uG||n instanceof lG||n instanceof pG?n:td(e)?new mG:gG(`runtime.boundary`,n)}var vG=class{constructor(e,t,n,r,i){this.executor=e,this.credentials=t,this.options=n,this.registrationSemaphore=r,this.state=i}upsertRegistration(e){let t=this;return this.runRegistrationOperation(e.registrationId,F(function*(){let n=(yield*t.openState()).registrations.get(e.registrationId);if(n)return yield*t.refreshRegistrationLocked(n);let r={allowedAddresses:new Set,connectionRef:{integration:xb.make(e.executorSlug),name:wb.make(e.connectionName),owner:`org`},credentialIds:new Set,generation:0,spec:e};return yield*t.insertRegistration(r),yield*t.refreshRegistrationLocked(r)}))}refreshRegistration(e){let t=this;return this.runRegistrationOperation(e,F(function*(){let n=yield*t.requireRegistration(e);return yield*t.refreshRegistrationLocked(n)}))}removeRegistration(e){let t=this;return this.registrationSemaphore.withPermit(F(function*(){let n=yield*hb(t.state,t=>{if(t.closed)return[{_tag:`closed`},t];let n=t.registrations.get(e);if(!n)return[{_tag:`missing`},t];let r=new Map(t.registrations);return r.delete(e),[{_tag:`removed`,integrationStillUsed:[...r.values()].some(e=>e.spec.executorSlug===n.spec.executorSlug),registration:n},{...t,registrations:r}]});if(n._tag===`closed`)return yield*I(new uG);n._tag!==`missing`&&(yield*t.executor.connections.remove(n.registration.connectionRef).pipe($f),yield*Tf([...n.registration.credentialIds].map(e=>t.credentials.deleteValue(e)),{discard:!0}),n.integrationStillUsed||(yield*t.executor.mcp.removeServer(n.registration.spec.executorSlug).pipe($f)))}))}callTool(e,t,n,r){let i=this;return Cp(a=>F(function*(){let o={},s=yield*hb(i.state,r=>{if(r.closed)return[{_tag:`closed`},r];if(r.inFlight.has(t))return[{_tag:`conflict`},r];let i=r.registrations.get(e);if(!i)return[{_tag:`missing`},r];if(!i.allowedAddresses.has(n))return[{_tag:`tool_missing`},r];let a={registrationId:e,token:o},s=new Map(r.inFlight);return s.set(t,a),[{_tag:`reserved`},{...r,inFlight:s}]});return s._tag===`closed`?yield*I(new uG):s._tag===`conflict`?yield*I(new dG(t)):s._tag===`missing`?yield*I(new fG(e)):s._tag===`tool_missing`?yield*I(new pG):yield*F(function*(){let e,s=yield*Wf(jf(()=>i.executor.execute(Ab.make(n),r,{onElicitation:n=>Of({catch:e=>gG(`tool.elicitation`,e),try:async()=>sG(await i.options.onElicitation(t,oG(n)))}).pipe(op({onFailure:t=>Mf(()=>(e??=t,{action:`cancel`})),onSuccess:P}))})).pipe(R(e=>gG(`tool.call`,e)))).pipe(Rf(t=>e===void 0?ld(t)?P(t.value):Pf(t.cause):I(e))).pipe(Op({uninterruptible:!1}));return(yield*hb(i.state,e=>{let n=e.inFlight.get(t);if(e.closed||!n||n.token!==o)return[!1,e];let r=new Map(e.inFlight);return r.set(t,{...n,fiber:s}),[!0,{...e,inFlight:r}]}))?yield*a(s_(s)).pipe(L(aG)):(yield*c_(s),yield*I(new mG))}).pipe(_p(i.removeInvocation(t,o)))}))}cancelInvocation(e){let t=this;return F(function*(){let n=yield*hb(t.state,t=>{let n=t.inFlight.get(e);if(!n)return[void 0,t];let r=new Map(t.inFlight);return r.delete(e),[n,{...t,inFlight:r}]});n&&n.fiber&&(yield*c_(n.fiber))})}shutdown(){let e=this;return F(function*(){yield*l_((yield*hb(e.state,e=>e.closed?[[],e]:[[...e.inFlight.values()],{...e,closed:!0,inFlight:new Map}])).flatMap(e=>e.fiber?[e.fiber]:[])),yield*e.registrationSemaphore.withPermit(F(function*(){yield*Tf((yield*hb(e.state,e=>[[...e.registrationGates.values()],{...e,registrationGates:new Map,registrations:new Map}])).map(e=>_d(e,new uG)),{discard:!0}),yield*e.credentials.clear()}))})}runRegistrationOperation(e,t){let n=this;return Cp(r=>F(function*(){let i=yield*md(),a=yield*hb(n.state,t=>{if(t.closed)return[{_tag:`closed`},t];let n=t.registrationGates.get(e);if(n)return[{_tag:`join`,gate:n},t];let r=new Map(t.registrationGates);return r.set(e,i),[{_tag:`owner`,gate:i},{...t,registrationGates:r}]});if(a._tag===`closed`)return yield*I(new uG);if(a._tag===`join`)return yield*r(hd(a.gate));let o=t=>F(function*(){yield*gd(a.gate,t),yield*n.removeRegistrationGate(e,a.gate)});return yield*r(n.registrationSemaphore.withPermit(t.pipe(yp(o)))).pipe(yp(o))}))}refreshRegistrationLocked(e){let t=this,n=e.spec.registrationId;return F(function*(){let r={...e,generation:e.generation+1},i=yield*Wf(F(function*(){yield*t.assertOpen(),yield*t.ensureIntegration(r.spec),r=yield*t.ensureConnection(r),yield*t.ensureApprovalPolicy(r);let e=yield*t.executor.connections.refresh(r.connectionRef);return(yield*t.executor.connections.checkHealth(r.connectionRef)).status===`healthy`?e:yield*I(gG(`registration.health`,{_tag:`McpConnectionUnavailable`}))}));if(ud(i))return ed(i.cause)?yield*Ff(new hG):td(i.cause)?yield*xp:(r={...yield*t.requireRegistration(n),generation:r.generation},yield*t.replaceRegistration(r),ZW(t.options.runtimeEpoch,n,r.generation,Zu(i.cause)));let a={...r,allowedAddresses:new Set(i.value.map(e=>String(e.address)))};return yield*t.replaceRegistration(a),{generation:a.generation,registrationId:n,runtimeEpoch:t.options.runtimeEpoch,status:`available`,tools:i.value.map(nG)}})}ensureIntegration(e){let t=this;return F(function*(){if(yield*t.executor.integrations.get(xb.make(e.executorSlug)))return;if(e.transport.transport===`remote`){let n={authenticationTemplate:e.transport.authentication.kind===`none`?[{kind:`none`,slug:`none`}]:[{headers:Object.fromEntries(Object.entries(e.transport.authentication.placements).map(([e,t])=>[e,[{name:t,type:`variable`}]])),label:`ACP session headers`,slug:`headers`,type:`apiKey`}],endpoint:e.transport.endpoint,name:e.executorSlug,remoteTransport:e.transport.remoteTransport,slug:e.executorSlug,transport:`remote`};yield*t.executor.mcp.addServer(n);return}if(!t.options.allowStdio)return yield*I(gG(`registration.integration`,{_tag:`StdioMcpDisabled`}));let n={args:[...e.transport.args],command:e.transport.command,cwd:e.transport.cwd,envVars:Object.keys(e.transport.env),name:e.executorSlug,slug:e.executorSlug,transport:`stdio`};yield*t.executor.mcp.addServer(n)})}ensureConnection(e){let t=this;return F(function*(){if(yield*t.executor.connections.get(e.connectionRef))return e;let n=e.spec.transport,r=n.transport===`remote`?n.authentication.kind===`headers`?`headers`:`none`:Object.keys(n.env).length>0?`env`:`none`,i=n.transport===`remote`?n.headers:n.env,a=Object.entries(i),o=new Set(e.credentialIds),s=[];for(let[n,r]of a){let i=[`agent-harness`,e.spec.registrationId,s.length].join(`.`);yield*t.credentials.setValue(i,r),o.add(i),s.push([n,{from:{id:Ob.make(i),provider:t.credentials.key}}])}let c={...e,credentialIds:o};yield*t.replaceRegistration(c);let l=s.length===0?{values:{}}:{inputs:Object.fromEntries(s)};return yield*t.executor.connections.create({...c.connectionRef,template:Sb.make(r),...l}),c})}ensureApprovalPolicy(e){let t=this;return F(function*(){let n=[e.spec.executorSlug,e.connectionRef.owner,e.spec.connectionName,`*`].join(`.`);(yield*t.executor.policies.list()).some(e=>e.owner===`org`&&e.pattern===n&&e.action===`approve`)||(yield*t.executor.policies.create({action:`approve`,owner:`org`,pattern:n}))})}requireRegistration(e){let t=this;return F(function*(){return(yield*t.openState()).registrations.get(e)||(yield*I(new fG(e)))})}assertOpen(){return this.openState().pipe(Kf)}openState(){return mb(this.state).pipe(Rf(e=>e.closed?I(new uG):P(e)))}insertRegistration(e){return hb(this.state,t=>{if(t.closed)return[!1,t];let n=new Map(t.registrations);return n.set(e.spec.registrationId,e),[!0,{...t,registrations:n}]}).pipe(Rf(e=>e?Nf:I(new uG)))}replaceRegistration(e){let t=this;return F(function*(){let n=yield*hb(t.state,t=>{if(t.closed)return[{_tag:`closed`},t];if(!t.registrations.has(e.spec.registrationId))return[{_tag:`missing`},t];let n=new Map(t.registrations);return n.set(e.spec.registrationId,e),[{_tag:`replaced`},{...t,registrations:n}]});if(n._tag===`closed`)return yield*I(new uG);if(n._tag===`missing`)return yield*I(new fG(e.spec.registrationId))})}removeRegistrationGate(e,t){return gb(this.state,n=>{if(n.registrationGates.get(e)!==t)return n;let r=new Map(n.registrationGates);return r.delete(e),{...n,registrationGates:r}})}removeInvocation(e,t){return gb(this.state,n=>{if(n.inFlight.get(e)?.token!==t)return n;let r=new Map(n.inFlight);return r.delete(e),{...n,inFlight:r}})}},yG=class extends la()(`agent-harness/ExecutorChildService`){};function bG(e,t,n){let r=t===void 0?void 0:xo({sampled:t.sampled,spanId:t.parentSpanId,traceId:t.traceId}),i={component:`executor`,operation:n,"runtime.role":`executor`};return z(e.pipe(Vf(()=>Up(UW).pipe(Wp({...i,outcome:`success`}))),Qf(()=>Hp(UW).pipe(Wp({...i,outcome:`error`})))),UW,{attributes:{...i},kind:`server`,...r===void 0?{}:{parent:r}})}function xG(e){let t={effectErrors:0,effectLogs:0,effectSpans:0},n=new Map,r=ya(ff,n),i=_f(`agent_harness_effect_logs_total`,{incremental:!0}),a=_f(`agent_harness_effect_errors_total`,{incremental:!0}),o=_f(`agent_harness_effect_spans_total`,{incremental:!0}),s=()=>GW(e,{kind:`metrics`,value:{...t}}),c=Ly(n=>{let r=Array.isArray(n.message)?n.message:[n.message];if(r.length!==1||r[0]!==UW)return;t.effectLogs+=1,i.updateUnsafe(1,n.fiber.context);let o=n.logLevel===`Error`||n.logLevel===`Fatal`?`error`:n.logLevel===`Warn`?`warn`:`info`;o===`error`&&(t.effectErrors+=1,a.updateUnsafe(1,n.fiber.context));let c=n.fiber.currentSpan,l=c?._tag===`Span`?qW(c.traceId,c.spanId):void 0;GW(e,{kind:`log`,value:{annotations:KW(n.fiber.getRef(yd)),level:o,message:UW,...c?._tag===`Span`&&l?{span:{name:UW,sampled:c.sampled,...l}}:{}}}),s()}),l=bo({span(n){let i=new Do(n),c=i.end.bind(i);return i.end=(n,l)=>{if(c(n,l),i.name!==UW)return;t.effectSpans+=1,o.updateUnsafe(1,r),l._tag===`Failure`&&(t.effectErrors+=1,a.updateUnsafe(1,r));let u=qW(i.traceId,i.spanId);if(u){let t=i.parent._tag===`Some`&&/^[0-9a-f]{16}$/.test(i.parent.value.spanId)&&i.parent.value.spanId!==`0000000000000000`?i.parent.value.spanId:void 0;GW(e,{kind:`span`,value:{attributes:KW(i.attributes),durationMs:JW(i.startTime,n),kind:i.kind,name:UW,outcome:l._tag===`Success`?`success`:`error`,...t===void 0?{}:{parentSpanId:t},sampled:i.sampled,...u}})}s()},i}});return Ud(Ry([c]),Ld(Eo,l),Ld(ff,n))}function SG(e,t){let n=II({onElicitation:()=>P({action:`cancel`}),plugins:[zW({dangerouslyAllowStdioMCP:t.allowStdio})],providers:[e.provider],tenant:Fb.make(t.tenantId),toolsSyncTtlMs:null}).pipe(R(e=>gG(`runtime.initialize`,e)),L(e=>e));return zd(yG,F(function*(){return new vG(yield*hp(n,e=>e.close().pipe(Zf)),e,t,yield*v_(1),yield*fb({closed:!1,inFlight:new Map,registrationGates:new Map,registrations:new Map}))}))}async function CG(e,t){let n=await e.runPromiseExit(t);if(ld(n))return n.value;throw _G(n.cause)}var wG=class e{static async create(t,n){let r=By(Wd(SG(new cG,t),xG(t.onTelemetry)));try{return await CG(r,bG(yG.asEffect(),n,`initialize`)),new e(r)}catch(e){throw await r.dispose().catch(()=>void 0),e}}constructor(e){this.managed=e}upsertRegistration(e,t){return this.runOpen(yG.use(t=>t.upsertRegistration(e)),t,`reconcile`)}refreshRegistration(e,t){return this.runOpen(yG.use(t=>t.refreshRegistration(e)),t,`refresh`)}removeRegistration(e,t){return this.runOpen(yG.use(t=>t.removeRegistration(e)),t,`release`)}callTool(e,t,n,r,i){return this.runOpen(yG.use(i=>i.callTool(e,t,n,r)),i,`dispatch`)}cancelInvocation(e,t){return this.closePromise?Promise.resolve():this.run(yG.use(t=>t.cancelInvocation(e)),t,`update`)}close(e){return this.closePromise||=this.closeOnce(e),this.closePromise}async closeOnce(e){let t;try{await this.run(yG.use(e=>e.shutdown()),e,`close`)}catch(e){t=e}try{let e=await Fp(this.managed.disposeEffect);ud(e)&&(t??=_G(e.cause))}catch(e){t??=gG(`runtime.close`,e)}if(t!==void 0)throw t}runOpen(e,t,n){return this.closePromise?Promise.reject(new uG):this.run(e,t,n)}run(e,t,n){return CG(this.managed,bG(e,t,n))}},TG=5e3,EG=250,DG=4*1024,OG=50,kG=class extends Error{constructor(){super(`stdio process-group anchor cleanup failed`),this._tag=`StdioProcessGroupAnchorCleanupError`,this.name=this._tag}};function AG(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function jG(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===4&&t.type===`ready`&&AG(t.anchorPid)&&AG(t.guardianPid)&&AG(t.targetProcessGroupId)}function MG(e,t,n,r){if(!e.stdout)return Promise.reject(Error(`stdio process-group anchor did not expose a ready pipe`));let i=e.stdout;return i.setEncoding(`utf8`),new Promise((a,o)=>{let s=``,c=!1,l=t=>{c||(c=!0,clearTimeout(p),e.removeListener(`error`,u),e.removeListener(`exit`,d),i.removeListener(`data`,f),t?o(t):(i.resume(),a()))},u=e=>l(e),d=()=>l(Error(`stdio process-group anchor exited before ready`)),f=r=>{if(s+=r,Buffer.byteLength(s,`utf8`)>DG){l(Error(`stdio process-group anchor handshake was oversized`));return}let i=s.indexOf(`
|
|
74
|
-
`);if(!(i<0))try{let r=JSON.parse(s.slice(0,i));if(s.slice(i+1).trim()!==``||!
|
|
73
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=DH(e,t,n,r,i,a,o,l,c);if(u.valid||O.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:O.length===0,errors:O}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?GV(e,h)||O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>GV(e,t))||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;DH(e,v,n,r,i,a,o,t).valid&&O.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Oe=[];if(y!==void 0){let t=`${s}/anyOf`,l=O.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=DH(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u||=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=O.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=DH(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u&&=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=O.length,u=x.filter((s,l)=>{let u=Object.create(c),d=DH(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return O.push(...d.errors),d.valid&&Oe.push(u),d.valid}).length;u===1?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Oe),S!==void 0){let t=`${s}/if`;if(DH(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=DH(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(ee!==void 0){let l=DH(e,ee,n,r,i,a,o,`${s}/else`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||O.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ae!==void 0&&t.length<ae&&O.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ae} properties.`}),T!==void 0&&t.length>T&&O.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${T} properties.`}),oe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${KV(s)}`,c=DH(s,oe,n,r,i,a,e,t);c.valid||O.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(se!==void 0){let t=`${s}/dependantRequired`;for(let n in se)if(n in e){let r=se[n];for(let i of r)i in e||O.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(ce!==void 0)for(let t in ce){let l=`${s}/dependentSchemas`;if(t in e){let s=DH(e,ce[t],n,r,i,a,o,`${l}/${KV(t)}`,c);s.valid||O.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(le!==void 0){let t=`${s}/dependencies`;for(let s in le)if(s in e){let c=le[s];if(Array.isArray(c))for(let n of c)n in e||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=DH(e,c,n,r,i,a,o,`${t}/${KV(s)}`);l.valid||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ne!==void 0){let t=`${s}/properties`;for(let s in ne){if(!(s in e))continue;let d=`${o}/${KV(s)}`,f=DH(e[s],ne[s],n,r,i,a,d,`${t}/${KV(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,O.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&re!==void 0){let t=`${s}/patternProperties`;for(let s in re){let d=new RegExp(s,`u`),f=re[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${KV(p)}`,h=DH(e[p],f,n,r,i,a,m,`${t}/${KV(s)}`);h.valid?c[p]=l[p]=!0:(u=i,O.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&ie!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${KV(s)}`,f=DH(e[s],ie,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,O.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&w!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${KV(s)}`,u=DH(e[s],w,n,r,i,a,l,t);u.valid?c[s]=!0:O.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){_e!==void 0&&e.length>_e&&O.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${_e}).`}),ge!==void 0&&e.length<ge&&O.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ge}).`});let t=e.length,l=0,u=!1;if(ue!==void 0){let d=`${s}/prefixItems`,f=Math.min(ue.length,t);for(;l<f;l++){let t=DH(e[l],ue[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(de!==void 0){let d=`${s}/items`;if(Array.isArray(de)){let s=Math.min(de.length,t);for(;l<s;l++){let t=DH(e[l],de[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=DH(e[l],de,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&fe!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=DH(e[l],fe,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,O.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(pe!==void 0)if(t===0&&me===void 0)O.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(me!==void 0&&t<me)O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${me}).`});else{let l=`${s}/contains`,u=O.length,d=0;for(let s=0;s<t;s++){let t=DH(e[s],pe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):O.push(...t.errors)}d>=(me||0)&&(O.length=u),me===void 0&&he===void 0&&d===0?O.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):me!==void 0&&d<me?O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${me} items matching schema. Only ${d} items were found.`}):he!==void 0&&d>he&&O.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${he} items matching schema. ${d} items were found.`})}if(!u&&E!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=DH(e[l],E,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||O.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ve)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&GV(r,t))&&(O.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(ye!==void 0&&(xe===!0&&e<=ye||e<ye)&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${xe?`or equal to `:``} ${ye}.`}),be!==void 0&&(D===!0&&e>=be||e>be)&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${D?`or equal to `:``} ${be}.`})):(ye!==void 0&&e<ye&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ye}.`}),be!==void 0&&e>be&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${be}.`}),xe!==void 0&&e<=xe&&O.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${xe}.`}),D!==void 0&&e>=D&&O.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${D}.`})),Se!==void 0){let t=e%Se;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Se-t)>=1.1920929e-7&&O.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Se}.`})}}else if(u===`string`){let t=Ce===void 0&&we===void 0?0:EH(e);Ce!==void 0&&t<Ce&&O.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Ce}).`}),we!==void 0&&t>we&&O.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${we}).`}),Te!==void 0&&!new RegExp(Te,`u`).test(e)&&O.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),te!==void 0&&hH[te]&&!hH[te](e)&&O.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${te}".`})}return{valid:O.length===0,errors:O}}var OH=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=QV(e)}validate(e){return DH(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),QV(e,this.lookup)}},kH=class{constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new OH(e,this.draft,this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}},AH=W({tools:G(W({name:U,description:V(K(U)),inputSchema:V(Lv),parameters:V(Lv),outputSchema:V(Lv),annotations:V(RL)}))}),jH=W({tools:G(Lv),nextCursor:V(K(U))}),MH=W({name:V(U),version:V(U)}),NH=B(AH),PH=B(jH),FH=B(MH),IH=e=>PH(e),LH=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`tool`,RH=(e,t)=>{let n=LH(e),r=(t.get(n)??0)+1;return t.set(n,r),r===1?n:`${n}_${r}`},zH=(e,t)=>{let n=new Map,r=NH(e).pipe(fi(e=>e.tools),ci(()=>[]));return{server:FH(t?.serverInfo).pipe(fi(e=>({name:e.name??null,version:e.version??null,instructions:t?.instructions??null})),ui),tools:r.flatMap(e=>{let t=e.name.trim();return t?[{toolId:RH(t,n),toolName:t,description:e.description??null,inputSchema:e.inputSchema??e.parameters,outputSchema:e.outputSchema,annotations:e.annotations}]:[]})}},BH=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``),VH=e=>URL.canParse(e)?new URL(e).hostname:null,HH=e=>e.trim().split(/[\\/]/).pop()??e.trim(),UH=e=>{if(e.name?.trim())return BH(e.name)||`mcp`;let t=e.endpoint?.trim()?VH(e.endpoint):null;return t?BH(t)||`mcp`:e.command?.trim()&&BH(HH(e.command))||`mcp`},WH=B(W({message:U})),GH=e=>si(WH(e),{onNone:()=>void 0,onSome:({message:e})=>{let t=/^Error POSTing to endpoint \(HTTP ([1-5][0-9]{2})\):/.exec(e);if(t)return Number(t[1])}}),KH=e=>{if(!(e instanceof UV))return;let t=e.code;return t!==void 0&&t>=100&&t<=599?t:void 0},qH=e=>KH(e)??GH(e),JH=/Server returned 403 after trying upscoping/,YH=e=>si(WH(e),{onNone:()=>!1,onSome:({message:e})=>$I(e)||JH.test(e)}),XH=(e,t)=>{let n=new URL(e);for(let[e,r]of Object.entries(t))n.searchParams.set(e,r);return n},ZH=new Set([`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`]),QH=e=>{let t=(e??`GET`).toUpperCase();return ZH.has(t)?t:`POST`},$H=e=>e?new Headers(e):new Headers,eU=e=>Object.fromEntries(e.entries()),tU=async(e,t,n)=>{if(n==null)return e;let r=t.get(`content-type`)??void 0;return typeof n==`string`?tk(e,n,r):n instanceof URLSearchParams?tk(e,n.toString(),r??`application/x-www-form-urlencoded;charset=UTF-8`):n instanceof Uint8Array?ek(e,n,r):n instanceof ArrayBuffer?ek(e,new Uint8Array(n),r):ek(e,new Uint8Array(await new Response(n).arrayBuffer()),r)},nU=e=>{if(e.reason!==void 0)return e.reason;let t=Error(`The operation was aborted`);return t.name=`AbortError`,t},rU=e=>async(t,n)=>{let r=$H(n?.headers),i=await tU(VO(QH(n?.method))(t,{headers:eU(r)}),r,n?.body),a=Np(F(function*(){let e=yield*(yield*uk).execute(i),t=new Headers;for(let[n,r]of Object.entries(e.headers))r!==void 0&&t.set(n,r);let n=e.status===204||e.status===205||e.status===304?null:Py(e.stream);return new Response(n,{status:e.status,headers:t})}).pipe(lp(e))).then(e=>{if(e.status===403){let t=e.headers.get(`www-authenticate`);if(t!==null&&eL({headers:{"www-authenticate":t}})!==null)throw new EL({message:`MCP server rejected the call: the OAuth grant does not cover the required scope`})}return e});if(a.catch(()=>void 0),!n?.signal)return a;if(n.signal.aborted)return Promise.reject(nU(n.signal));let o=new Promise((e,t)=>{n.signal?.addEventListener(`abort`,()=>t(nU(n.signal)),{once:!0})});return Promise.race([a,o])},iU=()=>new Rz({name:`executor-mcp`,version:`0.1.0`},{capabilities:{elicitation:{form:{},url:{}}},jsonSchemaValidator:new kH}),aU=e=>({client:e,close:()=>e.close()}),oU=(e,t,n)=>{if(yt(n,`McpOAuthReauthorizationRequired`))return new TL({message:`MCP OAuth re-authorization required`});if(yt(n,`McpInsufficientScopeError`))return new SL({transport:e,message:`${t} (HTTP 403: insufficient scope)`,httpStatus:403,insufficientScope:!0});let r=qH(n);return new SL({transport:e,message:r===void 0?t:`${t} (HTTP ${r})`,...r===void 0?{}:{httpStatus:r}})},sU=e=>F(function*(){let t=iU(),n=e.createTransport();return yield*Of({try:()=>t.connect(n),catch:t=>oU(e.transport,`Failed connecting via ${e.transport}`,t)}).pipe(z(`plugin.mcp.connection.handshake`,{attributes:{"plugin.mcp.transport":e.transport}})),aU(t)}),cU=e=>{if(e.transport===`stdio`){let t=e.command.trim();return t?F(function*(){let{createStdioTransport:n}=yield*Of({try:()=>import(`./stdio-connector-AA5S6UUJ.mjs`),catch:()=>new SL({transport:`stdio`,message:`Failed to load stdio transport module`})});return yield*sU({transport:`stdio`,createTransport:()=>n({command:t,args:e.args,env:e.env,cwd:e.cwd?.trim().length?e.cwd.trim():void 0})})}):I(new SL({transport:`stdio`,message:`MCP stdio transport requires a command`}))}let t=e.headers??{},n=e.remoteTransport??`auto`,r=Object.keys(t).length>0?{headers:t}:void 0,i=e.httpClientLayer?rU(e.httpClientLayer):void 0,a=XH(e.endpoint,e.queryParams??{}),o=sU({transport:`streamable-http`,createTransport:()=>new WV(a,{requestInit:r,authProvider:e.authProvider,fetch:i})}),s=sU({transport:`sse`,createTransport:()=>new BV(a,{requestInit:r,authProvider:e.authProvider,fetch:i})});return n===`streamable-http`?o:n===`sse`?s:o.pipe(qf(e=>yt(e,`McpOAuthReauthorizationRequired`)||e.httpStatus===401||e.httpStatus===403?I(e):s))},lU=300*1e3,uU=e=>Of(()=>e.close()).pipe($f),dU=e=>yt(e,`McpInvocationError`),fU=e=>yt(e,`McpConnectionError`)?!0:dU(e)?e.transportFailure===!0||e.status===400||e.status===401||e.status===404||e.status===408:!1,pU=e=>{if(ld(e))return!1;let t=e.cause.reasons.filter(Xu);return t.length===0?!0:t.some(e=>fU(e.error))},mU=()=>{let e=new Map,t=(t,n,r)=>F(function*(){if(r)return{connection:yield*n,reused:!1};let i=yield*Mf(()=>{let n=e.get(t);return n?(e.delete(t),Date.now()-n.idleSince>=lU?{connection:void 0,expired:n.connection}:{connection:n.connection,expired:void 0}):{connection:void 0,expired:void 0}});return i.expired&&(yield*uU(i.expired)),i.connection?{connection:i.connection,reused:!0}:{connection:yield*n,reused:!1}}),n=(t,n,r)=>F(function*(){if(pU(r)){yield*uU(n.connection);return}let i=yield*Mf(()=>{if(e.has(t))return n.connection;e.set(t,{connection:n.connection,idleSince:Date.now()})});i&&(yield*uU(i))});return{withConnection:(e,r,i)=>{let a=!1,o=o=>gp(t(e,r,o),e=>(o||(a=e.reused),i(e.connection)),(t,r)=>n(e,t,r));return o(!1).pipe(qf(e=>a&&dU(e)&&e.status===404?o(!0):I(e)))},close:()=>F(function*(){yield*Ef(yield*Mf(()=>{let t=[...e.values()].map(e=>e.connection);return e.clear(),t}),uU,{concurrency:`unbounded`,discard:!0})})}},hU=100,gU=Za(15),_U=e=>F(function*(){let t=[],n;for(let r=0;r<hU;r++){let r=n===void 0?void 0:{cursor:n},i=IH(yield*Of({try:()=>e.client.listTools(r),catch:()=>new CL({stage:`list_tools`,message:`Failed listing MCP tools`})}));if(ai(i))return yield*new CL({stage:`list_tools`,message:`MCP listTools response did not match the expected schema`});t.push(...i.value.tools);let a=i.value.nextCursor;if(a==null||a===``)break;n=a}return zH({tools:t},{serverInfo:e.client.getServerVersion?.(),instructions:e.client.getInstructions?.()})}),vU=(e,t=no(gU))=>F(function*(){let t=yield*e.pipe(R(e=>{let t=yt(e,`McpConnectionError`)?e.httpStatus:void 0;return new CL({stage:`connect`,message:`Failed connecting to MCP server: ${e.message}`,...t===void 0?{}:{httpStatus:t}})}));return yield*_U(t).pipe(yp(()=>yU(t)))}).pipe(rp({duration:Xa(t),orElse:()=>I(new CL({stage:`connect`,message:`MCP discovery timed out after ${t}ms`}))})),yU=e=>$f(Of({try:()=>e.close(),catch:()=>new CL({stage:`list_tools`,message:`Failed closing MCP connection`})})),bU=B(Uv(U,Lv)),xU=e=>ci(bU(e),()=>({})),SU=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),CU=(e,t)=>{let n=SU(t);return RegExp(`(?:unknown tool:?\\s*"?${n}"?|tool\\s+"?${n}"?\\s+(?:not found|is not available|does not exist))`,`i`).test(e)},wU=(e,t)=>e instanceof h&&(e.code===D.InvalidParams||e.code===D.MethodNotFound)&&CU(e.message,t),TU=kv(Kv([W({mode:H(`url`),message:U,url:U,elicitationId:V(U),id:V(U)}),W({mode:V(H(`form`)),message:U,requestedSchema:Uv(U,Lv)})])),EU=e=>e.mode===`url`?mx.make({message:e.message,url:e.url,elicitationId:Mb.make(e.elicitationId??e.id??``)}):px.make({message:e.message,requestedSchema:e.requestedSchema}),DU=(e,t)=>{e.setRequestHandler(O,async e=>{let n=await Fp(t(EU(TU(e.params))));if(ld(n)){let e=n.value;return{action:e.action,...e.action===`accept`&&e.content?{content:e.content}:{}}}let r=n.cause.reasons.find(Xu);if(r){let e=r.error;if(yt(e,`ElicitationDeclinedError`))return{action:j(e,`action`)&&e.action===`cancel`?`cancel`:`decline`}}throw Zu(n.cause)})},OU=(e,t)=>{t&&e.setNotificationHandler(f,()=>{t()})},kU=(e,t,n,r,i)=>F(function*(){return DU(e.client,r),OU(e.client,i),yield*Of({try:()=>e.client.callTool({name:t,arguments:n}),catch:e=>{if(yt(e,`McpOAuthReauthorizationRequired`))return new TL({message:`MCP OAuth re-authorization required`});if(yt(e,`McpInsufficientScopeError`))return new wL({toolName:t,message:`MCP tool call failed for ${t}`,status:403,insufficientScope:!0,transportFailure:!0});let n=qH(e),r=e instanceof h;return new wL({toolName:t,message:`MCP tool call failed for ${t}`,...n===void 0?{}:{status:n},...r?{}:{transportFailure:!0},...wU(e,t)?{unknownTool:!0}:{},...n===403&&YH(e)?{insufficientScope:!0}:{}})}}).pipe(z(`plugin.mcp.client.call_tool`,{attributes:{"mcp.tool.name":t}}))}),AU=e=>F(function*(){let t=xU(e.args),n=n=>kU(n,e.toolName,t,e.elicit,e.onToolListChanged);return e.connectionPool&&e.connectionPoolKey?yield*e.connectionPool.withConnection(e.connectionPoolKey,e.connector.pipe(z(`plugin.mcp.connection.acquire`,{attributes:{"plugin.mcp.transport":e.transport}})),n):yield*n(yield*hp(e.connector.pipe(z(`plugin.mcp.connection.acquire`,{attributes:{"plugin.mcp.transport":e.transport}})),t=>$f(Of({try:()=>t.close(),catch:()=>new SL({transport:e.transport,message:`Failed to close MCP connection`})}))))}).pipe(mp,z(`plugin.mcp.invoke`,{attributes:{"mcp.tool.name":e.toolName,"plugin.mcp.tool_id":e.toolId,"plugin.mcp.transport":e.transport}})),jU=JSON.stringify({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2025-06-18`,capabilities:{},clientInfo:{name:`executor-probe`,version:`0`}}}),MU=(e,t)=>{let n=e[t];if(n!==void 0)return n;let r=t.toLowerCase();for(let[t,n]of Object.entries(e))if(t.toLowerCase()===r)return n;return null},NU=class extends Gd(`ProbeTransportError`){},PU=B(ly(Lv)),FU=e=>{if(!e)return null;let t=PU(e);if(ai(t))return null;let n=t.value;return typeof n!=`object`||!n||Array.isArray(n)?null:n},IU=e=>{let t=FU(e);return!t||t.jsonrpc!==`2.0`?!1:`result`in t||`error`in t||`method`in t},LU=e=>{let t=FU(e);return!t||Array.isArray(t.errors)?!1:typeof t.error==`string`},RU=B(ly(W({resource:U,authorization_servers:G(U)}))),zU=e=>{let t=e.pathname===`/`?``:e.pathname;return`${e.origin}/.well-known/oauth-protected-resource${t}`},BU=(e,t)=>{if(!URL.canParse(e))return!1;let n=new URL(e);if(n.origin!==t.origin)return!1;let r=n.pathname.replace(/\/+$/,``),i=t.pathname.replace(/\/+$/,``);return i===r||i.startsWith(`${r}/`)},VU=(e,t,n)=>F(function*(){let r=yield*e.execute(HO(zU(t)).pipe(KO(`accept`,`application/json`))).pipe(np(Xa(n)));if(r.status<200||r.status>=300)return!1;let i=RU(yield*r.text.pipe(np(Xa(n)),qf(()=>P(``))));return ai(i)||i.value.authorization_servers.length===0?!1:BU(i.value.resource,t)}).pipe(qf(()=>P(!1))),HU=B(W({message:U})),UU=e=>{let t=HU(e);return oi(t)?t.value.message:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:typeof e==`symbol`?e.description??`symbol`:e===null?`null`:e===void 0?`undefined`:`fetch failed`},WU=(e,t={})=>F(function*(){let n=t.timeoutMs??8e3;return yield*F(function*(){let r=yield*uk,i=e=>e.text.pipe(np(Xa(n)),qf(()=>P(``))),a=(e,t)=>F(function*(){let a=MU(e.headers,`content-type`)??``,s=/^\s*text\/event-stream\b/i.test(a);if(e.status===401){let t=MU(e.headers,`www-authenticate`);if(!t||!/^\s*bearer\b/i.test(t))return(yield*VU(r,o,n))?{kind:`mcp`,requiresAuth:!0}:{kind:`not-mcp`,category:`auth-required`,reason:`401 without Bearer WWW-Authenticate — not an MCP auth challenge`};if(/(?:^|[\s,])resource_metadata\s*=/i.test(t)||/(?:^|[\s,])error\s*=/i.test(t)||s)return{kind:`mcp`,requiresAuth:!0};let a=yield*i(e);return!IU(a)&&!LU(a)?(yield*VU(r,o,n))?{kind:`mcp`,requiresAuth:!0}:{kind:`not-mcp`,category:`auth-required`,reason:`401 + Bearer without resource_metadata, JSON-RPC body, or OAuth error body`}:{kind:`mcp`,requiresAuth:!0}}return e.status>=200&&e.status<300?t===`GET`?s?{kind:`mcp`,requiresAuth:!1}:{kind:`not-mcp`,category:`wrong-shape`,reason:`GET response is not an SSE stream`}:s||IU(yield*i(e))?{kind:`mcp`,requiresAuth:!1}:{kind:`not-mcp`,category:`wrong-shape`,reason:`2xx POST body is not a JSON-RPC envelope`}:null}),o=new URL(e);for(let[e,n]of Object.entries(t.queryParams??{}))o.searchParams.set(e,n);let s=UO(o.toString()).pipe(KO(`content-type`,`application/json`),KO(`accept`,`application/json, text/event-stream`),tk(jU,`application/json`));for(let[e,n]of Object.entries(t.headers??{}))s=KO(s,e,n);let c=yield*r.execute(s).pipe(np(Xa(n))),l=yield*a(c,`POST`);if(l)return l;if([404,405,406,415].includes(c.status)){let e=HO(o.toString()).pipe(KO(`accept`,`text/event-stream`));for(let[n,r]of Object.entries(t.headers??{}))e=KO(e,n,r);let i=yield*a(yield*r.execute(e).pipe(np(Xa(n))),`GET`);if(i)return i}return{kind:`not-mcp`,category:`wrong-shape`,reason:`unexpected status ${c.status} for initialize`}}).pipe(lp(t.httpClientLayer??wk),R(e=>new NU({reason:UU(e),cause:e})),qf(e=>P({kind:`unreachable`,reason:e.reason})))}).pipe(z(`mcp.plugin.probe_shape`)),GU=`mcp`,KU=e=>{if(e.httpStatus!==void 0)return $b(e.httpStatus)===`expired`?`expired`:`degraded`;let t=e.message.toLowerCase();return t.includes(`oauth re-authorization`)||t.includes(`unauthorized`)||t.includes(`forbidden`)?`expired`:`degraded`},qU=e=>{let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:null},JU=(e,t)=>{let n=new Set,r=qU(e);r&&n.add(r);let i=t==null?null:qU(t.description);return i&&n.add(i),n},YU=(e,t)=>`${e}:${String(t)}`,XU=(e,t,n)=>!t.has(String(e.slug))||!n||n.transport!==`remote`||!n.authenticationTemplate.some(e=>e.kind===`oauth2`)?!1:e.grant===`authorization_code`&&(e.resource??null)===n.endpoint,ZU=B(W({mcp:W({toolName:U,upstream:V(W({title:V(U),readOnlyHint:V(Vv),destructiveHint:V(Vv),idempotentHint:V(Vv),openWorldHint:V(Vv)}))})})),QU=e=>si(ZU(e),{onNone:()=>null,onSome:e=>e.mcp}),$U=Kv([W({transport:V(H(`remote`)),name:U,description:V(U),endpoint:U,remoteTransport:V(DL),headers:V(Uv(U,U)),queryParams:V(Uv(U,U)),slug:V(U),authenticationTemplate:V(G(jL)),auth:V(kL)}),W({transport:H(`stdio`),name:U,description:V(U),command:U,args:V(G(U)),envVars:V(G(U)),env:V(Uv(U,U)),cwd:V(U),slug:V(U)})]),eW=W({slug:U});W({authenticationTemplate:G(jL),mode:V(qv([`merge`,`replace`]))});var tW=W({endpoint:U,headers:V(Uv(U,U)),queryParams:V(Uv(U,U))}),nW=W({connected:Vv,requiresAuthentication:Vv,requiresOAuth:Vv,supportsDynamicRegistration:Vv,name:U,slug:U,toolCount:K(Bv),serverName:K(U),instructions:K(U)}),rW=W({slug:U}),iW=W({integration:K(Lv)}),aW=e=>wv(Ev(e)),oW=aW($U),sW=aW(eW),cW=aW(tW),lW=aW(nW),uW=aW(rW),dW=aW(iW),fW=(e,t,n)=>$M.fail({code:e,message:t,...n===void 0?{}:{details:n}}),pW=e=>e.status===403&&e.insufficientScope===!0?iN({code:`oauth_scope_insufficient`,message:`MCP server rejected connection "${e.connection}" with HTTP 403: the connection's OAuth grant does not cover the scope this tool requires. Re-authenticating with the same grant will return the same error; reconnect with broader access.`,integration:{id:e.integration},credential:{kind:`oauth`,label:e.connection},status:e.status,upstream:{status:e.status}}):iN({code:`connection_rejected`,message:e.status===403?`MCP server rejected connection "${e.connection}" with HTTP 403. The credential may lack access or required scope; re-authenticate or update the connection before retrying this tool.`:`MCP server rejected connection "${e.connection}" with HTTP 401. Re-authenticate or update the connection before retrying this tool.`,integration:{id:e.integration},credential:{kind:`upstream`,label:e.connection},status:e.status,upstream:{status:e.status}}),mW=e=>iN({code:`oauth_reauth_required`,message:`OAuth connection "${e.connection}" requires reauthorization before retrying this MCP tool.`,integration:{id:e.integration},credential:{kind:`oauth`,label:e.connection}}),hW=e=>xb.make(e),gW=e=>e.slug??UH({name:e.name,endpoint:e.transport===`stdio`?void 0:e.endpoint,command:e.transport===`stdio`?e.command:void 0}),_W=`env`,vW=e=>{let t=new Set(e.envVars??[]);for(let n of Object.keys(e.env??{}))t.add(n);return[...t]},yW=e=>{if(e.transport===`stdio`){let t=vW(e);return{transport:`stdio`,command:e.command,args:e.args?[...e.args]:void 0,cwd:e.cwd,authenticationTemplate:t.length>0?[{slug:_W,kind:`stdio_env`,vars:t}]:[{slug:`none`,kind:`none`}]}}return{transport:`remote`,endpoint:e.endpoint,remoteTransport:e.remoteTransport??`auto`,queryParams:e.queryParams,headers:e.headers,authenticationTemplate:e.authenticationTemplate?PL(e.authenticationTemplate):[AL(e.auth??{kind:`none`})]}},bW=ce(Ee),xW=e=>{let t=bW.properties?.structuredContent??{};return{...bW,properties:{...bW.properties,structuredContent:e===void 0?t:e,isError:{const:!1}},required:e===void 0?[`content`]:[`content`,`structuredContent`]}},SW=e=>{let t=e.annotations?.destructiveHint===!0,n={toolName:e.toolName,...e.annotations?{upstream:e.annotations}:{}},r={requiresApproval:t,...t?{approvalDescription:e.annotations?.title??e.toolName}:{},mcp:n};return{name:jb.make(e.toolId),description:e.description??`MCP tool: ${e.toolName}`,inputSchema:e.inputSchema,outputSchema:xW(e.outputSchema),annotations:r}},CW=W({type:H(`text`),text:U}),wW=W({isError:V(Vv),content:V(G(Lv))}),TW=B(CW),EW=B(wW),DW=e=>{if(Array.isArray(e))for(let t of e){let e=di(TW(t));if(e!==void 0&&e.text.length>0)return e.text}return`MCP tool returned an error`},OW=(e,t)=>$M.fail({code:`mcp_tool_unknown`,message:`The MCP server no longer provides tool "${e}". Its tool catalog changed; list tools again for the current set.`,details:{integration:String(t.integration),connection:String(t.connection)}}),kW=(e,t)=>{let n=RegExp(`(?:^|[^a-z0-9])${t}(?:$|[^a-z0-9])`,`i`);return n.test(e.hostname)||n.test(e.pathname)},AW=e=>e.kind===`unreachable`?`Couldn't reach this URL. Check the address, your network, and that the server is running.`:`This URL doesn't appear to host an MCP server. Double-check the address, including the path.`,jW=e=>({get redirectUrl(){return`http://localhost/oauth/callback`},get clientMetadata(){return{redirect_uris:[`http://localhost/oauth/callback`],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`,client_name:`Executor`}},clientInformation:()=>void 0,saveClientInformation:()=>void 0,tokens:()=>({access_token:e,token_type:`Bearer`}),saveTokens:()=>void 0,redirectToAuthorization:async()=>{throw new TL({message:`MCP OAuth re-authorization required`})},saveCodeVerifier:()=>void 0,codeVerifier:()=>{throw Error(`No active PKCE verifier`)},saveDiscoveryState:()=>void 0,discoveryState:()=>void 0}),MW=(e,t)=>{let n=e.authenticationTemplate??[];if(t!==null){let e=n.find(e=>e.slug===t);if(e)return e}return n.length===1?n[0]:void 0},NW=(e,t,n,r,i)=>{if(e.transport===`stdio`){if(!r)return I(new SL({transport:`stdio`,message:"MCP stdio transport is disabled. Enable it by passing `dangerouslyAllowStdioMCP: true` to mcpPlugin() — only safe for trusted local contexts."}));let i=MW(e,n),a={...e.env??{}};if(i?.kind===`stdio_env`)for(let e of i.vars){let n=t[e];n!=null&&(a[e]=n)}return P({transport:`stdio`,command:e.command,args:e.args,env:Object.keys(a).length>0?a:void 0,cwd:e.cwd})}let a={...e.headers??{}},o={...e.queryParams??{}},s,c=MW(e,n);if(c?.kind===`apikey`){let e=sL(c.placements,t);Object.assign(a,e.headers),Object.assign(o,e.queryParams)}else if(c?.kind===`oauth2`){let e=t[nL];e!=null&&(s=jW(e))}return P({transport:`remote`,endpoint:e.endpoint,remoteTransport:e.remoteTransport??`auto`,queryParams:Object.keys(o).length>0?o:void 0,headers:Object.keys(a).length>0?a:void 0,authProvider:s,httpClientLayer:i})},PW=e=>Object.fromEntries(Object.entries(e??{}).filter(e=>e[1]!==void 0).sort(([e],[t])=>e<t?-1:+(e>t))),FW=(e,t,n)=>JSON.stringify({endpoint:e.endpoint,transport:e.transport,remoteTransport:e.remoteTransport,headers:PW(e.headers),queryParams:PW(e.queryParams),template:t,values:PW(n)}),IW=e=>({id:e.slug,label:`Environment variables`,kind:`apikey`,template:e.slug,placements:e.vars.map(e=>({carrier:`env`,name:e,prefix:``,variable:e}))}),LW=e=>{let t=LL(e.config);return t?(t.authenticationTemplate??[]).map(e=>e.kind===`stdio_env`?IW(e):e.kind===`apikey`?fL(e):e.kind===`oauth2`?{id:e.slug,label:`OAuth`,kind:`oauth`,template:e.slug,oauth:{discoveryUrl:t.transport===`remote`?t.endpoint:void 0,supportsDynamicRegistration:!0}}:pL(e.slug)):[]},RW=e=>{let t=LL(e.config);return!t||t.transport===`stdio`?{}:{url:t.endpoint}},zW=Xk(e=>{let t=e?.dangerouslyAllowStdioMCP??!1,n=mU();return{id:GU,packageName:`@executor-js/plugin-mcp`,remoteToolCatalog:!0,integrationPresets:(t?tL:tL.filter(e=>!(`transport`in e&&e.transport===`stdio`))).map(e=>({id:e.id,name:e.name,summary:e.summary,...`url`in e&&e.url?{url:e.url}:{},...`endpoint`in e&&e.endpoint?{endpoint:e.endpoint}:{},...e.icon?{icon:e.icon}:{},...e.featured?{featured:e.featured}:{},transport:`transport`in e&&e.transport===`stdio`?`stdio`:`remote`,...`command`in e?{command:e.command}:{},...`args`in e&&e.args?{args:[...e.args]}:{},...`env`in e&&e.env?{env:e.env}:{}})),clientConfig:{allowStdio:t},storage:()=>({}),close:()=>n.close(),extension:t=>{let n=e?.httpClientLayer??t.httpClientLayer;return{probeEndpoint:e=>F(function*(){let r=(typeof e==`string`?e:e.endpoint).trim();if(!r)return yield*new SL({transport:`remote`,message:`Endpoint URL is required`});let i=yield*If({try:()=>new URL(r).hostname,catch:()=>`mcp`}).pipe(tp(()=>`mcp`)),a=UH({endpoint:r}),o=typeof e==`string`?void 0:e.headers,s=typeof e==`string`?void 0:e.queryParams,c=yield*vU(cU({transport:`remote`,endpoint:r,headers:o,queryParams:s,httpClientLayer:n})).pipe(L(e=>({ok:!0,manifest:e})),qf(()=>P({ok:!1,manifest:null})),z(`mcp.plugin.discover_tools`));if(c.ok&&c.manifest)return{connected:!0,requiresAuthentication:!1,requiresOAuth:!1,supportsDynamicRegistration:!1,name:c.manifest.server?.name??i,slug:a,toolCount:c.manifest.tools.length,serverName:c.manifest.server?.name??null,instructions:c.manifest.server?.instructions??null};let l=yield*WU(r,{httpClientLayer:n,headers:o,queryParams:s});if(l.kind===`unreachable`)return yield*new SL({transport:`remote`,message:AW(l)});if(l.kind===`not-mcp`)return l.category===`wrong-shape`?yield*new SL({transport:`remote`,message:AW(l)}):{connected:!1,requiresAuthentication:!0,requiresOAuth:!1,supportsDynamicRegistration:!1,name:i,slug:a,toolCount:null,serverName:null,instructions:null};let u=yield*t.oauth.probe({url:r}).pipe(L(e=>({ok:!0,oauth:e})),qf(()=>P({ok:!1,oauth:null})),z(`mcp.plugin.probe_oauth`));return u.ok?{connected:!1,requiresAuthentication:!0,requiresOAuth:!0,supportsDynamicRegistration:u.oauth.registrationEndpoint!=null,name:i,slug:a,toolCount:null,serverName:null,instructions:null}:l.requiresAuth?{connected:!1,requiresAuthentication:!0,requiresOAuth:!1,supportsDynamicRegistration:!1,name:i,slug:a,toolCount:null,serverName:null,instructions:null}:yield*new SL({transport:`remote`,message:`This endpoint looks like MCP, but Executor couldn't discover tools from it. Check the URL and try again.`})}).pipe(z(`mcp.plugin.probe_endpoint`,{attributes:{"mcp.endpoint":typeof e==`string`?e:e.endpoint}})),addServer:e=>F(function*(){let n=gW(e),r=yW(e);if(yield*t.core.integrations.get(hW(n)))return yield*new Ax({slug:hW(n)});if(yield*t.core.integrations.register({slug:hW(n),name:e.name,description:e.description?.trim()||e.name,config:r,canRemove:!0,canRefresh:!0}).pipe(z(`mcp.plugin.register_integration`,{attributes:{"mcp.integration.slug":n}})),e.transport===`stdio`){let r=e.env!=null&&Object.keys(e.env).length>0,i=vW(e).length>0;(r||!i)&&(yield*t.connections.create({owner:`org`,name:wb.make(`default`),integration:hW(n),template:Sb.make(r?_W:`none`),values:r?{...e.env}:{}}).pipe(Yf({IntegrationNotFoundError:e=>I(new SL({transport:`stdio`,message:e.message})),CredentialProviderNotRegisteredError:e=>I(new SL({transport:`stdio`,message:e.message})),InvalidConnectionInputError:e=>I(new SL({transport:`stdio`,message:e.message}))}),z(`mcp.plugin.bootstrap_stdio_connection`,{attributes:{"mcp.integration.slug":n}})))}return{slug:n}}).pipe(z(`mcp.plugin.add_server`,{attributes:{"mcp.server.transport":e.transport??`remote`,"mcp.server.name":e.name}})),removeServer:e=>F(function*(){let n=hW(e),r=yield*t.core.integrations.get(n),i=r?LL(r.config):null,a=JU(e,r),o=yield*t.connections.list({integration:n}),s=yield*t.connections.list(),c=yield*t.oauth.listClients(),l=new Set(s.filter(e=>String(e.integration)!==String(n)).flatMap(e=>e.oauthClient==null?[]:[YU(e.oauthClientOwner??e.owner,e.oauthClient)])),u=new Map(c.map(e=>[YU(e.owner,e.slug),e])),d=new Map;for(let e of o){if(e.oauthClient==null)continue;let t=e.oauthClientOwner??e.owner,n=YU(t,e.oauthClient);u.get(n)?.origin.kind===`dynamic_client_registration`&&d.set(n,{owner:t,slug:e.oauthClient})}for(let t of c){let n=YU(t.owner,t.slug);if(!l.has(n)){if(t.origin.kind===`dynamic_client_registration`&&(t.origin.integration==null||String(t.origin.integration)===e)){d.set(n,{owner:t.owner,slug:t.slug});continue}XU(t,a,i)&&d.set(n,{owner:t.owner,slug:t.slug})}}yield*t.core.integrations.remove(n).pipe(Jf(`IntegrationRemovalNotAllowedError`,()=>Nf)),yield*Ef(d.values(),e=>t.oauth.removeClient(e.owner,e.slug),{discard:!0})}).pipe(z(`mcp.plugin.remove_server`,{attributes:{"mcp.integration.slug":e}})),reconcileStdioConnections:()=>F(function*(){let e=yield*t.core.integrations.list();for(let n of e)n.kind===GU&&(yield*F(function*(){let e=yield*t.core.integrations.get(n.slug),r=e?LL(e.config):null;if(!r||r.transport!==`stdio`||r.authenticationTemplate!==void 0||(yield*t.connections.list({integration:n.slug})).length>0)return;let i=r.env??{},a=Object.keys(i),o=a.length>0;yield*t.connections.create({owner:`org`,name:wb.make(`default`),integration:n.slug,template:Sb.make(o?_W:`none`),values:o?{...i}:{}});let s={transport:`stdio`,command:r.command,args:r.args,cwd:r.cwd,authenticationTemplate:o?[{slug:_W,kind:`stdio_env`,vars:a}]:[{slug:`none`,kind:`none`}]};yield*t.core.integrations.update(n.slug,{config:s})}).pipe(qf(e=>Hp(`mcp: failed healing stdio connection for "${n.slug}"`,e)),z(`mcp.plugin.reconcile_stdio_connection`,{attributes:{"mcp.integration.slug":String(n.slug)}})))}).pipe(z(`mcp.plugin.reconcile_stdio_connections`)),getServer:e=>t.core.integrations.get(hW(e)).pipe(z(`mcp.plugin.get_server`,{attributes:{"mcp.integration.slug":e}})),configureServer:(e,n)=>t.core.integrations.update(hW(e),{config:n}).pipe(z(`mcp.plugin.configure_server`,{attributes:{"mcp.integration.slug":e}})),configureAuth:(e,n)=>F(function*(){let r=yield*t.core.integrations.get(hW(e)),i=r?LL(r.config):null;if(!i||i.transport===`stdio`)return[];let a=n.mode===`replace`?PL(n.authenticationTemplate):zI(i.authenticationTemplate,NL(n.authenticationTemplate));return yield*t.core.integrations.update(hW(e),{config:{...i,authenticationTemplate:a}}),a}).pipe(z(`mcp.plugin.configure_auth`,{attributes:{"mcp.integration.slug":e}}))}},resolveTools:({config:e,connection:n,template:r,getValues:i,httpClientLayer:a})=>F(function*(){let o=LL(e);if(!o)return{tools:[],incomplete:!0};let s=yield*NW(o,yield*i().pipe(tp(()=>({}))),r===null?null:String(r),t,a).pipe(L(e=>cU(e)),Hf),c=yi(s)?yield*vU(s.success).pipe(L(e=>({ok:!0,manifest:e})),qf(()=>P({ok:!1,manifest:null})),z(`mcp.plugin.discover_tools`,{attributes:{"mcp.connection.name":String(n.name)}})):{ok:!1,manifest:null};return!c.ok||!c.manifest?{tools:[],incomplete:!0}:{tools:c.manifest.tools.map(SW)}}).pipe(z(`mcp.plugin.resolve_tools`,{attributes:{"mcp.connection.name":String(n.name)}})),invokeTool:({ctx:r,toolRow:i,credential:a,args:o,elicit:s})=>F(function*(){let c=LL(a.config);if(!c)return yield*new SL({transport:`auto`,message:`MCP integration "${i.integration}" has no usable config`});let l=QU(i.annotations);if(!l)return yield*new CL({stage:`list_tools`,message:`Tool "${i.name}" is missing its MCP binding \u2014 refresh the connection`});let u=c.transport===`stdio`?`stdio`:c.remoteTransport??`auto`;if(c.transport===`remote`){let e=MW(c,String(a.template));if(e?.kind===`apikey`){let t=cL(e.placements).filter(e=>a.values[e]==null);if(t.length>0)return iN({code:`connection_value_missing`,message:`Connection has no resolvable credential value for input(s): ${t.join(`, `)}. Re-create the connection with the required value(s).`,integration:{id:String(a.integration)},credential:{kind:`upstream`,label:String(a.connection)}})}}let d=yield*NW(c,a.values,String(a.template),t,e?.httpClientLayer??r.httpClientLayer),f=cU(d),p=d.transport===`remote`?FW(d,String(a.template),a.values):void 0,m={owner:a.owner,integration:a.integration,name:a.connection},h=!1,g=yield*AU({toolId:String(i.name),toolName:l.toolName,args:o,transport:u,connector:f,...p===void 0?{}:{connectionPool:n,connectionPoolKey:p},elicit:s,onToolListChanged:()=>{h=!0}}).pipe(yp(()=>h?r.connections.markToolsStale(m).pipe($f):Nf)),_=di(EW(g));if(_?.isError===!0){let e=DW(_.content);return CU(e,l.toolName)?yield*r.connections.markToolsStale(m).pipe($f,Gf(OW(String(i.name),a))):$M.fail({code:`mcp_tool_error`,message:e,details:{content:_.content}})}return $M.ok(g)}).pipe(Jf(`McpOAuthReauthorizationRequired`,()=>P(mW({integration:String(a.integration),connection:String(a.connection)}))),Jf(`McpConnectionError`,e=>e.httpStatus===401||e.httpStatus===403?P(pW({status:e.httpStatus,integration:String(a.integration),connection:String(a.connection),...e.insufficientScope===!0?{insufficientScope:!0}:{}})):P(iN({code:`connection_rejected`,message:e.message,integration:{id:String(a.integration)},credential:{kind:`upstream`,label:String(a.connection)}}))),Jf(`McpInvocationError`,e=>e.status===401||e.status===403?P(pW({status:e.status,integration:String(a.integration),connection:String(a.connection),...e.insufficientScope===!0?{insufficientScope:!0}:{}})):e.unknownTool===!0?r.connections.markToolsStale({owner:a.owner,integration:a.integration,name:a.connection}).pipe($f,Gf(OW(String(i.name),a))):I(e)),z(`mcp.plugin.invoke_tool`,{attributes:{"mcp.tool.name":String(i.name),"mcp.integration.slug":String(i.integration)}})),detect:({ctx:t,url:n})=>F(function*(){let r=e?.httpClientLayer??t.httpClientLayer,i=n.trim();if(!i)return null;let a=yield*If({try:()=>new URL(i),catch:e=>e}).pipe(Uf);if(ai(a))return null;let o=a.value.hostname||`mcp`,s=UH({endpoint:i});return(yield*vU(cU({transport:`remote`,endpoint:i,httpClientLayer:r})).pipe(L(()=>!0),qf(()=>P(!1)),z(`mcp.plugin.discover_tools`)))||(yield*WU(i,{httpClientLayer:r})).kind===`mcp`?{kind:GU,confidence:`high`,endpoint:i,name:o,slug:s}:kW(a.value,`mcp`)?{kind:GU,confidence:`low`,endpoint:i,name:o,slug:s}:null}).pipe(qf(()=>P(null)),z(`mcp.plugin.detect`,{attributes:{"mcp.endpoint":n}})),resolveAnnotations:({toolRows:e})=>Mf(()=>{let t={};for(let n of e){let e=QU(n.annotations),r=e?.upstream;r?.destructiveHint===!0?t[String(n.name)]={requiresApproval:!0,approvalDescription:r.title??e?.toolName??String(n.name)}:t[String(n.name)]={requiresApproval:!1}}return t}),checkHealth:({ctx:n,credential:r})=>F(function*(){let i=LL(r.config);return i?yield*vU(yield*NW(i,r.values,r.template===null?null:String(r.template),t,e?.httpClientLayer??n.httpClientLayer).pipe(L(e=>cU(e)))).pipe(L(()=>({status:`healthy`,checkedAt:Date.now()})),Jf(`McpToolDiscoveryError`,e=>P({status:KU(e),checkedAt:Date.now(),...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},detail:e.message}))):{status:`unknown`,checkedAt:Date.now()}}).pipe(Jf(`McpConnectionError`,e=>P({status:KU(e),checkedAt:Date.now(),...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},detail:e.message})),Vf(e=>Tp({"mcp.health.status":e.status,...`httpStatus`in e&&e.httpStatus!==void 0?{"mcp.health.http_status":e.httpStatus}:{}})),z(`mcp.plugin.check_health`,{attributes:{"executor.integration":String(r.integration),"mcp.connection.name":String(r.connection)}})),describeAuthMethods:LW,describeIntegrationDisplay:RW,integrationConfigure:{type:`mcp`,configure:({ctx:e,integration:t,config:n})=>F(function*(){let r=LL(n);r&&(yield*e.core.integrations.update(t,{config:r}))})},staticIntegrations:e=>[{id:`mcp`,kind:`executor`,name:`MCP`,tools:[Yk({name:`probeEndpoint`,description:"Probe a remote MCP endpoint before adding it. If the result requires OAuth, run the core OAuth handoff (`oauth.probe`, `oauth.start`) to mint a connection; otherwise create a connection with `connections.create` carrying the API key or header value.",inputSchema:cW,outputSchema:lW,execute:t=>e.probeEndpoint(t).pipe(L($M.ok),Jf(`McpConnectionError`,({message:e,transport:t})=>P(fW(`mcp_connection_failed`,e,{transport:t}))))}),Yk({name:`getServer`,description:"Inspect a registered MCP integration, including transport, endpoint/command, and auth template. Use this before creating a connection (`connections.create` / `oauth.start`).",inputSchema:uW,outputSchema:dW,execute:t=>{let n=t;return L(e.getServer(n.slug),e=>$M.ok({integration:e}))}}),Yk({name:`addServer`,description:"Register an MCP server in the catalog as an integration. Returns its `slug`. Then create a connection against it: for header/API-key auth call `connections.create` with the value; for OAuth-protected servers run `oauth.probe` + `oauth.start`. Tools are produced per-connection at connection create / refresh.",annotations:{requiresApproval:!0,approvalDescription:`Add an MCP server`},inputSchema:oW,outputSchema:sW,execute:t=>{let n=t;return e.addServer(n).pipe(L($M.ok),Jf(`IntegrationAlreadyExistsError`,({slug:e})=>P(fW(`integration_already_exists`,`Integration ${e} already exists; update it instead of re-adding.`))))}})]}]}});B(Kv([W({kind:H(`none`)}),W({kind:H(`header`),headerName:U,prefix:V(U)}),W({kind:H(`query`),paramName:U,prefix:V(U)}),W({kind:H(`oauth2`)})]));var BW=W({slug:U,kind:H(`header`),headerName:U,prefix:V(U)}),VW=W({slug:U,kind:H(`query`),paramName:U,prefix:V(U)}),HW=W({slug:U,type:H(`oauth`)});B(BW),B(VW),B(HW),B(Kv([W({slug:U,kind:qv([`none`,`oauth2`])}),W({slug:U,kind:H(`apikey`),label:V(U),placements:G(Lv)})]));var UW=`harness.executor.runtime`,WW=new Set([`close`,`dispatch`,`initialize`,`reconcile`,`refresh`,`release`,`update`]);function GW(e,t){try{e?.(t)}catch{}}function KW(e){let t={},n=e instanceof Map?e.entries():Object.entries(e);for(let[e,r]of n)(e===`component`&&r===`executor`||e===`runtime.role`&&r===`executor`||e===`operation`&&typeof r==`string`&&WW.has(r)||e===`outcome`&&(r===`cancelled`||r===`error`||r===`success`||r===`timeout`))&&(t[e]=r);return Object.freeze(t)}function qW(e,t){return/^[0-9a-f]{32}$/.test(e)&&e!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/.test(t)&&t!==`0000000000000000`?{spanId:t,traceId:e}:void 0}function JW(e,t){let n=t>=e?t-e:0n,r=Number(n)/1e6;return Number.isFinite(r)?Math.round(r*1e3)/1e3:0}function YW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XW(e){return YW(e)&&typeof e._tag==`string`?e._tag.slice(0,128):e instanceof Error&&e.name?e.name.slice(0,128):`mcp_unavailable`}function ZW(e,t,n,r){return{error:{code:XW(r),message:`MCP server is unavailable`,retryable:!0},generation:n,registrationId:t,runtimeEpoch:e,status:`unavailable`,tools:[]}}function QW(e){return YW(e)?e:void 0}function $W(e){if(!YW(e)||!YW(e.mcp)||!YW(e.mcp.upstream))return;let t=e.mcp.upstream,n={...typeof t.destructiveHint==`boolean`?{destructiveHint:t.destructiveHint}:{},...typeof t.idempotentHint==`boolean`?{idempotentHint:t.idempotentHint}:{},...typeof t.openWorldHint==`boolean`?{openWorldHint:t.openWorldHint}:{},...typeof t.readOnlyHint==`boolean`?{readOnlyHint:t.readOnlyHint}:{},...typeof t.title==`string`?{title:t.title}:{}};return Object.keys(n).length>0?n:void 0}function eG(e){let t=QW(QW(e.annotations)?.mcp);return typeof t?.toolName==`string`?t.toolName:String(e.name)}function tG(e){if(YW(e)&&!(!Array.isArray(e.required)||!e.required.includes(`structuredContent`)))return QW(QW(e.properties)?.structuredContent)}function nG(e){let t=tG(e.outputSchema);return{...$W(e.annotations)===void 0?{}:{annotations:$W(e.annotations)},...e.description?{description:e.description}:{},executorAddress:String(e.address),inputSchema:QW(e.inputSchema)??{additionalProperties:!0,type:`object`},...t===void 0?{}:{outputSchema:t},upstreamToolName:eG(e)}}function rG(e){return[{text:e,type:`text`}]}function iG(e,t=!1){if(!YW(e))return{content:rG(JSON.stringify(e)??String(e)),...t?{isError:!0}:{}};let n=Array.isArray(e.content)?e.content:rG(JSON.stringify(e)),r=QW(e.structuredContent),i=QW(e._meta);return{...i===void 0?{}:{_meta:i},content:n,...t||e.isError===!0?{isError:!0}:{},...r===void 0?{}:{structuredContent:r}}}function aG(e){if(!tN(e))return iG(e);if(e.ok)return iG(e.data);let t=QW(e.error.details)?.content;return{content:Array.isArray(t)?t:rG(e.error.message),isError:!0}}function oG(e){return e.request._tag===`FormElicitation`?{message:e.request.message,mode:`form`,requestedSchema:e.request.requestedSchema}:{elicitationId:String(e.request.elicitationId),message:e.request.message,mode:`url`,url:e.request.url}}function sG(e){return{action:e.action,...e.content===void 0?{}:{content:e.content}}}var cG=class{constructor(){this.key=Db.make(`agent-harness-ephemeral`),this.values=ib(new Map),this.provider={delete:e=>this.deleteValue(String(e)),get:e=>ab(this.values).pipe(L(t=>t.get(String(e))??null)),has:e=>ab(this.values).pipe(L(t=>t.has(String(e)))),key:this.key,list:()=>ab(this.values).pipe(L(e=>[...e.keys()].map(e=>({id:Ob.make(e),name:e})))),set:(e,t)=>this.setValue(String(e),t),writable:!0}}clear(){return ob(this.values,new Map)}deleteValue(e){return cb(this.values,t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})}setValue(e,t){return cb(this.values,n=>{let r=new Map(n);return r.set(e,t),r})}},lG=class extends Error{constructor(e,t,n=`Executor operation failed at ${e}`){super(n),this.stage=e,this.upstreamCode=t,this._tag=`ExecutorRuntimeFailure`,this.name=this._tag}},uG=class extends Error{constructor(){super(`Executor runtime is closed`),this._tag=`ExecutorRuntimeClosed`,this.name=this._tag}},dG=class extends Error{constructor(e){super(`Duplicate Executor invocation id "${e}"`),this.invocationId=e,this._tag=`ExecutorInvocationConflict`,this.name=this._tag}},fG=class extends Error{constructor(e){super(`Unknown Executor registration "${e}"`),this.registrationId=e,this._tag=`ExecutorRegistrationNotFound`,this.name=this._tag}},pG=class extends Error{constructor(){super(`Executor tool address is not present in the registration`),this._tag=`ExecutorToolAddressNotFound`,this.name=this._tag}},mG=class extends Error{constructor(){super(`Executor invocation was interrupted`),this._tag=`ExecutorInvocationInterrupted`,this.name=this._tag}},hG=class extends Error{constructor(){super(`Private Executor runtime encountered a fatal defect`),this._tag=`ExecutorRuntimeDefect`,this.name=this._tag}};function gG(e,t){return new lG(e,XW(t))}function _G(e){if(ed(e))return new hG;let t=$u(e),n=oi(t)?t.value:Zu(e);return n instanceof dG||n instanceof mG||n instanceof fG||n instanceof uG||n instanceof lG||n instanceof pG?n:td(e)?new mG:gG(`runtime.boundary`,n)}var vG=class{constructor(e,t,n,r,i){this.executor=e,this.credentials=t,this.options=n,this.registrationSemaphore=r,this.state=i}upsertRegistration(e){let t=this;return this.runRegistrationOperation(e.registrationId,F(function*(){let n=(yield*t.openState()).registrations.get(e.registrationId);if(n)return yield*t.refreshRegistrationLocked(n);let r={allowedAddresses:new Set,connectionRef:{integration:xb.make(e.executorSlug),name:wb.make(e.connectionName),owner:`org`},credentialIds:new Set,generation:0,spec:e};return yield*t.insertRegistration(r),yield*t.refreshRegistrationLocked(r)}))}refreshRegistration(e){let t=this;return this.runRegistrationOperation(e,F(function*(){let n=yield*t.requireRegistration(e);return yield*t.refreshRegistrationLocked(n)}))}removeRegistration(e){let t=this;return this.registrationSemaphore.withPermit(F(function*(){let n=yield*hb(t.state,t=>{if(t.closed)return[{_tag:`closed`},t];let n=t.registrations.get(e);if(!n)return[{_tag:`missing`},t];let r=new Map(t.registrations);return r.delete(e),[{_tag:`removed`,integrationStillUsed:[...r.values()].some(e=>e.spec.executorSlug===n.spec.executorSlug),registration:n},{...t,registrations:r}]});if(n._tag===`closed`)return yield*I(new uG);n._tag!==`missing`&&(yield*t.executor.connections.remove(n.registration.connectionRef).pipe($f),yield*Tf([...n.registration.credentialIds].map(e=>t.credentials.deleteValue(e)),{discard:!0}),n.integrationStillUsed||(yield*t.executor.mcp.removeServer(n.registration.spec.executorSlug).pipe($f)))}))}callTool(e,t,n,r){let i=this;return Cp(a=>F(function*(){let o={},s=yield*hb(i.state,r=>{if(r.closed)return[{_tag:`closed`},r];if(r.inFlight.has(t))return[{_tag:`conflict`},r];let i=r.registrations.get(e);if(!i)return[{_tag:`missing`},r];if(!i.allowedAddresses.has(n))return[{_tag:`tool_missing`},r];let a={registrationId:e,token:o},s=new Map(r.inFlight);return s.set(t,a),[{_tag:`reserved`},{...r,inFlight:s}]});return s._tag===`closed`?yield*I(new uG):s._tag===`conflict`?yield*I(new dG(t)):s._tag===`missing`?yield*I(new fG(e)):s._tag===`tool_missing`?yield*I(new pG):yield*F(function*(){let e,s=yield*Wf(jf(()=>i.executor.execute(Ab.make(n),r,{onElicitation:n=>Of({catch:e=>gG(`tool.elicitation`,e),try:async()=>sG(await i.options.onElicitation(t,oG(n)))}).pipe(op({onFailure:t=>Mf(()=>(e??=t,{action:`cancel`})),onSuccess:P}))})).pipe(R(e=>gG(`tool.call`,e)))).pipe(Rf(t=>e===void 0?ld(t)?P(t.value):Pf(t.cause):I(e))).pipe(Op({uninterruptible:!1}));return(yield*hb(i.state,e=>{let n=e.inFlight.get(t);if(e.closed||!n||n.token!==o)return[!1,e];let r=new Map(e.inFlight);return r.set(t,{...n,fiber:s}),[!0,{...e,inFlight:r}]}))?yield*a(s_(s)).pipe(L(aG)):(yield*c_(s),yield*I(new mG))}).pipe(_p(i.removeInvocation(t,o)))}))}cancelInvocation(e){let t=this;return F(function*(){let n=yield*hb(t.state,t=>{let n=t.inFlight.get(e);if(!n)return[void 0,t];let r=new Map(t.inFlight);return r.delete(e),[n,{...t,inFlight:r}]});n&&n.fiber&&(yield*c_(n.fiber))})}shutdown(){let e=this;return F(function*(){yield*l_((yield*hb(e.state,e=>e.closed?[[],e]:[[...e.inFlight.values()],{...e,closed:!0,inFlight:new Map}])).flatMap(e=>e.fiber?[e.fiber]:[])),yield*e.registrationSemaphore.withPermit(F(function*(){yield*Tf((yield*hb(e.state,e=>[[...e.registrationGates.values()],{...e,registrationGates:new Map,registrations:new Map}])).map(e=>_d(e,new uG)),{discard:!0}),yield*e.credentials.clear()}))})}runRegistrationOperation(e,t){let n=this;return Cp(r=>F(function*(){let i=yield*md(),a=yield*hb(n.state,t=>{if(t.closed)return[{_tag:`closed`},t];let n=t.registrationGates.get(e);if(n)return[{_tag:`join`,gate:n},t];let r=new Map(t.registrationGates);return r.set(e,i),[{_tag:`owner`,gate:i},{...t,registrationGates:r}]});if(a._tag===`closed`)return yield*I(new uG);if(a._tag===`join`)return yield*r(hd(a.gate));let o=t=>F(function*(){yield*gd(a.gate,t),yield*n.removeRegistrationGate(e,a.gate)});return yield*r(n.registrationSemaphore.withPermit(t.pipe(yp(o)))).pipe(yp(o))}))}refreshRegistrationLocked(e){let t=this,n=e.spec.registrationId;return F(function*(){let r={...e,generation:e.generation+1},i=yield*Wf(F(function*(){yield*t.assertOpen(),yield*t.ensureIntegration(r.spec),r=yield*t.ensureConnection(r),yield*t.ensureApprovalPolicy(r);let e=yield*t.executor.connections.refresh(r.connectionRef);return(yield*t.executor.connections.checkHealth(r.connectionRef)).status===`healthy`?e:yield*I(gG(`registration.health`,{_tag:`McpConnectionUnavailable`}))}));if(ud(i))return ed(i.cause)?yield*Ff(new hG):td(i.cause)?yield*xp:(r={...yield*t.requireRegistration(n),generation:r.generation},yield*t.replaceRegistration(r),ZW(t.options.runtimeEpoch,n,r.generation,Zu(i.cause)));let a={...r,allowedAddresses:new Set(i.value.map(e=>String(e.address)))};return yield*t.replaceRegistration(a),{generation:a.generation,registrationId:n,runtimeEpoch:t.options.runtimeEpoch,status:`available`,tools:i.value.map(nG)}})}ensureIntegration(e){let t=this;return F(function*(){if(yield*t.executor.integrations.get(xb.make(e.executorSlug)))return;if(e.transport.transport===`remote`){let n={authenticationTemplate:e.transport.authentication.kind===`none`?[{kind:`none`,slug:`none`}]:[{headers:Object.fromEntries(Object.entries(e.transport.authentication.placements).map(([e,t])=>[e,[{name:t,type:`variable`}]])),label:`ACP session headers`,slug:`headers`,type:`apiKey`}],endpoint:e.transport.endpoint,name:e.executorSlug,remoteTransport:e.transport.remoteTransport,slug:e.executorSlug,transport:`remote`};yield*t.executor.mcp.addServer(n);return}if(!t.options.allowStdio)return yield*I(gG(`registration.integration`,{_tag:`StdioMcpDisabled`}));let n={args:[...e.transport.args],command:e.transport.command,cwd:e.transport.cwd,envVars:Object.keys(e.transport.env),name:e.executorSlug,slug:e.executorSlug,transport:`stdio`};yield*t.executor.mcp.addServer(n)})}ensureConnection(e){let t=this;return F(function*(){if(yield*t.executor.connections.get(e.connectionRef))return e;let n=e.spec.transport,r=n.transport===`remote`?n.authentication.kind===`headers`?`headers`:`none`:Object.keys(n.env).length>0?`env`:`none`,i=n.transport===`remote`?n.headers:n.env,a=Object.entries(i),o=new Set(e.credentialIds),s=[];for(let[n,r]of a){let i=[`agent-harness`,e.spec.registrationId,s.length].join(`.`);yield*t.credentials.setValue(i,r),o.add(i),s.push([n,{from:{id:Ob.make(i),provider:t.credentials.key}}])}let c={...e,credentialIds:o};yield*t.replaceRegistration(c);let l=s.length===0?{values:{}}:{inputs:Object.fromEntries(s)};return yield*t.executor.connections.create({...c.connectionRef,template:Sb.make(r),...l}),c})}ensureApprovalPolicy(e){let t=this;return F(function*(){let n=[e.spec.executorSlug,e.connectionRef.owner,e.spec.connectionName,`*`].join(`.`);(yield*t.executor.policies.list()).some(e=>e.owner===`org`&&e.pattern===n&&e.action===`approve`)||(yield*t.executor.policies.create({action:`approve`,owner:`org`,pattern:n}))})}requireRegistration(e){let t=this;return F(function*(){return(yield*t.openState()).registrations.get(e)||(yield*I(new fG(e)))})}assertOpen(){return this.openState().pipe(Kf)}openState(){return mb(this.state).pipe(Rf(e=>e.closed?I(new uG):P(e)))}insertRegistration(e){return hb(this.state,t=>{if(t.closed)return[!1,t];let n=new Map(t.registrations);return n.set(e.spec.registrationId,e),[!0,{...t,registrations:n}]}).pipe(Rf(e=>e?Nf:I(new uG)))}replaceRegistration(e){let t=this;return F(function*(){let n=yield*hb(t.state,t=>{if(t.closed)return[{_tag:`closed`},t];if(!t.registrations.has(e.spec.registrationId))return[{_tag:`missing`},t];let n=new Map(t.registrations);return n.set(e.spec.registrationId,e),[{_tag:`replaced`},{...t,registrations:n}]});if(n._tag===`closed`)return yield*I(new uG);if(n._tag===`missing`)return yield*I(new fG(e.spec.registrationId))})}removeRegistrationGate(e,t){return gb(this.state,n=>{if(n.registrationGates.get(e)!==t)return n;let r=new Map(n.registrationGates);return r.delete(e),{...n,registrationGates:r}})}removeInvocation(e,t){return gb(this.state,n=>{if(n.inFlight.get(e)?.token!==t)return n;let r=new Map(n.inFlight);return r.delete(e),{...n,inFlight:r}})}},yG=class extends la()(`agent-harness/ExecutorChildService`){};function bG(e,t,n){let r=t===void 0?void 0:xo({sampled:t.sampled,spanId:t.parentSpanId,traceId:t.traceId}),i={component:`executor`,operation:n,"runtime.role":`executor`};return z(e.pipe(Vf(()=>Up(UW).pipe(Wp({...i,outcome:`success`}))),Qf(()=>Hp(UW).pipe(Wp({...i,outcome:`error`})))),UW,{attributes:{...i},kind:`server`,...r===void 0?{}:{parent:r}})}function xG(e){let t={effectErrors:0,effectLogs:0,effectSpans:0},n=new Map,r=ya(ff,n),i=_f(`agent_harness_effect_logs_total`,{incremental:!0}),a=_f(`agent_harness_effect_errors_total`,{incremental:!0}),o=_f(`agent_harness_effect_spans_total`,{incremental:!0}),s=()=>GW(e,{kind:`metrics`,value:{...t}}),c=Ly(n=>{let r=Array.isArray(n.message)?n.message:[n.message];if(r.length!==1||r[0]!==UW)return;t.effectLogs+=1,i.updateUnsafe(1,n.fiber.context);let o=n.logLevel===`Error`||n.logLevel===`Fatal`?`error`:n.logLevel===`Warn`?`warn`:`info`;o===`error`&&(t.effectErrors+=1,a.updateUnsafe(1,n.fiber.context));let c=n.fiber.currentSpan,l=c?._tag===`Span`?qW(c.traceId,c.spanId):void 0;GW(e,{kind:`log`,value:{annotations:KW(n.fiber.getRef(yd)),level:o,message:UW,...c?._tag===`Span`&&l?{span:{name:UW,sampled:c.sampled,...l}}:{}}}),s()}),l=bo({span(n){let i=new Do(n),c=i.end.bind(i);return i.end=(n,l)=>{if(c(n,l),i.name!==UW)return;t.effectSpans+=1,o.updateUnsafe(1,r),l._tag===`Failure`&&(t.effectErrors+=1,a.updateUnsafe(1,r));let u=qW(i.traceId,i.spanId);if(u){let t=i.parent._tag===`Some`&&/^[0-9a-f]{16}$/.test(i.parent.value.spanId)&&i.parent.value.spanId!==`0000000000000000`?i.parent.value.spanId:void 0;GW(e,{kind:`span`,value:{attributes:KW(i.attributes),durationMs:JW(i.startTime,n),kind:i.kind,name:UW,outcome:l._tag===`Success`?`success`:`error`,...t===void 0?{}:{parentSpanId:t},sampled:i.sampled,...u}})}s()},i}});return Ud(Ry([c]),Ld(Eo,l),Ld(ff,n))}function SG(e,t){let n=II({onElicitation:()=>P({action:`cancel`}),plugins:[zW({dangerouslyAllowStdioMCP:t.allowStdio})],providers:[e.provider],tenant:Fb.make(t.tenantId),toolsSyncTtlMs:null}).pipe(R(e=>gG(`runtime.initialize`,e)),L(e=>e));return zd(yG,F(function*(){return new vG(yield*hp(n,e=>e.close().pipe(Zf)),e,t,yield*v_(1),yield*fb({closed:!1,inFlight:new Map,registrationGates:new Map,registrations:new Map}))}))}async function CG(e,t){let n=await e.runPromiseExit(t);if(ld(n))return n.value;throw _G(n.cause)}var wG=class e{static async create(t,n){let r=By(Wd(SG(new cG,t),xG(t.onTelemetry)));try{return await CG(r,bG(yG.asEffect(),n,`initialize`)),new e(r)}catch(e){throw await r.dispose().catch(()=>void 0),e}}constructor(e){this.managed=e}upsertRegistration(e,t){return this.runOpen(yG.use(t=>t.upsertRegistration(e)),t,`reconcile`)}refreshRegistration(e,t){return this.runOpen(yG.use(t=>t.refreshRegistration(e)),t,`refresh`)}removeRegistration(e,t){return this.runOpen(yG.use(t=>t.removeRegistration(e)),t,`release`)}callTool(e,t,n,r,i){return this.runOpen(yG.use(i=>i.callTool(e,t,n,r)),i,`dispatch`)}cancelInvocation(e,t){return this.closePromise?Promise.resolve():this.run(yG.use(t=>t.cancelInvocation(e)),t,`update`)}close(e){return this.closePromise||=this.closeOnce(e),this.closePromise}async closeOnce(e){let t;try{await this.run(yG.use(e=>e.shutdown()),e,`close`)}catch(e){t=e}try{let e=await Fp(this.managed.disposeEffect);ud(e)&&(t??=_G(e.cause))}catch(e){t??=gG(`runtime.close`,e)}if(t!==void 0)throw t}runOpen(e,t,n){return this.closePromise?Promise.reject(new uG):this.run(e,t,n)}run(e,t,n){return CG(this.managed,bG(e,t,n))}},TG=5e3,EG=250,DG=4*1024,OG=50;function kG(e=process.env){return{AGENT_HARNESS_PRIVATE_STDIO_GROUP_ANCHOR:`1`,...e.ELECTRON_RUN_AS_NODE===`1`?{ELECTRON_RUN_AS_NODE:`1`}:{}}}var AG=class extends Error{constructor(){super(`stdio process-group anchor cleanup failed`),this._tag=`StdioProcessGroupAnchorCleanupError`,this.name=this._tag}};function jG(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function MG(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===4&&t.type===`ready`&&jG(t.anchorPid)&&jG(t.guardianPid)&&jG(t.targetProcessGroupId)}function NG(e,t,n,r){if(!e.stdout)return Promise.reject(Error(`stdio process-group anchor did not expose a ready pipe`));let i=e.stdout;return i.setEncoding(`utf8`),new Promise((a,o)=>{let s=``,c=!1,l=t=>{c||(c=!0,clearTimeout(p),e.removeListener(`error`,u),e.removeListener(`exit`,d),i.removeListener(`data`,f),t?o(t):(i.resume(),a()))},u=e=>l(e),d=()=>l(Error(`stdio process-group anchor exited before ready`)),f=r=>{if(s+=r,Buffer.byteLength(s,`utf8`)>DG){l(Error(`stdio process-group anchor handshake was oversized`));return}let i=s.indexOf(`
|
|
74
|
+
`);if(!(i<0))try{let r=JSON.parse(s.slice(0,i));if(s.slice(i+1).trim()!==``||!MG(r)||r.anchorPid!==e.pid||r.guardianPid!==t||r.targetProcessGroupId!==n){l(Error(`stdio process-group anchor handshake was invalid`));return}l()}catch{l(Error(`stdio process-group anchor handshake was malformed`))}},p=setTimeout(()=>l(Error(`stdio process-group anchor ready handshake timed out`)),r);p.unref?.(),e.once(`error`,u),e.once(`exit`,d),i.on(`data`,f)})}function PG(e,t){return Number.isSafeInteger(e)&&e!==void 0&&e>0?e:t}function FG(e,t){return e.exitCode!==null||e.signalCode!==null?Promise.resolve(!0):new Promise(n=>{let r=!1,i=t=>{r||(r=!0,clearTimeout(o),e.removeListener(`exit`,a),n(t))},a=()=>i(!0),o=setTimeout(()=>i(!1),t);o.unref?.(),e.once(`exit`,a)})}function IG(e){let t=e=>{try{e()}catch{}};e.connected&&t(()=>e.disconnect?.()),t(()=>e.channel?.unref()),t(()=>e.stdin?.destroy()),t(()=>e.stdout?.destroy()),t(()=>e.stderr?.destroy()),t(()=>e.unref())}async function LG(e,t=EG){if(e.exitCode!==null||e.signalCode!==null)return;let n=FG(e,PG(t,EG));try{e.kill(`SIGKILL`)}catch{}if(!await n)throw IG(e),new AG}async function RG(e,t={}){if(process.platform===`win32`||!Number.isSafeInteger(e)||e<=0)throw Error(`stdio process-group anchor configuration is invalid`);let n=Ge(new URL(`./stdio-group-anchor.mjs`,import.meta.url)),r=(t.spawnAnchor??Ne)(process.execPath,[n,String(e),String(process.pid),String(OG)],{detached:!1,env:kG(),stdio:[`ignore`,`pipe`,`ignore`],windowsHide:!0});r.stdout?.on(`error`,()=>void 0);try{return await NG(r,e,process.pid,PG(t.readyTimeoutMs,TG)),r}catch(e){throw await LG(r,PG(t.cleanupTimeoutMs,EG)),e}}var zG=250;function BG(e){try{let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf8`);return n<=ze?{bytes:n,message:e}:void 0}catch{return}}function VG(e){let t=[],n=0,r=!0,i=!1,a,o,s,c=!1,l,u=()=>{i||(r=!1,i=!0,l!==void 0&&(clearImmediate(l),l=void 0),s!==void 0&&(clearTimeout(s),s=void 0),t.length=0,n=0,o?.(),o=void 0)},d=()=>{a!==void 0&&!c&&t.length===0&&u()},f=()=>{i||c||l!==void 0||t.length===0||e.isPriorityBusy()||(l=setImmediate(()=>{l=void 0,p()}))},p=()=>{if(i||c||t.length===0||e.isPriorityBusy())return;let r=t.shift();if(!r)return;n-=r.bytes,c=!0;let a=!1,o=()=>{a||(a=!0,c=!1,d(),f())};try{e.send(r.message,o)}catch{o()}};return{get bufferedBytes(){return n},get bufferedMessages(){return t.length},close(){u()},flushAndClose(e=zG){return i?a??Promise.resolve():a===void 0?(r=!1,a=new Promise(e=>{o=e}),s=setTimeout(u,Number.isFinite(e)?Math.max(0,Math.floor(e)):zG),s.unref(),d(),f(),a):a},notifyPriorityAvailable(){f()},offer(a){if(!r||i)return;let o=e.runtimeEpoch();if(!o)return;let s=BG({jsonrpc:`2.0`,method:`telemetry/effect`,params:{runtimeEpoch:o,signal:a}});if(s){if(a.kind===`metrics`){let e=t.findIndex(e=>e.message.params.signal.kind===`metrics`);if(e>=0){let[r]=t.splice(e,1);r&&(n-=r.bytes)}}t.length>=Ve||n+s.bytes>Be||(t.push(s),n+=s.bytes,f())}}}}function HG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UG(e){let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Private Executor IPC payload must be JSON`);let n=Buffer.byteLength(t,`utf8`);if(n>Re)throw RangeError(`Private Executor IPC payload exceeds ${Re} bytes`);return n}var WG=0,GG=0,KG;function qG(e){return UG(e),WG+=1,new Promise((t,n)=>{if(!process.send||!process.connected){n(Error(`Private Executor IPC channel is closed`));return}process.send(e,e=>{e?n(e):t()})}).finally(()=>{--WG,KG?.notifyPriorityAvailable()})}function JG(e){return We(e)&&typeof e.id==`string`}function YG(e,t,n){return{error:{code:-32603,data:{code:HG(n)&&typeof n._tag==`string`?n._tag.slice(0,128):n instanceof Error?n.name.slice(0,128):`internal_error`,retryable:!0},message:`Private Executor operation failed`},id:e,jsonrpc:`2.0`,runtimeEpoch:t}}function XG(e,t){return{error:{code:-32603,data:{code:Le,retryable:!1},message:`Private Executor encountered a fatal runtime defect`},id:e,jsonrpc:`2.0`,runtimeEpoch:t}}var ZG=new Map,QG,$G=!1,eK=``,tK=!1,nK;KG=VG({isPriorityBusy:()=>GG>0||WG>0,runtimeEpoch:()=>eK,send(e,t){if(!process.send||!process.connected){t(Error(`Private Executor IPC channel is closed`));return}process.send(e,t)}});var rK=`AGENT_HARNESS_PRIVATE_WINDOWS_JOB_OBJECT`,iK=`AGENT_HARNESS_PRIVATE_WINDOWS_JOB_LAUNCHER`,aK=/^Local\\agent-harness-strict-v1-[0-9a-f]{32}$/;function oK(){let e=process.env[rK]??``;if(!aK.test(e)||process.arch!==`x64`&&process.arch!==`arm64`)return!1;let t=process.env[iK]??``;if(!Ie.win32.isAbsolute(t)||Ie.win32.basename(t).toLowerCase()!==`agent-harness-job.exe`||Ie.win32.basename(Ie.win32.dirname(t)).toLowerCase()!==`win32-${process.arch}`)return!1;let n=Pe(t,[`--verify-job`,e,`--pid`,String(process.pid)],{env:process.env,stdio:`ignore`,timeout:5e3,windowsHide:!0});return n.error===void 0&&n.signal===null&&n.status===0?(delete process.env[rK],delete process.env[iK],process.env[rK]===void 0&&process.env[iK]===void 0):!1}async function sK(e,t){let n=`elicitation-${Fe()}`,r=new Promise((e,t)=>{ZG.set(n,{reject:t,resolve:e})}),i=Ke();return await qG({id:n,jsonrpc:`2.0`,method:`elicitation/create`,params:{invocationId:e,request:t,runtimeEpoch:eK},...i===void 0?{}:{trace:i}}),r}async function cK(e,t,n){if(e===`runtime/initialize`){if(QG||$G)throw Error(`Private Executor runtime is already initialized`);$G=!0;let e=t,r;try{if(e.protocolVersion!==He||!e.runtimeEpoch||!e.tenantId)throw Error(`Private Executor initialize params are invalid`);if(eK=e.runtimeEpoch,process.platform===`win32`&&!oK())throw Error(`Private Executor runtime requires the strict Windows Job Object launcher`);if(e.stdioContainment===`posix_guardian`){if(e.stdioGuardianPid===void 0)throw Error(`Private Executor stdio runtime requires a guardian PID`);r=await RG(e.stdioGuardianPid)}else if(e.stdioContainment===`windows_job_object`&&process.platform!==`win32`)throw Error(`Private Executor stdio runtime requires the strict Windows Job Object launcher`);let t=await wG.create({allowStdio:e.allowStdio,onElicitation:sK,onTelemetry:e=>KG?.offer(e),runtimeEpoch:e.runtimeEpoch,tenantId:e.tenantId},n);return eK=e.runtimeEpoch,QG=t,nK=r,nK?.once(`exit`,()=>{if(!tK)try{process.kill(-process.pid,`SIGKILL`)}catch{process.exit(70)}}),{protocolVersion:He,runtimeEpoch:eK,...nK?.pid===void 0?{}:{stdioAnchorPid:nK.pid}}}catch(e){throw r&&await LG(r),e}finally{$G=!1}}if(!QG)throw Error(`Private Executor runtime is not initialized`);if(e===`runtime/health`){if(nK&&(nK.pid===void 0||nK.exitCode!==null||nK.signalCode!==null))throw Error(`stdio process-group anchor is unavailable`);return{runtimeEpoch:eK,status:`ready`,...nK?.pid===void 0?{}:{stdioAnchorPid:nK.pid}}}if(e===`registration/upsert`){let e=t;return await QG.upsertRegistration(e.registration,n)}if(e===`registration/refresh`){let e=t;return await QG.refreshRegistration(e.registrationId,n)}if(e===`registration/remove`){let e=t;return await QG.removeRegistration(e.registrationId,n),{}}if(e===`tool/call`){let e=t;return await QG.callTool(e.registrationId,e.invocationId,e.executorAddress,e.args,n)}if(e===`tool/cancel`){let e=t;return await QG.cancelInvocation(e.invocationId,n),{}}if(e===`runtime/close`)return tK=!0,await QG.close(n),{};throw Error(`Unsupported private Executor method "${e}"`)}async function lK(e){GG+=1;let t=!1,n=!1;try{if(tK&&e.method!==`runtime/close`){await qG(YG(e.id,eK,Error(`Private Executor runtime is closing`)));return}let t=e.trace===void 0?void 0:qe(e.trace),r=await Je(t,()=>cK(e.method,e.params,t));await qG({id:e.id,jsonrpc:`2.0`,result:r,runtimeEpoch:eK}),e.method===`runtime/close`&&(n=!0)}catch(n){n instanceof hG?(tK=!0,t=!0,await qG(XG(e.id,eK)).catch(()=>void 0)):await qG(YG(e.id,eK,n)).catch(()=>void 0)}finally{--GG,KG?.notifyPriorityAvailable()}t&&(await KG?.flushAndClose(),process.exit(70)),n&&(await KG?.flushAndClose(),process.connected?process.disconnect():process.exit())}function uK(e){if(e.runtimeEpoch!==eK)return;let t=ZG.get(e.id);if(t){if(ZG.delete(e.id),`error`in e){t.reject(Error(`Harness rejected private elicitation`));return}if(!HG(e.result)||e.result.action!==`accept`&&e.result.action!==`cancel`&&e.result.action!==`decline`){t.reject(Error(`Harness returned invalid elicitation response`));return}t.resolve({action:e.result.action,...HG(e.result.content)?{content:e.result.content}:{}})}}process.on(`message`,e=>{try{UG(e)}catch{process.disconnect();return}if(JG(e)){uK(e);return}if(!Ue(e)){qG(YG(null,eK,Error(`Invalid private Executor request`))).finally(()=>process.disconnect());return}lK(e)});var dK;function fK(e){for(let t of ZG.values())t.reject(e);ZG.clear()}function pK(e){dK===void 0&&(tK=!0,fK(e),dK=(async()=>{await QG?.close().catch(()=>void 0),await KG?.flushAndClose()})().finally(()=>process.exit()))}process.once(`disconnect`,()=>{pK(Error(`Harness IPC channel disconnected`))}),process.once(`SIGTERM`,()=>{pK(Error(`Private Executor received SIGTERM`))});export{oK as verifyWindowsJobObject};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ChildProcess, fork, spawn } from 'node:child_process';
|
|
2
2
|
import type { ExecutorElicitationRequest, ExecutorElicitationResponse, ExecutorMcpCallResult, ExecutorRegistrationSnapshot, ExecutorRegistrationSpec } from '#agent-harness-executor/types';
|
|
3
3
|
import { type HarnessEffectTelemetryLog, type HarnessEffectTelemetryMetrics, type HarnessEffectTelemetrySpan, type HarnessProcessRuntimeHandle } from '../effect-runtime/process-runtime-context.js';
|
|
4
|
+
import { type NodeRuntimeLaunch } from '../runtime/node-runtime.js';
|
|
4
5
|
import { CodeBuddyProcessContainment } from '../runtime/process-containment.js';
|
|
5
6
|
import { type ResolveWindowsJobLauncherPathOptions } from '../runtime/windows-job.js';
|
|
6
7
|
import { type RuntimeLifecycleRecorder } from '../telemetry/index.js';
|
|
@@ -52,6 +53,8 @@ export interface ExecutorProcessSupervisorOptions {
|
|
|
52
53
|
readonly maxCrashes?: number;
|
|
53
54
|
readonly maxPendingRequestBytes?: number;
|
|
54
55
|
readonly maxPendingRequests?: number;
|
|
56
|
+
/** @internal JavaScript runtime used for the private Executor child. */
|
|
57
|
+
readonly nodeRuntime?: NodeRuntimeLaunch;
|
|
55
58
|
readonly onElicitation: (elicitation: ExecutorSupervisorElicitation) => Promise<ExecutorElicitationResponse>;
|
|
56
59
|
readonly onFailure?: (error: Error) => void | Promise<void>;
|
|
57
60
|
readonly platform?: NodeJS.Platform;
|
|
@@ -89,7 +92,7 @@ export declare class ExecutorPrivateShutdownTimeoutError extends Error {
|
|
|
89
92
|
readonly _tag = "ExecutorPrivateShutdownTimeoutError";
|
|
90
93
|
constructor(timeoutMs: number);
|
|
91
94
|
}
|
|
92
|
-
export declare function createExecutorChildEnvironment(source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
95
|
+
export declare function createExecutorChildEnvironment(source?: NodeJS.ProcessEnv, nodeRuntime?: NodeRuntimeLaunch): NodeJS.ProcessEnv;
|
|
93
96
|
/**
|
|
94
97
|
* Preserves Node's inherited IPC descriptor table while replacing the direct
|
|
95
98
|
* Executor root with the native nested-Job owner. The actual Node target sees
|