@yukino.js/yukino 0.0.19 → 0.0.21-dev

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 (44) hide show
  1. package/README.md +36 -65
  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-2N7OIUQW.js +884 -0
  9. package/dist/{chunk-QDMUFOED.js → chunk-57IGGFHK.js} +6 -6
  10. package/dist/chunk-5AOJ5ZSQ.js +30 -0
  11. package/dist/chunk-5D3QKHYQ.js +36 -0
  12. package/dist/{chunk-PYFRT6N5.js → chunk-7WP7SERS.js} +1 -1
  13. package/dist/{chunk-S56AXDDN.js → chunk-EQABLL4S.js} +1 -1
  14. package/dist/{chunk-UX5DJPHN.js → chunk-P6K7EQHF.js} +29 -29
  15. package/dist/{chunk-WGRGSG2J.js → chunk-QSKJBSCI.js} +1 -1
  16. package/dist/chunk-WKTO7XPO.js +4 -0
  17. package/dist/lib/{anthropic-I7ZSAP7Z.js → anthropic-TYBMDJP3.js} +3 -3
  18. package/dist/lib/{chunk-T4WEXOQ7.js → chunk-3QGT2MSI.js} +1 -83
  19. package/dist/lib/{chunk-MJHQUFUL.js → chunk-IPKULHXR.js} +2 -2
  20. package/dist/lib/{chunk-UU6ZV6GB.js → chunk-NIUCGP4C.js} +82 -241
  21. package/dist/lib/{chunk-TO34ITLQ.js → chunk-OPEO6D4O.js} +2 -5
  22. package/dist/lib/chunk-XVXFUSSS.js +217 -0
  23. package/dist/lib/index.d.ts +1024 -1720
  24. package/dist/lib/index.js +5859 -9076
  25. package/dist/lib/{openai-Y4P7SWUB.js → openai-Z2JCYL6F.js} +3 -3
  26. package/dist/lib/{chunk-YZURLYHG.js → providers-2NPR2VR4.js} +28 -207
  27. package/dist/{main-MHJXHOY6.js → main-OMIZDIYB.js} +211 -275
  28. package/dist/main.js +4 -6
  29. package/dist/{openai-3IGA2BCD.js → openai-UOCUBMFA.js} +1 -1
  30. package/dist/{chunk-7WYSSZKU.js → providers-G5SKN22T.js} +9 -9
  31. package/dist/server-ESDMJACZ.js +14 -0
  32. package/dist/server-Z742CQSK.js +4 -0
  33. package/package.json +4 -6
  34. package/dist/anthropic-D72CIYEQ.js +0 -4
  35. package/dist/chunk-676RWZYX.js +0 -38
  36. package/dist/chunk-A4IB5PNW.js +0 -8
  37. package/dist/chunk-BCYFGWSM.js +0 -30
  38. package/dist/chunk-DGDF5PBF.js +0 -869
  39. package/dist/lib/providers-MRGAAMBB.js +0 -10
  40. package/dist/providers-GRYPIKCY.js +0 -4
  41. package/dist/server-XBVP3S5Q.js +0 -4
  42. package/dist/server-ZYP54JBK.js +0 -15
  43. package/dist/stdio-UHDEALLA.js +0 -5
  44. package/dist/websocket-J5DE5FRQ.js +0 -9
@@ -1,10 +0,0 @@
1
- import {
2
- createTelemetryRuntime,
3
- parseExporterTypes
4
- } from "./chunk-YZURLYHG.js";
5
- import "./chunk-T4WEXOQ7.js";
6
- import "./chunk-TRGKUGHQ.js";
7
- export {
8
- createTelemetryRuntime,
9
- parseExporterTypes
10
- };
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __yukinoCreateRequire } from "node:module";
3
- const require = __yukinoCreateRequire(import.meta.url);
4
- import{x as a,y as b}from"./chunk-7WYSSZKU.js";import"./chunk-BCYFGWSM.js";import"./chunk-QYUIIFJY.js";import"./chunk-WLJL66O5.js";import"./chunk-N7G2FDAI.js";import"./chunk-NPIMUWFO.js";import"./chunk-WKKH2UE5.js";import"./chunk-HKQWGX5S.js";import"./chunk-S56AXDDN.js";import"./chunk-WGRGSG2J.js";import"./chunk-456FRBGE.js";import"./chunk-7MKA3SHV.js";export{b as createTelemetryRuntime,a as parseExporterTypes};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __yukinoCreateRequire } from "node:module";
3
- const require = __yukinoCreateRequire(import.meta.url);
4
- import{h as a,i as b}from"./chunk-UX5DJPHN.js";import"./chunk-DGDF5PBF.js";import"./chunk-QDMUFOED.js";import"./chunk-676RWZYX.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-7WYSSZKU.js";import"./chunk-BCYFGWSM.js";import"./chunk-QYUIIFJY.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-N7G2FDAI.js";import"./chunk-NPIMUWFO.js";import"./chunk-WKKH2UE5.js";import"./chunk-HKQWGX5S.js";import"./chunk-S56AXDDN.js";import"./chunk-WGRGSG2J.js";import"./chunk-VM4YKTHC.js";import"./chunk-456FRBGE.js";import"./chunk-7MKA3SHV.js";export{b as RemoteServer,a as createRemoteAgent};
@@ -1,15 +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 ht,b as Hr,c as Kr,h as Vr}from"./chunk-UX5DJPHN.js";import{B as Fr,D as Br,j as zr,x as qr}from"./chunk-DGDF5PBF.js";import"./chunk-QDMUFOED.js";import{$ as Mr,_ as Dr,ba as Lr,ca as $r,j as Pr}from"./chunk-676RWZYX.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-7WYSSZKU.js";import{Oc as Dt,b as Cr,e as Ur,h as Jr,j as wr,p as xr}from"./chunk-BCYFGWSM.js";import"./chunk-QYUIIFJY.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-N7G2FDAI.js";import"./chunk-NPIMUWFO.js";import"./chunk-WKKH2UE5.js";import"./chunk-HKQWGX5S.js";import{a as Rr}from"./chunk-S56AXDDN.js";import{C as R}from"./chunk-WGRGSG2J.js";import"./chunk-VM4YKTHC.js";import"./chunk-456FRBGE.js";import{e as ft}from"./chunk-7MKA3SHV.js";import{createServer as El}from"http";var on=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}},w={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 Te(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var Zr=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function Gr(t){return t instanceof Zr}var ln=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new Zr("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(!Gr(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(!Gr(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})}},dn={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(",")},un="0.3";var cn=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||un,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=dn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function me(t){return t.user?.userName||"unknown"}var fn="a2a-protocol.org",hn="type.googleapis.com/google.rpc.ErrorInfo",br=Symbol.for("@a2a-js/sdk.A2AError"),zt=class jr extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(br in e))return!1;if(this===jr)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":hn,reason:this.reason,domain:fn,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(zt.prototype,br,{value:!0});var ti=[{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(ti.map(t=>[t.name,t]))),Al=Object.freeze(Object.fromEntries(ti.map(t=>[t.reason,t])));function tt(t){return{[t.name]:class extends zt{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 H=tt(j.TaskNotFoundError),ge=tt(j.TaskNotCancelableError),yt=tt(j.PushNotificationNotSupportedError),ot=tt(j.UnsupportedOperationError),ei=tt(j.ContentTypeNotSupportedError),pn=tt(j.InvalidAgentResponseError),ri=tt(j.ExtendedAgentCardNotConfiguredError),ii=tt(j.ExtensionSupportRequiredError),Sn=tt(j.VersionNotSupportedError),q=tt(j.RequestMalformedError),ai=Object.freeze({TaskNotFoundError:H,TaskNotCancelableError:ge,PushNotificationNotSupportedError:yt,UnsupportedOperationError:ot,ContentTypeNotSupportedError:ei,InvalidAgentResponseError:pn,ExtendedAgentCardNotConfiguredError:ri,ExtensionSupportRequiredError:ii,VersionNotSupportedError:Sn,RequestMalformedError:q});function Qr(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 K={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},b={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"},Tn=Object.freeze({TaskNotFoundError:K.NOT_FOUND,TaskNotCancelableError:K.BAD_REQUEST,PushNotificationNotSupportedError:K.BAD_REQUEST,UnsupportedOperationError:K.BAD_REQUEST,ContentTypeNotSupportedError:K.BAD_REQUEST,InvalidAgentResponseError:K.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:K.BAD_REQUEST,ExtensionSupportRequiredError:K.BAD_REQUEST,VersionNotSupportedError:K.BAD_REQUEST,RequestMalformedError:K.BAD_REQUEST}),Il=Object.freeze({TaskNotFoundError:b.NOT_FOUND,TaskNotCancelableError:b.FAILED_PRECONDITION,PushNotificationNotSupportedError:b.FAILED_PRECONDITION,UnsupportedOperationError:b.FAILED_PRECONDITION,ContentTypeNotSupportedError:b.INVALID_ARGUMENT,InvalidAgentResponseError:b.INTERNAL,ExtendedAgentCardNotConfiguredError:b.FAILED_PRECONDITION,ExtensionSupportRequiredError:b.FAILED_PRECONDITION,VersionNotSupportedError:b.FAILED_PRECONDITION,RequestMalformedError:b.INVALID_ARGUMENT});function et(t){let e=ai[t],r=Tn[t]??K.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 gn=et("TaskNotFoundError"),mn=et("TaskNotCancelableError"),Nn=et("PushNotificationNotSupportedError"),En=et("UnsupportedOperationError"),On=et("ContentTypeNotSupportedError"),vn=et("InvalidAgentResponseError"),_n=et("ExtendedAgentCardNotConfiguredError"),yn=et("ExtensionSupportRequiredError"),kn=et("VersionNotSupportedError"),An=et("RequestMalformedError"),Rl=Object.freeze({TaskNotFoundError:gn,TaskNotCancelableError:mn,PushNotificationNotSupportedError:Nn,UnsupportedOperationError:En,ContentTypeNotSupportedError:On,InvalidAgentResponseError:vn,ExtendedAgentCardNotConfiguredError:_n,ExtensionSupportRequiredError:yn,VersionNotSupportedError:kn,RequestMalformedError:An}),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},ni=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}),Cl=Object.freeze(Object.fromEntries(Object.entries(ni).map(([t,e])=>[e,t])));function rt(t){let e=ai[t],r=ni[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 In=rt("TaskNotFoundError"),Rn=rt("TaskNotCancelableError"),Cn=rt("PushNotificationNotSupportedError"),Un=rt("UnsupportedOperationError"),Jn=rt("ContentTypeNotSupportedError"),wn=rt("InvalidAgentResponseError"),xn=rt("ExtendedAgentCardNotConfiguredError"),Pn=rt("ExtensionSupportRequiredError"),Dn=rt("VersionNotSupportedError"),Mn=rt("RequestMalformedError"),Ul=Object.freeze({TaskNotFoundError:In,TaskNotCancelableError:Rn,PushNotificationNotSupportedError:Cn,UnsupportedOperationError:Un,ContentTypeNotSupportedError:Jn,InvalidAgentResponseError:wn,ExtendedAgentCardNotConfiguredError:xn,ExtensionSupportRequiredError:Pn,VersionNotSupportedError:Dn,RequestMalformedError:Mn});var Jl={[M.PARSE_ERROR]:"RequestMalformedError",[M.INVALID_REQUEST]:"RequestMalformedError",[M.METHOD_NOT_FOUND]:"RequestMalformedError"};function Ln(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 $n(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function zn(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function qn(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Yr={fromJSON(t){return{id:_(t.id)?globalThis.String(t.id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?qt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Bt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>pt.fromJSON(e)):[],metadata:St(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=>Bt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>pt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},qt={fromJSON(t){return{state:_(t.state)?Ln(t.state):0,message:_(t.message)?pt.fromJSON(t.message):void 0,timestamp:_(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=$n(t.state)),t.message!==void 0&&(e.message=pt.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Ft={fromJSON(t){return{content:_(t.text)?{$case:"text",value:globalThis.String(t.text)}:_(t.raw)?{$case:"raw",value:Buffer.from(Bn(t.raw))}:_(t.url)?{$case:"url",value:globalThis.String(t.url)}:_(t.data)?{$case:"data",value:t.data}:void 0,metadata:St(t.metadata)?t.metadata:void 0,filename:_(t.filename)?globalThis.String(t.filename):"",mediaType:_(t.mediaType)?globalThis.String(t.mediaType):_(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=Hn(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}},pt={fromJSON(t){return{messageId:_(t.messageId)?globalThis.String(t.messageId):_(t.message_id)?globalThis.String(t.message_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",role:_(t.role)?zn(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ft.fromJSON(e)):[],metadata:St(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=qn(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Ft.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}},Bt={fromJSON(t){return{artifactId:_(t.artifactId)?globalThis.String(t.artifactId):_(t.artifact_id)?globalThis.String(t.artifact_id):"",name:_(t.name)?globalThis.String(t.name):"",description:_(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ft.fromJSON(e)):[],metadata:St(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=>Ft.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ce={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?qt.fromJSON(t.status):void 0,metadata:St(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}},fe={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",artifact:_(t.artifact)?Bt.fromJSON(t.artifact):void 0,append:_(t.append)?globalThis.Boolean(t.append):!1,lastChunk:_(t.lastChunk)?globalThis.Boolean(t.lastChunk):_(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:St(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=Bt.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 Fn={fromJSON(t){return{payload:_(t.task)?{$case:"task",value:Yr.fromJSON(t.task)}:_(t.message)?{$case:"message",value:pt.fromJSON(t.message)}:_(t.statusUpdate)?{$case:"statusUpdate",value:ce.fromJSON(t.statusUpdate)}:_(t.status_update)?{$case:"statusUpdate",value:ce.fromJSON(t.status_update)}:_(t.artifactUpdate)?{$case:"artifactUpdate",value:fe.fromJSON(t.artifactUpdate)}:_(t.artifact_update)?{$case:"artifactUpdate",value:fe.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Yr.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=pt.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=ce.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=fe.toJSON(t.payload.value)),e}};function Bn(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Hn(t){return globalThis.Buffer.from(t).toString("base64")}function St(t){return typeof t=="object"&&t!==null}function _(t){return t!=null}var Kn="1.0",si="0.3",Vn="application/a2a+json",oi=50,wl=4*1024*1024,kt=[3,4,5,7],Gn=[0,1,2,3,4,5,6,7,8],li=[6],di=[8],Qn=[...li,...di];function Wr(t){return"status"in t}function Xr(t,e){return{tenant:t.tenant??"",owner:e(t)}}function Yn(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function Wn(t){try{let[e,...r]=Buffer.from(t,"base64").toString("utf-8").split("|");if(r.length===0)throw new q("Invalid page token format.");return{timestamp:e,id:r.join("|")}}catch(e){throw e instanceof q?e:new q("Token is not a valid base64-encoded cursor.")}}var Ne=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=Xr(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=Xr(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}},he=new cn,Ee=class{_scopedBuses;constructor(t=me){this._scopedBuses=new Ne(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??he),i=r.get(t);return i||(i=new ln,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??he)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??he);r?.get(t)?.removeAllListeners(),r?.delete(t)}},Mt=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&&(kt.includes(t.data.status.state)||li.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)}},Lt=new Map;function pe(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function Se(t,e){let i=(Lt.get(t)??Promise.resolve()).then(e,e);Lt.set(t,i);let a=()=>{Lt.get(t)===i&&Lt.delete(t)};return i.then(a,a),i}var $t=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 Se(pe(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await Se(pe(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await Se(pe(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Te(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&&kt.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}},Xn=class{_scopedStore;constructor(t=me){this._scopedStore=new Ne(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)}},Zn=class{serialize(t,e){return{body:JSON.stringify(Fn.toJSON(t)),contentType:Vn}}},bn=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 Zn;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(T){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,T)}});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 '${Kn}'. 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 T=this._resolveSerializer(n),{body:p,contentType:v}=T.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":v,...this._buildAuthHeaders(a)},body:p,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)}}},ui=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new Ee,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??Qn),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new Xn,this.pushNotificationSender=n||new bn(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new ot("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new ri;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 ei(`Media type '${i.mediaType}' is not supported. Supported media types: ${r.join(", ")}.`)}}async _createRequestContext(t,e){let r=t.message;if(!r)throw new q("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(h=>h.required&&!d.has(h.uri)).map(h=>h.uri);if(c.length>0)throw new ii(`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 H(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&kt.includes(i.status.state))throw new ot(`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 q(`contextId mismatch: message contextId '${r.contextId}' does not match task '${i.id}' contextId '${i.contextId}'`);i.history=[...i.history||[],r],await this.taskStore.save(i,e)}let T=r.taskId||crypto.randomUUID(),p=r.referenceTaskIds||[];if(p.length>0){a=[];for(let h of p){let g=await this.taskStore.load(h,e);g?a.push(g):console.warn(`Reference task ${h} not found.`)}}let v=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let h=new Set(o.map(g=>g.uri));e.setRequestedExtensions(e.requestedExtensions.filter(g=>h.has(g)))}let u={...r,contextId:v,taskId:T},N={...t,message:u};return new on(N,T,v,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 T=e.getFinalResult();T&&("messageId"in T||"id"in T)&&(c=T)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&d.kind==="statusUpdate"&&d.data.status&&di.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 q("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=jn(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Qr(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(w.task(d)),e.publish(w.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=ts(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Qr(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let d=a().task,c=d?.id??r.taskId,T=d?.contextId??i.contextId;if(!d){let v={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&&!v.history?.find(u=>u.messageId===i.messageId)&&v.history?.push(i),e.publish(w.task(v))}let p={taskId:c,contextId:T,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:T,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(w.statusUpdate(p))}).finally(()=>{this._settleBus(t,e,a().state,r.context)})}async sendMessage(t,e){let r=t.message;if(!r?.messageId)throw new q("message.messageId is required.");let i=t.configuration?.returnImmediately!==!0,a=new $t(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 v=structuredClone(t.configuration.taskPushNotificationConfig);v.taskId=o,await this.pushNotificationStore?.save(o,e,v)}let c=this.eventBusManager.createOrGetByTaskId(o,e),T=new Mt(c);this._runExecutor(o,c,n,d);let p=t.configuration;return i?new Promise((v,u)=>{let N=this._processEvents(o,a,T,e,{authRequiredSnapshotResolver:h=>{this._applyHistoryLengthSemantics(h,p??{}),v(h),this._continueDraining(o,N)},firstResultRejector:u});N.then(()=>{let h=a.getFinalResult();if(!h){u(new zt("Agent execution finished without a result, and no task context found."));return}Wr(h)&&this._applyHistoryLengthSemantics(h,p??{}),v(h)}).catch(u)}):new Promise((v,u)=>{this._processEvents(o,a,T,e,{firstResultResolver:N=>{Wr(N)&&this._applyHistoryLengthSemantics(N,p??{}),v(N)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new ot("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new q("message.messageId is required for streaming.");let i=new $t(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),d=new Mt(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let T=structuredClone(t.configuration.taskPushNotificationConfig);T.taskId=n,await this.pushNotificationStore?.save(n,e,T)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let T of d.events()){c=this._advanceStreamPattern(T,c),await i.processEvent(T);let p=await this._mapEventToStreamResponse(T,e);p.payload?.$case==="task"&&this._applyHistoryLengthSemantics(p.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,p,i.getCurrentTask()),yield p}}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 H(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??oi;if(!Number.isInteger(r)||r<1||r>100)throw new q("pageSize must be between 1 and 100");if(t.status!==void 0&&!Gn.includes(t.status))throw new q(`Invalid status filter: ${String(t.status)}`);if(t.statusTimestampAfter&&isNaN(Date.parse(t.statusTimestampAfter)))throw new q("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 H(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&kt.includes(a))throw new ge(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let d=new Mt(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new $t(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 $t(this.taskStore,e).processEvent(w.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 zt(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new ge(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new yt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`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 yt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new H(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new H(`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 yt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new yt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new ot("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new Mt(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new H(`Task not found: ${r}`);if(n.status?.state!==void 0&&kt.includes(n.status.state))throw new ot(`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:Te(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:Te(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(w.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 ot(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new ot(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new ot(`Stream ordering violation: received ${t.kind} in task lifecycle stream.`);return e}}_requireValidTaskId(t){if(!t||t.trim()==="")throw new q("Task ID is required")}_applyHistoryLengthSemantics(t,e){e.historyLength!==void 0&&(e.historyLength<=0?t.history=[]:t.history=(t.history??[]).slice(-e.historyLength))}};function jn(t){let e,r=i=>{(i.kind==="task"&&i.data.status?.state!==void 0||i.kind==="statusUpdate"&&i.data.status?.state!==void 0)&&(e=i.data.status.state)};return t.on("event",r),()=>(t.off("event",r),e)}function ts(t){let e,r,i=a=>{a.kind==="task"?(e=a.data,a.data.status?.state!==void 0&&(r=a.data.status.state)):a.kind==="statusUpdate"&&a.data.status?.state!==void 0&&(r=a.data.status.state)};return t.on("event",i),()=>(t.off("event",i),{task:e,state:r})}var ci=class{_scopedStore;constructor(t=me){this._scopedStore=new Ne(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=oi,pageToken:n,statusTimestampAfter:o,includeArtifacts:d=!1}=t,c=this._scopedStore.getBucket(e),T=c?Array.from(c.values()):[];if(r&&(T=T.filter(h=>h.contextId===r)),i!==void 0&&i!==0&&(T=T.filter(h=>h.status?.state===i)),o){let h=new Date(o).getTime();T=T.filter(g=>g.status?.timestamp&&new Date(g.status.timestamp).getTime()>h)}T.sort((h,g)=>{let y=h.status?.timestamp||"",C=g.status?.timestamp||"";return C!==y?C.localeCompare(y):g.id.localeCompare(h.id)});let p=T.length;if(n){let h=Wn(n),g=T.findIndex(y=>(y.status?.timestamp||"")===h.timestamp&&y.id===h.id);g!==-1?T=T.slice(g+1):T=[]}let v=T.slice(0,a),u=v.map(h=>{let g=structuredClone(h);return d||(g.artifacts=[]),g}),N="";if(v.length>0&&T.length>v.length){let h=v[v.length-1];N=Yn(h.status?.timestamp||"",h.id)}return{tasks:u,nextPageToken:N,pageSize:a,totalSize:p}}};var Ge=ft(ht(),1);var Ra=ft(ht(),1),Ca=ft(ht(),1),tr=ft(ht(),1),er=ft(ht(),1);import Fo from"crypto";import Bo from"crypto";var es=class{get isAuthenticated(){return!1}get userName(){return""}},rr={noAuthentication:()=>Promise.resolve(new es)};async function*ir(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 ar(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 Gi(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 rs(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 is(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var fi={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)?Q.fromJSON(t.taskPushNotificationConfig):s(t.task_push_notification_config)?Q.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=Q.toJSON(t.taskPushNotificationConfig)),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),t.returnImmediately!==!1&&(e.returnImmediately=t.returnImmediately),e}},G={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)?Vt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Qt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Y.fromJSON(e)):[],metadata:J(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=Vt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Qt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Y.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Vt={fromJSON(t){return{state:s(t.state)?ar(t.state):0,message:s(t.message)?Y.fromJSON(t.message):void 0,timestamp:s(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=Gi(t.state)),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Gt={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(hs(t.raw))}:s(t.url)?{$case:"url",value:globalThis.String(t.url)}:s(t.data)?{$case:"data",value:t.data}:void 0,metadata:J(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=ps(t.content.value):t.content?.$case==="url"?e.url=t.content.value:t.content?.$case==="data"&&(e.data=t.content.value),t.metadata!==void 0&&(e.metadata=t.metadata),t.filename!==""&&(e.filename=t.filename),t.mediaType!==""&&(e.mediaType=t.mediaType),e}},Y={fromJSON(t){return{messageId:s(t.messageId)?globalThis.String(t.messageId):s(t.message_id)?globalThis.String(t.message_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",role:s(t.role)?rs(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Gt.fromJSON(e)):[],metadata:J(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=is(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Gt.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}},Qt={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=>Gt.fromJSON(e)):[],metadata:J(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=>Gt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Oe={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)?Vt.fromJSON(t.status):void 0,metadata:J(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=Vt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ve={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)?Qt.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:J(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=Qt.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}},hi={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}},_e={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}},Qi={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=>_e.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>_e.fromJSON(e)):[],provider:s(t.provider)?pi.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)?Si.fromJSON(t.capabilities):void 0,securitySchemes:J(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=ye.fromJSON(i),e),{}):J(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=ye.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>gt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>gt.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)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>mi.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=>_e.toJSON(r))),t.provider!==void 0&&(e.provider=pi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Si.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=ye.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>gt.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.signatures?.length&&(e.signatures=t.signatures.map(r=>mi.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},pi={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}},Si={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=>Ti.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=>Ti.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},Ti={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:J(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: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=>gt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>gt.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=>gt.toJSON(r))),e}},mi={fromJSON(t){return{protected:s(t.protected)?globalThis.String(t.protected):"",signature:s(t.signature)?globalThis.String(t.signature):"",header:J(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}},Q={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)?hi.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=hi.toJSON(t.authentication)),e}},Ni={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}},gt={fromJSON(t){return{schemes:J(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Ni.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]=Ni.toJSON(n)}),e.schemes=i}}return e}},ye={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:ke.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:ke.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Ae.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Ae.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:Ie.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:Ie.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Re.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Re.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Ce.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Ce.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=ke.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Ae.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=Ie.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Re.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Ce.toJSON(t.scheme.value)),e}},ke={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}},Ae={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}},Ie={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?Ei.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=Ei.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Re={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}},Ce={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Ei={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:Ue.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:Ue.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Je.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Je.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:Oi.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:vi.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:we.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:we.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Ue.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Je.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Oi.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=vi.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=we.toJSON(t.flow.value)),e}},Ue={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:J(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}},Je={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:J(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}},Oi={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:J(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}},vi={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:J(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}},we={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:J(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}},Yt={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",message:s(t.message)?Y.fromJSON(t.message):void 0,configuration:s(t.configuration)?fi.fromJSON(t.configuration):void 0,metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.configuration!==void 0&&(e.configuration=fi.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},as={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}},ns={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)?ar(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=Gi(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}},Yi={fromJSON(t){return{tasks:globalThis.Array.isArray(t?.tasks)?t.tasks.map(e=>G.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=>G.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}},ss={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:J(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}},os={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},ls={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}},ds={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}},us={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}},cs={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},fs={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:G.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=G.toJSON(t.payload.value):t.payload?.$case==="message"&&(e.message=Y.toJSON(t.payload.value)),e}},Qe={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:G.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:Oe.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:Oe.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:ve.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:ve.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=G.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Y.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Oe.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=ve.toJSON(t.payload.value)),e}},Wi={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>Q.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=>Q.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function hs(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function ps(t){return globalThis.Buffer.from(t).toString("base64")}function J(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var mt="A2A-Extensions",it="A2A-Version",Ss="1.0",_t="0.3",nr="application/json",Ye="application/a2a+json",ae={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(",")},Wt={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function dt(t){return`data: ${JSON.stringify(t)}
5
-
6
- `}function Xt(t){return`event: error
7
- data: ${JSON.stringify(t)}
8
-
9
- `}var Wl=4*1024*1024;function Xi(t,e){let r=Yi.toJSON(t),{tasks:i,nextPageToken:a,pageSize:n,totalSize:o,...d}=r,c=i??[];return{tasks:e?.includeArtifacts?c.map(Ts):c,nextPageToken:a??"",pageSize:n??0,totalSize:o??0,...d}}function Ts(t){if(typeof t!="object"||t===null)return t;let e=t;return e.artifacts!==void 0?e:{...e,artifacts:[]}}var gs="a2a-protocol.org",ms="type.googleapis.com/google.rpc.ErrorInfo",Zi=Symbol.for("@a2a-js/sdk.A2AError"),W=class bi extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(Zi in e))return!1;if(this===bi)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":ms,reason:this.reason,domain:gs,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(W.prototype,Zi,{value:!0});var ji=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],X=Object.freeze(Object.fromEntries(ji.map(t=>[t.name,t]))),Xl=Object.freeze(Object.fromEntries(ji.map(t=>[t.reason,t])));function at(t){return{[t.name]:class extends W{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var ta=at(X.TaskNotFoundError),ea=at(X.TaskNotCancelableError),sr=at(X.PushNotificationNotSupportedError),ra=at(X.UnsupportedOperationError),or=at(X.ContentTypeNotSupportedError),Ns=at(X.InvalidAgentResponseError),ia=at(X.ExtendedAgentCardNotConfiguredError),Es=at(X.ExtensionSupportRequiredError),ne=at(X.VersionNotSupportedError),L=at(X.RequestMalformedError),lr=Object.freeze({TaskNotFoundError:ta,TaskNotCancelableError:ea,PushNotificationNotSupportedError:sr,UnsupportedOperationError:ra,ContentTypeNotSupportedError:or,InvalidAgentResponseError:Ns,ExtendedAgentCardNotConfiguredError:ia,ExtensionSupportRequiredError:Es,VersionNotSupportedError:ne,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"},aa=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}),Os=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 vs(t){return t instanceof W&&t.transport==="rest"}function nt(t){let e=lr[t],r=aa[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"),ys=nt("TaskNotCancelableError"),ks=nt("PushNotificationNotSupportedError"),As=nt("UnsupportedOperationError"),Is=nt("ContentTypeNotSupportedError"),Rs=nt("InvalidAgentResponseError"),Cs=nt("ExtendedAgentCardNotConfiguredError"),Us=nt("ExtensionSupportRequiredError"),Js=nt("VersionNotSupportedError"),ws=nt("RequestMalformedError"),Zl=Object.freeze({TaskNotFoundError:_s,TaskNotCancelableError:ys,PushNotificationNotSupportedError:ks,UnsupportedOperationError:As,ContentTypeNotSupportedError:Is,InvalidAgentResponseError:Rs,ExtendedAgentCardNotConfiguredError:Cs,ExtensionSupportRequiredError:Us,VersionNotSupportedError:Js,RequestMalformedError:ws});function Ht(t){return vs(t)?t.statusCode:t instanceof W?aa[t.name]??500:O.INTERNAL_SERVER_ERROR}function Rt(t,e){let r=t instanceof Error?t.message:"An unexpected error occurred.",i=[],a=P.UNKNOWN;return t instanceof W?(i.push(t.toErrorInfo()),a=Os[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},se=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}),xs=Object.freeze(Object.fromEntries(Object.entries(se).map(([t,e])=>[e,t])));function dr(t){return t instanceof W&&t.transport==="jsonrpc"}function st(t){let e=lr[t],r=se[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 Ps=st("TaskNotFoundError"),Ds=st("TaskNotCancelableError"),Ms=st("PushNotificationNotSupportedError"),ur=st("UnsupportedOperationError"),Ls=st("ContentTypeNotSupportedError"),$s=st("InvalidAgentResponseError"),zs=st("ExtendedAgentCardNotConfiguredError"),qs=st("ExtensionSupportRequiredError"),Fs=st("VersionNotSupportedError"),Jt=st("RequestMalformedError"),Bs=Object.freeze({TaskNotFoundError:Ps,TaskNotCancelableError:Ds,PushNotificationNotSupportedError:Ms,UnsupportedOperationError:ur,ContentTypeNotSupportedError:Ls,InvalidAgentResponseError:$s,ExtendedAgentCardNotConfiguredError:zs,ExtensionSupportRequiredError:qs,VersionNotSupportedError:Fs,RequestMalformedError:Jt}),na=class extends W{transport="jsonrpc";envelopeCode;data;errorResponse;constructor(t){super({message:t.error.message}),this.name="JsonRpcTransportError",this.envelopeCode=t.error.code,t.error.data!==void 0&&(this.data=t.error.data),this.errorResponse=t}};function Hs(t){if(dr(t)){let r=X[t.name];return{code:t.envelopeCode,message:t.message,...r?{data:[t.toErrorInfo()]}:{}}}if(t instanceof W)return{code:se[t.name]??U.INTERNAL_ERROR,message:t.message,data:[t.toErrorInfo()]};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var bl={[U.PARSE_ERROR]:"RequestMalformedError",[U.INVALID_REQUEST]:"RequestMalformedError",[U.METHOD_NOT_FOUND]:"RequestMalformedError"},We=class Xe{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=Xe.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(Yt.fromJSON(d),r):this.requestHandler.resubscribe(ds.fromJSON(d),r);return(async function*(){for await(let p of c)yield{jsonrpc:"2.0",id:n,result:Qe.toJSON(p)}})()}else{let d;switch(a){case"SendMessage":{let c=await this.requestHandler.sendMessage(Yt.fromJSON(i.params),r);d="messageId"in c?{message:Y.toJSON(c)}:{task:G.toJSON(c)};break}case"GetTask":d=G.toJSON(await this.requestHandler.getTask(as.fromJSON(i.params),r));break;case"ListTasks":{let c=ns.fromJSON(i.params);d=Xi(await this.requestHandler.listTasks(c,r),{includeArtifacts:c.includeArtifacts});break}case"CancelTask":d=G.toJSON(await this.requestHandler.cancelTask(ss.fromJSON(i.params),r));break;case"CreateTaskPushNotificationConfig":{d=Q.toJSON(await this.requestHandler.createTaskPushNotificationConfig(Q.fromJSON(i.params),r));break}case"GetTaskPushNotificationConfig":d=Q.toJSON(await this.requestHandler.getTaskPushNotificationConfig(os.fromJSON(i.params),r));break;case"DeleteTaskPushNotificationConfig":await this.requestHandler.deleteTaskPushNotificationConfig(ls.fromJSON(i.params),r),d=null;break;case"ListTaskPushNotificationConfigs":d=Wi.toJSON(await this.requestHandler.listTaskPushNotificationConfigs(us.fromJSON(i.params),r));break;case"GetExtendedAgentCard":d=Qi.toJSON(await this.requestHandler.getAuthenticatedExtendedAgentCard(cs.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:Xe.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 Hs(e)}},Ks="0.3",Vs="headers",cr=({extensions:t,user:e,headers:r,requestedVersion:i,tenant:a})=>{let n=new Map([[Vs,r]]);return new Gs({requestedExtensions:t,user:e,state:n,requestedVersion:i,tenant:a})},Gs=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||Ks,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=ae.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function Qs(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 fr(t,e,r){let i=Qs(e,r);if(!i.has(t))throw new ne(`The requested A2A protocol version '${t}' is not supported. Supported versions: ${[...i].join(", ")}`)}var sa=_t,Ys=Ss;function xe(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 _i(t,e){return t.major!==e.major?t.major-e.major:t.minor-e.minor}function hr(t){if(!t||t.trim()==="")return!0;let e=xe(t);if(!e)return!1;let r=xe(sa),i=xe(Ys);return!r||!i?!1:_i(e,r)>=0&&_i(e,i)<0}function Ws(t,e,r){let i=xs[t];return i?r===void 0?new lr[i]({message:e}):new Bs[i]({message:e,envelopeCode:t,data:r}):t===U.METHOD_NOT_FOUND?new ur({message:e,envelopeCode:t,data:r}):t===U.PARSE_ERROR||t===U.INVALID_REQUEST?new Jt({message:e,envelopeCode:t,data:r}):new na({jsonrpc:"2.0",id:null,error:{code:t,message:e,data:r}})}var S=Ws;Object.defineProperty(S,Symbol.hasInstance,{value:t=>t instanceof W});S.parseError=(t,e)=>new Jt({message:t,envelopeCode:U.PARSE_ERROR,data:e});S.invalidRequest=(t,e)=>new Jt({message:t,envelopeCode:U.INVALID_REQUEST,data:e});S.methodNotFound=t=>new ur({message:`Method not found: ${t}`,envelopeCode:U.METHOD_NOT_FOUND});S.invalidParams=(t,e)=>e===void 0?new L({message:t}):new Jt({message:t,envelopeCode:U.INVALID_PARAMS,data:e});S.internalError=(t,e)=>new na({jsonrpc:"2.0",id:null,error:{code:U.INTERNAL_ERROR,message:t,...e!==void 0?{data:e}:{}}});S.taskNotFound=t=>new ta({message:`Task not found: ${t}`});S.taskNotCancelable=t=>new ea({message:`Task not cancelable: ${t}`});S.pushNotificationNotSupported=()=>new sr;S.unsupportedOperation=t=>new ra({message:`Unsupported operation: ${t}`});S.authenticatedExtendedCardNotConfigured=()=>new ia({message:"Extended card not configured."});function V(t){return t!==void 0&&t!==""?t:void 0}function oa(t){return Object.fromEntries(Object.entries(t.schemes).map(([e,r])=>[e,[...r.list]]))}function Xs(t){let e={type:"apiKey",name:t.name,in:t.location==="cookie"||t.location==="query"?t.location:"header"},r=V(t.description);return r!==void 0&&(e.description=r),e}function Zs(t){let e={type:"http",scheme:t.scheme},r=V(t.description);r!==void 0&&(e.description=r);let i=V(t.bearerFormat);return i!==void 0&&(e.bearerFormat=i),e}function bs(t){let e={type:"mutualTLS"},r=V(t.description);return r!==void 0&&(e.description=r),e}function js(t){if(!t.flows)throw S.invalidParams("OAuth2 security scheme missing flows");let e={type:"oauth2",flows:ro(t.flows)},r=V(t.description);r!==void 0&&(e.description=r);let i=V(t.oauth2MetadataUrl);return i!==void 0&&(e.oauth2MetadataUrl=i),e}function to(t){let e={type:"openIdConnect",openIdConnectUrl:t.openIdConnectUrl},r=V(t.description);return r!==void 0&&(e.description=r),e}function eo(t){let e=t.scheme;if(!e)throw S.invalidParams("Invalid v1.0 SecurityScheme: missing inner scheme");switch(e.$case){case"apiKeySecurityScheme":return Xs(e.value);case"httpAuthSecurityScheme":return Zs(e.value);case"mtlsSecurityScheme":return bs(e.value);case"oauth2SecurityScheme":return js(e.value);case"openIdConnectSecurityScheme":return to(e.value);default:throw S.invalidParams(`Unsupported v1.0 SecurityScheme $case: ${e.$case??"unknown"}`)}}function ro(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=V(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=V(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=V(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=V(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 Nt(t,e){if(!Array.isArray(t))throw S.invalidParams(`${e} is required and must be an array`);return t}function io(t){return t!==void 0&&t!==""?t:void 0}function ao(t){return{url:t.url,transport:t.protocolBinding}}function no(t){return{url:t.url,organization:t.organization}}function so(t){let e={uri:t.uri},r=io(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 oo(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(so)),e}function lo(t){let e={id:t.id,name:t.name,description:t.description,tags:[...Nt(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(oa)),e}function uo(t){let e={protected:t.protected,signature:t.signature},r=$(t.header);return r!==void 0&&(e.header=r),e}function pr(t,e){let r=t.supportedInterfaces??[],i=r.filter(v=>!v.protocolVersion||hr(v.protocolVersion));if(i.length===0)throw new ne("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(ao),o=t.capabilities?oo(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(([v,u])=>[v,eo(u)])):void 0,T=a.protocolVersion||sa,p={name:t.name,description:t.description,version:t.version,url:a.url,preferredTransport:a.protocolBinding,protocolVersion:T,capabilities:o,defaultInputModes:[...Nt(t.defaultInputModes,"agentCard.defaultInputModes")],defaultOutputModes:[...Nt(t.defaultOutputModes,"agentCard.defaultOutputModes")],skills:Nt(t.skills,"agentCard.skills").map(lo)};return n.length>0&&(p.additionalInterfaces=n),t.provider&&(p.provider=no(t.provider)),t.documentationUrl!==void 0&&t.documentationUrl!==""&&(p.documentationUrl=t.documentationUrl),t.iconUrl!==void 0&&t.iconUrl!==""&&(p.iconUrl=t.iconUrl),d!==void 0&&(p.supportsAuthenticatedExtendedCard=d),c!==void 0&&(p.securitySchemes=c),t.securityRequirements&&t.securityRequirements.length>0&&(p.security=t.securityRequirements.map(oa)),t.signatures&&t.signatures.length>0&&(p.signatures=t.signatures.map(uo)),e?.embedV1Interfaces&&r.length>0&&(p.supportedInterfaces=structuredClone(r)),p}function la(t){if(dr(t))return{code:t.envelopeCode,message:t.message,...t.data!==void 0?{data:t.data}:{}};if(t instanceof W)return{code:se[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 co=Object.freeze({unknown:0,submitted:1,working:2,completed:3,failed:4,canceled:5,"input-required":6,rejected:7,"auth-required":8}),fo=new Map(Object.entries(co).map(([t,e])=>[e,t]));function ho(t){return fo.get(t)??"unknown"}function po(t){return t==="user"?1:t==="agent"?2:0}function So(t){return t===1?"user":"agent"}var Ze="data_part_compat";function da(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!Buffer.isBuffer(t)}function To(t){if(t===null||Array.isArray(t))return!0;let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function go(t){if(typeof t!="object"||t===null||Array.isArray(t))throw S.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 S.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[Ze]===!0&&(da(t.data)&&"value"in t.data&&(r=t.data.value),delete e[Ze],i=Object.keys(e).length>0?e:void 0),{content:{$case:"data",value:r},metadata:i,filename:"",mediaType:""}}throw S.invalidParams(`Invalid v0.3 part kind: ${t.kind??"undefined"}`)}function ua(t){let e=t.content,r=$(t.metadata);if(!e)throw S.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(da(i)){let a={kind:"data",data:i};return r!==void 0&&(a.metadata=r),a}if(To(i)){let a={value:i},n=r??{};return n[Ze]=!0,{kind:"data",data:a,metadata:n}}throw S.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 S.invalidParams(`Invalid v1.0 part content type: ${e.$case??"unknown"}`)}function yi(t){return t==null||t===""?void 0:t}function ki(t){return t==null||t.length===0?void 0:[...t]}function mo(t){if(typeof t!="object"||t===null)throw S.invalidParams("message must be an object");if(typeof t.messageId!="string"||t.messageId==="")throw S.invalidParams("message.messageId is required");if(t.role!=="user"&&t.role!=="agent")throw S.invalidParams('message.role must be "user" or "agent"');if(!Array.isArray(t.parts))throw S.invalidParams("message.parts must be an array");return{messageId:t.messageId,contextId:t.contextId??"",taskId:t.taskId??"",role:po(t.role),parts:t.parts.map(go),metadata:$(t.metadata),extensions:t.extensions?[...t.extensions]:[],referenceTaskIds:t.referenceTaskIds?[...t.referenceTaskIds]:[]}}function wt(t){let e={kind:"message",messageId:t.messageId,role:So(t.role),parts:Nt(t.parts,"message.parts").map(ua)},r=yi(t.contextId);r!==void 0&&(e.contextId=r);let i=yi(t.taskId);i!==void 0&&(e.taskId=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=ki(t.extensions);n!==void 0&&(e.extensions=n);let o=ki(t.referenceTaskIds);return o!==void 0&&(e.referenceTaskIds=o),e}function be(t){return t!==void 0&&t!==""?t:void 0}function ca(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 No(t){let e={schemes:t.scheme!==""?[t.scheme]:[]},r=be(t.credentials);return r!==void 0&&(e.credentials=r),e}function Eo(t,e=""){return{tenant:e,taskId:"",id:t.id??"",url:t.url,token:t.token??"",authentication:t.authentication?ca(t.authentication):void 0}}function Oo(t){let e={url:t.url},r=be(t.id);r!==void 0&&(e.id=r);let i=be(t.token);return i!==void 0&&(e.token=i),t.authentication&&(e.authentication=No(t.authentication)),e}function fa(t,e=""){return{tenant:e,taskId:t.taskId,id:t.pushNotificationConfig.id??"",url:t.pushNotificationConfig.url,token:t.pushNotificationConfig.token??"",authentication:t.pushNotificationConfig.authentication?ca(t.pushNotificationConfig.authentication):void 0}}function Et(t){return{taskId:t.taskId,pushNotificationConfig:Oo(t)}}function Ai(t){return t==null||t===""?void 0:t}function vo(t){return t==null||t.length===0?void 0:[...t]}function ha(t){let e={artifactId:t.artifactId,parts:Nt(t.parts,"artifact.parts").map(ua)},r=Ai(t.name);r!==void 0&&(e.name=r);let i=Ai(t.description);i!==void 0&&(e.description=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=vo(t.extensions);return n!==void 0&&(e.extensions=n),e}var _o=new Set(["completed","canceled","failed","rejected"]);function pa(t){let e={state:ho(t.state)};return t.message&&(e.message=wt(t.message)),t.timestamp!==void 0&&t.timestamp!==""&&(e.timestamp=t.timestamp),e}function ut(t){let e={kind:"task",id:t.id,contextId:t.contextId,status:t.status?pa(t.status):{state:"unknown"}};t.history&&t.history.length>0&&(e.history=t.history.map(wt)),t.artifacts&&t.artifacts.length>0&&(e.artifacts=t.artifacts.map(ha));let r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function yo(t){let e=t.status?pa(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 ko(t){if(!t.artifact)throw S.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");let e={kind:"artifact-update",taskId:t.taskId,contextId:t.contextId,artifact:ha(t.artifact),append:t.append,lastChunk:t.lastChunk},r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function Ao(t){return{acceptedOutputModes:t.acceptedOutputModes?[...t.acceptedOutputModes]:[],taskPushNotificationConfig:t.pushNotificationConfig?Eo(t.pushNotificationConfig):void 0,historyLength:t.historyLength,returnImmediately:t.blocking===void 0?!0:!t.blocking}}function Zt(t,e=""){return{tenant:e,message:mo(t.params.message),configuration:t.params.configuration?Ao(t.params.configuration):void 0,metadata:$(t.params.metadata)}}function Sa(t,e=null){let r=t.payload;if(!r)throw S.internalError("StreamResponse missing payload");let i;switch(r.$case){case"message":i=wt(r.value);break;case"task":i=ut(r.value);break;case"statusUpdate":i=yo(r.value);break;case"artifactUpdate":i=ko(r.value);break;default:throw S.internalError("StreamResponse has unknown payload case")}return{id:e,jsonrpc:"2.0",result:i}}function Io(t,e=""){return{tenant:e,id:t.params.id,historyLength:t.params.historyLength}}function Ro(t,e=""){return{tenant:e,id:t.params.id,metadata:$(t.params.metadata)}}function Co(t,e=""){return{tenant:e,id:t.params.id}}function Uo(t,e=""){return fa(t.params,e)}function Jo(t,e=""){let r=t.params,i="pushNotificationConfigId"in r?r.pushNotificationConfigId:void 0;return{tenant:e,taskId:r.id,id:i??""}}function wo(t,e=""){return{tenant:e,taskId:t.params.id,id:t.params.pushNotificationConfigId}}function xo(t,e=""){return{tenant:e,taskId:t.params.id,pageSize:0,pageToken:""}}function Po(t,e=null){return{id:e,jsonrpc:"2.0",result:t.configs.map(r=>Et(r))}}function Do(t,e=""){return{tenant:e}}var Ii=class je{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 S.invalidRequest("Invalid request body type.");if(!this.isRequestValid(i))throw S.invalidRequest("Invalid JSON-RPC Request.")}catch(o){let d=je.mapToLegacyJSONRPCError(o instanceof SyntaxError?S.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 S.invalidParams("Invalid method parameters.");if(a==="message/stream"||a==="tasks/resubscribe"){if(!(await this.requestHandler.getAgentCard()).capabilities?.streaming)throw S.unsupportedOperation(`Method ${a} requires streaming capability.`);let c=a==="message/stream"?this.requestHandler.sendMessageStream(Zt(i),r):this.requestHandler.resubscribe(Co(i),r);return(async function*(){for await(let p of c)yield Sa(p,n)})()}let o;switch(a){case"message/send":{let d=await this.requestHandler.sendMessage(Zt(i),r);o="messageId"in d?wt(d):ut(d);break}case"tasks/get":o=ut(await this.requestHandler.getTask(Io(i),r));break;case"tasks/cancel":o=ut(await this.requestHandler.cancelTask(Ro(i),r));break;case"tasks/pushNotificationConfig/set":o=Et(await this.requestHandler.createTaskPushNotificationConfig(Uo(i),r));break;case"tasks/pushNotificationConfig/get":o=Et(await this.requestHandler.getTaskPushNotificationConfig(Jo(i),r));break;case"tasks/pushNotificationConfig/list":{o=Po(await this.requestHandler.listTaskPushNotificationConfigs(xo(i),r),n).result;break}case"tasks/pushNotificationConfig/delete":await this.requestHandler.deleteTaskPushNotificationConfig(wo(i),r),o=null;break;case"agent/getAuthenticatedExtendedCard":o=pr(await this.requestHandler.getAuthenticatedExtendedAgentCard(Do(i),r));break;default:throw S.methodNotFound(a)}return{jsonrpc:"2.0",id:n,result:o}}catch(o){return{jsonrpc:"2.0",id:n,error:je.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 la(e)}},Mo={[-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 Ri(t){if(dr(t)){let e=Mo[t.envelopeCode];if(e!==void 0)return e}return Ht(t)}function Ot(t){return la(t)}var Lo=class Kt{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 pr(r)}validateMessageSendParams(e){if(!e.message)throw S.invalidParams("message is required");if(!e.message.messageId)throw S.invalidParams("message.messageId is required")}async sendMessage(e,r){this.validateMessageSendParams(e);let i=Zt(Ci(e,"message/send"),r.tenant??""),a=await this.requestHandler.sendMessage(i,r);return"messageId"in a?wt(a):ut(a)}async sendMessageStream(e,r){await this.requireCapability("streaming"),this.validateMessageSendParams(e);let i=Zt(Ci(e,"message/stream"),r.tenant??""),a=this.requestHandler.sendMessageStream(i,r);return Kt.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 ut(n)}async cancelTask(e,r){let i=await this.requestHandler.cancelTask({id:e,tenant:r.tenant??"",metadata:{}},r);return ut(i)}async resubscribe(e,r){await this.requireCapability("streaming");let i=this.requestHandler.resubscribe({id:e,tenant:r.tenant??""},r);return Kt.translateStream(i)}async setTaskPushNotificationConfig(e,r){if(await this.requireCapability("pushNotifications"),!e.taskId)throw S.invalidParams("taskId is required");if(!e.pushNotificationConfig)throw S.invalidParams("pushNotificationConfig is required");let i=fa(e,r.tenant??""),a=await this.requestHandler.createTaskPushNotificationConfig(i,r);return Et(a)}async listTaskPushNotificationConfigs(e,r){return(await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:r.tenant??""},r)).configs.map(a=>Et(a))}async getTaskPushNotificationConfig(e,r,i){let a=await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i);return Et(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 Sa(r,null).result}static CAPABILITY_ERRORS={streaming:()=>S.unsupportedOperation("Agent does not support streaming"),pushNotifications:()=>S.pushNotificationNotSupported()};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw Kt.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw S.invalidParams("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw S.invalidParams("historyLength must be a valid integer");if(r<0)throw S.invalidParams("historyLength must be non-negative");return r}static mapToLegacyHTTPError(e){return Ot(e)}};function Ci(t,e){return{jsonrpc:"2.0",id:0,method:e,params:t}}var bt="X-A2A-Extensions",Ct="application/json",Ta="message/send",ga="message/stream",ma="tasks/get",Na="tasks/cancel",Sr="tasks/resubscribe",Ea="tasks/pushNotificationConfig/set",Oa="tasks/pushNotificationConfig/get",va="tasks/pushNotificationConfig/list",_a="tasks/pushNotificationConfig/delete",ya="agent/getAuthenticatedExtendedCard",ka=Object.freeze({[Ta]:"SendMessage",[ga]:"SendStreamingMessage",[ma]:"GetTask",[Na]:"CancelTask",[Sr]:"SubscribeToTask",[Ea]:"CreateTaskPushNotificationConfig",[Oa]:"GetTaskPushNotificationConfig",[va]:"ListTaskPushNotificationConfigs",[_a]:"DeleteTaskPushNotificationConfig",[ya]:"GetExtendedAgentCard"}),jl=Object.freeze(Object.fromEntries(Object.entries(ka).map(([t,e])=>[e,t]))),Aa=Object.freeze({[Ta]:"SendMessage",[ga]:"SendStreamingMessage",[ma]:"GetTask",[Na]:"CancelTask",[Sr]:"TaskSubscription",[Ea]:"CreateTaskPushNotificationConfig",[Oa]:"GetTaskPushNotificationConfig",[va]:"ListTaskPushNotificationConfig",[_a]:"DeleteTaskPushNotificationConfig",[ya]:"GetAgentCard"}),td=Object.freeze(Object.fromEntries(Object.entries(Aa).map(([t,e])=>[e,t]))),$o=Object.freeze(Object.fromEntries(Object.entries(Aa).map(([t,e])=>[e,ka[t]]))),ed=Object.freeze(Object.fromEntries(Object.entries($o).map(([t,e])=>[e,t])));function Ia(t){let e=new We(t.requestHandler),r=t.legacyCompat?.enabled?new Ii(t.requestHandler):void 0,i=Ge.default.Router();return i.use(zo),i.use(Ge.default.json(),qo),i.post("/",async(a,n)=>{let o=r!==void 0&&(a.header(it)||_t)===_t,d=o?Ii.mapToLegacyJSONRPCError:We.mapToJSONRPCError;try{let c=await t.userBuilder(a),T=a.header(it)||void 0,p=o?a.header(bt)??a.header(mt):a.header(mt),u=(t.contextBuilder??cr)({extensions:ae.parseServiceParameter(p),user:c,headers:a.headers,requestedVersion:T}),N=await t.requestHandler.getAgentCard();fr(u.requestedVersion,N,"JSONRPC");let g=await(o?r:e).handle(a.body,u);if(u.activatedExtensions&&n.setHeader(o?bt:mt,Array.from(u.activatedExtensions)),typeof g?.[Symbol.asyncIterator]=="function"){let y=g;if(o&&a.body?.method===Sr){Object.entries(Wt).forEach(([m,k])=>{n.setHeader(m,k)}),n.flushHeaders();try{for await(let m of y)n.write(dt(m))}catch(m){console.error(`Error during SSE streaming (request ${a.body?.id}):`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.writableEnded||n.write(Xt(k))}finally{n.writableEnded||n.end()}return}let f=y[Symbol.asyncIterator](),E;try{E=await f.next()}catch(m){console.error(`Pre-stream error for request ${a.body?.id}:`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.status(200).json(k);return}Object.entries(Wt).forEach(([m,k])=>{n.setHeader(m,k)}),n.flushHeaders();try{E.done||n.write(dt(E.value));for await(let m of ir(f))n.write(dt(m))}catch(m){console.error(`Error during SSE streaming (request ${a.body?.id}):`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.headersSent?n.write(Xt(k)):n.status(500).json(k)}finally{n.writableEnded||n.end()}}else{let y=g;n.status(200).json(y)}}catch(c){console.error("Unhandled error in JSON-RPC POST handler:",c);let T=d(c),p={jsonrpc:"2.0",id:a.body?.id||null,error:T};if(n.headersSent)n.writableEnded||n.end();else{let v=T.code===U.INTERNAL_ERROR;n.status(v?500:200).json(p)}}}),i}var zo=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}if(i.split(";",1)[0].trim().toLowerCase()===nr){r();return}let n={jsonrpc:"2.0",id:null,error:We.mapToJSONRPCError(new or(`Unsupported Content-Type "${i}"; expected application/json.`))};e.status(200).json(n)},qo=(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 Ho(t){return`W/"${Bo.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function Ko(t){let e=Ca.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)||_t;hr(d)?o():o("router")}),e.get("/",async(a,n)=>{try{let o=await i(),d;try{d=pr(o,{embedV1Interfaces:!0})}catch(p){if(p instanceof ne){n.append("Vary",it),n.status(O.BAD_REQUEST).setHeader("Content-Type",Ct).json(Ot(p));return}throw p}let c=JSON.stringify(d),T=Ho(c);if(n.setHeader("ETag",T),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",Ct),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",Ct).json({error:"Failed to retrieve agent card"})}}),e}function Vo(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 Go(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 Qo(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 Yo(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Ui={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)?vt.fromJSON(t.pushNotification):l(t.push_notification)?vt.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=vt.toJSON(t.pushNotification)),t.historyLength!==0&&(e.historyLength=Math.round(t.historyLength)),t.blocking!==!1&&(e.blocking=t.blocking),e}},Ut={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)?jt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ee.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=jt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ee.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>z.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},jt={fromJSON(t){return{state:l(t.state)?Vo(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=Go(t.state)),t.update!==void 0&&(e.message=z.toJSON(t.update)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},te={fromJSON(t){return{part:l(t.text)?{$case:"text",value:globalThis.String(t.text)}:l(t.file)?{$case:"file",value:Ji.fromJSON(t.file)}:l(t.data)?{$case:"data",value:wi.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=Ji.toJSON(t.part.value):t.part?.$case==="data"&&(e.data=wi.toJSON(t.part.value)),e}},Ji={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(Hi(t.fileWithBytes))}:l(t.file_with_bytes)?{$case:"fileWithBytes",value:Buffer.from(Hi(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=tl(t.file.value)),t.mimeType!==""&&(e.mimeType=t.mimeType),e}},wi={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)?Qo(t.role):0,content:globalThis.Array.isArray(t?.content)?t.content.map(e=>te.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=Yo(t.role)),t.content?.length&&(e.content=t.content.map(r=>te.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ee={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=>te.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=>te.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Pe={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)?jt.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=jt.toJSON(t.status)),t.final!==!1&&(e.final=t.final),t.metadata!==void 0&&(e.metadata=t.metadata),e}},De={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)?ee.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=ee.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}},vt={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)?xi.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=xi.toJSON(t.authentication)),e}},xi={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}},Me={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}},Wo={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=>Me.fromJSON(e)):globalThis.Array.isArray(t?.additional_interfaces)?t.additional_interfaces.map(e=>Me.fromJSON(e)):[],provider:l(t.provider)?Pi.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)?Di.fromJSON(t.capabilities):void 0,securitySchemes:x(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=Le.fromJSON(i),e),{}):x(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=Le.fromJSON(i),e),{}):{},security:globalThis.Array.isArray(t?.security)?t.security.map(e=>ie.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=>Li.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=>$i.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=>Me.toJSON(r))),t.provider!==void 0&&(e.provider=Pi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==""&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Di.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);r.length>0&&(e.securitySchemes={},r.forEach(([i,a])=>{e.securitySchemes[i]=Le.toJSON(a)}))}return t.security?.length&&(e.security=t.security.map(r=>ie.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=>Li.toJSON(r))),t.supportsAuthenticatedExtendedCard!==!1&&(e.supportsAuthenticatedExtendedCard=t.supportsAuthenticatedExtendedCard),t.signatures?.length&&(e.signatures=t.signatures.map(r=>$i.toJSON(r))),e}},Pi={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}},Di={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=>Mi.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=>Mi.toJSON(r))),e}},Mi={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}},Li={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=>ie.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=>ie.toJSON(r))),e}},$i={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}},re={fromJSON(t){return{name:l(t.name)?globalThis.String(t.name):"",pushNotificationConfig:l(t.pushNotificationConfig)?vt.fromJSON(t.pushNotificationConfig):l(t.push_notification_config)?vt.fromJSON(t.push_notification_config):void 0}},toJSON(t){let e={};return t.name!==""&&(e.name=t.name),t.pushNotificationConfig!==void 0&&(e.pushNotificationConfig=vt.toJSON(t.pushNotificationConfig)),e}},zi={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}},ie={fromJSON(t){return{schemes:x(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=zi.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]=zi.toJSON(a)}))}return e}},Le={fromJSON(t){return{scheme:l(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:$e.fromJSON(t.apiKeySecurityScheme)}:l(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:$e.fromJSON(t.api_key_security_scheme)}:l(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:ze.fromJSON(t.httpAuthSecurityScheme)}:l(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:ze.fromJSON(t.http_auth_security_scheme)}:l(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:qe.fromJSON(t.oauth2SecurityScheme)}:l(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:qe.fromJSON(t.oauth2_security_scheme)}:l(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Fe.fromJSON(t.openIdConnectSecurityScheme)}:l(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Fe.fromJSON(t.open_id_connect_security_scheme)}:l(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Be.fromJSON(t.mtlsSecurityScheme)}:l(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Be.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=$e.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=ze.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=qe.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Fe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Be.toJSON(t.scheme.value)),e}},$e={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}},ze={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}},qe={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",flows:l(t.flows)?qi.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=qi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Fe={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}},Be={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},qi={fromJSON(t){return{flow:l(t.authorizationCode)?{$case:"authorizationCode",value:He.fromJSON(t.authorizationCode)}:l(t.authorization_code)?{$case:"authorizationCode",value:He.fromJSON(t.authorization_code)}:l(t.clientCredentials)?{$case:"clientCredentials",value:Ke.fromJSON(t.clientCredentials)}:l(t.client_credentials)?{$case:"clientCredentials",value:Ke.fromJSON(t.client_credentials)}:l(t.implicit)?{$case:"implicit",value:Fi.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=He.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Ke.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Fi.toJSON(t.flow.value):t.flow?.$case==="password"&&(e.password=Bi.toJSON(t.flow.value)),e}},He={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}},Ke={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}},Fi={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}},Xo={fromJSON(t){return{request:l(t.message)?z.fromJSON(t.message):l(t.request)?z.fromJSON(t.request):void 0,configuration:l(t.configuration)?Ui.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=Ui.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Zo={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:Ut.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=Ut.toJSON(t.payload.value):t.payload?.$case==="msg"&&(e.message=z.toJSON(t.payload.value)),e}},bo={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:Ut.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:Pe.fromJSON(t.statusUpdate)}:l(t.status_update)?{$case:"statusUpdate",value:Pe.fromJSON(t.status_update)}:l(t.artifactUpdate)?{$case:"artifactUpdate",value:De.fromJSON(t.artifactUpdate)}:l(t.artifact_update)?{$case:"artifactUpdate",value:De.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=Ut.toJSON(t.payload.value):t.payload?.$case==="msg"?e.message=z.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Pe.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=De.toJSON(t.payload.value)),e}},jo={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>re.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=>re.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function Hi(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function tl(t){return globalThis.Buffer.from(t).toString("base64")}function x(t){return typeof t=="object"&&t!==null}function l(t){return t!=null}var el=/^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/,rl=/^tasks\/([^/]+)(?:\/|$)/,At=t=>{let e=t.match(rl);if(!e)throw S.invalidParams(`Invalid or missing task ID in: "${t}"`);return e[1]},It=t=>`tasks/${t}`,Ki=t=>{let e=t.match(el);if(!e)throw S.invalidParams(`Invalid or missing config ID in: "${t}"`);return{taskId:e[1],configId:e[2]}},Ve=(t,e)=>`tasks/${t}/pushNotificationConfigs/${e}`,Vi=class A{static taskQueryParams(e){return{id:At(e.name),historyLength:e.historyLength}}static taskIdParams(e){return{id:At(e.name)}}static getTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Ki(e.name);return{id:r,pushNotificationConfigId:i}}static listTaskPushNotificationConfigParams(e){return{id:At(e.parent)}}static createTaskPushNotificationConfig(e){if(!e.config?.pushNotificationConfig)throw S.invalidParams("Request must include a `config` object with a `pushNotificationConfig`");return{taskId:At(e.parent),pushNotificationConfig:A.pushNotificationConfig(e.config.pushNotificationConfig)}}static deleteTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Ki(e.name);return{id:r,pushNotificationConfigId:i}}static message(e){if(e)return{kind:"message",messageId:e.messageId,parts:e.content.map(r=>A.part(r)),contextId:e.contextId||void 0,taskId:e.taskId||void 0,role:A.role(e.role),metadata:e.metadata,extensions:e.extensions}}static role(e){switch(e){case 2:return"agent";case 1:return"user";default:throw S.invalidParams(`Invalid role: ${e}`)}}static messageSendConfiguration(e){if(e)return{blocking:e.blocking,acceptedOutputModes:e.acceptedOutputModes,pushNotificationConfig:A.pushNotificationConfig(e.pushNotification)}}static pushNotificationConfig(e){if(e)return{id:e.id,url:e.url,token:e.token||void 0,authentication:A.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 S.invalidParams("Invalid file part type")}if(e.part?.$case==="data")return{kind:"data",data:e.part.value.data??{}};throw S.invalidParams("Invalid part type")}static messageSendParams(e){if(!e.request)throw S.invalidParams("SendMessageRequest missing message");return{message:A.message(e.request),configuration:A.messageSendConfiguration(e.configuration),metadata:e.metadata}}static sendMessageResult(e){if(e.payload?.$case==="task")return A.task(e.payload.value);if(e.payload?.$case==="msg")return A.message(e.payload.value);throw S.invalidParams("Invalid SendMessageResponse: missing result")}static task(e){if(!e.status)throw S.internalError("Task missing status");return{kind:"task",id:e.id,status:A.taskStatus(e.status),contextId:e.contextId,artifacts:e.artifacts?.map(r=>A.artifact(r)),history:e.history?.map(r=>A.message(r)),metadata:e.metadata}}static taskStatus(e){return{message:A.message(e.update),state:A.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 S.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=>A.part(r)),metadata:e.metadata}}static taskPushNotificationConfig(e){if(!e.pushNotificationConfig)throw S.invalidParams("TaskPushNotificationConfig missing pushNotificationConfig");return{taskId:At(e.name),pushNotificationConfig:A.pushNotificationConfig(e.pushNotificationConfig)}}static listTaskPushNotificationConfig(e){return e.configs.map(r=>A.taskPushNotificationConfig(r))}static agentCard(e){return{additionalInterfaces:e.additionalInterfaces?.map(r=>A.agentInterface(r)),capabilities:e.capabilities?A.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?A.agentProvider(e.provider):void 0,protocolVersion:e.protocolVersion,security:e.security?.map(r=>A.security(r)),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,A.securityScheme(i)])):{},skills:e.skills.map(r=>A.skills(r)),signatures:e.signatures?.map(r=>A.agentCardSignature(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard,url:e.url,version:e.version}}static agentCapabilities(e){return{extensions:e.extensions?.map(r=>A.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 S.internalError("OAuth2 security scheme missing flows");return{type:"oauth2",description:e.scheme.value.description||void 0,flows:A.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 S.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 S.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=>A.security(r))}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static taskStatusUpdateEvent(e){if(!e.status)throw S.invalidParams("Invalid TaskStatusUpdateEvent: missing status");return{kind:"status-update",taskId:e.taskId,status:A.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){if(!e.artifact)throw S.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");return{kind:"artifact-update",taskId:e.taskId,artifact:A.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,lastChunk:e.lastChunk}}static messageStreamResult(e){switch(e.payload?.$case){case"msg":return A.message(e.payload.value);case"task":return A.task(e.payload.value);case"statusUpdate":return A.taskStatusUpdateEvent(e.payload.value);case"artifactUpdate":return A.taskArtifactUpdateEvent(e.payload.value);default:throw S.internalError("Invalid event type in StreamResponse")}}},Tt=class I{static agentCard(e){return{protocolVersion:e.protocolVersion,name:e.name,description:e.description,url:e.url,preferredTransport:e.preferredTransport??"",additionalInterfaces:e.additionalInterfaces?.map(r=>I.agentInterface(r))??[],provider:I.agentProvider(e.provider),version:e.version,documentationUrl:e.documentationUrl??"",capabilities:I.agentCapabilities(e.capabilities),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,I.securityScheme(i)])):{},security:e.security?.map(r=>I.security(r))??[],defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,skills:e.skills.map(r=>I.agentSkill(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard??!1,signatures:e.signatures?.map(r=>I.agentCardSignature(r))??[]}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static agentSkill(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags??[],examples:e.examples??[],inputModes:e.inputModes??[],outputModes:e.outputModes??[],security:e.security?e.security.map(r=>I.security(r)):[]}}static security(e){return{schemes:Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{list:i}]))}}static securityScheme(e){switch(e.type){case"apiKey":return{scheme:{$case:"apiKeySecurityScheme",value:{name:e.name,location:e.in,description:e.description??""}}};case"http":return{scheme:{$case:"httpAuthSecurityScheme",value:{description:e.description??"",scheme:e.scheme,bearerFormat:e.bearerFormat??""}}};case"mutualTLS":return{scheme:{$case:"mtlsSecurityScheme",value:{description:e.description??""}}};case"oauth2":return{scheme:{$case:"oauth2SecurityScheme",value:{description:e.description??"",flows:I.oauthFlows(e.flows),oauth2MetadataUrl:e.oauth2MetadataUrl??""}}};case"openIdConnect":return{scheme:{$case:"openIdConnectSecurityScheme",value:{description:e.description??"",openIdConnectUrl:e.openIdConnectUrl}}};default:throw S.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 S.internalError("Unsupported OAuth flows")}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){if(e)return{url:e.url,organization:e.organization}}static agentCapabilities(e){return e?{streaming:e.streaming??!1,pushNotifications:e.pushNotifications??!1,extensions:e.extensions?e.extensions.map(r=>I.agentExtension(r)):[]}:{streaming:!1,pushNotifications:!1,extensions:[]}}static agentExtension(e){return{uri:e.uri,description:e.description??"",required:e.required??!1,params:e.params}}static listTaskPushNotificationConfig(e){return{configs:e.map(r=>I.taskPushNotificationConfig(r)),nextPageToken:""}}static getTaskPushNotificationConfigParams(e){return{name:Ve(e.id,e.pushNotificationConfigId??"")}}static listTaskPushNotificationConfigParams(e){return{parent:It(e.id),pageToken:"",pageSize:0}}static deleteTaskPushNotificationConfigParams(e){return{name:Ve(e.id,e.pushNotificationConfigId)}}static taskPushNotificationConfig(e){return{name:Ve(e.taskId,e.pushNotificationConfig.id??""),pushNotificationConfig:I.pushNotificationConfig(e.pushNotificationConfig)}}static taskPushNotificationConfigCreate(e){return{parent:It(e.taskId),config:I.taskPushNotificationConfig(e),configId:e.pushNotificationConfig.id??""}}static pushNotificationConfig(e){if(e)return{id:e.id??"",url:e.url,token:e.token??"",authentication:I.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials??""}}static messageStreamResult(e){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}};if(e.kind==="status-update")return{payload:{$case:"statusUpdate",value:I.taskStatusUpdateEvent(e)}};if(e.kind==="artifact-update")return{payload:{$case:"artifactUpdate",value:I.taskArtifactUpdateEvent(e)}};throw S.internalError("Invalid event type")}static taskStatusUpdateEvent(e){return{taskId:e.taskId,status:I.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){return{taskId:e.taskId,artifact:I.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,append:e.append??!1,lastChunk:e.lastChunk??!1}}static messageSendResult(e){if(e.kind){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}}}}static message(e){if(e)return{messageId:e.messageId,content:e.parts.map(r=>I.part(r)),contextId:e.contextId??"",taskId:e.taskId??"",role:I.role(e.role),metadata:e.metadata,extensions:e.extensions??[]}}static role(e){switch(e){case"agent":return 2;case"user":return 1;default:throw S.internalError("Invalid role")}}static task(e){return{id:e.id,contextId:e.contextId,status:I.taskStatus(e.status),artifacts:e.artifacts?.map(r=>I.artifact(r))??[],history:e.history?.map(r=>I.message(r)).filter(r=>!!r)??[],metadata:e.metadata}}static taskStatus(e){return{state:I.taskState(e.state),update:I.message(e.message),timestamp:e.timestamp}}static artifact(e){return{artifactId:e.artifactId,name:e.name??"",description:e.description??"",parts:e.parts.map(r=>I.part(r)),metadata:e.metadata,extensions:e.extensions?e.extensions:[]}}static taskState(e){switch(e){case"submitted":return 1;case"working":return 2;case"input-required":return 6;case"rejected":return 7;case"auth-required":return 8;case"completed":return 3;case"failed":return 4;case"canceled":return 5;case"unknown":return 0;default:return-1}}static part(e){if(e.kind==="text")return{part:{$case:"text",value:e.text}};if(e.kind==="file"){let r;if("uri"in e.file)r={file:{$case:"fileWithUri",value:e.file.uri},mimeType:e.file.mimeType??""};else if("bytes"in e.file)r={file:{$case:"fileWithBytes",value:Buffer.from(e.file.bytes,"base64")},mimeType:e.file.mimeType??""};else throw S.internalError("Invalid file part");return{part:{$case:"file",value:r}}}if(e.kind==="data")return{part:{$case:"data",value:{data:e.data}}};throw S.internalError("Invalid part type")}static messageSendParams(e){return{request:I.message(e.message),configuration:I.configuration(e.configuration),metadata:e.metadata}}static configuration(e){if(e)return{blocking:e.blocking??!1,acceptedOutputModes:e.acceptedOutputModes??[],pushNotification:I.pushNotificationConfig(e.pushNotificationConfig),historyLength:e.historyLength??0}}static taskQueryParams(e){return{name:It(e.id),historyLength:e.historyLength??0}}static cancelTaskRequest(e){return{name:It(e.id)}}static taskIdParams(e){return{name:It(e.id)}}static getAgentCardRequest(){return{}}},il=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(O.BAD_REQUEST).json(Ot(S.parseError("Invalid JSON payload.")));i(t)};function al(t){let e=tr.default.Router(),r=new Lo(t.requestHandler);e.use((f,E,m)=>{let k=f.header(it)||_t;hr(k)?m():m("router")}),e.use((f,E,m)=>{E.setHeader("Content-Type",Ct),m()},tr.default.json({type:Ct,strict:!1}),il);let i=async f=>{let E=await t.userBuilder(f),m=f.header(it)||_t,D=(t.contextBuilder??cr)({extensions:ae.parseServiceParameter(f.header(bt)??f.header(mt)),user:E,headers:f.headers,requestedVersion:m,tenant:f.params.tenant||void 0}),B=await r.getAgentCard();return fr(D.requestedVersion,B,"HTTP+JSON"),D},a=(f,E)=>{E.activatedExtensions&&f.setHeader(bt,Array.from(E.activatedExtensions))},n=(f,E,m,k)=>{a(f,m),f.status(E),E===O.NO_CONTENT?f.end():f.json(k)},o=f=>{let E=Tt.messageSendResult(f);if(!E)throw S.internalError("sendMessage produced no result.");return Zo.toJSON(E)},d=f=>Ut.toJSON(Tt.task(f)),c=f=>re.toJSON(Tt.taskPushNotificationConfig(f)),T=f=>Wo.toJSON(Tt.agentCard(f)),p=f=>jo.toJSON({configs:f.map(E=>Tt.taskPushNotificationConfig(E)),nextPageToken:""}),v=f=>{let E=Xo.fromJSON(f??{});return Vi.messageSendParams(E)},u=f=>{let E=re.fromJSON(f??{});return Vi.taskPushNotificationConfig(E)},N=f=>{let E=Tt.messageStreamResult(f);if(!E)throw S.internalError("Stream produced an unrepresentable event.");return bo.toJSON(E)},h=async(f,E,m)=>{let k=E[Symbol.asyncIterator](),D;try{D=await k.next()}catch(B){a(f,m);let ue=Ri(B);f.status(ue).json(Ot(B));return}Object.entries(Wt).forEach(([B,ue])=>{f.setHeader(B,ue)}),a(f,m),f.flushHeaders();try{D.done||f.write(dt(N(D.value)));for await(let B of ir(k))f.write(dt(N(B)))}catch(B){console.error("Legacy SSE streaming error:",B),f.writableEnded||f.write(Xt(Ot(B)))}finally{f.writableEnded||f.end()}},g=(f,E)=>{if(f.headersSent){f.writableEnded||f.end();return}let m=Ri(E);f.status(m).json(Ot(E))},y=f=>async(E,m)=>{try{await f(E,m)}catch(k){g(m,k)}};e.get("/v1/card",y(async(f,E)=>{let m=await i(f),k=await r.getAuthenticatedExtendedAgentCard(m);n(E,O.OK,m,T(k))})),e.post("/v1/message\\:send",y(async(f,E)=>{let m=await i(f),k=v(f.body),D=await r.sendMessage(k,m);n(E,O.CREATED,m,o(D))})),e.post("/v1/message\\:stream",y(async(f,E)=>{let m=await i(f),k=v(f.body),D=await r.sendMessageStream(k,m);await h(E,D,m)})),e.post("/v1/tasks/:taskId\\:cancel",y(async(f,E)=>{let m=await i(f),k=await r.cancelTask(f.params.taskId,m);n(E,O.OK,m,d(k))}));let C=y(async(f,E)=>{let m=await i(f),k=await r.resubscribe(f.params.taskId,m);await h(E,k,m)});return e.get("/v1/tasks/:taskId\\:subscribe",C),e.post("/v1/tasks/:taskId\\:subscribe",C),e.get("/v1/tasks/:taskId",y(async(f,E)=>{let m=await i(f),k=f.query.historyLength??f.query.history_length,D=await r.getTask(f.params.taskId,m,k);n(E,O.OK,m,d(D))})),e.post("/v1/tasks/:taskId/pushNotificationConfigs",y(async(f,E)=>{let m=await i(f),k=u(f.body),D=await r.setTaskPushNotificationConfig(k,m);n(E,O.CREATED,m,c(D))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs",y(async(f,E)=>{let m=await i(f),k=await r.listTaskPushNotificationConfigs(f.params.taskId,m);n(E,O.OK,m,p(k))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs/:configId",y(async(f,E)=>{let m=await i(f),k=await r.getTaskPushNotificationConfig(f.params.taskId,f.params.configId,m);n(E,O.OK,m,c(k))})),e.delete("/v1/tasks/:taskId/pushNotificationConfigs/:configId",y(async(f,E)=>{let m=await i(f);await r.deleteTaskPushNotificationConfig(f.params.taskId,f.params.configId,m),n(E,O.NO_CONTENT,m)})),e}function nl(t){return`W/"${Fo.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function Ua(t){let e=Ra.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(Ko(t)),e.get("/",async(a,n)=>{try{let o=await i(),d=JSON.stringify(o),c=nl(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 Ja(t){return t==="true"||t===!0}var sl=class wa{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?ar(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:Ja(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 sr};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw wa.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}},ol=class{static messageSendResult(t){if("messageId"in t)return{payload:{$case:"message",value:t}};if("artifacts"in t)return{payload:{$case:"task",value:t}};throw new W("Invalid SendMessageResult type")}},ll=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(400).json(Rt(new L("Invalid JSON payload."),400));i(t)},dl=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}let a=i.split(";",1)[0].trim().toLowerCase();if(a===nr||a===Ye){r();return}let n=new or(`Unsupported Content-Type "${i}"; expected application/json or application/a2a+json.`);e.status(O.BAD_REQUEST).json(Rt(n,O.BAD_REQUEST))};function xa(t){let e=er.default.Router(),r=new sl(t.requestHandler);t.legacyCompat?.enabled&&e.use(al(t)),e.use((u,N,h)=>{N.setHeader("Content-Type",Ye),h()},dl,er.default.json({type:[nr,Ye],strict:!1}),ll);let i=async u=>{let N=await t.userBuilder(u),h=u.params.tenant||void 0,g=u.header(it)||void 0,C=(t.contextBuilder??cr)({extensions:ae.parseServiceParameter(u.header(mt)),user:N,headers:u.headers,requestedVersion:g,tenant:h}),f=await r.getAgentCard();return fr(C.requestedVersion,f,"HTTP+JSON"),C},a=(u,N)=>{N.activatedExtensions&&u.setHeader(mt,Array.from(N.activatedExtensions))},n=(u,N,h,g,y)=>{if(a(u,h),u.status(N),N===O.NO_CONTENT)u.end();else{if(!y||g===void 0)throw new Error("Bug: toJson serializer and body must be provided for non-204 responses.");u.json(y.toJSON(g))}},o=async(u,N,h)=>{let g=N[Symbol.asyncIterator](),y;try{y=await g.next()}catch(C){a(u,h);let f=Ht(C);u.status(f).json(Rt(C,f));return}Object.entries(Wt).forEach(([C,f])=>{u.setHeader(C,f)}),a(u,h),u.flushHeaders();try{if(!y.done){let C=Qe.toJSON(y.value);u.write(dt(C))}for await(let C of ir(g)){let f=Qe.toJSON(C);u.write(dt(f))}}catch(C){console.error("SSE streaming error:",C),u.writableEnded||u.write(Xt(Rt(C,Ht(C))))}finally{u.writableEnded||u.end()}},d=(u,N)=>{if(u.headersSent){u.writableEnded||u.end();return}let h=Ht(N);u.status(h).json(Rt(N,h))},c=u=>async(N,h)=>{try{await u(N,h)}catch(g){d(h,g)}},T=(u,N,h)=>{let g=u.params.tenant;if(!g){h();return}let y=u.body?.tenant;y&&y!==g&&console.warn(`Tenant mismatch: URL path tenant "${g}" differs from request body tenant "${y}". Using path tenant as the canonical value.`);let C=u.query?.tenant;C&&C!==g&&console.warn(`Tenant mismatch: URL path tenant "${g}" differs from query param tenant "${C}". Using path tenant as the canonical value.`),u.body&&(u.body.tenant=g),u.query.tenant=g,h()},p=(u,N,h)=>{e[u](N,c(h)),e[u](`/:tenant${N}`,T,c(h))};p("get","/extendedAgentCard",async(u,N)=>{let h=await i(u),g=await r.getAuthenticatedExtendedAgentCard({tenant:u.query.tenant||""},h);n(N,O.OK,h,g,Qi)}),p("post","/message\\:send",async(u,N)=>{let h=await i(u),g=Yt.fromJSON(u.body??{}),y=await r.sendMessage(g,h),C=ol.messageSendResult(y);n(N,O.OK,h,C,fs)}),p("post","/message\\:stream",async(u,N)=>{let h=await i(u),g=Yt.fromJSON(u.body??{}),y=await r.sendMessageStream(g,h);await o(N,y,h)});let v=async(u,N)=>{let h=await i(u),g=await r.resubscribe(u.params.taskId,h,u.query.tenant||"");await o(N,g,h)};return p("get","/tasks/:taskId\\:subscribe",v),p("post","/tasks/:taskId\\:subscribe",v),p("post","/tasks/:taskId\\:cancel",async(u,N)=>{let h=await i(u),g=await r.cancelTask(u.params.taskId,h,u.query.tenant||"");n(N,O.OK,h,g,G)}),p("get","/tasks/:taskId",async(u,N)=>{let h=await i(u),g=await r.getTask(u.params.taskId,h,u.query.historyLength,u.query.tenant||"");n(N,O.OK,h,g,G)}),p("get","/tasks",async(u,N)=>{let h=await i(u),g=await r.listTasks(u.query,h),y=Ja(u.query.includeArtifacts);n(N,O.OK,h,g,{...Yi,toJSON:C=>Xi(C,{includeArtifacts:y})})}),p("post","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let h=await i(u),g=Q.fromJSON({...u.body??{},taskId:u.params.taskId}),y=await r.createTaskPushNotificationConfig(g,h);n(N,O.CREATED,h,y,Q)}),p("get","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let h=await i(u),g=await r.listTaskPushNotificationConfigs(u.params.taskId,h,u.query.tenant||"");n(N,O.OK,h,g,Wi)}),p("get","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let h=await i(u),g=await r.getTaskPushNotificationConfig(u.params.taskId,u.params.configId,h,u.query.tenant||"");n(N,O.OK,h,g,Q)}),p("delete","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let h=await i(u);await r.deleteTaskPushNotificationConfig(u.params.taskId,u.params.configId,h,u.query.tenant||""),n(N,O.NO_CONTENT,h)}),e}var sn=ft(ht(),1);var Z="yukino",oe="permission-request",Pa="permission-response",Tr="thinking",gr="tool-call",mr="tool-result";var Da=`
10
- \u2026 [truncated]`;var Nr="No active run is awaiting a permission response.",Ma="Message must contain text or a yukino permission-response data part.",La="Session closed during initialization.",$a="Task canceled by user request.";function Er(t,e){return`Context ${t} is busy with task ${e}. Cancel it or wait for it to finish before sending a new message.`}function za(t){return`Permission responses must be sent with taskId "${t}".`}function qa(t){return`Unknown or already resolved permission id "${t}".`}var Fa="A2A context transcript is no longer available. Start a new context.",Ba="No provider configured.",Ha="A2A session capacity reached; retry when an active context finishes.",Ka="Invalid persisted A2A context mapping.",Va="A2A server must listen on a loopback address.",Ga="A2A server did not bind to a TCP address.",Or=18890,Qa=`127.0.0.1:${String(Or)}`,vr="/.well-known/agent-card.json",_r="1.0",Ya="a2a-contexts";var Wa="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.",Xa="Executes software engineering tasks: answering questions about a codebase, writing and refactoring code, running commands, and fixing bugs.",Za=["Fix the failing tests in this repository.","Add a dark mode toggle to the settings page."];function ba(t){return{name:"yukino",description:Wa,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:_r,tenant:""},{url:t,protocolBinding:"HTTP+JSON",protocolVersion:_r,tenant:""}],provider:void 0,version:Rr,capabilities:{streaming:!0,pushNotifications:!1,extensions:[]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],skills:[{id:"coding",name:"Coding",description:Xa,tags:["code","development","programming"],examples:Za,inputModes:["text/plain"],outputModes:["text/plain"],securityRequirements:[]}],signatures:[]}}import{createHash as Sl,randomUUID as nn}from"crypto";import{existsSync as Tl,renameSync as gl,rmSync as ml}from"fs";import{dirname as Nl}from"path";var F=(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))(F||{}),yr=(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))(yr||{});var md=4*1024*1024;import{randomUUID as ul}from"crypto";var yd=R.object({[Z]:R.literal(oe),permissionId:R.string(),toolCallId:R.string(),toolName:R.string(),reason:R.string(),args:R.record(R.string(),R.unknown())}),cl=R.object({[Z]:R.literal(Pa),permissionId:R.string(),decision:R.enum(["allow","deny","allowAlways"])}),kd=R.object({[Z]:R.literal(Tr),text:R.string()}),Ad=R.object({[Z]:R.literal(gr),toolCallId:R.string(),toolName:R.string(),args:R.record(R.string(),R.unknown())}),Id=R.object({[Z]:R.literal(mr),toolCallId:R.string(),toolName:R.string(),isError:R.boolean(),elapsed:R.number(),output:R.string()});function Pt(t){return{content:{$case:"text",value:t},metadata:void 0,filename:"",mediaType:"text/plain"}}function xt(t){return{content:{$case:"data",value:t},metadata:void 0,filename:"",mediaType:"application/json"}}function lt(t,e,r){return{messageId:ul(),contextId:e,taskId:t,role:yr.ROLE_AGENT,parts:r,metadata:void 0,extensions:[],referenceTaskIds:[]}}function tn(t,e){return{state:t,message:e,timestamp:new Date().toISOString()}}function ct(t,e,r,i){return{taskId:t,contextId:e,status:tn(r,i),metadata:void 0}}function le(t,e,r,i){return{id:t,contextId:e,status:tn(r,i),artifacts:[],history:[],metadata:void 0}}function en(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 fl(t){let e=[];for(let r of t.parts)r.content?.$case==="data"&&e.push(r.content.value);return e}function rn(t){for(let e of fl(t)){let r=cl.safeParse(e);if(r.success)return r.data}return null}function an(t,e,r){switch(t.type){case"stream_text":return lt(e,r,[Pt(t.text)]);case"thinking_text":return lt(e,r,[xt({[Z]:Tr,text:t.text})]);case"tool_use":return lt(e,r,[xt({[Z]:gr,toolCallId:t.toolId,toolName:t.toolName,args:t.args})]);case"tool_result":{let a=t.output.length>8e3?`${t.output.slice(0,8e3)}${Da}`:t.output;return lt(e,r,[xt({[Z]:mr,toolCallId:t.toolId,toolName:t.toolName,isError:t.isError,elapsed:t.elapsed,output:a})])}default:return null}}async function Ir(t,e){let r=e?Fr(t,e):[];if(e&&r.length===0)throw new Error(Fa);let i=Lr($r(),t),a=Pr(i.providers,i.default_provider);if(!a)throw new Error(Ba);let n=await Vr({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:!Dr(i),memoryEnabled:Mr(i),...e?{sessionId:e}:{}});return e&&n.conv.appendMessages(Br(r)),{sessionId:n.sessionId,cwd:n.cwd,run:n.run.bind(n),abort:()=>{n.abort()},dispose:()=>n.dispose()}}function Ar(){let t=()=>{};return{promise:new Promise(r=>{t=r}),resolve:t}}var de=class{constructor(e=Ir,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=rn(i);if(n){let u=this.sessions.get(r);if(!u){this.reject(null,a,e,r,Nr);return}await this.handlePermissionResponse(u,e,r,n,a);return}let o=en(i);if(!o){this.reject(this.sessions.get(r)??null,a,e,r,Ma);return}let d=this.sessions.get(r);if(d?.run&&!d.run.finished){this.reject(d,a,e,r,Er(r,d.run.taskId));return}let c;try{c=d??this.createSession(r)}catch(u){this.reject(null,a,e,r,Dt(u));return}d&&(this.sessions.delete(r),this.sessions.set(r,c));let T;try{T=await this.ensureRuntime(c)}catch(u){this.reject(c,a,e,r,Dt(u));return}if(this.sessions.get(r)!==c){this.reject(null,a,e,r,La);return}let p=c.run;if(p&&!p.finished){this.reject(c,a,e,r,Er(r,p.taskId));return}let v=this.startRun(c,T,e,r,o,a);this.consume(c,v,o),await v.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(w.statusUpdate(ct(e,n,F.TASK_STATE_CANCELED,lt(e,n,[Pt($a)]))));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(Ha);let r=this.contextMappingPath(e),i=Tl(r)?wr(r,"utf8"):void 0;if(i!==void 0&&!Cr.test(i))throw new Error(Ka);let a={contextId:e,sessionId:i,runtimePromise:null,initializing:!1,run:null,idleTimer:null};return this.sessions.set(e,a),a}contextMappingPath(e){return xr(this.cwd,Ya,Sl("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);Ur(Nl(n),{recursive:!0}),zr(n,()=>{let o=`${n}.${nn()}.tmp`;try{Jr(o,i,{flag:"wx",mode:384}),gl(o,n)}finally{ml(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,Nr);return}if(o.taskId!==r){this.reject(e,n,r,i,za(o.taskId));return}let d=o.permissions.get(a.permissionId);if(!d){this.reject(e,n,r,i,qa(a.permissionId));return}o.bus=n,o.permissions.delete(a.permissionId),o.settle=Ar(),n.publish(w.task(le(r,i,F.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:Ar(),done:Ar(),canceled:!1,finished:!1,stopReason:null,permissions:new Map};return e.run=d,qr(r.cwd,r.sessionId,{role:"user",content:n,timestamp:Math.floor(Date.now()/1e3)}),o.publish(w.task(le(i,a,F.TASK_STATE_SUBMITTED))),d}consume(e,r,i){let a=r.taskId,n=e.contextId,o=r.runtime.run(i,{onPermissionRequest:(d,c,T,p,v,u)=>this.requestPermission(r,a,n,d,c,T,p,v,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=Dt(c)}this.finishRun(e,r,a,n,d)})()}requestPermission(e,r,i,a,n,o,d,c,T){if(c?.aborted||e.canceled||e.finished)return Promise.resolve("deny");this.permissionCounter+=1;let p=`perm-${String(this.permissionCounter)}-${nn().slice(0,8)}`,v={[Z]:oe,permissionId:p,toolCallId:d,toolName:a,reason:[T?`${T.agentName} \xB7 ${T.cwd}`:"",o.reason].filter(Boolean).join(`
13
- `),args:n};return new Promise(u=>{let N=g=>{c?.removeEventListener("abort",h),u(g)},h=()=>{e.permissions.delete(p)&&(N("deny"),!e.canceled&&!e.finished&&(e.permissions.size>0?this.publishPendingPermissions(e,r,i):e.bus.publish(w.statusUpdate(ct(r,i,F.TASK_STATE_WORKING)))))};e.permissions.set(p,{data:v,resolve:N}),c?.addEventListener("abort",h,{once:!0}),this.publishPendingPermissions(e,r,i),e.settle.resolve()})}publishPendingPermissions(e,r,i){let a=[...e.permissions.values()].map(n=>xt(n.data));e.bus.publish(w.statusUpdate(ct(r,i,F.TASK_STATE_INPUT_REQUIRED,lt(r,i,a))))}publishAgentEvent(e,r,i,a){let n=an(a,r,i);n&&e.bus.publish(w.statusUpdate(ct(r,i,F.TASK_STATE_WORKING,n)))}finishRun(e,r,i,a,n){if(r.finished)return;r.finished=!0;for(let c of r.permissions.values())c.resolve("deny");r.permissions.clear();let o=this.finalState(r,n),d=n?lt(i,a,[Pt(n)]):void 0;r.bus.publish(w.statusUpdate(ct(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"?F.TASK_STATE_CANCELED:r?F.TASK_STATE_FAILED:F.TASK_STATE_COMPLETED}reject(e,r,i,a,n){let o=lt(i,a,[Pt(n)]);if(e?.run&&!e.run.finished){r.publish(w.message(o));return}r.publish(w.task(le(i,a,F.TASK_STATE_FAILED))),r.publish(w.statusUpdate(ct(i,a,F.TASK_STATE_FAILED,o)))}};function Ol(t){let e=Hr(t??Qa,{defaultPort:Or,allowEphemeral:!0});if(!Kr.has(e.host))throw new Error(Va);return e}async function vl(t={}){let{host:e,port:r}=Ol(t.address),i=El();await _l(i,r,e);let a=i.address();if(!a||typeof a=="string")throw new Error(Ga);let o=`http://${a.family==="IPv6"?`[${a.address}]`:a.address}:${String(a.port)}/`,d=ba(o),c=new de(t.runtimeFactory??Ir,t.cwd??process.cwd()),T=new ui(d,new ci,c,new Ee),p=(0,sn.default)();p.use(vr,Ua({agentCardProvider:T})),p.use(Ia({requestHandler:T,userBuilder:rr.noAuthentication})),p.use(xa({requestHandler:T,userBuilder:rr.noAuthentication})),i.on("request",p);let v=!1;return{url:o,cardUrl:`${o}${vr.slice(1)}`,async close(){v||(v=!0,i.closeIdleConnections(),await yl(i),await c.dispose())}}}function _l(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 yl(t){return new Promise((e,r)=>{t.close(i=>{i?r(i):e()})})}async function tu(t){let e=await vl({address:t});process.stderr.write(`A2A server listening at ${e.url}
14
- `),process.stderr.write(`Agent card at ${e.cardUrl}
15
- `),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{Ol as parseA2aAddress,tu as runA2aServer,vl as startA2aServer};
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __yukinoCreateRequire } from "node:module";
3
- const require = __yukinoCreateRequire(import.meta.url);
4
- import{j as e,p as t}from"./chunk-A4IB5PNW.js";import"./chunk-UX5DJPHN.js";import"./chunk-DGDF5PBF.js";import"./chunk-QDMUFOED.js";import"./chunk-676RWZYX.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-7WYSSZKU.js";import"./chunk-BCYFGWSM.js";import"./chunk-QYUIIFJY.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-N7G2FDAI.js";import"./chunk-NPIMUWFO.js";import"./chunk-WKKH2UE5.js";import"./chunk-HKQWGX5S.js";import"./chunk-S56AXDDN.js";import"./chunk-WGRGSG2J.js";import"./chunk-VM4YKTHC.js";import"./chunk-456FRBGE.js";import"./chunk-7MKA3SHV.js";import{Readable as s,Writable as i}from"stream";function c(){let o=(...n)=>{process.stderr.write(`${n.map(String).join(" ")}
5
- `)};console.log=o,console.info=o,console.warn=o,console.debug=o}async function m(){c();let o=t(),n=e(i.toWeb(process.stdout),s.toWeb(process.stdin)),r=o.app.connect(n);process.stdin.resume();try{await r.closed}finally{await o.dispose()}}export{m as runAcpStdio};
@@ -1,9 +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 l,b as C,c as I,d as A,e as S,f as L,g as j,h as O,i as T,k as X,l as W,m as K,n as V,o as Y,p as oe}from"./chunk-A4IB5PNW.js";import{b as Q,c as Z,d as ee,e as te,f as ne,g as se}from"./chunk-UX5DJPHN.js";import"./chunk-DGDF5PBF.js";import"./chunk-QDMUFOED.js";import"./chunk-676RWZYX.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-7WYSSZKU.js";import"./chunk-BCYFGWSM.js";import"./chunk-QYUIIFJY.js";import"./chunk-KEPFYD6K.js";import"./chunk-N7ARR77W.js";import"./chunk-27PD4NBA.js";import"./chunk-WLJL66O5.js";import"./chunk-N7G2FDAI.js";import"./chunk-NPIMUWFO.js";import"./chunk-WKKH2UE5.js";import"./chunk-HKQWGX5S.js";import"./chunk-S56AXDDN.js";import"./chunk-WGRGSG2J.js";import{b as G}from"./chunk-VM4YKTHC.js";import"./chunk-456FRBGE.js";import"./chunk-7MKA3SHV.js";import{createServer as nt}from"http";var R="Acp-Connection-Id",M="Acp-Session-Id",H="text/event-stream",U="application/json",ke=new Set([l.session_cancel,l.session_close,l.session_delete,l.session_fork,l.session_load,l.session_prompt,l.session_resume,l.session_set_config_option,l.session_set_mode,"session/set_model"]);function ie(n){return ke.has(n)}function x(n){if(!S(n))return;let e=n.sessionId;return typeof e=="string"?e:void 0}function re(n){return"method"in n?x(n.params):void 0}function ae(n){if(!I(n)||!("result"in n)||!S(n.result))return;let e=n.result.sessionId;return typeof e=="string"?e:void 0}function E(n){return n.jsonrpc==="2.0"&&"id"in n&&"method"in n&&n.method===l.initialize}function y(n){if(typeof n=="string")return`string:${n}`;if(typeof n=="number")return`number:${n}`;if(n===null)return"null"}var dt=16*1024*1024;function ce(n,e){return(t,s,o)=>{let i,r=!1,a=()=>{e.off("headers",d),s.off("close",p),s.off("error",p)},d=(f,b)=>{b!==t||!i||f.push(`${R}: ${i.connectionId}`)},p=()=>{r||(a(),i?.reject())};try{i=n.prepareWebSocketUpgrade(),e.on("headers",d),s.once("close",p),s.once("error",p),e.handleUpgrade(t,s,o,f=>{r=!0,a(),i?.accept(f)})}catch(f){a(),i?.reject(),xe(s,f)}}}function xe(n,e){n.destroy(e instanceof Error?e:void 0)}var ue=64*1024*1024,he=6e4,fe=1024,le=1024,de=2**31-1,g=class extends Error{constructor(e){super(e),this.name="ConnectionLimitError"}};function _(n,e){return new g(`Connection exceeds ${n} (${e[n]})`)}function q(n){return new g(`Connection output stalled for maxOutputStallMs (${n.maxOutputStallMs})`)}var m=class extends Error{constructor(){super("ACP connection is closed"),this.name="ConnectionClosedError"}},P=class{enabled;onReceiverChange;observer;queue=[];head=0;activeLease;isFinished=!1;isAborted=!1;abortError;constructor(e=!0,t,s){this.enabled=e,this.onReceiverChange=t,this.observer=s}push(e){!this.enabled||this.isFinished||(this.queue.push(e),this.observer?.queued?.(e),this.activeLease?.wake())}get hasReceiver(){return this.activeLease!==void 0}get hasQueuedMessages(){return this.head<this.queue.length}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new z(this);return this.activeLease=e,this.onReceiverChange?.(),e}finish(){this.isFinished||(this.isFinished=!0,this.activeLease?.wake())}abort(e){if(!this.isAborted){for(this.isAborted=!0,this.abortError=e,this.isFinished=!0;this.hasQueuedMessages;)this.dequeue();this.observer=void 0,this.onReceiverChange=void 0,this.activeLease?.stop(e??new m)}}async receive(e){for(;;){if(e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.isAborted){if(this.abortError!==void 0)throw this.abortError;return{done:!0,value:void 0}}if(this.hasQueuedMessages)return{done:!1,value:this.dequeue()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){this.activeLease===e&&(this.activeLease=void 0,e.markReleased(),this.onReceiverChange?.())}dequeue(){let e=this.queue[this.head];return this.queue[this.head]=void 0,this.head+=1,this.head===this.queue.length?(this.queue=[],this.head=0):this.head>=1024&&this.head*2>=this.queue.length&&(this.queue=this.queue.slice(this.head),this.head=0),this.observer?.dequeued(e),e}},B=class{transport;limits;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;bufferedBytes=0;streamObserver={queued:e=>{this.bufferedBytes+=e.length},dequeued:e=>{this.bufferedBytes-=e.length,this.notifyOutboundProgress()}};bufferedSessionStreams=0;progressWaiters=new Set;supportsBatches=!1;hasStartedRouter=!1;hasAgentOutputEnded=!1;hasFinishedRouting=!1;hasStartedShutdown=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;abortAgentInbound=()=>{};endAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,t,s){this.transport=t,this.limits=s,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new P(t==="http",void 0,this.streamObserver),this.allOutbound=new P(t==="websocket",void 0,{dequeued:()=>{this.notifyOutboundProgress()}}),this.closed=new Promise(a=>{this.resolveClosed=a});let o=new TransformStream({start:a=>{this.abortAgentInbound=d=>a.error(d)}}),i=Le(a=>{if(!this.supportsBatches&&Array.isArray(a))throw new TypeError("AcpServer transports do not support outbound JSON-RPC batch messages")},()=>{this.hasAgentOutputEnded=!0,this.notifyOutboundProgress()});this.inboundTx=o.writable,this.outboundRx=i.readable,this.endAgentOutbound=i.end;let r={readable:o.readable,writable:i.writable};this.agentConnection=e.connect(r,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let t=this.outboundRx.getReader();this.initialReader=t;try{let s=await t.read();if(s.done||!s.value||!Oe(s.value,e))throw this.shutdownPromise||await this.shutdown(),new Error("Expected initialize response from agent");return s.value}finally{this.initialReader===t&&(this.initialReader=void 0),t.releaseLock()}}async writeInbound(e){if(!this.supportsBatches&&Array.isArray(e))throw new TypeError("AcpServer transports do not support inbound JSON-RPC batch messages");let t=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=t.catch(()=>{}),await t}startRouter(){this.hasStartedRouter||(this.hasStartedRouter=!0,this.routerPromise=this.runRouter())}startConnectHandlers(){typeof this.agentConnection=="object"&&this.agentConnection!==null&&"startConnectHandlers"in this.agentConnection&&typeof this.agentConnection.startConnectHandlers=="function"&&this.agentConnection.startConnectHandlers()}enableBatches(){this.supportsBatches=!0}get batchesEnabled(){return this.supportsBatches}get isClosed(){return this.hasStartedShutdown}get hasOutboundBacklog(){return this.transport==="http"?this.bufferedBytes>=this.limits.maxBufferedBytes:this.allOutbound.hasQueuedMessages}validateSessionId(e){this.validateIdLength("Session ID",e)}validateRequestId(e){typeof e=="string"&&this.validateIdLength("Request ID",e)}async waitForOutboundCapacity(e){await this.waitForRoom(()=>this.hasFinishedRouting,e)}ensureSession(e){if(this.validateSessionId(e),this.transport==="websocket")return this.connectionStream;let t=this.sessionStreams.get(e);if(t)return t;if(this.bufferedSessionStreams>=this.limits.maxBufferedSessionStreams)throw _("maxBufferedSessionStreams",this.limits);return this.createSessionStream(e)}acquireSessionStream(e){if(this.validateSessionId(e),this.transport==="websocket")return;let t=this.sessionStreams.get(e);if(t)return t.tryAcquire();if(this.isClosed||this.hasFinishedRouting)throw new m;return this.createSessionStream(e).tryAcquire()}async shutdown(e){return this.shutdownPromise||(this.shutdownPromise=this.runShutdown(e)),this.shutdownPromise}async runShutdown(e){try{this.hasStartedShutdown=!0,this.notifyOutboundProgress(),this.connectionStream.abort(e),this.allOutbound.abort(e);for(let t of this.sessionStreams.values())t.abort(e);this.sessionStreams.clear(),this.bufferedSessionStreams=0,this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.closeInbound(e),this.cancelOutboundReader()])}finally{this.resolveClosedOnce()}}observeAgentConnection(){typeof this.agentConnection!="object"||this.agentConnection===null||!("closed"in this.agentConnection)||!this.agentConnection.closed||Promise.resolve(this.agentConnection.closed).finally(async()=>{if(!this.hasStartedRouter){await this.shutdown();return}this.endAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;return e?e.cancel():this.outboundRx.cancel()}closeInbound(e){return e!==void 0||this.inboundTx.locked?(this.abortAgentInbound(e??new m),Promise.resolve()):this.inboundTx.close()}async writeInboundMessage(e){if(this.isClosed||this.hasFinishedRouting)throw new m;let t=this.inboundTx.getWriter();try{await t.write(e)}catch(s){throw this.isClosed?new m:s}finally{t.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{for(;;){let t=await e.read();if(t.done||this.isClosed)return;this.routeOutbound(t.value),await this.waitForRoom(()=>this.hasAgentOutputEnded)}}catch(t){t instanceof g?this.closeForLimit(t):(console.error(`ACP connection ${this.connectionId} router stopped unexpectedly:`,t),this.shutdown(t))}finally{this.hasFinishedRouting=!0,this.notifyOutboundProgress(),this.outboundReader===e&&(this.outboundReader=void 0),e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let t of this.sessionStreams.values())t.finish();this.resolveClosedOnce()}}resolveClosedOnce(){this.hasResolvedClosed||(this.hasResolvedClosed=!0,this.resolveClosed())}async waitForRoom(e,t){for(;!this.isClosed&&!e()&&this.hasOutboundBacklog;)if(!await this.waitForProgress(t)){this.closeForLimit(q(this.limits));return}}waitForProgress(e){let t=this.transport==="http"?this.limits.maxOutputStallMs:void 0;return new Promise((s,o)=>{if(e?.aborted){o(e.reason);return}let i,r=()=>{this.progressWaiters.delete(a),e?.removeEventListener("abort",d),clearTimeout(i)},a=()=>{r(),s(!0)},d=()=>{r(),o(e?.reason)};this.progressWaiters.add(a),e?.addEventListener("abort",d,{once:!0}),t!==void 0&&(i=setTimeout(()=>{r(),s(!1)},t))})}notifyOutboundProgress(){for(let e of[...this.progressWaiters])e()}routeOutbound(e){if(Array.isArray(e))for(let t of e)this.routeOutboundMessage(t);else this.routeOutboundMessage(e);this.allOutbound.push(e)}routeOutboundMessage(e){if(I(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let t=y(e.id),s=t?this.pendingRoutes.get(t):void 0,o=ae(e);o&&this.validateSessionId(o),t&&this.pendingRoutes.delete(t),this.pushToRoute(s??"connection",e)}createSessionStream(e){let t=new P(!0,()=>{this.onSessionReceiverChange(e,t)},this.streamObserver);return this.sessionStreams.set(e,t),this.bufferedSessionStreams+=1,t}onSessionReceiverChange(e,t){if(!this.isClosed){if(t.hasReceiver){this.bufferedSessionStreams-=1;return}if(!t.hasQueuedMessages){this.sessionStreams.delete(e),t.abort();return}this.bufferedSessionStreams+=1,!this.hasFinishedRouting&&this.bufferedSessionStreams>this.limits.maxBufferedSessionStreams&&this.closeForLimit(_("maxBufferedSessionStreams",this.limits))}}closeForLimit(e){console.warn(`Closing ACP connection ${this.connectionId}:`,e.message),this.shutdown(e)}validateIdLength(e,t){if(t.length>this.limits.maxIdLength)throw new g(`${e} exceeds maxIdLength (${this.limits.maxIdLength})`)}routeOutboundRequestOrNotification(e){let t=re(e);if(t){let s=this.ensureSession(t);this.trackClientResponseRoute(e,{session:t}),this.deliver(s,e);return}this.trackClientResponseRoute(e,"connection"),this.deliver(this.connectionStream,e)}trackClientResponseRoute(e,t){if(!("id"in e)||!("method"in e))return;let s=y(e.id);s&&this.clientResponseRoutes.set(s,t)}pushToRoute(e,t){if(e==="connection"){this.deliver(this.connectionStream,t);return}this.deliver(this.ensureSession(e.session),t)}deliver(e,t){this.transport==="http"&&e.push(JSON.stringify(t))}},F=class{limits;connections=new Map;pendingConnections=new Map;constructor(e={}){this.limits=Pe(e)}createConnection(e,t="http"){let s=new B(e,t,this.limits);return this.connections.set(s.connectionId,s),this.trackConnectionClose(s),s}createPendingConnection(e,t="websocket"){let s=new B(e,t,this.limits);return this.pendingConnections.set(s.connectionId,s),this.trackConnectionClose(s),s}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){let t=this.connections.get(e);return t?.isClosed?void 0:t}remove(e){let t=this.connections.get(e);if(t)return this.connections.delete(e),t.shutdown(),t}discard(e){let t=this.connections.get(e)??this.pendingConnections.get(e);if(t)return this.connections.delete(e),this.pendingConnections.delete(e),t.shutdown(),t}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,t=>t.shutdown()))}trackConnectionClose(e){e.closed.then(()=>{this.connections.get(e.connectionId)===e&&this.connections.delete(e.connectionId),this.pendingConnections.get(e.connectionId)===e&&this.pendingConnections.delete(e.connectionId)})}};function Pe(n){let e={maxBufferedBytes:n.maxBufferedBytes??ue,maxOutputStallMs:n.maxOutputStallMs??he,maxBufferedSessionStreams:n.maxBufferedSessionStreams??fe,maxIdLength:n.maxIdLength??le};for(let[t,s]of Object.entries(e))if(!Number.isSafeInteger(s)||s<=0)throw new RangeError(`${t} must be a positive safe integer`);if(e.maxOutputStallMs>de)throw new RangeError(`maxOutputStallMs must be at most ${de}`);return e}var z=class{mailbox;released=!1;stoppedController=new AbortController;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}get stopped(){return this.stoppedController.signal}async receive(){if(this.receiving)throw new Error("ACP outbound mailbox lease already has a pending receive");this.receiving=!0;try{return await this.mailbox.receive(this)}finally{this.receiving=!1}}release(){this.mailbox.release(this)}wake(){this.resolveWake?.(),this.wakePromise=void 0,this.resolveWake=void 0}wait(){return this.wakePromise||(this.wakePromise=new Promise(e=>{this.resolveWake=e})),this.wakePromise}markReleased(){this.released=!0,this.wake()}stop(e){this.stoppedController.abort(e),this.wake()}};function Le(n,e){let t,s=!1,o=!1,i,r=()=>{let f=i;i=void 0,f?.()},a=()=>{if(!s){s=!0;try{t?.close()}catch{}r(),e()}},d=f=>{if(!s){s=!0;try{t?.error(f)}catch{}r(),e()}},p=()=>{s||o||(o=!0,r(),setTimeout(a,0))};return{readable:new ReadableStream({start(f){t=f},pull:r,cancel(){s=!0,r()}},{highWaterMark:0}),writable:new WritableStream({async write(f){if(s)throw new Error("ACP outbound channel is closed");try{n(f),t?.enqueue(f)}catch(b){throw d(b),b}!s&&!o&&(t?.desiredSize??0)<0&&await new Promise(b=>{i=b})},close:a,abort:d}),end:p}}function Oe(n,e){return!Array.isArray(n)&&"id"in n&&!("method"in n)&&n.id===e}var Ct=new TextEncoder().encode("data:"),vt=new Uint8Array([10]);function pe(n){return`data: ${n}
5
-
6
- `}function we(){return`:
7
-
8
- `}function me(n){return new ReadableStream(Te(n),{highWaterMark:0})}function Te(n){let e=new TextEncoder,t,s=!1,o=!1,i=!1,r=()=>{t&&(clearInterval(t),t=void 0)},a=(c,h)=>{s=!1;try{return c.enqueue(e.encode(h)),!0}catch{return!1}},d=c=>{if(!i){i=!0,r(),n.release();try{c.close()}catch{}}},p=(c,h)=>{i||(i=!0,r(),n.release(),c.error(h))},f=c=>{n.stopped.aborted&&!s&&p(c,n.stopped.reason)},b=async c=>{if(!o){o=!0;try{for(;s&&!i;){let h=await n.receive();if(i)return;if(h.done){d(c);return}if(!a(c,pe(h.value))){d(c);return}f(c)}}catch(h){p(c,h)}finally{o=!1}}};return{start(c){n.stopped.addEventListener("abort",()=>{f(c)},{once:!0}),t=setInterval(()=>{i||!s||a(c,we())||d(c)},15e3)},pull(c){s=!0,b(c)},cancel(){i=!0,r(),n.release()}}}function D(n,e,t){if(n.on){let s=(...o)=>{t(...Me(e,o))};return n.on(e,s),()=>{if(n.off){n.off(e,s);return}n.removeListener?.(e,s)}}if(n.addEventListener){let s=o=>t(o);return n.addEventListener(e,s),()=>{n.removeEventListener?.(e,s)}}throw new Error("WebSocket object does not support event listeners")}function be(n){let e=Be(n);if(typeof e=="string")return e}function Me(n,e){return n!=="message"||typeof e[1]!="boolean"?e:e[1]?[void 0]:[_e(e[0])]}function _e(n){if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return new TextDecoder().decode(n);if(ArrayBuffer.isView(n))return new TextDecoder().decode(n);if(De(n))return Ne(n)}function Be(n){let[e]=n;return Fe(e)?e.data:e}function Fe(n){return typeof n=="object"&&n!==null&&"data"in n}function De(n){return Array.isArray(n)&&n.every(ArrayBuffer.isView)}function Ne(n){let e=n.reduce((o,i)=>o+i.byteLength,0),t=new Uint8Array(e),s=0;for(let o of n)t.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength),s),s+=o.byteLength;return new TextDecoder().decode(t)}var We=10,He=1e3,Ue=1024;function ye(n,e){let t=new $(n,e);return t.start(),t}var $=class{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();waitingInboundBytes=0;isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,t){this.socket=e,this.options=t,this.preparedConnection=t.connection,this.closedPromise=new Promise(s=>{this.resolveClosed=s})}get closed(){return this.closedPromise}start(){this.detachListeners.push(D(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(D(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(D(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,t="Server shutting down"){return this.shutdown(e,t)}enqueueSocketMessage(e){if(this.isClosed)return;let t=be(e);if(t===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let s=t.length+Ue,{limits:o}=this.options.registry;if(this.waitingInboundBytes>0&&s>o.maxBufferedBytes-this.waitingInboundBytes){this.closeForLimit(_("maxBufferedBytes",o));return}this.waitingInboundBytes+=s;let i=this.messageChain.then(()=>(this.waitingInboundBytes-=s,this.handleSocketMessage(t)));this.messageChain=i.catch(r=>{if(!(this.isClosed||r instanceof m)){if(r instanceof g){this.closeForLimit(r);return}console.error("ACP WebSocket message handling failed:",r),this.shutdown(1011,"Message handling failed")}})}async handleSocketMessage(e){if(this.isClosed)return;let t;try{t=JSON.parse(e)}catch{await this.waitForSocketCapacity(),this.send(T(O.parseError()));return}if(!Array.isArray(t)&&!S(t)){await this.waitForSocketCapacity(),this.send(T(O.invalidRequest(t)));return}if(!this.connection&&Array.isArray(t)){if(t.length===1&&C(t[0])){await this.handleInitialize(t[0],!0);return}console.warn("First ACP WebSocket message must be initialize or a single-entry initialize batch"),await this.shutdown(1002,"First message must be initialize");return}let s=t;if(!this.connection){if(L(s))return;if(!C(s)&&!A(s)){await this.waitForSocketCapacity(),this.send(T(O.invalidRequest(s)));return}await this.handleInitialize(s,!1);return}let o=await this.forwardMessage(s);o.ok||console.warn("Ignoring ACP WebSocket message:",o.message)}async handleInitialize(e,t){if(!E(e)){console.warn("First ACP WebSocket message must be initialize"),await this.shutdown(1002,"First message must be initialize");return}if(!("id"in e)||e.id===null){console.warn("ACP WebSocket initialize request must include an ID"),await this.shutdown(1002,"Initialize request must include an ID");return}let s=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=s;try{await ge(s,e);let o=await s.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(s.connectionId);return}this.preparedConnection=void 0,$e(o)===2&&s.enableBatches(),this.connection=s,this.options.registry.register(s),s.startRouter(),s.startConnectHandlers(),this.send(t?[o]:o),this.startOutboundPump(s)}catch(o){this.preparedConnection=void 0,this.options.registry.discard(s.connectionId);let i={jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:o instanceof Error?o.message:void 0}};this.send(t?[i]:i),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let t=this.connection;if(!t)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(Array.isArray(e)){if(!t.batchesEnabled)return await this.shutdown(1002,"JSON-RPC batches require ACP v2"),{ok:!1,message:"JSON-RPC batches require ACP v2"};if(e.some(qe))return await this.shutdown(1002,"Initialize not allowed on existing connection"),{ok:!1,message:"Initialize not allowed on existing connection"};for(let s of e)this.trackInboundRoutes(s);return await this.forwardToAgent(t,e)}return C(e)&&E(e)?(await this.waitForSocketCapacity(),this.send({jsonrpc:"2.0",id:e.id,error:{code:-32600,message:"Initialize not allowed on existing connection"}}),{ok:!1,message:"Initialize not allowed on existing connection"}):(this.trackInboundRoutes(e),await this.forwardToAgent(t,e))}async forwardToAgent(e,t){return ze(t)&&(await e.waitForOutboundCapacity(),await this.waitForSocketCapacity()),await this.writeInbound(t),{ok:!0}}async waitForSocketCapacity(){let{limits:e}=this.options.registry,t=We,s=this.socket.bufferedAmount??0,o=0;for(;!this.isClosed&&s>=e.maxBufferedBytes;){if(o>=e.maxOutputStallMs){this.closeForLimit(q(e));return}await new Promise(r=>setTimeout(r,t)),o+=t,t=Math.min(t*2,He);let i=s;s=this.socket.bufferedAmount??0,s<i&&(o=0)}}trackInboundRoutes(e){let t=this.connection;if(t){if(C(e)){let s=Se(e);s!=="connection"&&t.validateSessionId(s.session),t.validateRequestId(e.id);let o=y(e.id);o&&t.pendingRoutes.set(o,e.method===l.session_load?"connection":s);return}if(A(e)){let s=Se(e);s!=="connection"&&t.validateSessionId(s.session);return}if(L(e)){let s=e.id,o=s===null||typeof s=="string"||typeof s=="number"&&Number.isFinite(s)?y(s):void 0;o&&t.clientResponseRoutes.delete(o)}}}async writeInbound(e){let t=this.connection;if(!t)throw new Error("ACP WebSocket connection is not initialized");let s=this.inboundWriteChain.then(()=>ge(t,e));this.inboundWriteChain=s.catch(()=>{}),await s}startOutboundPump(e){let t=e.allOutbound.tryAcquire();if(!t){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=t,t.stopped.addEventListener("abort",()=>{this.closeForStoppedConnection(t.stopped.reason)},{once:!0}),(async()=>{try{for(;!this.isClosed;){let s=await t.receive();if(s.done||!this.send(s.value))return;await this.waitForSocketCapacity()}}catch(s){t.stopped.aborted||console.error("ACP WebSocket outbound pump failed:",s),await this.closeForStoppedConnection(s)}finally{this.outboundLease===t&&(this.outboundLease=void 0),t.release(),this.isClosed||this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(t){return console.warn("Failed to send ACP WebSocket message:",t),this.shutdown(1011,"Failed to send message"),!1}}closeForLimit(e){let t=this.connection?.connectionId??this.preparedConnection?.connectionId,s=t?`ACP connection ${t}`:"ACP connection";console.warn(`Closing ${s}:`,e.message),this.shutdown(1008,e.message)}async closeForStoppedConnection(e){this.isClosed||(e instanceof g?await this.shutdown(1008,e.message):e instanceof m?await this.shutdown():await this.shutdown(1011,"Internal error"))}async shutdownIfUninitialized(e,t){this.connection||await this.shutdown(e,t)}async shutdown(e,t){this.closeSocket(e,t),await this.closeSession()}closeSocket(e,t){try{this.socket.close(e,t)}catch(s){console.warn("Failed to close ACP WebSocket:",s)}}async closeSession(){if(!this.isClosed){this.isClosed=!0;try{for(let t of this.detachListeners.splice(0))t();let e=this.outboundLease;this.outboundLease=void 0,e?.release(),this.connection&&(this.options.registry.discard(this.connection.connectionId),this.connection=void 0),this.preparedConnection&&(this.options.registry.discard(this.preparedConnection.connectionId),this.preparedConnection=void 0)}finally{this.resolveClosed()}}}};async function ge(n,e){await n.writeInbound(e)}function Se(n){let e=x(n.params);return e?{session:e}:"connection"}function ze(n){return Array.isArray(n)?n.length===0||!j(n)&&!n.every(e=>A(e)):!A(n)&&!L(n)}function qe(n){return C(n)&&E(n)}function $e(n){if(!("result"in n)||!S(n.result))return;let e=n.result.protocolVersion;return typeof e=="number"?e:void 0}var N=class{agent;registry;webSocketSessions=new Set;constructor(e){this.agent=Re(e),this.registry=new F(e)}async handleRequest(e,t={}){try{return e.method==="POST"?await this.handlePost(e,t):e.method==="GET"?this.handleGet(e):e.method==="DELETE"?this.handleDelete(e):u("Method Not Allowed",405)}catch(s){if(s instanceof g)return u(s.message,400);if(s instanceof m)return u("Unknown Acp-Connection-Id",404);if(s instanceof v)return u("Request aborted",499);throw s}}prepareWebSocketUpgrade(e={}){let t=Ce(e,this.agent),s=this.registry.createPendingConnection(t),o=!1;return{connectionId:s.connectionId,accept:i=>{if(o)throw new Error("ACP WebSocket upgrade has already been settled");o=!0;let r=ye(i,{registry:this.registry,agent:t,connection:s});this.webSocketSessions.add(r),r.closed.finally(()=>{this.webSocketSessions.delete(r)})},reject:()=>{o||(o=!0,this.registry.discard(s.connectionId))}}}async close(){let e=this.registry.closeAll(),t=Promise.all(Array.from(this.webSocketSessions,s=>s.close()));await Promise.all([e,t])}async handlePost(e,t){let s=e.headers.get("Content-Type");if(!Ze(s))return u("Unsupported Media Type",415);let o=await Ge(e);if(!o.ok)return u("Invalid JSON",400);if(Array.isArray(o.value))return u("Batch JSON-RPC requests are not implemented",501);if(!S(o.value))return u("Invalid JSON-RPC message",400);let i=o.value,r=e.headers.get(R);if(E(i))return r?u("Initialize not allowed on existing connection",400):await this.handleInitialize(i,e.signal,t);if(!r)return u("Missing Acp-Connection-Id",400);let a=this.registry.get(r);if(!a)return u("Unknown Acp-Connection-Id",404);let d=await this.forwardConnectedMessage(a,i,e.headers,e.signal);return d.ok?Ae(202):u(d.message,d.status)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return u("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(H))return u("Not Acceptable",406);let s=e.headers.get(R);if(!s)return u("Missing Acp-Connection-Id",400);let o=this.registry.get(s);if(!o)return u("Unknown Acp-Connection-Id",404);let i=e.headers.get(M),r=i?o.acquireSessionStream(i):o.connectionStream.tryAcquire();return r?et(r):u("Outbound stream already has an active receiver",409)}handleDelete(e){let t=e.headers.get(R);return t?this.registry.remove(t)?Ae(202):u("Unknown Acp-Connection-Id",404):u("Missing Acp-Connection-Id",400)}async handleInitialize(e,t,s){if(!("id"in e)||e.id===null)return u("Initialize request must include an ID",400);if(t.aborted)return u("Request aborted",499);let o;try{o=this.registry.createConnection(Ce(s,this.agent));let i=je(o,e);i.catch(()=>{});let r=await Xe(i,t);if(t.aborted)throw new v;return o.startRouter(),o.startConnectHandlers(),ve(r,200,{[R]:o.connectionId})}catch(i){return o&&this.registry.remove(o.connectionId),i instanceof v?u("Request aborted",499):ve({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:i instanceof Error?i.message:void 0}},500)}}async forwardConnectedMessage(e,t,s,o){return I(t)?await Ve(e,t,s):await Ke(e,t,s,o)}};function Ce(n,e){return Je(n)?Re(n):e}function Je(n){return!!(n.agent||n.createAgent||n.createLegacyAgent)}function Re(n){if((n.agent?1:0)+(n.createAgent?1:0)+(n.createLegacyAgent?1:0)!==1)throw new Error("AcpServer requires exactly one of agent, createAgent, or createLegacyAgent");return n.agent?n.agent:n.createAgent?{connect:(t,s)=>n.createAgent().connect(t,s??{})}:{connect:t=>{new X(n.createLegacyAgent,t)}}}var v=class extends Error{constructor(){super("Request aborted"),this.name="RequestAbortedError"}};async function Ge(n){try{return{ok:!0,value:await n.json()}}catch{return{ok:!1}}}async function J(n,e){await n.writeInbound(e)}async function je(n,e){if(await J(n,e),!("id"in e)||e.id===null)throw new Error("Initialize request must include an ID");return await n.recvInitial(e.id)}async function Xe(n,e){if(e.aborted)throw new v;let t=()=>{},s=new Promise((o,i)=>{let r=()=>{i(new v)};e.addEventListener("abort",r,{once:!0}),t=()=>{e.removeEventListener("abort",r)}});try{return await Promise.race([n,s])}finally{t()}}async function Ke(n,e,t,s){let o=Qe(e,t);if(!o.ok)return o;o.value!=="connection"&&n.validateSessionId(o.value.session),A(e)||(n.validateRequestId(e.id),await n.waitForOutboundCapacity(s).catch(r=>{throw s.aborted?new v:r}));let i=C(e)?y(e.id):void 0;return i&&n.pendingRoutes.set(i,Ye(e,o.value)),await J(n,e),{ok:!0}}async function Ve(n,e,t){let s=y(e.id),o=s?n.clientResponseRoutes.get(s):void 0,i=t.get(M);return o&&o!=="connection"&&!i?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:o&&o!=="connection"&&i!==o.session?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:(s&&n.clientResponseRoutes.delete(s),await J(n,e),{ok:!0})}function Ye(n,e){return n.method===l.session_load?"connection":e}function Qe(n,e){let t=e.get(M),s=x(n.params);return(ie(n.method)||s!==void 0)&&!t?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:t!==null&&s!==void 0&&t!==s?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:t?{ok:!0,value:{session:t}}:s?{ok:!0,value:{session:s}}:{ok:!0,value:"connection"}}function Ze(n){return n?.split(";",1)[0]?.trim().toLowerCase()===U}function et(n){return new Response(me(n),{status:200,headers:{"Content-Type":H,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function ve(n,e,t){return new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":U,...t}})}function u(n,e){return new Response(n,{status:e,headers:{"Content-Type":"text/plain"}})}function Ae(n){return new Response(null,{status:n})}function st(n){let e=Q(n??K,{defaultPort:18889,allowEphemeral:!0});if(!Z.has(e.host))throw new Error(V);return e}async function ot(n){let{host:e,port:t}=st(n),s=ee(),o=new N({createAgent:()=>oe().app}),i=new G.default({noServer:!0}),r=ce(o,i),a=nt((c,h)=>{h.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),h.end("Not Found")});a.on("upgrade",(c,h,w)=>{let k=te(c,W,s);if(!k.allowed){ne(h,k);return}r(c,h,w)}),await new Promise((c,h)=>{let w=Ee=>{a.off("listening",k),h(Ee)},k=()=>{a.off("error",w),c()};a.once("error",w),a.once("listening",k),a.listen(t,e)});let d=a.address();if(!d||typeof d=="string")throw new Error(Y);let p=d,f=p.family==="IPv6"?`[${p.address}]`:p.address,b=!1;return{url:se(`ws://${f}:${String(p.port)}${W}`,s),async close(){if(b)return;b=!0;let c,h=w=>{c=c??(w instanceof Error?w:new Error(String(w)))};try{await o.close()}catch(w){h(w)}try{await Ie(i)}catch(w){h(w)}try{await Ie(a)}catch(w){h(w)}if(c!==void 0)throw c}}}function Ie(n){return new Promise((e,t)=>{n.close(s=>{s?t(s):e()})})}async function Yt(n){let e=await ot(n);process.stderr.write(`ACP WebSocket listening at ${e.url}
9
- `),await new Promise((t,s)=>{let o=()=>{process.off("SIGINT",o),process.off("SIGTERM",o),e.close().then(t,s)};process.once("SIGINT",o),process.once("SIGTERM",o)})}export{st as parseAcpWebSocketAddress,Yt as runAcpWebSocket,ot as startAcpWebSocketServer};