@yukino.js/yukino 0.0.7 → 0.0.8
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 +130 -25
- package/dist/a2a-GBVNBDMY.js +14 -0
- package/dist/{acp-76S2XII3.js → acp-C6VUCEZ6.js} +7 -7
- package/dist/anthropic-ZEQI4K52.js +4 -0
- package/dist/chunk-37IAJFPF.js +4 -0
- package/dist/{chunk-NG62ISUV.js → chunk-3P7BR7SO.js} +8 -8
- package/dist/{chunk-7PPWFSIC.js → chunk-6XDMANXO.js} +1 -1
- package/dist/{chunk-HWDSXNX4.js → chunk-L5C5JBLP.js} +1 -1
- package/dist/chunk-MU6PSBZT.js +358 -0
- package/dist/chunk-WGFROGUC.js +8 -0
- package/dist/{chunk-QRO6H32L.js → chunk-YHE4BT76.js} +148 -148
- package/dist/esm-4KOJC56H.js +225 -0
- package/dist/fe/dist/index.html +21 -0
- package/dist/fe/dist/static/index.css +2 -0
- package/dist/fe/dist/static/index.js +203 -0
- package/dist/lib/{anthropic-CDPTNR5L.js → anthropic-K7VWTSFH.js} +2 -2
- package/dist/lib/{chunk-EO23VPDZ.js → chunk-2NA2RSV7.js} +1 -9
- package/dist/lib/{chunk-PEV5NGQ2.js → chunk-E2DXHLHR.js} +1 -1
- package/dist/lib/{chunk-HE4RUUZP.js → chunk-IIL5NGQF.js} +461 -457
- package/dist/lib/{chunk-OYQY3Q45.js → chunk-K532PPI6.js} +0 -2
- package/dist/lib/{chunk-TKCJSTWI.js → chunk-RJQT6B2O.js} +1 -1
- package/dist/lib/index.d.ts +402 -3616
- package/dist/lib/index.js +2733 -1893
- package/dist/lib/{openai-TEFKPV7T.js → openai-6MPSWGKN.js} +2 -2
- package/dist/lib/{providers-2X5JB2JX.js → providers-N52Y2QTJ.js} +1 -1
- package/dist/lib/{tool-filter-HUVHJN3O.js → tool-filter-F4S25GMJ.js} +1 -1
- package/dist/main.js +366 -237
- package/dist/{openai-RYXW7AKZ.js → openai-VV2RYB77.js} +1 -1
- package/dist/{providers-YG2HYIG6.js → providers-UD3DPALA.js} +1 -1
- package/dist/server-FXK26WN2.js +4 -0
- package/package.json +11 -12
- package/dist/anthropic-WK6EYMUE.js +0 -4
- package/dist/chunk-4GE22WHI.js +0 -4
- package/dist/chunk-7ZBAF7M4.js +0 -4
- package/dist/chunk-QQZCYWYI.js +0 -241
- package/dist/esm-5V3TYPZK.js +0 -229
- package/dist/lib/chunk-EFNPK4SJ.js +0 -137
- package/dist/lib/sandbox-runtime-QDN5SXPM.js +0 -9
- package/dist/sandbox-runtime-ELKAYRIL.js +0 -4
- package/dist/server-66HLMSUR.js +0 -4
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
|
+
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
+
import{a as Et,b as Yr,c as Wr}from"./chunk-MU6PSBZT.js";import"./chunk-WGFROGUC.js";import{n as Gr,o as Kr,q as Qr,s as br}from"./chunk-YHE4BT76.js";import"./chunk-VU3JWAJR.js";import{a as Vr}from"./chunk-L5C5JBLP.js";import"./chunk-JFKC4VCA.js";import"./chunk-6XDMANXO.js";import{b as zr,c as Fr,d as Br,e as Hr}from"./chunk-37IAJFPF.js";import{Q as Oe,j as qr}from"./chunk-3P7BR7SO.js";import{D as R}from"./chunk-IW5L5276.js";import"./chunk-NAQRFHUX.js";import"./chunk-VM4YKTHC.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import{d as Kt,e as Nt}from"./chunk-7MKA3SHV.js";var _n={};Kt(_n,{parseA2aAddress:()=>En,runA2aServer:()=>$r,startA2aServer:()=>On});import{createServer as Sl}from"http";var vn=class{request;taskId;contextId;context;task;referenceTasks;constructor(t,e,r,i,a,n){if(!t.message)throw new Error("RequestContext requires request.message to be set.");this.request=structuredClone(t),this.taskId=e,this.contextId=r,this.context=i,this.task=a,this.referenceTasks=n}get userMessage(){return this.request.message}},x={message:t=>({kind:"message",data:t}),task:t=>({kind:"task",data:t}),statusUpdate:t=>({kind:"statusUpdate",data:t}),artifactUpdate:t=>({kind:"artifactUpdate",data:t})};function Ie(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var ri=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function Xr(t){return t instanceof ri}var yn=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new ri("event",{detail:t}))}finished(){this.dispatchEvent(new Event("finished"))}on(t,e){return t==="event"?this.addEventListenerInternal(e):this.addFinishedListenerInternal(e),this}off(t,e){return t==="event"?this.removeEventListenerInternal(e):this.removeFinishedListenerInternal(e),this}once(t,e){return t==="event"?this.addEventListenerOnceInternal(e):this.addFinishedListenerOnceInternal(e),this}removeAllListeners(t){if(t===void 0||t==="event"){for(let e of this.eventListeners.values())for(let r of e)this.removeEventListener("event",r);this.eventListeners.clear()}if(t===void 0||t==="finished"){for(let e of this.finishedListeners.values())for(let r of e)this.removeEventListener("finished",r);this.finishedListeners.clear()}return this}trackListener(t,e,r){let i=t.get(e);i?i.push(r):t.set(e,[r])}untrackWrappedListener(t,e,r){let i=t.get(e);if(i&&i.length>0){let a=i.indexOf(r);a!==-1&&(i.splice(a,1),i.length===0&&t.delete(e))}}addEventListenerInternal(t){let e=r=>{if(!Xr(r))throw new Error('Internal error: expected CustomEvent for "event" type');t.call(this,r.detail)};this.trackListener(this.eventListeners,t,e),this.addEventListener("event",e)}removeEventListenerInternal(t){let e=this.eventListeners.get(t);if(e&&e.length>0){let r=e.pop();e.length===0&&this.eventListeners.delete(t),this.removeEventListener("event",r)}}addEventListenerOnceInternal(t){let e=r=>{if(!Xr(r))throw new Error('Internal error: expected CustomEvent for "event" type');this.untrackWrappedListener(this.eventListeners,t,e),t.call(this,r.detail)};this.trackListener(this.eventListeners,t,e),this.addEventListener("event",e,{once:!0})}addFinishedListenerInternal(t){let e=()=>{t.call(this)};this.trackListener(this.finishedListeners,t,e),this.addEventListener("finished",e)}removeFinishedListenerInternal(t){let e=this.finishedListeners.get(t);if(e&&e.length>0){let r=e.pop();e.length===0&&this.finishedListeners.delete(t),this.removeEventListener("finished",r)}}addFinishedListenerOnceInternal(t){let e=()=>{this.untrackWrappedListener(this.finishedListeners,t,e),t.call(this)};this.trackListener(this.finishedListeners,t,e),this.addEventListener("finished",e,{once:!0})}},An={createFrom:(t,e)=>t?.includes(e)?t:[...t??[],e],parseServiceParameter:t=>{if(!t)return[];let e=new Set(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));return Array.from(e)},toServiceParameter:t=>t.join(",")},kn="0.3";var In=class{_requestedExtensions;_user;_requestedVersion;_tenant;_activatedExtensions;_state;constructor(t){this._requestedExtensions=t?.requestedExtensions,this._user=t?.user,this._tenant=t?.tenant,this._requestedVersion=t?.requestedVersion||kn,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=An.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function Ce(t){return t.user?.userName||"unknown"}var Rn="a2a-protocol.org",Cn="type.googleapis.com/google.rpc.ErrorInfo",ii=Symbol.for("@a2a-js/sdk.A2AError"),Wt=class ai extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(ii in e))return!1;if(this===ai)return!0;for(let r=Object.getPrototypeOf(e);r!==null;r=Object.getPrototypeOf(r))if(r.constructor?.name===this.name)return!0;return!1}constructor(e){let r=typeof e=="string"?{message:e}:e;super(r?.message??"An unexpected error occurred.",r?.cause!==void 0?{cause:r.cause}:void 0),this.name=new.target.name,r?.metadata&&Object.keys(r.metadata).length>0&&(this.metadata=r.metadata)}toErrorInfo(){return{"@type":Cn,reason:this.reason,domain:Rn,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Wt.prototype,ii,{value:!0});var ni=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],et=Object.freeze(Object.fromEntries(ni.map(t=>[t.name,t]))),_l=Object.freeze(Object.fromEntries(ni.map(t=>[t.reason,t])));function rt(t){return{[t.name]:class extends Wt{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var V=rt(et.TaskNotFoundError),Re=rt(et.TaskNotCancelableError),Pt=rt(et.PushNotificationNotSupportedError),St=rt(et.UnsupportedOperationError),si=rt(et.ContentTypeNotSupportedError),Un=rt(et.InvalidAgentResponseError),oi=rt(et.ExtendedAgentCardNotConfiguredError),di=rt(et.ExtensionSupportRequiredError),Jn=rt(et.VersionNotSupportedError),F=rt(et.RequestMalformedError),li=Object.freeze({TaskNotFoundError:V,TaskNotCancelableError:Re,PushNotificationNotSupportedError:Pt,UnsupportedOperationError:St,ContentTypeNotSupportedError:si,InvalidAgentResponseError:Un,ExtendedAgentCardNotConfiguredError:oi,ExtensionSupportRequiredError:di,VersionNotSupportedError:Jn,RequestMalformedError:F});function Zr(t){if(t instanceof Error)return t.message;if(t==null)return String(t);if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var G={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},tt={OK:"OK",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN",INVALID_ARGUMENT:"INVALID_ARGUMENT",DEADLINE_EXCEEDED:"DEADLINE_EXCEEDED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",PERMISSION_DENIED:"PERMISSION_DENIED",RESOURCE_EXHAUSTED:"RESOURCE_EXHAUSTED",FAILED_PRECONDITION:"FAILED_PRECONDITION",ABORTED:"ABORTED",OUT_OF_RANGE:"OUT_OF_RANGE",UNIMPLEMENTED:"UNIMPLEMENTED",INTERNAL:"INTERNAL",UNAVAILABLE:"UNAVAILABLE",DATA_LOSS:"DATA_LOSS",UNAUTHENTICATED:"UNAUTHENTICATED"},wn=Object.freeze({TaskNotFoundError:G.NOT_FOUND,TaskNotCancelableError:G.BAD_REQUEST,PushNotificationNotSupportedError:G.BAD_REQUEST,UnsupportedOperationError:G.BAD_REQUEST,ContentTypeNotSupportedError:G.BAD_REQUEST,InvalidAgentResponseError:G.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:G.BAD_REQUEST,ExtensionSupportRequiredError:G.BAD_REQUEST,VersionNotSupportedError:G.BAD_REQUEST,RequestMalformedError:G.BAD_REQUEST}),vl=Object.freeze({TaskNotFoundError:tt.NOT_FOUND,TaskNotCancelableError:tt.FAILED_PRECONDITION,PushNotificationNotSupportedError:tt.FAILED_PRECONDITION,UnsupportedOperationError:tt.FAILED_PRECONDITION,ContentTypeNotSupportedError:tt.INVALID_ARGUMENT,InvalidAgentResponseError:tt.INTERNAL,ExtendedAgentCardNotConfiguredError:tt.FAILED_PRECONDITION,ExtensionSupportRequiredError:tt.FAILED_PRECONDITION,VersionNotSupportedError:tt.FAILED_PRECONDITION,RequestMalformedError:tt.INVALID_ARGUMENT});function it(t){let e=li[t],r=wn[t]??G.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var xn=it("TaskNotFoundError"),Pn=it("TaskNotCancelableError"),Dn=it("PushNotificationNotSupportedError"),Mn=it("UnsupportedOperationError"),Ln=it("ContentTypeNotSupportedError"),$n=it("InvalidAgentResponseError"),qn=it("ExtendedAgentCardNotConfiguredError"),zn=it("ExtensionSupportRequiredError"),Fn=it("VersionNotSupportedError"),Bn=it("RequestMalformedError"),yl=Object.freeze({TaskNotFoundError:xn,TaskNotCancelableError:Pn,PushNotificationNotSupportedError:Dn,UnsupportedOperationError:Mn,ContentTypeNotSupportedError:Ln,InvalidAgentResponseError:$n,ExtendedAgentCardNotConfiguredError:qn,ExtensionSupportRequiredError:zn,VersionNotSupportedError:Fn,RequestMalformedError:Bn}),L={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},ui=Object.freeze({TaskNotFoundError:L.TASK_NOT_FOUND,TaskNotCancelableError:L.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:L.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:L.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:L.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:L.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:L.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:L.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:L.VERSION_NOT_SUPPORTED,RequestMalformedError:L.INVALID_PARAMS}),Al=Object.freeze(Object.fromEntries(Object.entries(ui).map(([t,e])=>[e,t])));function at(t){let e=li[t],r=ui[t]??L.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var Hn=at("TaskNotFoundError"),Vn=at("TaskNotCancelableError"),Gn=at("PushNotificationNotSupportedError"),Kn=at("UnsupportedOperationError"),Qn=at("ContentTypeNotSupportedError"),bn=at("InvalidAgentResponseError"),Yn=at("ExtendedAgentCardNotConfiguredError"),Wn=at("ExtensionSupportRequiredError"),Xn=at("VersionNotSupportedError"),Zn=at("RequestMalformedError"),kl=Object.freeze({TaskNotFoundError:Hn,TaskNotCancelableError:Vn,PushNotificationNotSupportedError:Gn,UnsupportedOperationError:Kn,ContentTypeNotSupportedError:Qn,InvalidAgentResponseError:bn,ExtendedAgentCardNotConfiguredError:Yn,ExtensionSupportRequiredError:Wn,VersionNotSupportedError:Xn,RequestMalformedError:Zn});var Il={[L.PARSE_ERROR]:"RequestMalformedError",[L.INVALID_REQUEST]:"RequestMalformedError",[L.METHOD_NOT_FOUND]:"RequestMalformedError"};function jn(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function ts(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function es(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function rs(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var jr={fromJSON(t){return{id:v(t.id)?globalThis.String(t.id):"",contextId:v(t.contextId)?globalThis.String(t.contextId):v(t.context_id)?globalThis.String(t.context_id):"",status:v(t.status)?Xt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>jt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Ot.fromJSON(e)):[],metadata:_t(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Xt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>jt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Ot.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Xt={fromJSON(t){return{state:v(t.state)?jn(t.state):0,message:v(t.message)?Ot.fromJSON(t.message):void 0,timestamp:v(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=ts(t.state)),t.message!==void 0&&(e.message=Ot.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Zt={fromJSON(t){return{content:v(t.text)?{$case:"text",value:globalThis.String(t.text)}:v(t.raw)?{$case:"raw",value:Buffer.from(as(t.raw))}:v(t.url)?{$case:"url",value:globalThis.String(t.url)}:v(t.data)?{$case:"data",value:t.data}:void 0,metadata:_t(t.metadata)?t.metadata:void 0,filename:v(t.filename)?globalThis.String(t.filename):"",mediaType:v(t.mediaType)?globalThis.String(t.mediaType):v(t.media_type)?globalThis.String(t.media_type):""}},toJSON(t){let e={};return t.content?.$case==="text"?e.text=t.content.value:t.content?.$case==="raw"?e.raw=ns(t.content.value):t.content?.$case==="url"?e.url=t.content.value:t.content?.$case==="data"&&(e.data=t.content.value),t.metadata!==void 0&&(e.metadata=t.metadata),t.filename!==""&&(e.filename=t.filename),t.mediaType!==""&&(e.mediaType=t.mediaType),e}},Ot={fromJSON(t){return{messageId:v(t.messageId)?globalThis.String(t.messageId):v(t.message_id)?globalThis.String(t.message_id):"",contextId:v(t.contextId)?globalThis.String(t.contextId):v(t.context_id)?globalThis.String(t.context_id):"",taskId:v(t.taskId)?globalThis.String(t.taskId):v(t.task_id)?globalThis.String(t.task_id):"",role:v(t.role)?es(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:_t(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[],referenceTaskIds:globalThis.Array.isArray(t?.referenceTaskIds)?t.referenceTaskIds.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.reference_task_ids)?t.reference_task_ids.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=rs(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Zt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),t.referenceTaskIds?.length&&(e.referenceTaskIds=t.referenceTaskIds),e}},jt={fromJSON(t){return{artifactId:v(t.artifactId)?globalThis.String(t.artifactId):v(t.artifact_id)?globalThis.String(t.artifact_id):"",name:v(t.name)?globalThis.String(t.name):"",description:v(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:_t(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>Zt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},_e={fromJSON(t){return{taskId:v(t.taskId)?globalThis.String(t.taskId):v(t.task_id)?globalThis.String(t.task_id):"",contextId:v(t.contextId)?globalThis.String(t.contextId):v(t.context_id)?globalThis.String(t.context_id):"",status:v(t.status)?Xt.fromJSON(t.status):void 0,metadata:_t(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Xt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ve={fromJSON(t){return{taskId:v(t.taskId)?globalThis.String(t.taskId):v(t.task_id)?globalThis.String(t.task_id):"",contextId:v(t.contextId)?globalThis.String(t.contextId):v(t.context_id)?globalThis.String(t.context_id):"",artifact:v(t.artifact)?jt.fromJSON(t.artifact):void 0,append:v(t.append)?globalThis.Boolean(t.append):!1,lastChunk:v(t.lastChunk)?globalThis.Boolean(t.lastChunk):v(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:_t(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=jt.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}};var is={fromJSON(t){return{payload:v(t.task)?{$case:"task",value:jr.fromJSON(t.task)}:v(t.message)?{$case:"message",value:Ot.fromJSON(t.message)}:v(t.statusUpdate)?{$case:"statusUpdate",value:_e.fromJSON(t.statusUpdate)}:v(t.status_update)?{$case:"statusUpdate",value:_e.fromJSON(t.status_update)}:v(t.artifactUpdate)?{$case:"artifactUpdate",value:ve.fromJSON(t.artifactUpdate)}:v(t.artifact_update)?{$case:"artifactUpdate",value:ve.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=jr.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Ot.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=_e.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=ve.toJSON(t.payload.value)),e}};function as(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function ns(t){return globalThis.Buffer.from(t).toString("base64")}function _t(t){return typeof t=="object"&&t!==null}function v(t){return t!=null}var ss="1.0",ci="0.3",os="application/a2a+json",fi=50,Rl=4*1024*1024,Dt=[3,4,5,7],ds=[0,1,2,3,4,5,6,7,8],pi=[6],hi=[8],ls=[...pi,...hi];function ti(t){return"status"in t}function ei(t,e){return{tenant:t.tenant??"",owner:e(t)}}function us(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function cs(t){try{let[e,...r]=Buffer.from(t,"base64").toString("utf-8").split("|");if(r.length===0)throw new F("Invalid page token format.");return{timestamp:e,id:r.join("|")}}catch(e){throw e instanceof F?e:new F("Token is not a valid base64-encoded cursor.")}}var Ue=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=ei(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ei(t,this._ownerResolver),i=this._store.get(e);i||(i=new Map,this._store.set(e,i));let a=i.get(r);return a||(a=new Map,i.set(r,a)),a}},ye=new In,Je=class{_scopedBuses;constructor(t=Ce){this._scopedBuses=new Ue(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??ye),i=r.get(t);return i||(i=new yn,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??ye)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??ye);r?.get(t)?.removeAllListeners(),r?.delete(t)}},Qt=class{eventBus;eventQueue=[];resolvePromise;stopped=!1;constructor(t){this.eventBus=t,this.eventBus.on("event",this.handleEvent),this.eventBus.on("finished",this.handleFinished)}handleEvent=t=>{this.stopped||(this.eventQueue.push(t),this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=void 0))};handleFinished=()=>{this.stop()};async*events(){for(;!this.stopped||this.eventQueue.length>0;)if(this.eventQueue.length>0){let t=this.eventQueue.shift();if(yield t,t.kind==="message"||t.kind==="statusUpdate"&&t.data.status&&(Dt.includes(t.data.status.state)||pi.includes(t.data.status.state))){this.handleFinished();break}}else this.stopped||await new Promise(t=>{this.resolvePromise=t})}stop(){this.stopped=!0,this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=void 0),this.eventBus.off("event",this.handleEvent),this.eventBus.off("finished",this.handleFinished)}},bt=new Map;function Ae(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function ke(t,e){let i=(bt.get(t)??Promise.resolve()).then(e,e);bt.set(t,i);let a=()=>{bt.get(t)===i&&bt.delete(t)};return i.then(a,a),i}var Yt=class{taskStore;serverCallContext;currentTask;latestUserMessage;finalMessageResult;lastSeenTaskId;constructor(t,e){this.taskStore=t,this.serverCallContext=e}setContext(t){this.latestUserMessage=structuredClone(t)}async processEvent(t){switch(t.kind){case"message":{this.finalMessageResult=structuredClone(t.data);break}case"task":{let e=t.data;if(!e.id){await this.processTaskEventLocked(e);break}await ke(Ae(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Ie(t)}}notePersistedTaskId(t){t&&(this.lastSeenTaskId&&this.lastSeenTaskId!==t&&console.warn(`ResultManager: event for task ${t} arrived after processing events for ${this.lastSeenTaskId}. This indicates the executor switched tasks mid-stream, which is not expected in normal operation.`),this.lastSeenTaskId=t)}async processTaskEventLocked(t){this.notePersistedTaskId(t.id);let e=t.id?await this.taskStore.load(t.id,this.serverCallContext):void 0,r=structuredClone(t);if(e&&e.id===t.id&&((!r.history||r.history.length===0)&&e.history&&(r.history=structuredClone(e.history)),r.artifacts=this.mergeArtifacts(e.artifacts,t.artifacts),(e.metadata||t.metadata)&&(r.metadata={...structuredClone(e.metadata??{}),...structuredClone(t.metadata??{})})),this.latestUserMessage){let i=this.latestUserMessage;r.history?.find(a=>a.messageId===i.messageId)||(r.history=[structuredClone(i),...r.history||[]])}this.currentTask=r,await this.saveCurrentTask()}async loadPersistedTask(t,e){if(!t)return;let r=await this.taskStore.load(t,this.serverCallContext);return r||console.warn(`ResultManager: Received ${e} for unknown task ${t}`),r}async applyStatusUpdate(t){this.notePersistedTaskId(t.taskId);let e=await this.loadPersistedTask(t.taskId,"status update");if(!e||e.id!==t.taskId){this.currentTask=e;return}let r=e.status?.state;if(r!==void 0&&Dt.includes(r)&&t.status?.state!==r){console.warn(`ResultManager: ignoring status update ${t.status?.state} for terminal task ${e.id} (${r})`),this.currentTask=e;return}e.status=structuredClone(t.status),t.metadata&&(e.metadata={...e.metadata,...structuredClone(t.metadata)});let i=t.status?.message;i&&(e.history?.find(a=>a.messageId===i.messageId)||(e.history=[...e.history||[],structuredClone(i)])),this.currentTask=e,await this.saveCurrentTask()}async applyArtifactUpdate(t){let e=t.artifact;if(!e)return;this.notePersistedTaskId(t.taskId);let r=await this.loadPersistedTask(t.taskId,"artifact update");if(!r||r.id!==t.taskId){this.currentTask=r;return}r.artifacts||(r.artifacts=[]);let i=r.artifacts.findIndex(a=>a.artifactId===e.artifactId);if(i!==-1)if(t.append){let a=r.artifacts[i];a.parts=[...a.parts||[],...structuredClone(e.parts||[])],e.description&&(a.description=e.description),e.name&&(a.name=e.name),e.metadata&&(a.metadata={...a.metadata,...structuredClone(e.metadata)})}else r.artifacts[i]=structuredClone(e);else r.artifacts.push(structuredClone(e));t.metadata&&(r.metadata={...r.metadata,...structuredClone(t.metadata)}),this.currentTask=r,await this.saveCurrentTask()}mergeArtifacts(t,e){if(!t||t.length===0)return e?structuredClone(e):[];if(!e||e.length===0)return structuredClone(t);let r=new Map;for(let n of e)r.set(n.artifactId,n);let i=t.map(n=>structuredClone(r.get(n.artifactId)??n)),a=new Set(t.map(n=>n.artifactId));for(let n of e)a.has(n.artifactId)||i.push(structuredClone(n));return i}async saveCurrentTask(){this.currentTask&&await this.taskStore.save(this.currentTask,this.serverCallContext)}getFinalResult(){return this.finalMessageResult?this.finalMessageResult:this.currentTask}getCurrentTask(){return this.currentTask}},fs=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(t)}async save(t,e,r){let i=this._scopedStore.getOrCreateBucket(e),a=i.get(t)||[];r.id||(r.id=crypto.randomUUID());let n=e.requestedVersion||ci,o=a.findIndex(l=>l.config.id===r.id);o!==-1&&a.splice(o,1),a.push({config:structuredClone(r),wireVersion:n}),i.set(t,a)}async load(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?r.map(i=>structuredClone(i.config)):[]}async loadWithMetadata(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?r.map(i=>structuredClone(i)):[]}async delete(t,e,r){r===void 0&&(r=t);let i=this._scopedStore.getBucket(e);if(!i)return;let a=i.get(t);if(!a)return;let n=a.findIndex(o=>o.config.id===r);n!==-1&&a.splice(n,1),a.length===0&&i.delete(t)}},ps=class{serialize(t,e){return{body:JSON.stringify(is.toJSON(t)),contentType:os}}},hs=class{pushNotificationStore;notificationChain;options;serializers;fallbackSerializer;warnedMissingSerializers=new Set;constructor(t,e={}){this.pushNotificationStore=t,this.notificationChain=new Map,this.options={timeout:e.timeout??5e3,tokenHeaderName:e.tokenHeaderName??"X-A2A-Notification-Token"};let r=new ps;if(this.serializers=new Map([["1.0",r]]),e.serializers)for(let[i,a]of Object.entries(e.serializers))a&&this.serializers.set(i,a);this.fallbackSerializer=this.serializers.get("1.0")??r}async send(t,e,r){let i=this._getTaskId(t);if(!i)return;let a=await this._loadStoredConfigs(i,e);if(!a||a.length===0)return;let o=(this.notificationChain.get(i)??Promise.resolve()).catch(()=>{}).then(async()=>{let l=a.map(async c=>{try{await this._dispatchNotification(t,c,i,r)}catch(T){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,T)}});await Promise.all(l)});return this.notificationChain.set(i,o),o.finally(()=>{this.notificationChain.get(i)===o&&this.notificationChain.delete(i)})}_getTaskId(t){let e=t.payload;if(!e)throw new Error("StreamResponse payload is undefined");switch(e.$case){case"task":return e.value.id;case"statusUpdate":case"artifactUpdate":case"message":return e.value.taskId;default:{let r=e;throw new Error(`Unknown payload case: ${r.$case}`)}}}async _loadStoredConfigs(t,e){if(this.pushNotificationStore.loadWithMetadata)return await this.pushNotificationStore.loadWithMetadata(t,e);let r=await this.pushNotificationStore.load(t,e),i=e.requestedVersion||ci;return r.map(a=>({config:a,wireVersion:i}))}_resolveSerializer(t){let e=this.serializers.get(t);return e||(this.warnedMissingSerializers.has(t)||(this.warnedMissingSerializers.add(t),console.warn(`No push notification serializer registered for wire version '${t}'; falling back to '${ss}'. Register one via DefaultPushNotificationSenderOptions.serializers to silence this warning.`)),this.fallbackSerializer)}_buildAuthHeaders(t){let e={};return t.authentication?.scheme&&t.authentication?.credentials?e.Authorization=`${t.authentication.scheme} ${t.authentication.credentials}`:t.token&&(e[this.options.tokenHeaderName]=t.token),e}async _dispatchNotification(t,e,r,i){let{config:a,wireVersion:n}=e,o=a.url,l=new AbortController,c=setTimeout(()=>l.abort(),this.options.timeout);try{let T=this._resolveSerializer(n),{body:S,contentType:_}=T.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":_,...this._buildAuthHeaders(a)},body:S,signal:l.signal});if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);console.info(`Push notification sent for task_id=${r} to URL: ${o}`)}finally{clearTimeout(c)}}},Si=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new Je,a,n,o,l,c={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=l,this.keepBusAliveStates=new Set(c.keepBusAliveStates??ls),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new fs,this.pushNotificationSender=n||new hs(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new St("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new oi;let r;return typeof this.extendedAgentCardProvider=="function"?r=await this.extendedAgentCardProvider(e):e.user?.isAuthenticated?r=this.extendedAgentCardProvider:r=this.agentCard,this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(r):r}_validateInputModes(t,e){let r=e.defaultInputModes??[];if(!(!this.validateInputModes||r.length===0)){for(let i of t.parts??[])if(i.mediaType&&!r.includes(i.mediaType))throw new si(`Media type '${i.mediaType}' is not supported. Supported media types: ${r.join(", ")}.`)}}async _createRequestContext(t,e){let r=t.message;if(!r)throw new F("request.message is required.");let i,a,n=await this.getAgentCard();this._validateInputModes(r,n);let o=n.capabilities?.extensions??[],l=new Set(e.requestedExtensions??[]),c=o.filter(p=>p.required&&!l.has(p.uri)).map(p=>p.uri);if(c.length>0)throw new di(`Client must declare support for required extensions: ${c.join(", ")}`);if(r.taskId){if(this._requireValidTaskId(r.taskId),i=await this.taskStore.load(r.taskId,e),!i)throw new V(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&Dt.includes(i.status.state))throw new St(`Task ${i.id} is in a terminal state (${i.status.state}) and cannot be modified.`);if(r.contextId&&i.contextId&&r.contextId!==i.contextId)throw new F(`contextId mismatch: message contextId '${r.contextId}' does not match task '${i.id}' contextId '${i.contextId}'`);i.history=[...i.history||[],r],await this.taskStore.save(i,e)}let T=r.taskId||crypto.randomUUID(),S=r.referenceTaskIds||[];if(S.length>0){a=[];for(let p of S){let m=await this.taskStore.load(p,e);m?a.push(m):console.warn(`Reference task ${p} not found.`)}}let _=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let p=new Set(o.map(m=>m.uri));e.setRequestedExtensions(e.requestedExtensions.filter(m=>p.has(m)))}let u={...r,contextId:_,taskId:T},N={...t,message:u};return new vn(N,T,_,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let l of r.events()){await e.processEvent(l);try{let c=await this._mapEventToStreamResponse(l,i);await this._sendPushNotificationIfNeeded(i,c,structuredClone(e.getCurrentTask()))}catch(c){console.error(`Error sending push notification: ${c}`)}if(a?.firstResultResolver&&!n){let c;if(l.kind==="message")c=l.data;else if(l.kind==="task")c=l.data;else{let T=e.getFinalResult();T&&("messageId"in T||"id"in T)&&(c=T)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&l.kind==="statusUpdate"&&l.data.status&&hi.includes(l.data.status.state)){let c=e.getCurrentTask();c&&(a.authRequiredSnapshotResolver(structuredClone(c)),o=!0,n=!0)}}a?.firstResultResolver&&a?.firstResultRejector&&!n&&a.firstResultRejector(new F("Execution finished before a message or task was produced."))}catch(l){console.error(`Event processing loop failed for task ${t}:`,l),await this._handleProcessingError(l,e,n,t,a?.firstResultRejector)}finally{r.stop()}}_continueDraining(t,e){e.catch(r=>{console.error(`Background AUTH_REQUIRED drain failed for task ${t}:`,r instanceof Error?r.message:r)})}_runExecutor(t,e,r,i){let a=Ss(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Zr(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let l={id:r.taskId,contextId:i.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:r.taskId,contextId:i.contextId,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},artifacts:[],history:r.task?.history?[...r.task.history]:[],metadata:{}};i&&!l.history?.find(c=>c.messageId===i.messageId)&&l.history?.push(i),e.publish(x.task(l)),e.publish(x.statusUpdate({taskId:l.id,contextId:l.contextId,status:l.status,metadata:{}}))}).finally(()=>{this._settleBus(t,e,a(),r.context)})}_settleBus(t,e,r,i){this.eventBusManager.settleByTaskId?.(t,e,r,i)||r!==void 0&&this.keepBusAliveStates.has(r)||(e.finished(),this.eventBusManager.cleanupByTaskId(t,i))}_runStreamExecutor(t,e,r){let i=r.userMessage,a=Ts(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Zr(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let l=a().task,c=l?.id??r.taskId,T=l?.contextId??i.contextId;if(!l){let _={id:r.taskId,contextId:i.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:r.taskId,contextId:i.contextId,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},artifacts:[],history:r.task?.history?[...r.task.history]:[],metadata:{}};i&&!_.history?.find(u=>u.messageId===i.messageId)&&_.history?.push(i),e.publish(x.task(_))}let S={taskId:c,contextId:T,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:T,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(x.statusUpdate(S))}).finally(()=>{this._settleBus(t,e,a().state,r.context)})}async sendMessage(t,e){let r=t.message;if(!r?.messageId)throw new F("message.messageId is required.");let i=t.configuration?.returnImmediately!==!0,a=new Yt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,l=n.userMessage;if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let _=structuredClone(t.configuration.taskPushNotificationConfig);_.taskId=o,await this.pushNotificationStore?.save(o,e,_)}let c=this.eventBusManager.createOrGetByTaskId(o,e),T=new Qt(c);this._runExecutor(o,c,n,l);let S=t.configuration;return i?new Promise((_,u)=>{let N=this._processEvents(o,a,T,e,{authRequiredSnapshotResolver:p=>{this._applyHistoryLengthSemantics(p,S??{}),_(p),this._continueDraining(o,N)},firstResultRejector:u});N.then(()=>{let p=a.getFinalResult();if(!p){u(new Wt("Agent execution finished without a result, and no task context found."));return}ti(p)&&this._applyHistoryLengthSemantics(p,S??{}),_(p)}).catch(u)}):new Promise((_,u)=>{this._processEvents(o,a,T,e,{firstResultResolver:N=>{ti(N)&&this._applyHistoryLengthSemantics(N,S??{}),_(N)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new F("message.messageId is required for streaming.");let i=new Yt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),l=new Qt(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let T=structuredClone(t.configuration.taskPushNotificationConfig);T.taskId=n,await this.pushNotificationStore?.save(n,e,T)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let T of l.events()){c=this._advanceStreamPattern(T,c),await i.processEvent(T);let S=await this._mapEventToStreamResponse(T,e);S.payload?.$case==="task"&&this._applyHistoryLengthSemantics(S.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,S,i.getCurrentTask()),yield S}}finally{l.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new V(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??fi;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!ds.includes(t.status))throw new F(`Invalid status filter: ${String(t.status)}`);if(t.statusTimestampAfter&&isNaN(Date.parse(t.statusTimestampAfter)))throw new F("statusTimestampAfter must be a valid ISO 8601 date string");let i=await this.taskStore.list({...t,pageSize:r},e);for(let a of i.tasks)this._applyHistoryLengthSemantics(a,t);return i}async cancelTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new V(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&Dt.includes(a))throw new Re(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let l=new Qt(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new Yt(this.taskStore,e),l,e)}else{let l={role:2,messageId:crypto.randomUUID(),taskId:i.id,contextId:i.contextId,parts:[{content:{$case:"text",value:"Task cancellation requested by user."},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]};await new Yt(this.taskStore,e).processEvent(x.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:l,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Wt(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new Re(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);return await this.pushNotificationStore?.save(r,e,t),structuredClone(t)}async getTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new V(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new V(`Push notification config with id '${t.id}' not found for task ${r}.`);return n}async listTaskPushNotificationConfigs(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new Qt(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new V(`Task not found: ${r}`);if(n.status?.state!==void 0&&Dt.includes(n.status.state))throw new St(`Task ${r} is in a terminal state (${n.status.state}) and cannot be subscribed to.`);if(yield{payload:{$case:"task",value:n}},!a)return;for await(let o of a.events())switch(o.kind){case"statusUpdate":o.data.taskId===r&&(yield{payload:{$case:"statusUpdate",value:o.data}});break;case"artifactUpdate":o.data.taskId===r&&(yield{payload:{$case:"artifactUpdate",value:o.data}});break;case"task":o.data.id===r&&(yield{payload:{$case:"task",value:o.data}});break;case"message":break;default:Ie(o)}}finally{a?.stop()}}async _mapEventToStreamResponse(t,e){switch(t.kind){case"task":{let r=t.data.id;return{payload:{$case:"task",value:await this.taskStore.load(r,e).catch(a=>(console.warn("Failed to load full task from store, falling back to event data:",a),null))||t.data}}}case"message":return{payload:{$case:"message",value:t.data}};case"statusUpdate":return{payload:{$case:"statusUpdate",value:t.data}};case"artifactUpdate":return{payload:{$case:"artifactUpdate",value:t.data}};default:Ie(t)}}async _sendPushNotificationIfNeeded(t,e,r){this.agentCard.capabilities?.pushNotifications&&this.pushNotificationSender&&this.pushNotificationSender.send(e,t,r).catch(i=>{console.error("Failed to send push notification:",i)})}async _handleProcessingError(t,e,r,i,a){if(a&&!r){a(t);return}if(!a)throw t;let n=e.getCurrentTask(),o=t instanceof Error&&t.message||"Unknown error";if(n){let l={taskId:n.id,contextId:n.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:n.id,contextId:n.contextId,parts:[{content:{$case:"text",value:`Event processing loop failed: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};try{await e.processEvent(x.statusUpdate(l))}catch(c){console.error(`Event processing loop failed for task ${i}: ${c instanceof Error&&c.message||"Unknown error"}`)}}else console.error(`Event processing loop failed for task ${i}: ${o}`)}_advanceStreamPattern(t,e){switch(e){case"undetermined":if(t.kind==="message")return"message-only";if(t.kind==="task")return"task-lifecycle";throw new St(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new St(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new St(`Stream ordering violation: received ${t.kind} in task lifecycle stream.`);return e}}_requireValidTaskId(t){if(!t||t.trim()==="")throw new F("Task ID is required")}_applyHistoryLengthSemantics(t,e){e.historyLength!==void 0&&(e.historyLength<=0?t.history=[]:t.history=(t.history??[]).slice(-e.historyLength))}};function Ss(t){let e,r=i=>{(i.kind==="task"&&i.data.status?.state!==void 0||i.kind==="statusUpdate"&&i.data.status?.state!==void 0)&&(e=i.data.status.state)};return t.on("event",r),()=>(t.off("event",r),e)}function Ts(t){let e,r,i=a=>{a.kind==="task"?(e=a.data,a.data.status?.state!==void 0&&(r=a.data.status.state)):a.kind==="statusUpdate"&&a.data.status?.state!==void 0&&(r=a.data.status.state)};return t.on("event",i),()=>(t.off("event",i),{task:e,state:r})}var Ti=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(t)}async load(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?structuredClone(r):void 0}async save(t,e){this._scopedStore.getOrCreateBucket(e).set(t.id,structuredClone(t))}async list(t,e){let{contextId:r,status:i,pageSize:a=fi,pageToken:n,statusTimestampAfter:o,includeArtifacts:l=!1}=t,c=this._scopedStore.getBucket(e),T=c?Array.from(c.values()):[];if(r&&(T=T.filter(p=>p.contextId===r)),i!==void 0&&i!==0&&(T=T.filter(p=>p.status?.state===i)),o){let p=new Date(o).getTime();T=T.filter(m=>m.status?.timestamp&&new Date(m.status.timestamp).getTime()>p)}T.sort((p,m)=>{let y=p.status?.timestamp||"",C=m.status?.timestamp||"";return C!==y?C.localeCompare(y):m.id.localeCompare(p.id)});let S=T.length;if(n){let p=cs(n),m=T.findIndex(y=>(y.status?.timestamp||"")===p.timestamp&&y.id===p.id);m!==-1?T=T.slice(m+1):T=[]}let _=T.slice(0,a),u=_.map(p=>{let m=structuredClone(p);return l||(m.artifacts=[]),m}),N="";if(_.length>0&&T.length>_.length){let p=_[_.length-1];N=us(p.status?.timestamp||"",p.id)}return{tasks:u,nextPageToken:N,pageSize:a,totalSize:S}}};var ir=Nt(Et(),1);var xa=Nt(Et(),1),Pa=Nt(Et(),1),cr=Nt(Et(),1),fr=Nt(Et(),1);import id from"crypto";import ad from"crypto";var gs=class{get isAuthenticated(){return!1}get userName(){return""}},pr={noAuthentication:()=>Promise.resolve(new gs)};async function*hr(t){let e=!1;try{for(;;){let r;try{r=await t.next()}catch(i){throw e=!0,i}if(r.done)return;yield r.value}}finally{e||await t.return?.()}}function Sr(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function Xi(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function ms(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function Ns(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var gi={fromJSON(t){return{acceptedOutputModes:globalThis.Array.isArray(t?.acceptedOutputModes)?t.acceptedOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.accepted_output_modes)?t.accepted_output_modes.map(e=>globalThis.String(e)):[],taskPushNotificationConfig:s(t.taskPushNotificationConfig)?b.fromJSON(t.taskPushNotificationConfig):s(t.task_push_notification_config)?b.fromJSON(t.task_push_notification_config):void 0,historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0,returnImmediately:s(t.returnImmediately)?globalThis.Boolean(t.returnImmediately):s(t.return_immediately)?globalThis.Boolean(t.return_immediately):!1}},toJSON(t){let e={};return t.acceptedOutputModes?.length&&(e.acceptedOutputModes=t.acceptedOutputModes),t.taskPushNotificationConfig!==void 0&&(e.taskPushNotificationConfig=b.toJSON(t.taskPushNotificationConfig)),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),t.returnImmediately!==!1&&(e.returnImmediately=t.returnImmediately),e}},Q={fromJSON(t){return{id:s(t.id)?globalThis.String(t.id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?re.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ae.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Y.fromJSON(e)):[],metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=re.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ae.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Y.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},re={fromJSON(t){return{state:s(t.state)?Sr(t.state):0,message:s(t.message)?Y.fromJSON(t.message):void 0,timestamp:s(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=Xi(t.state)),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},ie={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(Cs(t.raw))}:s(t.url)?{$case:"url",value:globalThis.String(t.url)}:s(t.data)?{$case:"data",value:t.data}:void 0,metadata:w(t.metadata)?t.metadata:void 0,filename:s(t.filename)?globalThis.String(t.filename):"",mediaType:s(t.mediaType)?globalThis.String(t.mediaType):s(t.media_type)?globalThis.String(t.media_type):""}},toJSON(t){let e={};return t.content?.$case==="text"?e.text=t.content.value:t.content?.$case==="raw"?e.raw=Us(t.content.value):t.content?.$case==="url"?e.url=t.content.value:t.content?.$case==="data"&&(e.data=t.content.value),t.metadata!==void 0&&(e.metadata=t.metadata),t.filename!==""&&(e.filename=t.filename),t.mediaType!==""&&(e.mediaType=t.mediaType),e}},Y={fromJSON(t){return{messageId:s(t.messageId)?globalThis.String(t.messageId):s(t.message_id)?globalThis.String(t.message_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",role:s(t.role)?ms(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>ie.fromJSON(e)):[],metadata:w(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[],referenceTaskIds:globalThis.Array.isArray(t?.referenceTaskIds)?t.referenceTaskIds.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.reference_task_ids)?t.reference_task_ids.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=Ns(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>ie.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),t.referenceTaskIds?.length&&(e.referenceTaskIds=t.referenceTaskIds),e}},ae={fromJSON(t){return{artifactId:s(t.artifactId)?globalThis.String(t.artifactId):s(t.artifact_id)?globalThis.String(t.artifact_id):"",name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>ie.fromJSON(e)):[],metadata:w(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>ie.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},we={fromJSON(t){return{taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?re.fromJSON(t.status):void 0,metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=re.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},xe={fromJSON(t){return{taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",artifact:s(t.artifact)?ae.fromJSON(t.artifact):void 0,append:s(t.append)?globalThis.Boolean(t.append):!1,lastChunk:s(t.lastChunk)?globalThis.Boolean(t.lastChunk):s(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=ae.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}},mi={fromJSON(t){return{scheme:s(t.scheme)?globalThis.String(t.scheme):"",credentials:s(t.credentials)?globalThis.String(t.credentials):""}},toJSON(t){let e={};return t.scheme!==""&&(e.scheme=t.scheme),t.credentials!==""&&(e.credentials=t.credentials),e}},Pe={fromJSON(t){return{url:s(t.url)?globalThis.String(t.url):"",protocolBinding:s(t.protocolBinding)?globalThis.String(t.protocolBinding):s(t.protocol_binding)?globalThis.String(t.protocol_binding):"",tenant:s(t.tenant)?globalThis.String(t.tenant):"",protocolVersion:s(t.protocolVersion)?globalThis.String(t.protocolVersion):s(t.protocol_version)?globalThis.String(t.protocol_version):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.protocolBinding!==""&&(e.protocolBinding=t.protocolBinding),t.tenant!==""&&(e.tenant=t.tenant),t.protocolVersion!==""&&(e.protocolVersion=t.protocolVersion),e}},Zi={fromJSON(t){return{name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",supportedInterfaces:globalThis.Array.isArray(t?.supportedInterfaces)?t.supportedInterfaces.map(e=>Pe.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>Pe.fromJSON(e)):[],provider:s(t.provider)?Ni.fromJSON(t.provider):void 0,version:s(t.version)?globalThis.String(t.version):"",documentationUrl:s(t.documentationUrl)?globalThis.String(t.documentationUrl):s(t.documentation_url)?globalThis.String(t.documentation_url):void 0,capabilities:s(t.capabilities)?Ei.fromJSON(t.capabilities):void 0,securitySchemes:w(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):w(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.fromJSON(e)):[],defaultInputModes:globalThis.Array.isArray(t?.defaultInputModes)?t.defaultInputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_input_modes)?t.default_input_modes.map(e=>globalThis.String(e)):[],defaultOutputModes:globalThis.Array.isArray(t?.defaultOutputModes)?t.defaultOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_output_modes)?t.default_output_modes.map(e=>globalThis.String(e)):[],skills:globalThis.Array.isArray(t?.skills)?t.skills.map(e=>_i.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>vi.fromJSON(e)):[],iconUrl:s(t.iconUrl)?globalThis.String(t.iconUrl):s(t.icon_url)?globalThis.String(t.icon_url):void 0}},toJSON(t){let e={};if(t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.supportedInterfaces?.length&&(e.supportedInterfaces=t.supportedInterfaces.map(r=>Pe.toJSON(r))),t.provider!==void 0&&(e.provider=Ni.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Ei.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=De.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>yt.toJSON(r))),t.defaultInputModes?.length&&(e.defaultInputModes=t.defaultInputModes),t.defaultOutputModes?.length&&(e.defaultOutputModes=t.defaultOutputModes),t.skills?.length&&(e.skills=t.skills.map(r=>_i.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>vi.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},Ni={fromJSON(t){return{url:s(t.url)?globalThis.String(t.url):"",organization:s(t.organization)?globalThis.String(t.organization):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.organization!==""&&(e.organization=t.organization),e}},Ei={fromJSON(t){return{streaming:s(t.streaming)?globalThis.Boolean(t.streaming):void 0,pushNotifications:s(t.pushNotifications)?globalThis.Boolean(t.pushNotifications):s(t.push_notifications)?globalThis.Boolean(t.push_notifications):void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>Oi.fromJSON(e)):[],extendedAgentCard:s(t.extendedAgentCard)?globalThis.Boolean(t.extendedAgentCard):s(t.extended_agent_card)?globalThis.Boolean(t.extended_agent_card):void 0}},toJSON(t){let e={};return t.streaming!==void 0&&(e.streaming=t.streaming),t.pushNotifications!==void 0&&(e.pushNotifications=t.pushNotifications),t.extensions?.length&&(e.extensions=t.extensions.map(r=>Oi.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},Oi={fromJSON(t){return{uri:s(t.uri)?globalThis.String(t.uri):"",description:s(t.description)?globalThis.String(t.description):"",required:s(t.required)?globalThis.Boolean(t.required):!1,params:w(t.params)?t.params:void 0}},toJSON(t){let e={};return t.uri!==""&&(e.uri=t.uri),t.description!==""&&(e.description=t.description),t.required!==!1&&(e.required=t.required),t.params!==void 0&&(e.params=t.params),e}},_i={fromJSON(t){return{id:s(t.id)?globalThis.String(t.id):"",name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",tags:globalThis.Array.isArray(t?.tags)?t.tags.map(e=>globalThis.String(e)):[],examples:globalThis.Array.isArray(t?.examples)?t.examples.map(e=>globalThis.String(e)):[],inputModes:globalThis.Array.isArray(t?.inputModes)?t.inputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.input_modes)?t.input_modes.map(e=>globalThis.String(e)):[],outputModes:globalThis.Array.isArray(t?.outputModes)?t.outputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.output_modes)?t.output_modes.map(e=>globalThis.String(e)):[],securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.fromJSON(e)):[]}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.tags?.length&&(e.tags=t.tags),t.examples?.length&&(e.examples=t.examples),t.inputModes?.length&&(e.inputModes=t.inputModes),t.outputModes?.length&&(e.outputModes=t.outputModes),t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>yt.toJSON(r))),e}},vi={fromJSON(t){return{protected:s(t.protected)?globalThis.String(t.protected):"",signature:s(t.signature)?globalThis.String(t.signature):"",header:w(t.header)?t.header:void 0}},toJSON(t){let e={};return t.protected!==""&&(e.protected=t.protected),t.signature!==""&&(e.signature=t.signature),t.header!==void 0&&(e.header=t.header),e}},b={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",url:s(t.url)?globalThis.String(t.url):"",token:s(t.token)?globalThis.String(t.token):"",authentication:s(t.authentication)?mi.fromJSON(t.authentication):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.taskId!==""&&(e.taskId=t.taskId),t.url!==""&&(e.url=t.url),t.token!==""&&(e.token=t.token),t.authentication!==void 0&&(e.authentication=mi.toJSON(t.authentication)),e}},yi={fromJSON(t){return{list:globalThis.Array.isArray(t?.list)?t.list.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.list?.length&&(e.list=t.list),e}},yt={fromJSON(t){return{schemes:w(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=yi.fromJSON(i),e),{}):{}}},toJSON(t){let e={};if(t.schemes){let r=globalThis.Object.entries(t.schemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=yi.toJSON(n)}),e.schemes=i}}return e}},De={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Me.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Le.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=$e.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=qe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=ze.toJSON(t.scheme.value)),e}},Me={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",location:s(t.location)?globalThis.String(t.location):"",name:s(t.name)?globalThis.String(t.name):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.location!==""&&(e.location=t.location),t.name!==""&&(e.name=t.name),e}},Le={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",scheme:s(t.scheme)?globalThis.String(t.scheme):"",bearerFormat:s(t.bearerFormat)?globalThis.String(t.bearerFormat):s(t.bearer_format)?globalThis.String(t.bearer_format):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.scheme!==""&&(e.scheme=t.scheme),t.bearerFormat!==""&&(e.bearerFormat=t.bearerFormat),e}},$e={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?Ai.fromJSON(t.flows):void 0,oauth2MetadataUrl:s(t.oauth2MetadataUrl)?globalThis.String(t.oauth2MetadataUrl):s(t.oauth2_metadata_url)?globalThis.String(t.oauth2_metadata_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.flows!==void 0&&(e.flows=Ai.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},qe={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",openIdConnectUrl:s(t.openIdConnectUrl)?globalThis.String(t.openIdConnectUrl):s(t.open_id_connect_url)?globalThis.String(t.open_id_connect_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.openIdConnectUrl!==""&&(e.openIdConnectUrl=t.openIdConnectUrl),e}},ze={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Ai={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Be.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Be.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:ki.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:Ii.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:He.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:He.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Fe.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Be.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=ki.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=Ii.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=He.toJSON(t.flow.value)),e}},Fe={fromJSON(t){return{authorizationUrl:s(t.authorizationUrl)?globalThis.String(t.authorizationUrl):s(t.authorization_url)?globalThis.String(t.authorization_url):"",tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:w(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{},pkceRequired:s(t.pkceRequired)?globalThis.Boolean(t.pkceRequired):s(t.pkce_required)?globalThis.Boolean(t.pkce_required):!1}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return t.pkceRequired!==!1&&(e.pkceRequired=t.pkceRequired),e}},Be={fromJSON(t){return{tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:w(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},ki={fromJSON(t){return{authorizationUrl:s(t.authorizationUrl)?globalThis.String(t.authorizationUrl):s(t.authorization_url)?globalThis.String(t.authorization_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:w(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},Ii={fromJSON(t){return{tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:w(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},He={fromJSON(t){return{deviceAuthorizationUrl:s(t.deviceAuthorizationUrl)?globalThis.String(t.deviceAuthorizationUrl):s(t.device_authorization_url)?globalThis.String(t.device_authorization_url):"",tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:w(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.deviceAuthorizationUrl!==""&&(e.deviceAuthorizationUrl=t.deviceAuthorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},ne={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",message:s(t.message)?Y.fromJSON(t.message):void 0,configuration:s(t.configuration)?gi.fromJSON(t.configuration):void 0,metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.configuration!==void 0&&(e.configuration=gi.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Es={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),e}},Os={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?Sr(t.status):0,pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):void 0,pageToken:s(t.pageToken)?globalThis.String(t.pageToken):s(t.page_token)?globalThis.String(t.page_token):"",historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0,statusTimestampAfter:s(t.statusTimestampAfter)?globalThis.String(t.statusTimestampAfter):s(t.status_timestamp_after)?globalThis.String(t.status_timestamp_after):void 0,includeArtifacts:s(t.includeArtifacts)?globalThis.Boolean(t.includeArtifacts):s(t.include_artifacts)?globalThis.Boolean(t.include_artifacts):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.contextId!==""&&(e.contextId=t.contextId),t.status!==0&&(e.status=Xi(t.status)),t.pageSize!==void 0&&(e.pageSize=Math.round(t.pageSize)),t.pageToken!==""&&(e.pageToken=t.pageToken),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),t.statusTimestampAfter!==void 0&&(e.statusTimestampAfter=t.statusTimestampAfter),t.includeArtifacts!==void 0&&(e.includeArtifacts=t.includeArtifacts),e}},ji={fromJSON(t){return{tasks:globalThis.Array.isArray(t?.tasks)?t.tasks.map(e=>Q.fromJSON(e)):[],nextPageToken:s(t.nextPageToken)?globalThis.String(t.nextPageToken):s(t.next_page_token)?globalThis.String(t.next_page_token):"",pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):0,totalSize:s(t.totalSize)?globalThis.Number(t.totalSize):s(t.total_size)?globalThis.Number(t.total_size):0}},toJSON(t){let e={};return t.tasks?.length&&(e.tasks=t.tasks.map(r=>Q.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),t.pageSize!==0&&(e.pageSize=Math.round(t.pageSize)),t.totalSize!==0&&(e.totalSize=Math.round(t.totalSize)),e}},_s={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.metadata!==void 0&&(e.metadata=t.metadata),e}},vs={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},ys={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},As={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),e}},ks={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):0,pageToken:s(t.pageToken)?globalThis.String(t.pageToken):s(t.page_token)?globalThis.String(t.page_token):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.pageSize!==0&&(e.pageSize=Math.round(t.pageSize)),t.pageToken!==""&&(e.pageToken=t.pageToken),e}},Is={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},Rs={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Q.toJSON(t.payload.value):t.payload?.$case==="message"&&(e.message=Y.toJSON(t.payload.value)),e}},ar={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:we.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:we.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Q.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Y.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=we.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=xe.toJSON(t.payload.value)),e}},ta={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>b.fromJSON(e)):[],nextPageToken:s(t.nextPageToken)?globalThis.String(t.nextPageToken):s(t.next_page_token)?globalThis.String(t.next_page_token):""}},toJSON(t){let e={};return t.configs?.length&&(e.configs=t.configs.map(r=>b.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function Cs(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Us(t){return globalThis.Buffer.from(t).toString("base64")}function w(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var At="A2A-Extensions",nt="A2A-Version",Js="1.0",Ut="0.3",Tr="application/json",nr="application/a2a+json",Se={createFrom:(t,e)=>t?.includes(e)?t:[...t??[],e],parseServiceParameter:t=>{if(!t)return[];let e=new Set(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));return Array.from(e)},toServiceParameter:t=>t.join(",")},se={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function Tt(t){return`data: ${JSON.stringify(t)}
|
|
5
|
+
|
|
6
|
+
`}function oe(t){return`event: error
|
|
7
|
+
data: ${JSON.stringify(t)}
|
|
8
|
+
|
|
9
|
+
`}var Gl=4*1024*1024;function ea(t,e){let r=ji.toJSON(t),{tasks:i,nextPageToken:a,pageSize:n,totalSize:o,...l}=r,c=i??[];return{tasks:e?.includeArtifacts?c.map(ws):c,nextPageToken:a??"",pageSize:n??0,totalSize:o??0,...l}}function ws(t){if(typeof t!="object"||t===null)return t;let e=t;return e.artifacts!==void 0?e:{...e,artifacts:[]}}var xs="a2a-protocol.org",Ps="type.googleapis.com/google.rpc.ErrorInfo",ra=Symbol.for("@a2a-js/sdk.A2AError"),W=class ia extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(ra in e))return!1;if(this===ia)return!0;for(let r=Object.getPrototypeOf(e);r!==null;r=Object.getPrototypeOf(r))if(r.constructor?.name===this.name)return!0;return!1}constructor(e){let r=typeof e=="string"?{message:e}:e;super(r?.message??"An unexpected error occurred.",r?.cause!==void 0?{cause:r.cause}:void 0),this.name=new.target.name,r?.metadata&&Object.keys(r.metadata).length>0&&(this.metadata=r.metadata)}toErrorInfo(){return{"@type":Ps,reason:this.reason,domain:xs,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(W.prototype,ra,{value:!0});var aa=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],X=Object.freeze(Object.fromEntries(aa.map(t=>[t.name,t]))),Kl=Object.freeze(Object.fromEntries(aa.map(t=>[t.reason,t])));function st(t){return{[t.name]:class extends W{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var na=st(X.TaskNotFoundError),sa=st(X.TaskNotCancelableError),gr=st(X.PushNotificationNotSupportedError),oa=st(X.UnsupportedOperationError),mr=st(X.ContentTypeNotSupportedError),Ds=st(X.InvalidAgentResponseError),da=st(X.ExtendedAgentCardNotConfiguredError),Ms=st(X.ExtensionSupportRequiredError),Te=st(X.VersionNotSupportedError),$=st(X.RequestMalformedError),Nr=Object.freeze({TaskNotFoundError:na,TaskNotCancelableError:sa,PushNotificationNotSupportedError:gr,UnsupportedOperationError:oa,ContentTypeNotSupportedError:mr,InvalidAgentResponseError:Ds,ExtendedAgentCardNotConfiguredError:da,ExtensionSupportRequiredError:Ms,VersionNotSupportedError:Te,RequestMalformedError:$}),O={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},D={OK:"OK",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN",INVALID_ARGUMENT:"INVALID_ARGUMENT",DEADLINE_EXCEEDED:"DEADLINE_EXCEEDED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",PERMISSION_DENIED:"PERMISSION_DENIED",RESOURCE_EXHAUSTED:"RESOURCE_EXHAUSTED",FAILED_PRECONDITION:"FAILED_PRECONDITION",ABORTED:"ABORTED",OUT_OF_RANGE:"OUT_OF_RANGE",UNIMPLEMENTED:"UNIMPLEMENTED",INTERNAL:"INTERNAL",UNAVAILABLE:"UNAVAILABLE",DATA_LOSS:"DATA_LOSS",UNAUTHENTICATED:"UNAUTHENTICATED"},la=Object.freeze({TaskNotFoundError:O.NOT_FOUND,TaskNotCancelableError:O.BAD_REQUEST,PushNotificationNotSupportedError:O.BAD_REQUEST,UnsupportedOperationError:O.BAD_REQUEST,ContentTypeNotSupportedError:O.BAD_REQUEST,InvalidAgentResponseError:O.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:O.BAD_REQUEST,ExtensionSupportRequiredError:O.BAD_REQUEST,VersionNotSupportedError:O.BAD_REQUEST,RequestMalformedError:O.BAD_REQUEST}),Ls=Object.freeze({TaskNotFoundError:D.NOT_FOUND,TaskNotCancelableError:D.FAILED_PRECONDITION,PushNotificationNotSupportedError:D.FAILED_PRECONDITION,UnsupportedOperationError:D.FAILED_PRECONDITION,ContentTypeNotSupportedError:D.INVALID_ARGUMENT,InvalidAgentResponseError:D.INTERNAL,ExtendedAgentCardNotConfiguredError:D.FAILED_PRECONDITION,ExtensionSupportRequiredError:D.FAILED_PRECONDITION,VersionNotSupportedError:D.FAILED_PRECONDITION,RequestMalformedError:D.INVALID_ARGUMENT});function $s(t){return t instanceof W&&t.transport==="rest"}function ot(t){let e=Nr[t],r=la[t]??O.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var qs=ot("TaskNotFoundError"),zs=ot("TaskNotCancelableError"),Fs=ot("PushNotificationNotSupportedError"),Bs=ot("UnsupportedOperationError"),Hs=ot("ContentTypeNotSupportedError"),Vs=ot("InvalidAgentResponseError"),Gs=ot("ExtendedAgentCardNotConfiguredError"),Ks=ot("ExtensionSupportRequiredError"),Qs=ot("VersionNotSupportedError"),bs=ot("RequestMalformedError"),Ql=Object.freeze({TaskNotFoundError:qs,TaskNotCancelableError:zs,PushNotificationNotSupportedError:Fs,UnsupportedOperationError:Bs,ContentTypeNotSupportedError:Hs,InvalidAgentResponseError:Vs,ExtendedAgentCardNotConfiguredError:Gs,ExtensionSupportRequiredError:Ks,VersionNotSupportedError:Qs,RequestMalformedError:bs});function te(t){return $s(t)?t.statusCode:t instanceof W?la[t.name]??500:O.INTERNAL_SERVER_ERROR}function $t(t,e){let r=t instanceof Error?t.message:"An unexpected error occurred.",i=[],a=D.UNKNOWN;return t instanceof W?(i.push(t.toErrorInfo()),a=Ls[t.name]??D.UNKNOWN):e===O.NOT_FOUND?a=D.NOT_FOUND:e===O.INTERNAL_SERVER_ERROR?a=D.INTERNAL:e===O.BAD_REQUEST&&(a=D.INVALID_ARGUMENT),{error:{code:e,status:a,message:r,details:i}}}var U={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},ge=Object.freeze({TaskNotFoundError:U.TASK_NOT_FOUND,TaskNotCancelableError:U.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:U.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:U.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:U.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:U.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:U.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:U.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:U.VERSION_NOT_SUPPORTED,RequestMalformedError:U.INVALID_PARAMS}),Ys=Object.freeze(Object.fromEntries(Object.entries(ge).map(([t,e])=>[e,t])));function Er(t){return t instanceof W&&t.transport==="jsonrpc"}function dt(t){let e=Nr[t],r=ge[t]??U.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var Ws=dt("TaskNotFoundError"),Xs=dt("TaskNotCancelableError"),Zs=dt("PushNotificationNotSupportedError"),Or=dt("UnsupportedOperationError"),js=dt("ContentTypeNotSupportedError"),to=dt("InvalidAgentResponseError"),eo=dt("ExtendedAgentCardNotConfiguredError"),ro=dt("ExtensionSupportRequiredError"),io=dt("VersionNotSupportedError"),Ft=dt("RequestMalformedError"),ao=Object.freeze({TaskNotFoundError:Ws,TaskNotCancelableError:Xs,PushNotificationNotSupportedError:Zs,UnsupportedOperationError:Or,ContentTypeNotSupportedError:js,InvalidAgentResponseError:to,ExtendedAgentCardNotConfiguredError:eo,ExtensionSupportRequiredError:ro,VersionNotSupportedError:io,RequestMalformedError:Ft}),ua=class extends W{transport="jsonrpc";envelopeCode;data;errorResponse;constructor(t){super({message:t.error.message}),this.name="JsonRpcTransportError",this.envelopeCode=t.error.code,t.error.data!==void 0&&(this.data=t.error.data),this.errorResponse=t}};function no(t){if(Er(t)){let r=X[t.name];return{code:t.envelopeCode,message:t.message,...r?{data:[t.toErrorInfo()]}:{}}}if(t instanceof W)return{code:ge[t.name]??U.INTERNAL_ERROR,message:t.message,data:[t.toErrorInfo()]};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var bl={[U.PARSE_ERROR]:"RequestMalformedError",[U.INVALID_REQUEST]:"RequestMalformedError",[U.METHOD_NOT_FOUND]:"RequestMalformedError"},sr=class or{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw new $("Invalid request body type.");if(!this.isRequestValid(i))throw new $("Invalid JSON-RPC Request.")}catch(o){let l=or.mapToJSONRPCError(o instanceof SyntaxError?new $(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:l}}let{method:a,id:n=null}=i;try{if(a!=="GetExtendedAgentCard"&&!this.paramsAreValid(i.params))throw new $("Invalid method parameters.");let o=i.params?.tenant;if(o&&r.setTenant(o),a==="SendStreamingMessage"||a==="SubscribeToTask"){let l=i.params,c=a==="SendStreamingMessage"?this.requestHandler.sendMessageStream(ne.fromJSON(l),r):this.requestHandler.resubscribe(As.fromJSON(l),r);return(async function*(){for await(let S of c)yield{jsonrpc:"2.0",id:n,result:ar.toJSON(S)}})()}else{let l;switch(a){case"SendMessage":{let c=await this.requestHandler.sendMessage(ne.fromJSON(i.params),r);l="messageId"in c?{message:Y.toJSON(c)}:{task:Q.toJSON(c)};break}case"GetTask":l=Q.toJSON(await this.requestHandler.getTask(Es.fromJSON(i.params),r));break;case"ListTasks":{let c=Os.fromJSON(i.params);l=ea(await this.requestHandler.listTasks(c,r),{includeArtifacts:c.includeArtifacts});break}case"CancelTask":l=Q.toJSON(await this.requestHandler.cancelTask(_s.fromJSON(i.params),r));break;case"CreateTaskPushNotificationConfig":{l=b.toJSON(await this.requestHandler.createTaskPushNotificationConfig(b.fromJSON(i.params),r));break}case"GetTaskPushNotificationConfig":l=b.toJSON(await this.requestHandler.getTaskPushNotificationConfig(vs.fromJSON(i.params),r));break;case"DeleteTaskPushNotificationConfig":await this.requestHandler.deleteTaskPushNotificationConfig(ys.fromJSON(i.params),r),l=null;break;case"ListTaskPushNotificationConfigs":l=ta.toJSON(await this.requestHandler.listTaskPushNotificationConfigs(ks.fromJSON(i.params),r));break;case"GetExtendedAgentCard":l=Zi.toJSON(await this.requestHandler.getAuthenticatedExtendedAgentCard(Is.fromJSON(i.params??{}),r));break;default:return{jsonrpc:"2.0",id:n,error:{code:U.METHOD_NOT_FOUND,message:"Invalid method."}}}return{jsonrpc:"2.0",id:n,result:l}}}catch(o){return{jsonrpc:"2.0",id:n,error:or.mapToJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToJSONRPCError(e){return no(e)}},so="0.3",oo="headers",_r=({extensions:t,user:e,headers:r,requestedVersion:i,tenant:a})=>{let n=new Map([[oo,r]]);return new lo({requestedExtensions:t,user:e,state:n,requestedVersion:i,tenant:a})},lo=class{_requestedExtensions;_user;_requestedVersion;_tenant;_activatedExtensions;_state;constructor(t){this._requestedExtensions=t?.requestedExtensions,this._user=t?.user,this._tenant=t?.tenant,this._requestedVersion=t?.requestedVersion||so,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=Se.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function uo(t,e){let r=new Set;for(let i of t.supportedInterfaces??[])e&&i.protocolBinding!==e||i.protocolVersion&&r.add(i.protocolVersion);return r}function vr(t,e,r){let i=uo(e,r);if(!i.has(t))throw new Te(`The requested A2A protocol version '${t}' is not supported. Supported versions: ${[...i].join(", ")}`)}var ca=Ut,co=Js;function Ve(t){let e=t.trim();if(e==="")return;let r=e.split(".");if(r.length===0)return;let i=Number.parseInt(r[0],10);if(!Number.isFinite(i)||i<0)return;let a=r[1],n=a===void 0?0:Number.parseInt(a,10);if(!(!Number.isFinite(n)||n<0))return{major:i,minor:n}}function Ri(t,e){return t.major!==e.major?t.major-e.major:t.minor-e.minor}function yr(t){if(!t||t.trim()==="")return!0;let e=Ve(t);if(!e)return!1;let r=Ve(ca),i=Ve(co);return!r||!i?!1:Ri(e,r)>=0&&Ri(e,i)<0}function fo(t,e,r){let i=Ys[t];return i?r===void 0?new Nr[i]({message:e}):new ao[i]({message:e,envelopeCode:t,data:r}):t===U.METHOD_NOT_FOUND?new Or({message:e,envelopeCode:t,data:r}):t===U.PARSE_ERROR||t===U.INVALID_REQUEST?new Ft({message:e,envelopeCode:t,data:r}):new ua({jsonrpc:"2.0",id:null,error:{code:t,message:e,data:r}})}var h=fo;Object.defineProperty(h,Symbol.hasInstance,{value:t=>t instanceof W});h.parseError=(t,e)=>new Ft({message:t,envelopeCode:U.PARSE_ERROR,data:e});h.invalidRequest=(t,e)=>new Ft({message:t,envelopeCode:U.INVALID_REQUEST,data:e});h.methodNotFound=t=>new Or({message:`Method not found: ${t}`,envelopeCode:U.METHOD_NOT_FOUND});h.invalidParams=(t,e)=>e===void 0?new $({message:t}):new Ft({message:t,envelopeCode:U.INVALID_PARAMS,data:e});h.internalError=(t,e)=>new ua({jsonrpc:"2.0",id:null,error:{code:U.INTERNAL_ERROR,message:t,...e!==void 0?{data:e}:{}}});h.taskNotFound=t=>new na({message:`Task not found: ${t}`});h.taskNotCancelable=t=>new sa({message:`Task not cancelable: ${t}`});h.pushNotificationNotSupported=()=>new gr;h.unsupportedOperation=t=>new oa({message:`Unsupported operation: ${t}`});h.authenticatedExtendedCardNotConfigured=()=>new da({message:"Extended card not configured."});function K(t){return t!==void 0&&t!==""?t:void 0}function fa(t){return Object.fromEntries(Object.entries(t.schemes).map(([e,r])=>[e,[...r.list]]))}function po(t){let e={type:"apiKey",name:t.name,in:t.location==="cookie"||t.location==="query"?t.location:"header"},r=K(t.description);return r!==void 0&&(e.description=r),e}function ho(t){let e={type:"http",scheme:t.scheme},r=K(t.description);r!==void 0&&(e.description=r);let i=K(t.bearerFormat);return i!==void 0&&(e.bearerFormat=i),e}function So(t){let e={type:"mutualTLS"},r=K(t.description);return r!==void 0&&(e.description=r),e}function To(t){if(!t.flows)throw h.invalidParams("OAuth2 security scheme missing flows");let e={type:"oauth2",flows:No(t.flows)},r=K(t.description);r!==void 0&&(e.description=r);let i=K(t.oauth2MetadataUrl);return i!==void 0&&(e.oauth2MetadataUrl=i),e}function go(t){let e={type:"openIdConnect",openIdConnectUrl:t.openIdConnectUrl},r=K(t.description);return r!==void 0&&(e.description=r),e}function mo(t){let e=t.scheme;if(!e)throw h.invalidParams("Invalid v1.0 SecurityScheme: missing inner scheme");switch(e.$case){case"apiKeySecurityScheme":return po(e.value);case"httpAuthSecurityScheme":return ho(e.value);case"mtlsSecurityScheme":return So(e.value);case"oauth2SecurityScheme":return To(e.value);case"openIdConnectSecurityScheme":return go(e.value);default:throw h.invalidParams(`Unsupported v1.0 SecurityScheme $case: ${e.$case??"unknown"}`)}}function No(t){let e={},r=t.flow;if(!r)return e;switch(r.$case){case"authorizationCode":{let i=r.value;e.authorizationCode={authorizationUrl:i.authorizationUrl,tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=K(i.refreshUrl);a!==void 0&&(e.authorizationCode.refreshUrl=a);break}case"clientCredentials":{let i=r.value;e.clientCredentials={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=K(i.refreshUrl);a!==void 0&&(e.clientCredentials.refreshUrl=a);break}case"implicit":{let i=r.value;e.implicit={authorizationUrl:i.authorizationUrl,scopes:{...i.scopes}};let a=K(i.refreshUrl);a!==void 0&&(e.implicit.refreshUrl=a);break}case"password":{let i=r.value;e.password={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=K(i.refreshUrl);a!==void 0&&(e.password.refreshUrl=a);break}default:break}return e}function q(t){return t===void 0?void 0:structuredClone(t)}function kt(t,e){if(!Array.isArray(t))throw h.invalidParams(`${e} is required and must be an array`);return t}function Eo(t){return t!==void 0&&t!==""?t:void 0}function Oo(t){return{url:t.url,transport:t.protocolBinding}}function _o(t){return{url:t.url,organization:t.organization}}function vo(t){let e={uri:t.uri},r=Eo(t.description);r!==void 0&&(e.description=r),e.required=t.required;let i=q(t.params);return i!==void 0&&(e.params=i),e}function yo(t){let e={};return t.streaming!==void 0&&(e.streaming=t.streaming),t.pushNotifications!==void 0&&(e.pushNotifications=t.pushNotifications),t.extensions&&t.extensions.length>0&&(e.extensions=t.extensions.map(vo)),e}function Ao(t){let e={id:t.id,name:t.name,description:t.description,tags:[...kt(t.tags,"skill.tags")]};return t.examples&&t.examples.length>0&&(e.examples=[...t.examples]),t.inputModes&&t.inputModes.length>0&&(e.inputModes=[...t.inputModes]),t.outputModes&&t.outputModes.length>0&&(e.outputModes=[...t.outputModes]),t.securityRequirements&&t.securityRequirements.length>0&&(e.security=t.securityRequirements.map(fa)),e}function ko(t){let e={protected:t.protected,signature:t.signature},r=q(t.header);return r!==void 0&&(e.header=r),e}function Ar(t,e){let r=t.supportedInterfaces??[],i=r.filter(_=>!_.protocolVersion||yr(_.protocolVersion));if(i.length===0)throw new Te("AgentCard must have at least one interface with a protocol version in [0.3, 1.0).");let a=i[0],n=i.slice(1).map(Oo),o=t.capabilities?yo(t.capabilities):{},l=t.capabilities&&t.capabilities.extendedAgentCard!==void 0?t.capabilities.extendedAgentCard:void 0,c=t.securitySchemes&&Object.keys(t.securitySchemes).length>0?Object.fromEntries(Object.entries(t.securitySchemes).map(([_,u])=>[_,mo(u)])):void 0,T=a.protocolVersion||ca,S={name:t.name,description:t.description,version:t.version,url:a.url,preferredTransport:a.protocolBinding,protocolVersion:T,capabilities:o,defaultInputModes:[...kt(t.defaultInputModes,"agentCard.defaultInputModes")],defaultOutputModes:[...kt(t.defaultOutputModes,"agentCard.defaultOutputModes")],skills:kt(t.skills,"agentCard.skills").map(Ao)};return n.length>0&&(S.additionalInterfaces=n),t.provider&&(S.provider=_o(t.provider)),t.documentationUrl!==void 0&&t.documentationUrl!==""&&(S.documentationUrl=t.documentationUrl),t.iconUrl!==void 0&&t.iconUrl!==""&&(S.iconUrl=t.iconUrl),l!==void 0&&(S.supportsAuthenticatedExtendedCard=l),c!==void 0&&(S.securitySchemes=c),t.securityRequirements&&t.securityRequirements.length>0&&(S.security=t.securityRequirements.map(fa)),t.signatures&&t.signatures.length>0&&(S.signatures=t.signatures.map(ko)),e?.embedV1Interfaces&&r.length>0&&(S.supportedInterfaces=structuredClone(r)),S}function pa(t){if(Er(t))return{code:t.envelopeCode,message:t.message,...t.data!==void 0?{data:t.data}:{}};if(t instanceof W)return{code:ge[t.name]??U.INTERNAL_ERROR,message:t.message};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var Io=Object.freeze({unknown:0,submitted:1,working:2,completed:3,failed:4,canceled:5,"input-required":6,rejected:7,"auth-required":8}),Ro=new Map(Object.entries(Io).map(([t,e])=>[e,t]));function Co(t){return Ro.get(t)??"unknown"}function Uo(t){return t==="user"?1:t==="agent"?2:0}function Jo(t){return t===1?"user":"agent"}var dr="data_part_compat";function ha(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!Buffer.isBuffer(t)}function wo(t){if(t===null||Array.isArray(t))return!0;let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function xo(t){if(typeof t!="object"||t===null||Array.isArray(t))throw h.invalidParams("Each part must be an object");if(t.kind==="text")return{content:{$case:"text",value:t.text},metadata:q(t.metadata),filename:"",mediaType:""};if(t.kind==="file"){let e=t.file,r=e.mimeType??"",i=e.name??"",a=q(t.metadata);if("bytes"in e)return{content:{$case:"raw",value:Buffer.from(e.bytes,"base64")},metadata:a,filename:i,mediaType:r};if("uri"in e)return{content:{$case:"url",value:e.uri},metadata:a,filename:i,mediaType:r};throw h.invalidParams("Invalid file part: missing `bytes` or `uri`")}if(t.kind==="data"){let e=q(t.metadata),r=t.data,i=e;return e!==void 0&&e[dr]===!0&&(ha(t.data)&&"value"in t.data&&(r=t.data.value),delete e[dr],i=Object.keys(e).length>0?e:void 0),{content:{$case:"data",value:r},metadata:i,filename:"",mediaType:""}}throw h.invalidParams(`Invalid v0.3 part kind: ${t.kind??"undefined"}`)}function Sa(t){let e=t.content,r=q(t.metadata);if(!e)throw h.invalidParams("Invalid v1.0 part: missing content");if(e.$case==="text"){let i={kind:"text",text:e.value};return r!==void 0&&(i.metadata=r),i}if(e.$case==="raw"||e.$case==="url"){let i=t.mediaType!==""?t.mediaType:void 0,a=t.filename!==""?t.filename:void 0,n;if(e.$case==="raw"){let c={bytes:(Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value)).toString("base64")};i!==void 0&&(c.mimeType=i),a!==void 0&&(c.name=a),n=c}else{let l={uri:e.value};i!==void 0&&(l.mimeType=i),a!==void 0&&(l.name=a),n=l}let o={kind:"file",file:n};return r!==void 0&&(o.metadata=r),o}if(e.$case==="data"){let i=e.value;if(ha(i)){let a={kind:"data",data:i};return r!==void 0&&(a.metadata=r),a}if(wo(i)){let a={value:i},n=r??{};return n[dr]=!0,{kind:"data",data:a,metadata:n}}throw h.invalidParams("Cannot translate v1 data part to v0.3: value is neither a plain object nor a wrap-eligible primitive / array / null (e.g., Symbol, function, bigint, undefined, Buffer). Primitives, arrays, and null are wrapped as { value: ... } with data_part_compat=true; all other non-plain-object values are rejected.")}throw h.invalidParams(`Invalid v1.0 part content type: ${e.$case??"unknown"}`)}function Ci(t){return t==null||t===""?void 0:t}function Ui(t){return t==null||t.length===0?void 0:[...t]}function Po(t){if(typeof t!="object"||t===null)throw h.invalidParams("message must be an object");if(typeof t.messageId!="string"||t.messageId==="")throw h.invalidParams("message.messageId is required");if(t.role!=="user"&&t.role!=="agent")throw h.invalidParams('message.role must be "user" or "agent"');if(!Array.isArray(t.parts))throw h.invalidParams("message.parts must be an array");return{messageId:t.messageId,contextId:t.contextId??"",taskId:t.taskId??"",role:Uo(t.role),parts:t.parts.map(xo),metadata:q(t.metadata),extensions:t.extensions?[...t.extensions]:[],referenceTaskIds:t.referenceTaskIds?[...t.referenceTaskIds]:[]}}function Bt(t){let e={kind:"message",messageId:t.messageId,role:Jo(t.role),parts:kt(t.parts,"message.parts").map(Sa)},r=Ci(t.contextId);r!==void 0&&(e.contextId=r);let i=Ci(t.taskId);i!==void 0&&(e.taskId=i);let a=q(t.metadata);a!==void 0&&(e.metadata=a);let n=Ui(t.extensions);n!==void 0&&(e.extensions=n);let o=Ui(t.referenceTaskIds);return o!==void 0&&(e.referenceTaskIds=o),e}function lr(t){return t!==void 0&&t!==""?t:void 0}function Ta(t){return t.schemes&&t.schemes.length>1&&console.warn(`toCoreAuthenticationInfo: Lossy conversion from v0.3 PushNotificationAuthenticationInfo to v1.0 AuthenticationInfo. Multiple schemes declared (${t.schemes.join(", ")}), but only the first one ('${t.schemes[0]}') will be kept.`),{scheme:t.schemes&&t.schemes.length>0?t.schemes[0]:"",credentials:t.credentials??""}}function Do(t){let e={schemes:t.scheme!==""?[t.scheme]:[]},r=lr(t.credentials);return r!==void 0&&(e.credentials=r),e}function Mo(t,e=""){return{tenant:e,taskId:"",id:t.id??"",url:t.url,token:t.token??"",authentication:t.authentication?Ta(t.authentication):void 0}}function Lo(t){let e={url:t.url},r=lr(t.id);r!==void 0&&(e.id=r);let i=lr(t.token);return i!==void 0&&(e.token=i),t.authentication&&(e.authentication=Do(t.authentication)),e}function ga(t,e=""){return{tenant:e,taskId:t.taskId,id:t.pushNotificationConfig.id??"",url:t.pushNotificationConfig.url,token:t.pushNotificationConfig.token??"",authentication:t.pushNotificationConfig.authentication?Ta(t.pushNotificationConfig.authentication):void 0}}function It(t){return{taskId:t.taskId,pushNotificationConfig:Lo(t)}}function Ji(t){return t==null||t===""?void 0:t}function $o(t){return t==null||t.length===0?void 0:[...t]}function ma(t){let e={artifactId:t.artifactId,parts:kt(t.parts,"artifact.parts").map(Sa)},r=Ji(t.name);r!==void 0&&(e.name=r);let i=Ji(t.description);i!==void 0&&(e.description=i);let a=q(t.metadata);a!==void 0&&(e.metadata=a);let n=$o(t.extensions);return n!==void 0&&(e.extensions=n),e}var qo=new Set(["completed","canceled","failed","rejected"]);function Na(t){let e={state:Co(t.state)};return t.message&&(e.message=Bt(t.message)),t.timestamp!==void 0&&t.timestamp!==""&&(e.timestamp=t.timestamp),e}function gt(t){let e={kind:"task",id:t.id,contextId:t.contextId,status:t.status?Na(t.status):{state:"unknown"}};t.history&&t.history.length>0&&(e.history=t.history.map(Bt)),t.artifacts&&t.artifacts.length>0&&(e.artifacts=t.artifacts.map(ma));let r=q(t.metadata);return r!==void 0&&(e.metadata=r),e}function zo(t){let e=t.status?Na(t.status):{state:"unknown"},r={kind:"status-update",taskId:t.taskId,contextId:t.contextId,status:e,final:qo.has(e.state)},i=q(t.metadata);return i!==void 0&&(r.metadata=i),r}function Fo(t){if(!t.artifact)throw h.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");let e={kind:"artifact-update",taskId:t.taskId,contextId:t.contextId,artifact:ma(t.artifact),append:t.append,lastChunk:t.lastChunk},r=q(t.metadata);return r!==void 0&&(e.metadata=r),e}function Bo(t){return{acceptedOutputModes:t.acceptedOutputModes?[...t.acceptedOutputModes]:[],taskPushNotificationConfig:t.pushNotificationConfig?Mo(t.pushNotificationConfig):void 0,historyLength:t.historyLength,returnImmediately:t.blocking===void 0?!0:!t.blocking}}function de(t,e=""){return{tenant:e,message:Po(t.params.message),configuration:t.params.configuration?Bo(t.params.configuration):void 0,metadata:q(t.params.metadata)}}function Ea(t,e=null){let r=t.payload;if(!r)throw h.internalError("StreamResponse missing payload");let i;switch(r.$case){case"message":i=Bt(r.value);break;case"task":i=gt(r.value);break;case"statusUpdate":i=zo(r.value);break;case"artifactUpdate":i=Fo(r.value);break;default:throw h.internalError("StreamResponse has unknown payload case")}return{id:e,jsonrpc:"2.0",result:i}}function Ho(t,e=""){return{tenant:e,id:t.params.id,historyLength:t.params.historyLength}}function Vo(t,e=""){return{tenant:e,id:t.params.id,metadata:q(t.params.metadata)}}function Go(t,e=""){return{tenant:e,id:t.params.id}}function Ko(t,e=""){return ga(t.params,e)}function Qo(t,e=""){let r=t.params,i="pushNotificationConfigId"in r?r.pushNotificationConfigId:void 0;return{tenant:e,taskId:r.id,id:i??""}}function bo(t,e=""){return{tenant:e,taskId:t.params.id,id:t.params.pushNotificationConfigId}}function Yo(t,e=""){return{tenant:e,taskId:t.params.id,pageSize:0,pageToken:""}}function Wo(t,e=null){return{id:e,jsonrpc:"2.0",result:t.configs.map(r=>It(r))}}function Xo(t,e=""){return{tenant:e}}var wi=class ur{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw h.invalidRequest("Invalid request body type.");if(!this.isRequestValid(i))throw h.invalidRequest("Invalid JSON-RPC Request.")}catch(o){let l=ur.mapToLegacyJSONRPCError(o instanceof SyntaxError?h.invalidRequest(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:l}}let{method:a,id:n=null}=i;try{if(a!=="agent/getAuthenticatedExtendedCard"&&!this.paramsAreValid(i.params))throw h.invalidParams("Invalid method parameters.");if(a==="message/stream"||a==="tasks/resubscribe"){if(!(await this.requestHandler.getAgentCard()).capabilities?.streaming)throw h.unsupportedOperation(`Method ${a} requires streaming capability.`);let c=a==="message/stream"?this.requestHandler.sendMessageStream(de(i),r):this.requestHandler.resubscribe(Go(i),r);return(async function*(){for await(let S of c)yield Ea(S,n)})()}let o;switch(a){case"message/send":{let l=await this.requestHandler.sendMessage(de(i),r);o="messageId"in l?Bt(l):gt(l);break}case"tasks/get":o=gt(await this.requestHandler.getTask(Ho(i),r));break;case"tasks/cancel":o=gt(await this.requestHandler.cancelTask(Vo(i),r));break;case"tasks/pushNotificationConfig/set":o=It(await this.requestHandler.createTaskPushNotificationConfig(Ko(i),r));break;case"tasks/pushNotificationConfig/get":o=It(await this.requestHandler.getTaskPushNotificationConfig(Qo(i),r));break;case"tasks/pushNotificationConfig/list":{o=Wo(await this.requestHandler.listTaskPushNotificationConfigs(Yo(i),r),n).result;break}case"tasks/pushNotificationConfig/delete":await this.requestHandler.deleteTaskPushNotificationConfig(bo(i),r),o=null;break;case"agent/getAuthenticatedExtendedCard":o=Ar(await this.requestHandler.getAuthenticatedExtendedAgentCard(Xo(i),r));break;default:throw h.methodNotFound(a)}return{jsonrpc:"2.0",id:n,result:o}}catch(o){return{jsonrpc:"2.0",id:n,error:ur.mapToLegacyJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToLegacyJSONRPCError(e){return pa(e)}},Zo={[-32700]:O.BAD_REQUEST,[-32600]:O.BAD_REQUEST,[-32601]:O.NOT_IMPLEMENTED,[-32602]:O.BAD_REQUEST,[-32603]:O.INTERNAL_SERVER_ERROR,[-32001]:O.NOT_FOUND,[-32002]:O.BAD_REQUEST,[-32003]:O.BAD_REQUEST,[-32004]:O.BAD_REQUEST,[-32005]:O.BAD_REQUEST,[-32006]:O.INTERNAL_SERVER_ERROR,[-32007]:O.BAD_REQUEST};function xi(t){if(Er(t)){let e=Zo[t.envelopeCode];if(e!==void 0)return e}return te(t)}function Rt(t){return pa(t)}var jo=class ee{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e){let r=await this.requestHandler.getAuthenticatedExtendedAgentCard({tenant:e.tenant??""},e);return Ar(r)}validateMessageSendParams(e){if(!e.message)throw h.invalidParams("message is required");if(!e.message.messageId)throw h.invalidParams("message.messageId is required")}async sendMessage(e,r){this.validateMessageSendParams(e);let i=de(Pi(e,"message/send"),r.tenant??""),a=await this.requestHandler.sendMessage(i,r);return"messageId"in a?Bt(a):gt(a)}async sendMessageStream(e,r){await this.requireCapability("streaming"),this.validateMessageSendParams(e);let i=de(Pi(e,"message/stream"),r.tenant??""),a=this.requestHandler.sendMessageStream(i,r);return ee.translateStream(a)}async getTask(e,r,i){let a={id:e,tenant:r.tenant??""};i!==void 0&&(a.historyLength=this.parseHistoryLength(i));let n=await this.requestHandler.getTask(a,r);return gt(n)}async cancelTask(e,r){let i=await this.requestHandler.cancelTask({id:e,tenant:r.tenant??"",metadata:{}},r);return gt(i)}async resubscribe(e,r){await this.requireCapability("streaming");let i=this.requestHandler.resubscribe({id:e,tenant:r.tenant??""},r);return ee.translateStream(i)}async setTaskPushNotificationConfig(e,r){if(await this.requireCapability("pushNotifications"),!e.taskId)throw h.invalidParams("taskId is required");if(!e.pushNotificationConfig)throw h.invalidParams("pushNotificationConfig is required");let i=ga(e,r.tenant??""),a=await this.requestHandler.createTaskPushNotificationConfig(i,r);return It(a)}async listTaskPushNotificationConfigs(e,r){return(await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:r.tenant??""},r)).configs.map(a=>It(a))}async getTaskPushNotificationConfig(e,r,i){let a=await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i);return It(a)}async deleteTaskPushNotificationConfig(e,r,i){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i)}static async*translateStream(e){for await(let r of e)yield Ea(r,null).result}static CAPABILITY_ERRORS={streaming:()=>h.unsupportedOperation("Agent does not support streaming"),pushNotifications:()=>h.pushNotificationNotSupported()};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw ee.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw h.invalidParams("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw h.invalidParams("historyLength must be a valid integer");if(r<0)throw h.invalidParams("historyLength must be non-negative");return r}static mapToLegacyHTTPError(e){return Rt(e)}};function Pi(t,e){return{jsonrpc:"2.0",id:0,method:e,params:t}}var le="X-A2A-Extensions",qt="application/json",Oa="message/send",_a="message/stream",va="tasks/get",ya="tasks/cancel",kr="tasks/resubscribe",Aa="tasks/pushNotificationConfig/set",ka="tasks/pushNotificationConfig/get",Ia="tasks/pushNotificationConfig/list",Ra="tasks/pushNotificationConfig/delete",Ca="agent/getAuthenticatedExtendedCard",Ua=Object.freeze({[Oa]:"SendMessage",[_a]:"SendStreamingMessage",[va]:"GetTask",[ya]:"CancelTask",[kr]:"SubscribeToTask",[Aa]:"CreateTaskPushNotificationConfig",[ka]:"GetTaskPushNotificationConfig",[Ia]:"ListTaskPushNotificationConfigs",[Ra]:"DeleteTaskPushNotificationConfig",[Ca]:"GetExtendedAgentCard"}),Yl=Object.freeze(Object.fromEntries(Object.entries(Ua).map(([t,e])=>[e,t]))),Ja=Object.freeze({[Oa]:"SendMessage",[_a]:"SendStreamingMessage",[va]:"GetTask",[ya]:"CancelTask",[kr]:"TaskSubscription",[Aa]:"CreateTaskPushNotificationConfig",[ka]:"GetTaskPushNotificationConfig",[Ia]:"ListTaskPushNotificationConfig",[Ra]:"DeleteTaskPushNotificationConfig",[Ca]:"GetAgentCard"}),Wl=Object.freeze(Object.fromEntries(Object.entries(Ja).map(([t,e])=>[e,t]))),td=Object.freeze(Object.fromEntries(Object.entries(Ja).map(([t,e])=>[e,Ua[t]]))),Xl=Object.freeze(Object.fromEntries(Object.entries(td).map(([t,e])=>[e,t])));function wa(t){let e=new sr(t.requestHandler),r=t.legacyCompat?.enabled?new wi(t.requestHandler):void 0,i=ir.default.Router();return i.use(ed),i.use(ir.default.json(),rd),i.post("/",async(a,n)=>{let o=r!==void 0&&(a.header(nt)||Ut)===Ut,l=o?wi.mapToLegacyJSONRPCError:sr.mapToJSONRPCError;try{let c=await t.userBuilder(a),T=a.header(nt)||void 0,S=o?a.header(le)??a.header(At):a.header(At),u=(t.contextBuilder??_r)({extensions:Se.parseServiceParameter(S),user:c,headers:a.headers,requestedVersion:T}),N=await t.requestHandler.getAgentCard();vr(u.requestedVersion,N,"JSONRPC");let m=await(o?r:e).handle(a.body,u);if(u.activatedExtensions&&n.setHeader(o?le:At,Array.from(u.activatedExtensions)),typeof m?.[Symbol.asyncIterator]=="function"){let y=m;if(o&&a.body?.method===kr){Object.entries(se).forEach(([g,A])=>{n.setHeader(g,A)}),n.flushHeaders();try{for await(let g of y)n.write(Tt(g))}catch(g){console.error(`Error during SSE streaming (request ${a.body?.id}):`,g);let A={jsonrpc:"2.0",id:a.body?.id||null,error:l(g)};n.writableEnded||n.write(oe(A))}finally{n.writableEnded||n.end()}return}let f=y[Symbol.asyncIterator](),E;try{E=await f.next()}catch(g){console.error(`Pre-stream error for request ${a.body?.id}:`,g);let A={jsonrpc:"2.0",id:a.body?.id||null,error:l(g)};n.status(200).json(A);return}Object.entries(se).forEach(([g,A])=>{n.setHeader(g,A)}),n.flushHeaders();try{E.done||n.write(Tt(E.value));for await(let g of hr(f))n.write(Tt(g))}catch(g){console.error(`Error during SSE streaming (request ${a.body?.id}):`,g);let A={jsonrpc:"2.0",id:a.body?.id||null,error:l(g)};n.headersSent?n.write(oe(A)):n.status(500).json(A)}finally{n.writableEnded||n.end()}}else{let y=m;n.status(200).json(y)}}catch(c){console.error("Unhandled error in JSON-RPC POST handler:",c);let T=l(c),S={jsonrpc:"2.0",id:a.body?.id||null,error:T};if(n.headersSent)n.writableEnded||n.end();else{let _=T.code===U.INTERNAL_ERROR;n.status(_?500:200).json(S)}}}),i}var ed=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}if(i.split(";",1)[0].trim().toLowerCase()===Tr){r();return}let n={jsonrpc:"2.0",id:null,error:sr.mapToJSONRPCError(new mr(`Unsupported Content-Type "${i}"; expected application/json.`))};e.status(200).json(n)},rd=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t){let a={jsonrpc:"2.0",id:null,error:{code:U.PARSE_ERROR,message:"Invalid JSON payload."}};return r.status(200).json(a)}i(t)};function nd(t){return`W/"${ad.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function sd(t){let e=Pa.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return e.use((a,n,o)=>{let l=a.header(nt)||Ut;yr(l)?o():o("router")}),e.get("/",async(a,n)=>{try{let o=await i(),l;try{l=Ar(o,{embedV1Interfaces:!0})}catch(S){if(S instanceof Te){n.append("Vary",nt),n.status(O.BAD_REQUEST).setHeader("Content-Type",qt).json(Rt(S));return}throw S}let c=JSON.stringify(l),T=nd(c);if(n.setHeader("ETag",T),n.append("Vary",nt),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type",qt),n.status(O.OK).send(c)}catch(o){console.error("Error fetching legacy agent card:",o),n.append("Vary",nt),n.status(500).setHeader("Content-Type",qt).json({error:"Failed to retrieve agent card"})}}),e}function od(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELLED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function dd(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELLED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function ld(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function ud(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Di={fromJSON(t){return{acceptedOutputModes:globalThis.Array.isArray(t?.acceptedOutputModes)?t.acceptedOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.accepted_output_modes)?t.accepted_output_modes.map(e=>globalThis.String(e)):[],pushNotification:d(t.pushNotification)?Ct.fromJSON(t.pushNotification):d(t.push_notification)?Ct.fromJSON(t.push_notification):void 0,historyLength:d(t.historyLength)?globalThis.Number(t.historyLength):d(t.history_length)?globalThis.Number(t.history_length):0,blocking:d(t.blocking)?globalThis.Boolean(t.blocking):!1}},toJSON(t){let e={};return t.acceptedOutputModes?.length&&(e.acceptedOutputModes=t.acceptedOutputModes),t.pushNotification!==void 0&&(e.pushNotification=Ct.toJSON(t.pushNotification)),t.historyLength!==0&&(e.historyLength=Math.round(t.historyLength)),t.blocking!==!1&&(e.blocking=t.blocking),e}},zt={fromJSON(t){return{id:d(t.id)?globalThis.String(t.id):"",contextId:d(t.contextId)?globalThis.String(t.contextId):d(t.context_id)?globalThis.String(t.context_id):"",status:d(t.status)?ue.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>fe.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>z.fromJSON(e)):[],metadata:P(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=ue.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>fe.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>z.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ue={fromJSON(t){return{state:d(t.state)?od(t.state):0,update:d(t.message)?z.fromJSON(t.message):d(t.update)?z.fromJSON(t.update):void 0,timestamp:d(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=dd(t.state)),t.update!==void 0&&(e.message=z.toJSON(t.update)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},ce={fromJSON(t){return{part:d(t.text)?{$case:"text",value:globalThis.String(t.text)}:d(t.file)?{$case:"file",value:Mi.fromJSON(t.file)}:d(t.data)?{$case:"data",value:Li.fromJSON(t.data)}:void 0}},toJSON(t){let e={};return t.part?.$case==="text"?e.text=t.part.value:t.part?.$case==="file"?e.file=Mi.toJSON(t.part.value):t.part?.$case==="data"&&(e.data=Li.toJSON(t.part.value)),e}},Mi={fromJSON(t){return{file:d(t.fileWithUri)?{$case:"fileWithUri",value:globalThis.String(t.fileWithUri)}:d(t.file_with_uri)?{$case:"fileWithUri",value:globalThis.String(t.file_with_uri)}:d(t.fileWithBytes)?{$case:"fileWithBytes",value:Buffer.from(bi(t.fileWithBytes))}:d(t.file_with_bytes)?{$case:"fileWithBytes",value:Buffer.from(bi(t.file_with_bytes))}:void 0,mimeType:d(t.mimeType)?globalThis.String(t.mimeType):d(t.mime_type)?globalThis.String(t.mime_type):""}},toJSON(t){let e={};return t.file?.$case==="fileWithUri"?e.fileWithUri=t.file.value:t.file?.$case==="fileWithBytes"&&(e.fileWithBytes=Td(t.file.value)),t.mimeType!==""&&(e.mimeType=t.mimeType),e}},Li={fromJSON(t){return{data:P(t.data)?t.data:void 0}},toJSON(t){let e={};return t.data!==void 0&&(e.data=t.data),e}},z={fromJSON(t){return{messageId:d(t.messageId)?globalThis.String(t.messageId):d(t.message_id)?globalThis.String(t.message_id):"",contextId:d(t.contextId)?globalThis.String(t.contextId):d(t.context_id)?globalThis.String(t.context_id):"",taskId:d(t.taskId)?globalThis.String(t.taskId):d(t.task_id)?globalThis.String(t.task_id):"",role:d(t.role)?ld(t.role):0,content:globalThis.Array.isArray(t?.content)?t.content.map(e=>ce.fromJSON(e)):[],metadata:P(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=ud(t.role)),t.content?.length&&(e.content=t.content.map(r=>ce.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},fe={fromJSON(t){return{artifactId:d(t.artifactId)?globalThis.String(t.artifactId):d(t.artifact_id)?globalThis.String(t.artifact_id):"",name:d(t.name)?globalThis.String(t.name):"",description:d(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>ce.fromJSON(e)):[],metadata:P(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>ce.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Ge={fromJSON(t){return{taskId:d(t.taskId)?globalThis.String(t.taskId):d(t.task_id)?globalThis.String(t.task_id):"",contextId:d(t.contextId)?globalThis.String(t.contextId):d(t.context_id)?globalThis.String(t.context_id):"",status:d(t.status)?ue.fromJSON(t.status):void 0,final:d(t.final)?globalThis.Boolean(t.final):!1,metadata:P(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=ue.toJSON(t.status)),t.final!==!1&&(e.final=t.final),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ke={fromJSON(t){return{taskId:d(t.taskId)?globalThis.String(t.taskId):d(t.task_id)?globalThis.String(t.task_id):"",contextId:d(t.contextId)?globalThis.String(t.contextId):d(t.context_id)?globalThis.String(t.context_id):"",artifact:d(t.artifact)?fe.fromJSON(t.artifact):void 0,append:d(t.append)?globalThis.Boolean(t.append):!1,lastChunk:d(t.lastChunk)?globalThis.Boolean(t.lastChunk):d(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:P(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=fe.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ct={fromJSON(t){return{id:d(t.id)?globalThis.String(t.id):"",url:d(t.url)?globalThis.String(t.url):"",token:d(t.token)?globalThis.String(t.token):"",authentication:d(t.authentication)?$i.fromJSON(t.authentication):void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.url!==""&&(e.url=t.url),t.token!==""&&(e.token=t.token),t.authentication!==void 0&&(e.authentication=$i.toJSON(t.authentication)),e}},$i={fromJSON(t){return{schemes:globalThis.Array.isArray(t?.schemes)?t.schemes.map(e=>globalThis.String(e)):[],credentials:d(t.credentials)?globalThis.String(t.credentials):""}},toJSON(t){let e={};return t.schemes?.length&&(e.schemes=t.schemes),t.credentials!==""&&(e.credentials=t.credentials),e}},Qe={fromJSON(t){return{url:d(t.url)?globalThis.String(t.url):"",transport:d(t.transport)?globalThis.String(t.transport):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.transport!==""&&(e.transport=t.transport),e}},cd={fromJSON(t){return{protocolVersion:d(t.protocolVersion)?globalThis.String(t.protocolVersion):d(t.protocol_version)?globalThis.String(t.protocol_version):"",name:d(t.name)?globalThis.String(t.name):"",description:d(t.description)?globalThis.String(t.description):"",url:d(t.url)?globalThis.String(t.url):"",preferredTransport:d(t.preferredTransport)?globalThis.String(t.preferredTransport):d(t.preferred_transport)?globalThis.String(t.preferred_transport):"",additionalInterfaces:globalThis.Array.isArray(t?.additionalInterfaces)?t.additionalInterfaces.map(e=>Qe.fromJSON(e)):globalThis.Array.isArray(t?.additional_interfaces)?t.additional_interfaces.map(e=>Qe.fromJSON(e)):[],provider:d(t.provider)?qi.fromJSON(t.provider):void 0,version:d(t.version)?globalThis.String(t.version):"",documentationUrl:d(t.documentationUrl)?globalThis.String(t.documentationUrl):d(t.documentation_url)?globalThis.String(t.documentation_url):"",capabilities:d(t.capabilities)?zi.fromJSON(t.capabilities):void 0,securitySchemes:P(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=be.fromJSON(i),e),{}):P(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=be.fromJSON(i),e),{}):{},security:globalThis.Array.isArray(t?.security)?t.security.map(e=>he.fromJSON(e)):[],defaultInputModes:globalThis.Array.isArray(t?.defaultInputModes)?t.defaultInputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_input_modes)?t.default_input_modes.map(e=>globalThis.String(e)):[],defaultOutputModes:globalThis.Array.isArray(t?.defaultOutputModes)?t.defaultOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_output_modes)?t.default_output_modes.map(e=>globalThis.String(e)):[],skills:globalThis.Array.isArray(t?.skills)?t.skills.map(e=>Bi.fromJSON(e)):[],supportsAuthenticatedExtendedCard:d(t.supportsAuthenticatedExtendedCard)?globalThis.Boolean(t.supportsAuthenticatedExtendedCard):d(t.supports_authenticated_extended_card)?globalThis.Boolean(t.supports_authenticated_extended_card):!1,signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Hi.fromJSON(e)):[]}},toJSON(t){let e={};if(t.protocolVersion!==""&&(e.protocolVersion=t.protocolVersion),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.url!==""&&(e.url=t.url),t.preferredTransport!==""&&(e.preferredTransport=t.preferredTransport),t.additionalInterfaces?.length&&(e.additionalInterfaces=t.additionalInterfaces.map(r=>Qe.toJSON(r))),t.provider!==void 0&&(e.provider=qi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==""&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=zi.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);r.length>0&&(e.securitySchemes={},r.forEach(([i,a])=>{e.securitySchemes[i]=be.toJSON(a)}))}return t.security?.length&&(e.security=t.security.map(r=>he.toJSON(r))),t.defaultInputModes?.length&&(e.defaultInputModes=t.defaultInputModes),t.defaultOutputModes?.length&&(e.defaultOutputModes=t.defaultOutputModes),t.skills?.length&&(e.skills=t.skills.map(r=>Bi.toJSON(r))),t.supportsAuthenticatedExtendedCard!==!1&&(e.supportsAuthenticatedExtendedCard=t.supportsAuthenticatedExtendedCard),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Hi.toJSON(r))),e}},qi={fromJSON(t){return{url:d(t.url)?globalThis.String(t.url):"",organization:d(t.organization)?globalThis.String(t.organization):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.organization!==""&&(e.organization=t.organization),e}},zi={fromJSON(t){return{streaming:d(t.streaming)?globalThis.Boolean(t.streaming):!1,pushNotifications:d(t.pushNotifications)?globalThis.Boolean(t.pushNotifications):d(t.push_notifications)?globalThis.Boolean(t.push_notifications):!1,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>Fi.fromJSON(e)):[]}},toJSON(t){let e={};return t.streaming!==!1&&(e.streaming=t.streaming),t.pushNotifications!==!1&&(e.pushNotifications=t.pushNotifications),t.extensions?.length&&(e.extensions=t.extensions.map(r=>Fi.toJSON(r))),e}},Fi={fromJSON(t){return{uri:d(t.uri)?globalThis.String(t.uri):"",description:d(t.description)?globalThis.String(t.description):"",required:d(t.required)?globalThis.Boolean(t.required):!1,params:P(t.params)?t.params:void 0}},toJSON(t){let e={};return t.uri!==""&&(e.uri=t.uri),t.description!==""&&(e.description=t.description),t.required!==!1&&(e.required=t.required),t.params!==void 0&&(e.params=t.params),e}},Bi={fromJSON(t){return{id:d(t.id)?globalThis.String(t.id):"",name:d(t.name)?globalThis.String(t.name):"",description:d(t.description)?globalThis.String(t.description):"",tags:globalThis.Array.isArray(t?.tags)?t.tags.map(e=>globalThis.String(e)):[],examples:globalThis.Array.isArray(t?.examples)?t.examples.map(e=>globalThis.String(e)):[],inputModes:globalThis.Array.isArray(t?.inputModes)?t.inputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.input_modes)?t.input_modes.map(e=>globalThis.String(e)):[],outputModes:globalThis.Array.isArray(t?.outputModes)?t.outputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.output_modes)?t.output_modes.map(e=>globalThis.String(e)):[],security:globalThis.Array.isArray(t?.security)?t.security.map(e=>he.fromJSON(e)):[]}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.tags?.length&&(e.tags=t.tags),t.examples?.length&&(e.examples=t.examples),t.inputModes?.length&&(e.inputModes=t.inputModes),t.outputModes?.length&&(e.outputModes=t.outputModes),t.security?.length&&(e.security=t.security.map(r=>he.toJSON(r))),e}},Hi={fromJSON(t){return{protected:d(t.protected)?globalThis.String(t.protected):"",signature:d(t.signature)?globalThis.String(t.signature):"",header:P(t.header)?t.header:void 0}},toJSON(t){let e={};return t.protected!==""&&(e.protected=t.protected),t.signature!==""&&(e.signature=t.signature),t.header!==void 0&&(e.header=t.header),e}},pe={fromJSON(t){return{name:d(t.name)?globalThis.String(t.name):"",pushNotificationConfig:d(t.pushNotificationConfig)?Ct.fromJSON(t.pushNotificationConfig):d(t.push_notification_config)?Ct.fromJSON(t.push_notification_config):void 0}},toJSON(t){let e={};return t.name!==""&&(e.name=t.name),t.pushNotificationConfig!==void 0&&(e.pushNotificationConfig=Ct.toJSON(t.pushNotificationConfig)),e}},Vi={fromJSON(t){return{list:globalThis.Array.isArray(t?.list)?t.list.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.list?.length&&(e.list=t.list),e}},he={fromJSON(t){return{schemes:P(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Vi.fromJSON(i),e),{}):{}}},toJSON(t){let e={};if(t.schemes){let r=globalThis.Object.entries(t.schemes);r.length>0&&(e.schemes={},r.forEach(([i,a])=>{e.schemes[i]=Vi.toJSON(a)}))}return e}},be={fromJSON(t){return{scheme:d(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Ye.fromJSON(t.apiKeySecurityScheme)}:d(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Ye.fromJSON(t.api_key_security_scheme)}:d(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:We.fromJSON(t.httpAuthSecurityScheme)}:d(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:We.fromJSON(t.http_auth_security_scheme)}:d(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:Xe.fromJSON(t.oauth2SecurityScheme)}:d(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:Xe.fromJSON(t.oauth2_security_scheme)}:d(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Ze.fromJSON(t.openIdConnectSecurityScheme)}:d(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Ze.fromJSON(t.open_id_connect_security_scheme)}:d(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:je.fromJSON(t.mtlsSecurityScheme)}:d(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:je.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Ye.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=We.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=Xe.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Ze.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=je.toJSON(t.scheme.value)),e}},Ye={fromJSON(t){return{description:d(t.description)?globalThis.String(t.description):"",location:d(t.location)?globalThis.String(t.location):"",name:d(t.name)?globalThis.String(t.name):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.location!==""&&(e.location=t.location),t.name!==""&&(e.name=t.name),e}},We={fromJSON(t){return{description:d(t.description)?globalThis.String(t.description):"",scheme:d(t.scheme)?globalThis.String(t.scheme):"",bearerFormat:d(t.bearerFormat)?globalThis.String(t.bearerFormat):d(t.bearer_format)?globalThis.String(t.bearer_format):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.scheme!==""&&(e.scheme=t.scheme),t.bearerFormat!==""&&(e.bearerFormat=t.bearerFormat),e}},Xe={fromJSON(t){return{description:d(t.description)?globalThis.String(t.description):"",flows:d(t.flows)?Gi.fromJSON(t.flows):void 0,oauth2MetadataUrl:d(t.oauth2MetadataUrl)?globalThis.String(t.oauth2MetadataUrl):d(t.oauth2_metadata_url)?globalThis.String(t.oauth2_metadata_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.flows!==void 0&&(e.flows=Gi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Ze={fromJSON(t){return{description:d(t.description)?globalThis.String(t.description):"",openIdConnectUrl:d(t.openIdConnectUrl)?globalThis.String(t.openIdConnectUrl):d(t.open_id_connect_url)?globalThis.String(t.open_id_connect_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.openIdConnectUrl!==""&&(e.openIdConnectUrl=t.openIdConnectUrl),e}},je={fromJSON(t){return{description:d(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Gi={fromJSON(t){return{flow:d(t.authorizationCode)?{$case:"authorizationCode",value:tr.fromJSON(t.authorizationCode)}:d(t.authorization_code)?{$case:"authorizationCode",value:tr.fromJSON(t.authorization_code)}:d(t.clientCredentials)?{$case:"clientCredentials",value:er.fromJSON(t.clientCredentials)}:d(t.client_credentials)?{$case:"clientCredentials",value:er.fromJSON(t.client_credentials)}:d(t.implicit)?{$case:"implicit",value:Ki.fromJSON(t.implicit)}:d(t.password)?{$case:"password",value:Qi.fromJSON(t.password)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=tr.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=er.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Ki.toJSON(t.flow.value):t.flow?.$case==="password"&&(e.password=Qi.toJSON(t.flow.value)),e}},tr={fromJSON(t){return{authorizationUrl:d(t.authorizationUrl)?globalThis.String(t.authorizationUrl):d(t.authorization_url)?globalThis.String(t.authorization_url):"",tokenUrl:d(t.tokenUrl)?globalThis.String(t.tokenUrl):d(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:d(t.refreshUrl)?globalThis.String(t.refreshUrl):d(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:P(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},er={fromJSON(t){return{tokenUrl:d(t.tokenUrl)?globalThis.String(t.tokenUrl):d(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:d(t.refreshUrl)?globalThis.String(t.refreshUrl):d(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:P(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},Ki={fromJSON(t){return{authorizationUrl:d(t.authorizationUrl)?globalThis.String(t.authorizationUrl):d(t.authorization_url)?globalThis.String(t.authorization_url):"",refreshUrl:d(t.refreshUrl)?globalThis.String(t.refreshUrl):d(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:P(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},Qi={fromJSON(t){return{tokenUrl:d(t.tokenUrl)?globalThis.String(t.tokenUrl):d(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:d(t.refreshUrl)?globalThis.String(t.refreshUrl):d(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:P(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},fd={fromJSON(t){return{request:d(t.message)?z.fromJSON(t.message):d(t.request)?z.fromJSON(t.request):void 0,configuration:d(t.configuration)?Di.fromJSON(t.configuration):void 0,metadata:P(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.request!==void 0&&(e.message=z.toJSON(t.request)),t.configuration!==void 0&&(e.configuration=Di.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},pd={fromJSON(t){return{payload:d(t.task)?{$case:"task",value:zt.fromJSON(t.task)}:d(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:d(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=zt.toJSON(t.payload.value):t.payload?.$case==="msg"&&(e.message=z.toJSON(t.payload.value)),e}},hd={fromJSON(t){return{payload:d(t.task)?{$case:"task",value:zt.fromJSON(t.task)}:d(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:d(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:d(t.statusUpdate)?{$case:"statusUpdate",value:Ge.fromJSON(t.statusUpdate)}:d(t.status_update)?{$case:"statusUpdate",value:Ge.fromJSON(t.status_update)}:d(t.artifactUpdate)?{$case:"artifactUpdate",value:Ke.fromJSON(t.artifactUpdate)}:d(t.artifact_update)?{$case:"artifactUpdate",value:Ke.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=zt.toJSON(t.payload.value):t.payload?.$case==="msg"?e.message=z.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Ge.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=Ke.toJSON(t.payload.value)),e}},Sd={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>pe.fromJSON(e)):[],nextPageToken:d(t.nextPageToken)?globalThis.String(t.nextPageToken):d(t.next_page_token)?globalThis.String(t.next_page_token):""}},toJSON(t){let e={};return t.configs?.length&&(e.configs=t.configs.map(r=>pe.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function bi(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Td(t){return globalThis.Buffer.from(t).toString("base64")}function P(t){return typeof t=="object"&&t!==null}function d(t){return t!=null}var gd=/^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/,md=/^tasks\/([^/]+)(?:\/|$)/,Mt=t=>{let e=t.match(md);if(!e)throw h.invalidParams(`Invalid or missing task ID in: "${t}"`);return e[1]},Lt=t=>`tasks/${t}`,Yi=t=>{let e=t.match(gd);if(!e)throw h.invalidParams(`Invalid or missing config ID in: "${t}"`);return{taskId:e[1],configId:e[2]}},rr=(t,e)=>`tasks/${t}/pushNotificationConfigs/${e}`,Wi=class k{static taskQueryParams(e){return{id:Mt(e.name),historyLength:e.historyLength}}static taskIdParams(e){return{id:Mt(e.name)}}static getTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Yi(e.name);return{id:r,pushNotificationConfigId:i}}static listTaskPushNotificationConfigParams(e){return{id:Mt(e.parent)}}static createTaskPushNotificationConfig(e){if(!e.config?.pushNotificationConfig)throw h.invalidParams("Request must include a `config` object with a `pushNotificationConfig`");return{taskId:Mt(e.parent),pushNotificationConfig:k.pushNotificationConfig(e.config.pushNotificationConfig)}}static deleteTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Yi(e.name);return{id:r,pushNotificationConfigId:i}}static message(e){if(e)return{kind:"message",messageId:e.messageId,parts:e.content.map(r=>k.part(r)),contextId:e.contextId||void 0,taskId:e.taskId||void 0,role:k.role(e.role),metadata:e.metadata,extensions:e.extensions}}static role(e){switch(e){case 2:return"agent";case 1:return"user";default:throw h.invalidParams(`Invalid role: ${e}`)}}static messageSendConfiguration(e){if(e)return{blocking:e.blocking,acceptedOutputModes:e.acceptedOutputModes,pushNotificationConfig:k.pushNotificationConfig(e.pushNotification)}}static pushNotificationConfig(e){if(e)return{id:e.id,url:e.url,token:e.token||void 0,authentication:k.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials}}static part(e){if(e.part?.$case==="text")return{kind:"text",text:e.part.value};if(e.part?.$case==="file"){let r=e.part.value;if(r.file?.$case==="fileWithUri")return{kind:"file",file:{uri:r.file.value,mimeType:r.mimeType}};if(r.file?.$case==="fileWithBytes")return{kind:"file",file:{bytes:Buffer.from(r.file.value).toString("base64"),mimeType:r.mimeType}};throw h.invalidParams("Invalid file part type")}if(e.part?.$case==="data")return{kind:"data",data:e.part.value.data??{}};throw h.invalidParams("Invalid part type")}static messageSendParams(e){if(!e.request)throw h.invalidParams("SendMessageRequest missing message");return{message:k.message(e.request),configuration:k.messageSendConfiguration(e.configuration),metadata:e.metadata}}static sendMessageResult(e){if(e.payload?.$case==="task")return k.task(e.payload.value);if(e.payload?.$case==="msg")return k.message(e.payload.value);throw h.invalidParams("Invalid SendMessageResponse: missing result")}static task(e){if(!e.status)throw h.internalError("Task missing status");return{kind:"task",id:e.id,status:k.taskStatus(e.status),contextId:e.contextId,artifacts:e.artifacts?.map(r=>k.artifact(r)),history:e.history?.map(r=>k.message(r)),metadata:e.metadata}}static taskStatus(e){return{message:k.message(e.update),state:k.taskState(e.state),timestamp:e.timestamp}}static taskState(e){switch(e){case 1:return"submitted";case 2:return"working";case 6:return"input-required";case 3:return"completed";case 5:return"canceled";case 4:return"failed";case 7:return"rejected";case 8:return"auth-required";case 0:return"unknown";default:throw h.invalidParams(`Invalid task state: ${e}`)}}static artifact(e){return{artifactId:e.artifactId,name:e.name||void 0,description:e.description||void 0,parts:e.parts.map(r=>k.part(r)),metadata:e.metadata}}static taskPushNotificationConfig(e){if(!e.pushNotificationConfig)throw h.invalidParams("TaskPushNotificationConfig missing pushNotificationConfig");return{taskId:Mt(e.name),pushNotificationConfig:k.pushNotificationConfig(e.pushNotificationConfig)}}static listTaskPushNotificationConfig(e){return e.configs.map(r=>k.taskPushNotificationConfig(r))}static agentCard(e){return{additionalInterfaces:e.additionalInterfaces?.map(r=>k.agentInterface(r)),capabilities:e.capabilities?k.agentCapabilities(e.capabilities):{},defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,description:e.description,documentationUrl:e.documentationUrl||void 0,name:e.name,preferredTransport:e.preferredTransport,provider:e.provider?k.agentProvider(e.provider):void 0,protocolVersion:e.protocolVersion,security:e.security?.map(r=>k.security(r)),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,k.securityScheme(i)])):{},skills:e.skills.map(r=>k.skills(r)),signatures:e.signatures?.map(r=>k.agentCardSignature(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard,url:e.url,version:e.version}}static agentCapabilities(e){return{extensions:e.extensions?.map(r=>k.agentExtension(r)),pushNotifications:e.pushNotifications,streaming:e.streaming}}static agentExtension(e){return{uri:e.uri,description:e.description||void 0,required:e.required,params:e.params}}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){return{organization:e.organization,url:e.url}}static security(e){return Object.fromEntries(Object.entries(e.schemes)?.map(([r,i])=>[r,i.list]))}static securityScheme(e){switch(e.scheme?.$case){case"apiKeySecurityScheme":return{type:"apiKey",name:e.scheme.value.name,in:e.scheme.value.location,description:e.scheme.value.description||void 0};case"httpAuthSecurityScheme":return{type:"http",scheme:e.scheme.value.scheme,bearerFormat:e.scheme.value.bearerFormat||void 0,description:e.scheme.value.description||void 0};case"mtlsSecurityScheme":return{type:"mutualTLS",description:e.scheme.value.description||void 0};case"oauth2SecurityScheme":if(!e.scheme.value.flows)throw h.internalError("OAuth2 security scheme missing flows");return{type:"oauth2",description:e.scheme.value.description||void 0,flows:k.oauthFlows(e.scheme.value.flows),oauth2MetadataUrl:e.scheme.value.oauth2MetadataUrl||void 0};case"openIdConnectSecurityScheme":return{type:"openIdConnect",description:e.scheme.value.description||void 0,openIdConnectUrl:e.scheme.value.openIdConnectUrl};default:throw h.internalError("Unsupported security scheme type")}}static oauthFlows(e){switch(e.flow?.$case){case"implicit":return{implicit:{authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,refreshUrl:e.flow.value.refreshUrl||void 0}};case"password":return{password:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"authorizationCode":return{authorizationCode:{refreshUrl:e.flow.value.refreshUrl||void 0,authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"clientCredentials":return{clientCredentials:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};default:throw h.internalError("Unsupported OAuth flows")}}static skills(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags,examples:e.examples,inputModes:e.inputModes,outputModes:e.outputModes,security:e.security?.map(r=>k.security(r))}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static taskStatusUpdateEvent(e){if(!e.status)throw h.invalidParams("Invalid TaskStatusUpdateEvent: missing status");return{kind:"status-update",taskId:e.taskId,status:k.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){if(!e.artifact)throw h.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");return{kind:"artifact-update",taskId:e.taskId,artifact:k.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,lastChunk:e.lastChunk}}static messageStreamResult(e){switch(e.payload?.$case){case"msg":return k.message(e.payload.value);case"task":return k.task(e.payload.value);case"statusUpdate":return k.taskStatusUpdateEvent(e.payload.value);case"artifactUpdate":return k.taskArtifactUpdateEvent(e.payload.value);default:throw h.internalError("Invalid event type in StreamResponse")}}},vt=class I{static agentCard(e){return{protocolVersion:e.protocolVersion,name:e.name,description:e.description,url:e.url,preferredTransport:e.preferredTransport??"",additionalInterfaces:e.additionalInterfaces?.map(r=>I.agentInterface(r))??[],provider:I.agentProvider(e.provider),version:e.version,documentationUrl:e.documentationUrl??"",capabilities:I.agentCapabilities(e.capabilities),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,I.securityScheme(i)])):{},security:e.security?.map(r=>I.security(r))??[],defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,skills:e.skills.map(r=>I.agentSkill(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard??!1,signatures:e.signatures?.map(r=>I.agentCardSignature(r))??[]}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static agentSkill(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags??[],examples:e.examples??[],inputModes:e.inputModes??[],outputModes:e.outputModes??[],security:e.security?e.security.map(r=>I.security(r)):[]}}static security(e){return{schemes:Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{list:i}]))}}static securityScheme(e){switch(e.type){case"apiKey":return{scheme:{$case:"apiKeySecurityScheme",value:{name:e.name,location:e.in,description:e.description??""}}};case"http":return{scheme:{$case:"httpAuthSecurityScheme",value:{description:e.description??"",scheme:e.scheme,bearerFormat:e.bearerFormat??""}}};case"mutualTLS":return{scheme:{$case:"mtlsSecurityScheme",value:{description:e.description??""}}};case"oauth2":return{scheme:{$case:"oauth2SecurityScheme",value:{description:e.description??"",flows:I.oauthFlows(e.flows),oauth2MetadataUrl:e.oauth2MetadataUrl??""}}};case"openIdConnect":return{scheme:{$case:"openIdConnectSecurityScheme",value:{description:e.description??"",openIdConnectUrl:e.openIdConnectUrl}}};default:throw h.internalError("Unsupported security scheme type")}}static oauthFlows(e){if(e.implicit)return{flow:{$case:"implicit",value:{authorizationUrl:e.implicit.authorizationUrl,scopes:e.implicit.scopes,refreshUrl:e.implicit.refreshUrl??""}}};if(e.password)return{flow:{$case:"password",value:{tokenUrl:e.password.tokenUrl,scopes:e.password.scopes,refreshUrl:e.password.refreshUrl??""}}};if(e.clientCredentials)return{flow:{$case:"clientCredentials",value:{tokenUrl:e.clientCredentials.tokenUrl,scopes:e.clientCredentials.scopes,refreshUrl:e.clientCredentials.refreshUrl??""}}};if(e.authorizationCode)return{flow:{$case:"authorizationCode",value:{authorizationUrl:e.authorizationCode.authorizationUrl,tokenUrl:e.authorizationCode.tokenUrl,scopes:e.authorizationCode.scopes,refreshUrl:e.authorizationCode.refreshUrl??""}}};throw h.internalError("Unsupported OAuth flows")}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){if(e)return{url:e.url,organization:e.organization}}static agentCapabilities(e){return e?{streaming:e.streaming??!1,pushNotifications:e.pushNotifications??!1,extensions:e.extensions?e.extensions.map(r=>I.agentExtension(r)):[]}:{streaming:!1,pushNotifications:!1,extensions:[]}}static agentExtension(e){return{uri:e.uri,description:e.description??"",required:e.required??!1,params:e.params}}static listTaskPushNotificationConfig(e){return{configs:e.map(r=>I.taskPushNotificationConfig(r)),nextPageToken:""}}static getTaskPushNotificationConfigParams(e){return{name:rr(e.id,e.pushNotificationConfigId??"")}}static listTaskPushNotificationConfigParams(e){return{parent:Lt(e.id),pageToken:"",pageSize:0}}static deleteTaskPushNotificationConfigParams(e){return{name:rr(e.id,e.pushNotificationConfigId)}}static taskPushNotificationConfig(e){return{name:rr(e.taskId,e.pushNotificationConfig.id??""),pushNotificationConfig:I.pushNotificationConfig(e.pushNotificationConfig)}}static taskPushNotificationConfigCreate(e){return{parent:Lt(e.taskId),config:I.taskPushNotificationConfig(e),configId:e.pushNotificationConfig.id??""}}static pushNotificationConfig(e){if(e)return{id:e.id??"",url:e.url,token:e.token??"",authentication:I.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials??""}}static messageStreamResult(e){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}};if(e.kind==="status-update")return{payload:{$case:"statusUpdate",value:I.taskStatusUpdateEvent(e)}};if(e.kind==="artifact-update")return{payload:{$case:"artifactUpdate",value:I.taskArtifactUpdateEvent(e)}};throw h.internalError("Invalid event type")}static taskStatusUpdateEvent(e){return{taskId:e.taskId,status:I.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){return{taskId:e.taskId,artifact:I.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,append:e.append??!1,lastChunk:e.lastChunk??!1}}static messageSendResult(e){if(e.kind){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}}}}static message(e){if(e)return{messageId:e.messageId,content:e.parts.map(r=>I.part(r)),contextId:e.contextId??"",taskId:e.taskId??"",role:I.role(e.role),metadata:e.metadata,extensions:e.extensions??[]}}static role(e){switch(e){case"agent":return 2;case"user":return 1;default:throw h.internalError("Invalid role")}}static task(e){return{id:e.id,contextId:e.contextId,status:I.taskStatus(e.status),artifacts:e.artifacts?.map(r=>I.artifact(r))??[],history:e.history?.map(r=>I.message(r)).filter(r=>!!r)??[],metadata:e.metadata}}static taskStatus(e){return{state:I.taskState(e.state),update:I.message(e.message),timestamp:e.timestamp}}static artifact(e){return{artifactId:e.artifactId,name:e.name??"",description:e.description??"",parts:e.parts.map(r=>I.part(r)),metadata:e.metadata,extensions:e.extensions?e.extensions:[]}}static taskState(e){switch(e){case"submitted":return 1;case"working":return 2;case"input-required":return 6;case"rejected":return 7;case"auth-required":return 8;case"completed":return 3;case"failed":return 4;case"canceled":return 5;case"unknown":return 0;default:return-1}}static part(e){if(e.kind==="text")return{part:{$case:"text",value:e.text}};if(e.kind==="file"){let r;if("uri"in e.file)r={file:{$case:"fileWithUri",value:e.file.uri},mimeType:e.file.mimeType??""};else if("bytes"in e.file)r={file:{$case:"fileWithBytes",value:Buffer.from(e.file.bytes,"base64")},mimeType:e.file.mimeType??""};else throw h.internalError("Invalid file part");return{part:{$case:"file",value:r}}}if(e.kind==="data")return{part:{$case:"data",value:{data:e.data}}};throw h.internalError("Invalid part type")}static messageSendParams(e){return{request:I.message(e.message),configuration:I.configuration(e.configuration),metadata:e.metadata}}static configuration(e){if(e)return{blocking:e.blocking??!1,acceptedOutputModes:e.acceptedOutputModes??[],pushNotification:I.pushNotificationConfig(e.pushNotificationConfig),historyLength:e.historyLength??0}}static taskQueryParams(e){return{name:Lt(e.id),historyLength:e.historyLength??0}}static cancelTaskRequest(e){return{name:Lt(e.id)}}static taskIdParams(e){return{name:Lt(e.id)}}static getAgentCardRequest(){return{}}},Nd=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(O.BAD_REQUEST).json(Rt(h.parseError("Invalid JSON payload.")));i(t)};function Ed(t){let e=cr.default.Router(),r=new jo(t.requestHandler);e.use((f,E,g)=>{let A=f.header(nt)||Ut;yr(A)?g():g("router")}),e.use((f,E,g)=>{E.setHeader("Content-Type",qt),g()},cr.default.json({type:qt,strict:!1}),Nd);let i=async f=>{let E=await t.userBuilder(f),g=f.header(nt)||Ut,M=(t.contextBuilder??_r)({extensions:Se.parseServiceParameter(f.header(le)??f.header(At)),user:E,headers:f.headers,requestedVersion:g,tenant:f.params.tenant||void 0}),H=await r.getAgentCard();return vr(M.requestedVersion,H,"HTTP+JSON"),M},a=(f,E)=>{E.activatedExtensions&&f.setHeader(le,Array.from(E.activatedExtensions))},n=(f,E,g,A)=>{a(f,g),f.status(E),E===O.NO_CONTENT?f.end():f.json(A)},o=f=>{let E=vt.messageSendResult(f);if(!E)throw h.internalError("sendMessage produced no result.");return pd.toJSON(E)},l=f=>zt.toJSON(vt.task(f)),c=f=>pe.toJSON(vt.taskPushNotificationConfig(f)),T=f=>cd.toJSON(vt.agentCard(f)),S=f=>Sd.toJSON({configs:f.map(E=>vt.taskPushNotificationConfig(E)),nextPageToken:""}),_=f=>{let E=fd.fromJSON(f??{});return Wi.messageSendParams(E)},u=f=>{let E=pe.fromJSON(f??{});return Wi.taskPushNotificationConfig(E)},N=f=>{let E=vt.messageStreamResult(f);if(!E)throw h.internalError("Stream produced an unrepresentable event.");return hd.toJSON(E)},p=async(f,E,g)=>{let A=E[Symbol.asyncIterator](),M;try{M=await A.next()}catch(H){a(f,g);let Ee=xi(H);f.status(Ee).json(Rt(H));return}Object.entries(se).forEach(([H,Ee])=>{f.setHeader(H,Ee)}),a(f,g),f.flushHeaders();try{M.done||f.write(Tt(N(M.value)));for await(let H of hr(A))f.write(Tt(N(H)))}catch(H){console.error("Legacy SSE streaming error:",H),f.writableEnded||f.write(oe(Rt(H)))}finally{f.writableEnded||f.end()}},m=(f,E)=>{if(f.headersSent){f.writableEnded||f.end();return}let g=xi(E);f.status(g).json(Rt(E))},y=f=>async(E,g)=>{try{await f(E,g)}catch(A){m(g,A)}};e.get("/v1/card",y(async(f,E)=>{let g=await i(f),A=await r.getAuthenticatedExtendedAgentCard(g);n(E,O.OK,g,T(A))})),e.post("/v1/message\\:send",y(async(f,E)=>{let g=await i(f),A=_(f.body),M=await r.sendMessage(A,g);n(E,O.CREATED,g,o(M))})),e.post("/v1/message\\:stream",y(async(f,E)=>{let g=await i(f),A=_(f.body),M=await r.sendMessageStream(A,g);await p(E,M,g)})),e.post("/v1/tasks/:taskId\\:cancel",y(async(f,E)=>{let g=await i(f),A=await r.cancelTask(f.params.taskId,g);n(E,O.OK,g,l(A))}));let C=y(async(f,E)=>{let g=await i(f),A=await r.resubscribe(f.params.taskId,g);await p(E,A,g)});return e.get("/v1/tasks/:taskId\\:subscribe",C),e.post("/v1/tasks/:taskId\\:subscribe",C),e.get("/v1/tasks/:taskId",y(async(f,E)=>{let g=await i(f),A=f.query.historyLength??f.query.history_length,M=await r.getTask(f.params.taskId,g,A);n(E,O.OK,g,l(M))})),e.post("/v1/tasks/:taskId/pushNotificationConfigs",y(async(f,E)=>{let g=await i(f),A=u(f.body),M=await r.setTaskPushNotificationConfig(A,g);n(E,O.CREATED,g,c(M))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs",y(async(f,E)=>{let g=await i(f),A=await r.listTaskPushNotificationConfigs(f.params.taskId,g);n(E,O.OK,g,S(A))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs/:configId",y(async(f,E)=>{let g=await i(f),A=await r.getTaskPushNotificationConfig(f.params.taskId,f.params.configId,g);n(E,O.OK,g,c(A))})),e.delete("/v1/tasks/:taskId/pushNotificationConfigs/:configId",y(async(f,E)=>{let g=await i(f);await r.deleteTaskPushNotificationConfig(f.params.taskId,f.params.configId,g),n(E,O.NO_CONTENT,g)})),e}function Od(t){return`W/"${id.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function Da(t){let e=xa.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return t.legacyCompat?.enabled&&e.use(sd(t)),e.get("/",async(a,n)=>{try{let o=await i(),l=JSON.stringify(o),c=Od(l);if(n.setHeader("ETag",c),t.legacyCompat?.enabled&&n.append("Vary",nt),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type","application/json"),n.status(200).send(l)}catch(o){console.error("Error fetching agent card:",o),n.status(500).json({error:"Failed to retrieve agent card"})}}),e}function Ma(t){return t==="true"||t===!0}var _d=class La{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e,r){return this.requestHandler.getAuthenticatedExtendedAgentCard(e,r)}validateSendMessageRequest(e){if(!e.message)throw new $("message is required");if(!e.message.messageId)throw new $("message.messageId is required")}async sendMessage(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessage(e,r)}async sendMessageStream(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessageStream(e,r)}async getTask(e,r,i,a){let n={id:e,tenant:a||""};return i!==void 0&&(n.historyLength=this.parseHistoryLength(i)),this.requestHandler.getTask(n,r)}async cancelTask(e,r,i){let a={id:e,tenant:i||"",metadata:{}};return this.requestHandler.cancelTask(a,r)}async listTasks(e,r){let i={tenant:e.tenant||"",contextId:e.contextId||"",status:e.status?Sr(isNaN(Number(e.status))?e.status:Number(e.status)):0,pageSize:e.pageSize!==void 0&&e.pageSize!==""?this.parsePageSize(e.pageSize):void 0,pageToken:e.pageToken||"",historyLength:e.historyLength!==void 0&&e.historyLength!==""?this.parseHistoryLength(e.historyLength):void 0,statusTimestampAfter:e.statusTimestampAfter||void 0,includeArtifacts:Ma(e.includeArtifacts)};return this.requestHandler.listTasks(i,r)}async resubscribe(e,r,i){return this.requestHandler.resubscribe({id:e,tenant:i||""},r)}async createTaskPushNotificationConfig(e,r){return await this.requireCapability("pushNotifications"),this.requestHandler.createTaskPushNotificationConfig(e,r)}async listTaskPushNotificationConfigs(e,r,i){return await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:i||""},r)}async getTaskPushNotificationConfig(e,r,i,a){return await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}async deleteTaskPushNotificationConfig(e,r,i,a){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}static CAPABILITY_ERRORS={pushNotifications:()=>new gr};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw La.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw new $("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw new $("historyLength must be a valid integer");if(r<0)throw new $("historyLength must be non-negative");return r}parsePageSize(e){let r=parseInt(String(e),10);if(isNaN(r)||String(r)!==String(e).trim())throw new $("pageSize must be a valid integer");if(r<1||r>100)throw new $("pageSize must be between 1 and 100");return r}},vd=class{static messageSendResult(t){if("messageId"in t)return{payload:{$case:"message",value:t}};if("artifacts"in t)return{payload:{$case:"task",value:t}};throw new W("Invalid SendMessageResult type")}},yd=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(400).json($t(new $("Invalid JSON payload."),400));i(t)},Ad=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}let a=i.split(";",1)[0].trim().toLowerCase();if(a===Tr||a===nr){r();return}let n=new mr(`Unsupported Content-Type "${i}"; expected application/json or application/a2a+json.`);e.status(O.BAD_REQUEST).json($t(n,O.BAD_REQUEST))};function $a(t){let e=fr.default.Router(),r=new _d(t.requestHandler);t.legacyCompat?.enabled&&e.use(Ed(t)),e.use((u,N,p)=>{N.setHeader("Content-Type",nr),p()},Ad,fr.default.json({type:[Tr,nr],strict:!1}),yd);let i=async u=>{let N=await t.userBuilder(u),p=u.params.tenant||void 0,m=u.header(nt)||void 0,C=(t.contextBuilder??_r)({extensions:Se.parseServiceParameter(u.header(At)),user:N,headers:u.headers,requestedVersion:m,tenant:p}),f=await r.getAgentCard();return vr(C.requestedVersion,f,"HTTP+JSON"),C},a=(u,N)=>{N.activatedExtensions&&u.setHeader(At,Array.from(N.activatedExtensions))},n=(u,N,p,m,y)=>{if(a(u,p),u.status(N),N===O.NO_CONTENT)u.end();else{if(!y||m===void 0)throw new Error("Bug: toJson serializer and body must be provided for non-204 responses.");u.json(y.toJSON(m))}},o=async(u,N,p)=>{let m=N[Symbol.asyncIterator](),y;try{y=await m.next()}catch(C){a(u,p);let f=te(C);u.status(f).json($t(C,f));return}Object.entries(se).forEach(([C,f])=>{u.setHeader(C,f)}),a(u,p),u.flushHeaders();try{if(!y.done){let C=ar.toJSON(y.value);u.write(Tt(C))}for await(let C of hr(m)){let f=ar.toJSON(C);u.write(Tt(f))}}catch(C){console.error("SSE streaming error:",C),u.writableEnded||u.write(oe($t(C,te(C))))}finally{u.writableEnded||u.end()}},l=(u,N)=>{if(u.headersSent){u.writableEnded||u.end();return}let p=te(N);u.status(p).json($t(N,p))},c=u=>async(N,p)=>{try{await u(N,p)}catch(m){l(p,m)}},T=(u,N,p)=>{let m=u.params.tenant;if(!m){p();return}let y=u.body?.tenant;y&&y!==m&&console.warn(`Tenant mismatch: URL path tenant "${m}" differs from request body tenant "${y}". Using path tenant as the canonical value.`);let C=u.query?.tenant;C&&C!==m&&console.warn(`Tenant mismatch: URL path tenant "${m}" differs from query param tenant "${C}". Using path tenant as the canonical value.`),u.body&&(u.body.tenant=m),u.query.tenant=m,p()},S=(u,N,p)=>{e[u](N,c(p)),e[u](`/:tenant${N}`,T,c(p))};S("get","/extendedAgentCard",async(u,N)=>{let p=await i(u),m=await r.getAuthenticatedExtendedAgentCard({tenant:u.query.tenant||""},p);n(N,O.OK,p,m,Zi)}),S("post","/message\\:send",async(u,N)=>{let p=await i(u),m=ne.fromJSON(u.body??{}),y=await r.sendMessage(m,p),C=vd.messageSendResult(y);n(N,O.OK,p,C,Rs)}),S("post","/message\\:stream",async(u,N)=>{let p=await i(u),m=ne.fromJSON(u.body??{}),y=await r.sendMessageStream(m,p);await o(N,y,p)});let _=async(u,N)=>{let p=await i(u),m=await r.resubscribe(u.params.taskId,p,u.query.tenant||"");await o(N,m,p)};return S("get","/tasks/:taskId\\:subscribe",_),S("post","/tasks/:taskId\\:subscribe",_),S("post","/tasks/:taskId\\:cancel",async(u,N)=>{let p=await i(u),m=await r.cancelTask(u.params.taskId,p,u.query.tenant||"");n(N,O.OK,p,m,Q)}),S("get","/tasks/:taskId",async(u,N)=>{let p=await i(u),m=await r.getTask(u.params.taskId,p,u.query.historyLength,u.query.tenant||"");n(N,O.OK,p,m,Q)}),S("get","/tasks",async(u,N)=>{let p=await i(u),m=await r.listTasks(u.query,p),y=Ma(u.query.includeArtifacts);n(N,O.OK,p,m,{...ji,toJSON:C=>ea(C,{includeArtifacts:y})})}),S("post","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let p=await i(u),m=b.fromJSON({...u.body??{},taskId:u.params.taskId}),y=await r.createTaskPushNotificationConfig(m,p);n(N,O.CREATED,p,y,b)}),S("get","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let p=await i(u),m=await r.listTaskPushNotificationConfigs(u.params.taskId,p,u.query.tenant||"");n(N,O.OK,p,m,ta)}),S("get","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let p=await i(u),m=await r.getTaskPushNotificationConfig(u.params.taskId,u.params.configId,p,u.query.tenant||"");n(N,O.OK,p,m,b)}),S("delete","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let p=await i(u);await r.deleteTaskPushNotificationConfig(u.params.taskId,u.params.configId,p,u.query.tenant||""),n(N,O.NO_CONTENT,p)}),e}var mn=Nt(Et(),1);var fn={};Kt(fn,{buildAgentCard:()=>Ur});var kd="a2a-protocol.org",Id="type.googleapis.com/google.rpc.ErrorInfo",za=Symbol.for("@a2a-js/sdk.A2AError"),me=class Fa extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(za in e))return!1;if(this===Fa)return!0;for(let r=Object.getPrototypeOf(e);r!==null;r=Object.getPrototypeOf(r))if(r.constructor?.name===this.name)return!0;return!1}constructor(e){let r=typeof e=="string"?{message:e}:e;super(r?.message??"An unexpected error occurred.",r?.cause!==void 0?{cause:r.cause}:void 0),this.name=new.target.name,r?.metadata&&Object.keys(r.metadata).length>0&&(this.metadata=r.metadata)}toErrorInfo(){return{"@type":Id,reason:this.reason,domain:kd,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(me.prototype,za,{value:!0});var Ba=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],ut=Object.freeze(Object.fromEntries(Ba.map(t=>[t.name,t]))),du=Object.freeze(Object.fromEntries(Ba.map(t=>[t.reason,t])));function ct(t){return{[t.name]:class extends me{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var Ha=ct(ut.TaskNotFoundError),Va=ct(ut.TaskNotCancelableError),Ga=ct(ut.PushNotificationNotSupportedError),Ka=ct(ut.UnsupportedOperationError),Rd=ct(ut.ContentTypeNotSupportedError),Cd=ct(ut.InvalidAgentResponseError),Qa=ct(ut.ExtendedAgentCardNotConfiguredError),Ud=ct(ut.ExtensionSupportRequiredError),Jd=ct(ut.VersionNotSupportedError),ba=ct(ut.RequestMalformedError),Rr=Object.freeze({TaskNotFoundError:Ha,TaskNotCancelableError:Va,PushNotificationNotSupportedError:Ga,UnsupportedOperationError:Ka,ContentTypeNotSupportedError:Rd,InvalidAgentResponseError:Cd,ExtendedAgentCardNotConfiguredError:Qa,ExtensionSupportRequiredError:Ud,VersionNotSupportedError:Jd,RequestMalformedError:ba}),J={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},Ya=Object.freeze({TaskNotFoundError:J.TASK_NOT_FOUND,TaskNotCancelableError:J.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:J.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:J.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:J.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:J.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:J.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:J.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:J.VERSION_NOT_SUPPORTED,RequestMalformedError:J.INVALID_PARAMS}),wd=Object.freeze(Object.fromEntries(Object.entries(Ya).map(([t,e])=>[e,t])));function ft(t){let e=Rr[t],r=Ya[t]??J.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var xd=ft("TaskNotFoundError"),Pd=ft("TaskNotCancelableError"),Dd=ft("PushNotificationNotSupportedError"),Cr=ft("UnsupportedOperationError"),Md=ft("ContentTypeNotSupportedError"),Ld=ft("InvalidAgentResponseError"),$d=ft("ExtendedAgentCardNotConfiguredError"),qd=ft("ExtensionSupportRequiredError"),zd=ft("VersionNotSupportedError"),Ht=ft("RequestMalformedError"),Fd=Object.freeze({TaskNotFoundError:xd,TaskNotCancelableError:Pd,PushNotificationNotSupportedError:Dd,UnsupportedOperationError:Cr,ContentTypeNotSupportedError:Md,InvalidAgentResponseError:Ld,ExtendedAgentCardNotConfiguredError:$d,ExtensionSupportRequiredError:qd,VersionNotSupportedError:zd,RequestMalformedError:Ht}),Wa=class extends me{transport="jsonrpc";envelopeCode;data;errorResponse;constructor(t){super({message:t.error.message}),this.name="JsonRpcTransportError",this.envelopeCode=t.error.code,t.error.data!==void 0&&(this.data=t.error.data),this.errorResponse=t}},lu={[J.PARSE_ERROR]:"RequestMalformedError",[J.INVALID_REQUEST]:"RequestMalformedError",[J.METHOD_NOT_FOUND]:"RequestMalformedError"},Z={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},lt={OK:"OK",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN",INVALID_ARGUMENT:"INVALID_ARGUMENT",DEADLINE_EXCEEDED:"DEADLINE_EXCEEDED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",PERMISSION_DENIED:"PERMISSION_DENIED",RESOURCE_EXHAUSTED:"RESOURCE_EXHAUSTED",FAILED_PRECONDITION:"FAILED_PRECONDITION",ABORTED:"ABORTED",OUT_OF_RANGE:"OUT_OF_RANGE",UNIMPLEMENTED:"UNIMPLEMENTED",INTERNAL:"INTERNAL",UNAVAILABLE:"UNAVAILABLE",DATA_LOSS:"DATA_LOSS",UNAUTHENTICATED:"UNAUTHENTICATED"},Bd=Object.freeze({TaskNotFoundError:Z.NOT_FOUND,TaskNotCancelableError:Z.BAD_REQUEST,PushNotificationNotSupportedError:Z.BAD_REQUEST,UnsupportedOperationError:Z.BAD_REQUEST,ContentTypeNotSupportedError:Z.BAD_REQUEST,InvalidAgentResponseError:Z.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:Z.BAD_REQUEST,ExtensionSupportRequiredError:Z.BAD_REQUEST,VersionNotSupportedError:Z.BAD_REQUEST,RequestMalformedError:Z.BAD_REQUEST}),uu=Object.freeze({TaskNotFoundError:lt.NOT_FOUND,TaskNotCancelableError:lt.FAILED_PRECONDITION,PushNotificationNotSupportedError:lt.FAILED_PRECONDITION,UnsupportedOperationError:lt.FAILED_PRECONDITION,ContentTypeNotSupportedError:lt.INVALID_ARGUMENT,InvalidAgentResponseError:lt.INTERNAL,ExtendedAgentCardNotConfiguredError:lt.FAILED_PRECONDITION,ExtensionSupportRequiredError:lt.FAILED_PRECONDITION,VersionNotSupportedError:lt.FAILED_PRECONDITION,RequestMalformedError:lt.INVALID_ARGUMENT});function pt(t){let e=Rr[t],r=Bd[t]??Z.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var Hd=pt("TaskNotFoundError"),Vd=pt("TaskNotCancelableError"),Gd=pt("PushNotificationNotSupportedError"),Kd=pt("UnsupportedOperationError"),Qd=pt("ContentTypeNotSupportedError"),bd=pt("InvalidAgentResponseError"),Yd=pt("ExtendedAgentCardNotConfiguredError"),Wd=pt("ExtensionSupportRequiredError"),Xd=pt("VersionNotSupportedError"),Zd=pt("RequestMalformedError"),cu=Object.freeze({TaskNotFoundError:Hd,TaskNotCancelableError:Vd,PushNotificationNotSupportedError:Gd,UnsupportedOperationError:Kd,ContentTypeNotSupportedError:Qd,InvalidAgentResponseError:bd,ExtendedAgentCardNotConfiguredError:Yd,ExtensionSupportRequiredError:Wd,VersionNotSupportedError:Xd,RequestMalformedError:Zd});function jd(t,e,r){let i=wd[t];return i?r===void 0?new Rr[i]({message:e}):new Fd[i]({message:e,envelopeCode:t,data:r}):t===J.METHOD_NOT_FOUND?new Cr({message:e,envelopeCode:t,data:r}):t===J.PARSE_ERROR||t===J.INVALID_REQUEST?new Ht({message:e,envelopeCode:t,data:r}):new Wa({jsonrpc:"2.0",id:null,error:{code:t,message:e,data:r}})}var j=jd;Object.defineProperty(j,Symbol.hasInstance,{value:t=>t instanceof me});j.parseError=(t,e)=>new Ht({message:t,envelopeCode:J.PARSE_ERROR,data:e});j.invalidRequest=(t,e)=>new Ht({message:t,envelopeCode:J.INVALID_REQUEST,data:e});j.methodNotFound=t=>new Cr({message:`Method not found: ${t}`,envelopeCode:J.METHOD_NOT_FOUND});j.invalidParams=(t,e)=>e===void 0?new ba({message:t}):new Ht({message:t,envelopeCode:J.INVALID_PARAMS,data:e});j.internalError=(t,e)=>new Wa({jsonrpc:"2.0",id:null,error:{code:J.INTERNAL_ERROR,message:t,...e!==void 0?{data:e}:{}}});j.taskNotFound=t=>new Ha({message:`Task not found: ${t}`});j.taskNotCancelable=t=>new Va({message:`Task not cancelable: ${t}`});j.pushNotificationNotSupported=()=>new Ga;j.unsupportedOperation=t=>new Ka({message:`Unsupported operation: ${t}`});j.authenticatedExtendedCardNotConfigured=()=>new Qa({message:"Extended card not configured."});var tl="1.0",el="0.3";var Xa="message/send",Za="message/stream",ja="tasks/get",tn="tasks/cancel",en="tasks/resubscribe",rn="tasks/pushNotificationConfig/set",an="tasks/pushNotificationConfig/get",nn="tasks/pushNotificationConfig/list",sn="tasks/pushNotificationConfig/delete",on="agent/getAuthenticatedExtendedCard",dn=Object.freeze({[Xa]:"SendMessage",[Za]:"SendStreamingMessage",[ja]:"GetTask",[tn]:"CancelTask",[en]:"SubscribeToTask",[rn]:"CreateTaskPushNotificationConfig",[an]:"GetTaskPushNotificationConfig",[nn]:"ListTaskPushNotificationConfigs",[sn]:"DeleteTaskPushNotificationConfig",[on]:"GetExtendedAgentCard"});var fu=Object.freeze(Object.fromEntries(Object.entries(dn).map(([t,e])=>[e,t]))),ln=Object.freeze({[Xa]:"SendMessage",[Za]:"SendStreamingMessage",[ja]:"GetTask",[tn]:"CancelTask",[en]:"TaskSubscription",[rn]:"CreateTaskPushNotificationConfig",[an]:"GetTaskPushNotificationConfig",[nn]:"ListTaskPushNotificationConfig",[sn]:"DeleteTaskPushNotificationConfig",[on]:"GetAgentCard"}),pu=Object.freeze(Object.fromEntries(Object.entries(ln).map(([t,e])=>[e,t]))),rl=Object.freeze(Object.fromEntries(Object.entries(ln).map(([t,e])=>[e,dn[t]]))),hu=Object.freeze(Object.fromEntries(Object.entries(rl).map(([t,e])=>[e,t])));var un=el,il=tl;function Ir(t){let e=t.trim();if(e==="")return;let r=e.split(".");if(r.length===0)return;let i=Number.parseInt(r[0],10);if(!Number.isFinite(i)||i<0)return;let a=r[1],n=a===void 0?0:Number.parseInt(a,10);if(!(!Number.isFinite(n)||n<0))return{major:i,minor:n}}function qa(t,e){return t.major!==e.major?t.major-e.major:t.minor-e.minor}function al(t){if(!t||t.trim()==="")return!0;let e=Ir(t);if(!e)return!1;let r=Ir(un),i=Ir(il);return!r||!i?!1:qa(e,r)>=0&&qa(e,i)<0}function cn(t,e){let r=t??[],i=structuredClone(r);for(let a of e){if(r.some(l=>l.protocolBinding===a&&(!l.protocolVersion||al(l.protocolVersion))))continue;let o=r.find(l=>l.protocolBinding===a);o&&i.push({...structuredClone(o),protocolVersion:un})}return i}var nl=Object.freeze({unknown:0,submitted:1,working:2,completed:3,failed:4,canceled:5,"input-required":6,rejected:7,"auth-required":8}),Su=new Map(Object.entries(nl).map(([t,e])=>[e,t]));var sl="Yukino is a terminal-based AI coding agent. It reads, edits, and creates files, runs shell commands, and drives multi-step coding tasks from natural language instructions.",ol="Executes software engineering tasks: answering questions about a codebase, writing and refactoring code, running commands, and fixing bugs.";function Ur(t){return{name:"yukino",description:sl,supportedInterfaces:cn([{url:t,protocolBinding:"JSONRPC",protocolVersion:"1.0",tenant:""},{url:t,protocolBinding:"HTTP+JSON",protocolVersion:"1.0",tenant:""}],["JSONRPC","HTTP+JSON"]),provider:void 0,version:Vr,capabilities:{streaming:!0,pushNotifications:!1,extensions:[]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],skills:[{id:"coding",name:"Coding",description:ol,tags:["code","development","programming"],examples:["Fix the failing tests in this repository.","Add a dark mode toggle to the settings page."],inputModes:["text/plain"],outputModes:["text/plain"],securityRequirements:[]}],signatures:[]}}var gn={};Kt(gn,{DEFAULT_IDLE_TIMEOUT_MS:()=>Tn,YukinoA2aExecutor:()=>Gt,createA2aRuntime:()=>Ne});import{randomUUID as hl}from"crypto";var B=(t=>(t[t.TASK_STATE_UNSPECIFIED=0]="TASK_STATE_UNSPECIFIED",t[t.TASK_STATE_SUBMITTED=1]="TASK_STATE_SUBMITTED",t[t.TASK_STATE_WORKING=2]="TASK_STATE_WORKING",t[t.TASK_STATE_COMPLETED=3]="TASK_STATE_COMPLETED",t[t.TASK_STATE_FAILED=4]="TASK_STATE_FAILED",t[t.TASK_STATE_CANCELED=5]="TASK_STATE_CANCELED",t[t.TASK_STATE_INPUT_REQUIRED=6]="TASK_STATE_INPUT_REQUIRED",t[t.TASK_STATE_REJECTED=7]="TASK_STATE_REJECTED",t[t.TASK_STATE_AUTH_REQUIRED=8]="TASK_STATE_AUTH_REQUIRED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(B||{}),Jr=(t=>(t[t.ROLE_UNSPECIFIED=0]="ROLE_UNSPECIFIED",t[t.ROLE_USER=1]="ROLE_USER",t[t.ROLE_AGENT=2]="ROLE_AGENT",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(Jr||{});var vu=4*1024*1024;var hn={};Kt(hn,{MAX_TOOL_OUTPUT_LENGTH:()=>wr,PermissionRequestDataSchema:()=>ll,PermissionResponseDataSchema:()=>pn,ThinkingDataSchema:()=>ul,ToolCallDataSchema:()=>cl,ToolResultDataSchema:()=>fl,YUKINO_DATA_KEY:()=>wt,agentEventToMessage:()=>Mr,agentMessage:()=>ht,dataPart:()=>Jt,findPermissionResponse:()=>Dr,messageText:()=>Pr,statusUpdate:()=>mt,taskSnapshot:()=>Vt,taskStatus:()=>xr,textPart:()=>xt});import{randomUUID as dl}from"crypto";var wt="yukino",ll=R.object({[wt]:R.literal("permission-request"),permissionId:R.string(),toolCallId:R.string(),toolName:R.string(),reason:R.string(),args:R.record(R.string(),R.unknown())}),pn=R.object({[wt]:R.literal("permission-response"),permissionId:R.string(),decision:R.enum(["allow","deny","allowAlways"])}),ul=R.object({[wt]:R.literal("thinking"),text:R.string()}),cl=R.object({[wt]:R.literal("tool-call"),toolCallId:R.string(),toolName:R.string(),args:R.record(R.string(),R.unknown())}),fl=R.object({[wt]:R.literal("tool-result"),toolCallId:R.string(),toolName:R.string(),isError:R.boolean(),elapsed:R.number(),output:R.string()}),wr=8e3;function xt(t){return{content:{$case:"text",value:t},metadata:void 0,filename:"",mediaType:"text/plain"}}function Jt(t){return{content:{$case:"data",value:t},metadata:void 0,filename:"",mediaType:"application/json"}}function ht(t,e,r){return{messageId:dl(),contextId:e,taskId:t,role:Jr.ROLE_AGENT,parts:r,metadata:void 0,extensions:[],referenceTaskIds:[]}}function xr(t,e){return{state:t,message:e,timestamp:new Date().toISOString()}}function mt(t,e,r,i){return{taskId:t,contextId:e,status:xr(r,i),metadata:void 0}}function Vt(t,e,r,i){return{id:t,contextId:e,status:xr(r,i),artifacts:[],history:[],metadata:void 0}}function Pr(t){let e=[];for(let r of t.parts)r.content?.$case==="text"&&e.push(r.content.value);return e.join(`
|
|
10
|
+
|
|
11
|
+
`).trim()}function pl(t){let e=[];for(let r of t.parts)r.content?.$case==="data"&&e.push(r.content.value);return e}function Dr(t){for(let e of pl(t)){let r=pn.safeParse(e);if(r.success)return r.data}return null}function Mr(t,e,r){switch(t.type){case"stream_text":return ht(e,r,[xt(t.text)]);case"thinking_text":return ht(e,r,[Jt({yukino:"thinking",text:t.text})]);case"tool_use":return ht(e,r,[Jt({yukino:"tool-call",toolCallId:t.toolId,toolName:t.toolName,args:t.args})]);case"tool_result":{let a=t.output.length>wr?`${t.output.slice(0,wr)}
|
|
12
|
+
\u2026 [truncated]`:t.output;return ht(e,r,[Jt({yukino:"tool-result",toolCallId:t.toolId,toolName:t.toolName,isError:t.isError,elapsed:t.elapsed,output:a})])}default:return null}}async function Ne(t,e){let r=Br(Hr(),t),i=qr(r.providers,r.default_provider);if(!i)throw new Error("No provider configured.");let a=await Wr({provider:i,workDir:t,hooks:r.hooks,mcpServers:r.mcp_servers,enableCoordinatorMode:r.enable_coordinator_mode??!1,forkDisabled:!zr(r),memoryEnabled:Fr(r),...e?{sessionId:e}:{}});return e&&a.conv.appendMessages(br(Qr(t,e))),{sessionId:a.sessionId,workDir:a.workDir,run:a.run.bind(a),abort:()=>{a.abort()},dispose:async()=>{a.abort(),await Promise.all([a.backgroundTaskManager.stopAll(),a.teamManager.stopAll(),a.mcpManager?.disconnectAll()??Promise.resolve()])}}}var Tn=1800*1e3,Sn="No active run is awaiting a permission response.";function Lr(){let t=()=>{};return{promise:new Promise(r=>{t=r}),resolve:t}}var Gt=class{constructor(e=Ne,r=process.cwd(),i=Tn){this.runtimeFactory=e;this.workDir=r;this.idleTimeoutMs=i}runtimeFactory;workDir;idleTimeoutMs;sessions=new Map;permissionCounter=0;async execute(e,r){let i=e.taskId,a=e.contextId,n=e.userMessage;this.disarmIdleTimer(this.sessions.get(a));try{await this.dispatch(i,a,n,r)}finally{let o=this.sessions.get(a);o&&this.armIdleTimer(o)}}async dispatch(e,r,i,a){let n=Dr(i);if(n){let _=this.sessions.get(r);if(!_){this.reject(null,a,e,r,Sn);return}await this.handlePermissionResponse(_,e,r,n,a);return}let o=Pr(i);if(!o){this.reject(this.sessions.get(r)??null,a,e,r,"Message must contain text or a yukino permission-response data part.");return}let l=this.sessions.get(r);if(l?.run&&!l.run.finished){this.reject(l,a,e,r,`Context ${r} is busy with task ${l.run.taskId}. Cancel it or wait for it to finish before sending a new message.`);return}let c=l??this.createSession(r),T;try{T=await this.ensureRuntime(c)}catch(_){this.reject(c,a,e,r,Oe(_));return}let S=this.startRun(c,T,e,r,o,a);this.consume(c,S,o),await S.settle.promise}async cancelTask(e,r){let i=this.findSessionByTask(e),a=i?.run;if(!i||!a||a.finished){let n=i?.contextId??"";r.publish(x.statusUpdate(mt(e,n,B.TASK_STATE_CANCELED,ht(e,n,[xt("Task canceled by user request.")]))));return}this.disarmIdleTimer(i),a.canceled=!0,a.bus=r;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),a.runtime.abort(),await a.done.promise}async dispose(){let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async r=>{if(this.disarmIdleTimer(r),!r.runtimePromise)return;let i;try{i=await r.runtimePromise}catch{return}let a=r.run;if(a&&!a.finished){a.canceled=!0;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),i.abort()}await i.dispose()}))}createSession(e){let r={contextId:e,sessionId:void 0,runtimePromise:null,run:null,idleTimer:null};return this.sessions.set(e,r),r}async ensureRuntime(e){e.runtimePromise||(e.runtimePromise=this.runtimeFactory(this.workDir,e.sessionId).then(r=>(e.sessionId=r.sessionId,r)));try{return await e.runtimePromise}catch(r){throw e.runtimePromise=null,r}}armIdleTimer(e){if(this.disarmIdleTimer(e),this.idleTimeoutMs<=0||!e.runtimePromise||e.run&&!e.run.finished)return;let r=setTimeout(()=>{e.idleTimer=null,this.evictSession(e)},this.idleTimeoutMs);r.unref(),e.idleTimer=r}disarmIdleTimer(e){e?.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}evictSession(e){if(e.run&&!e.run.finished)return;let r=e.runtimePromise;e.runtimePromise=null,r&&r.then(i=>i.dispose()).catch(()=>{})}findSessionByTask(e){for(let r of this.sessions.values())if(r.run?.taskId===e)return r}async handlePermissionResponse(e,r,i,a,n){let o=e.run;if(!o||o.finished){this.reject(e,n,r,i,Sn);return}if(o.taskId!==r){this.reject(e,n,r,i,`Permission responses must be sent with taskId "${o.taskId}".`);return}let l=o.permissions.get(a.permissionId);if(!l){this.reject(e,n,r,i,`Unknown or already resolved permission id "${a.permissionId}".`);return}o.bus=n,o.permissions.delete(a.permissionId),o.settle=Lr(),n.publish(x.task(Vt(r,i,B.TASK_STATE_WORKING))),l.resolve(a.decision),o.permissions.size>0&&(this.publishPendingPermissions(o,r,i),o.settle.resolve()),await o.settle.promise}startRun(e,r,i,a,n,o){this.disarmIdleTimer(e);let l={taskId:i,runtime:r,bus:o,settle:Lr(),done:Lr(),canceled:!1,finished:!1,stopReason:null,permissions:new Map};return e.run=l,Gr(r.workDir,r.sessionId,{role:"user",content:n,timestamp:Math.floor(Date.now()/1e3)}),o.publish(x.task(Vt(i,a,B.TASK_STATE_SUBMITTED))),l}consume(e,r,i){let a=r.taskId,n=e.contextId,o=r.runtime.run(i,{onPermissionRequest:(l,c,T,S)=>this.requestPermission(r,a,n,l,c,T,S)});(async()=>{let l=null;try{for await(let c of o)c.type==="compact"&&c.boundary&&Kr(r.runtime.workDir,r.runtime.sessionId,c.boundary),c.type==="loop_complete"&&(r.stopReason=c.stopReason),c.type==="error"&&(l=c.error.message),this.publishAgentEvent(r,a,n,c)}catch(c){l=Oe(c)}this.finishRun(e,r,a,n,l)})()}requestPermission(e,r,i,a,n,o,l){this.permissionCounter+=1;let c=`perm-${String(this.permissionCounter)}-${hl().slice(0,8)}`,T={yukino:"permission-request",permissionId:c,toolCallId:l,toolName:a,reason:o.reason,args:n};return new Promise(S=>{e.permissions.set(c,{data:T,resolve:S}),this.publishPendingPermissions(e,r,i),e.settle.resolve()})}publishPendingPermissions(e,r,i){let a=[...e.permissions.values()].map(n=>Jt(n.data));e.bus.publish(x.statusUpdate(mt(r,i,B.TASK_STATE_INPUT_REQUIRED,ht(r,i,a))))}publishAgentEvent(e,r,i,a){let n=Mr(a,r,i);n&&e.bus.publish(x.statusUpdate(mt(r,i,B.TASK_STATE_WORKING,n)))}finishRun(e,r,i,a,n){if(r.finished)return;r.finished=!0;for(let c of r.permissions.values())c.resolve("deny");r.permissions.clear();let o=this.finalState(r,n),l=n?ht(i,a,[xt(n)]):void 0;r.bus.publish(x.statusUpdate(mt(i,a,o,l))),e.run===r&&(e.run=null),r.settle.resolve(),r.done.resolve(),this.armIdleTimer(e)}finalState(e,r){return e.canceled||e.stopReason==="cancelled"||e.stopReason==="interrupted"?B.TASK_STATE_CANCELED:r?B.TASK_STATE_FAILED:B.TASK_STATE_COMPLETED}reject(e,r,i,a,n){let o=ht(i,a,[xt(n)]);if(e?.run&&!e.run.finished){r.publish(x.message(o));return}r.publish(x.task(Vt(i,a,B.TASK_STATE_FAILED))),r.publish(x.statusUpdate(mt(i,a,B.TASK_STATE_FAILED,o)))}};var Nn=18890,Tl=`127.0.0.1:${String(Nn)}`,gl=new Set(["127.0.0.1","::1","localhost"]);function En(t){let e=Yr(t??Tl,{defaultPort:Nn,allowEphemeral:!0});if(!gl.has(e.host))throw new Error("A2A server must listen on a loopback address.");return e}async function On(t={}){let{host:e,port:r}=En(t.address),i=Sl();await ml(i,r,e);let a=i.address();if(!a||typeof a=="string")throw new Error("A2A server did not bind to a TCP address.");let o=`http://${a.family==="IPv6"?`[${a.address}]`:a.address}:${String(a.port)}/`,l=Ur(o),c=new Gt(t.runtimeFactory??Ne,t.workDir??process.cwd()),T=new Si(l,new Ti,c,new Je),S=(0,mn.default)();S.use("/.well-known/agent-card.json",Da({agentCardProvider:T,legacyCompat:{enabled:!0}})),S.use(wa({requestHandler:T,userBuilder:pr.noAuthentication,legacyCompat:{enabled:!0}})),S.use($a({requestHandler:T,userBuilder:pr.noAuthentication,legacyCompat:{enabled:!0}})),i.on("request",S);let _=!1;return{url:o,cardUrl:`${o}.well-known/agent-card.json`,async close(){_||(_=!0,i.closeIdleConnections(),await Nl(i),await c.dispose())}}}function ml(t,e,r){return new Promise((i,a)=>{let n=l=>{t.off("listening",o),a(l)},o=()=>{t.off("error",n),i()};t.once("error",n),t.once("listening",o),t.listen(e,r)})}function Nl(t){return new Promise((e,r)=>{t.close(i=>{i?r(i):e()})})}async function $r(t){let e=await On({address:t});process.stderr.write(`A2A server listening at ${e.url}
|
|
13
|
+
`),process.stderr.write(`Agent card at ${e.cardUrl}
|
|
14
|
+
`),await new Promise(r=>{let i=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),e.close().finally(r)};process.once("SIGINT",i),process.once("SIGTERM",i)})}function El(t){let e=t.indexOf("--a2a");if(e===-1)return null;let r=t[e+1],i=r&&!r.startsWith("-")?2:1;if(t.length!==i)throw new Error("--a2a accepts only an optional port or host:port address.");return i===2?{address:r}:{}}async function Vu(t){let e=El(t);if(!e)throw new Error("A2A mode was not selected.");await $r(e.address)}export{fn as Card,hn as Conversion,gn as Executor,_n as Server,El as parseA2aMode,Vu as runA2a};
|