@yukino.js/yukino 0.0.20 → 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.
Files changed (35) hide show
  1. package/README.md +12 -38
  2. package/dist/anthropic-LB4T3BEN.js +4 -0
  3. package/dist/browser/dist/index.html +2 -2
  4. package/dist/browser/dist/static/chunk-3HWUJ4KR.js +1 -0
  5. package/dist/browser/dist/static/{highlight-ZDY7K2CR.js → highlight-KNDEBJWF.js} +10 -10
  6. package/dist/browser/dist/static/index.css +1 -1
  7. package/dist/browser/dist/static/index.js +40 -40
  8. package/dist/{chunk-LUBMW3QT.js → chunk-57IGGFHK.js} +5 -5
  9. package/dist/{chunk-Q6322VDG.js → chunk-5AOJ5ZSQ.js} +20 -20
  10. package/dist/chunk-5D3QKHYQ.js +36 -0
  11. package/dist/{chunk-SLZKGKP5.js → chunk-CEP5W4VW.js} +1 -1
  12. package/dist/{chunk-FK5B4XFN.js → chunk-ENUOAMFA.js} +1 -1
  13. package/dist/{chunk-T3MBBXTU.js → chunk-FCZRCSNM.js} +29 -29
  14. package/dist/{chunk-D64ZLLSN.js → chunk-WKTO7XPO.js} +1 -1
  15. package/dist/{chunk-3V2Q65BE.js → chunk-XXTMMEVY.js} +197 -198
  16. package/dist/lib/{anthropic-UZXEGJN5.js → anthropic-TYBMDJP3.js} +3 -3
  17. package/dist/lib/{chunk-6RBU5LDC.js → chunk-3QGT2MSI.js} +0 -42
  18. package/dist/lib/{chunk-V3WAJBLN.js → chunk-IPKULHXR.js} +2 -2
  19. package/dist/lib/{chunk-FHJHT233.js → chunk-NIUCGP4C.js} +80 -238
  20. package/dist/lib/{chunk-2QPNVR5H.js → chunk-OPEO6D4O.js} +2 -5
  21. package/dist/lib/{chunk-Y3EO3KLE.js → chunk-ZNDE6BQM.js} +2 -2
  22. package/dist/lib/index.d.ts +616 -819
  23. package/dist/lib/index.js +666 -1441
  24. package/dist/lib/{openai-DNNUHOKV.js → openai-Z2JCYL6F.js} +3 -3
  25. package/dist/lib/{providers-NBWCB4EA.js → providers-RONNZOUT.js} +2 -2
  26. package/dist/{main-IEQSD5OX.js → main-V4RKN5MY.js} +221 -221
  27. package/dist/main.js +2 -2
  28. package/dist/{openai-SRAHPUVF.js → openai-UOCUBMFA.js} +1 -1
  29. package/dist/{providers-ETXXDQGM.js → providers-NYJNJO7D.js} +1 -1
  30. package/dist/server-7QJH5UCM.js +14 -0
  31. package/dist/{server-N2WSM46R.js → server-XFB4HEJU.js} +1 -1
  32. package/package.json +4 -4
  33. package/dist/anthropic-XJSWCDJD.js +0 -4
  34. package/dist/chunk-ZZF3DILS.js +0 -38
  35. package/dist/server-HXOWUX6N.js +0 -14
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __yukinoCreateRequire } from "node:module";
3
- const require = __yukinoCreateRequire(import.meta.url);
4
- import{a as pt,b as Zr,c as jr,d as ti}from"./chunk-T3MBBXTU.js";import{B as br,i as Yr,v as Wr,z as Xr}from"./chunk-3V2Q65BE.js";import"./chunk-LUBMW3QT.js";import{Z as Kr,_ as Vr,aa as Gr,ba as Qr,i as Hr}from"./chunk-ZZF3DILS.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-D64ZLLSN.js";import{Ic as Mt,Lc as Lt,b as $r,e as zr,h as qr,j as Fr,p as Br}from"./chunk-Q6322VDG.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import{a as Lr}from"./chunk-SLZKGKP5.js";import{B as I}from"./chunk-QSKJBSCI.js";import"./chunk-VM4YKTHC.js";import{e as ht}from"./chunk-7MKA3SHV.js";import{createServer as Pl}from"http";var vn=class{request;taskId;contextId;context;task;referenceTasks;constructor(t,e,r,i,a,n){if(!t.message)throw new Error("RequestContext requires request.message to be set.");this.request=structuredClone(t),this.taskId=e,this.contextId=r,this.context=i,this.task=a,this.referenceTasks=n}get userMessage(){return this.request.message}},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 si=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function ei(t){return t instanceof si}var _n=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new si("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(!ei(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(!ei(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})}},yn={createFrom:(t,e)=>t?.includes(e)?t:[...t??[],e],parseServiceParameter:t=>{if(!t)return[];let e=new Set(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));return Array.from(e)},toServiceParameter:t=>t.join(",")},kn="0.3";var An=class{_requestedExtensions;_user;_requestedVersion;_tenant;_activatedExtensions;_state;constructor(t){this._requestedExtensions=t?.requestedExtensions,this._user=t?.user,this._tenant=t?.tenant,this._requestedVersion=t?.requestedVersion||kn,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=yn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function _e(t){return t.user?.userName||"unknown"}var In="a2a-protocol.org",Rn="type.googleapis.com/google.rpc.ErrorInfo",oi=Symbol.for("@a2a-js/sdk.A2AError"),Ft=class li extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(oi in e))return!1;if(this===li)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":Rn,reason:this.reason,domain:In,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Ft.prototype,oi,{value:!0});var di=[{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(di.map(t=>[t.name,t]))),ql=Object.freeze(Object.fromEntries(di.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),ui=tt(j.ContentTypeNotSupportedError),Cn=tt(j.InvalidAgentResponseError),ci=tt(j.ExtendedAgentCardNotConfiguredError),fi=tt(j.ExtensionSupportRequiredError),Un=tt(j.VersionNotSupportedError),F=tt(j.RequestMalformedError),hi=Object.freeze({TaskNotFoundError:K,TaskNotCancelableError:ve,PushNotificationNotSupportedError:kt,UnsupportedOperationError:lt,ContentTypeNotSupportedError:ui,InvalidAgentResponseError:Cn,ExtendedAgentCardNotConfiguredError:ci,ExtensionSupportRequiredError:fi,VersionNotSupportedError:Un,RequestMalformedError:F});function ri(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"},Jn=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}),Fl=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=hi[t],r=Jn[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 wn=et("TaskNotFoundError"),xn=et("TaskNotCancelableError"),Pn=et("PushNotificationNotSupportedError"),Dn=et("UnsupportedOperationError"),Mn=et("ContentTypeNotSupportedError"),Ln=et("InvalidAgentResponseError"),$n=et("ExtendedAgentCardNotConfiguredError"),zn=et("ExtensionSupportRequiredError"),qn=et("VersionNotSupportedError"),Fn=et("RequestMalformedError"),Bl=Object.freeze({TaskNotFoundError:wn,TaskNotCancelableError:xn,PushNotificationNotSupportedError:Pn,UnsupportedOperationError:Dn,ContentTypeNotSupportedError:Mn,InvalidAgentResponseError:Ln,ExtendedAgentCardNotConfiguredError:$n,ExtensionSupportRequiredError:zn,VersionNotSupportedError:qn,RequestMalformedError:Fn}),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},pi=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}),Hl=Object.freeze(Object.fromEntries(Object.entries(pi).map(([t,e])=>[e,t])));function rt(t){let e=hi[t],r=pi[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 Bn=rt("TaskNotFoundError"),Hn=rt("TaskNotCancelableError"),Kn=rt("PushNotificationNotSupportedError"),Vn=rt("UnsupportedOperationError"),Gn=rt("ContentTypeNotSupportedError"),Qn=rt("InvalidAgentResponseError"),Yn=rt("ExtendedAgentCardNotConfiguredError"),Wn=rt("ExtensionSupportRequiredError"),Xn=rt("VersionNotSupportedError"),bn=rt("RequestMalformedError"),Kl=Object.freeze({TaskNotFoundError:Bn,TaskNotCancelableError:Hn,PushNotificationNotSupportedError:Kn,UnsupportedOperationError:Vn,ContentTypeNotSupportedError:Gn,InvalidAgentResponseError:Qn,ExtendedAgentCardNotConfiguredError:Yn,ExtensionSupportRequiredError:Wn,VersionNotSupportedError:Xn,RequestMalformedError:bn});var Vl={[M.PARSE_ERROR]:"RequestMalformedError",[M.INVALID_REQUEST]:"RequestMalformedError",[M.METHOD_NOT_FOUND]:"RequestMalformedError"};function Zn(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 jn(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 ts(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 es(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var ii={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)?Zn(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=jn(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(is(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=as(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)?ts(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=es(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 rs={fromJSON(t){return{payload:y(t.task)?{$case:"task",value:ii.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=ii.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 is(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function as(t){return globalThis.Buffer.from(t).toString("base64")}function Tt(t){return typeof t=="object"&&t!==null}function y(t){return t!=null}var ns="1.0",Si="0.3",ss="application/a2a+json",Ti=50,Gl=4*1024*1024,At=[3,4,5,7],os=[0,1,2,3,4,5,6,7,8],gi=[6],mi=[8],ls=[...gi,...mi];function ai(t){return"status"in t}function ni(t,e){return{tenant:t.tenant??"",owner:e(t)}}function ds(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function us(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}=ni(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ni(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 An,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 _n,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)||gi.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}},cs=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||Si,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)}},fs=class{serialize(t,e){return{body:JSON.stringify(rs.toJSON(t)),contentType:ss}}},hs=class{pushNotificationStore;notificationChain;options;serializers;fallbackSerializer;warnedMissingSerializers=new Set;constructor(t,e={}){this.pushNotificationStore=t,this.notificationChain=new Map,this.options={timeout:e.timeout??5e3,tokenHeaderName:e.tokenHeaderName??"X-A2A-Notification-Token"};let r=new fs;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||Si;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 '${ns}'. 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)}}},Ni=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??ls),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new cs,this.pushNotificationSender=n||new hs(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new lt("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new ci;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 ui(`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 fi(`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 vn(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&&mi.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=ps(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ri(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=Ss(e);this.agentExecutor.execute(r,e).catch(n=>{let o=ri(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}ai(f)&&this._applyHistoryLengthSemantics(f,S??{}),_(f)}).catch(u)}):new Promise((_,u)=>{this._processEvents(o,a,m,e,{firstResultResolver:p=>{ai(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??Ti;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!os.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 ps(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 Ss(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 Ei=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=Ti,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=us(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=ds(f.status?.timestamp||"",f.id)}return{tasks:u,nextPageToken:p,pageSize:a,totalSize:S}}};var be=ht(pt(),1);var La=ht(pt(),1),$a=ht(pt(),1),nr=ht(pt(),1),sr=ht(pt(),1);import rl from"crypto";import il from"crypto";var Ts=class{get isAuthenticated(){return!1}get userName(){return""}},or={noAuthentication:()=>Promise.resolve(new Ts)};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 ea(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 gs(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 ms(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Oi={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=ea(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(Rs(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=Cs(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)?gs(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=ms(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}},vi={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}},ra={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)?_i.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)?yi.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=>Ai.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Ii.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=_i.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=yi.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=>Ai.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Ii.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},_i={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}},yi={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=>ki.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=>ki.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},ki={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}},Ai={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}},Ii={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)?vi.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=vi.toJSON(t.authentication)),e}},Ri={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]=Ri.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]=Ri.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)?Ci.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=Ci.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}},Ci={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:Ui.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:Ji.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=Ui.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=Ji.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}},Ui={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}},Ji={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)?Oi.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=Oi.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ns={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}},Es={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=ea(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}},ia={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}},Os={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:w(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.metadata!==void 0&&(e.metadata=t.metadata),e}},vs={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},_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):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},ys={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),e}},ks={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):0,pageToken:s(t.pageToken)?globalThis.String(t.pageToken):s(t.page_token)?globalThis.String(t.page_token):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.pageSize!==0&&(e.pageSize=Math.round(t.pageSize)),t.pageToken!==""&&(e.pageToken=t.pageToken),e}},As={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},Is={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}},aa={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 Rs(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Cs(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",Us="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
-
6
- `}function Zt(t){return`event: error
7
- data: ${JSON.stringify(t)}
8
-
9
- `}var dd=4*1024*1024;function na(t,e){let r=ia.toJSON(t),{tasks:i,nextPageToken:a,pageSize:n,totalSize:o,...d}=r,c=i??[];return{tasks:e?.includeArtifacts?c.map(Js):c,nextPageToken:a??"",pageSize:n??0,totalSize:o??0,...d}}function Js(t){if(typeof t!="object"||t===null)return t;let e=t;return e.artifacts!==void 0?e:{...e,artifacts:[]}}var ws="a2a-protocol.org",xs="type.googleapis.com/google.rpc.ErrorInfo",sa=Symbol.for("@a2a-js/sdk.A2AError"),X=class oa extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(sa in e))return!1;if(this===oa)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":xs,reason:this.reason,domain:ws,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(X.prototype,sa,{value:!0});var la=[{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"}],b=Object.freeze(Object.fromEntries(la.map(t=>[t.name,t]))),ud=Object.freeze(Object.fromEntries(la.map(t=>[t.reason,t])));function at(t){return{[t.name]:class extends X{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 da=at(b.TaskNotFoundError),ua=at(b.TaskNotCancelableError),cr=at(b.PushNotificationNotSupportedError),ca=at(b.UnsupportedOperationError),fr=at(b.ContentTypeNotSupportedError),Ps=at(b.InvalidAgentResponseError),fa=at(b.ExtendedAgentCardNotConfiguredError),Ds=at(b.ExtensionSupportRequiredError),oe=at(b.VersionNotSupportedError),L=at(b.RequestMalformedError),hr=Object.freeze({TaskNotFoundError:da,TaskNotCancelableError:ua,PushNotificationNotSupportedError:cr,UnsupportedOperationError:ca,ContentTypeNotSupportedError:fr,InvalidAgentResponseError:Ps,ExtendedAgentCardNotConfiguredError:fa,ExtensionSupportRequiredError:Ds,VersionNotSupportedError:oe,RequestMalformedError:L}),O={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},P={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"},ha=Object.freeze({TaskNotFoundError:O.NOT_FOUND,TaskNotCancelableError:O.BAD_REQUEST,PushNotificationNotSupportedError:O.BAD_REQUEST,UnsupportedOperationError:O.BAD_REQUEST,ContentTypeNotSupportedError:O.BAD_REQUEST,InvalidAgentResponseError:O.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:O.BAD_REQUEST,ExtensionSupportRequiredError:O.BAD_REQUEST,VersionNotSupportedError:O.BAD_REQUEST,RequestMalformedError:O.BAD_REQUEST}),Ms=Object.freeze({TaskNotFoundError:P.NOT_FOUND,TaskNotCancelableError:P.FAILED_PRECONDITION,PushNotificationNotSupportedError:P.FAILED_PRECONDITION,UnsupportedOperationError:P.FAILED_PRECONDITION,ContentTypeNotSupportedError:P.INVALID_ARGUMENT,InvalidAgentResponseError:P.INTERNAL,ExtendedAgentCardNotConfiguredError:P.FAILED_PRECONDITION,ExtensionSupportRequiredError:P.FAILED_PRECONDITION,VersionNotSupportedError:P.FAILED_PRECONDITION,RequestMalformedError:P.INVALID_ARGUMENT});function Ls(t){return t instanceof X&&t.transport==="rest"}function nt(t){let e=hr[t],r=ha[t]??O.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var $s=nt("TaskNotFoundError"),zs=nt("TaskNotCancelableError"),qs=nt("PushNotificationNotSupportedError"),Fs=nt("UnsupportedOperationError"),Bs=nt("ContentTypeNotSupportedError"),Hs=nt("InvalidAgentResponseError"),Ks=nt("ExtendedAgentCardNotConfiguredError"),Vs=nt("ExtensionSupportRequiredError"),Gs=nt("VersionNotSupportedError"),Qs=nt("RequestMalformedError"),cd=Object.freeze({TaskNotFoundError:$s,TaskNotCancelableError:zs,PushNotificationNotSupportedError:qs,UnsupportedOperationError:Fs,ContentTypeNotSupportedError:Bs,InvalidAgentResponseError:Hs,ExtendedAgentCardNotConfiguredError:Ks,ExtensionSupportRequiredError:Vs,VersionNotSupportedError:Gs,RequestMalformedError:Qs});function Vt(t){return Ls(t)?t.statusCode:t instanceof X?ha[t.name]??500:O.INTERNAL_SERVER_ERROR}function Ct(t,e){let r=t instanceof Error?t.message:"An unexpected error occurred.",i=[],a=P.UNKNOWN;return t instanceof X?(i.push(t.toErrorInfo()),a=Ms[t.name]??P.UNKNOWN):e===O.NOT_FOUND?a=P.NOT_FOUND:e===O.INTERNAL_SERVER_ERROR?a=P.INTERNAL:e===O.BAD_REQUEST&&(a=P.INVALID_ARGUMENT),{error:{code:e,status:a,message:r,details:i}}}var U={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},le=Object.freeze({TaskNotFoundError:U.TASK_NOT_FOUND,TaskNotCancelableError:U.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:U.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:U.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:U.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:U.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:U.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:U.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:U.VERSION_NOT_SUPPORTED,RequestMalformedError:U.INVALID_PARAMS}),Ys=Object.freeze(Object.fromEntries(Object.entries(le).map(([t,e])=>[e,t])));function pr(t){return t instanceof X&&t.transport==="jsonrpc"}function st(t){let e=hr[t],r=le[t]??U.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var Ws=st("TaskNotFoundError"),Xs=st("TaskNotCancelableError"),bs=st("PushNotificationNotSupportedError"),Sr=st("UnsupportedOperationError"),Zs=st("ContentTypeNotSupportedError"),js=st("InvalidAgentResponseError"),to=st("ExtendedAgentCardNotConfiguredError"),eo=st("ExtensionSupportRequiredError"),ro=st("VersionNotSupportedError"),wt=st("RequestMalformedError"),io=Object.freeze({TaskNotFoundError:Ws,TaskNotCancelableError:Xs,PushNotificationNotSupportedError:bs,UnsupportedOperationError:Sr,ContentTypeNotSupportedError:Zs,InvalidAgentResponseError:js,ExtendedAgentCardNotConfiguredError:to,ExtensionSupportRequiredError:eo,VersionNotSupportedError:ro,RequestMalformedError:wt}),pa=class extends X{transport="jsonrpc";envelopeCode;data;errorResponse;constructor(t){super({message:t.error.message}),this.name="JsonRpcTransportError",this.envelopeCode=t.error.code,t.error.data!==void 0&&(this.data=t.error.data),this.errorResponse=t}};function ao(t){if(pr(t)){let r=b[t.name];return{code:t.envelopeCode,message:t.message,...r?{data:[t.toErrorInfo()]}:{}}}if(t instanceof X)return{code:le[t.name]??U.INTERNAL_ERROR,message:t.message,data:[t.toErrorInfo()]};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var fd={[U.PARSE_ERROR]:"RequestMalformedError",[U.INVALID_REQUEST]:"RequestMalformedError",[U.METHOD_NOT_FOUND]:"RequestMalformedError"},tr=class er{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw new L("Invalid request body type.");if(!this.isRequestValid(i))throw new L("Invalid JSON-RPC Request.")}catch(o){let d=er.mapToJSONRPCError(o instanceof SyntaxError?new L(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:d}}let{method:a,id:n=null}=i;try{if(a!=="GetExtendedAgentCard"&&!this.paramsAreValid(i.params))throw new L("Invalid method parameters.");let o=i.params?.tenant;if(o&&r.setTenant(o),a==="SendStreamingMessage"||a==="SubscribeToTask"){let d=i.params,c=a==="SendStreamingMessage"?this.requestHandler.sendMessageStream(Xt.fromJSON(d),r):this.requestHandler.resubscribe(ys.fromJSON(d),r);return(async function*(){for await(let S of c)yield{jsonrpc:"2.0",id:n,result:Ze.toJSON(S)}})()}else{let d;switch(a){case"SendMessage":{let c=await this.requestHandler.sendMessage(Xt.fromJSON(i.params),r);d="messageId"in c?{message:W.toJSON(c)}:{task:Q.toJSON(c)};break}case"GetTask":d=Q.toJSON(await this.requestHandler.getTask(Ns.fromJSON(i.params),r));break;case"ListTasks":{let c=Es.fromJSON(i.params);d=na(await this.requestHandler.listTasks(c,r),{includeArtifacts:c.includeArtifacts});break}case"CancelTask":d=Q.toJSON(await this.requestHandler.cancelTask(Os.fromJSON(i.params),r));break;case"CreateTaskPushNotificationConfig":{d=Y.toJSON(await this.requestHandler.createTaskPushNotificationConfig(Y.fromJSON(i.params),r));break}case"GetTaskPushNotificationConfig":d=Y.toJSON(await this.requestHandler.getTaskPushNotificationConfig(vs.fromJSON(i.params),r));break;case"DeleteTaskPushNotificationConfig":await this.requestHandler.deleteTaskPushNotificationConfig(_s.fromJSON(i.params),r),d=null;break;case"ListTaskPushNotificationConfigs":d=aa.toJSON(await this.requestHandler.listTaskPushNotificationConfigs(ks.fromJSON(i.params),r));break;case"GetExtendedAgentCard":d=ra.toJSON(await this.requestHandler.getAuthenticatedExtendedAgentCard(As.fromJSON(i.params??{}),r));break;default:return{jsonrpc:"2.0",id:n,error:{code:U.METHOD_NOT_FOUND,message:"Invalid method."}}}return{jsonrpc:"2.0",id:n,result:d}}}catch(o){return{jsonrpc:"2.0",id:n,error:er.mapToJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToJSONRPCError(e){return ao(e)}},no="0.3",so="headers",Tr=({extensions:t,user:e,headers:r,requestedVersion:i,tenant:a})=>{let n=new Map([[so,r]]);return new oo({requestedExtensions:t,user:e,state:n,requestedVersion:i,tenant:a})},oo=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||no,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=se.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function lo(t,e){let r=new Set;for(let i of t.supportedInterfaces??[])e&&i.protocolBinding!==e||i.protocolVersion&&r.add(i.protocolVersion);return r}function gr(t,e,r){let i=lo(e,r);if(!i.has(t))throw new oe(`The requested A2A protocol version '${t}' is not supported. Supported versions: ${[...i].join(", ")}`)}var Sa=yt,uo=Us;function $e(t){let e=t.trim();if(e==="")return;let r=e.split(".");if(r.length===0)return;let i=Number.parseInt(r[0],10);if(!Number.isFinite(i)||i<0)return;let a=r[1],n=a===void 0?0:Number.parseInt(a,10);if(!(!Number.isFinite(n)||n<0))return{major:i,minor:n}}function wi(t,e){return t.major!==e.major?t.major-e.major:t.minor-e.minor}function mr(t){if(!t||t.trim()==="")return!0;let e=$e(t);if(!e)return!1;let r=$e(Sa),i=$e(uo);return!r||!i?!1:wi(e,r)>=0&&wi(e,i)<0}function co(t,e,r){let i=Ys[t];return i?r===void 0?new hr[i]({message:e}):new io[i]({message:e,envelopeCode:t,data:r}):t===U.METHOD_NOT_FOUND?new Sr({message:e,envelopeCode:t,data:r}):t===U.PARSE_ERROR||t===U.INVALID_REQUEST?new wt({message:e,envelopeCode:t,data:r}):new pa({jsonrpc:"2.0",id:null,error:{code:t,message:e,data:r}})}var g=co;Object.defineProperty(g,Symbol.hasInstance,{value:t=>t instanceof X});g.parseError=(t,e)=>new wt({message:t,envelopeCode:U.PARSE_ERROR,data:e});g.invalidRequest=(t,e)=>new wt({message:t,envelopeCode:U.INVALID_REQUEST,data:e});g.methodNotFound=t=>new Sr({message:`Method not found: ${t}`,envelopeCode:U.METHOD_NOT_FOUND});g.invalidParams=(t,e)=>e===void 0?new L({message:t}):new wt({message:t,envelopeCode:U.INVALID_PARAMS,data:e});g.internalError=(t,e)=>new pa({jsonrpc:"2.0",id:null,error:{code:U.INTERNAL_ERROR,message:t,...e!==void 0?{data:e}:{}}});g.taskNotFound=t=>new da({message:`Task not found: ${t}`});g.taskNotCancelable=t=>new ua({message:`Task not cancelable: ${t}`});g.pushNotificationNotSupported=()=>new cr;g.unsupportedOperation=t=>new ca({message:`Unsupported operation: ${t}`});g.authenticatedExtendedCardNotConfigured=()=>new fa({message:"Extended card not configured."});function G(t){return t!==void 0&&t!==""?t:void 0}function Ta(t){return Object.fromEntries(Object.entries(t.schemes).map(([e,r])=>[e,[...r.list]]))}function fo(t){let e={type:"apiKey",name:t.name,in:t.location==="cookie"||t.location==="query"?t.location:"header"},r=G(t.description);return r!==void 0&&(e.description=r),e}function ho(t){let e={type:"http",scheme:t.scheme},r=G(t.description);r!==void 0&&(e.description=r);let i=G(t.bearerFormat);return i!==void 0&&(e.bearerFormat=i),e}function po(t){let e={type:"mutualTLS"},r=G(t.description);return r!==void 0&&(e.description=r),e}function So(t){if(!t.flows)throw g.invalidParams("OAuth2 security scheme missing flows");let e={type:"oauth2",flows:mo(t.flows)},r=G(t.description);r!==void 0&&(e.description=r);let i=G(t.oauth2MetadataUrl);return i!==void 0&&(e.oauth2MetadataUrl=i),e}function To(t){let e={type:"openIdConnect",openIdConnectUrl:t.openIdConnectUrl},r=G(t.description);return r!==void 0&&(e.description=r),e}function go(t){let e=t.scheme;if(!e)throw g.invalidParams("Invalid v1.0 SecurityScheme: missing inner scheme");switch(e.$case){case"apiKeySecurityScheme":return fo(e.value);case"httpAuthSecurityScheme":return ho(e.value);case"mtlsSecurityScheme":return po(e.value);case"oauth2SecurityScheme":return So(e.value);case"openIdConnectSecurityScheme":return To(e.value);default:throw g.invalidParams(`Unsupported v1.0 SecurityScheme $case: ${e.$case??"unknown"}`)}}function mo(t){let e={},r=t.flow;if(!r)return e;switch(r.$case){case"authorizationCode":{let i=r.value;e.authorizationCode={authorizationUrl:i.authorizationUrl,tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=G(i.refreshUrl);a!==void 0&&(e.authorizationCode.refreshUrl=a);break}case"clientCredentials":{let i=r.value;e.clientCredentials={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=G(i.refreshUrl);a!==void 0&&(e.clientCredentials.refreshUrl=a);break}case"implicit":{let i=r.value;e.implicit={authorizationUrl:i.authorizationUrl,scopes:{...i.scopes}};let a=G(i.refreshUrl);a!==void 0&&(e.implicit.refreshUrl=a);break}case"password":{let i=r.value;e.password={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=G(i.refreshUrl);a!==void 0&&(e.password.refreshUrl=a);break}default:break}return e}function $(t){return t===void 0?void 0:structuredClone(t)}function Et(t,e){if(!Array.isArray(t))throw g.invalidParams(`${e} is required and must be an array`);return t}function No(t){return t!==void 0&&t!==""?t:void 0}function Eo(t){return{url:t.url,transport:t.protocolBinding}}function Oo(t){return{url:t.url,organization:t.organization}}function vo(t){let e={uri:t.uri},r=No(t.description);r!==void 0&&(e.description=r),e.required=t.required;let i=$(t.params);return i!==void 0&&(e.params=i),e}function _o(t){let e={};return t.streaming!==void 0&&(e.streaming=t.streaming),t.pushNotifications!==void 0&&(e.pushNotifications=t.pushNotifications),t.extensions&&t.extensions.length>0&&(e.extensions=t.extensions.map(vo)),e}function yo(t){let e={id:t.id,name:t.name,description:t.description,tags:[...Et(t.tags,"skill.tags")]};return t.examples&&t.examples.length>0&&(e.examples=[...t.examples]),t.inputModes&&t.inputModes.length>0&&(e.inputModes=[...t.inputModes]),t.outputModes&&t.outputModes.length>0&&(e.outputModes=[...t.outputModes]),t.securityRequirements&&t.securityRequirements.length>0&&(e.security=t.securityRequirements.map(Ta)),e}function ko(t){let e={protected:t.protected,signature:t.signature},r=$(t.header);return r!==void 0&&(e.header=r),e}function Nr(t,e){let r=t.supportedInterfaces??[],i=r.filter(_=>!_.protocolVersion||mr(_.protocolVersion));if(i.length===0)throw new oe("AgentCard must have at least one interface with a protocol version in [0.3, 1.0).");let a=i[0],n=i.slice(1).map(Eo),o=t.capabilities?_o(t.capabilities):{},d=t.capabilities&&t.capabilities.extendedAgentCard!==void 0?t.capabilities.extendedAgentCard:void 0,c=t.securitySchemes&&Object.keys(t.securitySchemes).length>0?Object.fromEntries(Object.entries(t.securitySchemes).map(([_,u])=>[_,go(u)])):void 0,m=a.protocolVersion||Sa,S={name:t.name,description:t.description,version:t.version,url:a.url,preferredTransport:a.protocolBinding,protocolVersion:m,capabilities:o,defaultInputModes:[...Et(t.defaultInputModes,"agentCard.defaultInputModes")],defaultOutputModes:[...Et(t.defaultOutputModes,"agentCard.defaultOutputModes")],skills:Et(t.skills,"agentCard.skills").map(yo)};return n.length>0&&(S.additionalInterfaces=n),t.provider&&(S.provider=Oo(t.provider)),t.documentationUrl!==void 0&&t.documentationUrl!==""&&(S.documentationUrl=t.documentationUrl),t.iconUrl!==void 0&&t.iconUrl!==""&&(S.iconUrl=t.iconUrl),d!==void 0&&(S.supportsAuthenticatedExtendedCard=d),c!==void 0&&(S.securitySchemes=c),t.securityRequirements&&t.securityRequirements.length>0&&(S.security=t.securityRequirements.map(Ta)),t.signatures&&t.signatures.length>0&&(S.signatures=t.signatures.map(ko)),e?.embedV1Interfaces&&r.length>0&&(S.supportedInterfaces=structuredClone(r)),S}function ga(t){if(pr(t))return{code:t.envelopeCode,message:t.message,...t.data!==void 0?{data:t.data}:{}};if(t instanceof X)return{code:le[t.name]??U.INTERNAL_ERROR,message:t.message};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var Ao=Object.freeze({unknown:0,submitted:1,working:2,completed:3,failed:4,canceled:5,"input-required":6,rejected:7,"auth-required":8}),Io=new Map(Object.entries(Ao).map(([t,e])=>[e,t]));function Ro(t){return Io.get(t)??"unknown"}function Co(t){return t==="user"?1:t==="agent"?2:0}function Uo(t){return t===1?"user":"agent"}var rr="data_part_compat";function ma(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!Buffer.isBuffer(t)}function Jo(t){if(t===null||Array.isArray(t))return!0;let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function wo(t){if(typeof t!="object"||t===null||Array.isArray(t))throw g.invalidParams("Each part must be an object");if(t.kind==="text")return{content:{$case:"text",value:t.text},metadata:$(t.metadata),filename:"",mediaType:""};if(t.kind==="file"){let e=t.file,r=e.mimeType??"",i=e.name??"",a=$(t.metadata);if("bytes"in e)return{content:{$case:"raw",value:Buffer.from(e.bytes,"base64")},metadata:a,filename:i,mediaType:r};if("uri"in e)return{content:{$case:"url",value:e.uri},metadata:a,filename:i,mediaType:r};throw g.invalidParams("Invalid file part: missing `bytes` or `uri`")}if(t.kind==="data"){let e=$(t.metadata),r=t.data,i=e;return e!==void 0&&e[rr]===!0&&(ma(t.data)&&"value"in t.data&&(r=t.data.value),delete e[rr],i=Object.keys(e).length>0?e:void 0),{content:{$case:"data",value:r},metadata:i,filename:"",mediaType:""}}throw g.invalidParams(`Invalid v0.3 part kind: ${t.kind??"undefined"}`)}function Na(t){let e=t.content,r=$(t.metadata);if(!e)throw g.invalidParams("Invalid v1.0 part: missing content");if(e.$case==="text"){let i={kind:"text",text:e.value};return r!==void 0&&(i.metadata=r),i}if(e.$case==="raw"||e.$case==="url"){let i=t.mediaType!==""?t.mediaType:void 0,a=t.filename!==""?t.filename:void 0,n;if(e.$case==="raw"){let c={bytes:(Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value)).toString("base64")};i!==void 0&&(c.mimeType=i),a!==void 0&&(c.name=a),n=c}else{let d={uri:e.value};i!==void 0&&(d.mimeType=i),a!==void 0&&(d.name=a),n=d}let o={kind:"file",file:n};return r!==void 0&&(o.metadata=r),o}if(e.$case==="data"){let i=e.value;if(ma(i)){let a={kind:"data",data:i};return r!==void 0&&(a.metadata=r),a}if(Jo(i)){let a={value:i},n=r??{};return n[rr]=!0,{kind:"data",data:a,metadata:n}}throw g.invalidParams("Cannot translate v1 data part to v0.3: value is neither a plain object nor a wrap-eligible primitive / array / null (e.g., Symbol, function, bigint, undefined, Buffer). Primitives, arrays, and null are wrapped as { value: ... } with data_part_compat=true; all other non-plain-object values are rejected.")}throw g.invalidParams(`Invalid v1.0 part content type: ${e.$case??"unknown"}`)}function xi(t){return t==null||t===""?void 0:t}function Pi(t){return t==null||t.length===0?void 0:[...t]}function xo(t){if(typeof t!="object"||t===null)throw g.invalidParams("message must be an object");if(typeof t.messageId!="string"||t.messageId==="")throw g.invalidParams("message.messageId is required");if(t.role!=="user"&&t.role!=="agent")throw g.invalidParams('message.role must be "user" or "agent"');if(!Array.isArray(t.parts))throw g.invalidParams("message.parts must be an array");return{messageId:t.messageId,contextId:t.contextId??"",taskId:t.taskId??"",role:Co(t.role),parts:t.parts.map(wo),metadata:$(t.metadata),extensions:t.extensions?[...t.extensions]:[],referenceTaskIds:t.referenceTaskIds?[...t.referenceTaskIds]:[]}}function xt(t){let e={kind:"message",messageId:t.messageId,role:Uo(t.role),parts:Et(t.parts,"message.parts").map(Na)},r=xi(t.contextId);r!==void 0&&(e.contextId=r);let i=xi(t.taskId);i!==void 0&&(e.taskId=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=Pi(t.extensions);n!==void 0&&(e.extensions=n);let o=Pi(t.referenceTaskIds);return o!==void 0&&(e.referenceTaskIds=o),e}function ir(t){return t!==void 0&&t!==""?t:void 0}function Ea(t){return t.schemes&&t.schemes.length>1&&console.warn(`toCoreAuthenticationInfo: Lossy conversion from v0.3 PushNotificationAuthenticationInfo to v1.0 AuthenticationInfo. Multiple schemes declared (${t.schemes.join(", ")}), but only the first one ('${t.schemes[0]}') will be kept.`),{scheme:t.schemes&&t.schemes.length>0?t.schemes[0]:"",credentials:t.credentials??""}}function Po(t){let e={schemes:t.scheme!==""?[t.scheme]:[]},r=ir(t.credentials);return r!==void 0&&(e.credentials=r),e}function Do(t,e=""){return{tenant:e,taskId:"",id:t.id??"",url:t.url,token:t.token??"",authentication:t.authentication?Ea(t.authentication):void 0}}function Mo(t){let e={url:t.url},r=ir(t.id);r!==void 0&&(e.id=r);let i=ir(t.token);return i!==void 0&&(e.token=i),t.authentication&&(e.authentication=Po(t.authentication)),e}function Oa(t,e=""){return{tenant:e,taskId:t.taskId,id:t.pushNotificationConfig.id??"",url:t.pushNotificationConfig.url,token:t.pushNotificationConfig.token??"",authentication:t.pushNotificationConfig.authentication?Ea(t.pushNotificationConfig.authentication):void 0}}function Ot(t){return{taskId:t.taskId,pushNotificationConfig:Mo(t)}}function Di(t){return t==null||t===""?void 0:t}function Lo(t){return t==null||t.length===0?void 0:[...t]}function va(t){let e={artifactId:t.artifactId,parts:Et(t.parts,"artifact.parts").map(Na)},r=Di(t.name);r!==void 0&&(e.name=r);let i=Di(t.description);i!==void 0&&(e.description=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=Lo(t.extensions);return n!==void 0&&(e.extensions=n),e}var $o=new Set(["completed","canceled","failed","rejected"]);function _a(t){let e={state:Ro(t.state)};return t.message&&(e.message=xt(t.message)),t.timestamp!==void 0&&t.timestamp!==""&&(e.timestamp=t.timestamp),e}function ft(t){let e={kind:"task",id:t.id,contextId:t.contextId,status:t.status?_a(t.status):{state:"unknown"}};t.history&&t.history.length>0&&(e.history=t.history.map(xt)),t.artifacts&&t.artifacts.length>0&&(e.artifacts=t.artifacts.map(va));let r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function zo(t){let e=t.status?_a(t.status):{state:"unknown"},r={kind:"status-update",taskId:t.taskId,contextId:t.contextId,status:e,final:$o.has(e.state)},i=$(t.metadata);return i!==void 0&&(r.metadata=i),r}function qo(t){if(!t.artifact)throw g.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");let e={kind:"artifact-update",taskId:t.taskId,contextId:t.contextId,artifact:va(t.artifact),append:t.append,lastChunk:t.lastChunk},r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function Fo(t){return{acceptedOutputModes:t.acceptedOutputModes?[...t.acceptedOutputModes]:[],taskPushNotificationConfig:t.pushNotificationConfig?Do(t.pushNotificationConfig):void 0,historyLength:t.historyLength,returnImmediately:t.blocking===void 0?!0:!t.blocking}}function jt(t,e=""){return{tenant:e,message:xo(t.params.message),configuration:t.params.configuration?Fo(t.params.configuration):void 0,metadata:$(t.params.metadata)}}function ya(t,e=null){let r=t.payload;if(!r)throw g.internalError("StreamResponse missing payload");let i;switch(r.$case){case"message":i=xt(r.value);break;case"task":i=ft(r.value);break;case"statusUpdate":i=zo(r.value);break;case"artifactUpdate":i=qo(r.value);break;default:throw g.internalError("StreamResponse has unknown payload case")}return{id:e,jsonrpc:"2.0",result:i}}function Bo(t,e=""){return{tenant:e,id:t.params.id,historyLength:t.params.historyLength}}function Ho(t,e=""){return{tenant:e,id:t.params.id,metadata:$(t.params.metadata)}}function Ko(t,e=""){return{tenant:e,id:t.params.id}}function Vo(t,e=""){return Oa(t.params,e)}function Go(t,e=""){let r=t.params,i="pushNotificationConfigId"in r?r.pushNotificationConfigId:void 0;return{tenant:e,taskId:r.id,id:i??""}}function Qo(t,e=""){return{tenant:e,taskId:t.params.id,id:t.params.pushNotificationConfigId}}function Yo(t,e=""){return{tenant:e,taskId:t.params.id,pageSize:0,pageToken:""}}function Wo(t,e=null){return{id:e,jsonrpc:"2.0",result:t.configs.map(r=>Ot(r))}}function Xo(t,e=""){return{tenant:e}}var Mi=class ar{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw g.invalidRequest("Invalid request body type.");if(!this.isRequestValid(i))throw g.invalidRequest("Invalid JSON-RPC Request.")}catch(o){let d=ar.mapToLegacyJSONRPCError(o instanceof SyntaxError?g.invalidRequest(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:d}}let{method:a,id:n=null}=i;try{if(a!=="agent/getAuthenticatedExtendedCard"&&!this.paramsAreValid(i.params))throw g.invalidParams("Invalid method parameters.");if(a==="message/stream"||a==="tasks/resubscribe"){if(!(await this.requestHandler.getAgentCard()).capabilities?.streaming)throw g.unsupportedOperation(`Method ${a} requires streaming capability.`);let c=a==="message/stream"?this.requestHandler.sendMessageStream(jt(i),r):this.requestHandler.resubscribe(Ko(i),r);return(async function*(){for await(let S of c)yield ya(S,n)})()}let o;switch(a){case"message/send":{let d=await this.requestHandler.sendMessage(jt(i),r);o="messageId"in d?xt(d):ft(d);break}case"tasks/get":o=ft(await this.requestHandler.getTask(Bo(i),r));break;case"tasks/cancel":o=ft(await this.requestHandler.cancelTask(Ho(i),r));break;case"tasks/pushNotificationConfig/set":o=Ot(await this.requestHandler.createTaskPushNotificationConfig(Vo(i),r));break;case"tasks/pushNotificationConfig/get":o=Ot(await this.requestHandler.getTaskPushNotificationConfig(Go(i),r));break;case"tasks/pushNotificationConfig/list":{o=Wo(await this.requestHandler.listTaskPushNotificationConfigs(Yo(i),r),n).result;break}case"tasks/pushNotificationConfig/delete":await this.requestHandler.deleteTaskPushNotificationConfig(Qo(i),r),o=null;break;case"agent/getAuthenticatedExtendedCard":o=Nr(await this.requestHandler.getAuthenticatedExtendedAgentCard(Xo(i),r));break;default:throw g.methodNotFound(a)}return{jsonrpc:"2.0",id:n,result:o}}catch(o){return{jsonrpc:"2.0",id:n,error:ar.mapToLegacyJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToLegacyJSONRPCError(e){return ga(e)}},bo={[-32700]:O.BAD_REQUEST,[-32600]:O.BAD_REQUEST,[-32601]:O.NOT_IMPLEMENTED,[-32602]:O.BAD_REQUEST,[-32603]:O.INTERNAL_SERVER_ERROR,[-32001]:O.NOT_FOUND,[-32002]:O.BAD_REQUEST,[-32003]:O.BAD_REQUEST,[-32004]:O.BAD_REQUEST,[-32005]:O.BAD_REQUEST,[-32006]:O.INTERNAL_SERVER_ERROR,[-32007]:O.BAD_REQUEST};function Li(t){if(pr(t)){let e=bo[t.envelopeCode];if(e!==void 0)return e}return Vt(t)}function vt(t){return ga(t)}var Zo=class Gt{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e){let r=await this.requestHandler.getAuthenticatedExtendedAgentCard({tenant:e.tenant??""},e);return Nr(r)}validateMessageSendParams(e){if(!e.message)throw g.invalidParams("message is required");if(!e.message.messageId)throw g.invalidParams("message.messageId is required")}async sendMessage(e,r){this.validateMessageSendParams(e);let i=jt($i(e,"message/send"),r.tenant??""),a=await this.requestHandler.sendMessage(i,r);return"messageId"in a?xt(a):ft(a)}async sendMessageStream(e,r){await this.requireCapability("streaming"),this.validateMessageSendParams(e);let i=jt($i(e,"message/stream"),r.tenant??""),a=this.requestHandler.sendMessageStream(i,r);return Gt.translateStream(a)}async getTask(e,r,i){let a={id:e,tenant:r.tenant??""};i!==void 0&&(a.historyLength=this.parseHistoryLength(i));let n=await this.requestHandler.getTask(a,r);return ft(n)}async cancelTask(e,r){let i=await this.requestHandler.cancelTask({id:e,tenant:r.tenant??"",metadata:{}},r);return ft(i)}async resubscribe(e,r){await this.requireCapability("streaming");let i=this.requestHandler.resubscribe({id:e,tenant:r.tenant??""},r);return Gt.translateStream(i)}async setTaskPushNotificationConfig(e,r){if(await this.requireCapability("pushNotifications"),!e.taskId)throw g.invalidParams("taskId is required");if(!e.pushNotificationConfig)throw g.invalidParams("pushNotificationConfig is required");let i=Oa(e,r.tenant??""),a=await this.requestHandler.createTaskPushNotificationConfig(i,r);return Ot(a)}async listTaskPushNotificationConfigs(e,r){return(await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:r.tenant??""},r)).configs.map(a=>Ot(a))}async getTaskPushNotificationConfig(e,r,i){let a=await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i);return Ot(a)}async deleteTaskPushNotificationConfig(e,r,i){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i)}static async*translateStream(e){for await(let r of e)yield ya(r,null).result}static CAPABILITY_ERRORS={streaming:()=>g.unsupportedOperation("Agent does not support streaming"),pushNotifications:()=>g.pushNotificationNotSupported()};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw Gt.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw g.invalidParams("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw g.invalidParams("historyLength must be a valid integer");if(r<0)throw g.invalidParams("historyLength must be non-negative");return r}static mapToLegacyHTTPError(e){return vt(e)}};function $i(t,e){return{jsonrpc:"2.0",id:0,method:e,params:t}}var te="X-A2A-Extensions",Ut="application/json",ka="message/send",Aa="message/stream",Ia="tasks/get",Ra="tasks/cancel",Er="tasks/resubscribe",Ca="tasks/pushNotificationConfig/set",Ua="tasks/pushNotificationConfig/get",Ja="tasks/pushNotificationConfig/list",wa="tasks/pushNotificationConfig/delete",xa="agent/getAuthenticatedExtendedCard",Pa=Object.freeze({[ka]:"SendMessage",[Aa]:"SendStreamingMessage",[Ia]:"GetTask",[Ra]:"CancelTask",[Er]:"SubscribeToTask",[Ca]:"CreateTaskPushNotificationConfig",[Ua]:"GetTaskPushNotificationConfig",[Ja]:"ListTaskPushNotificationConfigs",[wa]:"DeleteTaskPushNotificationConfig",[xa]:"GetExtendedAgentCard"}),hd=Object.freeze(Object.fromEntries(Object.entries(Pa).map(([t,e])=>[e,t]))),Da=Object.freeze({[ka]:"SendMessage",[Aa]:"SendStreamingMessage",[Ia]:"GetTask",[Ra]:"CancelTask",[Er]:"TaskSubscription",[Ca]:"CreateTaskPushNotificationConfig",[Ua]:"GetTaskPushNotificationConfig",[Ja]:"ListTaskPushNotificationConfig",[wa]:"DeleteTaskPushNotificationConfig",[xa]:"GetAgentCard"}),pd=Object.freeze(Object.fromEntries(Object.entries(Da).map(([t,e])=>[e,t]))),jo=Object.freeze(Object.fromEntries(Object.entries(Da).map(([t,e])=>[e,Pa[t]]))),Sd=Object.freeze(Object.fromEntries(Object.entries(jo).map(([t,e])=>[e,t])));function Ma(t){let e=new tr(t.requestHandler),r=t.legacyCompat?.enabled?new Mi(t.requestHandler):void 0,i=be.default.Router();return i.use(tl),i.use(be.default.json(),el),i.post("/",async(a,n)=>{let o=r!==void 0&&(a.header(it)||yt)===yt,d=o?Mi.mapToLegacyJSONRPCError:tr.mapToJSONRPCError;try{let c=await t.userBuilder(a),m=a.header(it)||void 0,S=o?a.header(te)??a.header(Nt):a.header(Nt),u=(t.contextBuilder??Tr)({extensions:se.parseServiceParameter(S),user:c,headers:a.headers,requestedVersion:m}),p=await t.requestHandler.getAgentCard();gr(u.requestedVersion,p,"JSONRPC");let T=await(o?r:e).handle(a.body,u);if(u.activatedExtensions&&n.setHeader(o?te:Nt,Array.from(u.activatedExtensions)),typeof T?.[Symbol.asyncIterator]=="function"){let v=T;if(o&&a.body?.method===Er){Object.entries(bt).forEach(([N,A])=>{n.setHeader(N,A)}),n.flushHeaders();try{for await(let N of v)n.write(ct(N))}catch(N){console.error(`Error during SSE streaming (request ${a.body?.id}):`,N);let A={jsonrpc:"2.0",id:a.body?.id||null,error:d(N)};n.writableEnded||n.write(Zt(A))}finally{n.writableEnded||n.end()}return}let h=v[Symbol.asyncIterator](),E;try{E=await h.next()}catch(N){console.error(`Pre-stream error for request ${a.body?.id}:`,N);let A={jsonrpc:"2.0",id:a.body?.id||null,error:d(N)};n.status(200).json(A);return}Object.entries(bt).forEach(([N,A])=>{n.setHeader(N,A)}),n.flushHeaders();try{E.done||n.write(ct(E.value));for await(let N of lr(h))n.write(ct(N))}catch(N){console.error(`Error during SSE streaming (request ${a.body?.id}):`,N);let A={jsonrpc:"2.0",id:a.body?.id||null,error:d(N)};n.headersSent?n.write(Zt(A)):n.status(500).json(A)}finally{n.writableEnded||n.end()}}else{let v=T;n.status(200).json(v)}}catch(c){console.error("Unhandled error in JSON-RPC POST handler:",c);let m=d(c),S={jsonrpc:"2.0",id:a.body?.id||null,error:m};if(n.headersSent)n.writableEnded||n.end();else{let _=m.code===U.INTERNAL_ERROR;n.status(_?500:200).json(S)}}}),i}var tl=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}if(i.split(";",1)[0].trim().toLowerCase()===ur){r();return}let n={jsonrpc:"2.0",id:null,error:tr.mapToJSONRPCError(new fr(`Unsupported Content-Type "${i}"; expected application/json.`))};e.status(200).json(n)},el=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t){let a={jsonrpc:"2.0",id:null,error:{code:U.PARSE_ERROR,message:"Invalid JSON payload."}};return r.status(200).json(a)}i(t)};function al(t){return`W/"${il.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function nl(t){let e=$a.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return e.use((a,n,o)=>{let d=a.header(it)||yt;mr(d)?o():o("router")}),e.get("/",async(a,n)=>{try{let o=await i(),d;try{d=Nr(o,{embedV1Interfaces:!0})}catch(S){if(S instanceof oe){n.append("Vary",it),n.status(O.BAD_REQUEST).setHeader("Content-Type",Ut).json(vt(S));return}throw S}let c=JSON.stringify(d),m=al(c);if(n.setHeader("ETag",m),n.append("Vary",it),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type",Ut),n.status(O.OK).send(c)}catch(o){console.error("Error fetching legacy agent card:",o),n.append("Vary",it),n.status(500).setHeader("Content-Type",Ut).json({error:"Failed to retrieve agent card"})}}),e}function sl(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELLED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function ol(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELLED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function ll(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 dl(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var zi={fromJSON(t){return{acceptedOutputModes:globalThis.Array.isArray(t?.acceptedOutputModes)?t.acceptedOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.accepted_output_modes)?t.accepted_output_modes.map(e=>globalThis.String(e)):[],pushNotification:l(t.pushNotification)?_t.fromJSON(t.pushNotification):l(t.push_notification)?_t.fromJSON(t.push_notification):void 0,historyLength:l(t.historyLength)?globalThis.Number(t.historyLength):l(t.history_length)?globalThis.Number(t.history_length):0,blocking:l(t.blocking)?globalThis.Boolean(t.blocking):!1}},toJSON(t){let e={};return t.acceptedOutputModes?.length&&(e.acceptedOutputModes=t.acceptedOutputModes),t.pushNotification!==void 0&&(e.pushNotification=_t.toJSON(t.pushNotification)),t.historyLength!==0&&(e.historyLength=Math.round(t.historyLength)),t.blocking!==!1&&(e.blocking=t.blocking),e}},Jt={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",status:l(t.status)?ee.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ie.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>z.fromJSON(e)):[],metadata:x(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=ee.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ie.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>z.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ee={fromJSON(t){return{state:l(t.state)?sl(t.state):0,update:l(t.message)?z.fromJSON(t.message):l(t.update)?z.fromJSON(t.update):void 0,timestamp:l(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=ol(t.state)),t.update!==void 0&&(e.message=z.toJSON(t.update)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},re={fromJSON(t){return{part:l(t.text)?{$case:"text",value:globalThis.String(t.text)}:l(t.file)?{$case:"file",value:qi.fromJSON(t.file)}:l(t.data)?{$case:"data",value:Fi.fromJSON(t.data)}:void 0}},toJSON(t){let e={};return t.part?.$case==="text"?e.text=t.part.value:t.part?.$case==="file"?e.file=qi.toJSON(t.part.value):t.part?.$case==="data"&&(e.data=Fi.toJSON(t.part.value)),e}},qi={fromJSON(t){return{file:l(t.fileWithUri)?{$case:"fileWithUri",value:globalThis.String(t.fileWithUri)}:l(t.file_with_uri)?{$case:"fileWithUri",value:globalThis.String(t.file_with_uri)}:l(t.fileWithBytes)?{$case:"fileWithBytes",value:Buffer.from(Zi(t.fileWithBytes))}:l(t.file_with_bytes)?{$case:"fileWithBytes",value:Buffer.from(Zi(t.file_with_bytes))}:void 0,mimeType:l(t.mimeType)?globalThis.String(t.mimeType):l(t.mime_type)?globalThis.String(t.mime_type):""}},toJSON(t){let e={};return t.file?.$case==="fileWithUri"?e.fileWithUri=t.file.value:t.file?.$case==="fileWithBytes"&&(e.fileWithBytes=Sl(t.file.value)),t.mimeType!==""&&(e.mimeType=t.mimeType),e}},Fi={fromJSON(t){return{data:x(t.data)?t.data:void 0}},toJSON(t){let e={};return t.data!==void 0&&(e.data=t.data),e}},z={fromJSON(t){return{messageId:l(t.messageId)?globalThis.String(t.messageId):l(t.message_id)?globalThis.String(t.message_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",role:l(t.role)?ll(t.role):0,content:globalThis.Array.isArray(t?.content)?t.content.map(e=>re.fromJSON(e)):[],metadata:x(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=dl(t.role)),t.content?.length&&(e.content=t.content.map(r=>re.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ie={fromJSON(t){return{artifactId:l(t.artifactId)?globalThis.String(t.artifactId):l(t.artifact_id)?globalThis.String(t.artifact_id):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>re.fromJSON(e)):[],metadata:x(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=>re.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ze={fromJSON(t){return{taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",status:l(t.status)?ee.fromJSON(t.status):void 0,final:l(t.final)?globalThis.Boolean(t.final):!1,metadata:x(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=ee.toJSON(t.status)),t.final!==!1&&(e.final=t.final),t.metadata!==void 0&&(e.metadata=t.metadata),e}},qe={fromJSON(t){return{taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",artifact:l(t.artifact)?ie.fromJSON(t.artifact):void 0,append:l(t.append)?globalThis.Boolean(t.append):!1,lastChunk:l(t.lastChunk)?globalThis.Boolean(t.lastChunk):l(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:x(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=ie.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}},_t={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",url:l(t.url)?globalThis.String(t.url):"",token:l(t.token)?globalThis.String(t.token):"",authentication:l(t.authentication)?Bi.fromJSON(t.authentication):void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.url!==""&&(e.url=t.url),t.token!==""&&(e.token=t.token),t.authentication!==void 0&&(e.authentication=Bi.toJSON(t.authentication)),e}},Bi={fromJSON(t){return{schemes:globalThis.Array.isArray(t?.schemes)?t.schemes.map(e=>globalThis.String(e)):[],credentials:l(t.credentials)?globalThis.String(t.credentials):""}},toJSON(t){let e={};return t.schemes?.length&&(e.schemes=t.schemes),t.credentials!==""&&(e.credentials=t.credentials),e}},Fe={fromJSON(t){return{url:l(t.url)?globalThis.String(t.url):"",transport:l(t.transport)?globalThis.String(t.transport):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.transport!==""&&(e.transport=t.transport),e}},ul={fromJSON(t){return{protocolVersion:l(t.protocolVersion)?globalThis.String(t.protocolVersion):l(t.protocol_version)?globalThis.String(t.protocol_version):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",url:l(t.url)?globalThis.String(t.url):"",preferredTransport:l(t.preferredTransport)?globalThis.String(t.preferredTransport):l(t.preferred_transport)?globalThis.String(t.preferred_transport):"",additionalInterfaces:globalThis.Array.isArray(t?.additionalInterfaces)?t.additionalInterfaces.map(e=>Fe.fromJSON(e)):globalThis.Array.isArray(t?.additional_interfaces)?t.additional_interfaces.map(e=>Fe.fromJSON(e)):[],provider:l(t.provider)?Hi.fromJSON(t.provider):void 0,version:l(t.version)?globalThis.String(t.version):"",documentationUrl:l(t.documentationUrl)?globalThis.String(t.documentationUrl):l(t.documentation_url)?globalThis.String(t.documentation_url):"",capabilities:l(t.capabilities)?Ki.fromJSON(t.capabilities):void 0,securitySchemes:x(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=Be.fromJSON(i),e),{}):x(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=Be.fromJSON(i),e),{}):{},security:globalThis.Array.isArray(t?.security)?t.security.map(e=>ne.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=>Gi.fromJSON(e)):[],supportsAuthenticatedExtendedCard:l(t.supportsAuthenticatedExtendedCard)?globalThis.Boolean(t.supportsAuthenticatedExtendedCard):l(t.supports_authenticated_extended_card)?globalThis.Boolean(t.supports_authenticated_extended_card):!1,signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Qi.fromJSON(e)):[]}},toJSON(t){let e={};if(t.protocolVersion!==""&&(e.protocolVersion=t.protocolVersion),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.url!==""&&(e.url=t.url),t.preferredTransport!==""&&(e.preferredTransport=t.preferredTransport),t.additionalInterfaces?.length&&(e.additionalInterfaces=t.additionalInterfaces.map(r=>Fe.toJSON(r))),t.provider!==void 0&&(e.provider=Hi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==""&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Ki.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);r.length>0&&(e.securitySchemes={},r.forEach(([i,a])=>{e.securitySchemes[i]=Be.toJSON(a)}))}return t.security?.length&&(e.security=t.security.map(r=>ne.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=>Gi.toJSON(r))),t.supportsAuthenticatedExtendedCard!==!1&&(e.supportsAuthenticatedExtendedCard=t.supportsAuthenticatedExtendedCard),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Qi.toJSON(r))),e}},Hi={fromJSON(t){return{url:l(t.url)?globalThis.String(t.url):"",organization:l(t.organization)?globalThis.String(t.organization):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.organization!==""&&(e.organization=t.organization),e}},Ki={fromJSON(t){return{streaming:l(t.streaming)?globalThis.Boolean(t.streaming):!1,pushNotifications:l(t.pushNotifications)?globalThis.Boolean(t.pushNotifications):l(t.push_notifications)?globalThis.Boolean(t.push_notifications):!1,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>Vi.fromJSON(e)):[]}},toJSON(t){let e={};return t.streaming!==!1&&(e.streaming=t.streaming),t.pushNotifications!==!1&&(e.pushNotifications=t.pushNotifications),t.extensions?.length&&(e.extensions=t.extensions.map(r=>Vi.toJSON(r))),e}},Vi={fromJSON(t){return{uri:l(t.uri)?globalThis.String(t.uri):"",description:l(t.description)?globalThis.String(t.description):"",required:l(t.required)?globalThis.Boolean(t.required):!1,params:x(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}},Gi={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",tags:globalThis.Array.isArray(t?.tags)?t.tags.map(e=>globalThis.String(e)):[],examples:globalThis.Array.isArray(t?.examples)?t.examples.map(e=>globalThis.String(e)):[],inputModes:globalThis.Array.isArray(t?.inputModes)?t.inputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.input_modes)?t.input_modes.map(e=>globalThis.String(e)):[],outputModes:globalThis.Array.isArray(t?.outputModes)?t.outputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.output_modes)?t.output_modes.map(e=>globalThis.String(e)):[],security:globalThis.Array.isArray(t?.security)?t.security.map(e=>ne.fromJSON(e)):[]}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.tags?.length&&(e.tags=t.tags),t.examples?.length&&(e.examples=t.examples),t.inputModes?.length&&(e.inputModes=t.inputModes),t.outputModes?.length&&(e.outputModes=t.outputModes),t.security?.length&&(e.security=t.security.map(r=>ne.toJSON(r))),e}},Qi={fromJSON(t){return{protected:l(t.protected)?globalThis.String(t.protected):"",signature:l(t.signature)?globalThis.String(t.signature):"",header:x(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}},ae={fromJSON(t){return{name:l(t.name)?globalThis.String(t.name):"",pushNotificationConfig:l(t.pushNotificationConfig)?_t.fromJSON(t.pushNotificationConfig):l(t.push_notification_config)?_t.fromJSON(t.push_notification_config):void 0}},toJSON(t){let e={};return t.name!==""&&(e.name=t.name),t.pushNotificationConfig!==void 0&&(e.pushNotificationConfig=_t.toJSON(t.pushNotificationConfig)),e}},Yi={fromJSON(t){return{list:globalThis.Array.isArray(t?.list)?t.list.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.list?.length&&(e.list=t.list),e}},ne={fromJSON(t){return{schemes:x(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Yi.fromJSON(i),e),{}):{}}},toJSON(t){let e={};if(t.schemes){let r=globalThis.Object.entries(t.schemes);r.length>0&&(e.schemes={},r.forEach(([i,a])=>{e.schemes[i]=Yi.toJSON(a)}))}return e}},Be={fromJSON(t){return{scheme:l(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:He.fromJSON(t.apiKeySecurityScheme)}:l(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:He.fromJSON(t.api_key_security_scheme)}:l(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Ke.fromJSON(t.httpAuthSecurityScheme)}:l(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Ke.fromJSON(t.http_auth_security_scheme)}:l(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:Ve.fromJSON(t.oauth2SecurityScheme)}:l(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:Ve.fromJSON(t.oauth2_security_scheme)}:l(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Ge.fromJSON(t.openIdConnectSecurityScheme)}:l(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Ge.fromJSON(t.open_id_connect_security_scheme)}:l(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Qe.fromJSON(t.mtlsSecurityScheme)}:l(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Qe.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=He.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Ke.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=Ve.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Ge.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Qe.toJSON(t.scheme.value)),e}},He={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",location:l(t.location)?globalThis.String(t.location):"",name:l(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}},Ke={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",scheme:l(t.scheme)?globalThis.String(t.scheme):"",bearerFormat:l(t.bearerFormat)?globalThis.String(t.bearerFormat):l(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}},Ve={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",flows:l(t.flows)?Wi.fromJSON(t.flows):void 0,oauth2MetadataUrl:l(t.oauth2MetadataUrl)?globalThis.String(t.oauth2MetadataUrl):l(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=Wi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Ge={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",openIdConnectUrl:l(t.openIdConnectUrl)?globalThis.String(t.openIdConnectUrl):l(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}},Qe={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Wi={fromJSON(t){return{flow:l(t.authorizationCode)?{$case:"authorizationCode",value:Ye.fromJSON(t.authorizationCode)}:l(t.authorization_code)?{$case:"authorizationCode",value:Ye.fromJSON(t.authorization_code)}:l(t.clientCredentials)?{$case:"clientCredentials",value:We.fromJSON(t.clientCredentials)}:l(t.client_credentials)?{$case:"clientCredentials",value:We.fromJSON(t.client_credentials)}:l(t.implicit)?{$case:"implicit",value:Xi.fromJSON(t.implicit)}:l(t.password)?{$case:"password",value:bi.fromJSON(t.password)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Ye.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=We.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Xi.toJSON(t.flow.value):t.flow?.$case==="password"&&(e.password=bi.toJSON(t.flow.value)),e}},Ye={fromJSON(t){return{authorizationUrl:l(t.authorizationUrl)?globalThis.String(t.authorizationUrl):l(t.authorization_url)?globalThis.String(t.authorization_url):"",tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},We={fromJSON(t){return{tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},Xi={fromJSON(t){return{authorizationUrl:l(t.authorizationUrl)?globalThis.String(t.authorizationUrl):l(t.authorization_url)?globalThis.String(t.authorization_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},bi={fromJSON(t){return{tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},cl={fromJSON(t){return{request:l(t.message)?z.fromJSON(t.message):l(t.request)?z.fromJSON(t.request):void 0,configuration:l(t.configuration)?zi.fromJSON(t.configuration):void 0,metadata:x(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.request!==void 0&&(e.message=z.toJSON(t.request)),t.configuration!==void 0&&(e.configuration=zi.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},fl={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:Jt.fromJSON(t.task)}:l(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:l(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Jt.toJSON(t.payload.value):t.payload?.$case==="msg"&&(e.message=z.toJSON(t.payload.value)),e}},hl={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:Jt.fromJSON(t.task)}:l(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:l(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:l(t.statusUpdate)?{$case:"statusUpdate",value:ze.fromJSON(t.statusUpdate)}:l(t.status_update)?{$case:"statusUpdate",value:ze.fromJSON(t.status_update)}:l(t.artifactUpdate)?{$case:"artifactUpdate",value:qe.fromJSON(t.artifactUpdate)}:l(t.artifact_update)?{$case:"artifactUpdate",value:qe.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Jt.toJSON(t.payload.value):t.payload?.$case==="msg"?e.message=z.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=ze.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=qe.toJSON(t.payload.value)),e}},pl={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>ae.fromJSON(e)):[],nextPageToken:l(t.nextPageToken)?globalThis.String(t.nextPageToken):l(t.next_page_token)?globalThis.String(t.next_page_token):""}},toJSON(t){let e={};return t.configs?.length&&(e.configs=t.configs.map(r=>ae.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function Zi(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Sl(t){return globalThis.Buffer.from(t).toString("base64")}function x(t){return typeof t=="object"&&t!==null}function l(t){return t!=null}var Tl=/^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/,gl=/^tasks\/([^/]+)(?:\/|$)/,It=t=>{let e=t.match(gl);if(!e)throw g.invalidParams(`Invalid or missing task ID in: "${t}"`);return e[1]},Rt=t=>`tasks/${t}`,ji=t=>{let e=t.match(Tl);if(!e)throw g.invalidParams(`Invalid or missing config ID in: "${t}"`);return{taskId:e[1],configId:e[2]}},Xe=(t,e)=>`tasks/${t}/pushNotificationConfigs/${e}`,ta=class R{static taskQueryParams(e){return{id:It(e.name),historyLength:e.historyLength}}static taskIdParams(e){return{id:It(e.name)}}static getTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=ji(e.name);return{id:r,pushNotificationConfigId:i}}static listTaskPushNotificationConfigParams(e){return{id:It(e.parent)}}static createTaskPushNotificationConfig(e){if(!e.config?.pushNotificationConfig)throw g.invalidParams("Request must include a `config` object with a `pushNotificationConfig`");return{taskId:It(e.parent),pushNotificationConfig:R.pushNotificationConfig(e.config.pushNotificationConfig)}}static deleteTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=ji(e.name);return{id:r,pushNotificationConfigId:i}}static message(e){if(e)return{kind:"message",messageId:e.messageId,parts:e.content.map(r=>R.part(r)),contextId:e.contextId||void 0,taskId:e.taskId||void 0,role:R.role(e.role),metadata:e.metadata,extensions:e.extensions}}static role(e){switch(e){case 2:return"agent";case 1:return"user";default:throw g.invalidParams(`Invalid role: ${e}`)}}static messageSendConfiguration(e){if(e)return{blocking:e.blocking,acceptedOutputModes:e.acceptedOutputModes,pushNotificationConfig:R.pushNotificationConfig(e.pushNotification)}}static pushNotificationConfig(e){if(e)return{id:e.id,url:e.url,token:e.token||void 0,authentication:R.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials}}static part(e){if(e.part?.$case==="text")return{kind:"text",text:e.part.value};if(e.part?.$case==="file"){let r=e.part.value;if(r.file?.$case==="fileWithUri")return{kind:"file",file:{uri:r.file.value,mimeType:r.mimeType}};if(r.file?.$case==="fileWithBytes")return{kind:"file",file:{bytes:Buffer.from(r.file.value).toString("base64"),mimeType:r.mimeType}};throw g.invalidParams("Invalid file part type")}if(e.part?.$case==="data")return{kind:"data",data:e.part.value.data??{}};throw g.invalidParams("Invalid part type")}static messageSendParams(e){if(!e.request)throw g.invalidParams("SendMessageRequest missing message");return{message:R.message(e.request),configuration:R.messageSendConfiguration(e.configuration),metadata:e.metadata}}static sendMessageResult(e){if(e.payload?.$case==="task")return R.task(e.payload.value);if(e.payload?.$case==="msg")return R.message(e.payload.value);throw g.invalidParams("Invalid SendMessageResponse: missing result")}static task(e){if(!e.status)throw g.internalError("Task missing status");return{kind:"task",id:e.id,status:R.taskStatus(e.status),contextId:e.contextId,artifacts:e.artifacts?.map(r=>R.artifact(r)),history:e.history?.map(r=>R.message(r)),metadata:e.metadata}}static taskStatus(e){return{message:R.message(e.update),state:R.taskState(e.state),timestamp:e.timestamp}}static taskState(e){switch(e){case 1:return"submitted";case 2:return"working";case 6:return"input-required";case 3:return"completed";case 5:return"canceled";case 4:return"failed";case 7:return"rejected";case 8:return"auth-required";case 0:return"unknown";default:throw g.invalidParams(`Invalid task state: ${e}`)}}static artifact(e){return{artifactId:e.artifactId,name:e.name||void 0,description:e.description||void 0,parts:e.parts.map(r=>R.part(r)),metadata:e.metadata}}static taskPushNotificationConfig(e){if(!e.pushNotificationConfig)throw g.invalidParams("TaskPushNotificationConfig missing pushNotificationConfig");return{taskId:It(e.name),pushNotificationConfig:R.pushNotificationConfig(e.pushNotificationConfig)}}static listTaskPushNotificationConfig(e){return e.configs.map(r=>R.taskPushNotificationConfig(r))}static agentCard(e){return{additionalInterfaces:e.additionalInterfaces?.map(r=>R.agentInterface(r)),capabilities:e.capabilities?R.agentCapabilities(e.capabilities):{},defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,description:e.description,documentationUrl:e.documentationUrl||void 0,name:e.name,preferredTransport:e.preferredTransport,provider:e.provider?R.agentProvider(e.provider):void 0,protocolVersion:e.protocolVersion,security:e.security?.map(r=>R.security(r)),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,R.securityScheme(i)])):{},skills:e.skills.map(r=>R.skills(r)),signatures:e.signatures?.map(r=>R.agentCardSignature(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard,url:e.url,version:e.version}}static agentCapabilities(e){return{extensions:e.extensions?.map(r=>R.agentExtension(r)),pushNotifications:e.pushNotifications,streaming:e.streaming}}static agentExtension(e){return{uri:e.uri,description:e.description||void 0,required:e.required,params:e.params}}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){return{organization:e.organization,url:e.url}}static security(e){return Object.fromEntries(Object.entries(e.schemes)?.map(([r,i])=>[r,i.list]))}static securityScheme(e){switch(e.scheme?.$case){case"apiKeySecurityScheme":return{type:"apiKey",name:e.scheme.value.name,in:e.scheme.value.location,description:e.scheme.value.description||void 0};case"httpAuthSecurityScheme":return{type:"http",scheme:e.scheme.value.scheme,bearerFormat:e.scheme.value.bearerFormat||void 0,description:e.scheme.value.description||void 0};case"mtlsSecurityScheme":return{type:"mutualTLS",description:e.scheme.value.description||void 0};case"oauth2SecurityScheme":if(!e.scheme.value.flows)throw g.internalError("OAuth2 security scheme missing flows");return{type:"oauth2",description:e.scheme.value.description||void 0,flows:R.oauthFlows(e.scheme.value.flows),oauth2MetadataUrl:e.scheme.value.oauth2MetadataUrl||void 0};case"openIdConnectSecurityScheme":return{type:"openIdConnect",description:e.scheme.value.description||void 0,openIdConnectUrl:e.scheme.value.openIdConnectUrl};default:throw g.internalError("Unsupported security scheme type")}}static oauthFlows(e){switch(e.flow?.$case){case"implicit":return{implicit:{authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,refreshUrl:e.flow.value.refreshUrl||void 0}};case"password":return{password:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"authorizationCode":return{authorizationCode:{refreshUrl:e.flow.value.refreshUrl||void 0,authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"clientCredentials":return{clientCredentials:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};default:throw g.internalError("Unsupported OAuth flows")}}static skills(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags,examples:e.examples,inputModes:e.inputModes,outputModes:e.outputModes,security:e.security?.map(r=>R.security(r))}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static taskStatusUpdateEvent(e){if(!e.status)throw g.invalidParams("Invalid TaskStatusUpdateEvent: missing status");return{kind:"status-update",taskId:e.taskId,status:R.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){if(!e.artifact)throw g.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");return{kind:"artifact-update",taskId:e.taskId,artifact:R.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,lastChunk:e.lastChunk}}static messageStreamResult(e){switch(e.payload?.$case){case"msg":return R.message(e.payload.value);case"task":return R.task(e.payload.value);case"statusUpdate":return R.taskStatusUpdateEvent(e.payload.value);case"artifactUpdate":return R.taskArtifactUpdateEvent(e.payload.value);default:throw g.internalError("Invalid event type in StreamResponse")}}},gt=class C{static agentCard(e){return{protocolVersion:e.protocolVersion,name:e.name,description:e.description,url:e.url,preferredTransport:e.preferredTransport??"",additionalInterfaces:e.additionalInterfaces?.map(r=>C.agentInterface(r))??[],provider:C.agentProvider(e.provider),version:e.version,documentationUrl:e.documentationUrl??"",capabilities:C.agentCapabilities(e.capabilities),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,C.securityScheme(i)])):{},security:e.security?.map(r=>C.security(r))??[],defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,skills:e.skills.map(r=>C.agentSkill(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard??!1,signatures:e.signatures?.map(r=>C.agentCardSignature(r))??[]}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static agentSkill(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags??[],examples:e.examples??[],inputModes:e.inputModes??[],outputModes:e.outputModes??[],security:e.security?e.security.map(r=>C.security(r)):[]}}static security(e){return{schemes:Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{list:i}]))}}static securityScheme(e){switch(e.type){case"apiKey":return{scheme:{$case:"apiKeySecurityScheme",value:{name:e.name,location:e.in,description:e.description??""}}};case"http":return{scheme:{$case:"httpAuthSecurityScheme",value:{description:e.description??"",scheme:e.scheme,bearerFormat:e.bearerFormat??""}}};case"mutualTLS":return{scheme:{$case:"mtlsSecurityScheme",value:{description:e.description??""}}};case"oauth2":return{scheme:{$case:"oauth2SecurityScheme",value:{description:e.description??"",flows:C.oauthFlows(e.flows),oauth2MetadataUrl:e.oauth2MetadataUrl??""}}};case"openIdConnect":return{scheme:{$case:"openIdConnectSecurityScheme",value:{description:e.description??"",openIdConnectUrl:e.openIdConnectUrl}}};default:throw g.internalError("Unsupported security scheme type")}}static oauthFlows(e){if(e.implicit)return{flow:{$case:"implicit",value:{authorizationUrl:e.implicit.authorizationUrl,scopes:e.implicit.scopes,refreshUrl:e.implicit.refreshUrl??""}}};if(e.password)return{flow:{$case:"password",value:{tokenUrl:e.password.tokenUrl,scopes:e.password.scopes,refreshUrl:e.password.refreshUrl??""}}};if(e.clientCredentials)return{flow:{$case:"clientCredentials",value:{tokenUrl:e.clientCredentials.tokenUrl,scopes:e.clientCredentials.scopes,refreshUrl:e.clientCredentials.refreshUrl??""}}};if(e.authorizationCode)return{flow:{$case:"authorizationCode",value:{authorizationUrl:e.authorizationCode.authorizationUrl,tokenUrl:e.authorizationCode.tokenUrl,scopes:e.authorizationCode.scopes,refreshUrl:e.authorizationCode.refreshUrl??""}}};throw g.internalError("Unsupported OAuth flows")}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){if(e)return{url:e.url,organization:e.organization}}static agentCapabilities(e){return e?{streaming:e.streaming??!1,pushNotifications:e.pushNotifications??!1,extensions:e.extensions?e.extensions.map(r=>C.agentExtension(r)):[]}:{streaming:!1,pushNotifications:!1,extensions:[]}}static agentExtension(e){return{uri:e.uri,description:e.description??"",required:e.required??!1,params:e.params}}static listTaskPushNotificationConfig(e){return{configs:e.map(r=>C.taskPushNotificationConfig(r)),nextPageToken:""}}static getTaskPushNotificationConfigParams(e){return{name:Xe(e.id,e.pushNotificationConfigId??"")}}static listTaskPushNotificationConfigParams(e){return{parent:Rt(e.id),pageToken:"",pageSize:0}}static deleteTaskPushNotificationConfigParams(e){return{name:Xe(e.id,e.pushNotificationConfigId)}}static taskPushNotificationConfig(e){return{name:Xe(e.taskId,e.pushNotificationConfig.id??""),pushNotificationConfig:C.pushNotificationConfig(e.pushNotificationConfig)}}static taskPushNotificationConfigCreate(e){return{parent:Rt(e.taskId),config:C.taskPushNotificationConfig(e),configId:e.pushNotificationConfig.id??""}}static pushNotificationConfig(e){if(e)return{id:e.id??"",url:e.url,token:e.token??"",authentication:C.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials??""}}static messageStreamResult(e){if(e.kind==="message")return{payload:{$case:"msg",value:C.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:C.task(e)}};if(e.kind==="status-update")return{payload:{$case:"statusUpdate",value:C.taskStatusUpdateEvent(e)}};if(e.kind==="artifact-update")return{payload:{$case:"artifactUpdate",value:C.taskArtifactUpdateEvent(e)}};throw g.internalError("Invalid event type")}static taskStatusUpdateEvent(e){return{taskId:e.taskId,status:C.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){return{taskId:e.taskId,artifact:C.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,append:e.append??!1,lastChunk:e.lastChunk??!1}}static messageSendResult(e){if(e.kind){if(e.kind==="message")return{payload:{$case:"msg",value:C.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:C.task(e)}}}}static message(e){if(e)return{messageId:e.messageId,content:e.parts.map(r=>C.part(r)),contextId:e.contextId??"",taskId:e.taskId??"",role:C.role(e.role),metadata:e.metadata,extensions:e.extensions??[]}}static role(e){switch(e){case"agent":return 2;case"user":return 1;default:throw g.internalError("Invalid role")}}static task(e){return{id:e.id,contextId:e.contextId,status:C.taskStatus(e.status),artifacts:e.artifacts?.map(r=>C.artifact(r))??[],history:e.history?.map(r=>C.message(r)).filter(r=>!!r)??[],metadata:e.metadata}}static taskStatus(e){return{state:C.taskState(e.state),update:C.message(e.message),timestamp:e.timestamp}}static artifact(e){return{artifactId:e.artifactId,name:e.name??"",description:e.description??"",parts:e.parts.map(r=>C.part(r)),metadata:e.metadata,extensions:e.extensions?e.extensions:[]}}static taskState(e){switch(e){case"submitted":return 1;case"working":return 2;case"input-required":return 6;case"rejected":return 7;case"auth-required":return 8;case"completed":return 3;case"failed":return 4;case"canceled":return 5;case"unknown":return 0;default:return-1}}static part(e){if(e.kind==="text")return{part:{$case:"text",value:e.text}};if(e.kind==="file"){let r;if("uri"in e.file)r={file:{$case:"fileWithUri",value:e.file.uri},mimeType:e.file.mimeType??""};else if("bytes"in e.file)r={file:{$case:"fileWithBytes",value:Buffer.from(e.file.bytes,"base64")},mimeType:e.file.mimeType??""};else throw g.internalError("Invalid file part");return{part:{$case:"file",value:r}}}if(e.kind==="data")return{part:{$case:"data",value:{data:e.data}}};throw g.internalError("Invalid part type")}static messageSendParams(e){return{request:C.message(e.message),configuration:C.configuration(e.configuration),metadata:e.metadata}}static configuration(e){if(e)return{blocking:e.blocking??!1,acceptedOutputModes:e.acceptedOutputModes??[],pushNotification:C.pushNotificationConfig(e.pushNotificationConfig),historyLength:e.historyLength??0}}static taskQueryParams(e){return{name:Rt(e.id),historyLength:e.historyLength??0}}static cancelTaskRequest(e){return{name:Rt(e.id)}}static taskIdParams(e){return{name:Rt(e.id)}}static getAgentCardRequest(){return{}}},ml=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(O.BAD_REQUEST).json(vt(g.parseError("Invalid JSON payload.")));i(t)};function Nl(t){let e=nr.default.Router(),r=new Zo(t.requestHandler);e.use((h,E,N)=>{let A=h.header(it)||yt;mr(A)?N():N("router")}),e.use((h,E,N)=>{E.setHeader("Content-Type",Ut),N()},nr.default.json({type:Ut,strict:!1}),ml);let i=async h=>{let E=await t.userBuilder(h),N=h.header(it)||yt,D=(t.contextBuilder??Tr)({extensions:se.parseServiceParameter(h.header(te)??h.header(Nt)),user:E,headers:h.headers,requestedVersion:N,tenant:h.params.tenant||void 0}),H=await r.getAgentCard();return gr(D.requestedVersion,H,"HTTP+JSON"),D},a=(h,E)=>{E.activatedExtensions&&h.setHeader(te,Array.from(E.activatedExtensions))},n=(h,E,N,A)=>{a(h,N),h.status(E),E===O.NO_CONTENT?h.end():h.json(A)},o=h=>{let E=gt.messageSendResult(h);if(!E)throw g.internalError("sendMessage produced no result.");return fl.toJSON(E)},d=h=>Jt.toJSON(gt.task(h)),c=h=>ae.toJSON(gt.taskPushNotificationConfig(h)),m=h=>ul.toJSON(gt.agentCard(h)),S=h=>pl.toJSON({configs:h.map(E=>gt.taskPushNotificationConfig(E)),nextPageToken:""}),_=h=>{let E=cl.fromJSON(h??{});return ta.messageSendParams(E)},u=h=>{let E=ae.fromJSON(h??{});return ta.taskPushNotificationConfig(E)},p=h=>{let E=gt.messageStreamResult(h);if(!E)throw g.internalError("Stream produced an unrepresentable event.");return hl.toJSON(E)},f=async(h,E,N)=>{let A=E[Symbol.asyncIterator](),D;try{D=await A.next()}catch(H){a(h,N);let Se=Li(H);h.status(Se).json(vt(H));return}Object.entries(bt).forEach(([H,Se])=>{h.setHeader(H,Se)}),a(h,N),h.flushHeaders();try{D.done||h.write(ct(p(D.value)));for await(let H of lr(A))h.write(ct(p(H)))}catch(H){console.error("Legacy SSE streaming error:",H),h.writableEnded||h.write(Zt(vt(H)))}finally{h.writableEnded||h.end()}},T=(h,E)=>{if(h.headersSent){h.writableEnded||h.end();return}let N=Li(E);h.status(N).json(vt(E))},v=h=>async(E,N)=>{try{await h(E,N)}catch(A){T(N,A)}};e.get("/v1/card",v(async(h,E)=>{let N=await i(h),A=await r.getAuthenticatedExtendedAgentCard(N);n(E,O.OK,N,m(A))})),e.post("/v1/message\\:send",v(async(h,E)=>{let N=await i(h),A=_(h.body),D=await r.sendMessage(A,N);n(E,O.CREATED,N,o(D))})),e.post("/v1/message\\:stream",v(async(h,E)=>{let N=await i(h),A=_(h.body),D=await r.sendMessageStream(A,N);await f(E,D,N)})),e.post("/v1/tasks/:taskId\\:cancel",v(async(h,E)=>{let N=await i(h),A=await r.cancelTask(h.params.taskId,N);n(E,O.OK,N,d(A))}));let k=v(async(h,E)=>{let N=await i(h),A=await r.resubscribe(h.params.taskId,N);await f(E,A,N)});return e.get("/v1/tasks/:taskId\\:subscribe",k),e.post("/v1/tasks/:taskId\\:subscribe",k),e.get("/v1/tasks/:taskId",v(async(h,E)=>{let N=await i(h),A=h.query.historyLength??h.query.history_length,D=await r.getTask(h.params.taskId,N,A);n(E,O.OK,N,d(D))})),e.post("/v1/tasks/:taskId/pushNotificationConfigs",v(async(h,E)=>{let N=await i(h),A=u(h.body),D=await r.setTaskPushNotificationConfig(A,N);n(E,O.CREATED,N,c(D))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs",v(async(h,E)=>{let N=await i(h),A=await r.listTaskPushNotificationConfigs(h.params.taskId,N);n(E,O.OK,N,S(A))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs/:configId",v(async(h,E)=>{let N=await i(h),A=await r.getTaskPushNotificationConfig(h.params.taskId,h.params.configId,N);n(E,O.OK,N,c(A))})),e.delete("/v1/tasks/:taskId/pushNotificationConfigs/:configId",v(async(h,E)=>{let N=await i(h);await r.deleteTaskPushNotificationConfig(h.params.taskId,h.params.configId,N),n(E,O.NO_CONTENT,N)})),e}function El(t){return`W/"${rl.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function za(t){let e=La.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return t.legacyCompat?.enabled&&e.use(nl(t)),e.get("/",async(a,n)=>{try{let o=await i(),d=JSON.stringify(o),c=El(d);if(n.setHeader("ETag",c),t.legacyCompat?.enabled&&n.append("Vary",it),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type","application/json"),n.status(200).send(d)}catch(o){console.error("Error fetching agent card:",o),n.status(500).json({error:"Failed to retrieve agent card"})}}),e}function qa(t){return t==="true"||t===!0}var Ol=class Fa{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e,r){return this.requestHandler.getAuthenticatedExtendedAgentCard(e,r)}validateSendMessageRequest(e){if(!e.message)throw new L("message is required");if(!e.message.messageId)throw new L("message.messageId is required")}async sendMessage(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessage(e,r)}async sendMessageStream(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessageStream(e,r)}async getTask(e,r,i,a){let n={id:e,tenant:a||""};return i!==void 0&&(n.historyLength=this.parseHistoryLength(i)),this.requestHandler.getTask(n,r)}async cancelTask(e,r,i){let a={id:e,tenant:i||"",metadata:{}};return this.requestHandler.cancelTask(a,r)}async listTasks(e,r){let i={tenant:e.tenant||"",contextId:e.contextId||"",status:e.status?dr(isNaN(Number(e.status))?e.status:Number(e.status)):0,pageSize:e.pageSize!==void 0&&e.pageSize!==""?this.parsePageSize(e.pageSize):void 0,pageToken:e.pageToken||"",historyLength:e.historyLength!==void 0&&e.historyLength!==""?this.parseHistoryLength(e.historyLength):void 0,statusTimestampAfter:e.statusTimestampAfter||void 0,includeArtifacts:qa(e.includeArtifacts)};return this.requestHandler.listTasks(i,r)}async resubscribe(e,r,i){return this.requestHandler.resubscribe({id:e,tenant:i||""},r)}async createTaskPushNotificationConfig(e,r){return await this.requireCapability("pushNotifications"),this.requestHandler.createTaskPushNotificationConfig(e,r)}async listTaskPushNotificationConfigs(e,r,i){return await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:i||""},r)}async getTaskPushNotificationConfig(e,r,i,a){return await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}async deleteTaskPushNotificationConfig(e,r,i,a){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}static CAPABILITY_ERRORS={pushNotifications:()=>new cr};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw Fa.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw new L("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw new L("historyLength must be a valid integer");if(r<0)throw new L("historyLength must be non-negative");return r}parsePageSize(e){let r=parseInt(String(e),10);if(isNaN(r)||String(r)!==String(e).trim())throw new L("pageSize must be a valid integer");if(r<1||r>100)throw new L("pageSize must be between 1 and 100");return r}},vl=class{static messageSendResult(t){if("messageId"in t)return{payload:{$case:"message",value:t}};if("artifacts"in t)return{payload:{$case:"task",value:t}};throw new X("Invalid SendMessageResult type")}},_l=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(400).json(Ct(new L("Invalid JSON payload."),400));i(t)},yl=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}let a=i.split(";",1)[0].trim().toLowerCase();if(a===ur||a===je){r();return}let n=new fr(`Unsupported Content-Type "${i}"; expected application/json or application/a2a+json.`);e.status(O.BAD_REQUEST).json(Ct(n,O.BAD_REQUEST))};function Ba(t){let e=sr.default.Router(),r=new Ol(t.requestHandler);t.legacyCompat?.enabled&&e.use(Nl(t)),e.use((u,p,f)=>{p.setHeader("Content-Type",je),f()},yl,sr.default.json({type:[ur,je],strict:!1}),_l);let i=async u=>{let p=await t.userBuilder(u),f=u.params.tenant||void 0,T=u.header(it)||void 0,k=(t.contextBuilder??Tr)({extensions:se.parseServiceParameter(u.header(Nt)),user:p,headers:u.headers,requestedVersion:T,tenant:f}),h=await r.getAgentCard();return gr(k.requestedVersion,h,"HTTP+JSON"),k},a=(u,p)=>{p.activatedExtensions&&u.setHeader(Nt,Array.from(p.activatedExtensions))},n=(u,p,f,T,v)=>{if(a(u,f),u.status(p),p===O.NO_CONTENT)u.end();else{if(!v||T===void 0)throw new Error("Bug: toJson serializer and body must be provided for non-204 responses.");u.json(v.toJSON(T))}},o=async(u,p,f)=>{let T=p[Symbol.asyncIterator](),v;try{v=await T.next()}catch(k){a(u,f);let h=Vt(k);u.status(h).json(Ct(k,h));return}Object.entries(bt).forEach(([k,h])=>{u.setHeader(k,h)}),a(u,f),u.flushHeaders();try{if(!v.done){let k=Ze.toJSON(v.value);u.write(ct(k))}for await(let k of lr(T)){let h=Ze.toJSON(k);u.write(ct(h))}}catch(k){console.error("SSE streaming error:",k),u.writableEnded||u.write(Zt(Ct(k,Vt(k))))}finally{u.writableEnded||u.end()}},d=(u,p)=>{if(u.headersSent){u.writableEnded||u.end();return}let f=Vt(p);u.status(f).json(Ct(p,f))},c=u=>async(p,f)=>{try{await u(p,f)}catch(T){d(f,T)}},m=(u,p,f)=>{let T=u.params.tenant;if(!T){f();return}let v=u.body?.tenant;v&&v!==T&&console.warn(`Tenant mismatch: URL path tenant "${T}" differs from request body tenant "${v}". Using path tenant as the canonical value.`);let k=u.query?.tenant;k&&k!==T&&console.warn(`Tenant mismatch: URL path tenant "${T}" differs from query param tenant "${k}". Using path tenant as the canonical value.`),u.body&&(u.body.tenant=T),u.query.tenant=T,f()},S=(u,p,f)=>{e[u](p,c(f)),e[u](`/:tenant${p}`,m,c(f))};S("get","/extendedAgentCard",async(u,p)=>{let f=await i(u),T=await r.getAuthenticatedExtendedAgentCard({tenant:u.query.tenant||""},f);n(p,O.OK,f,T,ra)}),S("post","/message\\:send",async(u,p)=>{let f=await i(u),T=Xt.fromJSON(u.body??{}),v=await r.sendMessage(T,f),k=vl.messageSendResult(v);n(p,O.OK,f,k,Is)}),S("post","/message\\:stream",async(u,p)=>{let f=await i(u),T=Xt.fromJSON(u.body??{}),v=await r.sendMessageStream(T,f);await o(p,v,f)});let _=async(u,p)=>{let f=await i(u),T=await r.resubscribe(u.params.taskId,f,u.query.tenant||"");await o(p,T,f)};return S("get","/tasks/:taskId\\:subscribe",_),S("post","/tasks/:taskId\\:subscribe",_),S("post","/tasks/:taskId\\:cancel",async(u,p)=>{let f=await i(u),T=await r.cancelTask(u.params.taskId,f,u.query.tenant||"");n(p,O.OK,f,T,Q)}),S("get","/tasks/:taskId",async(u,p)=>{let f=await i(u),T=await r.getTask(u.params.taskId,f,u.query.historyLength,u.query.tenant||"");n(p,O.OK,f,T,Q)}),S("get","/tasks",async(u,p)=>{let f=await i(u),T=await r.listTasks(u.query,f),v=qa(u.query.includeArtifacts);n(p,O.OK,f,T,{...ia,toJSON:k=>na(k,{includeArtifacts:v})})}),S("post","/tasks/:taskId/pushNotificationConfigs",async(u,p)=>{let f=await i(u),T=Y.fromJSON({...u.body??{},taskId:u.params.taskId}),v=await r.createTaskPushNotificationConfig(T,f);n(p,O.CREATED,f,v,Y)}),S("get","/tasks/:taskId/pushNotificationConfigs",async(u,p)=>{let f=await i(u),T=await r.listTaskPushNotificationConfigs(u.params.taskId,f,u.query.tenant||"");n(p,O.OK,f,T,aa)}),S("get","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,p)=>{let f=await i(u),T=await r.getTaskPushNotificationConfig(u.params.taskId,u.params.configId,f,u.query.tenant||"");n(p,O.OK,f,T,Y)}),S("delete","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,p)=>{let f=await i(u);await r.deleteTaskPushNotificationConfig(u.params.taskId,u.params.configId,f,u.query.tenant||""),n(p,O.NO_CONTENT,f)}),e}var Mr=ht(pt(),1);var B="yukino",de="permission-request",Ha="permission-response",Or="thinking",vr="tool-call",_r="tool-result";var Ka=`
10
- \u2026 [truncated]`;var yr="No active run is awaiting a permission response.",Va="Message must contain text or a yukino permission-response data part.",Ga="Session closed during initialization.",Qa="Task canceled by user request.";function kr(t,e){return`Context ${t} is busy with task ${e}. Cancel it or wait for it to finish before sending a new message.`}function Ya(t){return`Permission responses must be sent with taskId "${t}".`}function Wa(t){return`Unknown or already resolved permission id "${t}".`}var Xa="A2A context transcript is no longer available. Start a new context.",ba="No provider configured.",Za="A2A session capacity reached; retry when an active context finishes.",ja="Invalid persisted A2A context mapping.",tn="A2A server must listen on a loopback address.",en="A2A server did not bind to a TCP address.",Ar=18890,rn=`127.0.0.1:${String(Ar)}`,Ir="/.well-known/agent-card.json",Pt="1.0",an="a2a-contexts",ue=10,Rr=100*1024,nn="https://github.com/hangtiancheng/yukino-code/blob/main/apps/yukino/README.md#yukino-a2a-permissions-v1",Cr=new Set(["SendMessage","SendStreamingMessage","GetTask","ListTasks","CancelTask","SubscribeToTask","CreateTaskPushNotificationConfig","GetTaskPushNotificationConfig","ListTaskPushNotificationConfigs","DeleteTaskPushNotificationConfig","GetExtendedAgentCard"]),sn="Missing A2A-Version header; send A2A-Version: 1.0.",on=`Request body exceeds the ${String(Rr)} byte limit.`,ln="Request body must contain valid JSON.";function dn(t){return`Unsupported A2A-Version ${JSON.stringify(t)}; this server requires A2A-Version: 1.0.`}function un(t){return`Unknown method ${JSON.stringify(t)}. Supported methods: ${[...Cr].join(", ")}.`}import{randomUUID as kl}from"crypto";var q=(t=>(t[t.TASK_STATE_UNSPECIFIED=0]="TASK_STATE_UNSPECIFIED",t[t.TASK_STATE_SUBMITTED=1]="TASK_STATE_SUBMITTED",t[t.TASK_STATE_WORKING=2]="TASK_STATE_WORKING",t[t.TASK_STATE_COMPLETED=3]="TASK_STATE_COMPLETED",t[t.TASK_STATE_FAILED=4]="TASK_STATE_FAILED",t[t.TASK_STATE_CANCELED=5]="TASK_STATE_CANCELED",t[t.TASK_STATE_INPUT_REQUIRED=6]="TASK_STATE_INPUT_REQUIRED",t[t.TASK_STATE_REJECTED=7]="TASK_STATE_REJECTED",t[t.TASK_STATE_AUTH_REQUIRED=8]="TASK_STATE_AUTH_REQUIRED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(q||{}),Ur=(t=>(t[t.ROLE_UNSPECIFIED=0]="ROLE_UNSPECIFIED",t[t.ROLE_USER=1]="ROLE_USER",t[t.ROLE_AGENT=2]="ROLE_AGENT",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(Ur||{});var Id=4*1024*1024;var fn=I.object({[B]:I.literal(de),permissionId:I.string(),toolCallId:I.string(),toolName:I.string(),reason:I.string(),args:I.record(I.string(),I.unknown()),source:I.object({agentName:I.string(),cwd:I.string()}).optional()}),Jr=I.object({[B]:I.literal(Ha),permissionId:I.string(),decision:I.enum(["allow","deny","allowAlways"])}),xd=I.object({[B]:I.literal(Or),text:I.string()}),Pd=I.object({[B]:I.literal(vr),toolCallId:I.string(),toolName:I.string(),args:I.record(I.string(),I.unknown())}),Dd=I.object({[B]:I.literal(_r),toolCallId:I.string(),toolName:I.string(),isError:I.boolean(),elapsed:I.number(),output:I.string()});function dt(t){return{content:{$case:"text",value:t},metadata:void 0,filename:"",mediaType:"text/plain"}}function Dt(t){return{content:{$case:"data",value:t},metadata:void 0,filename:"",mediaType:"application/json"}}function ot(t,e,r){return{messageId:kl(),contextId:e,taskId:t,role:Ur.ROLE_AGENT,parts:r,metadata:void 0,extensions:[],referenceTaskIds:[]}}function hn(t,e){return{state:t,message:e,timestamp:new Date().toISOString()}}function ut(t,e,r,i){return{taskId:t,contextId:e,status:hn(r,i),metadata:void 0}}function ce(t,e,r,i){return{id:t,contextId:e,status:hn(r,i),artifacts:[],history:[],metadata:void 0}}function pn(t){let e=[];for(let r of t.parts)r.content?.$case==="text"&&e.push(r.content.value);return e.join(`
11
-
12
- `).trim()}function Al(t){let e=[];for(let r of t.parts)r.content?.$case==="data"&&e.push(r.content.value);return e}function Sn(t){for(let e of Al(t)){let r=Jr.safeParse(e);if(r.success)return r.data}return null}function Tn(t,e,r){switch(t.type){case"stream_text":return ot(e,r,[dt(t.text)]);case"thinking_text":return ot(e,r,[Dt({[B]:Or,text:t.text})]);case"tool_use":return ot(e,r,[Dt({[B]:vr,toolCallId:t.toolId,toolName:t.toolName,args:t.args})]);case"tool_result":{let a=t.output.length>8e3?`${t.output.slice(0,8e3)}${Ka}`:t.output;return ot(e,r,[Dt({[B]:_r,toolCallId:t.toolId,toolName:t.toolName,isError:t.isError,elapsed:t.elapsed,output:a})])}default:return null}}var gn="Yukino is a terminal-based AI coding agent. It reads, edits, and creates files, runs shell commands, and drives multi-step coding tasks from natural language instructions.",mn="Executes software engineering tasks: answering questions about a codebase, writing and refactoring code, running commands, and fixing bugs.",Nn=["Fix the failing tests in this repository.","Add a dark mode toggle to the settings page."],En="Yukino permission handshake v1: INPUT_REQUIRED status.message contains permission-request data parts; send a permission-response with permissionId and decision allow, deny, or allowAlways on the same task. allowAlways persists matching project rules; it does not bypass explicit denials. Server permission_mode controls the local policy. Thinking and tool stream events are carried in status-update metadata.yukino; assistant text streams as artifact updates. Task history contains complete assistant messages. SendMessage, GetTask and ListTasks default to the last 10 history messages; historyLength: 0 omits history while preserving status.message and artifacts.";function On(t){let e=[{url:t,protocolBinding:"JSONRPC",protocolVersion:Pt,tenant:""},{url:new URL("v1/",t).href,protocolBinding:"HTTP+JSON",protocolVersion:Pt,tenant:""}];return{name:"yukino",description:gn,supportedInterfaces:e,provider:void 0,version:Lr,capabilities:{streaming:!0,pushNotifications:!1,extensions:[{uri:nn,description:En,required:!1,params:{decisions:["allow","deny","allowAlways"],versionHeader:"A2A-Version: 1.0",requestSchema:I.toJSONSchema(fn),responseSchema:I.toJSONSchema(Jr)}}]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],skills:[{id:"coding",name:"Coding",description:mn,tags:["code","development","programming"],examples:Nn,inputModes:["text/plain"],outputModes:["text/plain"],securityRequirements:[]}],signatures:[]}}import{createHash as Cl,randomUUID as fe}from"crypto";import{existsSync as Ul,renameSync as Jl,rmSync as wl}from"fs";import{dirname as xl}from"path";async function Pr(t,e){let r=e?Xr(t,e):[];if(e&&r.length===0)throw new Error(Xa);let i=Gr(Qr(),t),a=Hr(i.providers,i.default_provider);if(!a)throw new Error(ba);let n=await ti({interactionMode:"non-interactive",provider:a,cwd:t,hooks:i.hooks,mcpServers:i.mcp_servers,mcpLoading:i.mcp_loading,lspServers:i.lsp_servers,sandboxConfig:i.sandbox,enableCoordinatorMode:i.enable_coordinator_mode??!1,forkDisabled:!Kr(i),memoryEnabled:Vr(i),...e?{sessionId:e}:{}});return n.permissionMode=i.permission_mode??"default",e&&n.conv.appendMessages(br(r)),{sessionId:n.sessionId,cwd:n.cwd,run:n.run.bind(n),abort:()=>{n.abort()},dispose:()=>n.dispose()}}function xr(){let t=()=>{};return{promise:new Promise(r=>{t=r}),resolve:t}}var he=class{constructor(e=Pr,r=process.cwd(),i=18e5){this.runtimeFactory=e;this.cwd=r;this.idleTimeoutMs=i}runtimeFactory;cwd;idleTimeoutMs;sessions=new Map;permissionCounter=0;async execute(e,r){let i=e.taskId,a=e.contextId,n=e.userMessage;this.disarmIdleTimer(this.sessions.get(a));try{await this.dispatch(i,a,n,r)}finally{let o=this.sessions.get(a);o&&this.armIdleTimer(o)}}async dispatch(e,r,i,a){let n=Sn(i);if(n){let u=this.sessions.get(r);if(!u){this.reject(null,a,e,r,yr);return}await this.handlePermissionResponse(u,e,r,n,a);return}let o=pn(i);if(!o){this.reject(this.sessions.get(r)??null,a,e,r,Va);return}let d=this.sessions.get(r);if(d?.run&&!d.run.finished){this.reject(d,a,e,r,kr(r,d.run.taskId));return}let c;try{c=d??this.createSession(r)}catch(u){this.reject(null,a,e,r,Lt(u));return}d&&(this.sessions.delete(r),this.sessions.set(r,c));let m;try{m=await this.ensureRuntime(c)}catch(u){this.reject(c,a,e,r,Lt(u));return}if(this.sessions.get(r)!==c){this.reject(null,a,e,r,Ga);return}let S=c.run;if(S&&!S.finished){this.reject(c,a,e,r,kr(r,S.taskId));return}let _=this.startRun(c,m,e,r,o,a);this.consume(c,_,o),await _.settle.promise}async cancelTask(e,r){let i=this.findSessionByTask(e),a=i?.run;if(!i||!a||a.finished){let n=i?.contextId??"";r.publish(J.statusUpdate(ut(e,n,q.TASK_STATE_CANCELED,ot(e,n,[dt(Qa)]))));return}this.disarmIdleTimer(i),a.canceled=!0,a.bus=r;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),a.runtime.abort(),await a.done.promise}async dispose(){let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async r=>{if(this.disarmIdleTimer(r),!r.runtimePromise)return;let i;try{i=await r.runtimePromise}catch{return}let a=r.run;if(a&&!a.finished){a.canceled=!0;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),i.abort()}await i.dispose()}))}createSession(e){if(this.evictOverflowSessions(),this.sessions.size>=256)throw new Error(Za);let r=this.contextMappingPath(e),i=Ul(r)?Fr(r,"utf8"):void 0;if(i!==void 0&&!$r.test(i))throw new Error(ja);let a={contextId:e,sessionId:i,runtimePromise:null,initializing:!1,run:null,idleTimer:null};return this.sessions.set(e,a),a}contextMappingPath(e){return Br(this.cwd,an,Cl("sha256").update(e).digest("hex"))}evictOverflowSessions(){if(!(this.sessions.size<256))for(let[e,r]of this.sessions){if(this.sessions.size<256)break;if(r.run&&!r.run.finished||r.initializing)continue;let i=r.sessionId;if(i){let n=this.contextMappingPath(e);zr(xl(n),{recursive:!0}),Yr(n,()=>{let o=`${n}.${fe()}.tmp`;try{qr(o,i,{flag:"wx",mode:384}),Jl(o,n)}finally{wl(o,{force:!0})}})}this.disarmIdleTimer(r);let a=r.runtimePromise;r.runtimePromise=null,a&&a.then(n=>n.dispose()).catch(()=>{}),this.sessions.delete(e)}}async ensureRuntime(e){e.initializing=!0,e.runtimePromise??=this.runtimeFactory(this.cwd,e.sessionId).then(r=>(e.sessionId=r.sessionId,r));try{return await e.runtimePromise}catch(r){throw e.runtimePromise=null,r}finally{e.initializing=!1}}armIdleTimer(e){if(this.disarmIdleTimer(e),this.idleTimeoutMs<=0||!e.runtimePromise||e.run&&!e.run.finished)return;let r=setTimeout(()=>{e.idleTimer=null,this.evictSession(e)},this.idleTimeoutMs);r.unref(),e.idleTimer=r}disarmIdleTimer(e){e?.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}evictSession(e){if(e.run&&!e.run.finished)return;let r=e.runtimePromise;e.runtimePromise=null,r&&r.then(i=>i.dispose()).catch(()=>{})}findSessionByTask(e){for(let r of this.sessions.values())if(r.run?.taskId===e)return r}async handlePermissionResponse(e,r,i,a,n){let o=e.run;if(!o||o.finished){this.reject(e,n,r,i,yr);return}if(o.taskId!==r){this.reject(e,n,r,i,Ya(o.taskId));return}let d=o.permissions.get(a.permissionId);if(!d){this.reject(e,n,r,i,Wa(a.permissionId));return}o.bus=n,o.permissions.delete(a.permissionId),o.settle=xr(),n.publish(J.task(ce(r,i,q.TASK_STATE_WORKING))),d.resolve(a.decision),o.permissions.size>0&&(this.publishPendingPermissions(o,r,i),o.settle.resolve()),await o.settle.promise}startRun(e,r,i,a,n,o){this.disarmIdleTimer(e);let d={taskId:i,runtime:r,bus:o,settle:xr(),done:xr(),canceled:!1,finished:!1,stopReason:null,text:"",messageId:fe(),permissions:new Map};return e.run=d,Wr(r.cwd,r.sessionId,{role:"user",content:n,timestamp:Math.floor(Date.now()/1e3)}),o.publish(J.task(ce(i,a,q.TASK_STATE_SUBMITTED))),d}consume(e,r,i){let a=r.taskId,n=e.contextId,o=r.runtime.run(i,{onPermissionRequest:(d,c,m,S,_,u)=>this.requestPermission(r,a,n,d,c,m,S,_,u)});(async()=>{let d=null;try{for await(let c of o)c.type==="loop_complete"&&(r.stopReason=c.stopReason),c.type==="error"&&(d=c.error.message),this.publishAgentEvent(r,a,n,c)}catch(c){d=Lt(c)}this.finishRun(e,r,a,n,d)})()}requestPermission(e,r,i,a,n,o,d,c,m){if(c?.aborted||e.canceled||e.finished)return Promise.resolve("deny");this.permissionCounter+=1;let S=`perm-${String(this.permissionCounter)}-${fe().slice(0,8)}`,_={[B]:de,permissionId:S,toolCallId:d,toolName:a,reason:o.reason,args:n,...m?{source:m}:{}};return new Promise(u=>{let p=T=>{c?.removeEventListener("abort",f),u(T)},f=()=>{e.permissions.delete(S)&&(p("deny"),!e.canceled&&!e.finished&&(e.permissions.size>0?this.publishPendingPermissions(e,r,i):e.bus.publish(J.statusUpdate(ut(r,i,q.TASK_STATE_WORKING)))))};e.permissions.set(S,{data:_,resolve:p}),c?.addEventListener("abort",f,{once:!0}),this.publishPendingPermissions(e,r,i),e.settle.resolve()})}publishPendingPermissions(e,r,i){let a=[...e.permissions.values()].map(n=>Dt(n.data));e.bus.publish(J.statusUpdate(ut(r,i,q.TASK_STATE_INPUT_REQUIRED,ot(r,i,a))))}publishAgentEvent(e,r,i,a){if(a.type==="turn_complete"){this.flushAnswer(e,r,i);return}let n=Tn(a,r,i);if(!n)return;if(a.type==="stream_text"){if(!a.text)return;let c=e.text.length>0;e.text+=a.text,e.bus.publish(J.artifactUpdate({taskId:r,contextId:i,artifact:{artifactId:e.messageId,name:"",description:"",parts:[dt(a.text)],metadata:void 0,extensions:[]},append:c,lastChunk:!1,metadata:void 0}));return}let o=ut(r,i,q.TASK_STATE_WORKING),d=n.parts[0]?.content?.value;o.metadata={[B]:d},e.bus.publish(J.statusUpdate(o))}flushAnswer(e,r,i){if(!e.text)return;let a=ot(r,i,[dt(e.text)]);a.messageId=e.messageId,e.lastAnswer=a,e.bus.publish(J.artifactUpdate({taskId:r,contextId:i,artifact:{artifactId:e.messageId,name:"",description:"",parts:[dt(e.text)],metadata:void 0,extensions:[]},append:!1,lastChunk:!0,metadata:void 0})),e.bus.publish(J.statusUpdate(ut(r,i,q.TASK_STATE_WORKING,a))),e.text="",e.messageId=fe()}finishRun(e,r,i,a,n){if(r.finished)return;r.finished=!0;for(let c of r.permissions.values())c.resolve("deny");r.permissions.clear(),this.flushAnswer(r,i,a);let o=this.finalState(r,n),d=n?ot(i,a,[dt(n)]):r.lastAnswer;r.bus.publish(J.statusUpdate(ut(i,a,o,d))),e.run===r&&(e.run=null),r.settle.resolve(),r.done.resolve(),this.armIdleTimer(e)}finalState(e,r){return e.canceled||e.stopReason==="cancelled"||e.stopReason==="interrupted"?q.TASK_STATE_CANCELED:r?q.TASK_STATE_FAILED:q.TASK_STATE_COMPLETED}reject(e,r,i,a,n){let o=ot(i,a,[dt(n)]);if(e?.run&&!e.run.finished){r.publish(J.message(o));return}r.publish(J.task(ce(i,a,q.TASK_STATE_FAILED))),r.publish(J.statusUpdate(ut(i,a,q.TASK_STATE_FAILED,o)))}};var pe=class extends Ni{sendMessage(e,r){return super.sendMessage({...e,configuration:{acceptedOutputModes:[],returnImmediately:!1,taskPushNotificationConfig:void 0,...e.configuration,historyLength:e.configuration?.historyLength??ue}},r)}getTask(e,r){return super.getTask({...e,historyLength:e.historyLength??ue},r)}listTasks(e,r){return super.listTasks({...e,historyLength:e.historyLength??ue},r)}};function Dl(t){let e=Zr(t??rn,{defaultPort:Ar,allowEphemeral:!0});if(!jr.has(e.host))throw new Error(tn);return e}async function Ml(t={}){let{host:e,port:r}=Dl(t.address),i=Pl();await Ll(i,r,e);let a=i.address();if(!a||typeof a=="string")throw new Error(en);let o=`http://${a.family==="IPv6"?`[${a.address}]`:a.address}:${String(a.port)}/`,d=On(o),c=new he(t.runtimeFactory??Pr,t.cwd??process.cwd()),m=new pe(d,new Ei,c,new ke),S=(0,Mr.default)();S.use(Ir,za({agentCardProvider:m})),S.use(Mr.default.json({limit:Rr,type:["application/json","application/a2a+json"],strict:!1}));let _=(p,f,T,v)=>{if(!Mt(p)||p.type!=="entity.too.large"&&p.type!=="entity.parse.failed"){v(p);return}let k=p.type==="entity.too.large";Dr(f,T,k?413:400,-32700,k?on:ln,k?"CONTENT_TOO_LARGE":"INVALID_ARGUMENT")};S.use(_),S.use((p,f,T)=>{if(p.path!=="/"&&!p.path.startsWith("/v1/")){T();return}let v=p.header("A2A-Version");if(v!==Pt){Dr(p,f,p.path==="/"?200:400,-32009,v?dn(v):sn,"VERSION_NOT_SUPPORTED");return}let k=p.body;if(p.path==="/"&&Mt(k)&&k.jsonrpc==="2.0"&&typeof k.method=="string"&&!Cr.has(k.method)){Dr(p,f,200,-32601,un(k.method),"METHOD_NOT_FOUND");return}T()}),S.use(Ma({requestHandler:m,userBuilder:or.noAuthentication})),S.use("/v1",Ba({requestHandler:m,userBuilder:or.noAuthentication})),i.on("request",S);let u=!1;return{url:o,cardUrl:`${o}${Ir.slice(1)}`,async close(){u||(u=!0,i.closeIdleConnections(),await $l(i),await c.dispose())}}}function Dr(t,e,r,i,a,n){let o=[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:n,domain:"a2a-protocol.org"}],d=t.body;t.path==="/"?e.status(r).json({jsonrpc:"2.0",id:Mt(d)?d.id??null:null,error:{code:i,message:a,data:o}}):e.status(r).json({error:{code:r,message:a,status:n==="VERSION_NOT_SUPPORTED"?"FAILED_PRECONDITION":"INVALID_ARGUMENT",details:o}})}function Ll(t,e,r){return new Promise((i,a)=>{let n=d=>{t.off("listening",o),a(d)},o=()=>{t.off("error",n),i()};t.once("error",n),t.once("listening",o),t.listen(e,r)})}function $l(t){return new Promise((e,r)=>{t.close(i=>{i?r(i):e()})})}async function Eu(t){let e=await Ml({address:t});process.stderr.write(`A2A server listening at ${e.url}
13
- `),process.stderr.write(`Agent card at ${e.cardUrl}
14
- `),await new Promise(r=>{let i=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),e.close().finally(r)};process.once("SIGINT",i),process.once("SIGTERM",i)})}export{Dl as parseA2aAddress,Eu as runA2aServer,Ml as startA2aServer};