@yukino.js/yukino 0.0.21-dev → 0.0.21

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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __yukinoCreateRequire } from "node:module";
3
3
  const require = __yukinoCreateRequire(import.meta.url);
4
- import{a as pt,b as br,c as Zr,d as jr}from"./chunk-P6K7EQHF.js";import{B as Xr,i as Qr,v as Yr,z as Wr}from"./chunk-2N7OIUQW.js";import"./chunk-57IGGFHK.js";import{A as Vr,B as Gr,i as Hr,y as Kr}from"./chunk-5D3QKHYQ.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-WKTO7XPO.js";import{Bc as Lt,b as $r,e as zr,h as qr,j as Fr,p as Br,yc as Mt}from"./chunk-5AOJ5ZSQ.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import{a as Lr}from"./chunk-EQABLL4S.js";import{B as I}from"./chunk-QSKJBSCI.js";import"./chunk-VM4YKTHC.js";import{e as ht}from"./chunk-7MKA3SHV.js";import{createServer as wl}from"http";var En=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}},J={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 Oe(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var ni=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function ti(t){return t instanceof ni}var On=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new ni("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(!ti(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(!ti(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})}},vn={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(",")},_n="0.3";var yn=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||_n,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=vn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function _e(t){return t.user?.userName||"unknown"}var kn="a2a-protocol.org",An="type.googleapis.com/google.rpc.ErrorInfo",si=Symbol.for("@a2a-js/sdk.A2AError"),Ft=class oi extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(si in e))return!1;if(this===oi)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":An,reason:this.reason,domain:kn,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Ft.prototype,si,{value:!0});var li=[{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"}],j=Object.freeze(Object.fromEntries(li.map(t=>[t.name,t]))),$l=Object.freeze(Object.fromEntries(li.map(t=>[t.reason,t])));function tt(t){return{[t.name]:class extends Ft{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 K=tt(j.TaskNotFoundError),ve=tt(j.TaskNotCancelableError),kt=tt(j.PushNotificationNotSupportedError),lt=tt(j.UnsupportedOperationError),di=tt(j.ContentTypeNotSupportedError),In=tt(j.InvalidAgentResponseError),ui=tt(j.ExtendedAgentCardNotConfiguredError),ci=tt(j.ExtensionSupportRequiredError),Rn=tt(j.VersionNotSupportedError),F=tt(j.RequestMalformedError),fi=Object.freeze({TaskNotFoundError:K,TaskNotCancelableError:ve,PushNotificationNotSupportedError:kt,UnsupportedOperationError:lt,ContentTypeNotSupportedError:di,InvalidAgentResponseError:In,ExtendedAgentCardNotConfiguredError:ui,ExtensionSupportRequiredError:ci,VersionNotSupportedError:Rn,RequestMalformedError:F});function ei(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 V={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},Z={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"},Cn=Object.freeze({TaskNotFoundError:V.NOT_FOUND,TaskNotCancelableError:V.BAD_REQUEST,PushNotificationNotSupportedError:V.BAD_REQUEST,UnsupportedOperationError:V.BAD_REQUEST,ContentTypeNotSupportedError:V.BAD_REQUEST,InvalidAgentResponseError:V.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:V.BAD_REQUEST,ExtensionSupportRequiredError:V.BAD_REQUEST,VersionNotSupportedError:V.BAD_REQUEST,RequestMalformedError:V.BAD_REQUEST}),zl=Object.freeze({TaskNotFoundError:Z.NOT_FOUND,TaskNotCancelableError:Z.FAILED_PRECONDITION,PushNotificationNotSupportedError:Z.FAILED_PRECONDITION,UnsupportedOperationError:Z.FAILED_PRECONDITION,ContentTypeNotSupportedError:Z.INVALID_ARGUMENT,InvalidAgentResponseError:Z.INTERNAL,ExtendedAgentCardNotConfiguredError:Z.FAILED_PRECONDITION,ExtensionSupportRequiredError:Z.FAILED_PRECONDITION,VersionNotSupportedError:Z.FAILED_PRECONDITION,RequestMalformedError:Z.INVALID_ARGUMENT});function et(t){let e=fi[t],r=Cn[t]??V.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 Un=et("TaskNotFoundError"),Jn=et("TaskNotCancelableError"),wn=et("PushNotificationNotSupportedError"),xn=et("UnsupportedOperationError"),Pn=et("ContentTypeNotSupportedError"),Dn=et("InvalidAgentResponseError"),Mn=et("ExtendedAgentCardNotConfiguredError"),Ln=et("ExtensionSupportRequiredError"),$n=et("VersionNotSupportedError"),zn=et("RequestMalformedError"),ql=Object.freeze({TaskNotFoundError:Un,TaskNotCancelableError:Jn,PushNotificationNotSupportedError:wn,UnsupportedOperationError:xn,ContentTypeNotSupportedError:Pn,InvalidAgentResponseError:Dn,ExtendedAgentCardNotConfiguredError:Mn,ExtensionSupportRequiredError:Ln,VersionNotSupportedError:$n,RequestMalformedError:zn}),M={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},hi=Object.freeze({TaskNotFoundError:M.TASK_NOT_FOUND,TaskNotCancelableError:M.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:M.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:M.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:M.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:M.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:M.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:M.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:M.VERSION_NOT_SUPPORTED,RequestMalformedError:M.INVALID_PARAMS}),Fl=Object.freeze(Object.fromEntries(Object.entries(hi).map(([t,e])=>[e,t])));function rt(t){let e=fi[t],r=hi[t]??M.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 qn=rt("TaskNotFoundError"),Fn=rt("TaskNotCancelableError"),Bn=rt("PushNotificationNotSupportedError"),Hn=rt("UnsupportedOperationError"),Kn=rt("ContentTypeNotSupportedError"),Vn=rt("InvalidAgentResponseError"),Gn=rt("ExtendedAgentCardNotConfiguredError"),Qn=rt("ExtensionSupportRequiredError"),Yn=rt("VersionNotSupportedError"),Wn=rt("RequestMalformedError"),Bl=Object.freeze({TaskNotFoundError:qn,TaskNotCancelableError:Fn,PushNotificationNotSupportedError:Bn,UnsupportedOperationError:Hn,ContentTypeNotSupportedError:Kn,InvalidAgentResponseError:Vn,ExtendedAgentCardNotConfiguredError:Gn,ExtensionSupportRequiredError:Qn,VersionNotSupportedError:Yn,RequestMalformedError:Wn});var Hl={[M.PARSE_ERROR]:"RequestMalformedError",[M.INVALID_REQUEST]:"RequestMalformedError",[M.METHOD_NOT_FOUND]:"RequestMalformedError"};function Xn(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 bn(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 Zn(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 jn(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var ri={fromJSON(t){return{id:y(t.id)?globalThis.String(t.id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Kt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>St.fromJSON(e)):[],metadata:Tt(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=Bt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Kt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>St.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Bt={fromJSON(t){return{state:y(t.state)?Xn(t.state):0,message:y(t.message)?St.fromJSON(t.message):void 0,timestamp:y(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=bn(t.state)),t.message!==void 0&&(e.message=St.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Ht={fromJSON(t){return{content:y(t.text)?{$case:"text",value:globalThis.String(t.text)}:y(t.raw)?{$case:"raw",value:Buffer.from(es(t.raw))}:y(t.url)?{$case:"url",value:globalThis.String(t.url)}:y(t.data)?{$case:"data",value:t.data}:void 0,metadata:Tt(t.metadata)?t.metadata:void 0,filename:y(t.filename)?globalThis.String(t.filename):"",mediaType:y(t.mediaType)?globalThis.String(t.mediaType):y(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=rs(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}},St={fromJSON(t){return{messageId:y(t.messageId)?globalThis.String(t.messageId):y(t.message_id)?globalThis.String(t.message_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",role:y(t.role)?Zn(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:Tt(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=jn(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Ht.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}},Kt={fromJSON(t){return{artifactId:y(t.artifactId)?globalThis.String(t.artifactId):y(t.artifact_id)?globalThis.String(t.artifact_id):"",name:y(t.name)?globalThis.String(t.name):"",description:y(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:Tt(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=>Ht.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Te={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,metadata:Tt(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=Bt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ge={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",artifact:y(t.artifact)?Kt.fromJSON(t.artifact):void 0,append:y(t.append)?globalThis.Boolean(t.append):!1,lastChunk:y(t.lastChunk)?globalThis.Boolean(t.lastChunk):y(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:Tt(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=Kt.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 ts={fromJSON(t){return{payload:y(t.task)?{$case:"task",value:ri.fromJSON(t.task)}:y(t.message)?{$case:"message",value:St.fromJSON(t.message)}:y(t.statusUpdate)?{$case:"statusUpdate",value:Te.fromJSON(t.statusUpdate)}:y(t.status_update)?{$case:"statusUpdate",value:Te.fromJSON(t.status_update)}:y(t.artifactUpdate)?{$case:"artifactUpdate",value:ge.fromJSON(t.artifactUpdate)}:y(t.artifact_update)?{$case:"artifactUpdate",value:ge.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=ri.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=St.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Te.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=ge.toJSON(t.payload.value)),e}};function es(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function rs(t){return globalThis.Buffer.from(t).toString("base64")}function Tt(t){return typeof t=="object"&&t!==null}function y(t){return t!=null}var is="1.0",pi="0.3",as="application/a2a+json",Si=50,Kl=4*1024*1024,At=[3,4,5,7],ns=[0,1,2,3,4,5,6,7,8],Ti=[6],gi=[8],ss=[...Ti,...gi];function ii(t){return"status"in t}function ai(t,e){return{tenant:t.tenant??"",owner:e(t)}}function os(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function ls(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 ye=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=ai(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ai(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}},me=new yn,ke=class{_scopedBuses;constructor(t=_e){this._scopedBuses=new ye(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??me),i=r.get(t);return i||(i=new On,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??me)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??me);r?.get(t)?.removeAllListeners(),r?.delete(t)}},$t=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&&(At.includes(t.data.status.state)||Ti.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)}},zt=new Map;function Ne(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function Ee(t,e){let i=(zt.get(t)??Promise.resolve()).then(e,e);zt.set(t,i);let a=()=>{zt.get(t)===i&&zt.delete(t)};return i.then(a,a),i}var qt=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 Ee(Ne(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await Ee(Ne(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await Ee(Ne(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Oe(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&&At.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}},ds=class{_scopedStore;constructor(t=_e){this._scopedStore=new ye(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||pi,o=a.findIndex(d=>d.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)}},us=class{serialize(t,e){return{body:JSON.stringify(ts.toJSON(t)),contentType:as}}},cs=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 us;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 d=a.map(async c=>{try{await this._dispatchNotification(t,c,i,r)}catch(m){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,m)}});await Promise.all(d)});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||pi;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 '${is}'. 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,d=new AbortController,c=setTimeout(()=>d.abort(),this.options.timeout);try{let m=this._resolveSerializer(n),{body:S,contentType:_}=m.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":_,...this._buildAuthHeaders(a)},body:S,signal:d.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)}}},mi=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new ke,a,n,o,d,c={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=d,this.keepBusAliveStates=new Set(c.keepBusAliveStates??ss),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new ds,this.pushNotificationSender=n||new cs(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new lt("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new ui;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 di(`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??[],d=new Set(e.requestedExtensions??[]),c=o.filter(f=>f.required&&!d.has(f.uri)).map(f=>f.uri);if(c.length>0)throw new ci(`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 K(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&At.includes(i.status.state))throw new lt(`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 m=r.taskId||crypto.randomUUID(),S=r.referenceTaskIds||[];if(S.length>0){a=[];for(let f of S){let T=await this.taskStore.load(f,e);T?a.push(T):console.warn(`Reference task ${f} not found.`)}}let _=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let f=new Set(o.map(T=>T.uri));e.setRequestedExtensions(e.requestedExtensions.filter(T=>f.has(T)))}let u={...r,contextId:_,taskId:m},p={...t,message:u};return new En(p,m,_,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let d of r.events()){await e.processEvent(d);try{let c=await this._mapEventToStreamResponse(d,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(d.kind==="message")c=d.data;else if(d.kind==="task")c=d.data;else{let m=e.getFinalResult();m&&("messageId"in m||"id"in m)&&(c=m)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&d.kind==="statusUpdate"&&d.data.status&&gi.includes(d.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(d){console.error(`Event processing loop failed for task ${t}:`,d),await this._handleProcessingError(d,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=fs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ei(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let d={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&&!d.history?.find(c=>c.messageId===i.messageId)&&d.history?.push(i),e.publish(J.task(d)),e.publish(J.statusUpdate({taskId:d.id,contextId:d.contextId,status:d.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=hs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ei(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let d=a().task,c=d?.id??r.taskId,m=d?.contextId??i.contextId;if(!d){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(J.task(_))}let S={taskId:c,contextId:m,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:m,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(J.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 qt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,d=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),m=new $t(c);this._runExecutor(o,c,n,d);let S=t.configuration;return i?new Promise((_,u)=>{let p=this._processEvents(o,a,m,e,{authRequiredSnapshotResolver:f=>{this._applyHistoryLengthSemantics(f,S??{}),_(f),this._continueDraining(o,p)},firstResultRejector:u});p.then(()=>{let f=a.getFinalResult();if(!f){u(new Ft("Agent execution finished without a result, and no task context found."));return}ii(f)&&this._applyHistoryLengthSemantics(f,S??{}),_(f)}).catch(u)}):new Promise((_,u)=>{this._processEvents(o,a,m,e,{firstResultResolver:p=>{ii(p)&&this._applyHistoryLengthSemantics(p,S??{}),_(p)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new lt("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new F("message.messageId is required for streaming.");let i=new qt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),d=new $t(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let m=structuredClone(t.configuration.taskPushNotificationConfig);m.taskId=n,await this.pushNotificationStore?.save(n,e,m)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let m of d.events()){c=this._advanceStreamPattern(m,c),await i.processEvent(m);let S=await this._mapEventToStreamResponse(m,e);S.payload?.$case==="task"&&this._applyHistoryLengthSemantics(S.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,S,i.getCurrentTask()),yield S}}finally{d.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new K(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??Si;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!ns.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 K(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&At.includes(a))throw new ve(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let d=new $t(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new qt(this.taskStore,e),d,e)}else{let d={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 qt(this.taskStore,e).processEvent(J.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:d,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Ft(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new ve(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`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 kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new K(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new K(`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 kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new lt("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new $t(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new K(`Task not found: ${r}`);if(n.status?.state!==void 0&&At.includes(n.status.state))throw new lt(`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:Oe(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:Oe(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 d={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(J.statusUpdate(d))}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 lt(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new lt(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new lt(`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 fs(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 hs(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 Ni=class{_scopedStore;constructor(t=_e){this._scopedStore=new ye(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=Si,pageToken:n,statusTimestampAfter:o,includeArtifacts:d=!1}=t,c=this._scopedStore.getBucket(e),m=c?Array.from(c.values()):[];if(r&&(m=m.filter(f=>f.contextId===r)),i!==void 0&&i!==0&&(m=m.filter(f=>f.status?.state===i)),o){let f=new Date(o).getTime();m=m.filter(T=>T.status?.timestamp&&new Date(T.status.timestamp).getTime()>f)}m.sort((f,T)=>{let v=f.status?.timestamp||"",k=T.status?.timestamp||"";return k!==v?k.localeCompare(v):T.id.localeCompare(f.id)});let S=m.length;if(n){let f=ls(n),T=m.findIndex(v=>(v.status?.timestamp||"")===f.timestamp&&v.id===f.id);T!==-1?m=m.slice(T+1):m=[]}let _=m.slice(0,a),u=_.map(f=>{let T=structuredClone(f);return d||(T.artifacts=[]),T}),p="";if(_.length>0&&m.length>_.length){let f=_[_.length-1];p=os(f.status?.timestamp||"",f.id)}return{tasks:u,nextPageToken:p,pageSize:a,totalSize:S}}};var be=ht(pt(),1);var Ma=ht(pt(),1),La=ht(pt(),1),nr=ht(pt(),1),sr=ht(pt(),1);import tl from"crypto";import el from"crypto";var ps=class{get isAuthenticated(){return!1}get userName(){return""}},or={noAuthentication:()=>Promise.resolve(new ps)};async function*lr(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 dr(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 ta(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 Ss(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 Ts(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Ei={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)?Y.fromJSON(t.taskPushNotificationConfig):s(t.task_push_notification_config)?Y.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=Y.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)?Qt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Wt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>W.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=Qt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Wt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>W.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Qt={fromJSON(t){return{state:s(t.state)?dr(t.state):0,message:s(t.message)?W.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=ta(t.state)),t.message!==void 0&&(e.message=W.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Yt={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(As(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=Is(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}},W={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)?Ss(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Yt.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=Ts(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Yt.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}},Wt={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=>Yt.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=>Yt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Ae={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)?Qt.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=Qt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ie={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)?Wt.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=Wt.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}},Oi={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}},Re={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}},ea={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=>Re.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>Re.fromJSON(e)):[],provider:s(t.provider)?vi.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)?_i.fromJSON(t.capabilities):void 0,securitySchemes:w(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=Ce.fromJSON(i),e),{}):w(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=Ce.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>mt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>mt.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=>ki.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Ai.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=>Re.toJSON(r))),t.provider!==void 0&&(e.provider=vi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=_i.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=Ce.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>mt.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=>ki.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Ai.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},vi={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}},_i={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=>yi.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=>yi.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},yi={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}},ki={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=>mt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>mt.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=>mt.toJSON(r))),e}},Ai={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}},Y={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)?Oi.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=Oi.toJSON(t.authentication)),e}},Ii={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}},mt={fromJSON(t){return{schemes:w(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Ii.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]=Ii.toJSON(n)}),e.schemes=i}}return e}},Ce={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Ue.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Ue.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Je.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Je.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:we.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:we.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:xe.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:xe.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Pe.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Pe.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Ue.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Je.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=we.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=xe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Pe.toJSON(t.scheme.value)),e}},Ue={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}},Je={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}},we={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?Ri.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=Ri.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},xe={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}},Pe={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Ri={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:De.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:De.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Me.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Me.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:Ci.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:Ui.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:Le.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:Le.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=De.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Me.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Ci.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=Ui.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=Le.toJSON(t.flow.value)),e}},De={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}},Me={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}},Ci={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}},Ui={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}},Le={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}},Xt={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",message:s(t.message)?W.fromJSON(t.message):void 0,configuration:s(t.configuration)?Ei.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=W.toJSON(t.message)),t.configuration!==void 0&&(e.configuration=Ei.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},gs={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}},ms={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)?dr(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=ta(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}},ra={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}},Ns={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}},Es={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}},Os={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}},vs={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}},_s={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}},ys={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},ks={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:W.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=W.toJSON(t.payload.value)),e}},Ze={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:W.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:Ae.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:Ae.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:Ie.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:Ie.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=W.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Ae.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=Ie.toJSON(t.payload.value)),e}},ia={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>Y.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=>Y.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function As(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Is(t){return globalThis.Buffer.from(t).toString("base64")}function w(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var Nt="A2A-Extensions",it="A2A-Version",Rs="1.0",yt="0.3",ur="application/json",je="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(",")},bt={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function ct(t){return`data: ${JSON.stringify(t)}
4
+ import{a as pt,b as br,c as Zr,d as jr}from"./chunk-FCZRCSNM.js";import{B as Xr,i as Qr,v as Yr,z as Wr}from"./chunk-XXTMMEVY.js";import"./chunk-57IGGFHK.js";import{A as Vr,B as Gr,i as Hr,y as Kr}from"./chunk-5D3QKHYQ.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-WKTO7XPO.js";import{Bc as Lt,b as $r,e as zr,h as qr,j as Fr,p as Br,yc as Mt}from"./chunk-5AOJ5ZSQ.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import{a as Lr}from"./chunk-CEP5W4VW.js";import{B as I}from"./chunk-QSKJBSCI.js";import"./chunk-VM4YKTHC.js";import{e as ht}from"./chunk-7MKA3SHV.js";import{createServer as wl}from"http";var En=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}},J={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 Oe(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var ni=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function ti(t){return t instanceof ni}var On=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new ni("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(!ti(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(!ti(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})}},vn={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(",")},_n="0.3";var yn=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||_n,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=vn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function _e(t){return t.user?.userName||"unknown"}var kn="a2a-protocol.org",An="type.googleapis.com/google.rpc.ErrorInfo",si=Symbol.for("@a2a-js/sdk.A2AError"),Ft=class oi extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(si in e))return!1;if(this===oi)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":An,reason:this.reason,domain:kn,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Ft.prototype,si,{value:!0});var li=[{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"}],j=Object.freeze(Object.fromEntries(li.map(t=>[t.name,t]))),$l=Object.freeze(Object.fromEntries(li.map(t=>[t.reason,t])));function tt(t){return{[t.name]:class extends Ft{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 K=tt(j.TaskNotFoundError),ve=tt(j.TaskNotCancelableError),kt=tt(j.PushNotificationNotSupportedError),lt=tt(j.UnsupportedOperationError),di=tt(j.ContentTypeNotSupportedError),In=tt(j.InvalidAgentResponseError),ui=tt(j.ExtendedAgentCardNotConfiguredError),ci=tt(j.ExtensionSupportRequiredError),Rn=tt(j.VersionNotSupportedError),F=tt(j.RequestMalformedError),fi=Object.freeze({TaskNotFoundError:K,TaskNotCancelableError:ve,PushNotificationNotSupportedError:kt,UnsupportedOperationError:lt,ContentTypeNotSupportedError:di,InvalidAgentResponseError:In,ExtendedAgentCardNotConfiguredError:ui,ExtensionSupportRequiredError:ci,VersionNotSupportedError:Rn,RequestMalformedError:F});function ei(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 V={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},Z={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"},Cn=Object.freeze({TaskNotFoundError:V.NOT_FOUND,TaskNotCancelableError:V.BAD_REQUEST,PushNotificationNotSupportedError:V.BAD_REQUEST,UnsupportedOperationError:V.BAD_REQUEST,ContentTypeNotSupportedError:V.BAD_REQUEST,InvalidAgentResponseError:V.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:V.BAD_REQUEST,ExtensionSupportRequiredError:V.BAD_REQUEST,VersionNotSupportedError:V.BAD_REQUEST,RequestMalformedError:V.BAD_REQUEST}),zl=Object.freeze({TaskNotFoundError:Z.NOT_FOUND,TaskNotCancelableError:Z.FAILED_PRECONDITION,PushNotificationNotSupportedError:Z.FAILED_PRECONDITION,UnsupportedOperationError:Z.FAILED_PRECONDITION,ContentTypeNotSupportedError:Z.INVALID_ARGUMENT,InvalidAgentResponseError:Z.INTERNAL,ExtendedAgentCardNotConfiguredError:Z.FAILED_PRECONDITION,ExtensionSupportRequiredError:Z.FAILED_PRECONDITION,VersionNotSupportedError:Z.FAILED_PRECONDITION,RequestMalformedError:Z.INVALID_ARGUMENT});function et(t){let e=fi[t],r=Cn[t]??V.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 Un=et("TaskNotFoundError"),Jn=et("TaskNotCancelableError"),wn=et("PushNotificationNotSupportedError"),xn=et("UnsupportedOperationError"),Pn=et("ContentTypeNotSupportedError"),Dn=et("InvalidAgentResponseError"),Mn=et("ExtendedAgentCardNotConfiguredError"),Ln=et("ExtensionSupportRequiredError"),$n=et("VersionNotSupportedError"),zn=et("RequestMalformedError"),ql=Object.freeze({TaskNotFoundError:Un,TaskNotCancelableError:Jn,PushNotificationNotSupportedError:wn,UnsupportedOperationError:xn,ContentTypeNotSupportedError:Pn,InvalidAgentResponseError:Dn,ExtendedAgentCardNotConfiguredError:Mn,ExtensionSupportRequiredError:Ln,VersionNotSupportedError:$n,RequestMalformedError:zn}),M={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},hi=Object.freeze({TaskNotFoundError:M.TASK_NOT_FOUND,TaskNotCancelableError:M.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:M.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:M.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:M.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:M.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:M.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:M.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:M.VERSION_NOT_SUPPORTED,RequestMalformedError:M.INVALID_PARAMS}),Fl=Object.freeze(Object.fromEntries(Object.entries(hi).map(([t,e])=>[e,t])));function rt(t){let e=fi[t],r=hi[t]??M.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 qn=rt("TaskNotFoundError"),Fn=rt("TaskNotCancelableError"),Bn=rt("PushNotificationNotSupportedError"),Hn=rt("UnsupportedOperationError"),Kn=rt("ContentTypeNotSupportedError"),Vn=rt("InvalidAgentResponseError"),Gn=rt("ExtendedAgentCardNotConfiguredError"),Qn=rt("ExtensionSupportRequiredError"),Yn=rt("VersionNotSupportedError"),Wn=rt("RequestMalformedError"),Bl=Object.freeze({TaskNotFoundError:qn,TaskNotCancelableError:Fn,PushNotificationNotSupportedError:Bn,UnsupportedOperationError:Hn,ContentTypeNotSupportedError:Kn,InvalidAgentResponseError:Vn,ExtendedAgentCardNotConfiguredError:Gn,ExtensionSupportRequiredError:Qn,VersionNotSupportedError:Yn,RequestMalformedError:Wn});var Hl={[M.PARSE_ERROR]:"RequestMalformedError",[M.INVALID_REQUEST]:"RequestMalformedError",[M.METHOD_NOT_FOUND]:"RequestMalformedError"};function Xn(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 bn(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 Zn(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 jn(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var ri={fromJSON(t){return{id:y(t.id)?globalThis.String(t.id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Kt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>St.fromJSON(e)):[],metadata:Tt(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=Bt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Kt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>St.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Bt={fromJSON(t){return{state:y(t.state)?Xn(t.state):0,message:y(t.message)?St.fromJSON(t.message):void 0,timestamp:y(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=bn(t.state)),t.message!==void 0&&(e.message=St.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Ht={fromJSON(t){return{content:y(t.text)?{$case:"text",value:globalThis.String(t.text)}:y(t.raw)?{$case:"raw",value:Buffer.from(es(t.raw))}:y(t.url)?{$case:"url",value:globalThis.String(t.url)}:y(t.data)?{$case:"data",value:t.data}:void 0,metadata:Tt(t.metadata)?t.metadata:void 0,filename:y(t.filename)?globalThis.String(t.filename):"",mediaType:y(t.mediaType)?globalThis.String(t.mediaType):y(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=rs(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}},St={fromJSON(t){return{messageId:y(t.messageId)?globalThis.String(t.messageId):y(t.message_id)?globalThis.String(t.message_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",role:y(t.role)?Zn(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:Tt(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=jn(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Ht.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}},Kt={fromJSON(t){return{artifactId:y(t.artifactId)?globalThis.String(t.artifactId):y(t.artifact_id)?globalThis.String(t.artifact_id):"",name:y(t.name)?globalThis.String(t.name):"",description:y(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:Tt(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=>Ht.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Te={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,metadata:Tt(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=Bt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ge={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",artifact:y(t.artifact)?Kt.fromJSON(t.artifact):void 0,append:y(t.append)?globalThis.Boolean(t.append):!1,lastChunk:y(t.lastChunk)?globalThis.Boolean(t.lastChunk):y(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:Tt(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=Kt.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 ts={fromJSON(t){return{payload:y(t.task)?{$case:"task",value:ri.fromJSON(t.task)}:y(t.message)?{$case:"message",value:St.fromJSON(t.message)}:y(t.statusUpdate)?{$case:"statusUpdate",value:Te.fromJSON(t.statusUpdate)}:y(t.status_update)?{$case:"statusUpdate",value:Te.fromJSON(t.status_update)}:y(t.artifactUpdate)?{$case:"artifactUpdate",value:ge.fromJSON(t.artifactUpdate)}:y(t.artifact_update)?{$case:"artifactUpdate",value:ge.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=ri.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=St.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Te.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=ge.toJSON(t.payload.value)),e}};function es(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function rs(t){return globalThis.Buffer.from(t).toString("base64")}function Tt(t){return typeof t=="object"&&t!==null}function y(t){return t!=null}var is="1.0",pi="0.3",as="application/a2a+json",Si=50,Kl=4*1024*1024,At=[3,4,5,7],ns=[0,1,2,3,4,5,6,7,8],Ti=[6],gi=[8],ss=[...Ti,...gi];function ii(t){return"status"in t}function ai(t,e){return{tenant:t.tenant??"",owner:e(t)}}function os(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function ls(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 ye=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=ai(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ai(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}},me=new yn,ke=class{_scopedBuses;constructor(t=_e){this._scopedBuses=new ye(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??me),i=r.get(t);return i||(i=new On,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??me)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??me);r?.get(t)?.removeAllListeners(),r?.delete(t)}},$t=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&&(At.includes(t.data.status.state)||Ti.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)}},zt=new Map;function Ne(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function Ee(t,e){let i=(zt.get(t)??Promise.resolve()).then(e,e);zt.set(t,i);let a=()=>{zt.get(t)===i&&zt.delete(t)};return i.then(a,a),i}var qt=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 Ee(Ne(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await Ee(Ne(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await Ee(Ne(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Oe(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&&At.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}},ds=class{_scopedStore;constructor(t=_e){this._scopedStore=new ye(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||pi,o=a.findIndex(d=>d.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)}},us=class{serialize(t,e){return{body:JSON.stringify(ts.toJSON(t)),contentType:as}}},cs=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 us;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 d=a.map(async c=>{try{await this._dispatchNotification(t,c,i,r)}catch(m){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,m)}});await Promise.all(d)});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||pi;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 '${is}'. 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,d=new AbortController,c=setTimeout(()=>d.abort(),this.options.timeout);try{let m=this._resolveSerializer(n),{body:S,contentType:_}=m.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":_,...this._buildAuthHeaders(a)},body:S,signal:d.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)}}},mi=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new ke,a,n,o,d,c={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=d,this.keepBusAliveStates=new Set(c.keepBusAliveStates??ss),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new ds,this.pushNotificationSender=n||new cs(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new lt("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new ui;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 di(`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??[],d=new Set(e.requestedExtensions??[]),c=o.filter(f=>f.required&&!d.has(f.uri)).map(f=>f.uri);if(c.length>0)throw new ci(`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 K(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&At.includes(i.status.state))throw new lt(`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 m=r.taskId||crypto.randomUUID(),S=r.referenceTaskIds||[];if(S.length>0){a=[];for(let f of S){let T=await this.taskStore.load(f,e);T?a.push(T):console.warn(`Reference task ${f} not found.`)}}let _=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let f=new Set(o.map(T=>T.uri));e.setRequestedExtensions(e.requestedExtensions.filter(T=>f.has(T)))}let u={...r,contextId:_,taskId:m},p={...t,message:u};return new En(p,m,_,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let d of r.events()){await e.processEvent(d);try{let c=await this._mapEventToStreamResponse(d,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(d.kind==="message")c=d.data;else if(d.kind==="task")c=d.data;else{let m=e.getFinalResult();m&&("messageId"in m||"id"in m)&&(c=m)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&d.kind==="statusUpdate"&&d.data.status&&gi.includes(d.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(d){console.error(`Event processing loop failed for task ${t}:`,d),await this._handleProcessingError(d,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=fs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ei(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let d={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&&!d.history?.find(c=>c.messageId===i.messageId)&&d.history?.push(i),e.publish(J.task(d)),e.publish(J.statusUpdate({taskId:d.id,contextId:d.contextId,status:d.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=hs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ei(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let d=a().task,c=d?.id??r.taskId,m=d?.contextId??i.contextId;if(!d){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(J.task(_))}let S={taskId:c,contextId:m,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:m,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(J.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 qt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,d=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),m=new $t(c);this._runExecutor(o,c,n,d);let S=t.configuration;return i?new Promise((_,u)=>{let p=this._processEvents(o,a,m,e,{authRequiredSnapshotResolver:f=>{this._applyHistoryLengthSemantics(f,S??{}),_(f),this._continueDraining(o,p)},firstResultRejector:u});p.then(()=>{let f=a.getFinalResult();if(!f){u(new Ft("Agent execution finished without a result, and no task context found."));return}ii(f)&&this._applyHistoryLengthSemantics(f,S??{}),_(f)}).catch(u)}):new Promise((_,u)=>{this._processEvents(o,a,m,e,{firstResultResolver:p=>{ii(p)&&this._applyHistoryLengthSemantics(p,S??{}),_(p)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new lt("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new F("message.messageId is required for streaming.");let i=new qt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),d=new $t(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let m=structuredClone(t.configuration.taskPushNotificationConfig);m.taskId=n,await this.pushNotificationStore?.save(n,e,m)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let m of d.events()){c=this._advanceStreamPattern(m,c),await i.processEvent(m);let S=await this._mapEventToStreamResponse(m,e);S.payload?.$case==="task"&&this._applyHistoryLengthSemantics(S.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,S,i.getCurrentTask()),yield S}}finally{d.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new K(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??Si;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!ns.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 K(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&At.includes(a))throw new ve(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let d=new $t(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new qt(this.taskStore,e),d,e)}else{let d={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 qt(this.taskStore,e).processEvent(J.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:d,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Ft(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new ve(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`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 kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new K(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new K(`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 kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new kt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new K(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new lt("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new $t(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new K(`Task not found: ${r}`);if(n.status?.state!==void 0&&At.includes(n.status.state))throw new lt(`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:Oe(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:Oe(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 d={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(J.statusUpdate(d))}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 lt(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new lt(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new lt(`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 fs(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 hs(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 Ni=class{_scopedStore;constructor(t=_e){this._scopedStore=new ye(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=Si,pageToken:n,statusTimestampAfter:o,includeArtifacts:d=!1}=t,c=this._scopedStore.getBucket(e),m=c?Array.from(c.values()):[];if(r&&(m=m.filter(f=>f.contextId===r)),i!==void 0&&i!==0&&(m=m.filter(f=>f.status?.state===i)),o){let f=new Date(o).getTime();m=m.filter(T=>T.status?.timestamp&&new Date(T.status.timestamp).getTime()>f)}m.sort((f,T)=>{let v=f.status?.timestamp||"",k=T.status?.timestamp||"";return k!==v?k.localeCompare(v):T.id.localeCompare(f.id)});let S=m.length;if(n){let f=ls(n),T=m.findIndex(v=>(v.status?.timestamp||"")===f.timestamp&&v.id===f.id);T!==-1?m=m.slice(T+1):m=[]}let _=m.slice(0,a),u=_.map(f=>{let T=structuredClone(f);return d||(T.artifacts=[]),T}),p="";if(_.length>0&&m.length>_.length){let f=_[_.length-1];p=os(f.status?.timestamp||"",f.id)}return{tasks:u,nextPageToken:p,pageSize:a,totalSize:S}}};var be=ht(pt(),1);var Ma=ht(pt(),1),La=ht(pt(),1),nr=ht(pt(),1),sr=ht(pt(),1);import tl from"crypto";import el from"crypto";var ps=class{get isAuthenticated(){return!1}get userName(){return""}},or={noAuthentication:()=>Promise.resolve(new ps)};async function*lr(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 dr(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 ta(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 Ss(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 Ts(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Ei={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)?Y.fromJSON(t.taskPushNotificationConfig):s(t.task_push_notification_config)?Y.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=Y.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)?Qt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Wt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>W.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=Qt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Wt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>W.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Qt={fromJSON(t){return{state:s(t.state)?dr(t.state):0,message:s(t.message)?W.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=ta(t.state)),t.message!==void 0&&(e.message=W.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Yt={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(As(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=Is(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}},W={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)?Ss(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Yt.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=Ts(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Yt.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}},Wt={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=>Yt.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=>Yt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Ae={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)?Qt.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=Qt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ie={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)?Wt.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=Wt.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}},Oi={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}},Re={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}},ea={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=>Re.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>Re.fromJSON(e)):[],provider:s(t.provider)?vi.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)?_i.fromJSON(t.capabilities):void 0,securitySchemes:w(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=Ce.fromJSON(i),e),{}):w(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=Ce.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>mt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>mt.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=>ki.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Ai.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=>Re.toJSON(r))),t.provider!==void 0&&(e.provider=vi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=_i.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=Ce.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>mt.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=>ki.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Ai.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},vi={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}},_i={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=>yi.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=>yi.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},yi={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}},ki={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=>mt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>mt.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=>mt.toJSON(r))),e}},Ai={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}},Y={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)?Oi.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=Oi.toJSON(t.authentication)),e}},Ii={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}},mt={fromJSON(t){return{schemes:w(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Ii.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]=Ii.toJSON(n)}),e.schemes=i}}return e}},Ce={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Ue.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Ue.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Je.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Je.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:we.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:we.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:xe.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:xe.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Pe.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Pe.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Ue.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Je.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=we.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=xe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Pe.toJSON(t.scheme.value)),e}},Ue={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}},Je={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}},we={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?Ri.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=Ri.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},xe={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}},Pe={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Ri={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:De.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:De.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Me.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Me.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:Ci.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:Ui.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:Le.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:Le.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=De.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Me.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Ci.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=Ui.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=Le.toJSON(t.flow.value)),e}},De={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}},Me={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}},Ci={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}},Ui={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}},Le={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}},Xt={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",message:s(t.message)?W.fromJSON(t.message):void 0,configuration:s(t.configuration)?Ei.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=W.toJSON(t.message)),t.configuration!==void 0&&(e.configuration=Ei.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},gs={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}},ms={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)?dr(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=ta(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}},ra={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}},Ns={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}},Es={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}},Os={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}},vs={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}},_s={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}},ys={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},ks={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:W.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=W.toJSON(t.payload.value)),e}},Ze={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:Q.fromJSON(t.task)}:s(t.message)?{$case:"message",value:W.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:Ae.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:Ae.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:Ie.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:Ie.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=W.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Ae.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=Ie.toJSON(t.payload.value)),e}},ia={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>Y.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=>Y.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function As(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Is(t){return globalThis.Buffer.from(t).toString("base64")}function w(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var Nt="A2A-Extensions",it="A2A-Version",Rs="1.0",yt="0.3",ur="application/json",je="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(",")},bt={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function ct(t){return`data: ${JSON.stringify(t)}
5
5
 
6
6
  `}function Zt(t){return`event: error
7
7
  data: ${JSON.stringify(t)}
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __yukinoCreateRequire } from "node:module";
3
3
  const require = __yukinoCreateRequire(import.meta.url);
4
- import{d as a,e as b}from"./chunk-P6K7EQHF.js";import"./chunk-2N7OIUQW.js";import"./chunk-57IGGFHK.js";import"./chunk-5D3QKHYQ.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-WKTO7XPO.js";import"./chunk-5AOJ5ZSQ.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-EQABLL4S.js";import"./chunk-QSKJBSCI.js";import"./chunk-VM4YKTHC.js";import"./chunk-7MKA3SHV.js";export{b as RemoteServer,a as createRemoteAgent};
4
+ import{d as a,e as b}from"./chunk-FCZRCSNM.js";import"./chunk-XXTMMEVY.js";import"./chunk-57IGGFHK.js";import"./chunk-5D3QKHYQ.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-WKTO7XPO.js";import"./chunk-5AOJ5ZSQ.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-CEP5W4VW.js";import"./chunk-QSKJBSCI.js";import"./chunk-VM4YKTHC.js";import"./chunk-7MKA3SHV.js";export{b as RemoteServer,a as createRemoteAgent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yukino.js/yukino",
3
- "version": "0.0.21-dev",
3
+ "version": "0.0.21",
4
4
  "description": "Yukino is a terminal-based AI coding agent. It provides an interactive UI (terminal user interface) for conversing with large language models, executing code, manipulating files, and orchestrating multi-agent workflows, all from the command line.",
5
5
  "keywords": [
6
6
  "a2a",