@kodax-ai/kodax 0.7.96 → 0.7.97-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -0
- package/README.md +85 -62
- package/README_CN.md +57 -67
- package/config-templates/config.example.jsonc +0 -14
- package/dist/chunks/{agent-7N427EVB.js → agent-J7SHFM5N.js} +1 -1
- package/dist/chunks/argument-completer-ZJQOWTIS.js +2 -0
- package/dist/chunks/{chunk-ABZDFK2X.js → chunk-2GV6MQ4T.js} +14 -14
- package/dist/chunks/{chunk-6QI3GOYG.js → chunk-3PS3YEDS.js} +1 -1
- package/dist/chunks/chunk-4VJMQDTH.js +417 -0
- package/dist/chunks/{chunk-NI7PBPUR.js → chunk-5DSUVP46.js} +1 -1
- package/dist/chunks/chunk-5P7RTSZT.js +21 -0
- package/dist/chunks/{chunk-XXNR6S4Q.js → chunk-6ZAQKFIM.js} +1 -1
- package/dist/chunks/chunk-7V2QBZ73.js +137 -0
- package/dist/chunks/{chunk-C7U542KM.js → chunk-F7DHZH6T.js} +1 -1
- package/dist/chunks/{chunk-7IMWOR34.js → chunk-HSRYDDPF.js} +1 -1
- package/dist/chunks/chunk-K3DQGSQU.js +372 -0
- package/dist/chunks/chunk-NO23K2CB.js +2 -0
- package/dist/chunks/{chunk-NKT3B3DR.js → chunk-OT5WHAX4.js} +1 -1
- package/dist/chunks/{chunk-YEAUDI6U.js → chunk-QGWHJIO4.js} +1 -1
- package/dist/chunks/chunk-QOFFAY5C.js +261 -0
- package/dist/chunks/{chunk-4PFZ7BEE.js → chunk-QVDTORL3.js} +11 -11
- package/dist/chunks/chunk-QZ4B4AWG.js +473 -0
- package/dist/chunks/chunk-RXDS6CNA.js +355 -0
- package/dist/chunks/{chunk-WV3DJVW4.js → chunk-VDGPJQL7.js} +135 -135
- package/dist/chunks/chunk-VEZ4WHPN.js +641 -0
- package/dist/chunks/chunk-ZPPAT25E.js +5 -0
- package/dist/chunks/chunk-ZQYWDI4O.js +1 -0
- package/dist/chunks/chunk-ZS2GUADU.js +498 -0
- package/dist/chunks/{chunk-GN2IY5YE.js → chunk-ZTYZYXGV.js} +1 -1
- package/dist/chunks/{chunk-EM4XJBTK.js → chunk-ZZQ4GDVU.js} +1 -1
- package/dist/chunks/{client-6WZZTTSV.js → client-MXOJ5XUN.js} +1 -1
- package/dist/chunks/{compaction-config-ZMEJU4U7.js → compaction-config-5VZSGKBQ.js} +1 -1
- package/dist/chunks/{construction-bootstrap-RX4DMHI7.js → construction-bootstrap-U2ZU2WAT.js} +1 -1
- package/dist/chunks/dist-CSLNWLOE.js +2 -0
- package/dist/chunks/dist-XXMJMJDU.js +2 -0
- package/dist/chunks/host-RUXYZFYN.js +2 -0
- package/dist/chunks/readline-helpers-JCVULR4C.js +2 -0
- package/dist/chunks/run-manager-DRIM5VNE.js +2 -0
- package/dist/chunks/utils-MQEBGKIX.js +2 -0
- package/dist/index.d.ts +63 -30
- package/dist/index.js +10 -6
- package/dist/kodax_bootstrap.js +1 -1
- package/dist/kodax_cli.js +1745 -1734
- package/dist/kodax_resume.js +32 -35
- package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
- package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
- package/dist/native/win32-x64/manifest.json +2 -2
- package/dist/sandbox-network-broker.js +77 -77
- package/dist/sdk-a2a.d.ts +33 -18
- package/dist/sdk-a2a.js +8 -9
- package/dist/sdk-agent.d.ts +33 -26
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-client.d.ts +40 -0
- package/dist/sdk-client.js +2 -0
- package/dist/sdk-coding.d.ts +87 -499
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.d.ts +3 -4
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-llm.d.ts +11 -9
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.d.ts +3 -3
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.d.ts +3 -1
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +317 -70
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-runtime.d.ts +580 -452
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +13 -9
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +57 -57
- package/dist/types-chunks/{base.d-Bt9lhwSV.d.ts → base.d-ZBOdjDUT.d.ts} +2 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-DWFIMg0v.d.ts → bash-prefix-extractor.d-DvswAXKS.d.ts} +136 -66
- package/dist/types-chunks/{capability-learning.d-gRtO03f6.d.ts → capability-learning.d-B4pxKwP4.d.ts} +1 -1
- package/dist/types-chunks/{capability.d-Ch5Vos33.d.ts → capability.d-DOF3r0fJ.d.ts} +1 -1
- package/dist/types-chunks/{capsule.d-Dj1n6s0Y.d.ts → capsule.d-B4atvlxE.d.ts} +7 -19
- package/dist/types-chunks/client-contract-A1jdk6xz.d.ts +1993 -0
- package/dist/types-chunks/{controller.d-C0IM1Tud.d.ts → controller.d-BkUJ_3sl.d.ts} +1 -1
- package/dist/types-chunks/{controller.d-J2t1q8Ly.d.ts → controller.d-yyKajPTi.d.ts} +140 -1380
- package/dist/types-chunks/{cost-tracker.d-BWI4lFWn.d.ts → cost-tracker.d-BeaenODW.d.ts} +2 -47
- package/dist/types-chunks/{history-retrieval.d-CPN5PMBV.d.ts → history-retrieval.d-JdFfkeF3.d.ts} +2 -2
- package/dist/types-chunks/{manager.d-rtmywU9M.d.ts → manager.d-C_20XqCV.d.ts} +8 -1
- package/dist/types-chunks/manifest.d-Bw2i-zQi.d.ts +18 -0
- package/dist/types-chunks/provider-credential-context.d-BH2OaB1b.d.ts +47 -0
- package/dist/types-chunks/provider-request-observation.d-jL8T6wVO.d.ts +34 -0
- package/dist/types-chunks/{public-api.d-amBop8Nk.d.ts → public-api.d-Cq8ILMte.d.ts} +52 -13
- package/dist/types-chunks/{resolver.d-BrwLoWNr.d.ts → resolver.d-DLY01RHx.d.ts} +4 -2
- package/dist/types-chunks/{types.d-CSv0_cZC.d.ts → review-inbox.d-BeaLRNHx.d.ts} +251 -3
- package/dist/types-chunks/{shell-command-sets.d-oejwpP_7.d.ts → review-packet.d-D4bbTbq3.d.ts} +46 -3
- package/dist/types-chunks/{exec-policy.d-BPESl90L.d.ts → run-manager.d-C7Q71rin.d.ts} +385 -62
- package/dist/types-chunks/runtime-client-info-CxnlZlW5.d.ts +175 -0
- package/dist/types-chunks/{sdk-session-B6XjHNU1.d.ts → sdk-session-BDFjCpDn.d.ts} +12 -4
- package/dist/types-chunks/{side-query.d-DHWG1JZg.d.ts → side-query.d-DTrhVd_r.d.ts} +4 -3
- package/dist/types-chunks/trusted-repl-entry-vbUM8R6P.d.ts +445 -0
- package/dist/types-chunks/{types.d-CtO8mR1s.d.ts → types.d-BJTN-RZr.d.ts} +5 -5
- package/dist/types-chunks/{types.d-BrQMB-hy.d.ts → types.d-BjOq57-z.d.ts} +6 -0
- package/dist/types-chunks/types.d-o7t9dds4.d.ts +1484 -0
- package/dist/types-chunks/{utils.d-DcznBeQ3.d.ts → utils.d-CWiMhFfu.d.ts} +202 -36
- package/docs/CLIENT_CONTRACT.md +441 -0
- package/docs/SDK_MIGRATION.md +123 -0
- package/docs/SPACE_SDK_SEAMS.md +139 -0
- package/package.json +10 -5
- package/public_docs/README.md +12 -133
- package/public_docs/configuration/config-files.md +8 -14
- package/public_docs/sdk/embedder-guide.md +494 -420
- package/dist/chunks/argument-completer-FAIHW7HZ.js +0 -2
- package/dist/chunks/chunk-66XN5AFU.js +0 -417
- package/dist/chunks/chunk-7O2AIFNE.js +0 -373
- package/dist/chunks/chunk-DSXUXUZG.js +0 -5
- package/dist/chunks/chunk-GYO73UYQ.js +0 -275
- package/dist/chunks/chunk-HPCS3LZ5.js +0 -324
- package/dist/chunks/chunk-HZYRLIOC.js +0 -137
- package/dist/chunks/chunk-SC2ELSUS.js +0 -675
- package/dist/chunks/chunk-TEUD5VPJ.js +0 -471
- package/dist/chunks/chunk-TYZ2ZAYL.js +0 -487
- package/dist/chunks/dist-3UCCMCYR.js +0 -2
- package/dist/chunks/dist-F5IWZSAY.js +0 -2
- package/dist/chunks/host-W2JJ3V3Q.js +0 -2
- package/dist/chunks/run-manager-RBWU3EVE.js +0 -2
- package/dist/chunks/utils-DJ4ZFJGL.js +0 -2
- package/dist/runtime-worker.js +0 -5381
- package/dist/types-chunks/review-inbox.d-CTeUIKda.d.ts +0 -225
- package/dist/types-chunks/run-manager.d-hm1XgEou.d.ts +0 -94
- package/dist/types-chunks/trusted-repl-entry-D0w5M0UZ.d.ts +0 -323
- package/dist/types-chunks/types.d-B1l9pWyX.d.ts +0 -146
package/dist/sdk-a2a.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import"./chunks/chunk-HPCS3LZ5.js";import"./chunks/chunk-SC2ELSUS.js";import{j as nt,p as rt}from"./chunks/chunk-GYO73UYQ.js";import"./chunks/chunk-YEAUDI6U.js";import"./chunks/chunk-TEUD5VPJ.js";import"./chunks/chunk-NKT3B3DR.js";import"./chunks/chunk-ABZDFK2X.js";import"./chunks/chunk-7O2AIFNE.js";import"./chunks/chunk-EM4XJBTK.js";import"./chunks/chunk-66XN5AFU.js";import"./chunks/chunk-C7U542KM.js";import"./chunks/chunk-NI7PBPUR.js";import{v as G}from"./chunks/chunk-WV3DJVW4.js";import"./chunks/chunk-DSXUXUZG.js";import"./chunks/chunk-HZYRLIOC.js";import{a as o}from"./chunks/chunk-ONUPGMER.js";var te="1.0",Pe="kodax-a2a-v1-jsonrpc";var A=class extends Error{constructor(n,r,i=200,s,a){super(r);this.code=n;this.httpStatus=i;this.data=s;this.headers=a;this.name="A2AError"}code;httpStatus;data;headers;static{o(this,"A2AError")}};function me(t){return t instanceof Error?t.message:String(t)}o(me,"errorMessage");var on=["apiKeySecurityScheme","httpAuthSecurityScheme","oauth2SecurityScheme","openIdConnectSecurityScheme","mtlsSecurityScheme"],an=["authorizationCode","clientCredentials","implicit","password","deviceCode"],cn=/^[\x21\x23-\x5B\x5D-\x7E]+$/u;function re(t,e){if(!cn.test(t))throw new Error(`${e} must be an RFC 6749 scope-token.`)}o(re,"assertOAuthScopeToken");function it(t,e){let n=t.split(" ");for(let r of n)re(r,e);return[...new Set(n)]}o(it,"parseOAuthScopeValue");function ie(t,e){if(!Array.isArray(t))throw new Error(`${e} must be an array of strings.`);let n=t.map((r,i)=>{if(typeof r!="string")throw new Error(`${e}[${i}] must be a string.`);return re(r,`${e}[${i}]`),r});if(new Set(n).size!==n.length)throw new Error(`${e} must not contain duplicates.`);return n}o(ie,"parseOAuthScopeList");function B(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}o(B,"isRecord");function O(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t}o(O,"requireNonEmptyString");function dn(t,e){if(t!==void 0)return O(t,e)}o(dn,"optionalString");function st(t,e){return O(t,e).trim()}o(st,"trimmedUri");function un(t){return/^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/u.exec(t)?.[1]?.includes("@")===!0}o(un,"hasAuthorityUserinfo");function ye(t){let e=t.toLowerCase().replace(/^\[|\]$/gu,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(ye,"isExactOAuthLoopbackHostname");function ot(t,e){let n=st(t,e);if(!/^https?:\/\/([^/?#]*)/iu.exec(n)?.[1])throw new Error(`${e} must be an absolute HTTP(S) URL.`);let i;try{i=new URL(n)}catch{throw new Error(`${e} must be an absolute HTTP(S) URL.`)}if(un(n)||i.username||i.password||n.includes("#"))throw new Error(`${e} must not contain userinfo or a fragment.`);if(i.protocol==="http:"&&!ye(i.hostname))throw new Error(`${e} must use HTTPS or exact loopback HTTP.`);return{raw:n,url:i}}o(ot,"secureOAuthHttpUrl");function F(t,e){let n=ot(t,e);if(n.raw.includes("?"))throw new Error(`${e} must not contain a query or fragment.`);return n.raw}o(F,"parseOAuthIssuerIdentifier");function $(t,e){return ot(t,e).url}o($,"parseOAuthEndpointUrl");function ne(t,e){let n=st(t,e);if(!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(n))throw new Error(`${e} must be an absolute URI.`);try{new URL(n)}catch{throw new Error(`${e} must be an absolute URI.`)}if(n.includes("#"))throw new Error(`${e} must not contain a fragment.`);return n}o(ne,"parseOAuthResourceIdentifier");function at(t,e){return $(t,e).href}o(at,"absoluteHttpUrl");function ln(t,e){if(!B(t))throw new Error(`${e} must be a scope-description object.`);return Object.entries(t).map(([n,r])=>{if(n.trim().length===0||typeof r!="string")throw new Error(`${e} must map non-empty scope names to descriptions.`);return re(n,`${e}.${n}`),n})}o(ln,"parseScopes");function An(t,e){if(!B(e))throw new Error(`securitySchemes.${t}.httpAuthSecurityScheme must be an object.`);let n=O(e.scheme,`securitySchemes.${t}.httpAuthSecurityScheme.scheme`),r=dn(e.bearerFormat,`securitySchemes.${t}.httpAuthSecurityScheme.bearerFormat`);return n.toLowerCase()!=="bearer"?{name:t,kind:"unsupported",protocol:`http:${n.toLowerCase()}`}:{name:t,kind:"http-bearer",...r?{bearerFormat:r}:{}}}o(An,"parseHttpScheme");function pn(t,e){let n=e.flows;if(!B(n))throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows must be an object.`);let r=an.filter(c=>n[c]!==void 0);if(r.length!==1)throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows must contain exactly one OAuth flow.`);let i=r[0],s=n[i];if(!B(s))throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows.${i} must be an object.`);let a=ln(s.scopes,`securitySchemes.${t}.oauth2SecurityScheme.flows.${i}.scopes`);if(i==="clientCredentials"){let c=at(s.tokenUrl,`securitySchemes.${t}.oauth2SecurityScheme.flows.clientCredentials.tokenUrl`);return{name:t,kind:"oauth2-client-credentials",tokenUrl:c,scopes:a}}return{name:t,kind:"unsupported",protocol:`oauth2:${i}`,oauthScopes:a}}o(pn,"parseOAuthFlow");function fn(t,e,n){if(!B(n))throw new Error(`securitySchemes.${t}.${e} must be an object.`);if(e==="apiKeySecurityScheme"){let r=O(n.location,`securitySchemes.${t}.${e}.location`);if(!["query","header","cookie"].includes(r))throw new Error(`securitySchemes.${t}.${e}.location must be query, header, or cookie.`);return O(n.name,`securitySchemes.${t}.${e}.name`),{name:t,kind:"unsupported",protocol:"api-key"}}return e==="openIdConnectSecurityScheme"?(at(n.openIdConnectUrl,`securitySchemes.${t}.${e}.openIdConnectUrl`),{name:t,kind:"unsupported",protocol:"openid-connect",acceptsOAuthScopes:!0}):{name:t,kind:"unsupported",protocol:"mutual-tls"}}o(fn,"parseUnsupportedScheme");function hn(t,e){if(!B(e))throw new Error(`securitySchemes.${t} must be an object.`);let n=on.filter(i=>e[i]!==void 0);if(n.length!==1)throw new Error(`securitySchemes.${t} must contain exactly one security scheme.`);let r=n[0];if(r==="httpAuthSecurityScheme")return An(t,e[r]);if(r==="oauth2SecurityScheme"){let i=e[r];if(!B(i))throw new Error(`securitySchemes.${t}.${r} must be an object.`);return pn(t,i)}return fn(t,r,e[r])}o(hn,"parseScheme");function gn(t){if(t===void 0)return{};if(!B(t))throw new Error("securitySchemes must be an object.");return Object.fromEntries(Object.entries(t).map(([e,n])=>{if(e.trim().length===0)throw new Error("securitySchemes names must not be empty.");return[e,hn(e,n)]}))}o(gn,"parseSchemes");function mn(t,e){if(!B(t))throw new Error(`${e} must be a StringList object.`);if(t.list===void 0)return[];if(!Array.isArray(t.list)||!t.list.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${e}.list must be an array of non-empty strings.`);if(new Set(t.list).size!==t.list.length)throw new Error(`${e}.list must not contain duplicate scopes.`);for(let n of t.list)re(n,`${e}.list`);return t.list}o(mn,"parseScopeList");function yn(t,e){if(t.kind==="oauth2-client-credentials"||t.kind==="unsupported"&&t.oauthScopes!==void 0){let n=t.kind==="oauth2-client-credentials"?t.scopes:t.oauthScopes??[];for(let r of e)if(!n.includes(r))throw new Error(`scope "${r}" is not declared by security scheme "${t.name}".`);return}if(e.length>0&&!(t.kind==="unsupported"&&t.acceptsOAuthScopes))throw new Error(`security scheme "${t.name}" does not accept OAuth scopes.`)}o(yn,"validateRequiredScopes");function wn(t,e,n){if(!B(t))throw new Error(`securityRequirements[${e}] must be an object.`);let r=t.schemes;if(r!==void 0&&!B(r))throw new Error(`securityRequirements[${e}].schemes must be an object.`);return{schemes:Object.entries(r??{}).map(([a,c])=>{if(!Object.hasOwn(n,a))throw new Error(`securityRequirements[${e}] references unknown security scheme "${a}".`);let d=n[a],u=mn(c,`securityRequirements[${e}].schemes.${a}`);return yn(d,u),{scheme:d,scopes:u}})}}o(wn,"parseRequirement");function J(t,e){let n=gn(t);if(e===void 0)return{schemes:n,requirements:[]};if(!Array.isArray(e))throw new Error("securityRequirements must be an array.");return{schemes:n,requirements:e.map((r,i)=>wn(r,i,n))}}o(J,"parseA2ASecurity");function kn(t,e){let{scheme:n,scopes:r}=e;return n.kind!=="unsupported"&&t.schemeName===n.name&&t.kind===n.kind&&r.every(i=>t.scopes?.includes(i)===!0)}o(kn,"capabilityMatches");function Ki(t,e){return we(t,e)[0]??null}o(Ki,"selectA2ASecurityRequirement");function we(t,e){return(t.requirements.length===0?[{schemes:[]}]:t.requirements).filter(r=>r.schemes.every(i=>e.some(s=>kn(s,i))))}o(we,"satisfiableA2ASecurityRequirements");var Sn=new Set(["TASK_STATE_UNSPECIFIED","TASK_STATE_SUBMITTED","TASK_STATE_WORKING","TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_INPUT_REQUIRED","TASK_STATE_REJECTED","TASK_STATE_AUTH_REQUIRED"]);function g(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}o(g,"isRecord");function ct(t){if(t===null)return;let e=t.split(";",1)[0]?.trim().toLowerCase();return e&&!/\s/u.test(e)?e:void 0}o(ct,"mediaTypeEssence");function de(t){let e=ct(t);return e==="application/json"||/^application\/[!#$%&'*+\-.^_`|~0-9a-z]+\+json$/u.test(e??"")}o(de,"isJsonMediaType");function dt(t){return ct(t)==="text/event-stream"}o(dt,"isEventStreamMediaType");function U(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new A(-32602,`${n}.${e} must be a non-empty string.`);return r}o(U,"requiredString");function x(t,e){let n=t[e];return typeof n=="string"&&n.length>0?n:void 0}o(x,"optionalString");function se(t,e){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new A(-32602,`${e} must be a string array.`);return t}o(se,"stringArray");function Rn(t){if(!g(t))throw new A(-32602,"Agent Card interface is invalid.");return{url:U(t,"url","interface"),protocolBinding:U(t,"protocolBinding","interface"),protocolVersion:U(t,"protocolVersion","interface"),...x(t,"tenant")?{tenant:x(t,"tenant")}:{}}}o(Rn,"parseInterface");function ut(t,e,n){try{J(t,e)}catch(r){let i=r instanceof Error?r.message:String(r);throw new A(-32602,`${n} is invalid: ${i}`)}}o(ut,"validateSecurity");function Tn(t,e){if(!g(t))throw new A(-32602,"Agent Card skill is invalid.");return t.securityRequirements!==void 0&&ut(e,t.securityRequirements,"skill.securityRequirements"),{id:U(t,"id","skill"),name:U(t,"name","skill"),description:U(t,"description","skill"),tags:se(t.tags,"skill.tags"),...Array.isArray(t.examples)?{examples:se(t.examples,"skill.examples")}:{},...Array.isArray(t.inputModes)?{inputModes:se(t.inputModes,"skill.inputModes")}:{},...Array.isArray(t.outputModes)?{outputModes:se(t.outputModes,"skill.outputModes")}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(g)}:{}}}o(Tn,"parseSkill");function En(t){if(!g(t))throw new A(-32602,"Agent Card extension is invalid.");let e=U(t,"uri","extension");try{new URL(e)}catch{throw new A(-32602,"Agent Card extension.uri must be an absolute URI.")}if(t.description!==void 0&&typeof t.description!="string")throw new A(-32602,"Agent Card extension.description must be a string.");if(t.required!==void 0&&typeof t.required!="boolean")throw new A(-32602,"Agent Card extension.required must be a boolean.");if(t.params!==void 0&&!g(t.params))throw new A(-32602,"Agent Card extension.params must be an object.");return{uri:e,...typeof t.description=="string"?{description:t.description}:{},...typeof t.required=="boolean"?{required:t.required}:{},...g(t.params)?{params:t.params}:{}}}o(En,"parseExtension");function lt(t){if(!g(t))throw new A(-32602,"Agent Card must be an object.");let e=t.supportedInterfaces,n=t.skills;if(!Array.isArray(e)||e.length===0)throw new A(-32602,"Agent Card must declare supportedInterfaces.");if(!Array.isArray(n))throw new A(-32602,"Agent Card must declare skills.");if(!g(t.capabilities))throw new A(-32602,"Agent Card capabilities are invalid.");if(t.capabilities.extensions!==void 0&&!Array.isArray(t.capabilities.extensions))throw new A(-32602,"Agent Card capabilities.extensions must be an array.");return ut(t.securitySchemes,t.securityRequirements,"Agent Card security declaration"),{name:U(t,"name","Agent Card"),description:U(t,"description","Agent Card"),supportedInterfaces:e.map(Rn),version:U(t,"version","Agent Card"),capabilities:{...typeof t.capabilities.streaming=="boolean"?{streaming:t.capabilities.streaming}:{},...typeof t.capabilities.pushNotifications=="boolean"?{pushNotifications:t.capabilities.pushNotifications}:{},...typeof t.capabilities.extendedAgentCard=="boolean"?{extendedAgentCard:t.capabilities.extendedAgentCard}:{},...Array.isArray(t.capabilities.extensions)?{extensions:t.capabilities.extensions.map(En)}:{}},...g(t.securitySchemes)?{securitySchemes:t.securitySchemes}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(g)}:{},defaultInputModes:se(t.defaultInputModes,"Agent Card defaultInputModes"),defaultOutputModes:se(t.defaultOutputModes,"Agent Card defaultOutputModes"),skills:n.map(r=>Tn(r,t.securitySchemes))}}o(lt,"parseA2AAgentCard");function At(t){if(!g(t))throw new A(-32602,"Message Part must be an object.");let e=["text","raw","url","data"].filter(r=>t[r]!==void 0);if(e.length!==1)throw new A(-32602,"Message Part must contain exactly one content field.");let n=e[0];if(n!=="data"&&typeof t[n]!="string")throw new A(-32602,`Message Part ${n} content must be a string.`);return{...typeof t.text=="string"?{text:t.text}:{},...typeof t.raw=="string"?{raw:t.raw}:{},...typeof t.url=="string"?{url:t.url}:{},...t.data!==void 0?{data:t.data}:{},...g(t.metadata)?{metadata:t.metadata}:{},...x(t,"filename")?{filename:x(t,"filename")}:{},...x(t,"mediaType")?{mediaType:x(t,"mediaType")}:{}}}o(At,"parseA2APart");function D(t){if(!g(t))throw new A(-32602,"Message must be an object.");if(t.role!=="ROLE_USER"&&t.role!=="ROLE_AGENT")throw new A(-32602,"Message role is invalid.");if(!Array.isArray(t.parts)||t.parts.length===0)throw new A(-32602,"Message parts must not be empty.");return{messageId:U(t,"messageId","Message"),role:t.role,parts:t.parts.map(At),...x(t,"contextId")?{contextId:x(t,"contextId")}:{},...x(t,"taskId")?{taskId:x(t,"taskId")}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(D,"parseA2AMessage");function bn(t){if(!g(t)||!Array.isArray(t.parts)||t.parts.length===0)throw new A(-32603,"A2A artifact is invalid.");return{artifactId:U(t,"artifactId","Artifact"),parts:t.parts.map(At),...x(t,"name")?{name:x(t,"name")}:{},...x(t,"description")?{description:x(t,"description")}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(bn,"parseArtifact");function H(t){if(!g(t)||!g(t.status))throw new A(-32603,"A2A task is invalid.");let e=t.status.state;if(typeof e!="string")throw new A(-32603,"A2A task state is invalid.");let n=Sn.has(e)?e:"TASK_STATE_UNSPECIFIED";return{id:U(t,"id","Task"),contextId:x(t,"contextId")??"",status:{state:n,...t.status.message!==void 0?{message:D(t.status.message)}:{},...x(t.status,"timestamp")?{timestamp:x(t.status,"timestamp")}:{}},...Array.isArray(t.artifacts)?{artifacts:t.artifacts.map(bn)}:{},...Array.isArray(t.history)?{history:t.history.map(D)}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(H,"parseA2ATask");function pt(t){if(!g(t)||t.jsonrpc!=="2.0")throw new A(-32600,"Invalid JSON-RPC request.");if(typeof t.id!="string"&&typeof t.id!="number")throw new A(-32600,"JSON-RPC request id is required.");return{jsonrpc:"2.0",id:t.id,method:U(t,"method","JSON-RPC request"),...g(t.params)?{params:t.params}:{}}}o(pt,"parseJsonRpcRequest");import{lookup as In}from"node:dns/promises";import{request as xn}from"node:http";import{request as Cn}from"node:https";import{BlockList as vn,isIP as ft}from"node:net";import{Readable as Pn}from"node:stream";var ke=new vn;ke.addSubnet("127.0.0.0",8,"ipv4");ke.addAddress("::1","ipv6");function Oe(t){let e=ft(t);return e===4?ke.check(t,"ipv4"):e===6&&ke.check(t,"ipv6")}o(Oe,"isLoopbackAddress");function On(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(On,"isExactLoopbackHostname");function _e(t){let e=t.split(".").map(Number),[n,r,i,s]=e;return e.length!==4||n===void 0||r===void 0||i===void 0||s===void 0?!0:n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&i===0&&s!==9&&s!==10||n===192&&r===0&&i===2||n===198&&(r===18||r===19)||n===198&&r===51&&i===100||n===203&&r===0&&i===113||n>=224}o(_e,"isPrivateIpv4");function _n(t){if(Oe(t))return!0;let e=t.toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(e)?.[1];if(n)return _e(n);let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(r?.[1]&&r[2]){let i=Number.parseInt(r[1],16),s=Number.parseInt(r[2],16);return _e(`${i>>8}.${i&255}.${s>>8}.${s&255}`)}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")||e.startsWith("ff")}o(_n,"isPrivateIpv6");function Un(t){let e=ft(t);return e===4?_e(t):e===6?_n(t):!0}o(Un,"isPrivateAddress");async function ht(t,e){if(t.protocol!=="https:"&&t.protocol!=="http:")throw new A(-32602,"A2A URL must use HTTP or HTTPS.");if(!e.allowedOrigins.includes(t.origin))throw new A(-32602,`A2A origin is not allowed: ${t.origin}`);if(t.username||t.password)throw new A(-32602,"A2A URL must not include credentials.");let n=t.hostname.startsWith("[")&&t.hostname.endsWith("]")?t.hostname.slice(1,-1):t.hostname,r=await In(n,{all:!0,verbatim:!0});if(r.length===0)throw new A(-32602,"A2A hostname did not resolve.");if(n.toLowerCase()==="localhost"&&!r.every(a=>Oe(a.address)))throw new A(-32602,"A2A localhost target must resolve only to loopback addresses.");let i=On(n)&&r.every(a=>Oe(a.address));if(t.protocol==="http:"&&!i&&e.allowInsecureHttp!==!0)throw new A(-32602,"Non-loopback A2A targets must use HTTPS unless plaintext HTTP is explicitly allowed.");if(!e.allowPrivateAddresses&&r.some(a=>Un(a.address)))throw new A(-32602,"A2A private network targets are not allowed.");let s=r[0];if(s===void 0||s.family!==4&&s.family!==6)throw new A(-32602,"A2A hostname returned an unsupported address.");return{address:s.address,family:s.family}}o(ht,"validateA2AUrl");async function Mn(t,e){await ht(t,e)}o(Mn,"assertSafeA2AUrl");function Ln(t){if(t==null||typeof t=="string")return t??void 0;if(t instanceof URLSearchParams)return t.toString();if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new A(-32602,"A2A request body type is not supported by the safe transport.")}o(Ln,"encodeRequestBody");function qn(t){return((e,n,r)=>{if(typeof n=="object"&&n.all){r(null,[t]);return}r(null,t.address,t.family)})}o(qn,"pinnedLookup");function Nn(t,e,n){return new Promise((r,i)=>{let s=new Headers(e.headers);s.set("accept-encoding","identity");let a=(t.protocol==="https:"?Cn:xn)(t,{method:e.method,headers:Object.fromEntries(s),lookup:qn(n),signal:e.signal??void 0},c=>{let d=new Headers;for(let p=0;p<c.rawHeaders.length;p+=2){let h=c.rawHeaders[p],w=c.rawHeaders[p+1];h!==void 0&&w!==void 0&&d.append(h,w)}let u=c.statusCode??500,l=e.method!=="HEAD"&&u!==204&&u!==205&&u!==304?Pn.toWeb(c):null;r(new Response(l,{status:u,statusText:c.statusMessage,headers:d}))});a.once("error",i),a.end(Ln(e.body))})}o(Nn,"requestValidatedAddress");async function Ue(t,e,n,r){let i=await ht(t,n);return r!==void 0?r(t,e):Nn(t,e,i)}o(Ue,"openSafeA2AResponse");async function $n(t,e){let n=t.headers.get("content-length");if(n&&Number(n)>e)throw new A(-32603,"A2A response is too large.");if(!t.body)return new Uint8Array;let r=t.body.getReader(),i=[],s=0;for(;;){let d=await r.read();if(d.done)break;if(s+=d.value.byteLength,s>e)throw await r.cancel(),new A(-32603,"A2A response is too large.");i.push(d.value)}let a=new Uint8Array(s),c=0;for(let d of i)a.set(d,c),c+=d.byteLength;return a}o($n,"boundedBody");function Dn(t,e){if(!t)return{signal:e,cleanup:o(()=>{},"cleanup")};let n=new AbortController,r=o(()=>n.abort(t.reason),"abortFromCaller"),i=o(()=>n.abort(e.reason),"abortFromDeadline");return t.aborted?r():t.addEventListener("abort",r,{once:!0}),e.aborted?i():e.addEventListener("abort",i,{once:!0}),{signal:n.signal,cleanup:o(()=>{t.removeEventListener("abort",r),e.removeEventListener("abort",i)},"cleanup")}}o(Dn,"combineAbortSignals");async function V(t,e,n,r){let i=t,s=new Headers(e.headers).get("authorization");for(let a=0;a<=n.maxRedirects;a+=1){let c=new AbortController,d=setTimeout(()=>c.abort(new Error("A2A request timed out.")),n.requestTimeoutMs),u=Dn(e.signal,c.signal),f=new Headers(e.headers);s===null?f.delete("authorization"):f.set("authorization",s);try{let l=await Ue(i,{...e,headers:f,redirect:"manual",signal:u.signal},n,r);if(l.status<300||l.status>=400)return{response:l,body:await $n(l,n.maxResponseBytes),url:i};let p=l.headers.get("location");if(!p||a===n.maxRedirects)throw new A(-32603,"A2A redirect limit exceeded.");let h=new URL(p,i);await l.body?.cancel(),h.origin!==i.origin&&(s=null),i=h}finally{clearTimeout(d),u.cleanup()}}throw new A(-32603,"A2A redirect limit exceeded.")}o(V,"safeA2AFetch");function X(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}o(X,"decodeUtf8");import{createHash as Fn,randomUUID as Me}from"node:crypto";import*as K from"oauth4webapi";var Kn=6e4,jn=1e3,Bn=.1;function Hn(t,e){return new Response(e.byteLength===0?null:X(e),{status:t.status,statusText:t.statusText,headers:t.headers})}o(Hn,"oauthResponse");function zn(t,e){if(e===void 0||e<=0)return t;let n=e*1e3,r=Math.min(Kn,Math.max(jn,n*Bn));return t+Math.max(0,n-r)}o(zn,"cacheExpiry");function gt(t){let e=O(t.clientId,"OAuth 2.0 clientId");if(t.clientAuthenticationMethod!=="basic"&&t.clientAuthenticationMethod!=="post")throw new Error("OAuth 2.0 clientAuthenticationMethod must be basic or post.");let n=t.clientAuthenticationMethod,r=t.scopes===void 0?void 0:ie(t.scopes,"OAuth 2.0 scopes"),i=F(t.issuer,"OAuth 2.0 issuer"),s=$(t.tokenUrl,"OAuth 2.0 token endpoint"),a=t.resource===void 0?void 0:ne(t.resource,"OAuth 2.0 resource"),c={issuer:i,token_endpoint:s.href},d={client_id:e},u={...t.networkPolicy,maxRedirects:0},f=t.now??Date.now,l,p,h=0;async function w(k){let y=n==="post"?K.ClientSecretPost(k):K.ClientSecretBasic(k),T=new URLSearchParams;r&&r.length>0&&T.set("scope",r.join(" ")),a!==void 0&&T.set("resource",a);let m={[K.customFetch]:async(R,_)=>{if(new URL(R).href!==s.href)throw new Error("OAuth 2.0 token request targeted an unexpected endpoint.");let j=await V(s,{method:_.method,headers:_.headers,body:_.body,redirect:"manual",..._.signal!==void 0?{signal:_.signal}:{}},u,t.fetch);return Hn(j.response,j.body)}};s.protocol==="http:"&&(m[K.allowInsecureRequests]=!0);let S;try{let R=await K.clientCredentialsGrantRequest(c,d,y,T,m);S=await K.processClientCredentialsResponse(c,d,R)}catch{throw new Error("OAuth 2.0 client credentials token request failed.")}if(S.token_type!=="bearer")throw new Error("OAuth 2.0 token endpoint did not return a Bearer access token.");let L=f();return{value:`Bearer ${S.access_token}`,expiresAt:zn(L,S.expires_in)}}return o(w,"requestAuthorization"),{async getAuthorization(k){if(k.length===0)throw new Error("OAuth 2.0 client secret is required.");let y=f();if(l!==void 0&&l.expiresAt>y)return l.value;if(p!==void 0)return p;let T=h,m;return m=w(k).then(S=>(h===T&&S.expiresAt>f()&&(l=S),S.value)).finally(()=>{p===m&&(p=void 0)}),p=m,m},invalidate(k){if(k!==void 0){l?.value===k&&(l=void 0);return}h+=1,l=void 0,p=void 0}}}o(gt,"createOAuth2ClientCredentialsTokenManager");var mt=4,yt=/^[A-Za-z0-9\-._~+/=]$/u;function Se(t){return t!==void 0&&/^Bearer\s+\S+$/iu.test(t)}o(Se,"isBearerAuthorization");function Jn(t,e){let n="",r=0;for(;r<t.length;){let i=t.indexOf(e,r);if(i<0)return n+t.slice(r);let s=i===0?void 0:t[i-1],a=i+e.length,c=a===t.length?void 0:t[a],d=s===void 0||!yt.test(s),u=c===void 0||!yt.test(c);n+=t.slice(r,i),d&&u?(n+="[REDACTED]",r=a):(n+=e,r=a)}return n}o(Jn,"replaceBoundedToken");function Ae(t){return Array.isArray(t)?`[${t.map(Ae).join(",")}]`:g(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Ae(t[e])}`).join(",")}}`:JSON.stringify(t)??"null"}o(Ae,"stableJson");function wt(t){return`sha256:${Fn("sha256").update(t).digest("hex")}`}o(wt,"sha256");var qe=class{static{o(this,"AuthorizationRedactor")}#e=[];#n=new Map;remember(e){if(!e)return;let n=this.#e.indexOf(e);n>=0&&this.#e.splice(n,1),this.#e.unshift(e),this.#e.length>mt&&(this.#e.length=mt)}retain(e){if(!e)return()=>{};this.remember(e),this.#n.set(e,(this.#n.get(e)??0)+1);let n=!1;return()=>{if(n)return;n=!0;let r=(this.#n.get(e)??1)-1;r===0?this.#n.delete(e):this.#n.set(e,r)}}redactText(e){let n=[...new Set([...this.#n.keys(),...this.#e])],r=n.sort((s,a)=>a.length-s.length).reduce((s,a)=>s.split(a).join("[REDACTED]"),e),i=n.flatMap(s=>{let a=/^Bearer\s+(\S+)$/iu.exec(s)?.[1];return a?[a]:[]}).sort((s,a)=>a.length-s.length);return[...new Set(i)].reduce((s,a)=>Jn(s,a),r)}redactContent(e){return typeof e=="string"?this.redactText(e):Array.isArray(e)?e.map(n=>this.redactContent(n)):g(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,this.redactContent(r)])):e}redactPart(e){return{...e,...e.text===void 0?{}:{text:this.redactText(e.text)},...e.raw===void 0?{}:{raw:this.redactText(e.raw)},...e.url===void 0?{}:{url:this.redactText(e.url)},...e.data===void 0?{}:{data:this.redactContent(e.data)},...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)},...e.filename===void 0?{}:{filename:this.redactText(e.filename)}}}redactMessage(e){return{...e,parts:e.parts.map(n=>this.redactPart(n)),...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactArtifact(e){return{...e,...e.name===void 0?{}:{name:this.redactText(e.name)},...e.description===void 0?{}:{description:this.redactText(e.description)},parts:e.parts.map(n=>this.redactPart(n)),...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactTask(e){return{...e,status:{...e.status,...e.status.message===void 0?{}:{message:this.redactMessage(e.status.message)}},...e.artifacts===void 0?{}:{artifacts:e.artifacts.map(n=>this.redactArtifact(n))},...e.history===void 0?{}:{history:e.history.map(n=>this.redactMessage(n))},...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactError(e){let n=this.redactText(e instanceof Error?e.message:String(e));return e instanceof A?new A(e.code,n,e.httpStatus,this.redactContent(e.data),e.headers):new Error(n)}};function kt(t,e){let n=new URL(e).origin;if(!t.allowedOrigins.some(i=>new URL(i).origin===n))throw new Error(`A2A endpoint origin is not allowed by network policy: ${n}`);return{...t,allowedOrigins:[n]}}o(kt,"endpointNetworkPolicy");function Wn(t){if(t!==void 0){if(!g(t)||typeof t.scheme!="string")throw new Error("A2A registration authentication is invalid.");if(t.type==="http-bearer")return{type:"http-bearer",scheme:t.scheme};if(t.type!=="oauth2-client-credentials"||typeof t.issuer!="string"||typeof t.tokenUrl!="string"||typeof t.clientId!="string"||!Array.isArray(t.scopes)||!t.scopes.every(e=>typeof e=="string")||!["client-secret-basic","client-secret-post"].includes(String(t.clientAuthentication)))throw new Error("A2A registration OAuth2 authentication is invalid.");return{type:"oauth2-client-credentials",scheme:t.scheme,issuer:t.issuer,tokenUrl:t.tokenUrl,clientId:t.clientId,scopes:t.scopes,...typeof t.resource=="string"?{resource:t.resource}:{},clientAuthentication:t.clientAuthentication}}}o(Wn,"executorAuthentication");function Q(t){let e=t.executorConfig;if(!g(e))throw new Error("A2A registration executorConfig is missing.");if(typeof e.agentCardUrl!="string"||typeof e.interfaceUrl!="string")throw new Error("A2A registration endpoints are invalid.");let n=Wn(e.authentication);return{agentCardUrl:e.agentCardUrl,interfaceUrl:e.interfaceUrl,...typeof e.tenant=="string"?{tenant:e.tenant}:{},...n?{authentication:n}:{}}}o(Q,"executorConfig");function Gn(t,e){let n=t.supportedInterfaces.find(i=>i.protocolBinding.toUpperCase()==="JSONRPC"&&i.protocolVersion==="1.0");if(!n)throw new Error("Agent Card has no supported A2A 1.0 JSONRPC interface.");let r=new URL(n.url);if(r.username||r.password||r.hash)throw new Error("A2A interface URL must not contain credentials or a fragment.");if(r.origin!==e.origin)throw new Error("A2A interface must use the same origin as the trusted Agent Card.");return n}o(Gn,"chooseInterface");function Vn(t){if(t===void 0)return;if(!g(t))throw new Error("A2A authentication must be an object.");let e=O(t.scheme,"A2A authentication.scheme");if(t.type==="http-bearer")return{type:"http-bearer",scheme:e,credentialRef:O(t.credentialRef,"A2A authentication.credentialRef")};if(t.type!=="oauth2-client-credentials")throw new Error("A2A authentication.type must be http-bearer or oauth2-client-credentials.");if(t.clientAuthentication!=="client-secret-basic"&&t.clientAuthentication!=="client-secret-post")throw new Error("A2A authentication.clientAuthentication is invalid.");return{type:"oauth2-client-credentials",scheme:e,issuer:F(t.issuer,"Configured OAuth2 issuer"),tokenUrl:$(t.tokenUrl,"Configured OAuth2 token endpoint").href,clientId:O(t.clientId,"Configured OAuth2 clientId"),clientSecretRef:O(t.clientSecretRef,"Configured OAuth2 clientSecretRef"),scopes:ie(t.scopes,"Configured OAuth2 scopes"),...t.resource===void 0?{}:{resource:ne(t.resource,"Configured OAuth2 resource")},clientAuthentication:t.clientAuthentication}}o(Vn,"validatedClientAuthentication");function Xn(t){let e=t.credentialRef===void 0?void 0:O(t.credentialRef,"A2A credentialRef"),n=Vn(t.authentication);if(t.credentialRef!==void 0&&t.authentication!==void 0)throw new Error("A2A registration cannot combine credentialRef with structured authentication.");return{agentId:t.agentId,agentCardUrl:t.agentCardUrl,...e!==void 0?{credentialRef:e}:{},...n!==void 0?{authentication:n}:{},effects:t.effects}}o(Xn,"validatedRegistrationInput");function Qn(t,e,n){if(t.authentication)return[[{schemeName:t.authentication.scheme,kind:t.authentication.type,...t.authentication.type==="oauth2-client-credentials"?{scopes:t.authentication.scopes}:{}}]];let r=Se(n);if(!t.credentialRef&&!r)return[[]];let i=J(e.securitySchemes,e.securityRequirements);return Object.values(i.schemes).flatMap(s=>s.kind==="http-bearer"?[[{schemeName:s.name,kind:"http-bearer"}]]:[])}o(Qn,"configuredCapabilityCandidates");function St(t,e){for(let n of t){if(n.schemes.length!==1)continue;let r=n.schemes[0].scheme;if(e.some(i=>i.schemeName===r.name&&i.kind===r.kind))return r}}o(St,"matchingDeclaredScheme");function Zn(t,e){let n=J(t.securitySchemes,t.securityRequirements),r=we(n,e).filter(a=>a.schemes.length<=1);if(r.length===0)return null;let i=St(r,e),s=[];for(let a of t.skills){let c=J(t.securitySchemes,a.securityRequirements),d=we(c,e).filter(u=>u.schemes.length<=1);d.length!==0&&(s.push(a.id),i??=St(d,e))}return t.skills.length>0&&s.length===0?null:{skillIds:s,...i?{declaredScheme:i}:{}}}o(Zn,"evaluateSecurityCapabilities");function Yn(t,e,n){if(t.credentialRef!==void 0&&t.authentication!==void 0)throw new Error("A2A registration cannot combine credentialRef with structured authentication.");if(n!==void 0&&!Se(n))throw new Error("A2A options.authorization must be a valid Bearer authorization.");let r=Se(n),i=t.credentialRef!==void 0||t.authentication!==void 0||r,s;for(let h of Qn(t,e,n)){let w=Zn(e,h);if(w&&(!i||w.declaredScheme)){s=w;break}}if(!s)throw new Error(i?"Configured A2A authentication cannot fully satisfy the Agent Card and any advertised Skill security requirements.":"Agent Card or at least one advertised Skill requires authentication, but no compatible A2A authentication is configured.");if(!i)return{skillIds:s.skillIds};let a=s.declaredScheme,c=t.authentication;if(!c&&!t.credentialRef&&r)return{skillIds:s.skillIds};if(!c)return{credentialRef:t.credentialRef,authentication:{type:"http-bearer",scheme:a.name},skillIds:s.skillIds};if(c.type==="http-bearer")return{credentialRef:c.credentialRef,authentication:{type:"http-bearer",scheme:c.scheme},skillIds:s.skillIds};if(a.kind!=="oauth2-client-credentials")throw new Error("Configured OAuth2 authentication does not match the selected Agent Card scheme.");let d=a,u=F(c.issuer,"Configured OAuth2 issuer"),f=$(c.tokenUrl,"Configured OAuth2 token endpoint").href,l=c.resource===void 0?void 0:ne(c.resource,"Configured OAuth2 resource");if(new URL(d.tokenUrl).href!==f)throw new Error("Configured OAuth2 tokenUrl does not match the selected Agent Card security scheme.");let p=c.scopes.find(h=>!d.scopes.includes(h));if(p)throw new Error(`Configured OAuth2 scope is not declared by the Agent Card: ${p}`);return{credentialRef:c.clientSecretRef,authentication:{type:"oauth2-client-credentials",scheme:c.scheme,issuer:u,tokenUrl:f,clientId:c.clientId,scopes:c.scopes,...l?{resource:l}:{},clientAuthentication:c.clientAuthentication},skillIds:s.skillIds}}o(Yn,"planClientAuthentication");function Ne(t,e){try{return JSON.parse(t)}catch{throw new Error(`${e} returned invalid JSON.`)}}o(Ne,"parseJson");function Et(t){let e=t.maxTaskResponseBytes??t.networkPolicy.maxResponseBytes;if(!Number.isSafeInteger(e)||e<=0)throw new Error("A2A maxTaskResponseBytes must be a positive safe integer.");return e}o(Et,"taskResponseBytes");function er(t){return{...t.networkPolicy,maxResponseBytes:Et(t)}}o(er,"taskNetworkPolicy");async function bt(t,e){let n=Xn(t),r=await V(new URL(n.agentCardUrl),{headers:{accept:"application/json"}},e.networkPolicy,e.fetch);if(!r.response.ok)throw new Error(`Agent Card request failed with HTTP ${r.response.status}.`);if(!de(r.response.headers.get("content-type")))throw new Error("Agent Card response is not JSON.");let i=lt(Ne(X(r.body),"Agent Card")),s=i.capabilities.extensions?.filter(f=>f.required)??[];if(s.length>0)throw new Error(`Agent Card required A2A extension(s) are unsupported: ${s.map(f=>f.uri).join(", ")}`);let a=Gn(i,r.url),c=Yn(n,i,e.authorization),d=Ae({agentCardUrl:r.url.href,interfaceUrl:a.url,protocolBinding:a.protocolBinding,protocolVersion:a.protocolVersion,tenant:a.tenant??"",authentication:c.authentication??null}),u=wt(Ae({card:i,endpointIdentity:d,credentialRef:c.credentialRef??null,effects:n.effects}));return{agentCard:i,registration:{agentId:n.agentId,displayName:i.name,description:i.description,enabled:!0,executorId:Pe,protocol:"a2a",configurationRevision:u,endpointIdentityHash:wt(d),...c.credentialRef?{credentialRef:c.credentialRef}:{},executorConfig:{agentCardUrl:r.url.href,interfaceUrl:a.url,...a.tenant?{tenant:a.tenant}:{},...c.authentication?{authentication:c.authentication}:{}},skills:c.skillIds,inputModalities:i.defaultInputModes,outputModalities:i.defaultOutputModes,capabilities:{streaming:i.capabilities.streaming?"supported":"unsupported",durableTasks:"supported",inputRequired:"supported",cancellation:"supported",artifacts:"supported"},effects:{remote:n.effects.remote,workspace:"proposal"},health:{status:"healthy",checkedAt:new Date().toISOString()}}}}o(bt,"discoverA2ARegistration");function le(t){return t.metadata??{}}o(le,"metadata");function $e(t){if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(Array.isArray(t))return t.map($e);if(g(t)){let e={};for(let[n,r]of Object.entries(t))e[n]=$e(r);return e}throw new Error("A2A response metadata must be JSON-safe.")}o($e,"toAgentJsonValue");function Rt(t){let e=le(t).directMessage;return e===void 0?void 0:D(e)}o(Rt,"directMessage");function tr(t){return{TASK_STATE_UNSPECIFIED:"unknown",TASK_STATE_SUBMITTED:"submitted",TASK_STATE_WORKING:"working",TASK_STATE_COMPLETED:"completed",TASK_STATE_FAILED:"failed",TASK_STATE_CANCELED:"canceled",TASK_STATE_INPUT_REQUIRED:"input-required",TASK_STATE_REJECTED:"rejected",TASK_STATE_AUTH_REQUIRED:"auth-required"}[t]??"unknown"}o(tr,"taskState");function De(t){return t.flatMap(e=>e.text===void 0?[]:[e.text]).join(`
|
|
3
|
-
`)}o(De,"textFromParts");function It(t,e){let n=t.mediaType??(t.data!==void 0?"application/json":"application/octet-stream"),r=t.raw!==void 0?`data:${n};base64,${t.raw}`:t.data!==void 0?`data:${n};base64,${Buffer.from(JSON.stringify(t.data),"utf8").toString("base64")}`:void 0,i=t.url??r;if(i)return{name:e,...t.mediaType?{mimeType:t.mediaType}:{},...t.raw!==void 0?{size:Buffer.from(t.raw,"base64").byteLength}:{},uri:i,provenance:"a2a"}}o(It,"partArtifactReference");function
|
|
4
|
-
`);return{state:
|
|
5
|
-
`);if(!R)continue;let _=await this.snapshotFromStreamPayload(Ne(R,"A2A stream"),a,e,k);if(_&&(yield _,_.state&&(Tt(_.state)||_.state==="input-required"||_.state==="auth-required")))return}}if(!this.#e)throw new Error("A2A event stream ended before the task reached a stable state.")}catch(l){throw this.#t.redactError(l)}finally{u(),c?.(),this.#n.delete(s)}}async snapshotFromStreamPayload(e,n,r,i){if(!g(e))throw new Error("A2A stream frame is invalid.");if(e.jsonrpc!=="2.0"||e.id!==n)throw new Error("A2A stream frame has an invalid JSON-RPC version or response id.");if(e.error!==void 0){let s=g(e.error)?e.error:{},a=typeof s.message=="string"?s.message:"A2A stream error.";throw new A(typeof s.code=="number"?s.code:-32603,this.#t.redactText(a))}if(g(e.result)){if(e.result.task!==void 0){let s=H(e.result.task);this.assertTaskReference(s,r),i.clear();for(let a of s.artifacts??[])i.set(a.artifactId,a);return this.authorizeArtifacts(ue(this.#t.redactTask(s)))}if(e.result.message!==void 0){let s=D(e.result.message);if(s.taskId!==void 0&&s.taskId!==r.remoteTaskId)throw new Error("A2A stream message belongs to a different task.");return this.authorizeArtifacts(Le(this.#t.redactMessage(s)))}if(g(e.result.statusUpdate)&&g(e.result.statusUpdate.status)){this.assertStreamTaskScope(e.result.statusUpdate,r);let s=H({id:r.remoteTaskId,contextId:e.result.statusUpdate.contextId,status:e.result.statusUpdate.status,...i.size>0?{artifacts:[...i.values()]}:{}});return this.authorizeArtifacts(ue(this.#t.redactTask(s)))}if(g(e.result.artifactUpdate)&&e.result.artifactUpdate.artifact!==void 0){this.assertStreamTaskScope(e.result.artifactUpdate,r);let s=H({id:r.remoteTaskId,contextId:e.result.artifactUpdate.contextId,status:{state:"TASK_STATE_WORKING"},artifacts:[e.result.artifactUpdate.artifact]}),a=s.artifacts?.[0];if(!a)throw new Error("A2A artifact update has no artifact.");rr(i,a,e.result.artifactUpdate.append===!0);let c={...s,artifacts:[...i.values()]};return this.authorizeArtifacts(ue(this.#t.redactTask(c)))}}}async authorizeArtifacts(e){for(let n of e.artifacts??[])await this.context.authorizeArtifact(n);return e}assertTaskReference(e,n){if(e.id!==n.remoteTaskId)throw new Error("A2A response belongs to a different task id.");let r=le(n).contextId;if(typeof r=="string"&&e.contextId&&e.contextId!==r)throw new Error("A2A response belongs to a different task context.")}assertStreamTaskScope(e,n){if(typeof e.taskId!="string"||e.taskId!==n.remoteTaskId)throw new Error("A2A stream event belongs to a different task.");let r=le(n).contextId;if(typeof e.contextId!="string"||typeof r=="string"&&e.contextId!==r)throw new Error("A2A stream event belongs to a different task context.")}async openStreamResponse(e,n,r,i){let s=o(a=>{let c=new Headers(n);return a&&c.set("authorization",a),Ue(e,{method:"POST",headers:c,redirect:"manual",signal:r,body:JSON.stringify(i)},this.options.networkPolicy,this.options.fetch)},"open");return this.withAuthorization(async a=>{let c=this.#t.retain(a);try{let d=await s(a);if(d.status===401)throw await d.body?.cancel(),new A(-32600,"A2A authentication was rejected.",401);return{response:d,releaseAuthorization:c}}catch(d){throw c(),d}})}taskParams(e){let n=Q(this.registration);return{id:e.remoteTaskId,...n.tenant?{tenant:n.tenant}:{}}}async sendMessage(e,n){let r=await this.rpc("SendMessage",{...e,...Q(this.registration).tenant?{tenant:Q(this.registration).tenant}:{}},n);if(!g(r))throw new Error("A2A SendMessage result is invalid.");return r}async rpc(e,n,r){if(this.#e)throw new Error("A2A executor is disposed.");return this.withAuthorization(i=>this.rpcWithAuthorization(e,n,i,r))}redactRpcResult(e,n){return e==="GetTask"||e==="CancelTask"?this.#t.redactTask(H(n)):e!=="SendMessage"||!g(n)?n:{...n,...n.task===void 0?{}:{task:this.#t.redactTask(H(n.task))},...n.message===void 0?{}:{message:this.#t.redactMessage(D(n.message))}}}async withAuthorization(e){let n=Q(this.registration).authentication;if(!n){if(this.options.authorization!==void 0&&!Se(this.options.authorization))throw new Error("A2A options.authorization must be a valid Bearer authorization.");let c=this.#t.retain(this.options.authorization);try{return await e(this.options.authorization)}catch(d){throw this.#t.redactError(d)}finally{c()}}let r=this.registration.credentialRef;if(!r)throw new Error("Authenticated A2A registration has no credential reference.");let i=o(c=>this.context.withCredential(r,async d=>{let u,f;try{return u=n.type==="http-bearer"?`Bearer ${d}`:await this.requireOAuthTokenManager().getAuthorization(d),f=this.#t.retain(u),{ok:!0,value:await e(u)}}catch(l){if(c&&n.type==="oauth2-client-credentials"&&l instanceof A&&l.httpStatus===401&&u!==void 0)return{ok:!1,rejectedAuthorization:u};throw this.#t.redactError(l)}finally{f?.()}}),"execute"),s=await i(n.type==="oauth2-client-credentials");if(s.ok)return s.value;this.requireOAuthTokenManager().invalidate(s.rejectedAuthorization);let a=await i(!1);if(!a.ok)throw new Error("A2A OAuth2 retry did not produce a result.");return a.value}requireOAuthTokenManager(){if(!this.oauthTokenManager)throw new Error("A2A OAuth2 token manager is unavailable.");return this.oauthTokenManager}async rpcWithAuthorization(e,n,r,i){let s=Q(this.registration),a=new Headers({accept:"application/json","a2a-version":"1.0","content-type":"application/json"});r&&a.set("authorization",r);let c=Me(),d=await V(new URL(s.interfaceUrl),{method:"POST",headers:a,body:JSON.stringify({jsonrpc:"2.0",id:c,method:e,params:n}),...i?{signal:i}:{}},er(this.options),this.options.fetch);if(d.response.status===401)throw new A(-32600,"A2A authentication was rejected.",401);if(!de(d.response.headers.get("content-type")))throw new Error("A2A JSON-RPC response has an invalid content type.");let u=Ne(X(d.body),"A2A endpoint");if(!g(u))throw new Error("A2A JSON-RPC response is invalid.");if(u.jsonrpc!=="2.0"||u.id!==c)throw new Error("A2A JSON-RPC response has an invalid version or response id.");let f=Object.hasOwn(u,"result"),l=Object.hasOwn(u,"error");if(f===l)throw new Error("A2A JSON-RPC response must contain exactly one result or error.");if(l)throw!g(u.error)||typeof u.error.code!="number"||typeof u.error.message!="string"?new Error("A2A JSON-RPC error response is invalid."):new A(u.error.code,this.#t.redactText(u.error.message),d.response.status,this.#t.redactContent(u.error.data));if(!d.response.ok)throw new Error(`A2A request failed with HTTP ${d.response.status}.`);return this.redactRpcResult(e,u.result)}};function xt(t){let e=new Map;return{executorId:Pe,protocol:"a2a",async create(n,r){let i=typeof t=="function"?t(n):t,s=Q(n),a=s.authentication,c={...i,networkPolicy:kt(i.networkPolicy,s.interfaceUrl)},d;if(a?.type==="oauth2-client-credentials"){let p=kt(i.networkPolicy,a.tokenUrl),h=Ae({authentication:a,credentialRef:n.credentialRef??"",networkPolicy:p}),w=e.get(n.agentId);if(d=w?.key===h&&w.fetch===i.fetch?w:void 0,!d){let k=gt({issuer:a.issuer,tokenUrl:a.tokenUrl,clientId:a.clientId,scopes:a.scopes,...a.resource?{resource:a.resource}:{},clientAuthenticationMethod:a.clientAuthentication==="client-secret-post"?"post":"basic",networkPolicy:p,...i.fetch?{fetch:i.fetch}:{}});d={key:h,fetch:i.fetch,manager:k,references:0},e.set(n.agentId,d)}}if(!d)return new Re(n,r,c);let u=d;u.references+=1;let f=!1,l=o(()=>{f||(f=!0,u.references-=1,u.references===0&&(u.manager.invalidate(),e.get(n.agentId)===u&&e.delete(n.agentId)))},"releaseOAuthTokenManager");return new Re(n,r,c,u.manager,l)}}}o(xt,"createA2AAgentExecutorFactory");import{createHash as ar,randomUUID as he}from"node:crypto";import W from"node:fs";import{createServer as cr}from"node:http";import b from"node:path";import{Readable as Ot}from"node:stream";import{createHash as ir}from"node:crypto";var Z="realm-subject-tenant-v1";function Ct(t){return ir("sha256").update(t).digest("hex")}o(Ct,"sha256");function vt(t){return Ct(`${t.subject}\0${t.tenant??""}`)}o(vt,"legacyA2APrincipalKey");function Te(t){return Ct(JSON.stringify([t.securityRealm,t.subject,t.tenant??null]))}o(Te,"realmA2APrincipalKey");import E from"node:fs";import pe from"node:path";import{createHash as sr}from"node:crypto";function Y(t){return structuredClone(t)}o(Y,"clone");function or(t){if(!g(t))throw new Error("A2A task store record must be an object.");for(let r of["taskId","contextId","principalKey","runtimeIdentity","sessionId","createdAt","updatedAt"])if(typeof t[r]!="string")throw new Error(`A2A task store record has invalid ${r}.`);if(!g(t.messageDigests)||!Object.values(t.messageDigests).every(r=>typeof r=="string"))throw new Error("A2A task store message digests are invalid.");if(!Array.isArray(t.runIds)||!t.runIds.every(r=>typeof r=="string"))throw new Error("A2A task store run IDs are invalid.");if(!Array.isArray(t.history))throw new Error("A2A task store history is invalid.");if(t.principalKeyScheme!==void 0&&t.principalKeyScheme!==Z)throw new Error("A2A task store principal key scheme is unsupported.");if(!Number.isSafeInteger(t.eventSeq))throw new Error("A2A task store event cursors are invalid.");let e=Pt(t.runtimeSessionCursor);if(t.runtimeSessionCursor!==void 0&&e===void 0)throw new Error("A2A task store Runtime Session cursor is invalid.");let n=t.pendingUserInput;if(n!==void 0&&(!g(n)||typeof n.requestId!="string"||!Number.isSafeInteger(n.revision)||typeof n.runId!="string"||typeof n.kind!="string"))throw new Error("A2A task store pending user input is invalid.");if(t.acceptedOutputModes!==void 0&&(!Array.isArray(t.acceptedOutputModes)||!t.acceptedOutputModes.every(r=>typeof r=="string")))throw new Error("A2A task store accepted output modes are invalid.");return{taskId:t.taskId,contextId:t.contextId,principalKey:t.principalKey,...t.principalKeyScheme===Z?{principalKeyScheme:Z}:{},runtimeIdentity:t.runtimeIdentity,sessionId:t.sessionId,...typeof t.workspaceRoot=="string"?{workspaceRoot:t.workspaceRoot}:{},...typeof t.executionPolicyRevision=="string"?{executionPolicyRevision:t.executionPolicyRevision}:{},messageDigests:t.messageDigests,runIds:t.runIds,task:H(t.task),history:t.history.map(D),createdAt:t.createdAt,updatedAt:t.updatedAt,eventSeq:t.eventSeq,...e!==void 0?{runtimeSessionCursor:e}:{},runtimeEventCount:Number.isSafeInteger(t.runtimeEventCount)?t.runtimeEventCount:0,runtimeEventBytes:Number.isSafeInteger(t.runtimeEventBytes)?t.runtimeEventBytes:0,...t.acceptedOutputModes!==void 0?{acceptedOutputModes:t.acceptedOutputModes}:{},...n!==void 0?{pendingUserInput:{requestId:n.requestId,revision:n.revision,runId:n.runId,kind:n.kind}}:{}}}o(or,"parseRecord");function Pt(t){if(!(!g(t)||typeof t.sessionId!="string"||t.sessionId.length===0||typeof t.journalEpoch!="string"||t.journalEpoch.length===0||!Number.isSafeInteger(t.seq)||typeof t.seq!="number"||t.seq<0))return{sessionId:t.sessionId,journalEpoch:t.journalEpoch,seq:t.seq}}o(Pt,"parseRuntimeSessionCursor");var oe=class{static{o(this,"A2AFileTaskStore")}#e=new Map;#n=new Map;#t;#s;#r;#i;constructor(e){let n=pe.resolve(e);E.mkdirSync(n,{recursive:!0,mode:448}),this.#t=pe.join(n,"tasks.json"),this.#s=pe.join(n,"runtime-cursors"),this.#r=pe.join(n,".server.lock"),this.#i=this.acquireLock();try{this.load()}catch(r){throw E.closeSync(this.#i),E.rmSync(this.#r,{force:!0}),r}}get(e){let n=this.#e.get(e);return n?Y(n):void 0}findByMessage(e,n){for(let r of this.#e.values())if(r.principalKey===e&&r.messageDigests[n]!==void 0)return Y(r)}list(e){return[...this.#e.values()].filter(n=>n.principalKey===e).sort((n,r)=>r.updatedAt.localeCompare(n.updatedAt)||r.taskId.localeCompare(n.taskId)).map(Y)}all(){return[...this.#e.values()].map(Y)}save(e){let n=Y(e),r=this.#e.get(e.taskId);this.#e.set(e.taskId,n);try{this.persist()}catch(i){throw r?this.#e.set(e.taskId,r):this.#e.delete(e.taskId),i}for(let i of this.#n.get(e.taskId)??[])i(Y(n));return Y(n)}checkpointRuntimeCursor(e,n){let r=this.#e.get(e);if(!r)return;if(n.sessionId!==r.sessionId)throw new Error(`A2A Runtime cursor belongs to another Session: ${e}`);let i={...r,runtimeSessionCursor:{...n}};this.#e.set(e,i);try{this.persistRuntimeCursor(e,n)}catch(s){throw this.#e.set(e,r),s}}pruneTerminal(e,n){let r=[...this.#e.values()].filter(s=>s.principalKey===e).sort((s,a)=>s.updatedAt.localeCompare(a.updatedAt)),i=[];for(;r.length>n;){let s=r.findIndex(c=>c.task.status.state==="TASK_STATE_COMPLETED"||c.task.status.state==="TASK_STATE_FAILED"||c.task.status.state==="TASK_STATE_CANCELED"||c.task.status.state==="TASK_STATE_REJECTED");if(s<0)break;let[a]=r.splice(s,1);if(!a)break;this.#e.delete(a.taskId),this.#n.delete(a.taskId),i.push(Y(a))}i.length>0&&this.persist();for(let s of i)E.rmSync(this.runtimeCursorFile(s.taskId),{force:!0});return i}migrateUnversionedPrincipalKeys(e){let n=0,r=0,i=0,s=[];for(let[a,c]of this.#e){if(c.principalKeyScheme!==void 0)continue;let d=e.legacyToCurrent.get(c.principalKey);d!==void 0?(n+=1,s.push([a,{...c,principalKey:d,principalKeyScheme:Z}])):e.currentKeys.has(c.principalKey)?(r+=1,s.push([a,{...c,principalKeyScheme:Z}])):i+=1}if(e.apply&&s.length>0){for(let[a,c]of s)this.#e.set(a,c);this.persist()}return{matchedLegacyTaskCount:n,matchedCurrentTaskCount:r,unmatchedUnversionedTaskCount:i}}subscribe(e,n){let r=this.#n.get(e)??new Set;return r.add(n),this.#n.set(e,r),()=>{r.delete(n),r.size===0&&this.#n.delete(e)}}close(){this.#n.clear(),E.closeSync(this.#i),E.rmSync(this.#r,{force:!0})}acquireLock(){let e=o(()=>{let n=E.openSync(this.#r,"wx",384);return E.writeFileSync(n,`${process.pid}
|
|
6
|
-
`,"utf8"),
|
|
7
|
-
`,{encoding:"utf8",mode:384}),
|
|
8
|
-
`,{encoding:"utf8",mode:384}),E.renameSync(e,this.#t)}};var M=new Set(["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_REJECTED"]),dr=new Set(["TASK_STATE_UNSPECIFIED","TASK_STATE_SUBMITTED","TASK_STATE_WORKING","TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_INPUT_REQUIRED","TASK_STATE_REJECTED","TASK_STATE_AUTH_REQUIRED"]),ur=new Set(["CreateTaskPushNotificationConfig","GetTaskPushNotificationConfig","ListTaskPushNotificationConfigs","DeleteTaskPushNotificationConfig"]),lr=4,Ar=8,pr=24*1024*1024,_t=new Set([1,7,9,11,13,15,17,19,20,21,22,23,25,37,42,43,53,69,77,79,87,95,101,102,103,104,109,110,111,113,115,117,119,123,135,137,139,143,161,179,389,427,465,512,513,514,515,526,530,531,532,540,548,554,556,563,587,601,636,989,990,993,995,1719,1720,1723,2049,3659,4045,4190,5060,5061,6e3,6566,6665,6666,6667,6668,6669,6679,6697,10080]),fr=16;function hr(t,e,n){return new Promise((r,i)=>{let s=o(c=>{t.off("listening",a),i(c)},"onError"),a=o(()=>{t.off("error",s),r()},"onListening");t.once("error",s),t.once("listening",a),t.listen(e,n)})}o(hr,"listenNodeServer");function Ut(t){return new Promise((e,n)=>{t.close(r=>r?n(r):e())})}o(Ut,"closeNodeServer");function C(t){return t().toISOString()}o(C,"nowIso");function z(t){return ar("sha256").update(t).digest("hex")}o(z,"sha256");function Ke(t){let e=t.securityRealm;if(typeof e!="string"||e.trim().length===0)throw new Error("A2A authentication.securityRealm must be a non-empty stable string.");return e}o(Ke,"securityRealm");function Nt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Nt,"isLoopbackHostname");function gr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Nt(e.hostname)))throw new Error("Published A2A base URL must use HTTPS, except on loopback.");if(e.username||e.password)throw new Error("Published A2A base URL must not contain credentials.");return e}o(gr,"validateBaseUrl");function mr(t){let n={SendMessage:"send-message",SendStreamingMessage:"send-streaming-message",GetTask:"get-task",ListTasks:"list-tasks",CancelTask:"cancel-task",SubscribeToTask:"subscribe-to-task",GetExtendedAgentCard:"get-extended-agent-card"}[t];if(!n)throw new A(-32601,"Method not found.");return n}o(mr,"operationForMethod");function yr(t){return{queued:"TASK_STATE_SUBMITTED",unknown:"TASK_STATE_UNSPECIFIED",waiting_agent:"TASK_STATE_WORKING",recovering:"TASK_STATE_WORKING",running:"TASK_STATE_WORKING",waiting_permission:"TASK_STATE_WORKING",waiting_user_input:"TASK_STATE_INPUT_REQUIRED",completed:"TASK_STATE_COMPLETED",failed:"TASK_STATE_FAILED",cancelled:"TASK_STATE_CANCELED",interrupted:"TASK_STATE_FAILED"}[t]}o(yr,"statusState");function Fe(t,e,n){return{messageId:he(),taskId:t,contextId:e,role:"ROLE_AGENT",parts:[{text:n,mediaType:"text/plain"}]}}o(Fe,"agentMessage");function wr(t){let e=gr(t);return e.pathname=`${e.pathname.replace(/\/$/,"")}/a2a`,e.search="",e.hash="",e.href}o(wr,"interfaceUrl");function je(t,e){if(t!==void 0){if(!Number.isSafeInteger(t)||t<0)throw new A(-32602,`${e} must be a non-negative integer.`);return t}}o(je,"parseHistoryLength");function Be(t){if(typeof t?.id!="string"||t.id.length===0)throw new A(-32602,"Task id is required.");return t.id}o(Be,"requiredTaskId");function kr(t){if(!(!g(t)||typeof t.label!="string"||typeof t.value!="string"))return{label:t.label,value:t.value,...typeof t.description=="string"?{description:t.description}:{}}}o(kr,"publicInputOption");function Mt(t){if(!g(t)||typeof t.question!="string")return;let e=Array.isArray(t.options)?t.options.flatMap(n=>{let r=kr(n);return r?[r]:[]}):void 0;return{question:t.question,...typeof t.header=="string"?{header:t.header}:{},...typeof t.kind=="string"?{kind:t.kind}:{},...e?{options:e}:{},...typeof t.multiSelect=="boolean"?{multiSelect:t.multiSelect}:{},...Number.isSafeInteger(t.minSelections)?{minSelections:t.minSelections}:{},...Number.isSafeInteger(t.maxSelections)?{maxSelections:t.maxSelections}:{},...typeof t.allowCustomInput=="boolean"?{allowCustomInput:t.allowCustomInput}:{},...typeof t.customInputLabel=="string"?{customInputLabel:t.customInputLabel}:{},...typeof t.customInputPrompt=="string"?{customInputPrompt:t.customInputPrompt}:{}}}o(Mt,"publicInputQuestion");function Sr(t){return g(t)?Array.isArray(t.questions)?{questions:t.questions.flatMap(n=>{let r=Mt(n);return r?[r]:[]})}:Mt(t)??{}:{}}o(Sr,"publicInputOptions");function Rr(t,e,n){if(!g(n.payload)||typeof n.payload.kind!="string")return;let r=Sr(n.payload.options),i="";try{i=JSON.stringify(r)}catch{i="{}"}let s=i.length>4096?`${i.slice(0,4093)}...`:i;return{...Fe(t,e,`Input required (${n.payload.kind}): ${s}`),metadata:{"kodax.ai/user-input":{kind:n.payload.kind,options:r}}}}o(Rr,"pendingInputMessage");function Tr(t,e){let n=t.parts.find(i=>i.data!==void 0)?.data;if(n!==void 0)return n;let r=t.parts.flatMap(i=>i.text===void 0?[]:[i.text]).join(`
|
|
9
|
-
`);if(e==="askUserMulti"||r.startsWith("[")||r.startsWith("{"))try{return JSON.parse(r)}catch{}return r}o(Tr,"continuationAnswer");function Lt(t,e){let n=b.relative(t,e);return n===""||!n.startsWith(`..${b.sep}`)&&n!==".."&&!b.isAbsolute(n)}o(Lt,"isInside");function Er(t){return{".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".json":"application/json",".pdf":"application/pdf",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".html":"text/html",".htm":"text/html"}[b.extname(t).toLowerCase()]??"application/octet-stream"}o(Er,"artifactMediaType");function br(t){return t.result?.writtenFiles?.map(e=>({target:e.path,admittedSkillOutput:e.sourceTool==="run_skill_script"}))??(t.result?.artifactLedger??[]).flatMap(e=>(e.kind==="file_created"||e.kind==="file_modified")&&typeof e.target=="string"?[{target:e.target,admittedSkillOutput:e.sourceTool==="run_skill_script"&&e.action==="promote_output"}]:[])}o(br,"outputFileCandidates");function Ir(t,e,n){let r=t.workspaceRoot??n.agent.projectPath;if(!r)return[];let i;try{i=W.realpathSync(r)}catch{return[]}let s=new Set,a=[];for(let c of br(e)){let d=b.isAbsolute(c.target)?c.target:b.resolve(r,c.target),u=b.relative(r,d),f=u.split(b.sep).includes(".kodax-a2a-staging"),{admittedSkillOutput:l}=c;if(!Lt(r,d)||!f&&!l)continue;let p,h,w;try{if(p=W.lstatSync(d),h=W.realpathSync(d),!p.isFile()||p.isSymbolicLink()||!Lt(i,h)||s.has(h)||p.size>n.limits.maxPartBytes)continue;w=W.readFileSync(h)}catch{continue}if(w.byteLength>n.limits.maxPartBytes)continue;let k=Er(d);(t.acceptedOutputModes??n.agent.outputModes).includes(k)&&(s.add(h),a.push({artifactId:`file-${z(`${t.taskId}\0${u}\0${w.byteLength}\0${p.mtimeMs}`).slice(0,24)}`,name:b.basename(d),description:l?"KodaX Skill task output":"KodaX staged task output",parts:[{raw:w.toString("base64"),filename:b.basename(d),mediaType:k}]}))}return a}o(Ir,"stagedArtifacts");function xr(t,e,n){let r=t;for(let i of[e.workspaceRoot,n.agent.projectPath,b.resolve(n.dataDir)])i&&(r=r.split(i).join("[redacted-path]"),r=r.split(i.replaceAll("\\","/")).join("[redacted-path]"));return r}o(xr,"safeTaskText");function He(t,e=t.agent.publicBaseUrl){let n=wr(e),r={name:t.agent.name,description:t.agent.description,supportedInterfaces:[{url:n,protocolBinding:"JSONRPC",protocolVersion:"1.0"}],version:t.agent.version,capabilities:{streaming:!0,pushNotifications:!1,extendedAgentCard:t.extendedAgentCard!==void 0},securitySchemes:t.authentication.securitySchemes,securityRequirements:t.authentication.securityRequirements,defaultInputModes:t.agent.inputModes,defaultOutputModes:t.agent.outputModes,skills:t.agent.skills};J(r.securitySchemes,r.securityRequirements);for(let i of r.skills)J(r.securitySchemes,i.securityRequirements);return r}o(He,"buildCard");function Cr(t,e){if(t===null)return!1;let n=e.replace(/^W\//iu,"");return t.split(",").some(r=>{let i=r.trim();return i==="*"||i.replace(/^W\//iu,"")===n})}o(Cr,"matchesIfNoneMatch");function ge(t,e=200,n){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8",...n}})}o(ge,"jsonResponse");async function vr(t,e){let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new A(-32600,"A2A request exceeds the configured limit.",413);if(!t.body)return new Uint8Array;let r=[],i=0,s=t.body.getReader();for(;;){let d=await s.read();if(d.done)break;if(i+=d.value.byteLength,i>e)throw await s.cancel("A2A request size limit exceeded."),new A(-32600,"A2A request exceeds the configured limit.",413);r.push(d.value)}let a=new Uint8Array(i),c=0;for(let d of r)a.set(d,c),c+=d.byteLength;return a}o(vr,"readBoundedBody");function fe(t,e){return ge({jsonrpc:"2.0",id:t,result:e})}o(fe,"rpcResult");function Pr(t,e){let r={[-32001]:"TASK_NOT_FOUND",[-32002]:"TASK_NOT_CANCELABLE",[-32003]:"PUSH_NOTIFICATION_NOT_SUPPORTED",[-32004]:"UNSUPPORTED_OPERATION",[-32005]:"CONTENT_TYPE_NOT_SUPPORTED",[-32006]:"INVALID_AGENT_RESPONSE",[-32007]:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",[-32008]:"EXTENSION_SUPPORT_REQUIRED",[-32009]:"VERSION_NOT_SUPPORTED"}[e.code],i=e.data??(r?[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:r,domain:"a2a-protocol.org"}]:void 0);return ge({jsonrpc:"2.0",id:t,error:{code:e.code,message:e.message,...i!==void 0?{data:i}:{}}},e.httpStatus,e.headers)}o(Pr,"rpcError");function qt(t){return z(JSON.stringify(t))}o(qt,"messageDigest");function Or(t){return t.text!==void 0?Buffer.byteLength(t.text):t.raw!==void 0?Buffer.byteLength(t.raw,"base64"):t.url!==void 0?Buffer.byteLength(t.url):Buffer.byteLength(JSON.stringify(t.data))}o(Or,"partBytes");function $t(t){return t.mediaType??(t.text!==void 0?"text/plain":t.data!==void 0?"application/json":"application/octet-stream")}o($t,"partMediaType");function Dt(t){if(!W.existsSync(t))return 0;let e=0;for(let n of W.readdirSync(t,{withFileTypes:!0})){let r=b.join(t,n.name);n.isSymbolicLink()||(n.isDirectory()?e+=Dt(r):n.isFile()&&(e+=W.statSync(r).size))}return e}o(Dt,"directoryBytes");function _r(t,e,n){if(t.role!=="ROLE_USER")throw new A(-32602,"Inbound message role must be ROLE_USER.");for(let r of t.parts){if(Or(r)>e)throw new A(-32602,"Message Part exceeds the configured limit.");if(r.url!==void 0)throw new A(-32602,"Remote file URLs are not accepted by this server.");if(r.raw!==void 0&&!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r.raw))throw new A(-32602,"Message Part raw content is not valid base64.");let i=$t(r);if(!n.includes(i))throw new A(-32005,`Media type ${i} is not supported.`)}}o(_r,"validateInput");function ze(t,e,n){if(n===0){let{history:i,...s}=t;return s}let r=n===void 0?e:e.slice(-n);return{...t,history:r}}o(ze,"withHistory");function Ur(t){if(!t)return;let e;try{e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new A(-32602,"Invalid page token.")}if(!g(e)||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||typeof e.taskId!="string"||e.taskId.length===0)throw new A(-32602,"Invalid page token.");return{updatedAt:e.updatedAt,taskId:e.taskId}}o(Ur,"parseTaskListCursor");function Mr(t){return Buffer.from(JSON.stringify({updatedAt:t.updatedAt,taskId:t.taskId})).toString("base64url")}o(Mr,"encodeTaskListCursor");function Lr(t,e){let n=t.updatedAt.localeCompare(e.updatedAt);return n<0||n===0&&t.taskId.localeCompare(e.taskId)<0}o(Lr,"followsTaskListCursor");var Ee=class{constructor(e){this.options=e;Ke(e.authentication),this.#n=e.now??(()=>new Date),this.#e=new oe(e.dataDir),this.#a=He(e),this.#d=this.recover()}options;static{o(this,"KodaXA2AServerRuntime")}#e;#n;#t=new Map;#s=new Set;#r=new Set;#i=new Map;#c=new Map;#f=new Set;#d;#u=0;#l;#h=0;#A=!1;#o=!1;#p;#a;#g;get agentCard(){return structuredClone(this.#a)}async whenReady(){await this.#d}updateHot(e){if(this.#A||this.#o)throw new Error("A2A server is closed.");Ke(e.authentication);let n={...this.options,...e},r=He(n,e.agent.publicBaseUrl);this.options=n,this.#a=r}handle(e){if(this.#A||this.#o)return Promise.resolve(ge({error:"A2A server is closed."},503));let n=o(()=>{},"release"),r=new Promise(i=>{n=i});return this.#f.add(r),this.handleAdmitted(e).finally(()=>{this.#f.delete(r),n()})}async handleAdmitted(e){await this.#d;let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/.well-known/agent-card.json"){let r=JSON.stringify(this.#a),i=`"${z(r)}"`,s={etag:i,"cache-control":"no-cache"};return Cr(e.headers.get("if-none-match"),i)?new Response(null,{status:304,headers:s}):ge(this.#a,200,s)}return e.method!=="POST"||n.pathname!=="/"&&n.pathname!=="/a2a"?ge({error:"Not found."},404):this.handleRpc(e)}async listen(e){if(this.#A||this.#o)throw new Error("A2A server is closed.");if(this.#l)throw new Error("A2A server is already listening.");if(!Nt(e.hostname))throw new Error("The built-in A2A HTTP listener is loopback-only; use handle() behind TLS for public service.");if(e.port!==0&&_t.has(e.port))throw new Error(`Fetch-compatible clients block port ${e.port}; choose another A2A listener port.`);let n=cr((i,s)=>{this.handleNodeRequest(i).then(a=>{if(s.statusCode=a.status,a.headers.forEach((u,f)=>s.setHeader(f,u)),!a.body){s.end();return}let c=Ot.fromWeb(a.body),d=o(()=>{c.destroy()},"closeBody");s.once("close",d),c.once("close",()=>s.off("close",d)),c.once("error",()=>{s.destroyed||s.destroy()}),c.pipe(s)}).catch(a=>{let c=z(me(a)).slice(0,16);this.emit({type:"server.request_failed",time:C(this.#n),outcome:"failed",diagnosticId:c}),s.statusCode=500,s.setHeader("content-type","application/json; charset=utf-8"),s.end(JSON.stringify({error:"Internal server error.",diagnosticId:c}))})}),r=e.port===0?fr:1;for(let i=0;i<r;i+=1){await hr(n,e.port,e.hostname);let s=n.address();if(!s||typeof s=="string")throw await Ut(n),new Error("A2A server did not expose a TCP address.");if(_t.has(s.port)){await Ut(n);continue}let a=`http://${e.hostname}:${s.port}`;return this.#l=n,this.#g=e.publicBaseUrl??a,this.#a=He(this.options,this.#g),a}throw new Error("A2A server could not allocate a Fetch-compatible listener port.")}close(){if(this.#p)return this.#p;this.#A=!0;let e=this.#l;this.#l=void 0;let n=e?new Promise((r,i)=>e.close(s=>s?i(s):r())):Promise.resolve();return this.#p=this.closeAdmittedWork(n),this.#p}async closeAdmittedWork(e){let n=[];try{await this.#d}catch(r){n.push(r)}await Promise.all([...this.#f]),this.#o=!0;for(let r of[...this.#r])try{r()}catch(i){n.push(i)}this.#r.clear();for(let r of this.#t.values())try{r.close()}catch(i){n.push(i)}this.#t.clear(),this.#s.clear();try{await e}catch(r){n.push(r)}try{this.#e.close()}catch(r){n.push(r)}try{await this.options.preparedExecution?.close()}catch(r){n.push(r)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"A2A server close failed.")}async handleNodeRequest(e){let r=`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,i=new Headers;for(let[a,c]of Object.entries(e.headers))if(typeof c=="string")i.set(a,c);else for(let d of c??[])i.append(a,d);let s={method:e.method,headers:i,...e.method==="GET"||e.method==="HEAD"?{}:{body:Ot.toWeb(e)},duplex:"half"};return this.handle(new Request(r,s))}async handleRpc(e){let n=this.options,r=null;try{if((e.headers.get("a2a-version")??new URL(e.url).searchParams.get("A2A-Version"))!=="1.0")throw new A(-32009,"A2A version is not supported.");if(!de(e.headers.get("content-type")))throw new A(-32600,"A2A JSON-RPC requests require application/json.",415);let s=await n.authentication.authenticate(e);if(!s)throw new A(-32600,"Authentication required.",401,void 0,{"www-authenticate":"Bearer"});let a=await vr(e,n.limits.maxRequestBytes),c;try{c=JSON.parse(new TextDecoder().decode(a))}catch{throw new A(-32700,"Invalid JSON payload.")}let d=pt(c);if(r=d.id,ur.has(d.method))throw new A(-32003,"Push notifications are not supported.");let u=mr(d.method),f=d.method==="SendMessage"||d.method==="SendStreamingMessage"?D(d.params?.message):void 0,l=typeof d.params?.id=="string"?d.params.id:f?.taskId,p=f?.contextId,h=f?[...new Set(f.parts.map($t))]:void 0;if(!await n.authorize({principal:s,operation:u,...l?{taskId:l}:{},...p?{contextId:p}:{},...h?{inputModes:h}:{}}))throw new A(-32001,"Task not found.");return await this.dispatch(d,s,n)}catch(i){let s=z(me(i)).slice(0,16),a=i instanceof A?i:new A(-32603,"Internal error.",500,[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:"INTERNAL",domain:"kodax.ai",metadata:{diagnosticId:s}}]);return this.emit({type:"rpc.failed",time:C(this.#n),outcome:"failed",diagnosticId:s}),Pr(r,a)}}async dispatch(e,n,r){let i=Te({securityRealm:Ke(r.authentication),subject:n.subject,...n.tenant!==void 0?{tenant:n.tenant}:{}});switch(e.method){case"SendMessage":return fe(e.id,{task:await this.sendMessage(e.params,i,!1,r)});case"SendStreamingMessage":{let s=await this.sendMessage(e.params,i,!0,r);return this.streamTask(e.id,s.id,i)}case"GetTask":return fe(e.id,await this.getTask(e.params,i));case"ListTasks":return fe(e.id,this.listTasks(e.params,i));case"CancelTask":return fe(e.id,await this.cancelTask(e.params,i,r));case"SubscribeToTask":return this.subscribeTask(e.id,e.params,i);case"GetExtendedAgentCard":{if(!r.extendedAgentCard)throw new A(-32004,"Extended Agent Card is not supported.");return fe(e.id,r.extendedAgentCard)}default:throw new A(-32601,"Method not found.")}}async sendMessage(e,n,r,i){let s=this.#c.get(n)??Promise.resolve(),a=o(()=>{},"release"),c=new Promise(d=>{a=d});this.#c.set(n,c),await s;try{return await this.sendMessageUnserialized(e,n,r,i)}finally{a(),this.#c.get(n)===c&&this.#c.delete(n)}}async sendMessageUnserialized(e,n,r,i){let s=D(e?.message);if(_r(s,i.limits.maxPartBytes,i.agent.inputModes),e?.configuration!==void 0&&!g(e.configuration))throw new A(-32602,"SendMessage configuration must be an object.");let a=g(e?.configuration)?e.configuration:{},c=je(a.historyLength,"SendMessage historyLength");if(a.returnImmediately!==void 0&&typeof a.returnImmediately!="boolean")throw new A(-32602,"SendMessage returnImmediately must be a boolean.");if(a.taskPushNotificationConfig!==void 0)throw new A(-32003,"Push notifications are not supported.");if(a.acceptedOutputModes!==void 0){if(!Array.isArray(a.acceptedOutputModes)||!a.acceptedOutputModes.every(p=>typeof p=="string"))throw new A(-32602,"SendMessage acceptedOutputModes must be a string array.");if(!a.acceptedOutputModes.some(p=>i.agent.outputModes.includes(p)))throw new A(-32005,"No requested output media type is supported.")}let d=await this.admitMessage(s,n,i,a.acceptedOutputModes);if(d.runtimeEventsAttached)try{await d.runtimeEventsAttached}catch(p){throw this.failTask(d.record.taskId,"Task could not be started.",i),p}let u=this.#e.get(d.record.taskId)??d.record,l=d.duplicate||r||a.returnImmediately===!0?u:await this.waitForTask(u.taskId,i.limits.maxTaskWaitMs??3e4);return ze(l.task,l.history,c)}async admitMessage(e,n,r,i){let s=qt(e),a=this.#e.findByMessage(n,e.messageId);if(a){if(a.messageDigests[e.messageId]!==s)throw new A(-32602,"Message ID was reused with different content.");return this.emit({type:"task.deduplicated",time:C(this.#n),taskId:a.taskId,contextId:a.contextId}),{record:a,duplicate:!0}}let c=e.taskId?this.requireOwnedTask(e.taskId,n):void 0;if(c&&e.contextId!==void 0&&e.contextId!==c.contextId)throw new A(-32602,"Message contextId does not match the task.");if(c&&c.task.status.state!=="TASK_STATE_INPUT_REQUIRED"&&c.task.status.state!=="TASK_STATE_AUTH_REQUIRED")throw new A(-32004,"Task is not waiting for input.");let d=r.limits.maxRetainedTasksPerPrincipal??r.limits.maxTasksPerPrincipal??100;c||this.#e.pruneTerminal(n,Math.max(0,d-1));let u=this.#e.list(n);if(!c&&u.length>=d)throw new A(-32004,"Principal task limit reached.");let f=u.filter(p=>!M.has(p.task.status.state)).length;if(!c&&f>=(r.limits.maxActiveTasksPerPrincipal??4))throw new A(-32004,"Principal active task limit reached.");let l=!1;if(!c){if(this.#e.all().filter(h=>!M.has(h.task.status.state)).length+this.#u>=r.limits.maxConcurrentTasks)throw new A(-32004,"Server task concurrency limit reached.");this.#u+=1,l=!0}try{let p,h;if(c?.task.status.state==="TASK_STATE_INPUT_REQUIRED")p=await this.resumeUserInput(c,e,s,r);else{let w=c??await this.createRecord(e,n,r,i);c||(this.#u-=1,l=!1);let k=c?this.appendMessage(w,e,s):w;try{let y=await this.startRun(k,e,r);p=y.record,h=y.runtimeEventsAttached}catch(y){throw this.failTask(k.taskId,"Task could not be started.",r),y}}return{record:p,duplicate:!1,...h?{runtimeEventsAttached:h}:{}}}finally{l&&(this.#u-=1)}}async resumeUserInput(e,n,r,i){let s=e.pendingUserInput;if(!s)throw new A(-32004,"Task has no pending Runtime input request.");if(!(await i.runtime.userInputs.respond(s.requestId,Tr(n,s.kind),{expectedRevision:s.revision,runId:s.runId})).accepted)throw new A(-32004,"Pending Runtime input request is no longer active.");let c=this.#e.get(e.taskId)??e,d=this.appendMessage(c,n,r),{pendingUserInput:u,...f}=d;return M.has(d.task.status.state)?this.#e.save(f):this.#e.save({...f,task:{...d.task,status:{state:"TASK_STATE_WORKING",timestamp:C(this.#n)}},updatedAt:C(this.#n),eventSeq:d.eventSeq+1})}async createRecord(e,n,r,i){let s=e.contextId??he(),a=this.#e.list(n).find(p=>p.contextId===s),c=z(`${n}\0${s}`),d=a?.workspaceRoot??await r.preparedExecution?.prepareWorkspace(c),u=await r.runtime.sessions.create({title:`A2A: ${r.agent.name}`,surface:"a2a",...r.execution?.profileId||r.agent.profileId?{profileId:r.execution?.profileId??r.agent.profileId}:{},...d?{projectPath:d,gitRoot:d}:r.agent.projectPath?{projectPath:r.agent.projectPath}:{}}),f=he(),l=C(this.#n);return this.#e.save({taskId:f,contextId:s,principalKey:n,principalKeyScheme:Z,runtimeIdentity:r.runtime.identity.runtimeId,sessionId:u.id,...d?{workspaceRoot:d}:{},...r.preparedExecution?{executionPolicyRevision:r.preparedExecution.binding.executionPolicyRevision}:{},messageDigests:{[e.messageId]:qt(e)},runIds:[],task:{id:f,contextId:s,status:{state:"TASK_STATE_SUBMITTED",timestamp:l},history:[{...e,taskId:f,contextId:s}]},history:[{...e,taskId:f,contextId:s}],createdAt:l,updatedAt:l,eventSeq:1,runtimeEventCount:0,runtimeEventBytes:0,...i?{acceptedOutputModes:i}:{}})}appendMessage(e,n,r){let i={...n,taskId:e.taskId,contextId:e.contextId};return this.#e.save({...e,messageDigests:{...e.messageDigests,[n.messageId]:r},history:[...e.history,i],task:{...e.task,history:[...e.history,i]},updatedAt:C(this.#n),eventSeq:e.eventSeq+1})}async startRun(e,n,r){let i=await this.inputsForMessage(e.taskId,n,r),s=r.preparedExecution;if(s&&e.executionPolicyRevision!==s.binding.executionPolicyRevision)throw new A(-32004,"A2A task execution binding revision changed.");let a=s?await s.start({sessionId:e.sessionId,inputs:i,principalKey:e.principalKey}):await r.runtime.runs.start({sessionId:e.sessionId,input:i,mode:"managed_task",permissionBroker:"runtime",...r.agent.runOptions?{options:r.agent.runOptions}:{},agentContext:{actorId:`a2a:${e.principalKey.slice(0,16)}`}}),c=this.#e.save({...e,runIds:[...e.runIds,a.runId],task:{...e.task,status:{state:"TASK_STATE_WORKING",timestamp:C(this.#n)}},updatedAt:C(this.#n),eventSeq:e.eventSeq+1});a.result.then(u=>this.finishRun(c.taskId,u,r)).catch(()=>{this.failTask(c.taskId,"Task execution failed.",r)});let d=this.attachRuntimeEvents(c,a.runId,r);return this.emit({type:"task.started",time:C(this.#n),taskId:c.taskId,contextId:c.contextId,runId:a.runId,outcome:"accepted"}),{record:c,runtimeEventsAttached:d}}async inputsForMessage(e,n,r){let i=[];for(let s of n.parts){if(s.text!==void 0){i.push({type:"text",text:s.text});continue}i.push(await this.materializePart(e,s,r))}return i}async materializePart(e,n,r){let i=n.mediaType??(n.data!==void 0?"application/json":"application/octet-stream"),s=n.data!==void 0?".json":".bin",a=this.#e.get(e),c=a?.workspaceRoot?b.join(a.workspaceRoot,"inbox",z(e)):b.join(b.resolve(r.dataDir),"attachments",z(e));W.mkdirSync(c,{recursive:!0,mode:448});let d=n.data!==void 0?Buffer.from(JSON.stringify(n.data),"utf8"):Buffer.from(n.raw??"","base64"),u=r.limits.maxWorkspaceBytesPerContext??1073741824;if(a?.workspaceRoot&&Dt(a.workspaceRoot)+d.byteLength>u)throw new A(-32004,"A2A context workspace size limit reached.");let f=n.filename?b.basename(n.filename).replace(/[^A-Za-z0-9._-]/g,"_"):`${he()}${s}`,l=b.join(c,`${he()}-${f}`);W.writeFileSync(l,d,{mode:384});let p=i.startsWith("image/")?"image":i.startsWith("video/")?"video":"file";return{type:"artifact_ref",artifactId:(await r.runtime.artifacts.create({kind:p,path:l,mediaType:i,mimeType:i,...n.filename?{name:b.basename(n.filename)}:{},source:"user-inline",description:"Inbound A2A message part"})).id,description:"Inbound A2A attachment"}}async attachRuntimeEvents(e,n,r){this.#t.get(e.taskId)?.close(),this.#t.delete(e.taskId);let i=[],s=!0,a=r.runtime.events.subscribe({sessionId:e.sessionId,runId:n},c=>{s?i.push(c):this.onRuntimeEvent(e.taskId,c,r)});this.#t.set(e.taskId,a);try{let d=[...await r.runtime.events.replay({sessionId:e.sessionId,runId:n,...e.runtimeSessionCursor!==void 0?{after:e.runtimeSessionCursor}:{}}),...i].sort((u,f)=>u.seq-f.seq||u.time.localeCompare(f.time)||u.id.localeCompare(f.id));for(let u of d)this.onRuntimeEvent(e.taskId,u,r);s=!1}catch(c){throw s=!1,this.#t.get(e.taskId)===a&&(a.close(),this.#t.delete(e.taskId)),c}}onRuntimeEvent(e,n,r){if(!this.#s.has(e))try{this.consumeRuntimeEvent(e,n,r)}catch(i){throw this.#s.add(e),this.#t.get(e)?.close(),this.#t.delete(e),i}}consumeRuntimeEvent(e,n,r){if(this.#o)return;let i=this.#e.get(e);if(!i||M.has(i.task.status.state))return;let s=n.cursor;if(s.sessionId!==i.sessionId||i.runtimeSessionCursor!==void 0&&s.journalEpoch!==i.runtimeSessionCursor.journalEpoch){this.failTask(e,"Runtime Session event journal changed; task resync is required.",r);return}if(i.runtimeSessionCursor!==void 0&&s.seq<=i.runtimeSessionCursor.seq)return;if(n.type!=="user_input.requested"&&n.type!=="user_input.resolved"&&n.type!=="run.started"){this.#e.checkpointRuntimeCursor(e,s);return}let a=Buffer.byteLength(JSON.stringify(n)),c=i.runtimeEventCount+1,d=i.runtimeEventBytes+a;if(c>(r.limits.maxEventsPerTask??1e3)||d>(r.limits.maxEventBytesPerTask??16777216)){let p=i.runIds.at(-1);p&&r.runtime.runs.abort(p),this.failTask(e,"A2A task event quota exceeded.",r);return}let u=n.type==="user_input.requested"?"TASK_STATE_INPUT_REQUIRED":"TASK_STATE_WORKING",f=n.type==="user_input.requested"?Rr(e,i.contextId,n):void 0,l=n.type==="user_input.requested"&&g(n.payload)&&typeof n.payload.id=="string"&&Number.isSafeInteger(n.payload.revision)&&typeof n.payload.runId=="string"&&typeof n.payload.kind=="string"?{requestId:n.payload.id,revision:n.payload.revision,runId:n.payload.runId,kind:n.payload.kind}:void 0;this.#e.save({...i,task:{...i.task,status:{state:u,...f?{message:f}:{},timestamp:n.time}},...l?{pendingUserInput:l}:{},...n.type==="user_input.resolved"?{pendingUserInput:void 0}:{},updatedAt:n.time,eventSeq:i.eventSeq+1,runtimeSessionCursor:s,runtimeEventCount:c,runtimeEventBytes:d})}finishRun(e,n,r=this.options){if(this.#o||this.#s.has(e))return;let i=this.#e.get(e);if(!i||M.has(i.task.status.state))return;let s=yr(n.phase),a=n.error?z(me(n.error)).slice(0,16):void 0,c=n.error?`Task failed. Diagnostic ID: ${a}`:xr(n.result?.lastText??"",i,r),d=c?Fe(e,i.contextId,c):void 0,u=d?[...i.history,d]:i.history,l=[...c&&(i.acceptedOutputModes??r.agent.outputModes).includes("text/plain")?[{artifactId:`final-${e}`,name:"final-output",parts:[{text:c,mediaType:"text/plain"}]}]:[],...Ir(i,n,r)],{pendingUserInput:p,...h}=i;this.#e.save({...h,history:u,task:{...i.task,status:{state:s,...d?{message:d}:{},timestamp:C(this.#n)},...l.length>0?{artifacts:l}:{},history:u},updatedAt:C(this.#n),eventSeq:i.eventSeq+1}),this.#t.get(e)?.close(),this.#t.delete(e),this.pruneRetained(i.principalKey,r),this.emit({type:"task.finished",time:C(this.#n),taskId:e,contextId:i.contextId,outcome:s==="TASK_STATE_COMPLETED"?"completed":"failed"})}failTask(e,n,r=this.options){if(this.#o)return;let i=this.#e.get(e);if(!i||M.has(i.task.status.state))return;let s=Fe(e,i.contextId,n),{pendingUserInput:a,...c}=i;this.#e.save({...c,task:{...i.task,status:{state:"TASK_STATE_FAILED",message:s,timestamp:C(this.#n)}},updatedAt:C(this.#n),eventSeq:i.eventSeq+1}),this.#t.get(e)?.close(),this.#t.delete(e),this.pruneRetained(i.principalKey,r)}pruneRetained(e,n){let r=n.limits.maxRetainedTasksPerPrincipal??n.limits.maxTasksPerPrincipal??100;this.#e.pruneTerminal(e,r)}async getTask(e,n){let r=Be(e),i=this.requireOwnedTask(r,n),s=je(e?.historyLength,"GetTask historyLength");return ze(i.task,i.history,s)}listTasks(e,n){let r=je(e?.historyLength,"ListTasks historyLength");if(e?.includeArtifacts!==void 0&&typeof e.includeArtifacts!="boolean")throw new A(-32602,"ListTasks includeArtifacts must be a boolean.");if(e?.contextId!==void 0&&typeof e.contextId!="string")throw new A(-32602,"ListTasks contextId must be a string.");if(e?.pageToken!==void 0&&typeof e.pageToken!="string")throw new A(-32602,"ListTasks pageToken must be a string.");if(e?.status!==void 0&&(typeof e.status!="string"||!dr.has(e.status)))throw new A(-32602,"ListTasks status is invalid.");let i=typeof e?.statusTimestampAfter=="string"?Date.parse(e.statusTimestampAfter):void 0;if(e?.statusTimestampAfter!==void 0&&!Number.isFinite(i))throw new A(-32602,"ListTasks statusTimestampAfter is invalid.");let s=this.#e.list(n).filter(l=>!(typeof e?.contextId=="string"&&l.contextId!==e.contextId||typeof e?.status=="string"&&l.task.status.state!==e.status||i!==void 0&&Date.parse(l.task.status.timestamp??l.updatedAt)<i));if(e?.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||e.pageSize<1||e.pageSize>100))throw new A(-32602,"ListTasks pageSize must be an integer from 1 to 100.");let a=typeof e?.pageSize=="number"?e.pageSize:50,c=Ur(typeof e?.pageToken=="string"?e.pageToken:void 0),d=c?s.filter(l=>Lr(l,c)):s,u=d.slice(0,a),f=u.at(-1);return{tasks:u.map(l=>{let p=ze(l.task,l.history,r);return e?.includeArtifacts===!0?p:{...p,artifacts:void 0}}),nextPageToken:f&&u.length<d.length?Mr(f):"",pageSize:a,totalSize:s.length}}async cancelTask(e,n,r){let i=Be(e),s=this.requireOwnedTask(i,n);if(M.has(s.task.status.state))throw new A(-32002,"Task is not cancelable.");let a=s.runIds.at(-1);a&&await r.runtime.runs.abort(a);let c=this.#e.save({...s,task:{...s.task,status:{state:"TASK_STATE_CANCELED",timestamp:C(this.#n)}},updatedAt:C(this.#n),eventSeq:s.eventSeq+1});return this.#t.get(i)?.close(),this.#t.delete(i),this.pruneRetained(s.principalKey,r),c.task}subscribeTask(e,n,r){let i=Be(n),s=this.requireOwnedTask(i,r);if(M.has(s.task.status.state))throw new A(-32004,"Cannot subscribe to a terminal task.");return this.streamTask(e,i,s.principalKey)}streamTask(e,n,r){let i=this.requireOwnedTask(n,r),s=new Map((i.task.artifacts??[]).map(l=>[l.artifactId,z(JSON.stringify(l))])),a=this.reserveStream(n),c=new TextEncoder,d,u=a,f=!1;try{let l=new ReadableStream({start:o(p=>{let h=o(k=>{f||(f=!0,u(),k?p.error(k):p.close())},"close");u=o(()=>{d?.(),d=void 0,this.#r.delete(h),a()},"cleanup");let w=o(k=>{let y=c.encode(this.sse(e,k));return p.desiredSize===null||p.desiredSize<y.byteLength?(h(new Error("A2A SSE subscriber exceeded its buffer budget.")),!1):(p.enqueue(y),!0)},"enqueue");if(this.#r.add(h),!!w({task:i.task})){if(M.has(i.task.status.state)){h();return}d=this.#e.subscribe(n,k=>{!this.enqueueArtifactUpdates(w,k.task,s)||!w({statusUpdate:{taskId:n,contextId:k.contextId,status:k.task.status}})||(M.has(k.task.status.state)||k.task.status.state==="TASK_STATE_INPUT_REQUIRED"||k.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&h()})}},"start"),cancel:o(()=>{f||(f=!0,u())},"cancel")},{highWaterMark:pr,size:o(p=>p.byteLength,"size")});return new Response(l,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}catch(l){throw u(),l}}enqueueArtifactUpdates(e,n,r){for(let i of n.artifacts??[]){let s=z(JSON.stringify(i));if(r.get(i.artifactId)!==s){if(!e({artifactUpdate:{taskId:n.id,contextId:n.contextId,artifact:i,append:!1,lastChunk:!0}}))return!1;r.set(i.artifactId,s)}}return!0}reserveStream(e){let n=this.#i.get(e)??0;if(n>=lr)throw new A(-32e3,"Task stream capacity reached.",429);if(this.#h>=Ar)throw new A(-32e3,"Server stream capacity reached.",429);this.#h+=1,this.#i.set(e,n+1);let r=!1;return()=>{if(r)return;r=!0,this.#h-=1;let i=(this.#i.get(e)??1)-1;i===0?this.#i.delete(e):this.#i.set(e,i)}}sse(e,n){return`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:n})}
|
|
2
|
+
import"./chunks/chunk-RXDS6CNA.js";import"./chunks/chunk-5P7RTSZT.js";import"./chunks/chunk-VEZ4WHPN.js";import"./chunks/chunk-ZQYWDI4O.js";import{j as nt,p as rt}from"./chunks/chunk-QOFFAY5C.js";import"./chunks/chunk-QGWHJIO4.js";import"./chunks/chunk-QZ4B4AWG.js";import"./chunks/chunk-K3DQGSQU.js";import"./chunks/chunk-OT5WHAX4.js";import"./chunks/chunk-ZZQ4GDVU.js";import"./chunks/chunk-2GV6MQ4T.js";import"./chunks/chunk-4VJMQDTH.js";import"./chunks/chunk-F7DHZH6T.js";import"./chunks/chunk-5DSUVP46.js";import{v as G}from"./chunks/chunk-VDGPJQL7.js";import"./chunks/chunk-ZPPAT25E.js";import"./chunks/chunk-7V2QBZ73.js";import{a as o}from"./chunks/chunk-ONUPGMER.js";var te="1.0",Pe="kodax-a2a-v1-jsonrpc";var A=class extends Error{constructor(n,r,i=200,s,a){super(r);this.code=n;this.httpStatus=i;this.data=s;this.headers=a;this.name="A2AError"}code;httpStatus;data;headers;static{o(this,"A2AError")}};function ge(t){return t instanceof Error?t.message:String(t)}o(ge,"errorMessage");var dn=["apiKeySecurityScheme","httpAuthSecurityScheme","oauth2SecurityScheme","openIdConnectSecurityScheme","mtlsSecurityScheme"],un=["authorizationCode","clientCredentials","implicit","password","deviceCode"],ln=/^[\x21\x23-\x5B\x5D-\x7E]+$/u;function re(t,e){if(!ln.test(t))throw new Error(`${e} must be an RFC 6749 scope-token.`)}o(re,"assertOAuthScopeToken");function it(t,e){let n=t.split(" ");for(let r of n)re(r,e);return[...new Set(n)]}o(it,"parseOAuthScopeValue");function ie(t,e){if(!Array.isArray(t))throw new Error(`${e} must be an array of strings.`);let n=t.map((r,i)=>{if(typeof r!="string")throw new Error(`${e}[${i}] must be a string.`);return re(r,`${e}[${i}]`),r});if(new Set(n).size!==n.length)throw new Error(`${e} must not contain duplicates.`);return n}o(ie,"parseOAuthScopeList");function B(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}o(B,"isRecord");function P(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t}o(P,"requireNonEmptyString");function An(t,e){if(t!==void 0)return P(t,e)}o(An,"optionalString");function st(t,e){return P(t,e).trim()}o(st,"trimmedUri");function pn(t){return/^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/u.exec(t)?.[1]?.includes("@")===!0}o(pn,"hasAuthorityUserinfo");function me(t){let e=t.toLowerCase().replace(/^\[|\]$/gu,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(me,"isExactOAuthLoopbackHostname");function ot(t,e){let n=st(t,e);if(!/^https?:\/\/([^/?#]*)/iu.exec(n)?.[1])throw new Error(`${e} must be an absolute HTTP(S) URL.`);let i;try{i=new URL(n)}catch{throw new Error(`${e} must be an absolute HTTP(S) URL.`)}if(pn(n)||i.username||i.password||n.includes("#"))throw new Error(`${e} must not contain userinfo or a fragment.`);if(i.protocol==="http:"&&!me(i.hostname))throw new Error(`${e} must use HTTPS or exact loopback HTTP.`);return{raw:n,url:i}}o(ot,"secureOAuthHttpUrl");function J(t,e){let n=ot(t,e);if(n.raw.includes("?"))throw new Error(`${e} must not contain a query or fragment.`);return n.raw}o(J,"parseOAuthIssuerIdentifier");function $(t,e){return ot(t,e).url}o($,"parseOAuthEndpointUrl");function ne(t,e){let n=st(t,e);if(!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(n))throw new Error(`${e} must be an absolute URI.`);try{new URL(n)}catch{throw new Error(`${e} must be an absolute URI.`)}if(n.includes("#"))throw new Error(`${e} must not contain a fragment.`);return n}o(ne,"parseOAuthResourceIdentifier");function at(t,e){return $(t,e).href}o(at,"absoluteHttpUrl");function fn(t,e){if(!B(t))throw new Error(`${e} must be a scope-description object.`);return Object.entries(t).map(([n,r])=>{if(n.trim().length===0||typeof r!="string")throw new Error(`${e} must map non-empty scope names to descriptions.`);return re(n,`${e}.${n}`),n})}o(fn,"parseScopes");function hn(t,e){if(!B(e))throw new Error(`securitySchemes.${t}.httpAuthSecurityScheme must be an object.`);let n=P(e.scheme,`securitySchemes.${t}.httpAuthSecurityScheme.scheme`),r=An(e.bearerFormat,`securitySchemes.${t}.httpAuthSecurityScheme.bearerFormat`);return n.toLowerCase()!=="bearer"?{name:t,kind:"unsupported",protocol:`http:${n.toLowerCase()}`}:{name:t,kind:"http-bearer",...r?{bearerFormat:r}:{}}}o(hn,"parseHttpScheme");function gn(t,e){let n=e.flows;if(!B(n))throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows must be an object.`);let r=un.filter(c=>n[c]!==void 0);if(r.length!==1)throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows must contain exactly one OAuth flow.`);let i=r[0],s=n[i];if(!B(s))throw new Error(`securitySchemes.${t}.oauth2SecurityScheme.flows.${i} must be an object.`);let a=fn(s.scopes,`securitySchemes.${t}.oauth2SecurityScheme.flows.${i}.scopes`);if(i==="clientCredentials"){let c=at(s.tokenUrl,`securitySchemes.${t}.oauth2SecurityScheme.flows.clientCredentials.tokenUrl`);return{name:t,kind:"oauth2-client-credentials",tokenUrl:c,scopes:a}}return{name:t,kind:"unsupported",protocol:`oauth2:${i}`,oauthScopes:a}}o(gn,"parseOAuthFlow");function mn(t,e,n){if(!B(n))throw new Error(`securitySchemes.${t}.${e} must be an object.`);if(e==="apiKeySecurityScheme"){let r=P(n.location,`securitySchemes.${t}.${e}.location`);if(!["query","header","cookie"].includes(r))throw new Error(`securitySchemes.${t}.${e}.location must be query, header, or cookie.`);return P(n.name,`securitySchemes.${t}.${e}.name`),{name:t,kind:"unsupported",protocol:"api-key"}}return e==="openIdConnectSecurityScheme"?(at(n.openIdConnectUrl,`securitySchemes.${t}.${e}.openIdConnectUrl`),{name:t,kind:"unsupported",protocol:"openid-connect",acceptsOAuthScopes:!0}):{name:t,kind:"unsupported",protocol:"mutual-tls"}}o(mn,"parseUnsupportedScheme");function yn(t,e){if(!B(e))throw new Error(`securitySchemes.${t} must be an object.`);let n=dn.filter(i=>e[i]!==void 0);if(n.length!==1)throw new Error(`securitySchemes.${t} must contain exactly one security scheme.`);let r=n[0];if(r==="httpAuthSecurityScheme")return hn(t,e[r]);if(r==="oauth2SecurityScheme"){let i=e[r];if(!B(i))throw new Error(`securitySchemes.${t}.${r} must be an object.`);return gn(t,i)}return mn(t,r,e[r])}o(yn,"parseScheme");function wn(t){if(t===void 0)return{};if(!B(t))throw new Error("securitySchemes must be an object.");return Object.fromEntries(Object.entries(t).map(([e,n])=>{if(e.trim().length===0)throw new Error("securitySchemes names must not be empty.");return[e,yn(e,n)]}))}o(wn,"parseSchemes");function kn(t,e){if(!B(t))throw new Error(`${e} must be a StringList object.`);if(t.list===void 0)return[];if(!Array.isArray(t.list)||!t.list.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${e}.list must be an array of non-empty strings.`);if(new Set(t.list).size!==t.list.length)throw new Error(`${e}.list must not contain duplicate scopes.`);for(let n of t.list)re(n,`${e}.list`);return t.list}o(kn,"parseScopeList");function Sn(t,e){if(t.kind==="oauth2-client-credentials"||t.kind==="unsupported"&&t.oauthScopes!==void 0){let n=t.kind==="oauth2-client-credentials"?t.scopes:t.oauthScopes??[];for(let r of e)if(!n.includes(r))throw new Error(`scope "${r}" is not declared by security scheme "${t.name}".`);return}if(e.length>0&&!(t.kind==="unsupported"&&t.acceptsOAuthScopes))throw new Error(`security scheme "${t.name}" does not accept OAuth scopes.`)}o(Sn,"validateRequiredScopes");function Rn(t,e,n){if(!B(t))throw new Error(`securityRequirements[${e}] must be an object.`);let r=t.schemes;if(r!==void 0&&!B(r))throw new Error(`securityRequirements[${e}].schemes must be an object.`);return{schemes:Object.entries(r??{}).map(([a,c])=>{if(!Object.hasOwn(n,a))throw new Error(`securityRequirements[${e}] references unknown security scheme "${a}".`);let d=n[a],u=kn(c,`securityRequirements[${e}].schemes.${a}`);return Sn(d,u),{scheme:d,scopes:u}})}}o(Rn,"parseRequirement");function F(t,e){let n=wn(t);if(e===void 0)return{schemes:n,requirements:[]};if(!Array.isArray(e))throw new Error("securityRequirements must be an array.");return{schemes:n,requirements:e.map((r,i)=>Rn(r,i,n))}}o(F,"parseA2ASecurity");function Tn(t,e){let{scheme:n,scopes:r}=e;return n.kind!=="unsupported"&&t.schemeName===n.name&&t.kind===n.kind&&r.every(i=>t.scopes?.includes(i)===!0)}o(Tn,"capabilityMatches");function Bi(t,e){return ye(t,e)[0]??null}o(Bi,"selectA2ASecurityRequirement");function ye(t,e){return(t.requirements.length===0?[{schemes:[]}]:t.requirements).filter(r=>r.schemes.every(i=>e.some(s=>Tn(s,i))))}o(ye,"satisfiableA2ASecurityRequirements");var En=new Set(["TASK_STATE_UNSPECIFIED","TASK_STATE_SUBMITTED","TASK_STATE_WORKING","TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_INPUT_REQUIRED","TASK_STATE_REJECTED","TASK_STATE_AUTH_REQUIRED"]);function g(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}o(g,"isRecord");function ct(t){if(t===null)return;let e=t.split(";",1)[0]?.trim().toLowerCase();return e&&!/\s/u.test(e)?e:void 0}o(ct,"mediaTypeEssence");function de(t){let e=ct(t);return e==="application/json"||/^application\/[!#$%&'*+\-.^_`|~0-9a-z]+\+json$/u.test(e??"")}o(de,"isJsonMediaType");function dt(t){return ct(t)==="text/event-stream"}o(dt,"isEventStreamMediaType");function M(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new A(-32602,`${n}.${e} must be a non-empty string.`);return r}o(M,"requiredString");function C(t,e){let n=t[e];return typeof n=="string"&&n.length>0?n:void 0}o(C,"optionalString");function se(t,e){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new A(-32602,`${e} must be a string array.`);return t}o(se,"stringArray");function bn(t){if(!g(t))throw new A(-32602,"Agent Card interface is invalid.");return{url:M(t,"url","interface"),protocolBinding:M(t,"protocolBinding","interface"),protocolVersion:M(t,"protocolVersion","interface"),...C(t,"tenant")?{tenant:C(t,"tenant")}:{}}}o(bn,"parseInterface");function ut(t,e,n){try{F(t,e)}catch(r){let i=r instanceof Error?r.message:String(r);throw new A(-32602,`${n} is invalid: ${i}`)}}o(ut,"validateSecurity");function In(t,e){if(!g(t))throw new A(-32602,"Agent Card skill is invalid.");return t.securityRequirements!==void 0&&ut(e,t.securityRequirements,"skill.securityRequirements"),{id:M(t,"id","skill"),name:M(t,"name","skill"),description:M(t,"description","skill"),tags:se(t.tags,"skill.tags"),...Array.isArray(t.examples)?{examples:se(t.examples,"skill.examples")}:{},...Array.isArray(t.inputModes)?{inputModes:se(t.inputModes,"skill.inputModes")}:{},...Array.isArray(t.outputModes)?{outputModes:se(t.outputModes,"skill.outputModes")}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(g)}:{}}}o(In,"parseSkill");function xn(t){if(!g(t))throw new A(-32602,"Agent Card extension is invalid.");let e=M(t,"uri","extension");try{new URL(e)}catch{throw new A(-32602,"Agent Card extension.uri must be an absolute URI.")}if(t.description!==void 0&&typeof t.description!="string")throw new A(-32602,"Agent Card extension.description must be a string.");if(t.required!==void 0&&typeof t.required!="boolean")throw new A(-32602,"Agent Card extension.required must be a boolean.");if(t.params!==void 0&&!g(t.params))throw new A(-32602,"Agent Card extension.params must be an object.");return{uri:e,...typeof t.description=="string"?{description:t.description}:{},...typeof t.required=="boolean"?{required:t.required}:{},...g(t.params)?{params:t.params}:{}}}o(xn,"parseExtension");function lt(t){if(!g(t))throw new A(-32602,"Agent Card must be an object.");let e=t.supportedInterfaces,n=t.skills;if(!Array.isArray(e)||e.length===0)throw new A(-32602,"Agent Card must declare supportedInterfaces.");if(!Array.isArray(n))throw new A(-32602,"Agent Card must declare skills.");if(!g(t.capabilities))throw new A(-32602,"Agent Card capabilities are invalid.");if(t.capabilities.extensions!==void 0&&!Array.isArray(t.capabilities.extensions))throw new A(-32602,"Agent Card capabilities.extensions must be an array.");return ut(t.securitySchemes,t.securityRequirements,"Agent Card security declaration"),{name:M(t,"name","Agent Card"),description:M(t,"description","Agent Card"),supportedInterfaces:e.map(bn),version:M(t,"version","Agent Card"),capabilities:{...typeof t.capabilities.streaming=="boolean"?{streaming:t.capabilities.streaming}:{},...typeof t.capabilities.pushNotifications=="boolean"?{pushNotifications:t.capabilities.pushNotifications}:{},...typeof t.capabilities.extendedAgentCard=="boolean"?{extendedAgentCard:t.capabilities.extendedAgentCard}:{},...Array.isArray(t.capabilities.extensions)?{extensions:t.capabilities.extensions.map(xn)}:{}},...g(t.securitySchemes)?{securitySchemes:t.securitySchemes}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(g)}:{},defaultInputModes:se(t.defaultInputModes,"Agent Card defaultInputModes"),defaultOutputModes:se(t.defaultOutputModes,"Agent Card defaultOutputModes"),skills:n.map(r=>In(r,t.securitySchemes))}}o(lt,"parseA2AAgentCard");function At(t){if(!g(t))throw new A(-32602,"Message Part must be an object.");let e=["text","raw","url","data"].filter(r=>t[r]!==void 0);if(e.length!==1)throw new A(-32602,"Message Part must contain exactly one content field.");let n=e[0];if(n!=="data"&&typeof t[n]!="string")throw new A(-32602,`Message Part ${n} content must be a string.`);return{...typeof t.text=="string"?{text:t.text}:{},...typeof t.raw=="string"?{raw:t.raw}:{},...typeof t.url=="string"?{url:t.url}:{},...t.data!==void 0?{data:t.data}:{},...g(t.metadata)?{metadata:t.metadata}:{},...C(t,"filename")?{filename:C(t,"filename")}:{},...C(t,"mediaType")?{mediaType:C(t,"mediaType")}:{}}}o(At,"parseA2APart");function D(t){if(!g(t))throw new A(-32602,"Message must be an object.");if(t.role!=="ROLE_USER"&&t.role!=="ROLE_AGENT")throw new A(-32602,"Message role is invalid.");if(!Array.isArray(t.parts)||t.parts.length===0)throw new A(-32602,"Message parts must not be empty.");return{messageId:M(t,"messageId","Message"),role:t.role,parts:t.parts.map(At),...C(t,"contextId")?{contextId:C(t,"contextId")}:{},...C(t,"taskId")?{taskId:C(t,"taskId")}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(D,"parseA2AMessage");function vn(t){if(!g(t)||!Array.isArray(t.parts)||t.parts.length===0)throw new A(-32603,"A2A artifact is invalid.");return{artifactId:M(t,"artifactId","Artifact"),parts:t.parts.map(At),...C(t,"name")?{name:C(t,"name")}:{},...C(t,"description")?{description:C(t,"description")}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(vn,"parseArtifact");function H(t){if(!g(t)||!g(t.status))throw new A(-32603,"A2A task is invalid.");let e=t.status.state;if(typeof e!="string")throw new A(-32603,"A2A task state is invalid.");let n=En.has(e)?e:"TASK_STATE_UNSPECIFIED";return{id:M(t,"id","Task"),contextId:C(t,"contextId")??"",status:{state:n,...t.status.message!==void 0?{message:D(t.status.message)}:{},...C(t.status,"timestamp")?{timestamp:C(t.status,"timestamp")}:{}},...Array.isArray(t.artifacts)?{artifacts:t.artifacts.map(vn)}:{},...Array.isArray(t.history)?{history:t.history.map(D)}:{},...g(t.metadata)?{metadata:t.metadata}:{}}}o(H,"parseA2ATask");function pt(t){if(!g(t)||t.jsonrpc!=="2.0")throw new A(-32600,"Invalid JSON-RPC request.");if(typeof t.id!="string"&&typeof t.id!="number")throw new A(-32600,"JSON-RPC request id is required.");return{jsonrpc:"2.0",id:t.id,method:M(t,"method","JSON-RPC request"),...g(t.params)?{params:t.params}:{}}}o(pt,"parseJsonRpcRequest");import{lookup as Cn}from"node:dns/promises";import{request as Pn}from"node:http";import{request as On}from"node:https";import{BlockList as _n,isIP as ft}from"node:net";import{Readable as Un}from"node:stream";var we=new _n;we.addSubnet("127.0.0.0",8,"ipv4");we.addAddress("::1","ipv6");function Oe(t){let e=ft(t);return e===4?we.check(t,"ipv4"):e===6&&we.check(t,"ipv6")}o(Oe,"isLoopbackAddress");function Mn(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Mn,"isExactLoopbackHostname");function _e(t){let e=t.split(".").map(Number),[n,r,i,s]=e;return e.length!==4||n===void 0||r===void 0||i===void 0||s===void 0?!0:n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&i===0&&s!==9&&s!==10||n===192&&r===0&&i===2||n===198&&(r===18||r===19)||n===198&&r===51&&i===100||n===203&&r===0&&i===113||n>=224}o(_e,"isPrivateIpv4");function Ln(t){if(Oe(t))return!0;let e=t.toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(e)?.[1];if(n)return _e(n);let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(r?.[1]&&r[2]){let i=Number.parseInt(r[1],16),s=Number.parseInt(r[2],16);return _e(`${i>>8}.${i&255}.${s>>8}.${s&255}`)}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")||e.startsWith("ff")}o(Ln,"isPrivateIpv6");function Nn(t){let e=ft(t);return e===4?_e(t):e===6?Ln(t):!0}o(Nn,"isPrivateAddress");async function ht(t,e){if(t.protocol!=="https:"&&t.protocol!=="http:")throw new A(-32602,"A2A URL must use HTTP or HTTPS.");if(!e.allowedOrigins.includes(t.origin))throw new A(-32602,`A2A origin is not allowed: ${t.origin}`);if(t.username||t.password)throw new A(-32602,"A2A URL must not include credentials.");let n=t.hostname.startsWith("[")&&t.hostname.endsWith("]")?t.hostname.slice(1,-1):t.hostname,r=await Cn(n,{all:!0,verbatim:!0});if(r.length===0)throw new A(-32602,"A2A hostname did not resolve.");if(n.toLowerCase()==="localhost"&&!r.every(a=>Oe(a.address)))throw new A(-32602,"A2A localhost target must resolve only to loopback addresses.");let i=Mn(n)&&r.every(a=>Oe(a.address));if(t.protocol==="http:"&&!i&&e.allowInsecureHttp!==!0)throw new A(-32602,"Non-loopback A2A targets must use HTTPS unless plaintext HTTP is explicitly allowed.");if(!e.allowPrivateAddresses&&r.some(a=>Nn(a.address)))throw new A(-32602,"A2A private network targets are not allowed.");let s=r[0];if(s===void 0||s.family!==4&&s.family!==6)throw new A(-32602,"A2A hostname returned an unsupported address.");return{address:s.address,family:s.family}}o(ht,"validateA2AUrl");async function qn(t,e){await ht(t,e)}o(qn,"assertSafeA2AUrl");function $n(t){if(t==null||typeof t=="string")return t??void 0;if(t instanceof URLSearchParams)return t.toString();if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new A(-32602,"A2A request body type is not supported by the safe transport.")}o($n,"encodeRequestBody");function Dn(t){return((e,n,r)=>{if(typeof n=="object"&&n.all){r(null,[t]);return}r(null,t.address,t.family)})}o(Dn,"pinnedLookup");function Kn(t,e,n){return new Promise((r,i)=>{let s=new Headers(e.headers);s.set("accept-encoding","identity");let a=(t.protocol==="https:"?On:Pn)(t,{method:e.method,headers:Object.fromEntries(s),lookup:Dn(n),signal:e.signal??void 0},c=>{let d=new Headers;for(let p=0;p<c.rawHeaders.length;p+=2){let h=c.rawHeaders[p],w=c.rawHeaders[p+1];h!==void 0&&w!==void 0&&d.append(h,w)}let u=c.statusCode??500,l=e.method!=="HEAD"&&u!==204&&u!==205&&u!==304?Un.toWeb(c):null;r(new Response(l,{status:u,statusText:c.statusMessage,headers:d}))});a.once("error",i),a.end($n(e.body))})}o(Kn,"requestValidatedAddress");async function Ue(t,e,n,r){let i=await ht(t,n);return r!==void 0?r(t,e):Kn(t,e,i)}o(Ue,"openSafeA2AResponse");async function jn(t,e){let n=t.headers.get("content-length");if(n&&Number(n)>e)throw new A(-32603,"A2A response is too large.");if(!t.body)return new Uint8Array;let r=t.body.getReader(),i=[],s=0;for(;;){let d=await r.read();if(d.done)break;if(s+=d.value.byteLength,s>e)throw await r.cancel(),new A(-32603,"A2A response is too large.");i.push(d.value)}let a=new Uint8Array(s),c=0;for(let d of i)a.set(d,c),c+=d.byteLength;return a}o(jn,"boundedBody");function Bn(t,e){if(!t)return{signal:e,cleanup:o(()=>{},"cleanup")};let n=new AbortController,r=o(()=>n.abort(t.reason),"abortFromCaller"),i=o(()=>n.abort(e.reason),"abortFromDeadline");return t.aborted?r():t.addEventListener("abort",r,{once:!0}),e.aborted?i():e.addEventListener("abort",i,{once:!0}),{signal:n.signal,cleanup:o(()=>{t.removeEventListener("abort",r),e.removeEventListener("abort",i)},"cleanup")}}o(Bn,"combineAbortSignals");async function V(t,e,n,r){let i=t,s=new Headers(e.headers).get("authorization");for(let a=0;a<=n.maxRedirects;a+=1){let c=new AbortController,d=setTimeout(()=>c.abort(new Error("A2A request timed out.")),n.requestTimeoutMs),u=Bn(e.signal,c.signal),f=new Headers(e.headers);s===null?f.delete("authorization"):f.set("authorization",s);try{let l=await Ue(i,{...e,headers:f,redirect:"manual",signal:u.signal},n,r);if(l.status<300||l.status>=400)return{response:l,body:await jn(l,n.maxResponseBytes),url:i};let p=l.headers.get("location");if(!p||a===n.maxRedirects)throw new A(-32603,"A2A redirect limit exceeded.");let h=new URL(p,i);await l.body?.cancel(),h.origin!==i.origin&&(s=null),i=h}finally{clearTimeout(d),u.cleanup()}}throw new A(-32603,"A2A redirect limit exceeded.")}o(V,"safeA2AFetch");function X(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}o(X,"decodeUtf8");import{createHash as Gn,randomUUID as Me}from"node:crypto";import*as K from"oauth4webapi";var Hn=6e4,zn=1e3,Jn=.1;function Fn(t,e){return new Response(e.byteLength===0?null:X(e),{status:t.status,statusText:t.statusText,headers:t.headers})}o(Fn,"oauthResponse");function Wn(t,e){if(e===void 0||e<=0)return t;let n=e*1e3,r=Math.min(Hn,Math.max(zn,n*Jn));return t+Math.max(0,n-r)}o(Wn,"cacheExpiry");function gt(t){let e=P(t.clientId,"OAuth 2.0 clientId");if(t.clientAuthenticationMethod!=="basic"&&t.clientAuthenticationMethod!=="post")throw new Error("OAuth 2.0 clientAuthenticationMethod must be basic or post.");let n=t.clientAuthenticationMethod,r=t.scopes===void 0?void 0:ie(t.scopes,"OAuth 2.0 scopes"),i=J(t.issuer,"OAuth 2.0 issuer"),s=$(t.tokenUrl,"OAuth 2.0 token endpoint"),a=t.resource===void 0?void 0:ne(t.resource,"OAuth 2.0 resource"),c={issuer:i,token_endpoint:s.href},d={client_id:e},u={...t.networkPolicy,maxRedirects:0},f=t.now??Date.now,l,p,h=0;async function w(k){let y=n==="post"?K.ClientSecretPost(k):K.ClientSecretBasic(k),T=new URLSearchParams;r&&r.length>0&&T.set("scope",r.join(" ")),a!==void 0&&T.set("resource",a);let m={[K.customFetch]:async(R,_)=>{if(new URL(R).href!==s.href)throw new Error("OAuth 2.0 token request targeted an unexpected endpoint.");let j=await V(s,{method:_.method,headers:_.headers,body:_.body,redirect:"manual",..._.signal!==void 0?{signal:_.signal}:{}},u,t.fetch);return Fn(j.response,j.body)}};s.protocol==="http:"&&(m[K.allowInsecureRequests]=!0);let S;try{let R=await K.clientCredentialsGrantRequest(c,d,y,T,m);S=await K.processClientCredentialsResponse(c,d,R)}catch{throw new Error("OAuth 2.0 client credentials token request failed.")}if(S.token_type!=="bearer")throw new Error("OAuth 2.0 token endpoint did not return a Bearer access token.");let L=f();return{value:`Bearer ${S.access_token}`,expiresAt:Wn(L,S.expires_in)}}return o(w,"requestAuthorization"),{async getAuthorization(k){if(k.length===0)throw new Error("OAuth 2.0 client secret is required.");let y=f();if(l!==void 0&&l.expiresAt>y)return l.value;if(p!==void 0)return p;let T=h,m;return m=w(k).then(S=>(h===T&&S.expiresAt>f()&&(l=S),S.value)).finally(()=>{p===m&&(p=void 0)}),p=m,m},invalidate(k){if(k!==void 0){l?.value===k&&(l=void 0);return}h+=1,l=void 0,p=void 0}}}o(gt,"createOAuth2ClientCredentialsTokenManager");var mt=4,yt=/^[A-Za-z0-9\-._~+/=]$/u;function ke(t){return t!==void 0&&/^Bearer\s+\S+$/iu.test(t)}o(ke,"isBearerAuthorization");function Vn(t,e){let n="",r=0;for(;r<t.length;){let i=t.indexOf(e,r);if(i<0)return n+t.slice(r);let s=i===0?void 0:t[i-1],a=i+e.length,c=a===t.length?void 0:t[a],d=s===void 0||!yt.test(s),u=c===void 0||!yt.test(c);n+=t.slice(r,i),d&&u?(n+="[REDACTED]",r=a):(n+=e,r=a)}return n}o(Vn,"replaceBoundedToken");function Ae(t){return Array.isArray(t)?`[${t.map(Ae).join(",")}]`:g(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Ae(t[e])}`).join(",")}}`:JSON.stringify(t)??"null"}o(Ae,"stableJson");function wt(t){return`sha256:${Gn("sha256").update(t).digest("hex")}`}o(wt,"sha256");var Ne=class{static{o(this,"AuthorizationRedactor")}#e=[];#n=new Map;remember(e){if(!e)return;let n=this.#e.indexOf(e);n>=0&&this.#e.splice(n,1),this.#e.unshift(e),this.#e.length>mt&&(this.#e.length=mt)}retain(e){if(!e)return()=>{};this.remember(e),this.#n.set(e,(this.#n.get(e)??0)+1);let n=!1;return()=>{if(n)return;n=!0;let r=(this.#n.get(e)??1)-1;r===0?this.#n.delete(e):this.#n.set(e,r)}}redactText(e){let n=[...new Set([...this.#n.keys(),...this.#e])],r=n.sort((s,a)=>a.length-s.length).reduce((s,a)=>s.split(a).join("[REDACTED]"),e),i=n.flatMap(s=>{let a=/^Bearer\s+(\S+)$/iu.exec(s)?.[1];return a?[a]:[]}).sort((s,a)=>a.length-s.length);return[...new Set(i)].reduce((s,a)=>Vn(s,a),r)}redactContent(e){return typeof e=="string"?this.redactText(e):Array.isArray(e)?e.map(n=>this.redactContent(n)):g(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,this.redactContent(r)])):e}redactPart(e){return{...e,...e.text===void 0?{}:{text:this.redactText(e.text)},...e.raw===void 0?{}:{raw:this.redactText(e.raw)},...e.url===void 0?{}:{url:this.redactText(e.url)},...e.data===void 0?{}:{data:this.redactContent(e.data)},...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)},...e.filename===void 0?{}:{filename:this.redactText(e.filename)}}}redactMessage(e){return{...e,parts:e.parts.map(n=>this.redactPart(n)),...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactArtifact(e){return{...e,...e.name===void 0?{}:{name:this.redactText(e.name)},...e.description===void 0?{}:{description:this.redactText(e.description)},parts:e.parts.map(n=>this.redactPart(n)),...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactTask(e){return{...e,status:{...e.status,...e.status.message===void 0?{}:{message:this.redactMessage(e.status.message)}},...e.artifacts===void 0?{}:{artifacts:e.artifacts.map(n=>this.redactArtifact(n))},...e.history===void 0?{}:{history:e.history.map(n=>this.redactMessage(n))},...e.metadata===void 0?{}:{metadata:this.redactContent(e.metadata)}}}redactError(e){let n=this.redactText(e instanceof Error?e.message:String(e));return e instanceof A?new A(e.code,n,e.httpStatus,this.redactContent(e.data),e.headers):new Error(n)}};function kt(t,e){let n=new URL(e).origin;if(!t.allowedOrigins.some(i=>new URL(i).origin===n))throw new Error(`A2A endpoint origin is not allowed by network policy: ${n}`);return{...t,allowedOrigins:[n]}}o(kt,"endpointNetworkPolicy");function Xn(t){if(t!==void 0){if(!g(t)||typeof t.scheme!="string")throw new Error("A2A registration authentication is invalid.");if(t.type==="http-bearer")return{type:"http-bearer",scheme:t.scheme};if(t.type!=="oauth2-client-credentials"||typeof t.issuer!="string"||typeof t.tokenUrl!="string"||typeof t.clientId!="string"||!Array.isArray(t.scopes)||!t.scopes.every(e=>typeof e=="string")||!["client-secret-basic","client-secret-post"].includes(String(t.clientAuthentication)))throw new Error("A2A registration OAuth2 authentication is invalid.");return{type:"oauth2-client-credentials",scheme:t.scheme,issuer:t.issuer,tokenUrl:t.tokenUrl,clientId:t.clientId,scopes:t.scopes,...typeof t.resource=="string"?{resource:t.resource}:{},clientAuthentication:t.clientAuthentication}}}o(Xn,"executorAuthentication");function Q(t){let e=t.executorConfig;if(!g(e))throw new Error("A2A registration executorConfig is missing.");if(typeof e.agentCardUrl!="string"||typeof e.interfaceUrl!="string")throw new Error("A2A registration endpoints are invalid.");let n=Xn(e.authentication);return{agentCardUrl:e.agentCardUrl,interfaceUrl:e.interfaceUrl,...typeof e.tenant=="string"?{tenant:e.tenant}:{},...n?{authentication:n}:{}}}o(Q,"executorConfig");function Qn(t,e){let n=t.supportedInterfaces.find(i=>i.protocolBinding.toUpperCase()==="JSONRPC"&&i.protocolVersion==="1.0");if(!n)throw new Error("Agent Card has no supported A2A 1.0 JSONRPC interface.");let r=new URL(n.url);if(r.username||r.password||r.hash)throw new Error("A2A interface URL must not contain credentials or a fragment.");if(r.origin!==e.origin)throw new Error("A2A interface must use the same origin as the trusted Agent Card.");return n}o(Qn,"chooseInterface");function Zn(t){if(t===void 0)return;if(!g(t))throw new Error("A2A authentication must be an object.");let e=P(t.scheme,"A2A authentication.scheme");if(t.type==="http-bearer")return{type:"http-bearer",scheme:e,credentialRef:P(t.credentialRef,"A2A authentication.credentialRef")};if(t.type!=="oauth2-client-credentials")throw new Error("A2A authentication.type must be http-bearer or oauth2-client-credentials.");if(t.clientAuthentication!=="client-secret-basic"&&t.clientAuthentication!=="client-secret-post")throw new Error("A2A authentication.clientAuthentication is invalid.");return{type:"oauth2-client-credentials",scheme:e,issuer:J(t.issuer,"Configured OAuth2 issuer"),tokenUrl:$(t.tokenUrl,"Configured OAuth2 token endpoint").href,clientId:P(t.clientId,"Configured OAuth2 clientId"),clientSecretRef:P(t.clientSecretRef,"Configured OAuth2 clientSecretRef"),scopes:ie(t.scopes,"Configured OAuth2 scopes"),...t.resource===void 0?{}:{resource:ne(t.resource,"Configured OAuth2 resource")},clientAuthentication:t.clientAuthentication}}o(Zn,"validatedClientAuthentication");function Yn(t){let e=t.credentialRef===void 0?void 0:P(t.credentialRef,"A2A credentialRef"),n=Zn(t.authentication);if(t.credentialRef!==void 0&&t.authentication!==void 0)throw new Error("A2A registration cannot combine credentialRef with structured authentication.");return{agentId:t.agentId,agentCardUrl:t.agentCardUrl,...e!==void 0?{credentialRef:e}:{},...n!==void 0?{authentication:n}:{},effects:t.effects}}o(Yn,"validatedRegistrationInput");function er(t,e,n){if(t.authentication)return[[{schemeName:t.authentication.scheme,kind:t.authentication.type,...t.authentication.type==="oauth2-client-credentials"?{scopes:t.authentication.scopes}:{}}]];let r=ke(n);if(!t.credentialRef&&!r)return[[]];let i=F(e.securitySchemes,e.securityRequirements);return Object.values(i.schemes).flatMap(s=>s.kind==="http-bearer"?[[{schemeName:s.name,kind:"http-bearer"}]]:[])}o(er,"configuredCapabilityCandidates");function St(t,e){for(let n of t){if(n.schemes.length!==1)continue;let r=n.schemes[0].scheme;if(e.some(i=>i.schemeName===r.name&&i.kind===r.kind))return r}}o(St,"matchingDeclaredScheme");function tr(t,e){let n=F(t.securitySchemes,t.securityRequirements),r=ye(n,e).filter(a=>a.schemes.length<=1);if(r.length===0)return null;let i=St(r,e),s=[];for(let a of t.skills){let c=F(t.securitySchemes,a.securityRequirements),d=ye(c,e).filter(u=>u.schemes.length<=1);d.length!==0&&(s.push(a.id),i??=St(d,e))}return t.skills.length>0&&s.length===0?null:{skillIds:s,...i?{declaredScheme:i}:{}}}o(tr,"evaluateSecurityCapabilities");function nr(t,e,n){if(t.credentialRef!==void 0&&t.authentication!==void 0)throw new Error("A2A registration cannot combine credentialRef with structured authentication.");if(n!==void 0&&!ke(n))throw new Error("A2A options.authorization must be a valid Bearer authorization.");let r=ke(n),i=t.credentialRef!==void 0||t.authentication!==void 0||r,s;for(let h of er(t,e,n)){let w=tr(e,h);if(w&&(!i||w.declaredScheme)){s=w;break}}if(!s)throw new Error(i?"Configured A2A authentication cannot fully satisfy the Agent Card and any advertised Skill security requirements.":"Agent Card or at least one advertised Skill requires authentication, but no compatible A2A authentication is configured.");if(!i)return{skillIds:s.skillIds};let a=s.declaredScheme,c=t.authentication;if(!c&&!t.credentialRef&&r)return{skillIds:s.skillIds};if(!c)return{credentialRef:t.credentialRef,authentication:{type:"http-bearer",scheme:a.name},skillIds:s.skillIds};if(c.type==="http-bearer")return{credentialRef:c.credentialRef,authentication:{type:"http-bearer",scheme:c.scheme},skillIds:s.skillIds};if(a.kind!=="oauth2-client-credentials")throw new Error("Configured OAuth2 authentication does not match the selected Agent Card scheme.");let d=a,u=J(c.issuer,"Configured OAuth2 issuer"),f=$(c.tokenUrl,"Configured OAuth2 token endpoint").href,l=c.resource===void 0?void 0:ne(c.resource,"Configured OAuth2 resource");if(new URL(d.tokenUrl).href!==f)throw new Error("Configured OAuth2 tokenUrl does not match the selected Agent Card security scheme.");let p=c.scopes.find(h=>!d.scopes.includes(h));if(p)throw new Error(`Configured OAuth2 scope is not declared by the Agent Card: ${p}`);return{credentialRef:c.clientSecretRef,authentication:{type:"oauth2-client-credentials",scheme:c.scheme,issuer:u,tokenUrl:f,clientId:c.clientId,scopes:c.scopes,...l?{resource:l}:{},clientAuthentication:c.clientAuthentication},skillIds:s.skillIds}}o(nr,"planClientAuthentication");function qe(t,e){try{return JSON.parse(t)}catch{throw new Error(`${e} returned invalid JSON.`)}}o(qe,"parseJson");function Et(t){let e=t.maxTaskResponseBytes??t.networkPolicy.maxResponseBytes;if(!Number.isSafeInteger(e)||e<=0)throw new Error("A2A maxTaskResponseBytes must be a positive safe integer.");return e}o(Et,"taskResponseBytes");function rr(t){return{...t.networkPolicy,maxResponseBytes:Et(t)}}o(rr,"taskNetworkPolicy");async function bt(t,e){let n=Yn(t),r=await V(new URL(n.agentCardUrl),{headers:{accept:"application/json"}},e.networkPolicy,e.fetch);if(!r.response.ok)throw new Error(`Agent Card request failed with HTTP ${r.response.status}.`);if(!de(r.response.headers.get("content-type")))throw new Error("Agent Card response is not JSON.");let i=lt(qe(X(r.body),"Agent Card")),s=i.capabilities.extensions?.filter(f=>f.required)??[];if(s.length>0)throw new Error(`Agent Card required A2A extension(s) are unsupported: ${s.map(f=>f.uri).join(", ")}`);let a=Qn(i,r.url),c=nr(n,i,e.authorization),d=Ae({agentCardUrl:r.url.href,interfaceUrl:a.url,protocolBinding:a.protocolBinding,protocolVersion:a.protocolVersion,tenant:a.tenant??"",authentication:c.authentication??null}),u=wt(Ae({card:i,endpointIdentity:d,credentialRef:c.credentialRef??null,effects:n.effects}));return{agentCard:i,registration:{agentId:n.agentId,displayName:i.name,description:i.description,enabled:!0,executorId:Pe,protocol:"a2a",configurationRevision:u,endpointIdentityHash:wt(d),...c.credentialRef?{credentialRef:c.credentialRef}:{},executorConfig:{agentCardUrl:r.url.href,interfaceUrl:a.url,...a.tenant?{tenant:a.tenant}:{},...c.authentication?{authentication:c.authentication}:{}},skills:c.skillIds,inputModalities:i.defaultInputModes,outputModalities:i.defaultOutputModes,capabilities:{streaming:i.capabilities.streaming?"supported":"unsupported",durableTasks:"supported",inputRequired:"supported",cancellation:"supported",artifacts:"supported"},effects:{remote:n.effects.remote,workspace:"proposal"},health:{status:"healthy",checkedAt:new Date().toISOString()}}}}o(bt,"discoverA2ARegistration");function le(t){return t.metadata??{}}o(le,"metadata");function $e(t){if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(Array.isArray(t))return t.map($e);if(g(t)){let e={};for(let[n,r]of Object.entries(t))e[n]=$e(r);return e}throw new Error("A2A response metadata must be JSON-safe.")}o($e,"toAgentJsonValue");function Rt(t){let e=le(t).directMessage;return e===void 0?void 0:D(e)}o(Rt,"directMessage");function ir(t){return{TASK_STATE_UNSPECIFIED:"unknown",TASK_STATE_SUBMITTED:"submitted",TASK_STATE_WORKING:"working",TASK_STATE_COMPLETED:"completed",TASK_STATE_FAILED:"failed",TASK_STATE_CANCELED:"canceled",TASK_STATE_INPUT_REQUIRED:"input-required",TASK_STATE_REJECTED:"rejected",TASK_STATE_AUTH_REQUIRED:"auth-required"}[t]??"unknown"}o(ir,"taskState");function De(t){return t.flatMap(e=>e.text===void 0?[]:[e.text]).join(`
|
|
3
|
+
`)}o(De,"textFromParts");function It(t,e){let n=t.mediaType??(t.data!==void 0?"application/json":"application/octet-stream"),r=t.raw!==void 0?`data:${n};base64,${t.raw}`:t.data!==void 0?`data:${n};base64,${Buffer.from(JSON.stringify(t.data),"utf8").toString("base64")}`:void 0,i=t.url??r;if(i)return{name:e,...t.mediaType?{mimeType:t.mediaType}:{},...t.raw!==void 0?{size:Buffer.from(t.raw,"base64").byteLength}:{},uri:i,provenance:"a2a"}}o(It,"partArtifactReference");function sr(t){let e=t.parts.find(n=>n.url!==void 0||n.raw!==void 0||n.data!==void 0);return e?It(e,t.name??t.artifactId):void 0}o(sr,"artifactReference");function ue(t){let e=(t.artifacts??[]).flatMap(i=>De(i.parts)),n=t.status.message?De(t.status.message.parts):"",r=[...e,n].filter(Boolean).join(`
|
|
4
|
+
`);return{state:ir(t.status.state),...r?{output:r}:{},...t.status.state==="TASK_STATE_FAILED"?{error:n||"Remote A2A task failed."}:{},...t.artifacts?.length?{artifacts:t.artifacts.flatMap(i=>sr(i)??[])}:{}}}o(ue,"snapshotFromTask");function Le(t){let e=De(t.parts),n=t.parts.flatMap((r,i)=>{if(r.text!==void 0)return[];let s=It(r,r.filename??`message-part-${i+1}`);return s?[s]:[]});return{state:"completed",...e?{output:e}:{},...n.length>0?{artifacts:n}:{}}}o(Le,"snapshotFromMessage");function Tt(t){return t==="completed"||t==="failed"||t==="canceled"||t==="rejected"}o(Tt,"isTerminal");function or(t,e,n){let r=t.get(e.artifactId);t.set(e.artifactId,n&&r?{...r,...e,parts:[...r.parts,...e.parts]}:e)}o(or,"mergeStreamArtifact");var Se=class{constructor(e,n,r,i,s){this.registration=e;this.context=n;this.options=r;this.oauthTokenManager=i;this.releaseOAuthTokenManager=s}registration;context;options;oauthTokenManager;releaseOAuthTokenManager;static{o(this,"A2AClientExecutor")}#e=!1;#n=new Set;#t=new Ne;async preflight(){try{return Q(this.registration),{ok:!0}}catch(e){return{ok:!1,reasons:[e instanceof Error?e.message:String(e)]}}}async start(e,n){let r=e.idempotencyKey;if(!r)throw new Error("A2A executor requires an idempotency key.");let i=await this.sendMessage({message:{messageId:r,role:"ROLE_USER",parts:[{text:e.input??e.objective,mediaType:"text/plain"}]},configuration:{returnImmediately:!0}},n);if(g(i.task)){let s=H(i.task);return{idempotencyKey:r,remoteTaskId:s.id,...s.contextId?{metadata:{contextId:s.contextId}}:{}}}if(i.message!==void 0){let s=this.#t.redactMessage(D(i.message));return{idempotencyKey:r,metadata:{directMessage:$e(s)}}}throw new Error("A2A SendMessage returned neither task nor message.")}async*events(e){let n=Rt(e);if(n){yield await this.authorizeArtifacts(Le(this.#t.redactMessage(n)));return}if(this.registration.capabilities.streaming==="supported")try{yield*this.streamEvents(e);return}catch(r){if(this.#e)return;G({source:"a2a.client",level:"warn",message:"A2A event stream failed; polling fallback started.",detail:r}),yield{progress:{message:"A2A stream unavailable; polling."}}}for(;!this.#e;){let r=await this.get(e);if(yield r,Tt(r.state)||r.state==="input-required"||r.state==="auth-required")return;await new Promise(i=>setTimeout(i,this.options.pollIntervalMs))}}async get(e){let n=Rt(e);if(n)return this.authorizeArtifacts(Le(this.#t.redactMessage(n)));if(!e.remoteTaskId)throw new Error("A2A task reference has no remote task ID.");let r=H(await this.rpc("GetTask",this.taskParams(e)));return this.assertTaskReference(r,e),this.authorizeArtifacts(ue(this.#t.redactTask(r)))}async sendInput(e,n){if(!e.remoteTaskId)throw new Error("Direct A2A responses cannot accept input.");await this.sendMessage({message:{messageId:Me(),taskId:e.remoteTaskId,...typeof le(e).contextId=="string"?{contextId:le(e).contextId}:{},role:"ROLE_USER",parts:[{text:n.content,mediaType:"text/plain"}]},configuration:{returnImmediately:!0}})}async cancel(e){if(!e.remoteTaskId)return this.get(e);let n=H(await this.rpc("CancelTask",this.taskParams(e)));return this.assertTaskReference(n,e),this.authorizeArtifacts(ue(this.#t.redactTask(n)))}async reconcile(e){return this.get(e)}async dispose(){if(!this.#e){this.#e=!0;try{for(let e of this.#n)e.abort(new Error("A2A executor disposed."))}finally{this.releaseOAuthTokenManager?.()}}}async*streamEvents(e){if(!e.remoteTaskId)throw new Error("A2A stream requires a remote task ID.");let n=Q(this.registration),r=new URL(n.interfaceUrl),i=new Headers({accept:"text/event-stream","a2a-version":"1.0","content-type":"application/json"}),s=new AbortController,a=Me();this.#n.add(s);let c,d,u=o(()=>{d!==void 0&&clearTimeout(d),d=void 0},"disarmTimeout"),f=o(l=>{u(),d=setTimeout(()=>s.abort(new Error(l)),this.options.networkPolicy.requestTimeoutMs),d.unref?.()},"armTimeout");try{f("A2A stream connection timed out.");let l=await this.openStreamResponse(r,i,s.signal,{jsonrpc:"2.0",id:a,method:"SubscribeToTask",params:this.taskParams(e)}),p=l.response;if(c=l.releaseAuthorization,u(),!p.ok||!p.body)throw new Error(`A2A stream failed with HTTP ${p.status}.`);if(!dt(p.headers.get("content-type")))throw new Error("A2A stream returned an invalid content type.");let h=p.body.getReader(),w=new TextDecoder,k=new Map,y="",T=0;for(;!this.#e;){f("A2A stream was idle for too long.");let m=await h.read();if(u(),m.done)break;if(T+=m.value.byteLength,T>Et(this.options))throw new Error("A2A stream exceeded the response size limit.");y+=w.decode(m.value,{stream:!0});let S=y.split(/\r?\n\r?\n/);y=S.pop()??"";for(let L of S){let R=L.split(/\r?\n/).filter(j=>j.startsWith("data:")).map(j=>j.slice(5).trimStart()).join(`
|
|
5
|
+
`);if(!R)continue;let _=await this.snapshotFromStreamPayload(qe(R,"A2A stream"),a,e,k);if(_&&(yield _,_.state&&(Tt(_.state)||_.state==="input-required"||_.state==="auth-required")))return}}if(!this.#e)throw new Error("A2A event stream ended before the task reached a stable state.")}catch(l){throw this.#t.redactError(l)}finally{u(),c?.(),this.#n.delete(s)}}async snapshotFromStreamPayload(e,n,r,i){if(!g(e))throw new Error("A2A stream frame is invalid.");if(e.jsonrpc!=="2.0"||e.id!==n)throw new Error("A2A stream frame has an invalid JSON-RPC version or response id.");if(e.error!==void 0){let s=g(e.error)?e.error:{},a=typeof s.message=="string"?s.message:"A2A stream error.";throw new A(typeof s.code=="number"?s.code:-32603,this.#t.redactText(a))}if(g(e.result)){if(e.result.task!==void 0){let s=H(e.result.task);this.assertTaskReference(s,r),i.clear();for(let a of s.artifacts??[])i.set(a.artifactId,a);return this.authorizeArtifacts(ue(this.#t.redactTask(s)))}if(e.result.message!==void 0){let s=D(e.result.message);if(s.taskId!==void 0&&s.taskId!==r.remoteTaskId)throw new Error("A2A stream message belongs to a different task.");return this.authorizeArtifacts(Le(this.#t.redactMessage(s)))}if(g(e.result.statusUpdate)&&g(e.result.statusUpdate.status)){this.assertStreamTaskScope(e.result.statusUpdate,r);let s=H({id:r.remoteTaskId,contextId:e.result.statusUpdate.contextId,status:e.result.statusUpdate.status,...i.size>0?{artifacts:[...i.values()]}:{}});return this.authorizeArtifacts(ue(this.#t.redactTask(s)))}if(g(e.result.artifactUpdate)&&e.result.artifactUpdate.artifact!==void 0){this.assertStreamTaskScope(e.result.artifactUpdate,r);let s=H({id:r.remoteTaskId,contextId:e.result.artifactUpdate.contextId,status:{state:"TASK_STATE_WORKING"},artifacts:[e.result.artifactUpdate.artifact]}),a=s.artifacts?.[0];if(!a)throw new Error("A2A artifact update has no artifact.");or(i,a,e.result.artifactUpdate.append===!0);let c={...s,artifacts:[...i.values()]};return this.authorizeArtifacts(ue(this.#t.redactTask(c)))}}}async authorizeArtifacts(e){for(let n of e.artifacts??[])await this.context.authorizeArtifact(n);return e}assertTaskReference(e,n){if(e.id!==n.remoteTaskId)throw new Error("A2A response belongs to a different task id.");let r=le(n).contextId;if(typeof r=="string"&&e.contextId&&e.contextId!==r)throw new Error("A2A response belongs to a different task context.")}assertStreamTaskScope(e,n){if(typeof e.taskId!="string"||e.taskId!==n.remoteTaskId)throw new Error("A2A stream event belongs to a different task.");let r=le(n).contextId;if(typeof e.contextId!="string"||typeof r=="string"&&e.contextId!==r)throw new Error("A2A stream event belongs to a different task context.")}async openStreamResponse(e,n,r,i){let s=o(a=>{let c=new Headers(n);return a&&c.set("authorization",a),Ue(e,{method:"POST",headers:c,redirect:"manual",signal:r,body:JSON.stringify(i)},this.options.networkPolicy,this.options.fetch)},"open");return this.withAuthorization(async a=>{let c=this.#t.retain(a);try{let d=await s(a);if(d.status===401)throw await d.body?.cancel(),new A(-32600,"A2A authentication was rejected.",401);return{response:d,releaseAuthorization:c}}catch(d){throw c(),d}})}taskParams(e){let n=Q(this.registration);return{id:e.remoteTaskId,...n.tenant?{tenant:n.tenant}:{}}}async sendMessage(e,n){let r=await this.rpc("SendMessage",{...e,...Q(this.registration).tenant?{tenant:Q(this.registration).tenant}:{}},n);if(!g(r))throw new Error("A2A SendMessage result is invalid.");return r}async rpc(e,n,r){if(this.#e)throw new Error("A2A executor is disposed.");return this.withAuthorization(i=>this.rpcWithAuthorization(e,n,i,r))}redactRpcResult(e,n){return e==="GetTask"||e==="CancelTask"?this.#t.redactTask(H(n)):e!=="SendMessage"||!g(n)?n:{...n,...n.task===void 0?{}:{task:this.#t.redactTask(H(n.task))},...n.message===void 0?{}:{message:this.#t.redactMessage(D(n.message))}}}async withAuthorization(e){let n=Q(this.registration).authentication;if(!n){if(this.options.authorization!==void 0&&!ke(this.options.authorization))throw new Error("A2A options.authorization must be a valid Bearer authorization.");let c=this.#t.retain(this.options.authorization);try{return await e(this.options.authorization)}catch(d){throw this.#t.redactError(d)}finally{c()}}let r=this.registration.credentialRef;if(!r)throw new Error("Authenticated A2A registration has no credential reference.");let i=o(c=>this.context.withCredential(r,async d=>{let u,f;try{return u=n.type==="http-bearer"?`Bearer ${d}`:await this.requireOAuthTokenManager().getAuthorization(d),f=this.#t.retain(u),{ok:!0,value:await e(u)}}catch(l){if(c&&n.type==="oauth2-client-credentials"&&l instanceof A&&l.httpStatus===401&&u!==void 0)return{ok:!1,rejectedAuthorization:u};throw this.#t.redactError(l)}finally{f?.()}}),"execute"),s=await i(n.type==="oauth2-client-credentials");if(s.ok)return s.value;this.requireOAuthTokenManager().invalidate(s.rejectedAuthorization);let a=await i(!1);if(!a.ok)throw new Error("A2A OAuth2 retry did not produce a result.");return a.value}requireOAuthTokenManager(){if(!this.oauthTokenManager)throw new Error("A2A OAuth2 token manager is unavailable.");return this.oauthTokenManager}async rpcWithAuthorization(e,n,r,i){let s=Q(this.registration),a=new Headers({accept:"application/json","a2a-version":"1.0","content-type":"application/json"});r&&a.set("authorization",r);let c=Me(),d=await V(new URL(s.interfaceUrl),{method:"POST",headers:a,body:JSON.stringify({jsonrpc:"2.0",id:c,method:e,params:n}),...i?{signal:i}:{}},rr(this.options),this.options.fetch);if(d.response.status===401)throw new A(-32600,"A2A authentication was rejected.",401);if(!de(d.response.headers.get("content-type")))throw new Error("A2A JSON-RPC response has an invalid content type.");let u=qe(X(d.body),"A2A endpoint");if(!g(u))throw new Error("A2A JSON-RPC response is invalid.");if(u.jsonrpc!=="2.0"||u.id!==c)throw new Error("A2A JSON-RPC response has an invalid version or response id.");let f=Object.hasOwn(u,"result"),l=Object.hasOwn(u,"error");if(f===l)throw new Error("A2A JSON-RPC response must contain exactly one result or error.");if(l)throw!g(u.error)||typeof u.error.code!="number"||typeof u.error.message!="string"?new Error("A2A JSON-RPC error response is invalid."):new A(u.error.code,this.#t.redactText(u.error.message),d.response.status,this.#t.redactContent(u.error.data));if(!d.response.ok)throw new Error(`A2A request failed with HTTP ${d.response.status}.`);return this.redactRpcResult(e,u.result)}};function xt(t){let e=new Map;return{executorId:Pe,protocol:"a2a",async create(n,r){let i=typeof t=="function"?t(n):t,s=Q(n),a=s.authentication,c={...i,networkPolicy:kt(i.networkPolicy,s.interfaceUrl)},d;if(a?.type==="oauth2-client-credentials"){let p=kt(i.networkPolicy,a.tokenUrl),h=Ae({authentication:a,credentialRef:n.credentialRef??"",networkPolicy:p}),w=e.get(n.agentId);if(d=w?.key===h&&w.fetch===i.fetch?w:void 0,!d){let k=gt({issuer:a.issuer,tokenUrl:a.tokenUrl,clientId:a.clientId,scopes:a.scopes,...a.resource?{resource:a.resource}:{},clientAuthenticationMethod:a.clientAuthentication==="client-secret-post"?"post":"basic",networkPolicy:p,...i.fetch?{fetch:i.fetch}:{}});d={key:h,fetch:i.fetch,manager:k,references:0},e.set(n.agentId,d)}}if(!d)return new Se(n,r,c);let u=d;u.references+=1;let f=!1,l=o(()=>{f||(f=!0,u.references-=1,u.references===0&&(u.manager.invalidate(),e.get(n.agentId)===u&&e.delete(n.agentId)))},"releaseOAuthTokenManager");return new Se(n,r,c,u.manager,l)}}}o(xt,"createA2AAgentExecutorFactory");import{createHash as dr,randomUUID as fe}from"node:crypto";import W from"node:fs";import{createServer as ur}from"node:http";import I from"node:path";import{Readable as Pt}from"node:stream";import{createHash as ar}from"node:crypto";var Z="realm-subject-tenant-v1";function vt(t){return ar("sha256").update(t).digest("hex")}o(vt,"sha256");function Ct(t){return vt(`${t.subject}\0${t.tenant??""}`)}o(Ct,"legacyA2APrincipalKey");function Re(t){return vt(JSON.stringify([t.securityRealm,t.subject,t.tenant??null]))}o(Re,"realmA2APrincipalKey");import U from"node:fs";import Te from"node:path";function Y(t){return structuredClone(t)}o(Y,"clone");function cr(t){if(!g(t))throw new Error("A2A task store record must be an object.");for(let n of["taskId","contextId","principalKey","runtimeIdentity","sessionId","createdAt","updatedAt"])if(typeof t[n]!="string")throw new Error(`A2A task store record has invalid ${n}.`);if(!g(t.messageDigests)||!Object.values(t.messageDigests).every(n=>typeof n=="string"))throw new Error("A2A task store message digests are invalid.");if(!Array.isArray(t.runIds)||!t.runIds.every(n=>typeof n=="string"))throw new Error("A2A task store run IDs are invalid.");if(!Array.isArray(t.history))throw new Error("A2A task store history is invalid.");if(t.principalKeyScheme!==void 0&&t.principalKeyScheme!==Z)throw new Error("A2A task store principal key scheme is unsupported.");if(!Number.isSafeInteger(t.eventSeq))throw new Error("A2A task store event cursors are invalid.");let e=t.pendingUserInput;if(e!==void 0&&(!g(e)||typeof e.requestId!="string"||!Number.isSafeInteger(e.revision)||typeof e.runId!="string"||typeof e.kind!="string"))throw new Error("A2A task store pending user input is invalid.");if(t.acceptedOutputModes!==void 0&&(!Array.isArray(t.acceptedOutputModes)||!t.acceptedOutputModes.every(n=>typeof n=="string")))throw new Error("A2A task store accepted output modes are invalid.");return{taskId:t.taskId,contextId:t.contextId,principalKey:t.principalKey,...t.principalKeyScheme===Z?{principalKeyScheme:Z}:{},runtimeIdentity:t.runtimeIdentity,sessionId:t.sessionId,...typeof t.workspaceRoot=="string"?{workspaceRoot:t.workspaceRoot}:{},...typeof t.executionPolicyRevision=="string"?{executionPolicyRevision:t.executionPolicyRevision}:{},messageDigests:t.messageDigests,runIds:t.runIds,task:H(t.task),history:t.history.map(D),createdAt:t.createdAt,updatedAt:t.updatedAt,eventSeq:t.eventSeq,runtimeEventCount:Number.isSafeInteger(t.runtimeEventCount)?t.runtimeEventCount:0,runtimeEventBytes:Number.isSafeInteger(t.runtimeEventBytes)?t.runtimeEventBytes:0,...t.acceptedOutputModes!==void 0?{acceptedOutputModes:t.acceptedOutputModes}:{},...e!==void 0?{pendingUserInput:{requestId:e.requestId,revision:e.revision,runId:e.runId,kind:e.kind}}:{}}}o(cr,"parseRecord");var oe=class{static{o(this,"A2AFileTaskStore")}#e=new Map;#n=new Map;#t;#r;#i;constructor(e){let n=Te.resolve(e);U.mkdirSync(n,{recursive:!0,mode:448}),this.#t=Te.join(n,"tasks.json"),this.#r=Te.join(n,".server.lock"),this.#i=this.acquireLock();try{this.load()}catch(r){throw U.closeSync(this.#i),U.rmSync(this.#r,{force:!0}),r}try{U.rmSync(Te.join(n,"runtime-cursors"),{recursive:!0,force:!0})}catch{}}get(e){let n=this.#e.get(e);return n?Y(n):void 0}findByMessage(e,n){for(let r of this.#e.values())if(r.principalKey===e&&r.messageDigests[n]!==void 0)return Y(r)}list(e){return[...this.#e.values()].filter(n=>n.principalKey===e).sort((n,r)=>r.updatedAt.localeCompare(n.updatedAt)||r.taskId.localeCompare(n.taskId)).map(Y)}all(){return[...this.#e.values()].map(Y)}save(e){let n=Y(e),r=this.#e.get(e.taskId);this.#e.set(e.taskId,n);try{this.persist()}catch(i){throw r?this.#e.set(e.taskId,r):this.#e.delete(e.taskId),i}for(let i of this.#n.get(e.taskId)??[])i(Y(n));return Y(n)}pruneTerminal(e,n){let r=[...this.#e.values()].filter(s=>s.principalKey===e).sort((s,a)=>s.updatedAt.localeCompare(a.updatedAt)),i=[];for(;r.length>n;){let s=r.findIndex(c=>c.task.status.state==="TASK_STATE_COMPLETED"||c.task.status.state==="TASK_STATE_FAILED"||c.task.status.state==="TASK_STATE_CANCELED"||c.task.status.state==="TASK_STATE_REJECTED");if(s<0)break;let[a]=r.splice(s,1);if(!a)break;this.#e.delete(a.taskId),this.#n.delete(a.taskId),i.push(Y(a))}return i.length>0&&this.persist(),i}migrateUnversionedPrincipalKeys(e){let n=0,r=0,i=0,s=[];for(let[a,c]of this.#e){if(c.principalKeyScheme!==void 0)continue;let d=e.legacyToCurrent.get(c.principalKey);d!==void 0?(n+=1,s.push([a,{...c,principalKey:d,principalKeyScheme:Z}])):e.currentKeys.has(c.principalKey)?(r+=1,s.push([a,{...c,principalKeyScheme:Z}])):i+=1}if(e.apply&&s.length>0){for(let[a,c]of s)this.#e.set(a,c);this.persist()}return{matchedLegacyTaskCount:n,matchedCurrentTaskCount:r,unmatchedUnversionedTaskCount:i}}subscribe(e,n){let r=this.#n.get(e)??new Set;return r.add(n),this.#n.set(e,r),()=>{r.delete(n),r.size===0&&this.#n.delete(e)}}close(){this.#n.clear(),U.closeSync(this.#i),U.rmSync(this.#r,{force:!0})}acquireLock(){let e=o(()=>{let n=U.openSync(this.#r,"wx",384);return U.writeFileSync(n,`${process.pid}
|
|
6
|
+
`,"utf8"),U.fsyncSync(n),n},"attempt");try{return e()}catch(n){let r=!1;try{let i=Number.parseInt(U.readFileSync(this.#r,"utf8").trim(),10);if(Number.isSafeInteger(i)&&i>0)try{process.kill(i,0)}catch(s){r=s.code==="ESRCH"}}catch{r=!1}if(!r)throw new Error("A2A task store is already owned by another server.",{cause:n});return U.rmSync(this.#r,{force:!0}),e()}}load(){if(!U.existsSync(this.#t))return;let e;try{e=JSON.parse(U.readFileSync(this.#t,"utf8"))}catch(n){throw new Error(`Failed to read A2A task store: ${n instanceof Error?n.message:String(n)}`)}if(!Array.isArray(e))throw new Error("A2A task store root must be an array.");for(let n of e){let r=cr(n);this.#e.set(r.taskId,r)}}persist(){let e=`${this.#t}.${process.pid}.tmp`;U.writeFileSync(e,`${JSON.stringify([...this.#e.values()],null,2)}
|
|
7
|
+
`,{encoding:"utf8",mode:384}),U.renameSync(e,this.#t)}};var O=new Set(["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_REJECTED"]),qt=new Set(["completed","failed","cancelled","interrupted"]),lr=new Set(["TASK_STATE_UNSPECIFIED","TASK_STATE_SUBMITTED","TASK_STATE_WORKING","TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_INPUT_REQUIRED","TASK_STATE_REJECTED","TASK_STATE_AUTH_REQUIRED"]),Ar=new Set(["CreateTaskPushNotificationConfig","GetTaskPushNotificationConfig","ListTaskPushNotificationConfigs","DeleteTaskPushNotificationConfig"]),pr=4,fr=8,hr=24*1024*1024,Ot=new Set([1,7,9,11,13,15,17,19,20,21,22,23,25,37,42,43,53,69,77,79,87,95,101,102,103,104,109,110,111,113,115,117,119,123,135,137,139,143,161,179,389,427,465,512,513,514,515,526,530,531,532,540,548,554,556,563,587,601,636,989,990,993,995,1719,1720,1723,2049,3659,4045,4190,5060,5061,6e3,6566,6665,6666,6667,6668,6669,6679,6697,10080]),gr=16;function mr(t,e,n){return new Promise((r,i)=>{let s=o(c=>{t.off("listening",a),i(c)},"onError"),a=o(()=>{t.off("error",s),r()},"onListening");t.once("error",s),t.once("listening",a),t.listen(e,n)})}o(mr,"listenNodeServer");function _t(t){return new Promise((e,n)=>{t.close(r=>r?n(r):e())})}o(_t,"closeNodeServer");function E(t){return t().toISOString()}o(E,"nowIso");function z(t){return dr("sha256").update(t).digest("hex")}o(z,"sha256");function Ke(t){let e=t.securityRealm;if(typeof e!="string"||e.trim().length===0)throw new Error("A2A authentication.securityRealm must be a non-empty stable string.");return e}o(Ke,"securityRealm");function $t(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o($t,"isLoopbackHostname");function yr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&$t(e.hostname)))throw new Error("Published A2A base URL must use HTTPS, except on loopback.");if(e.username||e.password)throw new Error("Published A2A base URL must not contain credentials.");return e}o(yr,"validateBaseUrl");function wr(t){let n={SendMessage:"send-message",SendStreamingMessage:"send-streaming-message",GetTask:"get-task",ListTasks:"list-tasks",CancelTask:"cancel-task",SubscribeToTask:"subscribe-to-task",GetExtendedAgentCard:"get-extended-agent-card"}[t];if(!n)throw new A(-32601,"Method not found.");return n}o(wr,"operationForMethod");function kr(t){return{queued:"TASK_STATE_SUBMITTED",running:"TASK_STATE_WORKING",waiting_agent:"TASK_STATE_WORKING",recovering:"TASK_STATE_WORKING",waiting_permission:"TASK_STATE_WORKING",waiting_user_input:"TASK_STATE_INPUT_REQUIRED",unknown:"TASK_STATE_FAILED",completed:"TASK_STATE_COMPLETED",failed:"TASK_STATE_FAILED",cancelled:"TASK_STATE_CANCELED",interrupted:"TASK_STATE_FAILED"}[t]}o(kr,"statusState");function Sr(t){return!qt.has(t)&&t!=="unknown"}o(Sr,"isLiveRunPhase");function Je(t,e,n){return{messageId:fe(),taskId:t,contextId:e,role:"ROLE_AGENT",parts:[{text:n,mediaType:"text/plain"}]}}o(Je,"agentMessage");function Rr(t){let e=yr(t);return e.pathname=`${e.pathname.replace(/\/$/,"")}/a2a`,e.search="",e.hash="",e.href}o(Rr,"interfaceUrl");function je(t,e){if(t!==void 0){if(!Number.isSafeInteger(t)||t<0)throw new A(-32602,`${e} must be a non-negative integer.`);return t}}o(je,"parseHistoryLength");function Be(t){if(typeof t?.id!="string"||t.id.length===0)throw new A(-32602,"Task id is required.");return t.id}o(Be,"requiredTaskId");function Tr(t){if(!(!g(t)||typeof t.label!="string"||typeof t.value!="string"))return{label:t.label,value:t.value,...typeof t.description=="string"?{description:t.description}:{}}}o(Tr,"publicInputOption");function Ut(t){if(!g(t)||typeof t.question!="string")return;let e=Array.isArray(t.options)?t.options.flatMap(n=>{let r=Tr(n);return r?[r]:[]}):void 0;return{question:t.question,...typeof t.header=="string"?{header:t.header}:{},...typeof t.kind=="string"?{kind:t.kind}:{},...e?{options:e}:{},...typeof t.multiSelect=="boolean"?{multiSelect:t.multiSelect}:{},...Number.isSafeInteger(t.minSelections)?{minSelections:t.minSelections}:{},...Number.isSafeInteger(t.maxSelections)?{maxSelections:t.maxSelections}:{},...typeof t.allowCustomInput=="boolean"?{allowCustomInput:t.allowCustomInput}:{},...typeof t.customInputLabel=="string"?{customInputLabel:t.customInputLabel}:{},...typeof t.customInputPrompt=="string"?{customInputPrompt:t.customInputPrompt}:{}}}o(Ut,"publicInputQuestion");function Er(t){return g(t)?Array.isArray(t.questions)?{questions:t.questions.flatMap(n=>{let r=Ut(n);return r?[r]:[]})}:Ut(t)??{}:{}}o(Er,"publicInputOptions");function Mt(t,e,n){let r=Er(n.options),i="";try{i=JSON.stringify(r)}catch{i="{}"}let s=i.length>4096?`${i.slice(0,4093)}...`:i;return{...Je(t,e,`Input required (${n.kind}): ${s}`),metadata:{"kodax.ai/user-input":{kind:n.kind,options:r}}}}o(Mt,"pendingInputMessage");function br(t,e){let n=t.parts.find(i=>i.data!==void 0)?.data;if(n!==void 0)return n;let r=t.parts.flatMap(i=>i.text===void 0?[]:[i.text]).join(`
|
|
8
|
+
`);if(e==="askUserMulti"||r.startsWith("[")||r.startsWith("{"))try{return JSON.parse(r)}catch{}return r}o(br,"continuationAnswer");function Ir(t,e){return t===void 0||e===void 0?t===e:t.requestId===e.requestId&&t.revision===e.revision&&t.runId===e.runId&&t.kind===e.kind}o(Ir,"samePendingUserInput");function Lt(t,e){let n=I.relative(t,e);return n===""||!n.startsWith(`..${I.sep}`)&&n!==".."&&!I.isAbsolute(n)}o(Lt,"isInside");function xr(t){return{".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".json":"application/json",".pdf":"application/pdf",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".html":"text/html",".htm":"text/html"}[I.extname(t).toLowerCase()]??"application/octet-stream"}o(xr,"artifactMediaType");function vr(t){return t.result?.writtenFiles?.map(e=>({target:e.path,admittedSkillOutput:e.sourceTool==="run_skill_script"}))??(t.result?.artifactLedger??[]).flatMap(e=>(e.kind==="file_created"||e.kind==="file_modified")&&typeof e.target=="string"?[{target:e.target,admittedSkillOutput:e.sourceTool==="run_skill_script"&&e.action==="promote_output"}]:[])}o(vr,"outputFileCandidates");function Cr(t,e,n){let r=t.workspaceRoot??n.agent.projectPath;if(!r)return[];let i;try{i=W.realpathSync(r)}catch{return[]}let s=new Set,a=[];for(let c of vr(e)){let d=I.isAbsolute(c.target)?c.target:I.resolve(r,c.target),u=I.relative(r,d),f=u.split(I.sep).includes(".kodax-a2a-staging"),{admittedSkillOutput:l}=c;if(!Lt(r,d)||!f&&!l)continue;let p,h,w;try{if(p=W.lstatSync(d),h=W.realpathSync(d),!p.isFile()||p.isSymbolicLink()||!Lt(i,h)||s.has(h)||p.size>n.limits.maxPartBytes)continue;w=W.readFileSync(h)}catch{continue}if(w.byteLength>n.limits.maxPartBytes)continue;let k=xr(d);(t.acceptedOutputModes??n.agent.outputModes).includes(k)&&(s.add(h),a.push({artifactId:`file-${z(`${t.taskId}\0${u}\0${w.byteLength}\0${p.mtimeMs}`).slice(0,24)}`,name:I.basename(d),description:l?"KodaX Skill task output":"KodaX staged task output",parts:[{raw:w.toString("base64"),filename:I.basename(d),mediaType:k}]}))}return a}o(Cr,"stagedArtifacts");function Pr(t,e,n){let r=t;for(let i of[e.workspaceRoot,n.agent.projectPath,I.resolve(n.dataDir)])i&&(r=r.split(i).join("[redacted-path]"),r=r.split(i.replaceAll("\\","/")).join("[redacted-path]"));return r}o(Pr,"safeTaskText");function He(t,e=t.agent.publicBaseUrl){let n=Rr(e),r={name:t.agent.name,description:t.agent.description,supportedInterfaces:[{url:n,protocolBinding:"JSONRPC",protocolVersion:"1.0"}],version:t.agent.version,capabilities:{streaming:!0,pushNotifications:!1,extendedAgentCard:t.extendedAgentCard!==void 0},securitySchemes:t.authentication.securitySchemes,securityRequirements:t.authentication.securityRequirements,defaultInputModes:t.agent.inputModes,defaultOutputModes:t.agent.outputModes,skills:t.agent.skills};F(r.securitySchemes,r.securityRequirements);for(let i of r.skills)F(r.securitySchemes,i.securityRequirements);return r}o(He,"buildCard");function Or(t,e){if(t===null)return!1;let n=e.replace(/^W\//iu,"");return t.split(",").some(r=>{let i=r.trim();return i==="*"||i.replace(/^W\//iu,"")===n})}o(Or,"matchesIfNoneMatch");function he(t,e=200,n){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8",...n}})}o(he,"jsonResponse");async function _r(t,e){let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new A(-32600,"A2A request exceeds the configured limit.",413);if(!t.body)return new Uint8Array;let r=[],i=0,s=t.body.getReader();for(;;){let d=await s.read();if(d.done)break;if(i+=d.value.byteLength,i>e)throw await s.cancel("A2A request size limit exceeded."),new A(-32600,"A2A request exceeds the configured limit.",413);r.push(d.value)}let a=new Uint8Array(i),c=0;for(let d of r)a.set(d,c),c+=d.byteLength;return a}o(_r,"readBoundedBody");function pe(t,e){return he({jsonrpc:"2.0",id:t,result:e})}o(pe,"rpcResult");function Ur(t,e){let r={[-32001]:"TASK_NOT_FOUND",[-32002]:"TASK_NOT_CANCELABLE",[-32003]:"PUSH_NOTIFICATION_NOT_SUPPORTED",[-32004]:"UNSUPPORTED_OPERATION",[-32005]:"CONTENT_TYPE_NOT_SUPPORTED",[-32006]:"INVALID_AGENT_RESPONSE",[-32007]:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",[-32008]:"EXTENSION_SUPPORT_REQUIRED",[-32009]:"VERSION_NOT_SUPPORTED"}[e.code],i=e.data??(r?[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:r,domain:"a2a-protocol.org"}]:void 0);return he({jsonrpc:"2.0",id:t,error:{code:e.code,message:e.message,...i!==void 0?{data:i}:{}}},e.httpStatus,e.headers)}o(Ur,"rpcError");function Nt(t){return z(JSON.stringify(t))}o(Nt,"messageDigest");function Mr(t){return t.text!==void 0?Buffer.byteLength(t.text):t.raw!==void 0?Buffer.byteLength(t.raw,"base64"):t.url!==void 0?Buffer.byteLength(t.url):Buffer.byteLength(JSON.stringify(t.data))}o(Mr,"partBytes");function Dt(t){return t.mediaType??(t.text!==void 0?"text/plain":t.data!==void 0?"application/json":"application/octet-stream")}o(Dt,"partMediaType");function Kt(t){if(!W.existsSync(t))return 0;let e=0;for(let n of W.readdirSync(t,{withFileTypes:!0})){let r=I.join(t,n.name);n.isSymbolicLink()||(n.isDirectory()?e+=Kt(r):n.isFile()&&(e+=W.statSync(r).size))}return e}o(Kt,"directoryBytes");function Lr(t,e,n){if(t.role!=="ROLE_USER")throw new A(-32602,"Inbound message role must be ROLE_USER.");for(let r of t.parts){if(Mr(r)>e)throw new A(-32602,"Message Part exceeds the configured limit.");if(r.url!==void 0)throw new A(-32602,"Remote file URLs are not accepted by this server.");if(r.raw!==void 0&&!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r.raw))throw new A(-32602,"Message Part raw content is not valid base64.");let i=Dt(r);if(!n.includes(i))throw new A(-32005,`Media type ${i} is not supported.`)}}o(Lr,"validateInput");function ze(t,e,n){if(n===0){let{history:i,...s}=t;return s}let r=n===void 0?e:e.slice(-n);return{...t,history:r}}o(ze,"withHistory");function Nr(t){if(!t)return;let e;try{e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new A(-32602,"Invalid page token.")}if(!g(e)||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||typeof e.taskId!="string"||e.taskId.length===0)throw new A(-32602,"Invalid page token.");return{updatedAt:e.updatedAt,taskId:e.taskId}}o(Nr,"parseTaskListCursor");function qr(t){return Buffer.from(JSON.stringify({updatedAt:t.updatedAt,taskId:t.taskId})).toString("base64url")}o(qr,"encodeTaskListCursor");function $r(t,e){let n=t.updatedAt.localeCompare(e.updatedAt);return n<0||n===0&&t.taskId.localeCompare(e.taskId)<0}o($r,"followsTaskListCursor");var Ee=class{constructor(e){this.options=e;Ke(e.authentication),this.#n=e.now??(()=>new Date),this.#e=new oe(e.dataDir),this.#o=He(e),this.#d=this.recover()}options;static{o(this,"KodaXA2AServerRuntime")}#e;#n;#t=new Map;#r=new Set;#i=new Set;#a=new Map;#c=new Map;#f=new Set;#d;#u=0;#l;#h=0;#A=!1;#s=!1;#p;#o;#g;get agentCard(){return structuredClone(this.#o)}async whenReady(){await this.#d}updateHot(e){if(this.#A||this.#s)throw new Error("A2A server is closed.");Ke(e.authentication);let n={...this.options,...e},r=He(n,e.agent.publicBaseUrl);this.options=n,this.#o=r}handle(e){if(this.#A||this.#s)return Promise.resolve(he({error:"A2A server is closed."},503));let n=o(()=>{},"release"),r=new Promise(i=>{n=i});return this.#f.add(r),this.handleAdmitted(e).finally(()=>{this.#f.delete(r),n()})}async handleAdmitted(e){await this.#d;let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/.well-known/agent-card.json"){let r=JSON.stringify(this.#o),i=`"${z(r)}"`,s={etag:i,"cache-control":"no-cache"};return Or(e.headers.get("if-none-match"),i)?new Response(null,{status:304,headers:s}):he(this.#o,200,s)}return e.method!=="POST"||n.pathname!=="/"&&n.pathname!=="/a2a"?he({error:"Not found."},404):this.handleRpc(e)}async listen(e){if(this.#A||this.#s)throw new Error("A2A server is closed.");if(this.#l)throw new Error("A2A server is already listening.");if(!$t(e.hostname))throw new Error("The built-in A2A HTTP listener is loopback-only; use handle() behind TLS for public service.");if(e.port!==0&&Ot.has(e.port))throw new Error(`Fetch-compatible clients block port ${e.port}; choose another A2A listener port.`);let n=ur((i,s)=>{this.handleNodeRequest(i).then(a=>{if(s.statusCode=a.status,a.headers.forEach((u,f)=>s.setHeader(f,u)),!a.body){s.end();return}let c=Pt.fromWeb(a.body),d=o(()=>{c.destroy()},"closeBody");s.once("close",d),c.once("close",()=>s.off("close",d)),c.once("error",()=>{s.destroyed||s.destroy()}),c.pipe(s)}).catch(a=>{let c=z(ge(a)).slice(0,16);this.emit({type:"server.request_failed",time:E(this.#n),outcome:"failed",diagnosticId:c}),s.statusCode=500,s.setHeader("content-type","application/json; charset=utf-8"),s.end(JSON.stringify({error:"Internal server error.",diagnosticId:c}))})}),r=e.port===0?gr:1;for(let i=0;i<r;i+=1){await mr(n,e.port,e.hostname);let s=n.address();if(!s||typeof s=="string")throw await _t(n),new Error("A2A server did not expose a TCP address.");if(Ot.has(s.port)){await _t(n);continue}let a=`http://${e.hostname}:${s.port}`;return this.#l=n,this.#g=e.publicBaseUrl??a,this.#o=He(this.options,this.#g),a}throw new Error("A2A server could not allocate a Fetch-compatible listener port.")}close(){if(this.#p)return this.#p;this.#A=!0;let e=this.#l;this.#l=void 0;let n=e?new Promise((r,i)=>e.close(s=>s?i(s):r())):Promise.resolve();return this.#p=this.closeAdmittedWork(n),this.#p}async closeAdmittedWork(e){let n=[];try{await this.#d}catch(r){n.push(r)}await Promise.all([...this.#f]),this.#s=!0;for(let r of[...this.#i])try{r()}catch(i){n.push(i)}this.#i.clear();for(let r of this.#t.values())try{r.close()}catch(i){n.push(i)}this.#t.clear(),this.#r.clear();try{await e}catch(r){n.push(r)}try{this.#e.close()}catch(r){n.push(r)}try{await this.options.preparedExecution?.close()}catch(r){n.push(r)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"A2A server close failed.")}async handleNodeRequest(e){let r=`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,i=new Headers;for(let[a,c]of Object.entries(e.headers))if(typeof c=="string")i.set(a,c);else for(let d of c??[])i.append(a,d);let s={method:e.method,headers:i,...e.method==="GET"||e.method==="HEAD"?{}:{body:Pt.toWeb(e)},duplex:"half"};return this.handle(new Request(r,s))}async handleRpc(e){let n=this.options,r=null;try{if((e.headers.get("a2a-version")??new URL(e.url).searchParams.get("A2A-Version"))!=="1.0")throw new A(-32009,"A2A version is not supported.");if(!de(e.headers.get("content-type")))throw new A(-32600,"A2A JSON-RPC requests require application/json.",415);let s=await n.authentication.authenticate(e);if(!s)throw new A(-32600,"Authentication required.",401,void 0,{"www-authenticate":"Bearer"});let a=await _r(e,n.limits.maxRequestBytes),c;try{c=JSON.parse(new TextDecoder().decode(a))}catch{throw new A(-32700,"Invalid JSON payload.")}let d=pt(c);if(r=d.id,Ar.has(d.method))throw new A(-32003,"Push notifications are not supported.");let u=wr(d.method),f=d.method==="SendMessage"||d.method==="SendStreamingMessage"?D(d.params?.message):void 0,l=typeof d.params?.id=="string"?d.params.id:f?.taskId,p=f?.contextId,h=f?[...new Set(f.parts.map(Dt))]:void 0;if(!await n.authorize({principal:s,operation:u,...l?{taskId:l}:{},...p?{contextId:p}:{},...h?{inputModes:h}:{}}))throw new A(-32001,"Task not found.");return await this.dispatch(d,s,n)}catch(i){let s=z(ge(i)).slice(0,16),a=i instanceof A?i:new A(-32603,"Internal error.",500,[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:"INTERNAL",domain:"kodax.ai",metadata:{diagnosticId:s}}]);return this.emit({type:"rpc.failed",time:E(this.#n),outcome:"failed",diagnosticId:s}),Ur(r,a)}}async dispatch(e,n,r){let i=Re({securityRealm:Ke(r.authentication),subject:n.subject,...n.tenant!==void 0?{tenant:n.tenant}:{}});switch(e.method){case"SendMessage":return pe(e.id,{task:await this.sendMessage(e.params,i,!1,r)});case"SendStreamingMessage":{let s=await this.sendMessage(e.params,i,!0,r);return this.streamTask(e.id,s.id,i)}case"GetTask":return pe(e.id,await this.getTask(e.params,i));case"ListTasks":return pe(e.id,this.listTasks(e.params,i));case"CancelTask":return pe(e.id,await this.cancelTask(e.params,i,r));case"SubscribeToTask":return this.subscribeTask(e.id,e.params,i);case"GetExtendedAgentCard":{if(!r.extendedAgentCard)throw new A(-32004,"Extended Agent Card is not supported.");return pe(e.id,r.extendedAgentCard)}default:throw new A(-32601,"Method not found.")}}async sendMessage(e,n,r,i){let s=this.#c.get(n)??Promise.resolve(),a=o(()=>{},"release"),c=new Promise(d=>{a=d});this.#c.set(n,c),await s;try{return await this.sendMessageUnserialized(e,n,r,i)}finally{a(),this.#c.get(n)===c&&this.#c.delete(n)}}async sendMessageUnserialized(e,n,r,i){let s=D(e?.message);if(Lr(s,i.limits.maxPartBytes,i.agent.inputModes),e?.configuration!==void 0&&!g(e.configuration))throw new A(-32602,"SendMessage configuration must be an object.");let a=g(e?.configuration)?e.configuration:{},c=je(a.historyLength,"SendMessage historyLength");if(a.returnImmediately!==void 0&&typeof a.returnImmediately!="boolean")throw new A(-32602,"SendMessage returnImmediately must be a boolean.");if(a.taskPushNotificationConfig!==void 0)throw new A(-32003,"Push notifications are not supported.");if(a.acceptedOutputModes!==void 0){if(!Array.isArray(a.acceptedOutputModes)||!a.acceptedOutputModes.every(p=>typeof p=="string"))throw new A(-32602,"SendMessage acceptedOutputModes must be a string array.");if(!a.acceptedOutputModes.some(p=>i.agent.outputModes.includes(p)))throw new A(-32005,"No requested output media type is supported.")}let d=await this.admitMessage(s,n,i,a.acceptedOutputModes);if(d.runtimeEventsAttached)try{await d.runtimeEventsAttached}catch(p){throw this.failTask(d.record.taskId,"Task could not be started.",i),p}let u=this.#e.get(d.record.taskId)??d.record,l=d.duplicate||r||a.returnImmediately===!0?u:await this.waitForTask(u.taskId,i.limits.maxTaskWaitMs??3e4);return ze(l.task,l.history,c)}async admitMessage(e,n,r,i){let s=Nt(e),a=this.#e.findByMessage(n,e.messageId);if(a){if(a.messageDigests[e.messageId]!==s)throw new A(-32602,"Message ID was reused with different content.");return this.emit({type:"task.deduplicated",time:E(this.#n),taskId:a.taskId,contextId:a.contextId}),{record:a,duplicate:!0}}let c=e.taskId?this.requireOwnedTask(e.taskId,n):void 0;if(c&&e.contextId!==void 0&&e.contextId!==c.contextId)throw new A(-32602,"Message contextId does not match the task.");if(c&&c.task.status.state!=="TASK_STATE_INPUT_REQUIRED"&&c.task.status.state!=="TASK_STATE_AUTH_REQUIRED")throw new A(-32004,"Task is not waiting for input.");let d=r.limits.maxRetainedTasksPerPrincipal??r.limits.maxTasksPerPrincipal??100;c||this.#e.pruneTerminal(n,Math.max(0,d-1));let u=this.#e.list(n);if(!c&&u.length>=d)throw new A(-32004,"Principal task limit reached.");let f=u.filter(p=>!O.has(p.task.status.state)).length;if(!c&&f>=(r.limits.maxActiveTasksPerPrincipal??4))throw new A(-32004,"Principal active task limit reached.");let l=!1;if(!c){if(this.#e.all().filter(h=>!O.has(h.task.status.state)).length+this.#u>=r.limits.maxConcurrentTasks)throw new A(-32004,"Server task concurrency limit reached.");this.#u+=1,l=!0}try{let p,h;if(c?.task.status.state==="TASK_STATE_INPUT_REQUIRED")p=await this.resumeUserInput(c,e,s,r);else{let w=c??await this.createRecord(e,n,r,i);c||(this.#u-=1,l=!1);let k=c?this.appendMessage(w,e,s):w;try{let y=await this.startRun(k,e,r);p=y.record,h=y.runtimeEventsAttached}catch(y){throw this.failTask(k.taskId,"Task could not be started.",r),y}}return{record:p,duplicate:!1,...h?{runtimeEventsAttached:h}:{}}}finally{l&&(this.#u-=1)}}async resumeUserInput(e,n,r,i){let s=e.pendingUserInput;if(!s)throw new A(-32004,"Task has no pending Runtime input request.");if(!(await i.runtime.userInputs.respond(s.requestId,br(n,s.kind),{expectedRevision:s.revision,runId:s.runId})).accepted)throw new A(-32004,"Pending Runtime input request is no longer active.");let c=this.#e.get(e.taskId)??e,d=this.appendMessage(c,n,r),{pendingUserInput:u,...f}=d;return O.has(d.task.status.state)?this.#e.save(f):this.#e.save({...f,task:{...d.task,status:{state:"TASK_STATE_WORKING",timestamp:E(this.#n)}},updatedAt:E(this.#n),eventSeq:d.eventSeq+1})}async createRecord(e,n,r,i){let s=e.contextId??fe(),a=this.#e.list(n).find(p=>p.contextId===s),c=z(`${n}\0${s}`),d=a?.workspaceRoot??await r.preparedExecution?.prepareWorkspace(c),u=await r.runtime.sessions.create({title:`A2A: ${r.agent.name}`,surface:"a2a",...r.execution?.profileId||r.agent.profileId?{profileId:r.execution?.profileId??r.agent.profileId}:{},...d?{projectPath:d,gitRoot:d}:r.agent.projectPath?{projectPath:r.agent.projectPath}:{}}),f=fe(),l=E(this.#n);return this.#e.save({taskId:f,contextId:s,principalKey:n,principalKeyScheme:Z,runtimeIdentity:r.runtime.identity.runtimeId,sessionId:u.id,...d?{workspaceRoot:d}:{},...r.preparedExecution?{executionPolicyRevision:r.preparedExecution.binding.executionPolicyRevision}:{},messageDigests:{[e.messageId]:Nt(e)},runIds:[],task:{id:f,contextId:s,status:{state:"TASK_STATE_SUBMITTED",timestamp:l},history:[{...e,taskId:f,contextId:s}]},history:[{...e,taskId:f,contextId:s}],createdAt:l,updatedAt:l,eventSeq:1,runtimeEventCount:0,runtimeEventBytes:0,...i?{acceptedOutputModes:i}:{}})}appendMessage(e,n,r){let i={...n,taskId:e.taskId,contextId:e.contextId};return this.#e.save({...e,messageDigests:{...e.messageDigests,[n.messageId]:r},history:[...e.history,i],task:{...e.task,history:[...e.history,i]},updatedAt:E(this.#n),eventSeq:e.eventSeq+1})}async startRun(e,n,r){let i=await this.inputsForMessage(e.taskId,n,r),s=r.preparedExecution;if(s&&e.executionPolicyRevision!==s.binding.executionPolicyRevision)throw new A(-32004,"A2A task execution binding revision changed.");let a=s?await s.start({sessionId:e.sessionId,inputs:i,principalKey:e.principalKey}):await r.runtime.runs.start({sessionId:e.sessionId,input:i,mode:"managed_task",permissionBroker:"runtime",...r.agent.runOptions?{options:r.agent.runOptions}:{},agentContext:{actorId:`a2a:${e.principalKey.slice(0,16)}`}}),c=this.#e.save({...e,runIds:[...e.runIds,a.runId],task:{...e.task,status:{state:"TASK_STATE_WORKING",timestamp:E(this.#n)}},updatedAt:E(this.#n),eventSeq:e.eventSeq+1});a.result.then(u=>this.finishRun(c.taskId,u,r)).catch(()=>{this.failTask(c.taskId,"Task execution failed.",r)});let d=this.attachRuntimeEvents(c,a.runId,r);return this.emit({type:"task.started",time:E(this.#n),taskId:c.taskId,contextId:c.contextId,runId:a.runId,outcome:"accepted"}),{record:c,runtimeEventsAttached:d}}async inputsForMessage(e,n,r){let i=[];for(let s of n.parts){if(s.text!==void 0){i.push({type:"text",text:s.text});continue}i.push(await this.materializePart(e,s,r))}return i}async materializePart(e,n,r){let i=n.mediaType??(n.data!==void 0?"application/json":"application/octet-stream"),s=n.data!==void 0?".json":".bin",a=this.#e.get(e),c=a?.workspaceRoot?I.join(a.workspaceRoot,"inbox",z(e)):I.join(I.resolve(r.dataDir),"attachments",z(e));W.mkdirSync(c,{recursive:!0,mode:448});let d=n.data!==void 0?Buffer.from(JSON.stringify(n.data),"utf8"):Buffer.from(n.raw??"","base64"),u=r.limits.maxWorkspaceBytesPerContext??1073741824;if(a?.workspaceRoot&&Kt(a.workspaceRoot)+d.byteLength>u)throw new A(-32004,"A2A context workspace size limit reached.");let f=n.filename?I.basename(n.filename).replace(/[^A-Za-z0-9._-]/g,"_"):`${fe()}${s}`,l=I.join(c,`${fe()}-${f}`);W.writeFileSync(l,d,{mode:384});let p=i.startsWith("image/")?"image":i.startsWith("video/")?"video":"file";return{type:"artifact_ref",artifactId:(await r.runtime.artifacts.create({kind:p,path:l,mediaType:i,mimeType:i,...n.filename?{name:I.basename(n.filename)}:{},source:"user-inline",description:"Inbound A2A message part"})).id,description:"Inbound A2A attachment"}}async attachRuntimeEvents(e,n,r){this.#t.get(e.taskId)?.close(),this.#t.delete(e.taskId);let i=[],s=!0,a=r.runtime.events.subscribe({sessionId:e.sessionId,runId:n},c=>{s?i.push(c):this.onRuntimeEvent(e.taskId,c,r)});this.#t.set(e.taskId,a);try{for(let c of i.splice(0))this.onRuntimeEvent(e.taskId,c,r);await this.applyCurrentRunState(e.taskId,n,r),s=!1;for(let c of i.splice(0))this.onRuntimeEvent(e.taskId,c,r)}catch(c){throw s=!1,this.#t.get(e.taskId)===a&&(a.close(),this.#t.delete(e.taskId)),c}}async applyCurrentRunState(e,n,r){if(this.#s)return;let i=this.#e.get(e);if(!i||O.has(i.task.status.state))return;let s=i.eventSeq,a=await r.runtime.runs.get(n);if(qt.has(a.phase))return;let c=(await r.runtime.userInputs.listPending({sessionId:i.sessionId})).find(h=>h.runId===n);if(i=this.#e.get(e),!i||O.has(i.task.status.state)||i.eventSeq!==s)return;let d=c!==void 0?"TASK_STATE_INPUT_REQUIRED":"TASK_STATE_WORKING",u=c===void 0?void 0:{requestId:c.id,revision:c.revision,runId:c.runId,kind:c.kind};if(i.task.status.state===d&&Ir(i.pendingUserInput,u))return;let f=c!==void 0?Mt(e,i.contextId,{kind:c.kind,options:c.options}):void 0,{pendingUserInput:l,...p}=i;this.#e.save({...p,task:{...i.task,status:{state:d,...f?{message:f}:{},timestamp:E(this.#n)}},...u!==void 0?{pendingUserInput:u}:{},updatedAt:E(this.#n),eventSeq:i.eventSeq+1})}onRuntimeEvent(e,n,r){if(!this.#r.has(e))try{this.consumeRuntimeEvent(e,n,r)}catch(i){throw this.#r.add(e),this.#t.get(e)?.close(),this.#t.delete(e),i}}consumeRuntimeEvent(e,n,r){if(this.#s)return;let i=this.#e.get(e);if(!i||O.has(i.task.status.state)||n.type!=="user_input.requested"&&n.type!=="user_input.resolved"&&n.type!=="run.started")return;let s=Buffer.byteLength(JSON.stringify(n)),a=i.runtimeEventCount+1,c=i.runtimeEventBytes+s;if(a>(r.limits.maxEventsPerTask??1e3)||c>(r.limits.maxEventBytesPerTask??16777216)){let h=i.runIds.at(-1);h&&r.runtime.runs.abort(h),this.failTask(e,"A2A task event quota exceeded.",r);return}let d=n.type==="user_input.requested"?"TASK_STATE_INPUT_REQUIRED":"TASK_STATE_WORKING",u=n.type==="user_input.requested"&&g(n.payload)&&typeof n.payload.kind=="string"?Mt(e,i.contextId,{kind:n.payload.kind,options:n.payload.options}):void 0,f=n.type==="user_input.requested"&&g(n.payload)&&typeof n.payload.id=="string"&&Number.isSafeInteger(n.payload.revision)&&typeof n.payload.runId=="string"&&typeof n.payload.kind=="string"?{requestId:n.payload.id,revision:n.payload.revision,runId:n.payload.runId,kind:n.payload.kind}:void 0,{pendingUserInput:l,...p}=i;this.#e.save({...p,task:{...i.task,status:{state:d,...u?{message:u}:{},timestamp:n.time}},...f?{pendingUserInput:f}:{},...n.type==="user_input.resolved"?{pendingUserInput:void 0}:{},updatedAt:n.time,eventSeq:i.eventSeq+1,runtimeEventCount:a,runtimeEventBytes:c})}finishRun(e,n,r=this.options){if(this.#s||this.#r.has(e))return;let i=this.#e.get(e);if(!i||O.has(i.task.status.state))return;let s=kr(n.phase),a=n.error?z(ge(n.error)).slice(0,16):void 0,c=n.error?`Task failed. Diagnostic ID: ${a}`:Pr(n.result?.lastText??"",i,r),d=c?Je(e,i.contextId,c):void 0,u=d?[...i.history,d]:i.history,l=[...c&&(i.acceptedOutputModes??r.agent.outputModes).includes("text/plain")?[{artifactId:`final-${e}`,name:"final-output",parts:[{text:c,mediaType:"text/plain"}]}]:[],...Cr(i,n,r)],{pendingUserInput:p,...h}=i;this.#e.save({...h,history:u,task:{...i.task,status:{state:s,...d?{message:d}:{},timestamp:E(this.#n)},...l.length>0?{artifacts:l}:{},history:u},updatedAt:E(this.#n),eventSeq:i.eventSeq+1}),this.#t.get(e)?.close(),this.#t.delete(e),this.pruneRetained(i.principalKey,r),this.emit({type:"task.finished",time:E(this.#n),taskId:e,contextId:i.contextId,outcome:s==="TASK_STATE_COMPLETED"?"completed":"failed"})}failTask(e,n,r=this.options){if(this.#s)return;let i=this.#e.get(e);if(!i||O.has(i.task.status.state))return;let s=Je(e,i.contextId,n),{pendingUserInput:a,...c}=i;this.#e.save({...c,task:{...i.task,status:{state:"TASK_STATE_FAILED",message:s,timestamp:E(this.#n)}},updatedAt:E(this.#n),eventSeq:i.eventSeq+1}),this.#t.get(e)?.close(),this.#t.delete(e),this.pruneRetained(i.principalKey,r)}pruneRetained(e,n){let r=n.limits.maxRetainedTasksPerPrincipal??n.limits.maxTasksPerPrincipal??100;this.#e.pruneTerminal(e,r)}async getTask(e,n){let r=Be(e),i=this.requireOwnedTask(r,n),s=je(e?.historyLength,"GetTask historyLength");return ze(i.task,i.history,s)}listTasks(e,n){let r=je(e?.historyLength,"ListTasks historyLength");if(e?.includeArtifacts!==void 0&&typeof e.includeArtifacts!="boolean")throw new A(-32602,"ListTasks includeArtifacts must be a boolean.");if(e?.contextId!==void 0&&typeof e.contextId!="string")throw new A(-32602,"ListTasks contextId must be a string.");if(e?.pageToken!==void 0&&typeof e.pageToken!="string")throw new A(-32602,"ListTasks pageToken must be a string.");if(e?.status!==void 0&&(typeof e.status!="string"||!lr.has(e.status)))throw new A(-32602,"ListTasks status is invalid.");let i=typeof e?.statusTimestampAfter=="string"?Date.parse(e.statusTimestampAfter):void 0;if(e?.statusTimestampAfter!==void 0&&!Number.isFinite(i))throw new A(-32602,"ListTasks statusTimestampAfter is invalid.");let s=this.#e.list(n).filter(l=>!(typeof e?.contextId=="string"&&l.contextId!==e.contextId||typeof e?.status=="string"&&l.task.status.state!==e.status||i!==void 0&&Date.parse(l.task.status.timestamp??l.updatedAt)<i));if(e?.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||e.pageSize<1||e.pageSize>100))throw new A(-32602,"ListTasks pageSize must be an integer from 1 to 100.");let a=typeof e?.pageSize=="number"?e.pageSize:50,c=Nr(typeof e?.pageToken=="string"?e.pageToken:void 0),d=c?s.filter(l=>$r(l,c)):s,u=d.slice(0,a),f=u.at(-1);return{tasks:u.map(l=>{let p=ze(l.task,l.history,r);return e?.includeArtifacts===!0?p:{...p,artifacts:void 0}}),nextPageToken:f&&u.length<d.length?qr(f):"",pageSize:a,totalSize:s.length}}async cancelTask(e,n,r){let i=Be(e),s=this.requireOwnedTask(i,n);if(O.has(s.task.status.state))throw new A(-32002,"Task is not cancelable.");let a=s.runIds.at(-1);a&&await r.runtime.runs.abort(a);let c=this.#e.save({...s,task:{...s.task,status:{state:"TASK_STATE_CANCELED",timestamp:E(this.#n)}},updatedAt:E(this.#n),eventSeq:s.eventSeq+1});return this.#t.get(i)?.close(),this.#t.delete(i),this.pruneRetained(s.principalKey,r),c.task}subscribeTask(e,n,r){let i=Be(n),s=this.requireOwnedTask(i,r);if(O.has(s.task.status.state))throw new A(-32004,"Cannot subscribe to a terminal task.");return this.streamTask(e,i,s.principalKey)}streamTask(e,n,r){let i=this.requireOwnedTask(n,r),s=new Map((i.task.artifacts??[]).map(l=>[l.artifactId,z(JSON.stringify(l))])),a=this.reserveStream(n),c=new TextEncoder,d,u=a,f=!1;try{let l=new ReadableStream({start:o(p=>{let h=o(k=>{f||(f=!0,u(),k?p.error(k):p.close())},"close");u=o(()=>{d?.(),d=void 0,this.#i.delete(h),a()},"cleanup");let w=o(k=>{let y=c.encode(this.sse(e,k));return p.desiredSize===null||p.desiredSize<y.byteLength?(h(new Error("A2A SSE subscriber exceeded its buffer budget.")),!1):(p.enqueue(y),!0)},"enqueue");if(this.#i.add(h),!!w({task:i.task})){if(O.has(i.task.status.state)){h();return}d=this.#e.subscribe(n,k=>{!this.enqueueArtifactUpdates(w,k.task,s)||!w({statusUpdate:{taskId:n,contextId:k.contextId,status:k.task.status}})||(O.has(k.task.status.state)||k.task.status.state==="TASK_STATE_INPUT_REQUIRED"||k.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&h()})}},"start"),cancel:o(()=>{f||(f=!0,u())},"cancel")},{highWaterMark:hr,size:o(p=>p.byteLength,"size")});return new Response(l,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}catch(l){throw u(),l}}enqueueArtifactUpdates(e,n,r){for(let i of n.artifacts??[]){let s=z(JSON.stringify(i));if(r.get(i.artifactId)!==s){if(!e({artifactUpdate:{taskId:n.id,contextId:n.contextId,artifact:i,append:!1,lastChunk:!0}}))return!1;r.set(i.artifactId,s)}}return!0}reserveStream(e){let n=this.#a.get(e)??0;if(n>=pr)throw new A(-32e3,"Task stream capacity reached.",429);if(this.#h>=fr)throw new A(-32e3,"Server stream capacity reached.",429);this.#h+=1,this.#a.set(e,n+1);let r=!1;return()=>{if(r)return;r=!0,this.#h-=1;let i=(this.#a.get(e)??1)-1;i===0?this.#a.delete(e):this.#a.set(e,i)}}sse(e,n){return`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:n})}
|
|
10
9
|
|
|
11
|
-
`}waitForTask(e,n){let r=this.#e.get(e);return r?M.has(r.task.status.state)||r.task.status.state==="TASK_STATE_INPUT_REQUIRED"||r.task.status.state==="TASK_STATE_AUTH_REQUIRED"?Promise.resolve(r):new Promise(i=>{let s=!1,a=o(()=>{},"unsubscribe"),c=o(f=>{s||(s=!0,clearTimeout(d),a(),i(f))},"finish"),d=setTimeout(()=>c(this.#e.get(e)??r),n);a=this.#e.subscribe(e,f=>{(M.has(f.task.status.state)||f.task.status.state==="TASK_STATE_INPUT_REQUIRED"||f.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&c(f)});let u=this.#e.get(e);u&&(M.has(u.task.status.state)||u.task.status.state==="TASK_STATE_INPUT_REQUIRED"||u.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&c(u)}):Promise.reject(new A(-32001,"Task not found."))}requireOwnedTask(e,n){let r=this.#e.get(e);if(!r||r.principalKey!==n)throw new A(-32001,"Task not found.");return r}async recover(){let e=this.options;for(let n of this.#e.all()){if(M.has(n.task.status.state))continue;let r=n.runIds.at(-1);if(!r||n.runtimeIdentity!==e.runtime.identity.runtimeId){this.failTask(n.taskId,"Runtime execution was interrupted before A2A recovery.",e);continue}try{let i=await e.runtime.runs.get(r);i.phase==="running"||i.phase==="queued"||i.phase==="waiting_permission"||i.phase==="waiting_user_input"?(await this.attachRuntimeEvents(n,r,e),e.runtime.runs.await(r).then(s=>this.finishRun(n.taskId,s,e)).catch(()=>{this.failTask(n.taskId,"Runtime execution failed during A2A recovery.",e)})):(await this.attachRuntimeEvents(n,r,e),this.finishRun(n.taskId,{runId:r,sessionId:n.sessionId,phase:i.phase},e))}catch(i){G({source:"a2a.server",level:"warn",message:"A2A task recovery could not reattach to its Runtime run.",detail:{taskId:n.taskId,error:i}}),this.failTask(n.taskId,"Runtime execution was unavailable during A2A recovery.",e)}}}emit(e){this.options.onEvent?.(e)}};function Ns(t){return new Ee(t)}o(Ns,"createKodaXA2AServer");async function qr(t){let e=t.execution;if(!e)throw new Error("A2A execution declaration is required for prepared serving.");let n=t.runtime.agents.execution;if(!n)throw new Error("local-agent-capability-unavailable: Runtime does not own an embedded execution binding service.");if(t.signal?.aborted)throw t.signal.reason??new Error("A2A preparation aborted.");let r=await n.openOwnerSession();try{let i=e.kind==="local-agent"?await n.bindLocal({ownerSessionId:r.ownerSessionId,ref:e.agentRef,profileId:e.profileId,workspace:e.workspace,toolPolicy:e.toolPolicy,workspaceByteLimit:t.limits.maxWorkspaceBytesPerContext}):await n.bindDefault({ownerSessionId:r.ownerSessionId,profileId:e.profileId,workspace:e.workspace,toolPolicy:e.toolPolicy,workspaceByteLimit:t.limits.maxWorkspaceBytesPerContext}),s=!1;return{service:n,ownerSessionId:r.ownerSessionId,binding:i,declaration:e,prepareWorkspace(a){return n.prepareWorkspace({ownerSessionId:r.ownerSessionId,bindingId:i.bindingId,contextKey:a})},start(a){let c={ownerSessionId:r.ownerSessionId,bindingId:i.bindingId,expectedExecutionPolicyRevision:i.executionPolicyRevision,sessionId:a.sessionId,input:a.inputs,permissionBroker:"runtime",agentContext:{actorId:`a2a:${a.principalKey.slice(0,16)}`}};if(e.kind==="local-agent"){let d="configurationRevision"in i&&typeof i.configurationRevision=="string"?i.configurationRevision:void 0;if(!d)throw new Error("Prepared local-Agent binding is missing its revision.");return n.startLocal({...c,expectedConfigurationRevision:d})}return n.startDefault(c)},async close(){s||(s=!0,await n.closeOwnerSession(r.ownerSessionId))}}}catch(i){throw await n.closeOwnerSession(r.ownerSessionId),i}}o(qr,"prepareExecution");async function $s(t){let e=await qr(t);try{let n=new Ee({...t,preparedExecution:e});return await n.whenReady(),n}catch(n){throw await e.close(),n}}o($s,"prepareKodaXA2AServer");import{createPublicKey as Nr}from"node:crypto";import*as ee from"oauth4webapi";var $r=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"],q=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="OAuthJwksUnavailableError"}cause;static{o(this,"OAuthJwksUnavailableError")}};function Kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(Kt,"isRecord");function Dr(t){for(let e of["kid","alg","use"])if(t[e]!==void 0&&typeof t[e]!="string")throw new q(`OAuth JWKS key field ${e} must be a string.`);if(t.key_ops!==void 0&&(!Array.isArray(t.key_ops)||!t.key_ops.every(e=>typeof e=="string")))throw new q("OAuth JWKS key_ops must be an array of strings.");if(typeof t.kty!="string"||t.kty.length===0)throw new q("OAuth JWKS key kty must be a non-empty string.");if(["RSA","EC","OKP"].includes(t.kty))try{Nr({key:t,format:"jwk"})}catch(e){throw new q("OAuth JWKS endpoint returned an invalid public key.",e)}}o(Dr,"assertPublicJwk");function Kr(t,e){if(t.status!==200)throw new q("OAuth JWKS endpoint returned an unexpected status.");let n=t.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();if(n!=="application/json"&&n!=="application/jwk-set+json")throw new q("OAuth JWKS endpoint returned an unsupported media type.");let r;try{r=JSON.parse(X(e))}catch(i){throw new q("OAuth JWKS endpoint returned malformed JSON.",i)}if(!Kt(r)||!Array.isArray(r.keys)||!r.keys.every(Kt))throw new q("OAuth JWKS endpoint returned an invalid key set.");for(let i of r.keys)Dr(i)}o(Kr,"assertJwksResponse");function jr(t){let e=new Set,n=t;for(;n!=null&&!e.has(n);){if(n instanceof q)return!0;if(e.add(n),typeof n!="object"||!("cause"in n))return!1;n=n.cause}return!1}o(jr,"isJwksUnavailable");function Br(t){return{allowedOrigins:[t.origin],allowPrivateAddresses:ye(t.hostname),requestTimeoutMs:1e4,maxResponseBytes:1048576,maxRedirects:0}}o(Br,"jwksNetworkPolicy");function Hr(t,e){return async(n,r)=>{try{let i=await V(new URL(n),{...r,redirect:"manual"},t,e);return Kr(i.response,i.body),new Response(i.body,{status:i.response.status,statusText:i.response.statusText,headers:i.response.headers})}catch(i){throw i instanceof q?i:new q("OAuth JWKS endpoint is unavailable.",i)}}}o(Hr,"boundedOAuthFetch");function zr(t){if(t===void 0)return[];if(typeof t!="string")throw new Error("OAuth access-token scope claim must be a string.");return it(t,"OAuth access-token scope claim")}o(zr,"scopesFromClaim");function jt(t,e){if(t.type!=="oauth2-jwt")throw new Error("A2A authentication.type must be oauth2-jwt.");let n=O(t.scheme,"A2A authentication.scheme"),r=O(t.audience,"A2A authentication.audience"),i=ie(t.requiredScopes,"A2A authentication.requiredScopes"),s=F(t.issuer,"OAuth issuer"),a=$(t.jwksUrl,"OAuth JWKS endpoint"),c=$(t.tokenUrl,"OAuth token endpoint"),d=t.metadataUrl===void 0?void 0:$(t.metadataUrl,"OAuth metadata endpoint"),u={issuer:s,jwks_uri:a.href},f={},l=Hr(Br(a),e),p=Object.fromEntries(i.map(h=>[h,"Required to invoke this Agent."]));return{securityRealm:`oauth2-jwt:${s}`,securitySchemes:{[n]:{oauth2SecurityScheme:{flows:{clientCredentials:{tokenUrl:c.href,scopes:p}},...d?{oauth2MetadataUrl:d.href}:{}}}},securityRequirements:[{schemes:{[n]:{list:i}}}],async authenticate(h){if(!h.headers.get("authorization"))return null;let k,y;try{k=await ee.validateJwtAccessToken(u,h,r,{signingAlgorithms:$r,[ee.jwksCache]:f,[ee.customFetch]:l,...a.protocol==="http:"&&ye(a.hostname)?{[ee.allowInsecureRequests]:!0}:{}});let m=k.scope;y=zr(m)}catch(m){throw jr(m)?new A(-32603,"OAuth token verification is temporarily unavailable.",503):new A(-32600,"Invalid OAuth access token.",401,void 0,{"www-authenticate":'Bearer error="invalid_token"'})}if(i.filter(m=>!y.includes(m)).length>0)throw new A(-32600,"Insufficient OAuth scope.",403,void 0,{"www-authenticate":`Bearer error="insufficient_scope", scope="${i.join(" ")}"`});return{subject:k.sub,scopes:y}}}}o(jt,"createOAuth2JwtA2AAuthentication");import Bt from"node:os";import Ht from"node:path";function Fr(t){return t==="~"?Bt.homedir():t.startsWith("~/")||t.startsWith("~\\")?Ht.join(Bt.homedir(),t.slice(2)):Ht.resolve(t)}o(Fr,"resolveDataDir");function Jr(t,e){if(typeof t.subject!="string")throw new Error(`A2A legacy task owner mapping ${e} subject must be a string.`);if(t.tenant!==void 0&&typeof t.tenant!="string")throw new Error(`A2A legacy task owner mapping ${e} tenant must be a string.`);if(typeof t.securityRealm!="string"||t.securityRealm.trim().length===0)throw new Error(`A2A legacy task owner mapping ${e} securityRealm must be a non-empty stable string.`)}o(Jr,"validateMapping");function Qs(t){if(typeof t.dataDir!="string"||t.dataDir.trim().length===0)throw new Error("A2A legacy task owner migration dataDir must be a non-empty path.");if(!Array.isArray(t.mappings)||t.mappings.length===0)throw new Error("A2A legacy task owner migration requires at least one explicit mapping.");if(typeof t.apply!="boolean")throw new Error("A2A legacy task owner migration apply must be a boolean.");let e=new Map,n=new Set;t.mappings.forEach((s,a)=>{Jr(s,a);let c=vt(s),d=Te(s),u=e.get(c);if(u!==void 0&&u!==d)throw new Error("A2A legacy task owner mappings are ambiguous across security realms.");e.set(c,d),n.add(d)});let r=Fr(t.dataDir),i=new oe(r);try{let s=i.migrateUnversionedPrincipalKeys({legacyToCurrent:e,currentKeys:n,apply:t.apply});return{dataDir:r,applied:t.apply,...s}}finally{i.close()}}o(Qs,"migrateA2ALegacyTaskOwners");import{createHash as Wr}from"node:crypto";import{existsSync as Gr,readFileSync as Vr}from"node:fs";import Ie from"node:path";import{isDeepStrictEqual as Je}from"node:util";var Ft={maxRequestBytes:33554432,maxPartBytes:16777216,maxConcurrentTasks:4,maxTaskWaitMs:3e4,maxActiveTasksPerPrincipal:4,maxRetainedTasksPerPrincipal:100,maxEventsPerTask:1e3,maxEventBytesPerTask:16777216,maxWorkspaceBytesPerContext:1073741824},zt=Object.keys(Ft),xe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Xr=/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/,Qr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Zr(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Zr,"isExactLoopback");function P(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object.`);return t}o(P,"record");function I(t,e,n){let r=new Set(e),i=Object.keys(t).find(s=>!r.has(s));if(i!==void 0)throw new Error(`${n} has unknown field "${i}".`)}o(I,"noUnknown");function v(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t.trim()}o(v,"text");function ae(t,e,n=!1){if(!Array.isArray(t)||!n&&t.length===0)throw new Error(`${e} must be ${n?"an":"a non-empty"} array of strings.`);let r=t.map((i,s)=>v(i,`${e}[${s}]`));if(new Set(r).size!==r.length)throw new Error(`${e} contains duplicates.`);return r}o(ae,"stringList");function We(t,e,n=!0){let r=ae(t,e,n);if(r.some(i=>i.includes("*")))throw new Error(`${e} does not accept wildcard authority.`);return r}o(We,"exactNames");function Yr(t,e){return We(t,e).map(n=>{if(!Xr.test(n))throw new Error(`${e} entries must be valid host tool names.`);return n})}o(Yr,"hostToolNames");function Jt(t,e){let n=P(t,e),r={};for(let[i,s]of Object.entries(n)){if(!xe.test(i)||i.includes("*"))throw new Error(`${e} keys must be exact names without wildcards.`);r[i]=We(s,`${e}.${i}`,!1)}return r}o(Jt,"namedExactLists");function Wt(t,e){let n=v(t,e);if(!xe.test(n))throw new Error(`${e} is invalid.`);return n}o(Wt,"parseSchemeName");function Gt(t,e){return F(t,e)}o(Gt,"parseIssuer");function Vt(t,e){let n=ae(t,e,!0);for(let r of n)re(r,e);return n}o(Vt,"oauthScopeList");function ei(t,e){return ne(t,e)}o(ei,"parseResource");function be(t,e){return $(t,e).href}o(be,"parseOAuthEndpoint");function ti(t,e){let n=P(t,e);if(I(n,["type","scheme","issuer","tokenUrl","clientId","clientSecretEnv","scopes","resource","clientAuthentication"],e),n.type!=="oauth2-client-credentials")throw new Error(`${e}.type must be oauth2-client-credentials.`);let r=n.clientAuthentication??"client-secret-basic";if(!["client-secret-basic","client-secret-post"].includes(String(r)))throw new Error(`${e}.clientAuthentication is invalid.`);return{type:"oauth2-client-credentials",scheme:Wt(n.scheme,`${e}.scheme`),issuer:Gt(n.issuer,`${e}.issuer`),tokenUrl:be(n.tokenUrl,`${e}.tokenUrl`),clientId:v(n.clientId,`${e}.clientId`),clientSecretEnv:Ge(n.clientSecretEnv,`${e}.clientSecretEnv`),scopes:Vt(n.scopes,`${e}.scopes`),...n.resource===void 0?{}:{resource:ei(n.resource,`${e}.resource`)},clientAuthentication:r}}o(ti,"parseOutboundAuthentication");function ni(t,e,n){let r=P(t,e);I(r,n===1?["cardUrl","credentialEnv","effect"]:["cardUrl","enabled","credentialEnv","authentication","network","effect"],e);let i=r.network===void 0?void 0:ri(r.network,`${e}.network`),s=Xt(r.cardUrl,`${e}.cardUrl`,i?.allowInsecureHttp===!0),a=r.effect;if(!["none","read","write","unknown"].includes(String(a)))throw new Error(`${e}.effect is invalid.`);let c=r.credentialEnv===void 0?void 0:Ge(r.credentialEnv,`${e}.credentialEnv`);if(c&&r.authentication!==void 0)throw new Error(`${e}.credentialEnv and ${e}.authentication are mutually exclusive.`);if(r.enabled!==void 0&&typeof r.enabled!="boolean")throw new Error(`${e}.enabled must be a boolean.`);return{cardUrl:s,enabled:r.enabled??!0,...c?{credentialEnv:c}:{},...r.authentication===void 0?{}:{authentication:ti(r.authentication,`${e}.authentication`)},...i===void 0?{}:{network:i},effect:a}}o(ni,"parseOutboundAgent");function ri(t,e){let n=P(t,e);if(I(n,["allowPrivateAddresses","allowInsecureHttp"],e),typeof n.allowPrivateAddresses!="boolean")throw new Error(`${e}.allowPrivateAddresses must be a boolean.`);if(typeof n.allowInsecureHttp!="boolean")throw new Error(`${e}.allowInsecureHttp must be a boolean.`);return{allowPrivateAddresses:n.allowPrivateAddresses,allowInsecureHttp:n.allowInsecureHttp}}o(ri,"parseOutboundNetwork");function Xt(t,e,n){let r=v(t,e),i;try{i=new URL(r)}catch(a){throw new Error(`${e} must be an absolute HTTP URL.`,{cause:a})}if(i.username||i.password)throw new Error(`${e} must not contain embedded credentials.`);if(i.hash)throw new Error(`${e} must not contain a fragment.`);let s=Zr(i.hostname);if(i.protocol!=="https:"&&!(i.protocol==="http:"&&(s||n)))throw new Error(`${e} must use HTTPS, exact loopback HTTP, or explicitly authorized plaintext HTTP.`);return i.toString()}o(Xt,"parseHttpUrl");function Ge(t,e){let n=v(t,e);if(!Qr.test(n))throw new Error(`${e} must be an environment variable name.`);return n}o(Ge,"parseEnvironmentName");function ii(t){if(t===void 0)return{mode:"managed"};let e=P(t,"A2A server execution.workspace");if(e.mode==="managed")return I(e,["mode"],"A2A server execution.workspace"),{mode:"managed"};if(e.mode!=="fixed")throw new Error("A2A server execution.workspace.mode is invalid.");I(e,["mode","root"],"A2A server execution.workspace");let n=v(e.root,"A2A server execution.workspace.root");if(!Ie.isAbsolute(n))throw new Error("Fixed A2A workspace root must be absolute.");return{mode:"fixed",root:Ie.resolve(n)}}o(ii,"parseWorkspace");function si(t){return{workspace:t.mode==="managed"?"write":"read",process:"deny",network:{mode:"deny"},tools:[],mcp:{},skillScripts:{},subagents:"deny"}}o(si,"defaultToolPolicy");function oi(t){let e=P(t,"A2A toolPolicy.network");if(e.mode==="deny")return I(e,["mode"],"A2A toolPolicy.network"),{mode:"deny"};if(e.mode!=="allowlist")throw new Error("A2A toolPolicy.network.mode is invalid.");I(e,["mode","origins"],"A2A toolPolicy.network");let n=ae(e.origins,"A2A toolPolicy.network.origins").map(r=>{let i;try{i=new URL(r)}catch(s){throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.",{cause:s})}if(!["http:","https:"].includes(i.protocol)||i.origin==="null")throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.");return i.origin});if(new Set(n).size!==n.length)throw new Error("A2A toolPolicy.network.origins contains duplicates after normalization.");return{mode:"allowlist",origins:n}}o(oi,"parseNetworkPolicy");function ai(t){let e=Jt(t,"A2A toolPolicy.skillScripts");for(let[n,r]of Object.entries(e))e[n]=r.map(i=>{if(i.includes("\\")||Ie.posix.isAbsolute(i))throw new Error("A2A skillScripts paths must use relative POSIX scripts/... paths.");let s=Ie.posix.normalize(i);if(!s.startsWith("scripts/")||s.includes("../"))throw new Error("A2A skillScripts paths must remain below the Skill scripts directory.");return s});return e}o(ai,"parseSkillScripts");function ci(t,e){if(t===void 0)return si(e);let n=P(t,"A2A server execution.toolPolicy"),r=["workspace","process","network","tools","mcp","skillScripts","subagents"];if(I(n,[...r,"hostTools"],"A2A server execution.toolPolicy"),r.some(a=>n[a]===void 0))throw new Error("A2A server execution.toolPolicy must be a complete object when present.");if(!["none","read","write"].includes(String(n.workspace)))throw new Error("A2A toolPolicy.workspace is invalid.");if(!["deny","isolated"].includes(String(n.process)))throw new Error("A2A toolPolicy.process is invalid.");if(!["deny","inherit"].includes(String(n.subagents)))throw new Error("A2A toolPolicy.subagents is invalid.");let i=ai(n.skillScripts),s=Object.values(i).reduce((a,c)=>a+c.length,0);if(n.process==="deny"&&s>0)throw new Error("A2A toolPolicy process deny requires empty skillScripts.");if(n.process==="isolated"&&s===0)throw new Error("A2A toolPolicy process isolated requires non-empty skillScripts.");return{workspace:n.workspace,process:n.process,network:oi(n.network),tools:We(n.tools,"A2A toolPolicy.tools"),mcp:Jt(n.mcp,"A2A toolPolicy.mcp"),skillScripts:i,subagents:n.subagents,...n.hostTools===void 0?{}:{hostTools:Yr(n.hostTools,"A2A toolPolicy.hostTools")}}}o(ci,"parseToolPolicy");function di(t){let e=P(t,"A2A server execution"),n=ii(e.workspace),r=ci(e.toolPolicy,n),i=e.profileId===void 0?void 0:v(e.profileId,"A2A server execution.profileId");if(e.kind==="runtime-default")return I(e,["kind","workspace","toolPolicy","profileId"],"A2A server execution"),{kind:"runtime-default",workspace:n,toolPolicy:r,...i?{profileId:i}:{}};if(e.kind!=="local-agent")throw new Error("A2A server execution.kind is invalid.");I(e,["kind","agentRef","workspace","toolPolicy","profileId"],"A2A server execution");let s=P(e.agentRef,"A2A server execution.agentRef");if(I(s,["source","name"],"A2A server execution.agentRef"),s.source!=="markdown:user")throw new Error("A2A local Agent source must be markdown:user.");let a=v(s.name,"A2A server execution.agentRef.name");if(!xe.test(a))throw new Error("A2A local Agent name is invalid.");return{kind:"local-agent",agentRef:{source:"markdown:user",name:a},workspace:n,toolPolicy:r,...i?{profileId:i}:{}}}o(di,"parseExecution");function ui(t,e){let n=`A2A server published.skills[${e}]`,r=P(t,n);return I(r,["id","name","description","tags"],n),{id:v(r.id,`${n}.id`),name:v(r.name,`${n}.name`),description:v(r.description,`${n}.description`),tags:ae(r.tags,`${n}.tags`,!0)}}o(ui,"parsePublishedSkill");function li(t){let e=P(t,"A2A server published");if(I(e,["name","description","version","skills","inputModes","outputModes"],"A2A server published"),!Array.isArray(e.skills))throw new Error("A2A server published.skills must be an array.");let n=e.skills.map(ui),r=n.map(i=>i.id);if(new Set(r).size!==r.length)throw new Error("A2A published Skill ids must be unique.");return{name:v(e.name,"A2A server published.name"),description:v(e.description,"A2A server published.description"),version:v(e.version,"A2A server published.version"),skills:n,inputModes:ae(e.inputModes,"A2A server published.inputModes"),outputModes:ae(e.outputModes,"A2A server published.outputModes")}}o(li,"parsePublished");function Ai(t,e){let n=P(t,"A2A server authentication");if(n.type==="bearer-env")return I(n,["type","tokenEnv","principalId"],"A2A server authentication"),{type:"bearer-env",tokenEnv:Ge(n.tokenEnv,"A2A server authentication.tokenEnv"),principalId:v(n.principalId,"A2A server authentication.principalId")};if(e===1)throw new Error("A2A oauth2-jwt authentication requires integration config version 2.");if(n.type!=="oauth2-jwt")throw new Error("A2A authentication type must be bearer-env or oauth2-jwt.");return I(n,["type","scheme","issuer","audience","jwksUrl","tokenUrl","metadataUrl","requiredScopes"],"A2A server authentication"),{type:"oauth2-jwt",scheme:Wt(n.scheme,"A2A server authentication.scheme"),issuer:Gt(n.issuer,"A2A server authentication.issuer"),audience:v(n.audience,"A2A server authentication.audience"),jwksUrl:be(n.jwksUrl,"A2A server authentication.jwksUrl"),tokenUrl:be(n.tokenUrl,"A2A server authentication.tokenUrl"),...n.metadataUrl===void 0?{}:{metadataUrl:be(n.metadataUrl,"A2A server authentication.metadataUrl")},requiredScopes:Vt(n.requiredScopes,"A2A server authentication.requiredScopes")}}o(Ai,"parseAuthentication");function pi(t,e){if(!Number.isSafeInteger(t)||Number(t)<=0)throw new Error(`${e} must be a positive safe integer.`);return Number(t)}o(pi,"positiveInteger");function fi(t,e){let n=t===void 0?{}:P(t,"A2A server limits");I(n,zt,"A2A server limits");let r=Object.fromEntries(zt.map(s=>[s,n[s]===void 0?Ft[s]:pi(n[s],`A2A server limits.${s}`)]));if(r.maxPartBytes>r.maxRequestBytes)throw new Error("A2A server limits.maxPartBytes must not exceed maxRequestBytes.");let i=e.workspace.mode==="fixed"&&e.toolPolicy.workspace==="write";if(i&&n.maxConcurrentTasks===void 0)return{...r,maxConcurrentTasks:1};if(i&&r.maxConcurrentTasks!==1)throw new Error("A2A fixed writable workspace requires maxConcurrentTasks 1.");return r}o(fi,"parseLimits");function hi(t,e){let n=P(t,"A2A server");I(n,["execution","published","publicBaseUrl","authentication","limits","dataDir"],"A2A server");let r=di(n.execution),i=n.publicBaseUrl===void 0?void 0:Xt(n.publicBaseUrl,"A2A server.publicBaseUrl",!0);return{execution:r,published:li(n.published),...i?{publicBaseUrl:i}:{},authentication:Ai(n.authentication,e),limits:fi(n.limits,r),dataDir:v(n.dataDir,"A2A server.dataDir")}}o(hi,"parseServer");function Ce(t){let e=P(t,"A2A integration config");if(I(e,["version","agents","server"],"A2A integration config"),e.version!==1&&e.version!==2)throw new Error("A2A integration config version must be 1 or 2.");let n=e.version,r=P(e.agents,"A2A integration config agents"),i={};for(let[s,a]of Object.entries(r)){if(!xe.test(s))throw new Error(`A2A outbound Agent name "${s}" is invalid.`);i[s]=ni(a,`A2A outbound Agent "${s}"`,n)}return{version:2,agents:i,...e.server===void 0?{}:{server:hi(e.server,n)}}}o(Ce,"parseA2AIntegrationDocument");function gi(t){return Wr("sha256").update(t).digest("hex")}o(gi,"hash");function Qt(t){let e=nt("a2a",t),n=Gr(e),r=n?Vr(e,"utf8"):JSON.stringify({version:2,agents:{}}),i;try{i=JSON.parse(r)}catch(u){throw new Error("Invalid A2A integration JSON.",{cause:u})}let s=Ce(i),a=P(i,"A2A integration config");if(a.version!==1&&a.version!==2)throw new Error("A2A integration config version must be 1 or 2.");let c=a.version;return{snapshot:{domain:"a2a",source:n?"user":"default",path:e,revision:gi(r),document:s,loadedAt:new Date().toISOString()},sourceVersion:c,nonEmptyLegacy:c===1&&(Object.keys(s.agents).length>0||s.server!==void 0)}}o(Qt,"loadA2AIntegration");function Ve(t){return Qt(t).snapshot}o(Ve,"readA2AIntegration");function mi(t){let e=Qt(t);return{sourceVersion:e.sourceVersion,snapshot:e.snapshot}}o(mi,"inspectA2AIntegration");function yi(t,e){if(Je(t,e))return{kind:"none",fields:[]};if(t===void 0||e===void 0)return{kind:"restart-required",fields:["server"]};let n=["execution","dataDir"].filter(i=>!Je(t[i],e[i])),r=["published","publicBaseUrl","authentication","limits"].filter(i=>!Je(t[i],e[i]));return n.length>0?{kind:"restart-required",fields:[...n,...r]}:{kind:"hot",fields:r}}o(yi,"classifyA2AServerChange");import{timingSafeEqual as wi}from"node:crypto";import Zt from"node:os";import Yt from"node:path";function ki(t){return t==="~"?Zt.homedir():t.startsWith("~/")||t.startsWith("~\\")?Yt.join(Zt.homedir(),t.slice(2)):Yt.resolve(t)}o(ki,"expandHome");function Si(t){let e=t.headers.get("authorization");return(e?/^Bearer ([^\s]+)$/i.exec(e):null)?.[1]}o(Si,"bearerToken");function Ri(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.byteLength===r.byteLength&&wi(n,r)}o(Ri,"equalSecret");function Ti(t,e=process.env){let n=e[t.tokenEnv];if(!n)throw new Error(`A2A bearer token environment variable is unset: ${t.tokenEnv}.`);return{securityRealm:`bearer-env:${t.tokenEnv}`,securitySchemes:{bearer:{httpAuthSecurityScheme:{scheme:"Bearer",bearerFormat:"opaque"}}},securityRequirements:[{schemes:{bearer:{list:[]}}}],async authenticate(r){let i=Si(r);return i&&Ri(n,i)?{subject:t.principalId,scopes:["a2a:invoke"]}:null}}}o(Ti,"createBearerEnvA2AAuthentication");function en(t,e){return t.type==="bearer-env"?Ti(t,e):jt(t)}o(en,"createConfiguredAuthentication");function tn(t,e){return{name:t.published.name,description:t.published.description,version:t.published.version,publicBaseUrl:t.publicBaseUrl??e,skills:t.published.skills,inputModes:t.published.inputModes,outputModes:t.published.outputModes,...t.execution.profileId?{profileId:t.execution.profileId}:{}}}o(tn,"publishedAgent");function nn(){return Promise.resolve(!0)}o(nn,"authorization");function fo(t){return{runtime:t.runtime,agent:tn(t.config,t.listenBaseUrl),execution:t.config.execution,dataDir:ki(t.config.dataDir),limits:t.config.limits,authentication:en(t.config.authentication,t.env),authorize:nn}}o(fo,"createA2AServerOptionsFromConfig");function ho(t){return{agent:tn(t.config,t.listenBaseUrl),limits:t.config.limits,authentication:en(t.config.authentication,t.env),authorize:nn}}o(ho,"createA2AServerHotOptions");import{createHash as Ei}from"node:crypto";import{isDeepStrictEqual as bi}from"node:util";var N="kodax-a2a-runtime-config-v1",Qe="kodax-a2a-config-v1:";function Ii(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Ii,"isExactLoopback");var ve={allowPrivateAddresses:!1,allowInsecureHttp:!1};function Xe(t,e=ve){let n=t.map(r=>Ii(r.hostname));if(n.some(Boolean)&&!n.every(Boolean))throw new Error("Configured A2A Agent and OAuth endpoints must not mix loopback and public origins.");return{allowedOrigins:[...new Set(t.map(r=>r.origin))],allowPrivateAddresses:e.allowPrivateAddresses||n.every(Boolean),allowInsecureHttp:e.allowInsecureHttp,requestTimeoutMs:1e4,maxResponseBytes:1e6,maxRedirects:3}}o(Xe,"networkPolicy");var xi=32*1024*1024;function Ci(t){let e=t.executorConfig?.interfaceUrl;if(typeof e!="string")throw new Error("Configured A2A registration has no interface URL.");return new URL(e)}o(Ci,"registrationUrl");function vi(t){let e=[Ci(t)],n=t.executorConfig?.authentication;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r=n.tokenUrl;typeof r=="string"&&e.push(new URL(r))}return e}o(vi,"registrationNetworkUrls");function Pi(t){let e=t.executorConfig?.network;if(e===null||typeof e!="object"||Array.isArray(e))return ve;let n=e;return{allowPrivateAddresses:n.allowPrivateAddresses===!0,allowInsecureHttp:n.allowInsecureHttp===!0}}o(Pi,"registrationNetworkAccess");function Oi(){let t=o(e=>{if(!e.startsWith("env:")||e.length===4)throw new Error("Configured A2A credentials must use an environment reference.");return e.slice(4)},"environmentName");return{isAvailable(e){let n=process.env[t(e)];return typeof n=="string"&&n.length>0},async withCredential(e,n){let r=process.env[t(e)];if(!r)throw new Error("Configured A2A credential is unavailable.");return n(r)}}}o(Oi,"environmentCredentialBroker");var _i=o(({artifact:t})=>{if(t.provenance!=="a2a"||!t.uri)return{allowed:!1,reason:"Configured A2A artifacts require an A2A provenance URI."};let e;try{e=new URL(t.uri).protocol}catch{return{allowed:!1,reason:"Configured A2A artifact URI is invalid."}}return e!=="data:"&&e!=="http:"&&e!=="https:"?{allowed:!1,reason:`Configured A2A artifact URI scheme is not allowed: ${e}`}:{allowed:!0}},"configuredA2AArtifactPolicy");function Ui(t,e){return{agentId:`external:${t}`,agentCardUrl:e.cardUrl,...e.credentialEnv?{credentialRef:`env:${e.credentialEnv}`}:{},...e.authentication?{authentication:{type:"oauth2-client-credentials",scheme:e.authentication.scheme,issuer:e.authentication.issuer,tokenUrl:e.authentication.tokenUrl,clientId:e.authentication.clientId,clientSecretRef:`env:${e.authentication.clientSecretEnv}`,scopes:e.authentication.scopes,...e.authentication.resource?{resource:e.authentication.resource}:{},clientAuthentication:e.authentication.clientAuthentication}}:{},effects:{remote:e.effect}}}o(Ui,"registrationInput");function Mi(t){let e=t.authentication?[t.authentication.type,t.authentication.scheme,t.authentication.issuer,t.authentication.tokenUrl,t.authentication.clientId,t.authentication.clientSecretEnv,t.authentication.scopes,t.authentication.resource??null,t.authentication.clientAuthentication]:null;return Ei("sha256").update(JSON.stringify([t.cardUrl,t.credentialEnv??null,e,t.network??ve,t.effect])).digest("hex")}o(Mi,"configFingerprint");function rn(t){if(!t.startsWith(Qe))return;let e=Qe.length,n=t.indexOf(":",e);if(n<0)return;let r=t.slice(e,n),i=t.slice(n+1);if(!(!/^[a-f0-9]{64}$/.test(r)||i.length===0))return{fingerprint:r,registrationRevision:i}}o(rn,"parseConfiguredRegistrationRevision");function Li(t,e){let n=rn(e)?.registrationRevision??e;return`${Qe}${t}:${n}`}o(Li,"configuredRegistrationRevision");function qi(t,e,n){return{...t,executorConfig:{...t.executorConfig,network:{...n.network??ve}},managementOwner:N,configurationRevision:Li(e,t.configurationRevision)}}o(qi,"markConfiguredRegistration");function Eo(t){return{runtimeOptions:{factories:[xt(n=>({networkPolicy:Xe(vi(n),Pi(n)),maxTaskResponseBytes:xi,pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}))],policy:o(()=>({allowed:!0}),"policy"),credentialBroker:Oi(),artifactPolicy:_i,defaultContext:{actorId:N}},async start(n){let r=new Map,i=new Map,s=o(l=>{try{t.onEvent?.(l)}catch(p){G({source:"a2a.runtime-config",level:"warn",message:"A2A Runtime event observer failed.",detail:p})}},"notify"),a=o((l,p,h)=>{G({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${l}" reconciliation failed; ${p}.`,detail:h}),s(`A2A Agent "${l}" could not be reconciled; ${p}.`)},"reportEntryFailure"),c=new rt({domain:"a2a",configHome:t.configHome,validate:Ce,read:o(()=>Ve(t.configHome),"read"),coldStartDefault:{version:2,agents:{}}}),d=o(async(l,p)=>{if(p.managementOwner!==void 0&&p.managementOwner!==N)throw new Error(`A2A registration "${l}" is owned by ${p.managementOwner}.`);let h=r.get(l),w=await n.admin.agentRegistrations.setEnabled(l,!1,{expectedConfigurationRevision:p.configurationRevision,expectedManagementOwner:p.managementOwner??null,...p.managementOwner===void 0?{claimOwner:N}:{}});if(!w){r.delete(l),s(`A2A registration "${l}" changed concurrently; disable was deferred.`);return}return h?.configurationRevision===p.configurationRevision&&h.endpointIdentityHash===p.endpointIdentityHash?r.set(l,{...h,managementOwner:N,enabled:!1}):r.delete(l),w},"persistDisabledFence"),u=o(async(l,p,h,w,k,y)=>{let T=`external:${l}`;try{let m=new URL(p.cardUrl),S=[m,...p.authentication?[new URL(p.authentication.tokenUrl)]:[]];Xe(S,p.network);let L=await bt(Ui(l,p),{networkPolicy:Xe([m],p.network),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}),R=qi(L.registration,h,p);await n.admin.agentRegistrations.upsert(R,{expectedConfigurationRevision:k,expectedManagementOwner:y}),r.set(T,R),i.set(T,p)}catch(m){let S=w?"the live registration was left unchanged":"the activation was not applied";G({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${l}" refresh failed; ${S}.`,detail:m}),s(`A2A Agent "${l}" could not be refreshed; ${S}.`)}},"refreshConfiguredAgent"),f=o(async l=>{let p=await n.admin.agentRegistrations.list(),h=new Map(p.map(y=>[y.agentId,y])),w=new Set(Object.keys(l.agents).map(y=>`external:${y}`));for(let[y,T]of h){if(w.has(y)||T.managementOwner!==N)continue;let m;try{m=await n.admin.agentRegistrations.remove(y,{expectedConfigurationRevision:T.configurationRevision,expectedManagementOwner:N})}catch(S){a(y,"removal was not applied",S);continue}if(!m){r.delete(y),s(`A2A registration "${y}" changed concurrently; removal was deferred.`);continue}r.delete(y),i.delete(y),h.delete(y)}for(let[y,T]of Object.entries(l.agents)){if(T.enabled)continue;let m=`external:${y}`,S=h.get(m);if(S?.managementOwner!==void 0&&S.managementOwner!==N){a(m,"the registration belongs to another manager",new Error(`A2A registration "${m}" is owned by ${S.managementOwner}.`));continue}if(S&&(S.enabled||S.managementOwner!==N))try{let L=await d(m,S);L?h.set(m,L):h.delete(m)}catch(L){a(m,"the disabled fence was not applied",L);continue}i.set(m,T)}let k=[];for(let[y,T]of Object.entries(l.agents)){if(!T.enabled)continue;let m=`external:${y}`,S=Mi(T),L=i.get(m),R=h.get(m);if(R?.managementOwner!==void 0&&R.managementOwner!==N){a(m,"the registration belongs to another manager",new Error(`A2A registration "${m}" is owned by ${R.managementOwner}.`));continue}let _=R?rn(R.configurationRevision):void 0,j=r.get(m),Ze=j!==void 0&&R!==void 0&&j.configurationRevision===R.configurationRevision&&j.endpointIdentityHash===R.endpointIdentityHash;if(R?.enabled&&R.managementOwner===N&&_?.fingerprint===S&&L&&bi(L,T)&&Ze)continue;let Ye=R?.enabled===!0&&R.managementOwner===N&&_?.fingerprint===S&&(j===void 0||Ze),et=R?.configurationRevision??null,tt=R?.managementOwner??null;if(R&&!Ye&&(R.enabled||R.managementOwner!==N)){let ce;try{ce=await d(m,R)}catch(sn){a(m,"the authority fence was not applied",sn);continue}if(!ce){h.delete(m);continue}h.set(m,ce),et=ce.configurationRevision,tt=ce.managementOwner??null}k.push(u(y,T,S,Ye,et,tt))}await Promise.all(k)},"reconcile");try{let l=await c.initialize(),p=c.status().diagnostic;return p&&s(`a2a: ${p.message}`),await f(l.document),c.subscribe(async(h,w)=>{if(h.revision===w?.revision)return;await f(h.document);let k=Object.values(h.document.agents).filter(y=>y.enabled).length;s(`A2A configuration hot-reloaded (${k} enabled outbound Agents).`)}),c.startWatching(),{status:o(()=>c.status(),"status"),async reload(){let h=c.snapshot(),w=await c.reload();w.ok&&w.snapshot.revision===h?.revision&&await f(w.snapshot.document)},close(){c.close()}}}catch(l){throw c.close(),l}}}}o(Eo,"createConfiguredA2ARuntimeIntegration");export{A as A2AError,Pe as A2A_EXECUTOR_ID,te as A2A_PROTOCOL_VERSION,xi as CONFIGURED_A2A_TASK_RESPONSE_BYTES,re as assertOAuthScopeToken,Mn as assertSafeA2AUrl,yi as classifyA2AServerChange,_i as configuredA2AArtifactPolicy,xt as createA2AAgentExecutorFactory,ho as createA2AServerHotOptions,fo as createA2AServerOptionsFromConfig,Ti as createBearerEnvA2AAuthentication,Eo as createConfiguredA2ARuntimeIntegration,Ns as createKodaXA2AServer,gt as createOAuth2ClientCredentialsTokenManager,jt as createOAuth2JwtA2AAuthentication,X as decodeUtf8,bt as discoverA2ARegistration,me as errorMessage,mi as inspectA2AIntegration,dt as isEventStreamMediaType,ye as isExactOAuthLoopbackHostname,de as isJsonMediaType,g as isRecord,Qs as migrateA2ALegacyTaskOwners,lt as parseA2AAgentCard,Ce as parseA2AIntegrationDocument,D as parseA2AMessage,At as parseA2APart,J as parseA2ASecurity,H as parseA2ATask,pt as parseJsonRpcRequest,$ as parseOAuthEndpointUrl,F as parseOAuthIssuerIdentifier,ne as parseOAuthResourceIdentifier,ie as parseOAuthScopeList,it as parseOAuthScopeValue,$s as prepareKodaXA2AServer,Ve as readA2AIntegration,O as requireNonEmptyString,V as safeA2AFetch,we as satisfiableA2ASecurityRequirements,Ki as selectA2ASecurityRequirement};
|
|
10
|
+
`}waitForTask(e,n){let r=this.#e.get(e);return r?O.has(r.task.status.state)||r.task.status.state==="TASK_STATE_INPUT_REQUIRED"||r.task.status.state==="TASK_STATE_AUTH_REQUIRED"?Promise.resolve(r):new Promise(i=>{let s=!1,a=o(()=>{},"unsubscribe"),c=o(f=>{s||(s=!0,clearTimeout(d),a(),i(f))},"finish"),d=setTimeout(()=>c(this.#e.get(e)??r),n);a=this.#e.subscribe(e,f=>{(O.has(f.task.status.state)||f.task.status.state==="TASK_STATE_INPUT_REQUIRED"||f.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&c(f)});let u=this.#e.get(e);u&&(O.has(u.task.status.state)||u.task.status.state==="TASK_STATE_INPUT_REQUIRED"||u.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&c(u)}):Promise.reject(new A(-32001,"Task not found."))}requireOwnedTask(e,n){let r=this.#e.get(e);if(!r||r.principalKey!==n)throw new A(-32001,"Task not found.");return r}async recover(){let e=this.options;for(let n of this.#e.all()){if(O.has(n.task.status.state))continue;let r=n.runIds.at(-1);if(!r||n.runtimeIdentity!==e.runtime.identity.runtimeId){this.failTask(n.taskId,"Runtime execution was interrupted before A2A recovery.",e);continue}try{let i=await e.runtime.runs.get(r);Sr(i.phase)?(await this.attachRuntimeEvents(n,r,e),e.runtime.runs.await(r).then(s=>this.finishRun(n.taskId,s,e)).catch(()=>{this.failTask(n.taskId,"Runtime execution failed during A2A recovery.",e)})):(await this.attachRuntimeEvents(n,r,e),this.finishRun(n.taskId,{runId:r,sessionId:n.sessionId,phase:i.phase},e))}catch(i){G({source:"a2a.server",level:"warn",message:"A2A task recovery could not reattach to its Runtime run.",detail:{taskId:n.taskId,error:i}}),this.failTask(n.taskId,"Runtime execution was unavailable during A2A recovery.",e)}}}emit(e){this.options.onEvent?.(e)}};function $s(t){return new Ee(t)}o($s,"createKodaXA2AServer");async function Dr(t){let e=t.execution;if(!e)throw new Error("A2A execution declaration is required for prepared serving.");let n=t.runtime.agents.execution;if(!n)throw new Error("local-agent-capability-unavailable: Runtime does not own an embedded execution binding service.");if(t.signal?.aborted)throw t.signal.reason??new Error("A2A preparation aborted.");let r=await n.openOwnerSession();try{let i=e.kind==="local-agent"?await n.bindLocal({ownerSessionId:r.ownerSessionId,ref:e.agentRef,profileId:e.profileId,workspace:e.workspace,toolPolicy:e.toolPolicy,workspaceByteLimit:t.limits.maxWorkspaceBytesPerContext}):await n.bindDefault({ownerSessionId:r.ownerSessionId,profileId:e.profileId,workspace:e.workspace,toolPolicy:e.toolPolicy,workspaceByteLimit:t.limits.maxWorkspaceBytesPerContext}),s=!1;return{service:n,ownerSessionId:r.ownerSessionId,binding:i,declaration:e,prepareWorkspace(a){return n.prepareWorkspace({ownerSessionId:r.ownerSessionId,bindingId:i.bindingId,contextKey:a})},start(a){let c={ownerSessionId:r.ownerSessionId,bindingId:i.bindingId,expectedExecutionPolicyRevision:i.executionPolicyRevision,sessionId:a.sessionId,input:a.inputs,permissionBroker:"runtime",agentContext:{actorId:`a2a:${a.principalKey.slice(0,16)}`}};if(e.kind==="local-agent"){let d="configurationRevision"in i&&typeof i.configurationRevision=="string"?i.configurationRevision:void 0;if(!d)throw new Error("Prepared local-Agent binding is missing its revision.");return n.startLocal({...c,expectedConfigurationRevision:d})}return n.startDefault(c)},async close(){s||(s=!0,await n.closeOwnerSession(r.ownerSessionId))}}}catch(i){throw await n.closeOwnerSession(r.ownerSessionId),i}}o(Dr,"prepareExecution");async function Ds(t){let e=await Dr(t);try{let n=new Ee({...t,preparedExecution:e});return await n.whenReady(),n}catch(n){throw await e.close(),n}}o(Ds,"prepareKodaXA2AServer");import{createPublicKey as Kr}from"node:crypto";import*as ee from"oauth4webapi";var jr=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"],N=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="OAuthJwksUnavailableError"}cause;static{o(this,"OAuthJwksUnavailableError")}};function jt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(jt,"isRecord");function Br(t){for(let e of["kid","alg","use"])if(t[e]!==void 0&&typeof t[e]!="string")throw new N(`OAuth JWKS key field ${e} must be a string.`);if(t.key_ops!==void 0&&(!Array.isArray(t.key_ops)||!t.key_ops.every(e=>typeof e=="string")))throw new N("OAuth JWKS key_ops must be an array of strings.");if(typeof t.kty!="string"||t.kty.length===0)throw new N("OAuth JWKS key kty must be a non-empty string.");if(["RSA","EC","OKP"].includes(t.kty))try{Kr({key:t,format:"jwk"})}catch(e){throw new N("OAuth JWKS endpoint returned an invalid public key.",e)}}o(Br,"assertPublicJwk");function Hr(t,e){if(t.status!==200)throw new N("OAuth JWKS endpoint returned an unexpected status.");let n=t.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();if(n!=="application/json"&&n!=="application/jwk-set+json")throw new N("OAuth JWKS endpoint returned an unsupported media type.");let r;try{r=JSON.parse(X(e))}catch(i){throw new N("OAuth JWKS endpoint returned malformed JSON.",i)}if(!jt(r)||!Array.isArray(r.keys)||!r.keys.every(jt))throw new N("OAuth JWKS endpoint returned an invalid key set.");for(let i of r.keys)Br(i)}o(Hr,"assertJwksResponse");function zr(t){let e=new Set,n=t;for(;n!=null&&!e.has(n);){if(n instanceof N)return!0;if(e.add(n),typeof n!="object"||!("cause"in n))return!1;n=n.cause}return!1}o(zr,"isJwksUnavailable");function Jr(t){return{allowedOrigins:[t.origin],allowPrivateAddresses:me(t.hostname),requestTimeoutMs:1e4,maxResponseBytes:1048576,maxRedirects:0}}o(Jr,"jwksNetworkPolicy");function Fr(t,e){return async(n,r)=>{try{let i=await V(new URL(n),{...r,redirect:"manual"},t,e);return Hr(i.response,i.body),new Response(i.body,{status:i.response.status,statusText:i.response.statusText,headers:i.response.headers})}catch(i){throw i instanceof N?i:new N("OAuth JWKS endpoint is unavailable.",i)}}}o(Fr,"boundedOAuthFetch");function Wr(t){if(t===void 0)return[];if(typeof t!="string")throw new Error("OAuth access-token scope claim must be a string.");return it(t,"OAuth access-token scope claim")}o(Wr,"scopesFromClaim");function Bt(t,e){if(t.type!=="oauth2-jwt")throw new Error("A2A authentication.type must be oauth2-jwt.");let n=P(t.scheme,"A2A authentication.scheme"),r=P(t.audience,"A2A authentication.audience"),i=ie(t.requiredScopes,"A2A authentication.requiredScopes"),s=J(t.issuer,"OAuth issuer"),a=$(t.jwksUrl,"OAuth JWKS endpoint"),c=$(t.tokenUrl,"OAuth token endpoint"),d=t.metadataUrl===void 0?void 0:$(t.metadataUrl,"OAuth metadata endpoint"),u={issuer:s,jwks_uri:a.href},f={},l=Fr(Jr(a),e),p=Object.fromEntries(i.map(h=>[h,"Required to invoke this Agent."]));return{securityRealm:`oauth2-jwt:${s}`,securitySchemes:{[n]:{oauth2SecurityScheme:{flows:{clientCredentials:{tokenUrl:c.href,scopes:p}},...d?{oauth2MetadataUrl:d.href}:{}}}},securityRequirements:[{schemes:{[n]:{list:i}}}],async authenticate(h){if(!h.headers.get("authorization"))return null;let k,y;try{k=await ee.validateJwtAccessToken(u,h,r,{signingAlgorithms:jr,[ee.jwksCache]:f,[ee.customFetch]:l,...a.protocol==="http:"&&me(a.hostname)?{[ee.allowInsecureRequests]:!0}:{}});let m=k.scope;y=Wr(m)}catch(m){throw zr(m)?new A(-32603,"OAuth token verification is temporarily unavailable.",503):new A(-32600,"Invalid OAuth access token.",401,void 0,{"www-authenticate":'Bearer error="invalid_token"'})}if(i.filter(m=>!y.includes(m)).length>0)throw new A(-32600,"Insufficient OAuth scope.",403,void 0,{"www-authenticate":`Bearer error="insufficient_scope", scope="${i.join(" ")}"`});return{subject:k.sub,scopes:y}}}}o(Bt,"createOAuth2JwtA2AAuthentication");import Ht from"node:os";import zt from"node:path";function Gr(t){return t==="~"?Ht.homedir():t.startsWith("~/")||t.startsWith("~\\")?zt.join(Ht.homedir(),t.slice(2)):zt.resolve(t)}o(Gr,"resolveDataDir");function Vr(t,e){if(typeof t.subject!="string")throw new Error(`A2A legacy task owner mapping ${e} subject must be a string.`);if(t.tenant!==void 0&&typeof t.tenant!="string")throw new Error(`A2A legacy task owner mapping ${e} tenant must be a string.`);if(typeof t.securityRealm!="string"||t.securityRealm.trim().length===0)throw new Error(`A2A legacy task owner mapping ${e} securityRealm must be a non-empty stable string.`)}o(Vr,"validateMapping");function Zs(t){if(typeof t.dataDir!="string"||t.dataDir.trim().length===0)throw new Error("A2A legacy task owner migration dataDir must be a non-empty path.");if(!Array.isArray(t.mappings)||t.mappings.length===0)throw new Error("A2A legacy task owner migration requires at least one explicit mapping.");if(typeof t.apply!="boolean")throw new Error("A2A legacy task owner migration apply must be a boolean.");let e=new Map,n=new Set;t.mappings.forEach((s,a)=>{Vr(s,a);let c=Ct(s),d=Re(s),u=e.get(c);if(u!==void 0&&u!==d)throw new Error("A2A legacy task owner mappings are ambiguous across security realms.");e.set(c,d),n.add(d)});let r=Gr(t.dataDir),i=new oe(r);try{let s=i.migrateUnversionedPrincipalKeys({legacyToCurrent:e,currentKeys:n,apply:t.apply});return{dataDir:r,applied:t.apply,...s}}finally{i.close()}}o(Zs,"migrateA2ALegacyTaskOwners");import{createHash as Xr}from"node:crypto";import{existsSync as Qr,readFileSync as Zr}from"node:fs";import Ie from"node:path";import{isDeepStrictEqual as Fe}from"node:util";var Ft={maxRequestBytes:33554432,maxPartBytes:16777216,maxConcurrentTasks:4,maxTaskWaitMs:3e4,maxActiveTasksPerPrincipal:4,maxRetainedTasksPerPrincipal:100,maxEventsPerTask:1e3,maxEventBytesPerTask:16777216,maxWorkspaceBytesPerContext:1073741824},Jt=Object.keys(Ft),xe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Yr=/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/,ei=/^[A-Za-z_][A-Za-z0-9_]*$/;function Wt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Wt,"isExactLoopback");function v(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object.`);return t}o(v,"record");function b(t,e,n){let r=new Set(e),i=Object.keys(t).find(s=>!r.has(s));if(i!==void 0)throw new Error(`${n} has unknown field "${i}".`)}o(b,"noUnknown");function x(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t.trim()}o(x,"text");function ae(t,e,n=!1){if(!Array.isArray(t)||!n&&t.length===0)throw new Error(`${e} must be ${n?"an":"a non-empty"} array of strings.`);let r=t.map((i,s)=>x(i,`${e}[${s}]`));if(new Set(r).size!==r.length)throw new Error(`${e} contains duplicates.`);return r}o(ae,"stringList");function We(t,e,n=!0){let r=ae(t,e,n);if(r.some(i=>i.includes("*")))throw new Error(`${e} does not accept wildcard authority.`);return r}o(We,"exactNames");function ti(t,e){return We(t,e).map(n=>{if(!Yr.test(n))throw new Error(`${e} entries must be valid host tool names.`);return n})}o(ti,"hostToolNames");function Gt(t,e){let n=v(t,e),r={};for(let[i,s]of Object.entries(n)){if(!xe.test(i)||i.includes("*"))throw new Error(`${e} keys must be exact names without wildcards.`);r[i]=We(s,`${e}.${i}`,!1)}return r}o(Gt,"namedExactLists");function Vt(t,e){let n=x(t,e);if(!xe.test(n))throw new Error(`${e} is invalid.`);return n}o(Vt,"parseSchemeName");function Xt(t,e){return J(t,e)}o(Xt,"parseIssuer");function Qt(t,e){let n=ae(t,e,!0);for(let r of n)re(r,e);return n}o(Qt,"oauthScopeList");function ni(t,e){return ne(t,e)}o(ni,"parseResource");function be(t,e){return $(t,e).href}o(be,"parseOAuthEndpoint");function ri(t,e){let n=v(t,e);if(b(n,["type","scheme","issuer","tokenUrl","clientId","clientSecretEnv","scopes","resource","clientAuthentication"],e),n.type!=="oauth2-client-credentials")throw new Error(`${e}.type must be oauth2-client-credentials.`);let r=n.clientAuthentication??"client-secret-basic";if(!["client-secret-basic","client-secret-post"].includes(String(r)))throw new Error(`${e}.clientAuthentication is invalid.`);return{type:"oauth2-client-credentials",scheme:Vt(n.scheme,`${e}.scheme`),issuer:Xt(n.issuer,`${e}.issuer`),tokenUrl:be(n.tokenUrl,`${e}.tokenUrl`),clientId:x(n.clientId,`${e}.clientId`),clientSecretEnv:Ge(n.clientSecretEnv,`${e}.clientSecretEnv`),scopes:Qt(n.scopes,`${e}.scopes`),...n.resource===void 0?{}:{resource:ni(n.resource,`${e}.resource`)},clientAuthentication:r}}o(ri,"parseOutboundAuthentication");function ii(t,e,n){let r=v(t,e);b(r,n===1?["cardUrl","credentialEnv","effect"]:["cardUrl","enabled","credentialEnv","authentication","network","effect"],e);let i=r.network===void 0?void 0:si(r.network,`${e}.network`),s=Zt(r.cardUrl,`${e}.cardUrl`,i?.allowInsecureHttp===!0),a=r.effect;if(!["none","read","write","unknown"].includes(String(a)))throw new Error(`${e}.effect is invalid.`);let c=r.credentialEnv===void 0?void 0:Ge(r.credentialEnv,`${e}.credentialEnv`);if(c&&r.authentication!==void 0)throw new Error(`${e}.credentialEnv and ${e}.authentication are mutually exclusive.`);if(r.enabled!==void 0&&typeof r.enabled!="boolean")throw new Error(`${e}.enabled must be a boolean.`);return{cardUrl:s,enabled:r.enabled??!0,...c?{credentialEnv:c}:{},...r.authentication===void 0?{}:{authentication:ri(r.authentication,`${e}.authentication`)},...i===void 0?{}:{network:i},effect:a}}o(ii,"parseOutboundAgent");function si(t,e){let n=v(t,e);if(b(n,["allowPrivateAddresses","allowInsecureHttp"],e),typeof n.allowPrivateAddresses!="boolean")throw new Error(`${e}.allowPrivateAddresses must be a boolean.`);if(typeof n.allowInsecureHttp!="boolean")throw new Error(`${e}.allowInsecureHttp must be a boolean.`);return{allowPrivateAddresses:n.allowPrivateAddresses,allowInsecureHttp:n.allowInsecureHttp}}o(si,"parseOutboundNetwork");function Zt(t,e,n){let r=x(t,e),i;try{i=new URL(r)}catch(a){throw new Error(`${e} must be an absolute HTTP URL.`,{cause:a})}if(i.username||i.password)throw new Error(`${e} must not contain embedded credentials.`);if(i.hash)throw new Error(`${e} must not contain a fragment.`);let s=Wt(i.hostname);if(i.protocol!=="https:"&&!(i.protocol==="http:"&&(s||n)))throw new Error(`${e} must use HTTPS, exact loopback HTTP, or explicitly authorized plaintext HTTP.`);return i.toString()}o(Zt,"parseHttpUrl");function Ge(t,e){let n=x(t,e);if(!ei.test(n))throw new Error(`${e} must be an environment variable name.`);return n}o(Ge,"parseEnvironmentName");function oi(t){if(t===void 0)return{mode:"managed"};let e=v(t,"A2A server execution.workspace");if(e.mode==="managed")return b(e,["mode"],"A2A server execution.workspace"),{mode:"managed"};if(e.mode!=="fixed")throw new Error("A2A server execution.workspace.mode is invalid.");b(e,["mode","root"],"A2A server execution.workspace");let n=x(e.root,"A2A server execution.workspace.root");if(!Ie.isAbsolute(n))throw new Error("Fixed A2A workspace root must be absolute.");return{mode:"fixed",root:Ie.resolve(n)}}o(oi,"parseWorkspace");function ai(t){return{workspace:t.mode==="managed"?"write":"read",process:"deny",network:{mode:"deny"},tools:[],mcp:{},skillScripts:{},subagents:"deny"}}o(ai,"defaultToolPolicy");function ci(t){let e=v(t,"A2A toolPolicy.network");if(e.mode==="deny")return b(e,["mode"],"A2A toolPolicy.network"),{mode:"deny"};if(e.mode!=="allowlist")throw new Error("A2A toolPolicy.network.mode is invalid.");b(e,["mode","origins"],"A2A toolPolicy.network");let n=ae(e.origins,"A2A toolPolicy.network.origins").map(r=>{let i;try{i=new URL(r)}catch(s){throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.",{cause:s})}if(!["http:","https:"].includes(i.protocol)||i.origin==="null")throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.");return i.origin});if(new Set(n).size!==n.length)throw new Error("A2A toolPolicy.network.origins contains duplicates after normalization.");return{mode:"allowlist",origins:n}}o(ci,"parseNetworkPolicy");function di(t){let e=Gt(t,"A2A toolPolicy.skillScripts");for(let[n,r]of Object.entries(e))e[n]=r.map(i=>{if(i.includes("\\")||Ie.posix.isAbsolute(i))throw new Error("A2A skillScripts paths must use relative POSIX scripts/... paths.");let s=Ie.posix.normalize(i);if(!s.startsWith("scripts/")||s.includes("../"))throw new Error("A2A skillScripts paths must remain below the Skill scripts directory.");return s});return e}o(di,"parseSkillScripts");function ui(t,e){if(t===void 0)return ai(e);let n=v(t,"A2A server execution.toolPolicy"),r=["workspace","process","network","tools","mcp","skillScripts","subagents"];if(b(n,[...r,"hostTools"],"A2A server execution.toolPolicy"),r.some(a=>n[a]===void 0))throw new Error("A2A server execution.toolPolicy must be a complete object when present.");if(!["none","read","write"].includes(String(n.workspace)))throw new Error("A2A toolPolicy.workspace is invalid.");if(!["deny","isolated"].includes(String(n.process)))throw new Error("A2A toolPolicy.process is invalid.");if(!["deny","inherit"].includes(String(n.subagents)))throw new Error("A2A toolPolicy.subagents is invalid.");let i=di(n.skillScripts),s=Object.values(i).reduce((a,c)=>a+c.length,0);if(n.process==="deny"&&s>0)throw new Error("A2A toolPolicy process deny requires empty skillScripts.");if(n.process==="isolated"&&s===0)throw new Error("A2A toolPolicy process isolated requires non-empty skillScripts.");return{workspace:n.workspace,process:n.process,network:ci(n.network),tools:We(n.tools,"A2A toolPolicy.tools"),mcp:Gt(n.mcp,"A2A toolPolicy.mcp"),skillScripts:i,subagents:n.subagents,...n.hostTools===void 0?{}:{hostTools:ti(n.hostTools,"A2A toolPolicy.hostTools")}}}o(ui,"parseToolPolicy");function li(t){let e=v(t,"A2A server execution"),n=oi(e.workspace),r=ui(e.toolPolicy,n),i=e.profileId===void 0?void 0:x(e.profileId,"A2A server execution.profileId");if(e.kind==="runtime-default")return b(e,["kind","workspace","toolPolicy","profileId"],"A2A server execution"),{kind:"runtime-default",workspace:n,toolPolicy:r,...i?{profileId:i}:{}};if(e.kind!=="local-agent")throw new Error("A2A server execution.kind is invalid.");b(e,["kind","agentRef","workspace","toolPolicy","profileId"],"A2A server execution");let s=v(e.agentRef,"A2A server execution.agentRef");if(b(s,["source","name"],"A2A server execution.agentRef"),s.source!=="markdown:user")throw new Error("A2A local Agent source must be markdown:user.");let a=x(s.name,"A2A server execution.agentRef.name");if(!xe.test(a))throw new Error("A2A local Agent name is invalid.");return{kind:"local-agent",agentRef:{source:"markdown:user",name:a},workspace:n,toolPolicy:r,...i?{profileId:i}:{}}}o(li,"parseExecution");function Ai(t,e){let n=`A2A server published.skills[${e}]`,r=v(t,n);return b(r,["id","name","description","tags"],n),{id:x(r.id,`${n}.id`),name:x(r.name,`${n}.name`),description:x(r.description,`${n}.description`),tags:ae(r.tags,`${n}.tags`,!0)}}o(Ai,"parsePublishedSkill");function pi(t){let e=v(t,"A2A server published");if(b(e,["name","description","version","skills","inputModes","outputModes"],"A2A server published"),!Array.isArray(e.skills))throw new Error("A2A server published.skills must be an array.");let n=e.skills.map(Ai),r=n.map(i=>i.id);if(new Set(r).size!==r.length)throw new Error("A2A published Skill ids must be unique.");return{name:x(e.name,"A2A server published.name"),description:x(e.description,"A2A server published.description"),version:x(e.version,"A2A server published.version"),skills:n,inputModes:ae(e.inputModes,"A2A server published.inputModes"),outputModes:ae(e.outputModes,"A2A server published.outputModes")}}o(pi,"parsePublished");function fi(t,e){let n=v(t,"A2A server authentication");if(n.type==="bearer-env")return b(n,["type","tokenEnv","principalId"],"A2A server authentication"),{type:"bearer-env",tokenEnv:Ge(n.tokenEnv,"A2A server authentication.tokenEnv"),principalId:x(n.principalId,"A2A server authentication.principalId")};if(e===1)throw new Error("A2A oauth2-jwt authentication requires integration config version 2.");if(n.type!=="oauth2-jwt")throw new Error("A2A authentication type must be bearer-env or oauth2-jwt.");return b(n,["type","scheme","issuer","audience","jwksUrl","tokenUrl","metadataUrl","requiredScopes"],"A2A server authentication"),{type:"oauth2-jwt",scheme:Vt(n.scheme,"A2A server authentication.scheme"),issuer:Xt(n.issuer,"A2A server authentication.issuer"),audience:x(n.audience,"A2A server authentication.audience"),jwksUrl:be(n.jwksUrl,"A2A server authentication.jwksUrl"),tokenUrl:be(n.tokenUrl,"A2A server authentication.tokenUrl"),...n.metadataUrl===void 0?{}:{metadataUrl:be(n.metadataUrl,"A2A server authentication.metadataUrl")},requiredScopes:Qt(n.requiredScopes,"A2A server authentication.requiredScopes")}}o(fi,"parseAuthentication");function Yt(t,e){if(!Number.isSafeInteger(t)||Number(t)<=0)throw new Error(`${e} must be a positive safe integer.`);return Number(t)}o(Yt,"positiveInteger");function hi(t,e){let n=t===void 0?{}:v(t,"A2A server limits");b(n,Jt,"A2A server limits");let r=Object.fromEntries(Jt.map(s=>[s,n[s]===void 0?Ft[s]:Yt(n[s],`A2A server limits.${s}`)]));if(r.maxPartBytes>r.maxRequestBytes)throw new Error("A2A server limits.maxPartBytes must not exceed maxRequestBytes.");let i=e.workspace.mode==="fixed"&&e.toolPolicy.workspace==="write";if(i&&n.maxConcurrentTasks===void 0)return{...r,maxConcurrentTasks:1};if(i&&r.maxConcurrentTasks!==1)throw new Error("A2A fixed writable workspace requires maxConcurrentTasks 1.");return r}o(hi,"parseLimits");function gi(t){let e=v(t,"A2A server.listen");b(e,["hostname","port"],"A2A server.listen");let n=x(e.hostname,"A2A server.listen.hostname");if(!Wt(n))throw new Error("A2A server.listen.hostname must be a loopback address.");let r=Yt(e.port,"A2A server.listen.port");if(r>65535)throw new Error("A2A server.listen.port must be at most 65535.");return{hostname:n,port:r}}o(gi,"parseListen");function mi(t,e){let n=v(t,"A2A server");b(n,["execution","published","publicBaseUrl","listen","authentication","limits","dataDir"],"A2A server");let r=li(n.execution),i=n.publicBaseUrl===void 0?void 0:Zt(n.publicBaseUrl,"A2A server.publicBaseUrl",!0),s=n.listen===void 0?void 0:gi(n.listen);return{execution:r,published:pi(n.published),...i?{publicBaseUrl:i}:{},...s?{listen:s}:{},authentication:fi(n.authentication,e),limits:hi(n.limits,r),dataDir:x(n.dataDir,"A2A server.dataDir")}}o(mi,"parseServer");function ve(t){let e=v(t,"A2A integration config");if(b(e,["version","agents","server"],"A2A integration config"),e.version!==1&&e.version!==2)throw new Error("A2A integration config version must be 1 or 2.");let n=e.version,r=v(e.agents,"A2A integration config agents"),i={};for(let[s,a]of Object.entries(r)){if(!xe.test(s))throw new Error(`A2A outbound Agent name "${s}" is invalid.`);i[s]=ii(a,`A2A outbound Agent "${s}"`,n)}return{version:2,agents:i,...e.server===void 0?{}:{server:mi(e.server,n)}}}o(ve,"parseA2AIntegrationDocument");function yi(t){return Xr("sha256").update(t).digest("hex")}o(yi,"hash");function en(t){let e=nt("a2a",t),n=Qr(e),r=n?Zr(e,"utf8"):JSON.stringify({version:2,agents:{}}),i;try{i=JSON.parse(r)}catch(u){throw new Error("Invalid A2A integration JSON.",{cause:u})}let s=ve(i),a=v(i,"A2A integration config");if(a.version!==1&&a.version!==2)throw new Error("A2A integration config version must be 1 or 2.");let c=a.version;return{snapshot:{domain:"a2a",source:n?"user":"default",path:e,revision:yi(r),document:s,loadedAt:new Date().toISOString()},sourceVersion:c,nonEmptyLegacy:c===1&&(Object.keys(s.agents).length>0||s.server!==void 0)}}o(en,"loadA2AIntegration");function Ve(t){return en(t).snapshot}o(Ve,"readA2AIntegration");function wi(t){let e=en(t);return{sourceVersion:e.sourceVersion,snapshot:e.snapshot}}o(wi,"inspectA2AIntegration");function ki(t,e){if(Fe(t,e))return{kind:"none",fields:[]};if(t===void 0||e===void 0)return{kind:"restart-required",fields:["server"]};let n=["execution","dataDir","listen"].filter(i=>!Fe(t[i],e[i])),r=["published","publicBaseUrl","authentication","limits"].filter(i=>!Fe(t[i],e[i]));return n.length>0?{kind:"restart-required",fields:[...n,...r]}:{kind:"hot",fields:r}}o(ki,"classifyA2AServerChange");import{timingSafeEqual as Si}from"node:crypto";import tn from"node:os";import nn from"node:path";function Ri(t){return t==="~"?tn.homedir():t.startsWith("~/")||t.startsWith("~\\")?nn.join(tn.homedir(),t.slice(2)):nn.resolve(t)}o(Ri,"expandHome");function Ti(t){let e=t.headers.get("authorization");return(e?/^Bearer ([^\s]+)$/i.exec(e):null)?.[1]}o(Ti,"bearerToken");function Ei(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.byteLength===r.byteLength&&Si(n,r)}o(Ei,"equalSecret");function bi(t,e=process.env){let n=e[t.tokenEnv];if(!n)throw new Error(`A2A bearer token environment variable is unset: ${t.tokenEnv}.`);return{securityRealm:`bearer-env:${t.tokenEnv}`,securitySchemes:{bearer:{httpAuthSecurityScheme:{scheme:"Bearer",bearerFormat:"opaque"}}},securityRequirements:[{schemes:{bearer:{list:[]}}}],async authenticate(r){let i=Ti(r);return i&&Ei(n,i)?{subject:t.principalId,scopes:["a2a:invoke"]}:null}}}o(bi,"createBearerEnvA2AAuthentication");function rn(t,e){return t.type==="bearer-env"?bi(t,e):Bt(t)}o(rn,"createConfiguredAuthentication");function sn(t,e){return{name:t.published.name,description:t.published.description,version:t.published.version,publicBaseUrl:t.publicBaseUrl??e,skills:t.published.skills,inputModes:t.published.inputModes,outputModes:t.published.outputModes,...t.execution.profileId?{profileId:t.execution.profileId}:{}}}o(sn,"publishedAgent");function on(){return Promise.resolve(!0)}o(on,"authorization");function ho(t){return{runtime:t.runtime,agent:sn(t.config,t.listenBaseUrl),execution:t.config.execution,dataDir:Ri(t.config.dataDir),limits:t.config.limits,authentication:rn(t.config.authentication,t.env),authorize:on}}o(ho,"createA2AServerOptionsFromConfig");function go(t){return{agent:sn(t.config,t.listenBaseUrl),limits:t.config.limits,authentication:rn(t.config.authentication,t.env),authorize:on}}o(go,"createA2AServerHotOptions");import{createHash as Ii}from"node:crypto";import{isDeepStrictEqual as xi}from"node:util";var q="kodax-a2a-runtime-config-v1",Qe="kodax-a2a-config-v1:";function vi(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(vi,"isExactLoopback");var Ce={allowPrivateAddresses:!1,allowInsecureHttp:!1};function Xe(t,e=Ce){let n=t.map(r=>vi(r.hostname));if(n.some(Boolean)&&!n.every(Boolean))throw new Error("Configured A2A Agent and OAuth endpoints must not mix loopback and public origins.");return{allowedOrigins:[...new Set(t.map(r=>r.origin))],allowPrivateAddresses:e.allowPrivateAddresses||n.every(Boolean),allowInsecureHttp:e.allowInsecureHttp,requestTimeoutMs:1e4,maxResponseBytes:1e6,maxRedirects:3}}o(Xe,"networkPolicy");var Ci=32*1024*1024;function Pi(t){let e=t.executorConfig?.interfaceUrl;if(typeof e!="string")throw new Error("Configured A2A registration has no interface URL.");return new URL(e)}o(Pi,"registrationUrl");function Oi(t){let e=[Pi(t)],n=t.executorConfig?.authentication;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r=n.tokenUrl;typeof r=="string"&&e.push(new URL(r))}return e}o(Oi,"registrationNetworkUrls");function _i(t){let e=t.executorConfig?.network;if(e===null||typeof e!="object"||Array.isArray(e))return Ce;let n=e;return{allowPrivateAddresses:n.allowPrivateAddresses===!0,allowInsecureHttp:n.allowInsecureHttp===!0}}o(_i,"registrationNetworkAccess");function Ui(){let t=o(e=>{if(!e.startsWith("env:")||e.length===4)throw new Error("Configured A2A credentials must use an environment reference.");return e.slice(4)},"environmentName");return{isAvailable(e){let n=process.env[t(e)];return typeof n=="string"&&n.length>0},async withCredential(e,n){let r=process.env[t(e)];if(!r)throw new Error("Configured A2A credential is unavailable.");return n(r)}}}o(Ui,"environmentCredentialBroker");var Mi=o(({artifact:t})=>{if(t.provenance!=="a2a"||!t.uri)return{allowed:!1,reason:"Configured A2A artifacts require an A2A provenance URI."};let e;try{e=new URL(t.uri).protocol}catch{return{allowed:!1,reason:"Configured A2A artifact URI is invalid."}}return e!=="data:"&&e!=="http:"&&e!=="https:"?{allowed:!1,reason:`Configured A2A artifact URI scheme is not allowed: ${e}`}:{allowed:!0}},"configuredA2AArtifactPolicy");function Li(t,e){return{agentId:`external:${t}`,agentCardUrl:e.cardUrl,...e.credentialEnv?{credentialRef:`env:${e.credentialEnv}`}:{},...e.authentication?{authentication:{type:"oauth2-client-credentials",scheme:e.authentication.scheme,issuer:e.authentication.issuer,tokenUrl:e.authentication.tokenUrl,clientId:e.authentication.clientId,clientSecretRef:`env:${e.authentication.clientSecretEnv}`,scopes:e.authentication.scopes,...e.authentication.resource?{resource:e.authentication.resource}:{},clientAuthentication:e.authentication.clientAuthentication}}:{},effects:{remote:e.effect}}}o(Li,"registrationInput");function Ni(t){let e=t.authentication?[t.authentication.type,t.authentication.scheme,t.authentication.issuer,t.authentication.tokenUrl,t.authentication.clientId,t.authentication.clientSecretEnv,t.authentication.scopes,t.authentication.resource??null,t.authentication.clientAuthentication]:null;return Ii("sha256").update(JSON.stringify([t.cardUrl,t.credentialEnv??null,e,t.network??Ce,t.effect])).digest("hex")}o(Ni,"configFingerprint");function an(t){if(!t.startsWith(Qe))return;let e=Qe.length,n=t.indexOf(":",e);if(n<0)return;let r=t.slice(e,n),i=t.slice(n+1);if(!(!/^[a-f0-9]{64}$/.test(r)||i.length===0))return{fingerprint:r,registrationRevision:i}}o(an,"parseConfiguredRegistrationRevision");function qi(t,e){let n=an(e)?.registrationRevision??e;return`${Qe}${t}:${n}`}o(qi,"configuredRegistrationRevision");function $i(t,e,n){return{...t,executorConfig:{...t.executorConfig,network:{...n.network??Ce}},managementOwner:q,configurationRevision:qi(e,t.configurationRevision)}}o($i,"markConfiguredRegistration");function bo(t){return{runtimeOptions:{factories:[xt(n=>({networkPolicy:Xe(Oi(n),_i(n)),maxTaskResponseBytes:Ci,pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}))],policy:o(()=>({allowed:!0}),"policy"),credentialBroker:Ui(),artifactPolicy:Mi,defaultContext:{actorId:q}},async start(n){let r=new Map,i=new Map,s=o(l=>{try{t.onEvent?.(l)}catch(p){G({source:"a2a.runtime-config",level:"warn",message:"A2A Runtime event observer failed.",detail:p})}},"notify"),a=o((l,p,h)=>{G({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${l}" reconciliation failed; ${p}.`,detail:h}),s(`A2A Agent "${l}" could not be reconciled; ${p}.`)},"reportEntryFailure"),c=new rt({domain:"a2a",configHome:t.configHome,validate:ve,read:o(()=>Ve(t.configHome),"read"),coldStartDefault:{version:2,agents:{}}}),d=o(async(l,p)=>{if(p.managementOwner!==void 0&&p.managementOwner!==q)throw new Error(`A2A registration "${l}" is owned by ${p.managementOwner}.`);let h=r.get(l),w=await n.admin.agentRegistrations.setEnabled(l,!1,{expectedConfigurationRevision:p.configurationRevision,expectedManagementOwner:p.managementOwner??null,...p.managementOwner===void 0?{claimOwner:q}:{}});if(!w){r.delete(l),s(`A2A registration "${l}" changed concurrently; disable was deferred.`);return}return h?.configurationRevision===p.configurationRevision&&h.endpointIdentityHash===p.endpointIdentityHash?r.set(l,{...h,managementOwner:q,enabled:!1}):r.delete(l),w},"persistDisabledFence"),u=o(async(l,p,h,w,k,y)=>{let T=`external:${l}`;try{let m=new URL(p.cardUrl),S=[m,...p.authentication?[new URL(p.authentication.tokenUrl)]:[]];Xe(S,p.network);let L=await bt(Li(l,p),{networkPolicy:Xe([m],p.network),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}),R=$i(L.registration,h,p);await n.admin.agentRegistrations.upsert(R,{expectedConfigurationRevision:k,expectedManagementOwner:y}),r.set(T,R),i.set(T,p)}catch(m){let S=w?"the live registration was left unchanged":"the activation was not applied";G({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${l}" refresh failed; ${S}.`,detail:m}),s(`A2A Agent "${l}" could not be refreshed; ${S}.`)}},"refreshConfiguredAgent"),f=o(async l=>{let p=await n.admin.agentRegistrations.list(),h=new Map(p.map(y=>[y.agentId,y])),w=new Set(Object.keys(l.agents).map(y=>`external:${y}`));for(let[y,T]of h){if(w.has(y)||T.managementOwner!==q)continue;let m;try{m=await n.admin.agentRegistrations.remove(y,{expectedConfigurationRevision:T.configurationRevision,expectedManagementOwner:q})}catch(S){a(y,"removal was not applied",S);continue}if(!m){r.delete(y),s(`A2A registration "${y}" changed concurrently; removal was deferred.`);continue}r.delete(y),i.delete(y),h.delete(y)}for(let[y,T]of Object.entries(l.agents)){if(T.enabled)continue;let m=`external:${y}`,S=h.get(m);if(S?.managementOwner!==void 0&&S.managementOwner!==q){a(m,"the registration belongs to another manager",new Error(`A2A registration "${m}" is owned by ${S.managementOwner}.`));continue}if(S&&(S.enabled||S.managementOwner!==q))try{let L=await d(m,S);L?h.set(m,L):h.delete(m)}catch(L){a(m,"the disabled fence was not applied",L);continue}i.set(m,T)}let k=[];for(let[y,T]of Object.entries(l.agents)){if(!T.enabled)continue;let m=`external:${y}`,S=Ni(T),L=i.get(m),R=h.get(m);if(R?.managementOwner!==void 0&&R.managementOwner!==q){a(m,"the registration belongs to another manager",new Error(`A2A registration "${m}" is owned by ${R.managementOwner}.`));continue}let _=R?an(R.configurationRevision):void 0,j=r.get(m),Ze=j!==void 0&&R!==void 0&&j.configurationRevision===R.configurationRevision&&j.endpointIdentityHash===R.endpointIdentityHash;if(R?.enabled&&R.managementOwner===q&&_?.fingerprint===S&&L&&xi(L,T)&&Ze)continue;let Ye=R?.enabled===!0&&R.managementOwner===q&&_?.fingerprint===S&&(j===void 0||Ze),et=R?.configurationRevision??null,tt=R?.managementOwner??null;if(R&&!Ye&&(R.enabled||R.managementOwner!==q)){let ce;try{ce=await d(m,R)}catch(cn){a(m,"the authority fence was not applied",cn);continue}if(!ce){h.delete(m);continue}h.set(m,ce),et=ce.configurationRevision,tt=ce.managementOwner??null}k.push(u(y,T,S,Ye,et,tt))}await Promise.all(k)},"reconcile");try{let l=await c.initialize(),p=c.status().diagnostic;return p&&s(`a2a: ${p.message}`),await f(l.document),c.subscribe(async(h,w)=>{if(h.revision===w?.revision)return;await f(h.document);let k=Object.values(h.document.agents).filter(y=>y.enabled).length;s(`A2A configuration hot-reloaded (${k} enabled outbound Agents).`)}),c.startWatching(),{status:o(()=>c.status(),"status"),async reload(){let h=c.snapshot(),w=await c.reload();w.ok&&w.snapshot.revision===h?.revision&&await f(w.snapshot.document)},close(){c.close()}}}catch(l){throw c.close(),l}}}}o(bo,"createConfiguredA2ARuntimeIntegration");export{A as A2AError,Pe as A2A_EXECUTOR_ID,te as A2A_PROTOCOL_VERSION,Ci as CONFIGURED_A2A_TASK_RESPONSE_BYTES,re as assertOAuthScopeToken,qn as assertSafeA2AUrl,ki as classifyA2AServerChange,Mi as configuredA2AArtifactPolicy,xt as createA2AAgentExecutorFactory,go as createA2AServerHotOptions,ho as createA2AServerOptionsFromConfig,bi as createBearerEnvA2AAuthentication,bo as createConfiguredA2ARuntimeIntegration,$s as createKodaXA2AServer,gt as createOAuth2ClientCredentialsTokenManager,Bt as createOAuth2JwtA2AAuthentication,X as decodeUtf8,bt as discoverA2ARegistration,ge as errorMessage,wi as inspectA2AIntegration,dt as isEventStreamMediaType,me as isExactOAuthLoopbackHostname,de as isJsonMediaType,g as isRecord,Zs as migrateA2ALegacyTaskOwners,lt as parseA2AAgentCard,ve as parseA2AIntegrationDocument,D as parseA2AMessage,At as parseA2APart,F as parseA2ASecurity,H as parseA2ATask,pt as parseJsonRpcRequest,$ as parseOAuthEndpointUrl,J as parseOAuthIssuerIdentifier,ne as parseOAuthResourceIdentifier,ie as parseOAuthScopeList,it as parseOAuthScopeValue,Ds as prepareKodaXA2AServer,Ve as readA2AIntegration,P as requireNonEmptyString,V as safeA2AFetch,ye as satisfiableA2ASecurityRequirements,Bi as selectA2ASecurityRequirement};
|