@kodax-ai/kodax 0.7.69 → 0.7.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/LICENSE +158 -191
  3. package/README.md +38 -5
  4. package/README_CN.md +31 -7
  5. package/config-templates/integrations/a2a.example.jsonc +1 -1
  6. package/dist/chunks/{agent-DQRXT6M7.js → agent-T72XYPW4.js} +1 -1
  7. package/dist/chunks/argument-completer-QXJC36UP.js +2 -0
  8. package/dist/chunks/chunk-34L74PEG.js +60 -0
  9. package/dist/chunks/{chunk-ZG4DMYBS.js → chunk-4P4L3WEK.js} +1 -1
  10. package/dist/chunks/{chunk-VYKFM3TB.js → chunk-7PV577LP.js} +67 -63
  11. package/dist/chunks/{chunk-PQ3XUSY2.js → chunk-AQGNRBEJ.js} +189 -180
  12. package/dist/chunks/{chunk-URC6ZI6P.js → chunk-F4NOOBRZ.js} +1 -1
  13. package/dist/chunks/{chunk-PA76WUBL.js → chunk-GOQRVDFP.js} +2 -2
  14. package/dist/chunks/{chunk-VAZ25MDX.js → chunk-K7RYV2SE.js} +2 -2
  15. package/dist/chunks/{chunk-M7TCFYTO.js → chunk-P2UKNYYS.js} +3 -3
  16. package/dist/chunks/{chunk-4WIODYOH.js → chunk-RY5OLVQV.js} +1 -1
  17. package/dist/chunks/{chunk-NGJURAY5.js → chunk-XNQ2O7NI.js} +4 -4
  18. package/dist/chunks/{compaction-config-ABLL6UH3.js → compaction-config-TC6C2PJ6.js} +1 -1
  19. package/dist/chunks/{construction-bootstrap-GH6RW6ST.js → construction-bootstrap-BPRXZK4A.js} +1 -1
  20. package/dist/chunks/{dist-RWL2RBO4.js → dist-UENHF5OS.js} +1 -1
  21. package/dist/chunks/{host-7SAB4WEC.js → host-XUVAICP7.js} +1 -1
  22. package/dist/chunks/{run-manager-XMDKTONJ.js → run-manager-T7ALQZNT.js} +1 -1
  23. package/dist/chunks/{utils-QYE5Y73D.js → utils-TMMH6PKT.js} +1 -1
  24. package/dist/index.d.ts +8 -8
  25. package/dist/index.js +6 -6
  26. package/dist/kodax_cli.js +1207 -1192
  27. package/dist/runtime-worker.js +1104 -1090
  28. package/dist/sdk-a2a.d.ts +6 -6
  29. package/dist/sdk-a2a.js +8 -7
  30. package/dist/sdk-agent.d.ts +2 -2
  31. package/dist/sdk-agent.js +1 -1
  32. package/dist/sdk-coding.d.ts +19 -11
  33. package/dist/sdk-coding.js +1 -1
  34. package/dist/sdk-llm.d.ts +1 -1
  35. package/dist/sdk-mcp.d.ts +2 -2
  36. package/dist/sdk-mcp.js +1 -1
  37. package/dist/sdk-repl.d.ts +10 -10
  38. package/dist/sdk-repl.js +1 -1
  39. package/dist/sdk-runtime.d.ts +80 -11
  40. package/dist/sdk-runtime.js +1 -1
  41. package/dist/sdk-session.d.ts +4 -4
  42. package/dist/sdk-session.js +1 -1
  43. package/dist/sdk-skills.js +1 -1
  44. package/dist/semantic-worker.js +10 -10
  45. package/dist/types-chunks/{bash-prefix-extractor.d-BkIA8Wto.d.ts → bash-prefix-extractor.d-h9AwGqmO.d.ts} +12 -2
  46. package/dist/types-chunks/{capability.d-3C62G8Eq.d.ts → capability.d-K664nHOS.d.ts} +21 -6
  47. package/dist/types-chunks/{commands.d-DkPfcQWG.d.ts → commands.d-DxiVanpI.d.ts} +3 -3
  48. package/dist/types-chunks/{manager.d-CoEuPRAo.d.ts → manager.d-B67TmPO1.d.ts} +27 -3
  49. package/dist/types-chunks/{public-api.d-7G4--RZE.d.ts → public-api.d-BqFKI5fK.d.ts} +1 -1
  50. package/dist/types-chunks/{sdk-session-BQccrODn.d.ts → sdk-session-tcoxrMHQ.d.ts} +2 -2
  51. package/dist/types-chunks/{types.d-C9YHEAmA.d.ts → types.d-DZaYznxo.d.ts} +2 -2
  52. package/dist/types-chunks/{utils.d-BbB5jzi1.d.ts → utils.d-B4zc7oot.d.ts} +2 -2
  53. package/docs/SDK_EMBEDDER_GUIDE.md +112 -19
  54. package/package.json +2 -2
  55. package/dist/chunks/argument-completer-RSK6CCGP.js +0 -2
  56. package/dist/chunks/chunk-Z4PPLJF2.js +0 -60
package/dist/sdk-a2a.d.ts CHANGED
@@ -2,21 +2,21 @@ import { ar as ExternalAgentRegistration, u as AgentEffectDeclaration, x as Agen
2
2
  import { RuntimeKodaXOptions, RuntimeWorkspaceBinding, RuntimeExecutionToolPolicy, RuntimeUserMarkdownAgentRef, KodaXRuntime, RuntimeExternalAgentsOptions } from './sdk-runtime.js';
3
3
  import { c as IntegrationConfigSnapshot, e as IntegrationConfigStatus } from './types-chunks/integration-config.d-ojG4swOP.js';
4
4
  import './types-chunks/types.d-TTvpAGWf.js';
5
- import './types-chunks/bash-prefix-extractor.d-BkIA8Wto.js';
5
+ import './types-chunks/bash-prefix-extractor.d-h9AwGqmO.js';
6
6
  import './types-chunks/types.d-vJExiRje.js';
7
7
  import 'vscode-languageserver-protocol';
8
8
  import './types-chunks/cost-tracker.d-BeaenODW.js';
9
- import './types-chunks/capability.d-3C62G8Eq.js';
9
+ import './types-chunks/capability.d-K664nHOS.js';
10
10
  import './types-chunks/base.d-CYjtB68X.js';
11
11
  import './types-chunks/config.d-CJy1WENT.js';
12
- import './types-chunks/manager.d-CoEuPRAo.js';
12
+ import './types-chunks/manager.d-B67TmPO1.js';
13
13
  import './types-chunks/run-manager.d-BaXtkryp.js';
14
- import './types-chunks/types.d-C9YHEAmA.js';
15
- import './types-chunks/utils.d-BbB5jzi1.js';
14
+ import './types-chunks/types.d-DZaYznxo.js';
15
+ import './types-chunks/utils.d-B4zc7oot.js';
16
16
  import './types-chunks/guardrail.d-R7AiGfrI.js';
17
17
  import './types-chunks/guardrail.d-6ZDbNbHO.js';
18
18
  import 'readline';
19
- import './types-chunks/public-api.d-7G4--RZE.js';
19
+ import './types-chunks/public-api.d-BqFKI5fK.js';
20
20
  import 'child_process';
21
21
 
22
22
  declare const A2A_PROTOCOL_VERSION = "1.0";
package/dist/sdk-a2a.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import"./chunks/chunk-NGJURAY5.js";import"./chunks/chunk-VAZ25MDX.js";import{f as ge,k as me,l as ye}from"./chunks/chunk-M7TCFYTO.js";import"./chunks/chunk-WW2O2DEP.js";import"./chunks/chunk-ZG4DMYBS.js";import"./chunks/chunk-URC6ZI6P.js";import"./chunks/chunk-PA76WUBL.js";import"./chunks/chunk-4WIODYOH.js";import"./chunks/chunk-I4TPQEJN.js";import"./chunks/chunk-Y4WOTWUC.js";import"./chunks/chunk-PQ3XUSY2.js";import"./chunks/chunk-UJEMSPM5.js";import"./chunks/chunk-VYKFM3TB.js";import{b as M}from"./chunks/chunk-AWMTNUDS.js";import"./chunks/chunk-F7C7J6IM.js";import"./chunks/chunk-NGHQIGVW.js";import{a as i}from"./chunks/chunk-ONUPGMER.js";var C="1.0",L="kodax-a2a-v1-jsonrpc";var u=class extends Error{constructor(n,r,s=200,o){super(r);this.code=n;this.httpStatus=s;this.data=o;this.name="A2AError"}code;httpStatus;data;static{i(this,"A2AError")}};function q(t){return t instanceof Error?t.message:String(t)}i(q,"errorMessage");var ze=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 A(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(A,"isRecord");function w(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new u(-32602,`${n}.${e} must be a non-empty string.`);return r}i(w,"requiredString");function m(t,e){let n=t[e];return typeof n=="string"&&n.length>0?n:void 0}i(m,"optionalString");function D(t,e){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new u(-32602,`${e} must be a string array.`);return t}i(D,"stringArray");function We(t){if(!A(t))throw new u(-32602,"Agent Card interface is invalid.");return{url:w(t,"url","interface"),protocolBinding:w(t,"protocolBinding","interface"),protocolVersion:w(t,"protocolVersion","interface"),...m(t,"tenant")?{tenant:m(t,"tenant")}:{}}}i(We,"parseInterface");function Xe(t){if(!A(t))throw new u(-32602,"Agent Card skill is invalid.");return{id:w(t,"id","skill"),name:w(t,"name","skill"),description:w(t,"description","skill"),tags:D(t.tags,"skill.tags"),...Array.isArray(t.examples)?{examples:D(t.examples,"skill.examples")}:{},...Array.isArray(t.inputModes)?{inputModes:D(t.inputModes,"skill.inputModes")}:{},...Array.isArray(t.outputModes)?{outputModes:D(t.outputModes,"skill.outputModes")}:{}}}i(Xe,"parseSkill");function he(t){if(!A(t))throw new u(-32602,"Agent Card must be an object.");let e=t.supportedInterfaces,n=t.skills;if(!Array.isArray(e)||e.length===0)throw new u(-32602,"Agent Card must declare supportedInterfaces.");if(!Array.isArray(n))throw new u(-32602,"Agent Card must declare skills.");if(!A(t.capabilities))throw new u(-32602,"Agent Card capabilities are invalid.");return{name:w(t,"name","Agent Card"),description:w(t,"description","Agent Card"),supportedInterfaces:e.map(We),version:w(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.filter(A)}:{}},...A(t.securitySchemes)?{securitySchemes:t.securitySchemes}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(A)}:{},defaultInputModes:D(t.defaultInputModes,"Agent Card defaultInputModes"),defaultOutputModes:D(t.defaultOutputModes,"Agent Card defaultOutputModes"),skills:n.map(Xe)}}i(he,"parseA2AAgentCard");function we(t){if(!A(t))throw new u(-32602,"Message Part must be an object.");if(["text","raw","url","data"].filter(n=>t[n]!==void 0).length!==1)throw new u(-32602,"Message Part must contain exactly one content field.");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}:{},...A(t.metadata)?{metadata:t.metadata}:{},...m(t,"filename")?{filename:m(t,"filename")}:{},...m(t,"mediaType")?{mediaType:m(t,"mediaType")}:{}}}i(we,"parseA2APart");function v(t){if(!A(t))throw new u(-32602,"Message must be an object.");if(t.role!=="ROLE_USER"&&t.role!=="ROLE_AGENT")throw new u(-32602,"Message role is invalid.");if(!Array.isArray(t.parts)||t.parts.length===0)throw new u(-32602,"Message parts must not be empty.");return{messageId:w(t,"messageId","Message"),role:t.role,parts:t.parts.map(we),...m(t,"contextId")?{contextId:m(t,"contextId")}:{},...m(t,"taskId")?{taskId:m(t,"taskId")}:{},...A(t.metadata)?{metadata:t.metadata}:{}}}i(v,"parseA2AMessage");function Ge(t){if(!A(t)||!Array.isArray(t.parts)||t.parts.length===0)throw new u(-32603,"A2A artifact is invalid.");return{artifactId:w(t,"artifactId","Artifact"),parts:t.parts.map(we),...m(t,"name")?{name:m(t,"name")}:{},...m(t,"description")?{description:m(t,"description")}:{},...A(t.metadata)?{metadata:t.metadata}:{}}}i(Ge,"parseArtifact");function I(t){if(!A(t)||!A(t.status))throw new u(-32603,"A2A task is invalid.");let e=t.status.state;if(typeof e!="string"||!ze.has(e))throw new u(-32603,"A2A task state is invalid.");return{id:w(t,"id","Task"),contextId:w(t,"contextId","Task"),status:{state:e,...t.status.message!==void 0?{message:v(t.status.message)}:{},...m(t.status,"timestamp")?{timestamp:m(t.status,"timestamp")}:{}},...Array.isArray(t.artifacts)?{artifacts:t.artifacts.map(Ge)}:{},...Array.isArray(t.history)?{history:t.history.map(v)}:{},...A(t.metadata)?{metadata:t.metadata}:{}}}i(I,"parseA2ATask");function ke(t){if(!A(t)||t.jsonrpc!=="2.0")throw new u(-32600,"Invalid JSON-RPC request.");if(typeof t.id!="string"&&typeof t.id!="number")throw new u(-32600,"JSON-RPC request id is required.");return{jsonrpc:"2.0",id:t.id,method:w(t,"method","JSON-RPC request"),...A(t.params)?{params:t.params}:{}}}i(ke,"parseJsonRpcRequest");import{lookup as Ve}from"node:dns/promises";import{request as Qe}from"node:http";import{request as Ze}from"node:https";import{isIP as Ye}from"node:net";import{Readable as et}from"node:stream";function tt(t){let e=t.split(".").map(Number),[n,r]=e;return e.length!==4||n===void 0||r===void 0?!0:n===0||n===10||n===127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n>=224}i(tt,"isPrivateIpv4");function nt(t){let e=t.toLowerCase();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")}i(nt,"isPrivateIpv6");function Te(t){let e=Ye(t);return e===4?tt(t):e===6?nt(t):!0}i(Te,"isPrivateAddress");async function Se(t,e){if(t.protocol!=="https:"&&t.protocol!=="http:")throw new u(-32602,"A2A URL must use HTTP or HTTPS.");if(!e.allowedOrigins.includes(t.origin))throw new u(-32602,`A2A origin is not allowed: ${t.origin}`);if(t.username||t.password)throw new u(-32602,"A2A URL must not include credentials.");let n=await Ve(t.hostname,{all:!0,verbatim:!0});if(n.length===0)throw new u(-32602,"A2A hostname did not resolve.");if(t.protocol==="http:"&&!n.every(s=>Te(s.address)))throw new u(-32602,"Public A2A targets must use HTTPS.");if(!e.allowPrivateAddresses&&n.some(s=>Te(s.address)))throw new u(-32602,"A2A private network targets are not allowed.");let r=n[0];if(r===void 0||r.family!==4&&r.family!==6)throw new u(-32602,"A2A hostname returned an unsupported address.");return{address:r.address,family:r.family}}i(Se,"validateA2AUrl");async function rt(t,e){await Se(t,e)}i(rt,"assertSafeA2AUrl");function st(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 u(-32602,"A2A request body type is not supported by the safe transport.")}i(st,"encodeRequestBody");function ot(t){return((e,n,r)=>{if(typeof n=="object"&&n.all){r(null,[t]);return}r(null,t.address,t.family)})}i(ot,"pinnedLookup");function it(t,e,n){return new Promise((r,s)=>{let o=new Headers(e.headers);o.set("accept-encoding","identity");let a=(t.protocol==="https:"?Ze:Qe)(t,{method:e.method,headers:Object.fromEntries(o),lookup:ot(n),signal:e.signal??void 0},d=>{let c=new Headers;for(let f=0;f<d.rawHeaders.length;f+=2){let E=d.rawHeaders[f],b=d.rawHeaders[f+1];E!==void 0&&b!==void 0&&c.append(E,b)}let l=d.statusCode??500,g=e.method!=="HEAD"&&l!==204&&l!==205&&l!==304?et.toWeb(d):null;r(new Response(g,{status:l,statusText:d.statusMessage,headers:c}))});a.once("error",s),a.end(st(e.body))})}i(it,"requestValidatedAddress");async function oe(t,e,n,r){let s=await Se(t,n);return r!==void 0?r(t,e):it(t,e,s)}i(oe,"openSafeA2AResponse");async function at(t,e){let n=t.headers.get("content-length");if(n&&Number(n)>e)throw new u(-32603,"A2A response is too large.");if(!t.body)return new Uint8Array;let r=t.body.getReader(),s=[],o=0;for(;;){let c=await r.read();if(c.done)break;if(o+=c.value.byteLength,o>e)throw await r.cancel(),new u(-32603,"A2A response is too large.");s.push(c.value)}let a=new Uint8Array(o),d=0;for(let c of s)a.set(c,d),d+=c.byteLength;return a}i(at,"boundedBody");async function W(t,e,n,r){let s=t,o=new Headers(e.headers).get("authorization");for(let a=0;a<=n.maxRedirects;a+=1){let d=new AbortController,c=setTimeout(()=>d.abort(new Error("A2A request timed out.")),n.requestTimeoutMs),l=new Headers(e.headers);o===null?l.delete("authorization"):l.set("authorization",o);try{let p=await oe(s,{...e,headers:l,redirect:"manual",signal:d.signal},n,r);if(p.status<300||p.status>=400)return{response:p,body:await at(p,n.maxResponseBytes),url:s};let g=p.headers.get("location");if(!g||a===n.maxRedirects)throw new u(-32603,"A2A redirect limit exceeded.");let f=new URL(g,s);await p.body?.cancel(),f.origin!==s.origin&&(o=null),s=f}finally{clearTimeout(c)}}throw new u(-32603,"A2A redirect limit exceeded.")}i(W,"safeA2AFetch");function X(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}i(X,"decodeUtf8");import{createHash as dt,randomUUID as ie}from"node:crypto";function V(t){return Array.isArray(t)?`[${t.map(V).join(",")}]`:A(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${V(t[e])}`).join(",")}}`:JSON.stringify(t)??"null"}i(V,"stableJson");function Re(t){return`sha256:${dt("sha256").update(t).digest("hex")}`}i(Re,"sha256");function N(t){let e=t.executorConfig;if(!A(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.");return{agentCardUrl:e.agentCardUrl,interfaceUrl:e.interfaceUrl,...typeof e.tenant=="string"?{tenant:e.tenant}:{}}}i(N,"executorConfig");function ct(t){let e=t.supportedInterfaces.find(n=>n.protocolBinding.toUpperCase()==="JSONRPC"&&n.protocolVersion==="1.0");if(!e)throw new Error("Agent Card has no supported A2A 1.0 JSONRPC interface.");return e}i(ct,"chooseInterface");function de(t,e){try{return JSON.parse(t)}catch{throw new Error(`${e} returned invalid JSON.`)}}i(de,"parseJson");async function be(t,e){let n=await W(new URL(t.agentCardUrl),{headers:{accept:"application/json"}},e.networkPolicy,e.fetch);if(!n.response.ok)throw new Error(`Agent Card request failed with HTTP ${n.response.status}.`);if(!n.response.headers.get("content-type")?.toLowerCase().includes("json"))throw new Error("Agent Card response is not JSON.");let r=he(de(X(n.body),"Agent Card")),s=ct(r),o=V({agentCardUrl:n.url.href,interfaceUrl:s.url,protocolBinding:s.protocolBinding,protocolVersion:s.protocolVersion,tenant:s.tenant??""}),a=Re(V(r));return{agentCard:r,registration:{agentId:t.agentId,displayName:r.name,description:r.description,enabled:!0,executorId:L,protocol:"a2a",configurationRevision:a,endpointIdentityHash:Re(o),...t.credentialRef?{credentialRef:t.credentialRef}:{},executorConfig:{agentCardUrl:n.url.href,interfaceUrl:s.url,...s.tenant?{tenant:s.tenant}:{}},skills:r.skills.map(d=>d.id),inputModalities:r.defaultInputModes,outputModalities:r.defaultOutputModes,capabilities:{streaming:r.capabilities.streaming?"supported":"unsupported",durableTasks:"supported",inputRequired:"supported",cancellation:"supported",artifacts:"supported"},effects:{remote:t.effects.remote,workspace:"proposal"},health:{status:"healthy",checkedAt:new Date().toISOString()}}}}i(be,"discoverA2ARegistration");function ce(t){return t.metadata??{}}i(ce,"metadata");function Ee(t){let e=ce(t).directMessage;return e===void 0?void 0:v(e)}i(Ee,"directMessage");function ve(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]}i(ve,"taskState");function Q(t){return t.flatMap(e=>e.text===void 0?[]:[e.text]).join(`
3
- `)}i(Q,"textFromParts");function ut(t){let e=t.parts.find(n=>n.url!==void 0);return{name:t.name??t.artifactId,...t.parts[0]?.mediaType?{mimeType:t.parts[0].mediaType}:{},...e?.url?{uri:e.url}:{},provenance:"a2a"}}i(ut,"artifactReference");function G(t){let e=(t.artifacts??[]).flatMap(s=>Q(s.parts)),n=t.status.message?Q(t.status.message.parts):"",r=[...e,n].filter(Boolean).join(`
4
- `);return{state:ve(t.status.state),...r?{output:r}:{},...t.status.state==="TASK_STATE_FAILED"?{error:n||"Remote A2A task failed."}:{},...t.artifacts?.length?{artifacts:t.artifacts.map(ut)}:{}}}i(G,"snapshotFromTask");function ae(t){return{state:"completed",output:Q(t.parts)}}i(ae,"snapshotFromMessage");function xe(t){return t==="completed"||t==="failed"||t==="canceled"||t==="rejected"}i(xe,"isTerminal");var ue=class{constructor(e,n,r){this.registration=e;this.context=n;this.options=r}registration;context;options;static{i(this,"A2AClientExecutor")}#e=!1;#t=new Set;async preflight(){try{return N(this.registration),{ok:!0}}catch(e){return{ok:!1,reasons:[e instanceof Error?e.message:String(e)]}}}async start(e){let n=e.idempotencyKey;if(!n)throw new Error("A2A executor requires an idempotency key.");let r=await this.sendMessage({message:{messageId:n,role:"ROLE_USER",parts:[{text:e.input??e.objective,mediaType:"text/plain"}]},configuration:{returnImmediately:!0}});if(A(r.task)){let s=I(r.task);return{idempotencyKey:n,remoteTaskId:s.id,metadata:{contextId:s.contextId}}}if(r.message!==void 0)return{idempotencyKey:n,metadata:{directMessage:v(r.message)}};throw new Error("A2A SendMessage returned neither task nor message.")}async*events(e){let n=Ee(e);if(n){yield ae(n);return}if(this.registration.capabilities.streaming==="supported"&&!this.registration.credentialRef)try{yield*this.streamEvents(e);return}catch(r){if(this.#e)return;M({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,xe(r.state)||r.state==="input-required"||r.state==="auth-required")return;await new Promise(s=>setTimeout(s,this.options.pollIntervalMs))}}async get(e){let n=Ee(e);if(n)return ae(n);if(!e.remoteTaskId)throw new Error("A2A task reference has no remote task ID.");return G(I(await this.rpc("GetTask",this.taskParams(e))))}async sendInput(e,n){if(!e.remoteTaskId)throw new Error("Direct A2A responses cannot accept input.");await this.sendMessage({message:{messageId:ie(),taskId:e.remoteTaskId,...typeof ce(e).contextId=="string"?{contextId:ce(e).contextId}:{},role:"ROLE_USER",parts:[{text:n.content,mediaType:"text/plain"}]},configuration:{returnImmediately:!0}})}async cancel(e){return e.remoteTaskId?G(I(await this.rpc("CancelTask",this.taskParams(e)))):this.get(e)}async reconcile(e){return this.get(e)}async dispose(){this.#e=!0;for(let e of this.#t)e.abort(new Error("A2A executor disposed."))}async*streamEvents(e){if(!e.remoteTaskId)throw new Error("A2A stream requires a remote task ID.");let n=N(this.registration),r=new URL(n.interfaceUrl),s=new Headers({accept:"text/event-stream","a2a-version":"1.0","content-type":"application/json"});this.options.authorization&&s.set("authorization",this.options.authorization);let o=new AbortController;this.#t.add(o);let a,d=i(()=>{a!==void 0&&clearTimeout(a),a=void 0},"disarmTimeout"),c=i(l=>{d(),a=setTimeout(()=>o.abort(new Error(l)),this.options.networkPolicy.requestTimeoutMs),a.unref?.()},"armTimeout");try{c("A2A stream connection timed out.");let l=await oe(r,{method:"POST",headers:s,redirect:"manual",signal:o.signal,body:JSON.stringify({jsonrpc:"2.0",id:ie(),method:"SubscribeToTask",params:this.taskParams(e)})},this.options.networkPolicy,this.options.fetch);if(d(),!l.ok||!l.body)throw new Error(`A2A stream failed with HTTP ${l.status}.`);if(!l.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream"))throw new Error("A2A stream returned an invalid content type.");let p=l.body.getReader(),g=new TextDecoder,f="",E=0;for(;!this.#e;){c("A2A stream was idle for too long.");let b=await p.read();if(d(),b.done)break;if(E+=b.value.byteLength,E>this.options.networkPolicy.maxResponseBytes)throw new Error("A2A stream exceeded the response size limit.");f+=g.decode(b.value,{stream:!0});let J=f.split(/\r?\n\r?\n/);f=J.pop()??"";for(let z of J){let re=z.split(/\r?\n/).filter(se=>se.startsWith("data:")).map(se=>se.slice(5).trimStart()).join(`
5
- `);if(!re)continue;let x=this.snapshotFromStreamPayload(de(re,"A2A stream"));if(x&&(yield x,x.state&&(xe(x.state)||x.state==="input-required"||x.state==="auth-required")))return}}}finally{d(),this.#t.delete(o)}}snapshotFromStreamPayload(e){if(!A(e))throw new Error("A2A stream frame is invalid.");if(e.error!==void 0){let n=A(e.error)?e.error:{};throw new u(typeof n.code=="number"?n.code:-32603,typeof n.message=="string"?n.message:"A2A stream error.")}if(A(e.result)){if(e.result.task!==void 0)return G(I(e.result.task));if(e.result.message!==void 0)return ae(v(e.result.message));if(A(e.result.statusUpdate)&&A(e.result.statusUpdate.status)){let n=e.result.statusUpdate.status.state;if(typeof n!="string")throw new Error("A2A status update has no state.");let r=e.result.statusUpdate.status.message,s=r===void 0?"":Q(v(r).parts);return{state:ve(n),...s?{output:s}:{}}}if(A(e.result.artifactUpdate)&&e.result.artifactUpdate.artifact!==void 0){let n=I({id:"stream-artifact",contextId:"stream-artifact",status:{state:"TASK_STATE_WORKING"},artifacts:[e.result.artifactUpdate.artifact]});return G(n)}}}taskParams(e){let n=N(this.registration);return{id:e.remoteTaskId,...n.tenant?{tenant:n.tenant}:{}}}async sendMessage(e){let n=await this.rpc("SendMessage",{...e,...N(this.registration).tenant?{tenant:N(this.registration).tenant}:{}});if(!A(n))throw new Error("A2A SendMessage result is invalid.");return n}async rpc(e,n){if(this.#e)throw new Error("A2A executor is disposed.");let r=i(s=>this.rpcWithAuthorization(e,n,s),"run");return this.registration.credentialRef?this.context.withCredential(this.registration.credentialRef,s=>r(`Bearer ${s}`)):r(this.options.authorization)}async rpcWithAuthorization(e,n,r){let s=N(this.registration),o=new Headers({accept:"application/json","a2a-version":"1.0","content-type":"application/json"});r&&o.set("authorization",r);let a=await W(new URL(s.interfaceUrl),{method:"POST",headers:o,body:JSON.stringify({jsonrpc:"2.0",id:ie(),method:e,params:n})},this.options.networkPolicy,this.options.fetch);if(!a.response.headers.get("content-type")?.toLowerCase().includes("json"))throw new Error("A2A JSON-RPC response has an invalid content type.");let d=de(X(a.body),"A2A endpoint");if(!A(d))throw new Error("A2A JSON-RPC response is invalid.");let c=d;if(c.error)throw new u(c.error.code,c.error.message,a.response.status);if(!a.response.ok)throw new Error(`A2A request failed with HTTP ${a.response.status}.`);return c.result}};function Ie(t){return{executorId:L,protocol:"a2a",async create(e,n){let r=typeof t=="function"?t(e):t;return new ue(e,n,r)}}}i(Ie,"createA2AAgentExecutorFactory");import{createHash as At,randomUUID as K}from"node:crypto";import j from"node:fs";import{createServer as pt}from"node:http";import U from"node:path";import{Readable as Pe}from"node:stream";import k from"node:fs";import le from"node:path";function _(t){return structuredClone(t)}i(_,"clone");function lt(t){if(!A(t))throw new Error("A2A task store record must be an object.");for(let e of["taskId","contextId","principalKey","runtimeIdentity","sessionId","createdAt","updatedAt"])if(typeof t[e]!="string")throw new Error(`A2A task store record has invalid ${e}.`);if(!A(t.messageDigests)||!Object.values(t.messageDigests).every(e=>typeof e=="string"))throw new Error("A2A task store message digests are invalid.");if(!Array.isArray(t.runIds)||!t.runIds.every(e=>typeof e=="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(!Number.isSafeInteger(t.eventSeq)||!Number.isSafeInteger(t.lastRuntimeEventSeq))throw new Error("A2A task store event cursors are invalid.");return{taskId:t.taskId,contextId:t.contextId,principalKey:t.principalKey,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:I(t.task),history:t.history,createdAt:t.createdAt,updatedAt:t.updatedAt,eventSeq:t.eventSeq,lastRuntimeEventSeq:t.lastRuntimeEventSeq,runtimeEventCount:Number.isSafeInteger(t.runtimeEventCount)?t.runtimeEventCount:0,runtimeEventBytes:Number.isSafeInteger(t.runtimeEventBytes)?t.runtimeEventBytes:0}}i(lt,"parseRecord");var Z=class{static{i(this,"A2AFileTaskStore")}#e=new Map;#t=new Map;#n;#r;#s;constructor(e){let n=le.resolve(e);k.mkdirSync(n,{recursive:!0,mode:448}),this.#n=le.join(n,"tasks.json"),this.#r=le.join(n,".server.lock"),this.#s=this.acquireLock();try{this.load()}catch(r){throw k.closeSync(this.#s),k.rmSync(this.#r,{force:!0}),r}}get(e){let n=this.#e.get(e);return n?_(n):void 0}findByMessage(e,n){for(let r of this.#e.values())if(r.principalKey===e&&r.messageDigests[n]!==void 0)return _(r)}list(e){return[...this.#e.values()].filter(n=>n.principalKey===e).sort((n,r)=>r.updatedAt.localeCompare(n.updatedAt)).map(_)}all(){return[...this.#e.values()].map(_)}save(e){let n=_(e);this.#e.set(e.taskId,n),this.persist();for(let r of this.#t.get(e.taskId)??[])r(_(n));return _(n)}subscribe(e,n){let r=this.#t.get(e)??new Set;return r.add(n),this.#t.set(e,r),()=>{r.delete(n),r.size===0&&this.#t.delete(e)}}close(){this.persist(),this.#t.clear(),k.closeSync(this.#s),k.rmSync(this.#r,{force:!0})}acquireLock(){let e=i(()=>{let n=k.openSync(this.#r,"wx",384);return k.writeFileSync(n,`${process.pid}
6
- `,"utf8"),k.fsyncSync(n),n},"attempt");try{return e()}catch(n){let r=!1;try{let s=Number.parseInt(k.readFileSync(this.#r,"utf8").trim(),10);if(Number.isSafeInteger(s)&&s>0)try{process.kill(s,0)}catch{r=!0}}catch{r=!1}if(!r)throw new Error("A2A task store is already owned by another server.",{cause:n});return k.rmSync(this.#r,{force:!0}),e()}}load(){if(!k.existsSync(this.#n))return;let e;try{e=JSON.parse(k.readFileSync(this.#n,"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=lt(n);this.#e.set(r.taskId,r)}}persist(){let e=`${this.#n}.${process.pid}.tmp`;k.writeFileSync(e,`${JSON.stringify([...this.#e.values()],null,2)}
7
- `,{encoding:"utf8",mode:384}),k.renameSync(e,this.#n)}};var R=new Set(["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_REJECTED"]),ft=new Set(["CreateTaskPushNotificationConfig","GetTaskPushNotificationConfig","ListTaskPushNotificationConfigs","DeleteTaskPushNotificationConfig"]);function y(t){return t().toISOString()}i(y,"nowIso");function P(t){return At("sha256").update(t).digest("hex")}i(P,"sha256");function O(t){return P(`${t.subject}\0${t.tenant??""}`)}i(O,"principalKey");function Oe(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}i(Oe,"isLoopbackHostname");function gt(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Oe(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}i(gt,"validateBaseUrl");function mt(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 u(-32601,"Method not found.");return n}i(mt,"operationForMethod");function yt(t){return{queued:"TASK_STATE_SUBMITTED",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]}i(yt,"statusState");function Ce(t,e,n){return{messageId:K(),taskId:t,contextId:e,role:"ROLE_AGENT",parts:[{text:n,mediaType:"text/plain"}]}}i(Ce,"agentMessage");function Ae(t,e=t.agent.publicBaseUrl){let n=new URL("/",gt(e)).href;return{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}}i(Ae,"buildCard");function $(t,e=200,n){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8",...n}})}i($,"jsonResponse");async function ht(t,e){let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new u(-32600,"A2A request exceeds the configured limit.",413);if(!t.body)return new Uint8Array;let r=[],s=0,o=t.body.getReader();for(;;){let c=await o.read();if(c.done)break;if(s+=c.value.byteLength,s>e)throw await o.cancel("A2A request size limit exceeded."),new u(-32600,"A2A request exceeds the configured limit.",413);r.push(c.value)}let a=new Uint8Array(s),d=0;for(let c of r)a.set(c,d),d+=c.byteLength;return a}i(ht,"readBoundedBody");function B(t,e){return $({jsonrpc:"2.0",id:t,result:e})}i(B,"rpcResult");function wt(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],s=e.data??(r?[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:r,domain:"kodax.ai"}]:void 0);return $({jsonrpc:"2.0",id:t,error:{code:e.code,message:e.message,...s!==void 0?{data:s}:{}}},e.httpStatus)}i(wt,"rpcError");function _e(t){return P(JSON.stringify(t))}i(_e,"messageDigest");function kt(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))}i(kt,"partBytes");function Ue(t){if(!j.existsSync(t))return 0;let e=0;for(let n of j.readdirSync(t,{withFileTypes:!0})){let r=U.join(t,n.name);n.isSymbolicLink()||(n.isDirectory()?e+=Ue(r):n.isFile()&&(e+=j.statSync(r).size))}return e}i(Ue,"directoryBytes");function Tt(t,e,n){if(t.role!=="ROLE_USER")throw new u(-32602,"Inbound message role must be ROLE_USER.");for(let r of t.parts){if(kt(r)>e)throw new u(-32602,"Message Part exceeds the configured limit.");if(r.url!==void 0)throw new u(-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 u(-32602,"Message Part raw content is not valid base64.");let s=r.mediaType??(r.text!==void 0?"text/plain":r.data!==void 0?"application/json":"application/octet-stream");if(!n.includes(s))throw new u(-32005,`Media type ${s} is not supported.`)}}i(Tt,"validateInput");function St(t,e,n){if(n===0){let{history:s,...o}=t;return o}let r=n===void 0?e:e.slice(-n);return{...t,history:r}}i(St,"withHistory");var Y=class{constructor(e){this.options=e;this.#t=e.now??(()=>new Date),this.#e=new Z(e.dataDir),this.#i=Ae(e),this.#d=this.recover()}options;static{i(this,"KodaXA2AServerRuntime")}#e;#t;#n=new Map;#r=new Set;#s=new Map;#d;#a;#o=!1;#i;#c;get agentCard(){return structuredClone(this.#i)}async whenReady(){await this.#d}updateHot(e){if(this.#o)throw new Error("A2A server is closed.");this.options={...this.options,...e},this.#i=Ae(this.options,e.agent.publicBaseUrl)}async handle(e){if(await this.#d,this.#o)return $({error:"A2A server is closed."},503);let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/.well-known/agent-card.json"){let r=JSON.stringify(this.#i);return $(this.#i,200,{etag:`"${P(r)}"`,"cache-control":"public, max-age=300"})}return e.method!=="POST"||n.pathname!=="/"&&n.pathname!=="/a2a"?$({error:"Not found."},404):this.handleRpc(e)}async listen(e){if(this.#a)throw new Error("A2A server is already listening.");if(!Oe(e.hostname))throw new Error("The built-in A2A HTTP listener is loopback-only; use handle() behind TLS for public service.");let n=pt((o,a)=>{this.handleNodeRequest(o).then(d=>{if(a.statusCode=d.status,d.headers.forEach((c,l)=>a.setHeader(l,c)),!d.body){a.end();return}Pe.fromWeb(d.body).pipe(a)}).catch(d=>{let c=P(q(d)).slice(0,16);this.emit({type:"server.request_failed",time:y(this.#t),outcome:"failed",diagnosticId:c}),a.statusCode=500,a.setHeader("content-type","application/json; charset=utf-8"),a.end(JSON.stringify({error:"Internal server error.",diagnosticId:c}))})});this.#a=n,await new Promise((o,a)=>{n.once("error",a),n.listen(e.port,e.hostname,o)});let r=n.address();if(!r||typeof r=="string")throw new Error("A2A server did not expose a TCP address.");let s=`http://${e.hostname}:${r.port}`;return this.#c=e.publicBaseUrl??s,this.#i=Ae(this.options,this.#c),s}async close(){if(this.#o)return;this.#o=!0;for(let n of this.#r)n();this.#r.clear();for(let n of this.#n.values())n.close();this.#n.clear(),this.#e.close();let e=this.#a;this.#a=void 0,e&&await new Promise((n,r)=>e.close(s=>s?r(s):n())),await this.options.preparedExecution?.close()}async handleNodeRequest(e){let r=`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,s=new Headers;for(let[a,d]of Object.entries(e.headers))if(typeof d=="string")s.set(a,d);else for(let c of d??[])s.append(a,c);let o={method:e.method,headers:s,...e.method==="GET"||e.method==="HEAD"?{}:{body:Pe.toWeb(e)},duplex:"half"};return this.handle(new Request(r,o))}async handleRpc(e){let n=this.options,r=null;try{let s=e.headers.get("a2a-version");if(s&&s!=="1.0")throw new u(-32009,"A2A version is not supported.");if(!e.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new u(-32600,"A2A JSON-RPC requests require application/json.",415);let o=await ht(e,n.limits.maxRequestBytes),a;try{a=JSON.parse(new TextDecoder().decode(o))}catch{throw new u(-32700,"Invalid JSON payload.")}let d=ke(a);r=d.id;let c=await n.authentication.authenticate(e);if(!c)throw new u(-32600,"Authentication required.",401);if(ft.has(d.method))throw new u(-32003,"Push notifications are not supported.");let l=mt(d.method),p=typeof d.params?.id=="string"?d.params.id:A(d.params?.message)&&typeof d.params.message.taskId=="string"?d.params.message.taskId:void 0;if(!await n.authorize({principal:c,operation:l,...p?{taskId:p}:{}}))throw new u(-32001,"Task not found.");return await this.dispatch(d,c,n)}catch(s){let o=P(q(s)).slice(0,16),a=s instanceof u?s:new u(-32603,"Internal error.",500,[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:"INTERNAL",domain:"kodax.ai",metadata:{diagnosticId:o}}]);return this.emit({type:"rpc.failed",time:y(this.#t),outcome:"failed",diagnosticId:o}),wt(r,a)}}async dispatch(e,n,r){switch(e.method){case"SendMessage":return B(e.id,{task:await this.sendMessage(e.params,n,!1,r)});case"SendStreamingMessage":{let s=await this.sendMessage(e.params,n,!0,r);return this.streamTask(e.id,s.id,O(n))}case"GetTask":return B(e.id,await this.getTask(e.params,n));case"ListTasks":return B(e.id,this.listTasks(e.params,n));case"CancelTask":return B(e.id,await this.cancelTask(e.params,n,r));case"SubscribeToTask":return this.subscribeTask(e.id,e.params,n);case"GetExtendedAgentCard":{if(!r.extendedAgentCard)throw new u(-32007,"Extended Agent Card is not configured.");return B(e.id,r.extendedAgentCard)}default:throw new u(-32601,"Method not found.")}}async sendMessage(e,n,r,s){let o=O(n),a=this.#s.get(o)??Promise.resolve(),d=i(()=>{},"release"),c=new Promise(l=>{d=l});this.#s.set(o,c),await a;try{return await this.sendMessageUnserialized(e,n,r,s)}finally{d(),this.#s.get(o)===c&&this.#s.delete(o)}}async sendMessageUnserialized(e,n,r,s){let o=v(e?.message);Tt(o,s.limits.maxPartBytes,s.agent.inputModes);let a=O(n),d=_e(o),c=this.#e.findByMessage(a,o.messageId);if(c){if(c.messageDigests[o.messageId]!==d)throw new u(-32602,"Message ID was reused with different content.");return this.emit({type:"task.deduplicated",time:y(this.#t),taskId:c.taskId,contextId:c.contextId}),c.task}let l=o.taskId?this.requireOwnedTask(o.taskId,a):void 0;if(l&&o.contextId!==void 0&&o.contextId!==l.contextId)throw new u(-32602,"Message contextId does not match the task.");if(l&&l.task.status.state!=="TASK_STATE_INPUT_REQUIRED"&&l.task.status.state!=="TASK_STATE_AUTH_REQUIRED")throw new u(-32004,"Task is not waiting for input.");let p=this.#e.list(a),g=s.limits.maxRetainedTasksPerPrincipal??s.limits.maxTasksPerPrincipal??100;if(!l&&p.length>=g)throw new u(-32004,"Principal task limit reached.");let f=p.filter(x=>!R.has(x.task.status.state)).length;if(!l&&f>=(s.limits.maxActiveTasksPerPrincipal??4))throw new u(-32004,"Principal active task limit reached.");let E=this.#e.all().filter(x=>!R.has(x.task.status.state)).length;if(!l&&E>=s.limits.maxConcurrentTasks)throw new u(-32004,"Server task concurrency limit reached.");let b=l??await this.createRecord(o,a,s),J=l?this.appendMessage(b,o,d):b,z=await this.startRun(J,o,s);return r||A(e?.configuration)&&e.configuration.returnImmediately===!0?z.task:(await this.waitForTask(z.taskId,s.limits.maxTaskWaitMs??3e4)).task}async createRecord(e,n,r){let s=e.contextId??K(),o=this.#e.list(n).find(g=>g.contextId===s),a=P(`${n}\0${s}`),d=o?.workspaceRoot??await r.preparedExecution?.prepareWorkspace(a),c=o?{id:o.sessionId}: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}:{}}),l=K(),p=y(this.#t);return this.#e.save({taskId:l,contextId:s,principalKey:n,runtimeIdentity:r.runtime.identity.runtimeId,sessionId:c.id,...d?{workspaceRoot:d}:{},...r.preparedExecution?{executionPolicyRevision:r.preparedExecution.binding.executionPolicyRevision}:{},messageDigests:{[e.messageId]:_e(e)},runIds:[],task:{id:l,contextId:s,status:{state:"TASK_STATE_SUBMITTED",timestamp:p},history:[{...e,taskId:l,contextId:s}]},history:[{...e,taskId:l,contextId:s}],createdAt:p,updatedAt:p,eventSeq:1,lastRuntimeEventSeq:0,runtimeEventCount:0,runtimeEventBytes:0})}appendMessage(e,n,r){let s={...n,taskId:e.taskId,contextId:e.contextId};return this.#e.save({...e,messageDigests:{...e.messageDigests,[n.messageId]:r},history:[...e.history,s],task:{...e.task,history:[...e.history,s]},updatedAt:y(this.#t),eventSeq:e.eventSeq+1})}async startRun(e,n,r){let s=await this.inputsForMessage(e.taskId,n,r),o=r.preparedExecution;if(o&&e.executionPolicyRevision!==o.binding.executionPolicyRevision)throw new u(-32004,"A2A task execution binding revision changed.");let a=o?await o.start({sessionId:e.sessionId,inputs:s,principalKey:e.principalKey}):await r.runtime.runs.start({sessionId:e.sessionId,input:s,mode:"managed_task",permissionBroker:"runtime",...r.agent.runOptions?{options:r.agent.runOptions}:{},agentContext:{actorId:`a2a:${e.principalKey.slice(0,16)}`}}),d=this.#e.save({...e,runIds:[...e.runIds,a.runId],task:{...e.task,status:{state:"TASK_STATE_WORKING",timestamp:y(this.#t)}},updatedAt:y(this.#t),eventSeq:e.eventSeq+1});return this.subscribeRuntime(d,a.runId,r),a.result.then(c=>this.finishRun(d.taskId,c)).catch(c=>{this.failTask(d.taskId,q(c))}),this.emit({type:"task.started",time:y(this.#t),taskId:d.taskId,contextId:d.contextId,runId:a.runId,outcome:"accepted"}),d}async inputsForMessage(e,n,r){let s=[];for(let o of n.parts){if(o.text!==void 0){s.push({type:"text",text:o.text});continue}s.push(await this.materializePart(e,o,r))}return s}async materializePart(e,n,r){let s=n.mediaType??(n.data!==void 0?"application/json":"application/octet-stream"),o=n.data!==void 0?".json":".bin",a=this.#e.get(e),d=a?.workspaceRoot?U.join(a.workspaceRoot,"inbox",P(e)):U.join(U.resolve(r.dataDir),"attachments",P(e));j.mkdirSync(d,{recursive:!0,mode:448});let c=n.data!==void 0?Buffer.from(JSON.stringify(n.data),"utf8"):Buffer.from(n.raw??"","base64"),l=r.limits.maxWorkspaceBytesPerContext??1073741824;if(a?.workspaceRoot&&Ue(a.workspaceRoot)+c.byteLength>l)throw new u(-32004,"A2A context workspace size limit reached.");let p=n.filename?U.basename(n.filename).replace(/[^A-Za-z0-9._-]/g,"_"):`${K()}${o}`,g=U.join(d,`${K()}-${p}`);j.writeFileSync(g,c,{mode:384});let f=s.startsWith("image/")?"image":s.startsWith("video/")?"video":"file";return{type:"artifact_ref",artifactId:(await r.runtime.artifacts.create({kind:f,path:g,mediaType:s,mimeType:s,...n.filename?{name:U.basename(n.filename)}:{},source:"user-inline",description:"Inbound A2A message part"})).id,description:"Inbound A2A attachment"}}subscribeRuntime(e,n,r){this.#n.get(e.taskId)?.close();let s=r.runtime.events.subscribe({runId:n},o=>this.onRuntimeEvent(e.taskId,o,r));this.#n.set(e.taskId,s)}onRuntimeEvent(e,n,r){let s=this.#e.get(e);if(!s||R.has(s.task.status.state))return;let o=Buffer.byteLength(JSON.stringify(n)),a=s.runtimeEventCount+1,d=s.runtimeEventBytes+o;if(a>(r.limits.maxEventsPerTask??1e3)||d>(r.limits.maxEventBytesPerTask??16777216)){let l=s.runIds.at(-1);l&&r.runtime.runs.abort(l),this.failTask(e,"A2A task event quota exceeded.");return}let c=n.type==="user_input.requested"?"TASK_STATE_INPUT_REQUIRED":s.task.status.state;this.#e.save({...s,task:{...s.task,status:{...s.task.status,state:c,timestamp:n.time}},updatedAt:n.time,eventSeq:s.eventSeq+1,lastRuntimeEventSeq:Math.max(s.lastRuntimeEventSeq,n.seq),runtimeEventCount:a,runtimeEventBytes:d})}finishRun(e,n){if(this.#o)return;let r=this.#e.get(e);if(!r||R.has(r.task.status.state))return;let s=yt(n.phase),o=n.result?.lastText??n.error?.message??"",a=o?Ce(e,r.contextId,o):void 0,d=a?[...r.history,a]:r.history,c=o?[{artifactId:`final-${e}`,name:"final-output",parts:[{text:o,mediaType:"text/plain"}]}]:void 0;this.#e.save({...r,history:d,task:{...r.task,status:{state:s,...a?{message:a}:{},timestamp:y(this.#t)},...c?{artifacts:c}:{},history:d},updatedAt:y(this.#t),eventSeq:r.eventSeq+1}),this.#n.get(e)?.close(),this.#n.delete(e),this.emit({type:"task.finished",time:y(this.#t),taskId:e,contextId:r.contextId,outcome:s==="TASK_STATE_COMPLETED"?"completed":"failed"})}failTask(e,n){if(this.#o)return;let r=this.#e.get(e);if(!r||R.has(r.task.status.state))return;let s=Ce(e,r.contextId,n);this.#e.save({...r,task:{...r.task,status:{state:"TASK_STATE_FAILED",message:s,timestamp:y(this.#t)}},updatedAt:y(this.#t),eventSeq:r.eventSeq+1})}async getTask(e,n){let r=typeof e?.id=="string"?e.id:"",s=this.requireOwnedTask(r,O(n)),o=typeof e?.historyLength=="number"?e.historyLength:void 0;return St(s.task,s.history,o)}listTasks(e,n){let r=this.#e.list(O(n)).filter(c=>!(typeof e?.contextId=="string"&&c.contextId!==e.contextId||typeof e?.status=="string"&&c.task.status.state!==e.status)),s=typeof e?.pageSize=="number"?Math.max(1,Math.min(100,Math.floor(e.pageSize))):50,o=typeof e?.pageToken=="string"&&e.pageToken?Number(Buffer.from(e.pageToken,"base64url").toString("utf8")):0;if(!Number.isSafeInteger(o)||o<0)throw new u(-32602,"Invalid page token.");let a=r.slice(o,o+s),d=o+a.length;return{tasks:a.map(c=>e?.includeArtifacts===!0?c.task:{...c.task,artifacts:void 0}),nextPageToken:d<r.length?Buffer.from(String(d)).toString("base64url"):"",pageSize:s,totalSize:r.length}}async cancelTask(e,n,r){let s=typeof e?.id=="string"?e.id:"",o=this.requireOwnedTask(s,O(n));if(R.has(o.task.status.state))throw new u(-32002,"Task is not cancelable.");let a=o.runIds.at(-1);return a&&await r.runtime.runs.abort(a),this.#e.save({...o,task:{...o.task,status:{state:"TASK_STATE_CANCELED",timestamp:y(this.#t)}},updatedAt:y(this.#t),eventSeq:o.eventSeq+1}).task}subscribeTask(e,n,r){let s=typeof n?.id=="string"?n.id:"",o=this.requireOwnedTask(s,O(r));if(R.has(o.task.status.state))throw new u(-32004,"Cannot subscribe to a terminal task.");return this.streamTask(e,s,o.principalKey)}streamTask(e,n,r){let s=this.requireOwnedTask(n,r),o=new TextEncoder,a,d=i(()=>{},"cleanup"),c=!1,l=new ReadableStream({start:i(p=>{let g=i(()=>{c||(c=!0,d(),p.close())},"close");if(d=i(()=>{a?.(),this.#r.delete(g)},"cleanup"),this.#r.add(g),p.enqueue(o.encode(this.sse(e,{task:s.task}))),R.has(s.task.status.state)){g();return}a=this.#e.subscribe(n,f=>{p.enqueue(o.encode(this.sse(e,{statusUpdate:{taskId:n,contextId:f.contextId,status:f.task.status}}))),(R.has(f.task.status.state)||f.task.status.state==="TASK_STATE_INPUT_REQUIRED"||f.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&g()})},"start"),cancel:i(()=>{c||(c=!0,d())},"cancel")});return new Response(l,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}sse(e,n){return`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:n})}
2
+ import"./chunks/chunk-XNQ2O7NI.js";import"./chunks/chunk-K7RYV2SE.js";import{f as Se,k as Re,l as Ee}from"./chunks/chunk-P2UKNYYS.js";import"./chunks/chunk-WW2O2DEP.js";import"./chunks/chunk-4P4L3WEK.js";import"./chunks/chunk-F4NOOBRZ.js";import"./chunks/chunk-GOQRVDFP.js";import"./chunks/chunk-RY5OLVQV.js";import"./chunks/chunk-I4TPQEJN.js";import"./chunks/chunk-Y4WOTWUC.js";import"./chunks/chunk-AQGNRBEJ.js";import"./chunks/chunk-UJEMSPM5.js";import"./chunks/chunk-7PV577LP.js";import{b as q}from"./chunks/chunk-AWMTNUDS.js";import"./chunks/chunk-F7C7J6IM.js";import"./chunks/chunk-NGHQIGVW.js";import{a as o}from"./chunks/chunk-ONUPGMER.js";var N="1.0",j="kodax-a2a-v1-jsonrpc";var u=class extends Error{constructor(n,r,s=200,i){super(r);this.code=n;this.httpStatus=s;this.data=i;this.name="A2AError"}code;httpStatus;data;static{o(this,"A2AError")}};function V(t){return t instanceof Error?t.message:String(t)}o(V,"errorMessage");var tt=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 f(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}o(f,"isRecord");function b(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new u(-32602,`${n}.${e} must be a non-empty string.`);return r}o(b,"requiredString");function h(t,e){let n=t[e];return typeof n=="string"&&n.length>0?n:void 0}o(h,"optionalString");function K(t,e){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new u(-32602,`${e} must be a string array.`);return t}o(K,"stringArray");function nt(t){if(!f(t))throw new u(-32602,"Agent Card interface is invalid.");return{url:b(t,"url","interface"),protocolBinding:b(t,"protocolBinding","interface"),protocolVersion:b(t,"protocolVersion","interface"),...h(t,"tenant")?{tenant:h(t,"tenant")}:{}}}o(nt,"parseInterface");function rt(t){if(!f(t))throw new u(-32602,"Agent Card skill is invalid.");return{id:b(t,"id","skill"),name:b(t,"name","skill"),description:b(t,"description","skill"),tags:K(t.tags,"skill.tags"),...Array.isArray(t.examples)?{examples:K(t.examples,"skill.examples")}:{},...Array.isArray(t.inputModes)?{inputModes:K(t.inputModes,"skill.inputModes")}:{},...Array.isArray(t.outputModes)?{outputModes:K(t.outputModes,"skill.outputModes")}:{}}}o(rt,"parseSkill");function xe(t){if(!f(t))throw new u(-32602,"Agent Card must be an object.");let e=t.supportedInterfaces,n=t.skills;if(!Array.isArray(e)||e.length===0)throw new u(-32602,"Agent Card must declare supportedInterfaces.");if(!Array.isArray(n))throw new u(-32602,"Agent Card must declare skills.");if(!f(t.capabilities))throw new u(-32602,"Agent Card capabilities are invalid.");return{name:b(t,"name","Agent Card"),description:b(t,"description","Agent Card"),supportedInterfaces:e.map(nt),version:b(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.filter(f)}:{}},...f(t.securitySchemes)?{securitySchemes:t.securitySchemes}:{},...Array.isArray(t.securityRequirements)?{securityRequirements:t.securityRequirements.filter(f)}:{},defaultInputModes:K(t.defaultInputModes,"Agent Card defaultInputModes"),defaultOutputModes:K(t.defaultOutputModes,"Agent Card defaultOutputModes"),skills:n.map(rt)}}o(xe,"parseA2AAgentCard");function Ie(t){if(!f(t))throw new u(-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 u(-32602,"Message Part must contain exactly one content field.");let n=e[0];if(n!=="data"&&typeof t[n]!="string")throw new u(-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}:{},...f(t.metadata)?{metadata:t.metadata}:{},...h(t,"filename")?{filename:h(t,"filename")}:{},...h(t,"mediaType")?{mediaType:h(t,"mediaType")}:{}}}o(Ie,"parseA2APart");function v(t){if(!f(t))throw new u(-32602,"Message must be an object.");if(t.role!=="ROLE_USER"&&t.role!=="ROLE_AGENT")throw new u(-32602,"Message role is invalid.");if(!Array.isArray(t.parts)||t.parts.length===0)throw new u(-32602,"Message parts must not be empty.");return{messageId:b(t,"messageId","Message"),role:t.role,parts:t.parts.map(Ie),...h(t,"contextId")?{contextId:h(t,"contextId")}:{},...h(t,"taskId")?{taskId:h(t,"taskId")}:{},...f(t.metadata)?{metadata:t.metadata}:{}}}o(v,"parseA2AMessage");function st(t){if(!f(t)||!Array.isArray(t.parts)||t.parts.length===0)throw new u(-32603,"A2A artifact is invalid.");return{artifactId:b(t,"artifactId","Artifact"),parts:t.parts.map(Ie),...h(t,"name")?{name:h(t,"name")}:{},...h(t,"description")?{description:h(t,"description")}:{},...f(t.metadata)?{metadata:t.metadata}:{}}}o(st,"parseArtifact");function _(t){if(!f(t)||!f(t.status))throw new u(-32603,"A2A task is invalid.");let e=t.status.state;if(typeof e!="string")throw new u(-32603,"A2A task state is invalid.");let n=tt.has(e)?e:"TASK_STATE_UNSPECIFIED";return{id:b(t,"id","Task"),contextId:h(t,"contextId")??"",status:{state:n,...t.status.message!==void 0?{message:v(t.status.message)}:{},...h(t.status,"timestamp")?{timestamp:h(t.status,"timestamp")}:{}},...Array.isArray(t.artifacts)?{artifacts:t.artifacts.map(st)}:{},...Array.isArray(t.history)?{history:t.history.map(v)}:{},...f(t.metadata)?{metadata:t.metadata}:{}}}o(_,"parseA2ATask");function be(t){if(!f(t)||t.jsonrpc!=="2.0")throw new u(-32600,"Invalid JSON-RPC request.");if(typeof t.id!="string"&&typeof t.id!="number")throw new u(-32600,"JSON-RPC request id is required.");return{jsonrpc:"2.0",id:t.id,method:b(t,"method","JSON-RPC request"),...f(t.params)?{params:t.params}:{}}}o(be,"parseJsonRpcRequest");import{lookup as it}from"node:dns/promises";import{request as ot}from"node:http";import{request as at}from"node:https";import{isIP as dt}from"node:net";import{Readable as ct}from"node:stream";function de(t){let e=t.split(".").map(Number),[n,r,s,i]=e;return e.length!==4||n===void 0||r===void 0||s===void 0||i===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&&s===0&&i!==9&&i!==10||n===192&&r===0&&s===2||n===198&&(r===18||r===19)||n===198&&r===51&&s===100||n===203&&r===0&&s===113||n>=224}o(de,"isPrivateIpv4");function ut(t){let e=t.toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(e)?.[1];if(n)return de(n);let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(r?.[1]&&r[2]){let s=Number.parseInt(r[1],16),i=Number.parseInt(r[2],16);return de(`${s>>8}.${s&255}.${i>>8}.${i&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(ut,"isPrivateIpv6");function ve(t){let e=dt(t);return e===4?de(t):e===6?ut(t):!0}o(ve,"isPrivateAddress");async function Pe(t,e){if(t.protocol!=="https:"&&t.protocol!=="http:")throw new u(-32602,"A2A URL must use HTTP or HTTPS.");if(!e.allowedOrigins.includes(t.origin))throw new u(-32602,`A2A origin is not allowed: ${t.origin}`);if(t.username||t.password)throw new u(-32602,"A2A URL must not include credentials.");let n=t.hostname.startsWith("[")&&t.hostname.endsWith("]")?t.hostname.slice(1,-1):t.hostname,r=await it(n,{all:!0,verbatim:!0});if(r.length===0)throw new u(-32602,"A2A hostname did not resolve.");if(t.protocol==="http:"&&!r.every(i=>ve(i.address)))throw new u(-32602,"Public A2A targets must use HTTPS.");if(!e.allowPrivateAddresses&&r.some(i=>ve(i.address)))throw new u(-32602,"A2A private network targets are not allowed.");let s=r[0];if(s===void 0||s.family!==4&&s.family!==6)throw new u(-32602,"A2A hostname returned an unsupported address.");return{address:s.address,family:s.family}}o(Pe,"validateA2AUrl");async function lt(t,e){await Pe(t,e)}o(lt,"assertSafeA2AUrl");function At(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 u(-32602,"A2A request body type is not supported by the safe transport.")}o(At,"encodeRequestBody");function pt(t){return((e,n,r)=>{if(typeof n=="object"&&n.all){r(null,[t]);return}r(null,t.address,t.family)})}o(pt,"pinnedLookup");function ft(t,e,n){return new Promise((r,s)=>{let i=new Headers(e.headers);i.set("accept-encoding","identity");let a=(t.protocol==="https:"?at:ot)(t,{method:e.method,headers:Object.fromEntries(i),lookup:pt(n),signal:e.signal??void 0},d=>{let c=new Headers;for(let g=0;g<d.rawHeaders.length;g+=2){let m=d.rawHeaders[g],T=d.rawHeaders[g+1];m!==void 0&&T!==void 0&&c.append(m,T)}let A=d.statusCode??500,p=e.method!=="HEAD"&&A!==204&&A!==205&&A!==304?ct.toWeb(d):null;r(new Response(p,{status:A,statusText:d.statusMessage,headers:c}))});a.once("error",s),a.end(At(e.body))})}o(ft,"requestValidatedAddress");async function ce(t,e,n,r){let s=await Pe(t,n);return r!==void 0?r(t,e):ft(t,e,s)}o(ce,"openSafeA2AResponse");async function gt(t,e){let n=t.headers.get("content-length");if(n&&Number(n)>e)throw new u(-32603,"A2A response is too large.");if(!t.body)return new Uint8Array;let r=t.body.getReader(),s=[],i=0;for(;;){let c=await r.read();if(c.done)break;if(i+=c.value.byteLength,i>e)throw await r.cancel(),new u(-32603,"A2A response is too large.");s.push(c.value)}let a=new Uint8Array(i),d=0;for(let c of s)a.set(c,d),d+=c.byteLength;return a}o(gt,"boundedBody");async function Z(t,e,n,r){let s=t,i=new Headers(e.headers).get("authorization");for(let a=0;a<=n.maxRedirects;a+=1){let d=new AbortController,c=setTimeout(()=>d.abort(new Error("A2A request timed out.")),n.requestTimeoutMs),A=new Headers(e.headers);i===null?A.delete("authorization"):A.set("authorization",i);try{let l=await ce(s,{...e,headers:A,redirect:"manual",signal:d.signal},n,r);if(l.status<300||l.status>=400)return{response:l,body:await gt(l,n.maxResponseBytes),url:s};let p=l.headers.get("location");if(!p||a===n.maxRedirects)throw new u(-32603,"A2A redirect limit exceeded.");let g=new URL(p,s);await l.body?.cancel(),g.origin!==s.origin&&(i=null),s=g}finally{clearTimeout(c)}}throw new u(-32603,"A2A redirect limit exceeded.")}o(Z,"safeA2AFetch");function Y(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}o(Y,"decodeUtf8");import{createHash as mt,randomUUID as ue}from"node:crypto";function ee(t){return Array.isArray(t)?`[${t.map(ee).join(",")}]`:f(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ee(t[e])}`).join(",")}}`:JSON.stringify(t)??"null"}o(ee,"stableJson");function Ce(t){return`sha256:${mt("sha256").update(t).digest("hex")}`}o(Ce,"sha256");function B(t){let e=t.executorConfig;if(!f(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.");return{agentCardUrl:e.agentCardUrl,interfaceUrl:e.interfaceUrl,...typeof e.tenant=="string"?{tenant:e.tenant}:{}}}o(B,"executorConfig");function yt(t,e){let n=t.supportedInterfaces.find(s=>s.protocolBinding.toUpperCase()==="JSONRPC"&&s.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)throw new Error("A2A interface URL must not contain credentials.");if(r.origin!==e.origin)throw new Error("A2A interface must use the same origin as the trusted Agent Card.");return n}o(yt,"chooseInterface");function ht(t){let e=new Set(Object.entries(t.securitySchemes??{}).flatMap(([n,r])=>!f(r)||!f(r.httpAuthSecurityScheme)?[]:typeof r.httpAuthSecurityScheme.scheme=="string"&&r.httpAuthSecurityScheme.scheme.toLowerCase()==="bearer"?[n]:[]));return(t.securityRequirements??[]).some(n=>f(n.schemes)&&Object.keys(n.schemes).some(r=>e.has(r)))}o(ht,"advertisesBearerAuthentication");function Ae(t,e){try{return JSON.parse(t)}catch{throw new Error(`${e} returned invalid JSON.`)}}o(Ae,"parseJson");async function Ue(t,e){let n=await Z(new URL(t.agentCardUrl),{headers:{accept:"application/json"}},e.networkPolicy,e.fetch);if(!n.response.ok)throw new Error(`Agent Card request failed with HTTP ${n.response.status}.`);if(!n.response.headers.get("content-type")?.toLowerCase().includes("json"))throw new Error("Agent Card response is not JSON.");let r=xe(Ae(Y(n.body),"Agent Card")),s=yt(r,n.url);if(t.credentialRef&&!ht(r))throw new Error("Configured A2A credential requires an advertised Bearer security scheme.");let i=ee({agentCardUrl:n.url.href,interfaceUrl:s.url,protocolBinding:s.protocolBinding,protocolVersion:s.protocolVersion,tenant:s.tenant??""}),a=Ce(ee(r));return{agentCard:r,registration:{agentId:t.agentId,displayName:r.name,description:r.description,enabled:!0,executorId:j,protocol:"a2a",configurationRevision:a,endpointIdentityHash:Ce(i),...t.credentialRef?{credentialRef:t.credentialRef}:{},executorConfig:{agentCardUrl:n.url.href,interfaceUrl:s.url,...s.tenant?{tenant:s.tenant}:{}},skills:r.skills.map(d=>d.id),inputModalities:r.defaultInputModes,outputModalities:r.defaultOutputModes,capabilities:{streaming:r.capabilities.streaming?"supported":"unsupported",durableTasks:"supported",inputRequired:"supported",cancellation:"supported",artifacts:"supported"},effects:{remote:t.effects.remote,workspace:"proposal"},health:{status:"healthy",checkedAt:new Date().toISOString()}}}}o(Ue,"discoverA2ARegistration");function H(t){return t.metadata??{}}o(H,"metadata");function _e(t){let e=H(t).directMessage;return e===void 0?void 0:v(e)}o(_e,"directMessage");function wt(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(wt,"taskState");function pe(t){return t.flatMap(e=>e.text===void 0?[]:[e.text]).join(`
3
+ `)}o(pe,"textFromParts");function Me(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,s=t.url??r;if(s)return{name:e,...t.mediaType?{mimeType:t.mediaType}:{},...t.raw!==void 0?{size:Buffer.from(t.raw,"base64").byteLength}:{},uri:s,provenance:"a2a"}}o(Me,"partArtifactReference");function kt(t){let e=t.parts.find(n=>n.url!==void 0||n.raw!==void 0||n.data!==void 0);return e?Me(e,t.name??t.artifactId):void 0}o(kt,"artifactReference");function z(t){let e=(t.artifacts??[]).flatMap(s=>pe(s.parts)),n=t.status.message?pe(t.status.message.parts):"",r=[...e,n].filter(Boolean).join(`
4
+ `);return{state:wt(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(s=>kt(s)??[])}:{}}}o(z,"snapshotFromTask");function le(t){let e=pe(t.parts),n=t.parts.flatMap((r,s)=>{if(r.text!==void 0)return[];let i=Me(r,r.filename??`message-part-${s+1}`);return i?[i]:[]});return{state:"completed",...e?{output:e}:{},...n.length>0?{artifacts:n}:{}}}o(le,"snapshotFromMessage");function Oe(t){return t==="completed"||t==="failed"||t==="canceled"||t==="rejected"}o(Oe,"isTerminal");function Tt(t,e,n){let r=t.get(e.artifactId);t.set(e.artifactId,n&&r?{...r,...e,parts:[...r.parts,...e.parts]}:e)}o(Tt,"mergeStreamArtifact");var fe=class{constructor(e,n,r){this.registration=e;this.context=n;this.options=r}registration;context;options;static{o(this,"A2AClientExecutor")}#e=!1;#t=new Set;async preflight(){try{return B(this.registration),{ok:!0}}catch(e){return{ok:!1,reasons:[e instanceof Error?e.message:String(e)]}}}async start(e){let n=e.idempotencyKey;if(!n)throw new Error("A2A executor requires an idempotency key.");let r=await this.sendMessage({message:{messageId:n,role:"ROLE_USER",parts:[{text:e.input??e.objective,mediaType:"text/plain"}]},configuration:{returnImmediately:!0}});if(f(r.task)){let s=_(r.task);return{idempotencyKey:n,remoteTaskId:s.id,...s.contextId?{metadata:{contextId:s.contextId}}:{}}}if(r.message!==void 0)return{idempotencyKey:n,metadata:{directMessage:v(r.message)}};throw new Error("A2A SendMessage returned neither task nor message.")}async*events(e){let n=_e(e);if(n){yield await this.authorizeArtifacts(le(n));return}if(this.registration.capabilities.streaming==="supported")try{yield*this.streamEvents(e);return}catch(r){if(this.#e)return;q({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,Oe(r.state)||r.state==="input-required"||r.state==="auth-required")return;await new Promise(s=>setTimeout(s,this.options.pollIntervalMs))}}async get(e){let n=_e(e);if(n)return this.authorizeArtifacts(le(n));if(!e.remoteTaskId)throw new Error("A2A task reference has no remote task ID.");let r=_(await this.rpc("GetTask",this.taskParams(e)));return this.assertTaskReference(r,e),this.authorizeArtifacts(z(r))}async sendInput(e,n){if(!e.remoteTaskId)throw new Error("Direct A2A responses cannot accept input.");await this.sendMessage({message:{messageId:ue(),taskId:e.remoteTaskId,...typeof H(e).contextId=="string"?{contextId:H(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=_(await this.rpc("CancelTask",this.taskParams(e)));return this.assertTaskReference(n,e),this.authorizeArtifacts(z(n))}async reconcile(e){return this.get(e)}async dispose(){this.#e=!0;for(let e of this.#t)e.abort(new Error("A2A executor disposed."))}async*streamEvents(e){if(!e.remoteTaskId)throw new Error("A2A stream requires a remote task ID.");let n=B(this.registration),r=new URL(n.interfaceUrl),s=new Headers({accept:"text/event-stream","a2a-version":"1.0","content-type":"application/json"}),i=new AbortController,a=ue();this.#t.add(i);let d,c=o(()=>{d!==void 0&&clearTimeout(d),d=void 0},"disarmTimeout"),A=o(l=>{c(),d=setTimeout(()=>i.abort(new Error(l)),this.options.networkPolicy.requestTimeoutMs),d.unref?.()},"armTimeout");try{A("A2A stream connection timed out.");let l=await this.openStreamResponse(r,s,i.signal,{jsonrpc:"2.0",id:a,method:"SubscribeToTask",params:this.taskParams(e)});if(c(),!l.ok||!l.body)throw new Error(`A2A stream failed with HTTP ${l.status}.`);if(!l.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream"))throw new Error("A2A stream returned an invalid content type.");let p=l.body.getReader(),g=new TextDecoder,m=new Map,T="",L=0;for(;!this.#e;){A("A2A stream was idle for too long.");let U=await p.read();if(c(),U.done)break;if(L+=U.value.byteLength,L>this.options.networkPolicy.maxResponseBytes)throw new Error("A2A stream exceeded the response size limit.");T+=g.decode(U.value,{stream:!0});let ae=T.split(/\r?\n\r?\n/);T=ae.pop()??"";for(let Q of ae){let I=Q.split(/\r?\n/).filter($=>$.startsWith("data:")).map($=>$.slice(5).trimStart()).join(`
5
+ `);if(!I)continue;let C=await this.snapshotFromStreamPayload(Ae(I,"A2A stream"),a,e,m);if(C&&(yield C,C.state&&(Oe(C.state)||C.state==="input-required"||C.state==="auth-required")))return}}if(!this.#e)throw new Error("A2A event stream ended before the task reached a stable state.")}finally{c(),this.#t.delete(i)}}async snapshotFromStreamPayload(e,n,r,s){if(!f(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 i=f(e.error)?e.error:{};throw new u(typeof i.code=="number"?i.code:-32603,typeof i.message=="string"?i.message:"A2A stream error.")}if(f(e.result)){if(e.result.task!==void 0){let i=_(e.result.task);this.assertTaskReference(i,r),s.clear();for(let a of i.artifacts??[])s.set(a.artifactId,a);return this.authorizeArtifacts(z(i))}if(e.result.message!==void 0){let i=v(e.result.message);if(i.taskId!==void 0&&i.taskId!==r.remoteTaskId)throw new Error("A2A stream message belongs to a different task.");return this.authorizeArtifacts(le(i))}if(f(e.result.statusUpdate)&&f(e.result.statusUpdate.status)){this.assertStreamTaskScope(e.result.statusUpdate,r);let i=_({id:r.remoteTaskId,contextId:e.result.statusUpdate.contextId,status:e.result.statusUpdate.status,...s.size>0?{artifacts:[...s.values()]}:{}});return this.authorizeArtifacts(z(i))}if(f(e.result.artifactUpdate)&&e.result.artifactUpdate.artifact!==void 0){this.assertStreamTaskScope(e.result.artifactUpdate,r);let i=_({id:r.remoteTaskId,contextId:e.result.artifactUpdate.contextId,status:{state:"TASK_STATE_WORKING"},artifacts:[e.result.artifactUpdate.artifact]}),a=i.artifacts?.[0];if(!a)throw new Error("A2A artifact update has no artifact.");return Tt(s,a,e.result.artifactUpdate.append===!0),this.authorizeArtifacts(z({...i,artifacts:[...s.values()]}))}}}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=H(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=H(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,s){let i=o(a=>{let d=new Headers(n);return a&&d.set("authorization",a),ce(e,{method:"POST",headers:d,redirect:"manual",signal:r,body:JSON.stringify(s)},this.options.networkPolicy,this.options.fetch)},"open");return this.registration.credentialRef?this.context.withCredential(this.registration.credentialRef,a=>i(`Bearer ${a}`)):i(this.options.authorization)}taskParams(e){let n=B(this.registration);return{id:e.remoteTaskId,...n.tenant?{tenant:n.tenant}:{}}}async sendMessage(e){let n=await this.rpc("SendMessage",{...e,...B(this.registration).tenant?{tenant:B(this.registration).tenant}:{}});if(!f(n))throw new Error("A2A SendMessage result is invalid.");return n}async rpc(e,n){if(this.#e)throw new Error("A2A executor is disposed.");let r=o(s=>this.rpcWithAuthorization(e,n,s),"run");return this.registration.credentialRef?this.context.withCredential(this.registration.credentialRef,s=>r(`Bearer ${s}`)):r(this.options.authorization)}async rpcWithAuthorization(e,n,r){let s=B(this.registration),i=new Headers({accept:"application/json","a2a-version":"1.0","content-type":"application/json"});r&&i.set("authorization",r);let a=ue(),d=await Z(new URL(s.interfaceUrl),{method:"POST",headers:i,body:JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:n})},this.options.networkPolicy,this.options.fetch);if(!d.response.headers.get("content-type")?.toLowerCase().includes("json"))throw new Error("A2A JSON-RPC response has an invalid content type.");let c=Ae(Y(d.body),"A2A endpoint");if(!f(c))throw new Error("A2A JSON-RPC response is invalid.");if(c.jsonrpc!=="2.0"||c.id!==a)throw new Error("A2A JSON-RPC response has an invalid version or response id.");let A=Object.hasOwn(c,"result"),l=Object.hasOwn(c,"error");if(A===l)throw new Error("A2A JSON-RPC response must contain exactly one result or error.");if(l)throw!f(c.error)||typeof c.error.code!="number"||typeof c.error.message!="string"?new Error("A2A JSON-RPC error response is invalid."):new u(c.error.code,c.error.message,d.response.status);if(!d.response.ok)throw new Error(`A2A request failed with HTTP ${d.response.status}.`);return c.result}};function Le(t){return{executorId:j,protocol:"a2a",async create(e,n){let r=typeof t=="function"?t(e):t;return new fe(e,n,r)}}}o(Le,"createA2AAgentExecutorFactory");import{createHash as Rt,randomUUID as J}from"node:crypto";import O from"node:fs";import{createServer as Et}from"node:http";import y from"node:path";import{Readable as Ne}from"node:stream";import S from"node:fs";import ge from"node:path";function M(t){return structuredClone(t)}o(M,"clone");function St(t){if(!f(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(!f(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(!Number.isSafeInteger(t.eventSeq)||!Number.isSafeInteger(t.lastRuntimeEventSeq))throw new Error("A2A task store event cursors are invalid.");let e=t.pendingUserInput;if(e!==void 0&&(!f(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,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:_(t.task),history:t.history.map(v),createdAt:t.createdAt,updatedAt:t.updatedAt,eventSeq:t.eventSeq,lastRuntimeEventSeq:t.lastRuntimeEventSeq,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(St,"parseRecord");var te=class{static{o(this,"A2AFileTaskStore")}#e=new Map;#t=new Map;#n;#r;#s;constructor(e){let n=ge.resolve(e);S.mkdirSync(n,{recursive:!0,mode:448}),this.#n=ge.join(n,"tasks.json"),this.#r=ge.join(n,".server.lock"),this.#s=this.acquireLock();try{this.load()}catch(r){throw S.closeSync(this.#s),S.rmSync(this.#r,{force:!0}),r}}get(e){let n=this.#e.get(e);return n?M(n):void 0}findByMessage(e,n){for(let r of this.#e.values())if(r.principalKey===e&&r.messageDigests[n]!==void 0)return M(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(M)}all(){return[...this.#e.values()].map(M)}save(e){let n=M(e);this.#e.set(e.taskId,n),this.persist();for(let r of this.#t.get(e.taskId)??[])r(M(n));return M(n)}pruneTerminal(e,n){let r=[...this.#e.values()].filter(i=>i.principalKey===e).sort((i,a)=>i.updatedAt.localeCompare(a.updatedAt)),s=[];for(;r.length>n;){let i=r.findIndex(d=>d.task.status.state==="TASK_STATE_COMPLETED"||d.task.status.state==="TASK_STATE_FAILED"||d.task.status.state==="TASK_STATE_CANCELED"||d.task.status.state==="TASK_STATE_REJECTED");if(i<0)break;let[a]=r.splice(i,1);if(!a)break;this.#e.delete(a.taskId),this.#t.delete(a.taskId),s.push(M(a))}return s.length>0&&this.persist(),s}subscribe(e,n){let r=this.#t.get(e)??new Set;return r.add(n),this.#t.set(e,r),()=>{r.delete(n),r.size===0&&this.#t.delete(e)}}close(){this.persist(),this.#t.clear(),S.closeSync(this.#s),S.rmSync(this.#r,{force:!0})}acquireLock(){let e=o(()=>{let n=S.openSync(this.#r,"wx",384);return S.writeFileSync(n,`${process.pid}
6
+ `,"utf8"),S.fsyncSync(n),n},"attempt");try{return e()}catch(n){let r=!1;try{let s=Number.parseInt(S.readFileSync(this.#r,"utf8").trim(),10);if(Number.isSafeInteger(s)&&s>0)try{process.kill(s,0)}catch(i){r=i.code==="ESRCH"}}catch{r=!1}if(!r)throw new Error("A2A task store is already owned by another server.",{cause:n});return S.rmSync(this.#r,{force:!0}),e()}}load(){if(!S.existsSync(this.#n))return;let e;try{e=JSON.parse(S.readFileSync(this.#n,"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=St(n);this.#e.set(r.taskId,r)}}persist(){let e=`${this.#n}.${process.pid}.tmp`;S.writeFileSync(e,`${JSON.stringify([...this.#e.values()],null,2)}
7
+ `,{encoding:"utf8",mode:384}),S.renameSync(e,this.#n)}};var R=new Set(["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED","TASK_STATE_REJECTED"]),xt=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"]),It=new Set(["CreateTaskPushNotificationConfig","GetTaskPushNotificationConfig","ListTaskPushNotificationConfigs","DeleteTaskPushNotificationConfig"]);function w(t){return t().toISOString()}o(w,"nowIso");function P(t){return Rt("sha256").update(t).digest("hex")}o(P,"sha256");function D(t){return P(`${t.subject}\0${t.tenant??""}`)}o(D,"principalKey");function Be(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(Be,"isLoopbackHostname");function bt(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Be(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(bt,"validateBaseUrl");function vt(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 u(-32601,"Method not found.");return n}o(vt,"operationForMethod");function Pt(t){return{queued:"TASK_STATE_SUBMITTED",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(Pt,"statusState");function we(t,e,n){return{messageId:J(),taskId:t,contextId:e,role:"ROLE_AGENT",parts:[{text:n,mediaType:"text/plain"}]}}o(we,"agentMessage");function Ct(t){let e=bt(t);return e.pathname=`${e.pathname.replace(/\/$/,"")}/a2a`,e.search="",e.hash="",e.href}o(Ct,"interfaceUrl");function me(t,e){if(t!==void 0){if(!Number.isSafeInteger(t)||t<0)throw new u(-32602,`${e} must be a non-negative integer.`);return t}}o(me,"parseHistoryLength");function ye(t){if(typeof t?.id!="string"||t.id.length===0)throw new u(-32602,"Task id is required.");return t.id}o(ye,"requiredTaskId");function _t(t){if(!(!f(t)||typeof t.label!="string"||typeof t.value!="string"))return{label:t.label,value:t.value,...typeof t.description=="string"?{description:t.description}:{}}}o(_t,"publicInputOption");function De(t){if(!f(t)||typeof t.question!="string")return;let e=Array.isArray(t.options)?t.options.flatMap(n=>{let r=_t(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(De,"publicInputQuestion");function Ot(t){return f(t)?Array.isArray(t.questions)?{questions:t.questions.flatMap(n=>{let r=De(n);return r?[r]:[]})}:De(t)??{}:{}}o(Ot,"publicInputOptions");function Ut(t,e,n){if(!f(n.payload)||typeof n.payload.kind!="string")return;let r=Ot(n.payload.options),s="";try{s=JSON.stringify(r)}catch{s="{}"}let i=s.length>4096?`${s.slice(0,4093)}...`:s;return{...we(t,e,`Input required (${n.payload.kind}): ${i}`),metadata:{"kodax.ai/user-input":{kind:n.payload.kind,options:r}}}}o(Ut,"pendingInputMessage");function Mt(t,e){let n=t.parts.find(s=>s.data!==void 0)?.data;if(n!==void 0)return n;let r=t.parts.flatMap(s=>s.text===void 0?[]:[s.text]).join(`
8
+ `);if(e==="askUserMulti"||r.startsWith("[")||r.startsWith("{"))try{return JSON.parse(r)}catch{}return r}o(Mt,"continuationAnswer");function qe(t,e){let n=y.relative(t,e);return n===""||!n.startsWith(`..${y.sep}`)&&n!==".."&&!y.isAbsolute(n)}o(qe,"isInside");function Lt(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"}[y.extname(t).toLowerCase()]??"application/octet-stream"}o(Lt,"artifactMediaType");function Nt(t,e,n){let r=t.workspaceRoot??n.agent.projectPath;if(!r||!e.result?.artifactLedger)return[];let s;try{s=O.realpathSync(r)}catch{return[]}let i=new Set,a=[];for(let d of e.result.artifactLedger){if(d.kind!=="file_created"&&d.kind!=="file_modified"||typeof d.target!="string")continue;let c=y.isAbsolute(d.target)?d.target:y.resolve(r,d.target),A=y.relative(r,c),l=A.split(y.sep).includes(".kodax-a2a-staging"),p=d.sourceTool==="run_skill_script"&&d.action==="promote_output";if(!qe(r,c)||!l&&!p)continue;let g,m,T;try{if(g=O.lstatSync(c),m=O.realpathSync(c),!g.isFile()||g.isSymbolicLink()||!qe(s,m)||i.has(m)||g.size>n.limits.maxPartBytes)continue;T=O.readFileSync(m)}catch{continue}if(T.byteLength>n.limits.maxPartBytes)continue;let L=Lt(c);(t.acceptedOutputModes??n.agent.outputModes).includes(L)&&(i.add(m),a.push({artifactId:`file-${P(`${t.taskId}\0${A}\0${T.byteLength}\0${g.mtimeMs}`).slice(0,24)}`,name:y.basename(c),description:p?"KodaX Skill task output":"KodaX staged task output",parts:[{raw:T.toString("base64"),filename:y.basename(c),mediaType:L}]}))}return a}o(Nt,"stagedArtifacts");function Dt(t,e,n){let r=t;for(let s of[e.workspaceRoot,n.agent.projectPath,y.resolve(n.dataDir)])s&&(r=r.split(s).join("[redacted-path]"),r=r.split(s.replaceAll("\\","/")).join("[redacted-path]"));return r}o(Dt,"safeTaskText");function he(t,e=t.agent.publicBaseUrl){let n=Ct(e);return{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}}o(he,"buildCard");function W(t,e=200,n){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8",...n}})}o(W,"jsonResponse");async function qt(t,e){let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new u(-32600,"A2A request exceeds the configured limit.",413);if(!t.body)return new Uint8Array;let r=[],s=0,i=t.body.getReader();for(;;){let c=await i.read();if(c.done)break;if(s+=c.value.byteLength,s>e)throw await i.cancel("A2A request size limit exceeded."),new u(-32600,"A2A request exceeds the configured limit.",413);r.push(c.value)}let a=new Uint8Array(s),d=0;for(let c of r)a.set(c,d),d+=c.byteLength;return a}o(qt,"readBoundedBody");function F(t,e){return W({jsonrpc:"2.0",id:t,result:e})}o(F,"rpcResult");function Kt(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],s=e.data??(r?[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:r,domain:"a2a-protocol.org"}]:void 0);return W({jsonrpc:"2.0",id:t,error:{code:e.code,message:e.message,...s!==void 0?{data:s}:{}}},e.httpStatus)}o(Kt,"rpcError");function Ke(t){return P(JSON.stringify(t))}o(Ke,"messageDigest");function Bt(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(Bt,"partBytes");function $e(t){return t.mediaType??(t.text!==void 0?"text/plain":t.data!==void 0?"application/json":"application/octet-stream")}o($e,"partMediaType");function je(t){if(!O.existsSync(t))return 0;let e=0;for(let n of O.readdirSync(t,{withFileTypes:!0})){let r=y.join(t,n.name);n.isSymbolicLink()||(n.isDirectory()?e+=je(r):n.isFile()&&(e+=O.statSync(r).size))}return e}o(je,"directoryBytes");function $t(t,e,n){if(t.role!=="ROLE_USER")throw new u(-32602,"Inbound message role must be ROLE_USER.");for(let r of t.parts){if(Bt(r)>e)throw new u(-32602,"Message Part exceeds the configured limit.");if(r.url!==void 0)throw new u(-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 u(-32602,"Message Part raw content is not valid base64.");let s=$e(r);if(!n.includes(s))throw new u(-32005,`Media type ${s} is not supported.`)}}o($t,"validateInput");function ne(t,e,n){if(n===0){let{history:s,...i}=t;return i}let r=n===void 0?e:e.slice(-n);return{...t,history:r}}o(ne,"withHistory");function jt(t){if(!t)return;let e;try{e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new u(-32602,"Invalid page token.")}if(!f(e)||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||typeof e.taskId!="string"||e.taskId.length===0)throw new u(-32602,"Invalid page token.");return{updatedAt:e.updatedAt,taskId:e.taskId}}o(jt,"parseTaskListCursor");function zt(t){return Buffer.from(JSON.stringify({updatedAt:t.updatedAt,taskId:t.taskId})).toString("base64url")}o(zt,"encodeTaskListCursor");function Ht(t,e){let n=t.updatedAt.localeCompare(e.updatedAt);return n<0||n===0&&t.taskId.localeCompare(e.taskId)<0}o(Ht,"followsTaskListCursor");var re=class{constructor(e){this.options=e;this.#t=e.now??(()=>new Date),this.#e=new te(e.dataDir),this.#o=he(e),this.#d=this.recover()}options;static{o(this,"KodaXA2AServerRuntime")}#e;#t;#n=new Map;#r=new Set;#s=new Map;#d;#a;#i=!1;#o;#c;get agentCard(){return structuredClone(this.#o)}async whenReady(){await this.#d}updateHot(e){if(this.#i)throw new Error("A2A server is closed.");this.options={...this.options,...e},this.#o=he(this.options,e.agent.publicBaseUrl)}async handle(e){if(await this.#d,this.#i)return W({error:"A2A server is closed."},503);let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/.well-known/agent-card.json"){let r=JSON.stringify(this.#o);return W(this.#o,200,{etag:`"${P(r)}"`,"cache-control":"public, max-age=300"})}return e.method!=="POST"||n.pathname!=="/"&&n.pathname!=="/a2a"?W({error:"Not found."},404):this.handleRpc(e)}async listen(e){if(this.#a)throw new Error("A2A server is already listening.");if(!Be(e.hostname))throw new Error("The built-in A2A HTTP listener is loopback-only; use handle() behind TLS for public service.");let n=Et((i,a)=>{this.handleNodeRequest(i).then(d=>{if(a.statusCode=d.status,d.headers.forEach((c,A)=>a.setHeader(A,c)),!d.body){a.end();return}Ne.fromWeb(d.body).pipe(a)}).catch(d=>{let c=P(V(d)).slice(0,16);this.emit({type:"server.request_failed",time:w(this.#t),outcome:"failed",diagnosticId:c}),a.statusCode=500,a.setHeader("content-type","application/json; charset=utf-8"),a.end(JSON.stringify({error:"Internal server error.",diagnosticId:c}))})});this.#a=n,await new Promise((i,a)=>{n.once("error",a),n.listen(e.port,e.hostname,i)});let r=n.address();if(!r||typeof r=="string")throw new Error("A2A server did not expose a TCP address.");let s=`http://${e.hostname}:${r.port}`;return this.#c=e.publicBaseUrl??s,this.#o=he(this.options,this.#c),s}async close(){if(this.#i)return;this.#i=!0;for(let n of this.#r)n();this.#r.clear();for(let n of this.#n.values())n.close();this.#n.clear();let e=this.#a;this.#a=void 0,e&&await new Promise((n,r)=>e.close(s=>s?r(s):n())),this.#e.close(),await this.options.preparedExecution?.close()}async handleNodeRequest(e){let r=`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,s=new Headers;for(let[a,d]of Object.entries(e.headers))if(typeof d=="string")s.set(a,d);else for(let c of d??[])s.append(a,c);let i={method:e.method,headers:s,...e.method==="GET"||e.method==="HEAD"?{}:{body:Ne.toWeb(e)},duplex:"half"};return this.handle(new Request(r,i))}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 u(-32009,"A2A version is not supported.");if(!e.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new u(-32600,"A2A JSON-RPC requests require application/json.",415);let i=await qt(e,n.limits.maxRequestBytes),a;try{a=JSON.parse(new TextDecoder().decode(i))}catch{throw new u(-32700,"Invalid JSON payload.")}let d=be(a);r=d.id;let c=await n.authentication.authenticate(e);if(!c)throw new u(-32600,"Authentication required.",401);if(It.has(d.method))throw new u(-32003,"Push notifications are not supported.");let A=vt(d.method),l=d.method==="SendMessage"||d.method==="SendStreamingMessage"?v(d.params?.message):void 0,p=typeof d.params?.id=="string"?d.params.id:l?.taskId,g=l?.contextId,m=l?[...new Set(l.parts.map($e))]:void 0;if(!await n.authorize({principal:c,operation:A,...p?{taskId:p}:{},...g?{contextId:g}:{},...m?{inputModes:m}:{}}))throw new u(-32001,"Task not found.");return await this.dispatch(d,c,n)}catch(s){let i=P(V(s)).slice(0,16),a=s instanceof u?s:new u(-32603,"Internal error.",500,[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",reason:"INTERNAL",domain:"kodax.ai",metadata:{diagnosticId:i}}]);return this.emit({type:"rpc.failed",time:w(this.#t),outcome:"failed",diagnosticId:i}),Kt(r,a)}}async dispatch(e,n,r){switch(e.method){case"SendMessage":return F(e.id,{task:await this.sendMessage(e.params,n,!1,r)});case"SendStreamingMessage":{let s=await this.sendMessage(e.params,n,!0,r);return this.streamTask(e.id,s.id,D(n))}case"GetTask":return F(e.id,await this.getTask(e.params,n));case"ListTasks":return F(e.id,this.listTasks(e.params,n));case"CancelTask":return F(e.id,await this.cancelTask(e.params,n,r));case"SubscribeToTask":return this.subscribeTask(e.id,e.params,n);case"GetExtendedAgentCard":{if(!r.extendedAgentCard)throw new u(-32004,"Extended Agent Card is not supported.");return F(e.id,r.extendedAgentCard)}default:throw new u(-32601,"Method not found.")}}async sendMessage(e,n,r,s){let i=D(n),a=this.#s.get(i)??Promise.resolve(),d=o(()=>{},"release"),c=new Promise(A=>{d=A});this.#s.set(i,c),await a;try{return await this.sendMessageUnserialized(e,n,r,s)}finally{d(),this.#s.get(i)===c&&this.#s.delete(i)}}async sendMessageUnserialized(e,n,r,s){let i=v(e?.message);if($t(i,s.limits.maxPartBytes,s.agent.inputModes),e?.configuration!==void 0&&!f(e.configuration))throw new u(-32602,"SendMessage configuration must be an object.");let a=f(e?.configuration)?e.configuration:{},d=me(a.historyLength,"SendMessage historyLength");if(a.returnImmediately!==void 0&&typeof a.returnImmediately!="boolean")throw new u(-32602,"SendMessage returnImmediately must be a boolean.");if(a.taskPushNotificationConfig!==void 0)throw new u(-32003,"Push notifications are not supported.");if(a.acceptedOutputModes!==void 0){if(!Array.isArray(a.acceptedOutputModes)||!a.acceptedOutputModes.every(I=>typeof I=="string"))throw new u(-32602,"SendMessage acceptedOutputModes must be a string array.");if(!a.acceptedOutputModes.some(I=>s.agent.outputModes.includes(I)))throw new u(-32005,"No requested output media type is supported.")}let c=D(n),A=Ke(i),l=this.#e.findByMessage(c,i.messageId);if(l){if(l.messageDigests[i.messageId]!==A)throw new u(-32602,"Message ID was reused with different content.");return this.emit({type:"task.deduplicated",time:w(this.#t),taskId:l.taskId,contextId:l.contextId}),ne(l.task,l.history,d)}let p=i.taskId?this.requireOwnedTask(i.taskId,c):void 0;if(p&&i.contextId!==void 0&&i.contextId!==p.contextId)throw new u(-32602,"Message contextId does not match the task.");if(p&&p.task.status.state!=="TASK_STATE_INPUT_REQUIRED"&&p.task.status.state!=="TASK_STATE_AUTH_REQUIRED")throw new u(-32004,"Task is not waiting for input.");let g=s.limits.maxRetainedTasksPerPrincipal??s.limits.maxTasksPerPrincipal??100;p||this.#e.pruneTerminal(c,Math.max(0,g-1));let m=this.#e.list(c);if(!p&&m.length>=g)throw new u(-32004,"Principal task limit reached.");let T=m.filter(I=>!R.has(I.task.status.state)).length;if(!p&&T>=(s.limits.maxActiveTasksPerPrincipal??4))throw new u(-32004,"Principal active task limit reached.");let L=this.#e.all().filter(I=>!R.has(I.task.status.state)).length;if(!p&&L>=s.limits.maxConcurrentTasks)throw new u(-32004,"Server task concurrency limit reached.");let U;if(p?.task.status.state==="TASK_STATE_INPUT_REQUIRED")U=await this.resumeUserInput(p,i,A,s);else{let I=p??await this.createRecord(i,c,s,a.acceptedOutputModes),C=p?this.appendMessage(I,i,A):I;try{U=await this.startRun(C,i,s)}catch($){throw this.failTask(C.taskId,"Task could not be started.",s),$}}let Q=r||a.returnImmediately===!0?U:await this.waitForTask(U.taskId,s.limits.maxTaskWaitMs??3e4);return ne(Q.task,Q.history,d)}async resumeUserInput(e,n,r,s){let i=e.pendingUserInput;if(!i)throw new u(-32004,"Task has no pending Runtime input request.");if(!(await s.runtime.userInputs.respond(i.requestId,Mt(n,i.kind),{expectedRevision:i.revision,runId:i.runId})).accepted)throw new u(-32004,"Pending Runtime input request is no longer active.");let d=this.#e.get(e.taskId)??e,c=this.appendMessage(d,n,r),{pendingUserInput:A,...l}=c;return R.has(c.task.status.state)?this.#e.save(l):this.#e.save({...l,task:{...c.task,status:{state:"TASK_STATE_WORKING",timestamp:w(this.#t)}},updatedAt:w(this.#t),eventSeq:c.eventSeq+1})}async createRecord(e,n,r,s){let i=e.contextId??J(),a=this.#e.list(n).find(g=>g.contextId===i),d=P(`${n}\0${i}`),c=a?.workspaceRoot??await r.preparedExecution?.prepareWorkspace(d),A=a?{id:a.sessionId}: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}:{},...c?{projectPath:c,gitRoot:c}:r.agent.projectPath?{projectPath:r.agent.projectPath}:{}}),l=J(),p=w(this.#t);return this.#e.save({taskId:l,contextId:i,principalKey:n,runtimeIdentity:r.runtime.identity.runtimeId,sessionId:A.id,...c?{workspaceRoot:c}:{},...r.preparedExecution?{executionPolicyRevision:r.preparedExecution.binding.executionPolicyRevision}:{},messageDigests:{[e.messageId]:Ke(e)},runIds:[],task:{id:l,contextId:i,status:{state:"TASK_STATE_SUBMITTED",timestamp:p},history:[{...e,taskId:l,contextId:i}]},history:[{...e,taskId:l,contextId:i}],createdAt:p,updatedAt:p,eventSeq:1,lastRuntimeEventSeq:0,runtimeEventCount:0,runtimeEventBytes:0,...s?{acceptedOutputModes:s}:{}})}appendMessage(e,n,r){let s={...n,taskId:e.taskId,contextId:e.contextId};return this.#e.save({...e,messageDigests:{...e.messageDigests,[n.messageId]:r},history:[...e.history,s],task:{...e.task,history:[...e.history,s]},updatedAt:w(this.#t),eventSeq:e.eventSeq+1})}async startRun(e,n,r){let s=await this.inputsForMessage(e.taskId,n,r),i=r.preparedExecution;if(i&&e.executionPolicyRevision!==i.binding.executionPolicyRevision)throw new u(-32004,"A2A task execution binding revision changed.");let a=i?await i.start({sessionId:e.sessionId,inputs:s,principalKey:e.principalKey}):await r.runtime.runs.start({sessionId:e.sessionId,input:s,mode:"managed_task",permissionBroker:"runtime",...r.agent.runOptions?{options:r.agent.runOptions}:{},agentContext:{actorId:`a2a:${e.principalKey.slice(0,16)}`}}),d=this.#e.save({...e,runIds:[...e.runIds,a.runId],task:{...e.task,status:{state:"TASK_STATE_WORKING",timestamp:w(this.#t)}},updatedAt:w(this.#t),eventSeq:e.eventSeq+1});return this.subscribeRuntime(d,a.runId,r),a.result.then(c=>this.finishRun(d.taskId,c,r)).catch(()=>{this.failTask(d.taskId,"Task execution failed.",r)}),this.emit({type:"task.started",time:w(this.#t),taskId:d.taskId,contextId:d.contextId,runId:a.runId,outcome:"accepted"}),d}async inputsForMessage(e,n,r){let s=[];for(let i of n.parts){if(i.text!==void 0){s.push({type:"text",text:i.text});continue}s.push(await this.materializePart(e,i,r))}return s}async materializePart(e,n,r){let s=n.mediaType??(n.data!==void 0?"application/json":"application/octet-stream"),i=n.data!==void 0?".json":".bin",a=this.#e.get(e),d=a?.workspaceRoot?y.join(a.workspaceRoot,"inbox",P(e)):y.join(y.resolve(r.dataDir),"attachments",P(e));O.mkdirSync(d,{recursive:!0,mode:448});let c=n.data!==void 0?Buffer.from(JSON.stringify(n.data),"utf8"):Buffer.from(n.raw??"","base64"),A=r.limits.maxWorkspaceBytesPerContext??1073741824;if(a?.workspaceRoot&&je(a.workspaceRoot)+c.byteLength>A)throw new u(-32004,"A2A context workspace size limit reached.");let l=n.filename?y.basename(n.filename).replace(/[^A-Za-z0-9._-]/g,"_"):`${J()}${i}`,p=y.join(d,`${J()}-${l}`);O.writeFileSync(p,c,{mode:384});let g=s.startsWith("image/")?"image":s.startsWith("video/")?"video":"file";return{type:"artifact_ref",artifactId:(await r.runtime.artifacts.create({kind:g,path:p,mediaType:s,mimeType:s,...n.filename?{name:y.basename(n.filename)}:{},source:"user-inline",description:"Inbound A2A message part"})).id,description:"Inbound A2A attachment"}}subscribeRuntime(e,n,r){this.#n.get(e.taskId)?.close();let s=r.runtime.events.subscribe({runId:n},i=>this.onRuntimeEvent(e.taskId,i,r));this.#n.set(e.taskId,s)}onRuntimeEvent(e,n,r){let s=this.#e.get(e);if(!s||R.has(s.task.status.state))return;let i=Buffer.byteLength(JSON.stringify(n)),a=s.runtimeEventCount+1,d=s.runtimeEventBytes+i;if(a>(r.limits.maxEventsPerTask??1e3)||d>(r.limits.maxEventBytesPerTask??16777216)){let p=s.runIds.at(-1);p&&r.runtime.runs.abort(p),this.failTask(e,"A2A task event quota exceeded.",r);return}let c=n.type==="user_input.requested"?"TASK_STATE_INPUT_REQUIRED":s.task.status.state,A=n.type==="user_input.requested"?Ut(e,s.contextId,n):void 0,l=n.type==="user_input.requested"&&f(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({...s,task:{...s.task,status:{...s.task.status,state:c,...A?{message:A}:{},timestamp:n.time}},...l?{pendingUserInput:l}:{},updatedAt:n.time,eventSeq:s.eventSeq+1,lastRuntimeEventSeq:Math.max(s.lastRuntimeEventSeq,n.seq),runtimeEventCount:a,runtimeEventBytes:d})}finishRun(e,n,r=this.options){if(this.#i)return;let s=this.#e.get(e);if(!s||R.has(s.task.status.state))return;let i=Pt(n.phase),a=n.error?P(V(n.error)).slice(0,16):void 0,d=n.error?`Task failed. Diagnostic ID: ${a}`:Dt(n.result?.lastText??"",s,r),c=d?we(e,s.contextId,d):void 0,A=c?[...s.history,c]:s.history,p=[...d&&(s.acceptedOutputModes??r.agent.outputModes).includes("text/plain")?[{artifactId:`final-${e}`,name:"final-output",parts:[{text:d,mediaType:"text/plain"}]}]:[],...Nt(s,n,r)],{pendingUserInput:g,...m}=s;this.#e.save({...m,history:A,task:{...s.task,status:{state:i,...c?{message:c}:{},timestamp:w(this.#t)},...p.length>0?{artifacts:p}:{},history:A},updatedAt:w(this.#t),eventSeq:s.eventSeq+1}),this.#n.get(e)?.close(),this.#n.delete(e),this.pruneRetained(s.principalKey,r),this.emit({type:"task.finished",time:w(this.#t),taskId:e,contextId:s.contextId,outcome:i==="TASK_STATE_COMPLETED"?"completed":"failed"})}failTask(e,n,r=this.options){if(this.#i)return;let s=this.#e.get(e);if(!s||R.has(s.task.status.state))return;let i=we(e,s.contextId,n),{pendingUserInput:a,...d}=s;this.#e.save({...d,task:{...s.task,status:{state:"TASK_STATE_FAILED",message:i,timestamp:w(this.#t)}},updatedAt:w(this.#t),eventSeq:s.eventSeq+1}),this.#n.get(e)?.close(),this.#n.delete(e),this.pruneRetained(s.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=ye(e),s=this.requireOwnedTask(r,D(n)),i=me(e?.historyLength,"GetTask historyLength");return ne(s.task,s.history,i)}listTasks(e,n){let r=me(e?.historyLength,"ListTasks historyLength");if(e?.includeArtifacts!==void 0&&typeof e.includeArtifacts!="boolean")throw new u(-32602,"ListTasks includeArtifacts must be a boolean.");if(e?.contextId!==void 0&&typeof e.contextId!="string")throw new u(-32602,"ListTasks contextId must be a string.");if(e?.pageToken!==void 0&&typeof e.pageToken!="string")throw new u(-32602,"ListTasks pageToken must be a string.");if(e?.status!==void 0&&(typeof e.status!="string"||!xt.has(e.status)))throw new u(-32602,"ListTasks status is invalid.");let s=typeof e?.statusTimestampAfter=="string"?Date.parse(e.statusTimestampAfter):void 0;if(e?.statusTimestampAfter!==void 0&&!Number.isFinite(s))throw new u(-32602,"ListTasks statusTimestampAfter is invalid.");let i=this.#e.list(D(n)).filter(p=>!(typeof e?.contextId=="string"&&p.contextId!==e.contextId||typeof e?.status=="string"&&p.task.status.state!==e.status||s!==void 0&&Date.parse(p.task.status.timestamp??p.updatedAt)<s));if(e?.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||e.pageSize<1||e.pageSize>100))throw new u(-32602,"ListTasks pageSize must be an integer from 1 to 100.");let a=typeof e?.pageSize=="number"?e.pageSize:50,d=jt(typeof e?.pageToken=="string"?e.pageToken:void 0),c=d?i.filter(p=>Ht(p,d)):i,A=c.slice(0,a),l=A.at(-1);return{tasks:A.map(p=>{let g=ne(p.task,p.history,r);return e?.includeArtifacts===!0?g:{...g,artifacts:void 0}}),nextPageToken:l&&A.length<c.length?zt(l):"",pageSize:a,totalSize:i.length}}async cancelTask(e,n,r){let s=ye(e),i=this.requireOwnedTask(s,D(n));if(R.has(i.task.status.state))throw new u(-32002,"Task is not cancelable.");let a=i.runIds.at(-1);a&&await r.runtime.runs.abort(a);let d=this.#e.save({...i,task:{...i.task,status:{state:"TASK_STATE_CANCELED",timestamp:w(this.#t)}},updatedAt:w(this.#t),eventSeq:i.eventSeq+1});return this.#n.get(s)?.close(),this.#n.delete(s),this.pruneRetained(i.principalKey,r),d.task}subscribeTask(e,n,r){let s=ye(n),i=this.requireOwnedTask(s,D(r));if(R.has(i.task.status.state))throw new u(-32004,"Cannot subscribe to a terminal task.");return this.streamTask(e,s,i.principalKey)}streamTask(e,n,r){let s=this.requireOwnedTask(n,r),i=new TextEncoder,a,d=o(()=>{},"cleanup"),c=!1,A=new ReadableStream({start:o(l=>{let p=o(()=>{c||(c=!0,d(),l.close())},"close");if(d=o(()=>{a?.(),this.#r.delete(p)},"cleanup"),this.#r.add(p),l.enqueue(i.encode(this.sse(e,{task:s.task}))),this.enqueueArtifactUpdates(l,i,e,s.task),R.has(s.task.status.state)){p();return}a=this.#e.subscribe(n,g=>{this.enqueueArtifactUpdates(l,i,e,g.task),l.enqueue(i.encode(this.sse(e,{statusUpdate:{taskId:n,contextId:g.contextId,status:g.task.status}}))),(R.has(g.task.status.state)||g.task.status.state==="TASK_STATE_INPUT_REQUIRED"||g.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&p()})},"start"),cancel:o(()=>{c||(c=!0,d())},"cancel")});return new Response(A,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}enqueueArtifactUpdates(e,n,r,s){for(let i of s.artifacts??[])e.enqueue(n.encode(this.sse(r,{artifactUpdate:{taskId:s.id,contextId:s.contextId,artifact:i,append:!1,lastChunk:!0}})))}sse(e,n){return`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:n})}
8
9
 
9
- `}waitForTask(e,n){let r=this.#e.get(e);return r?R.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(s=>{let o=!1,a=i(()=>{},"unsubscribe"),d=i(p=>{o||(o=!0,clearTimeout(c),a(),s(p))},"finish"),c=setTimeout(()=>d(this.#e.get(e)??r),n);a=this.#e.subscribe(e,p=>{(R.has(p.task.status.state)||p.task.status.state==="TASK_STATE_INPUT_REQUIRED"||p.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&d(p)});let l=this.#e.get(e);l&&(R.has(l.task.status.state)||l.task.status.state==="TASK_STATE_INPUT_REQUIRED"||l.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&d(l)}):Promise.reject(new u(-32001,"Task not found."))}requireOwnedTask(e,n){let r=this.#e.get(e);if(!r||r.principalKey!==n)throw new u(-32001,"Task not found.");return r}async recover(){let e=this.options;for(let n of this.#e.all()){if(R.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.");continue}try{let s=await e.runtime.runs.get(r);if(s.phase==="running"||s.phase==="queued"||s.phase==="waiting_permission"||s.phase==="waiting_user_input"){for(let o of await e.runtime.events.replay({runId:r,sinceSeq:n.lastRuntimeEventSeq}))this.onRuntimeEvent(n.taskId,o,e);this.subscribeRuntime(n,r,e),e.runtime.runs.await(r).then(o=>this.finishRun(n.taskId,o)).catch(o=>{this.failTask(n.taskId,q(o))})}else this.finishRun(n.taskId,{runId:r,sessionId:n.sessionId,phase:s.phase})}catch(s){M({source:"a2a.server",level:"warn",message:"A2A task recovery could not reattach to its Runtime run.",detail:{taskId:n.taskId,error:s}}),this.failTask(n.taskId,"Runtime execution was unavailable during A2A recovery.")}}}emit(e){this.options.onEvent?.(e)}};function Mn(t){return new Y(t)}i(Mn,"createKodaXA2AServer");async function Rt(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 s=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}),o=!1;return{service:n,ownerSessionId:r.ownerSessionId,binding:s,declaration:e,prepareWorkspace(a){return n.prepareWorkspace({ownerSessionId:r.ownerSessionId,bindingId:s.bindingId,contextKey:a})},start(a){let d={ownerSessionId:r.ownerSessionId,bindingId:s.bindingId,expectedExecutionPolicyRevision:s.executionPolicyRevision,sessionId:a.sessionId,input:a.inputs,permissionBroker:"runtime",agentContext:{actorId:`a2a:${a.principalKey.slice(0,16)}`}};if(e.kind==="local-agent"){let c="configurationRevision"in s&&typeof s.configurationRevision=="string"?s.configurationRevision:void 0;if(!c)throw new Error("Prepared local-Agent binding is missing its revision.");return n.startLocal({...d,expectedConfigurationRevision:c})}return n.startDefault(d)},async close(){o||(o=!0,await n.closeOwnerSession(r.ownerSessionId))}}}catch(s){throw await n.closeOwnerSession(r.ownerSessionId),s}}i(Rt,"prepareExecution");async function Dn(t){let e=await Rt(t);try{let n=new Y({...t,preparedExecution:e});return await n.whenReady(),n}catch(n){throw await e.close(),n}}i(Dn,"prepareKodaXA2AServer");import{createHash as Et}from"node:crypto";import{existsSync as xt,readFileSync as bt}from"node:fs";import ee from"node:path";import{isDeepStrictEqual as pe}from"node:util";var De={maxRequestBytes:33554432,maxPartBytes:16777216,maxConcurrentTasks:4,maxTaskWaitMs:3e4,maxActiveTasksPerPrincipal:4,maxRetainedTasksPerPrincipal:100,maxEventsPerTask:1e3,maxEventBytesPerTask:16777216,maxWorkspaceBytesPerContext:1073741824},Me=Object.keys(De),te=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,vt=/^[A-Za-z_][A-Za-z0-9_]*$/;function S(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object.`);return t}i(S,"record");function h(t,e,n){let r=new Set(e),s=Object.keys(t).find(o=>!r.has(o));if(s!==void 0)throw new Error(`${n} has unknown field "${s}".`)}i(h,"noUnknown");function T(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t.trim()}i(T,"text");function H(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((s,o)=>T(s,`${e}[${o}]`));if(new Set(r).size!==r.length)throw new Error(`${e} contains duplicates.`);return r}i(H,"stringList");function Ne(t,e,n=!0){let r=H(t,e,n);if(r.some(s=>s.includes("*")))throw new Error(`${e} does not accept wildcard authority.`);return r}i(Ne,"exactNames");function Le(t,e){let n=S(t,e),r={};for(let[s,o]of Object.entries(n)){if(!te.test(s)||s.includes("*"))throw new Error(`${e} keys must be exact names without wildcards.`);r[s]=Ne(o,`${e}.${s}`,!1)}return r}i(Le,"namedExactLists");function It(t,e){let n=S(t,e);h(n,["cardUrl","credentialEnv","effect"],e);let r=qe(n.cardUrl,`${e}.cardUrl`,!0),s=n.effect;if(!["none","read","write","unknown"].includes(String(s)))throw new Error(`${e}.effect is invalid.`);let o=n.credentialEnv===void 0?void 0:Be(n.credentialEnv,`${e}.credentialEnv`);return{cardUrl:r,...o?{credentialEnv:o}:{},effect:s}}i(It,"parseOutboundAgent");function qe(t,e,n){let r=T(t,e),s;try{s=new URL(r)}catch(a){throw new Error(`${e} must be an absolute HTTP URL.`,{cause:a})}if(s.username||s.password)throw new Error(`${e} must not contain embedded credentials.`);let o=["localhost","127.0.0.1","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&o&&n))throw new Error(`${e} must use HTTPS or explicit loopback HTTP.`);return s.toString()}i(qe,"parseHttpUrl");function Be(t,e){let n=T(t,e);if(!vt.test(n))throw new Error(`${e} must be an environment variable name.`);return n}i(Be,"parseEnvironmentName");function Pt(t){if(t===void 0)return{mode:"managed"};let e=S(t,"A2A server execution.workspace");if(e.mode==="managed")return h(e,["mode"],"A2A server execution.workspace"),{mode:"managed"};if(e.mode!=="fixed")throw new Error("A2A server execution.workspace.mode is invalid.");h(e,["mode","root"],"A2A server execution.workspace");let n=T(e.root,"A2A server execution.workspace.root");if(!ee.isAbsolute(n))throw new Error("Fixed A2A workspace root must be absolute.");return{mode:"fixed",root:ee.resolve(n)}}i(Pt,"parseWorkspace");function Ct(t){return{workspace:t.mode==="managed"?"write":"read",process:"deny",network:{mode:"deny"},tools:[],mcp:{},skillScripts:{},subagents:"deny"}}i(Ct,"defaultToolPolicy");function _t(t){let e=S(t,"A2A toolPolicy.network");if(e.mode==="deny")return h(e,["mode"],"A2A toolPolicy.network"),{mode:"deny"};if(e.mode!=="allowlist")throw new Error("A2A toolPolicy.network.mode is invalid.");h(e,["mode","origins"],"A2A toolPolicy.network");let n=H(e.origins,"A2A toolPolicy.network.origins").map(r=>{let s;try{s=new URL(r)}catch(o){throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.",{cause:o})}if(!["http:","https:"].includes(s.protocol)||s.origin==="null")throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.");return s.origin});if(new Set(n).size!==n.length)throw new Error("A2A toolPolicy.network.origins contains duplicates after normalization.");return{mode:"allowlist",origins:n}}i(_t,"parseNetworkPolicy");function Ot(t){let e=Le(t,"A2A toolPolicy.skillScripts");for(let[n,r]of Object.entries(e))e[n]=r.map(s=>{if(s.includes("\\")||ee.posix.isAbsolute(s))throw new Error("A2A skillScripts paths must use relative POSIX scripts/... paths.");let o=ee.posix.normalize(s);if(!o.startsWith("scripts/")||o.includes("../"))throw new Error("A2A skillScripts paths must remain below the Skill scripts directory.");return o});return e}i(Ot,"parseSkillScripts");function Ut(t,e){if(t===void 0)return Ct(e);let n=S(t,"A2A server execution.toolPolicy"),r=["workspace","process","network","tools","mcp","skillScripts","subagents"];if(h(n,r,"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 s=Ot(n.skillScripts),o=Object.values(s).reduce((a,d)=>a+d.length,0);if(n.process==="deny"&&o>0)throw new Error("A2A toolPolicy process deny requires empty skillScripts.");if(n.process==="isolated"&&o===0)throw new Error("A2A toolPolicy process isolated requires non-empty skillScripts.");return{workspace:n.workspace,process:n.process,network:_t(n.network),tools:Ne(n.tools,"A2A toolPolicy.tools"),mcp:Le(n.mcp,"A2A toolPolicy.mcp"),skillScripts:s,subagents:n.subagents}}i(Ut,"parseToolPolicy");function Mt(t){let e=S(t,"A2A server execution"),n=Pt(e.workspace),r=Ut(e.toolPolicy,n),s=e.profileId===void 0?void 0:T(e.profileId,"A2A server execution.profileId");if(e.kind==="runtime-default")return h(e,["kind","workspace","toolPolicy","profileId"],"A2A server execution"),{kind:"runtime-default",workspace:n,toolPolicy:r,...s?{profileId:s}:{}};if(e.kind!=="local-agent")throw new Error("A2A server execution.kind is invalid.");h(e,["kind","agentRef","workspace","toolPolicy","profileId"],"A2A server execution");let o=S(e.agentRef,"A2A server execution.agentRef");if(h(o,["source","name"],"A2A server execution.agentRef"),o.source!=="markdown:user")throw new Error("A2A local Agent source must be markdown:user.");let a=T(o.name,"A2A server execution.agentRef.name");if(!te.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,...s?{profileId:s}:{}}}i(Mt,"parseExecution");function Dt(t,e){let n=`A2A server published.skills[${e}]`,r=S(t,n);return h(r,["id","name","description","tags"],n),{id:T(r.id,`${n}.id`),name:T(r.name,`${n}.name`),description:T(r.description,`${n}.description`),tags:H(r.tags,`${n}.tags`,!0)}}i(Dt,"parsePublishedSkill");function Nt(t){let e=S(t,"A2A server published");if(h(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(Dt),r=n.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("A2A published Skill ids must be unique.");return{name:T(e.name,"A2A server published.name"),description:T(e.description,"A2A server published.description"),version:T(e.version,"A2A server published.version"),skills:n,inputModes:H(e.inputModes,"A2A server published.inputModes"),outputModes:H(e.outputModes,"A2A server published.outputModes")}}i(Nt,"parsePublished");function Lt(t){let e=S(t,"A2A server authentication");if(h(e,["type","tokenEnv","principalId"],"A2A server authentication"),e.type!=="bearer-env")throw new Error("A2A authentication type must be bearer-env.");return{type:"bearer-env",tokenEnv:Be(e.tokenEnv,"A2A server authentication.tokenEnv"),principalId:T(e.principalId,"A2A server authentication.principalId")}}i(Lt,"parseAuthentication");function qt(t,e){if(!Number.isSafeInteger(t)||Number(t)<=0)throw new Error(`${e} must be a positive safe integer.`);return Number(t)}i(qt,"positiveInteger");function Bt(t,e){let n=t===void 0?{}:S(t,"A2A server limits");h(n,Me,"A2A server limits");let r=Object.fromEntries(Me.map(o=>[o,n[o]===void 0?De[o]:qt(n[o],`A2A server limits.${o}`)]));if(r.maxPartBytes>r.maxRequestBytes)throw new Error("A2A server limits.maxPartBytes must not exceed maxRequestBytes.");let s=e.workspace.mode==="fixed"&&e.toolPolicy.workspace==="write";if(s&&n.maxConcurrentTasks===void 0)return{...r,maxConcurrentTasks:1};if(s&&r.maxConcurrentTasks!==1)throw new Error("A2A fixed writable workspace requires maxConcurrentTasks 1.");return r}i(Bt,"parseLimits");function Kt(t){let e=S(t,"A2A server");h(e,["execution","published","publicBaseUrl","authentication","limits","dataDir"],"A2A server");let n=Mt(e.execution),r=e.publicBaseUrl===void 0?void 0:qe(e.publicBaseUrl,"A2A server.publicBaseUrl",!0);return{execution:n,published:Nt(e.published),...r?{publicBaseUrl:r}:{},authentication:Lt(e.authentication),limits:Bt(e.limits,n),dataDir:T(e.dataDir,"A2A server.dataDir")}}i(Kt,"parseServer");function ne(t){let e=S(t,"A2A integration config");if(h(e,["version","agents","server"],"A2A integration config"),e.version!==1)throw new Error("A2A integration config version must be 1.");let n=S(e.agents,"A2A integration config agents"),r={};for(let[s,o]of Object.entries(n)){if(!te.test(s))throw new Error(`A2A outbound Agent name "${s}" is invalid.`);r[s]=It(o,`A2A outbound Agent "${s}"`)}return{version:1,agents:r,...e.server===void 0?{}:{server:Kt(e.server)}}}i(ne,"parseA2AIntegrationDocument");function jt(t){return Et("sha256").update(t).digest("hex")}i(jt,"hash");function F(t){let e=ge("a2a",t),n=xt(e),r=n?bt(e,"utf8"):JSON.stringify({version:1,agents:{}}),s;try{s=JSON.parse(r)}catch(o){throw new Error("Invalid A2A integration JSON.",{cause:o})}return{domain:"a2a",source:n?"user":"default",path:e,revision:jt(r),document:ne(s),loadedAt:new Date().toISOString()}}i(F,"readA2AIntegration");function fe(t,e,n){return me({domain:"a2a",configHome:t,document:e,validate:ne,...n?{expectedRevision:n}:{}})}i(fe,"writeA2AIntegration");function Hn(t,e,n,r){if(!te.test(e))throw new Error("A2A outbound Agent name is invalid.");let s=F(t);return fe(t,{...s.document,agents:{...s.document.agents,[e]:n}},r??(s.source==="user"?s.revision:void 0))}i(Hn,"upsertA2AOutboundAgent");function Fn(t,e,n){let r=F(t);if(r.document.agents[e]===void 0)return!1;let s={...r.document.agents};return delete s[e],fe(t,{...r.document,agents:s},n??(r.source==="user"?r.revision:void 0)),!0}i(Fn,"removeA2AOutboundAgent");function Jn(t,e,n){let r=F(t),s=e===void 0?{version:1,agents:r.document.agents}:{...r.document,server:e};return fe(t,s,n??(r.source==="user"?r.revision:void 0))}i(Jn,"setA2AServerConfig");function zn(t,e){if(pe(t,e))return{kind:"none",fields:[]};if(t===void 0||e===void 0)return{kind:"restart-required",fields:["server"]};let n=["execution","dataDir"].filter(s=>!pe(t[s],e[s])),r=["published","publicBaseUrl","authentication","limits"].filter(s=>!pe(t[s],e[s]));return n.length>0?{kind:"restart-required",fields:[...n,...r]}:{kind:"hot",fields:r}}i(zn,"classifyA2AServerChange");import{timingSafeEqual as $t}from"node:crypto";import Ke from"node:os";import je from"node:path";function Ht(t){return t==="~"?Ke.homedir():t.startsWith("~/")||t.startsWith("~\\")?je.join(Ke.homedir(),t.slice(2)):je.resolve(t)}i(Ht,"expandHome");function Ft(t){let e=t.headers.get("authorization");return(e?/^Bearer ([^\s]+)$/i.exec(e):null)?.[1]}i(Ft,"bearerToken");function Jt(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.byteLength===r.byteLength&&$t(n,r)}i(Jt,"equalSecret");function $e(t,e=process.env){let n=e[t.tokenEnv];if(!n)throw new Error(`A2A bearer token environment variable is unset: ${t.tokenEnv}.`);return{securitySchemes:{bearer:{type:"http",scheme:"bearer",bearerFormat:"opaque"}},securityRequirements:[{bearer:[]}],async authenticate(r){let s=Ft(r);return s&&Jt(n,s)?{subject:t.principalId,scopes:["a2a:invoke"]}:null}}}i($e,"createBearerEnvA2AAuthentication");function He(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}:{}}}i(He,"publishedAgent");function Fe(){return Promise.resolve(!0)}i(Fe,"authorization");function Zn(t){return{runtime:t.runtime,agent:He(t.config,t.listenBaseUrl),execution:t.config.execution,dataDir:Ht(t.config.dataDir),limits:t.config.limits,authentication:$e(t.config.authentication,t.env),authorize:Fe}}i(Zn,"createA2AServerOptionsFromConfig");function Yn(t){return{agent:He(t.config,t.listenBaseUrl),limits:t.config.limits,authentication:$e(t.config.authentication,t.env),authorize:Fe}}i(Yn,"createA2AServerHotOptions");function zt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}i(zt,"isExactLoopback");function Je(t){return{allowedOrigins:[t.origin],allowPrivateAddresses:zt(t.hostname),requestTimeoutMs:1e4,maxResponseBytes:1e6,maxRedirects:3}}i(Je,"networkPolicy");function Wt(t){let e=t.executorConfig?.interfaceUrl;if(typeof e!="string")throw new Error("Configured A2A registration has no interface URL.");return new URL(e)}i(Wt,"registrationUrl");function Xt(){let t=i(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)}}}i(Xt,"environmentCredentialBroker");function Gt(t,e){return{agentId:`external:${t}`,agentCardUrl:e.cardUrl,...e.credentialEnv?{credentialRef:`env:${e.credentialEnv}`}:{},effects:{remote:e.effect}}}i(Gt,"registrationInput");function ar(t){return{runtimeOptions:{factories:[Ie(n=>({networkPolicy:Je(Wt(n)),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}))],policy:i(()=>({allowed:!0}),"policy"),credentialBroker:Xt()},async start(n){let r=new ye({domain:"a2a",configHome:t.configHome,validate:ne,read:i(()=>F(t.configHome),"read")}),s=i(async a=>{let d=await n.admin.agentRegistrations.list(),c=new Set(d.filter(l=>l.executorId===L).map(l=>l.agentId));for(let[l,p]of Object.entries(a.agents)){let g=`external:${l}`;try{let f=new URL(p.cardUrl),E=await be(Gt(l,p),{networkPolicy:Je(f),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}});await n.admin.agentRegistrations.upsert(E.registration),c.delete(g)}catch(f){M({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${l}" refresh failed; last-known-good registration retained.`,detail:f}),t.onEvent?.(`A2A Agent "${l}" could not be refreshed; its last-known-good registration was retained.`),c.delete(g)}}for(let l of c)await n.admin.agentRegistrations.remove(l)},"reconcile"),o=await r.initialize();return await s(o.document),r.subscribe(async(a,d)=>{a.revision!==d?.revision&&(await s(a.document),t.onEvent?.(`A2A configuration hot-reloaded (${Object.keys(a.document.agents).length} outbound Agents).`))}),r.startWatching(),{status:i(()=>r.status(),"status"),async reload(){await r.reload()},close(){r.close()}}}}}i(ar,"createConfiguredA2ARuntimeIntegration");export{u as A2AError,L as A2A_EXECUTOR_ID,C as A2A_PROTOCOL_VERSION,rt as assertSafeA2AUrl,zn as classifyA2AServerChange,Ie as createA2AAgentExecutorFactory,Yn as createA2AServerHotOptions,Zn as createA2AServerOptionsFromConfig,$e as createBearerEnvA2AAuthentication,ar as createConfiguredA2ARuntimeIntegration,Mn as createKodaXA2AServer,X as decodeUtf8,be as discoverA2ARegistration,q as errorMessage,A as isRecord,he as parseA2AAgentCard,ne as parseA2AIntegrationDocument,v as parseA2AMessage,we as parseA2APart,I as parseA2ATask,ke as parseJsonRpcRequest,Dn as prepareKodaXA2AServer,F as readA2AIntegration,Fn as removeA2AOutboundAgent,W as safeA2AFetch,Jn as setA2AServerConfig,Hn as upsertA2AOutboundAgent};
10
+ `}waitForTask(e,n){let r=this.#e.get(e);return r?R.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(s=>{let i=!1,a=o(()=>{},"unsubscribe"),d=o(l=>{i||(i=!0,clearTimeout(c),a(),s(l))},"finish"),c=setTimeout(()=>d(this.#e.get(e)??r),n);a=this.#e.subscribe(e,l=>{(R.has(l.task.status.state)||l.task.status.state==="TASK_STATE_INPUT_REQUIRED"||l.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&d(l)});let A=this.#e.get(e);A&&(R.has(A.task.status.state)||A.task.status.state==="TASK_STATE_INPUT_REQUIRED"||A.task.status.state==="TASK_STATE_AUTH_REQUIRED")&&d(A)}):Promise.reject(new u(-32001,"Task not found."))}requireOwnedTask(e,n){let r=this.#e.get(e);if(!r||r.principalKey!==n)throw new u(-32001,"Task not found.");return r}async recover(){let e=this.options;for(let n of this.#e.all()){if(R.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 s=await e.runtime.runs.get(r);if(s.phase==="running"||s.phase==="queued"||s.phase==="waiting_permission"||s.phase==="waiting_user_input"){for(let i of await e.runtime.events.replay({runId:r,sinceSeq:n.lastRuntimeEventSeq}))this.onRuntimeEvent(n.taskId,i,e);this.subscribeRuntime(n,r,e),e.runtime.runs.await(r).then(i=>this.finishRun(n.taskId,i,e)).catch(()=>{this.failTask(n.taskId,"Runtime execution failed during A2A recovery.",e)})}else this.finishRun(n.taskId,{runId:r,sessionId:n.sessionId,phase:s.phase},e)}catch(s){q({source:"a2a.server",level:"warn",message:"A2A task recovery could not reattach to its Runtime run.",detail:{taskId:n.taskId,error:s}}),this.failTask(n.taskId,"Runtime execution was unavailable during A2A recovery.",e)}}}emit(e){this.options.onEvent?.(e)}};function nr(t){return new re(t)}o(nr,"createKodaXA2AServer");async function Ft(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 s=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}),i=!1;return{service:n,ownerSessionId:r.ownerSessionId,binding:s,declaration:e,prepareWorkspace(a){return n.prepareWorkspace({ownerSessionId:r.ownerSessionId,bindingId:s.bindingId,contextKey:a})},start(a){let d={ownerSessionId:r.ownerSessionId,bindingId:s.bindingId,expectedExecutionPolicyRevision:s.executionPolicyRevision,sessionId:a.sessionId,input:a.inputs,permissionBroker:"runtime",agentContext:{actorId:`a2a:${a.principalKey.slice(0,16)}`}};if(e.kind==="local-agent"){let c="configurationRevision"in s&&typeof s.configurationRevision=="string"?s.configurationRevision:void 0;if(!c)throw new Error("Prepared local-Agent binding is missing its revision.");return n.startLocal({...d,expectedConfigurationRevision:c})}return n.startDefault(d)},async close(){i||(i=!0,await n.closeOwnerSession(r.ownerSessionId))}}}catch(s){throw await n.closeOwnerSession(r.ownerSessionId),s}}o(Ft,"prepareExecution");async function rr(t){let e=await Ft(t);try{let n=new re({...t,preparedExecution:e});return await n.whenReady(),n}catch(n){throw await e.close(),n}}o(rr,"prepareKodaXA2AServer");import{createHash as Jt}from"node:crypto";import{existsSync as Wt,readFileSync as Xt}from"node:fs";import se from"node:path";import{isDeepStrictEqual as ke}from"node:util";var He={maxRequestBytes:33554432,maxPartBytes:16777216,maxConcurrentTasks:4,maxTaskWaitMs:3e4,maxActiveTasksPerPrincipal:4,maxRetainedTasksPerPrincipal:100,maxEventsPerTask:1e3,maxEventBytesPerTask:16777216,maxWorkspaceBytesPerContext:1073741824},ze=Object.keys(He),ie=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Gt=/^[A-Za-z_][A-Za-z0-9_]*$/;function x(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object.`);return t}o(x,"record");function k(t,e,n){let r=new Set(e),s=Object.keys(t).find(i=>!r.has(i));if(s!==void 0)throw new Error(`${n} has unknown field "${s}".`)}o(k,"noUnknown");function E(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} must be a non-empty string.`);return t.trim()}o(E,"text");function X(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((s,i)=>E(s,`${e}[${i}]`));if(new Set(r).size!==r.length)throw new Error(`${e} contains duplicates.`);return r}o(X,"stringList");function Fe(t,e,n=!0){let r=X(t,e,n);if(r.some(s=>s.includes("*")))throw new Error(`${e} does not accept wildcard authority.`);return r}o(Fe,"exactNames");function Je(t,e){let n=x(t,e),r={};for(let[s,i]of Object.entries(n)){if(!ie.test(s)||s.includes("*"))throw new Error(`${e} keys must be exact names without wildcards.`);r[s]=Fe(i,`${e}.${s}`,!1)}return r}o(Je,"namedExactLists");function Qt(t,e){let n=x(t,e);k(n,["cardUrl","credentialEnv","effect"],e);let r=We(n.cardUrl,`${e}.cardUrl`,!0),s=n.effect;if(!["none","read","write","unknown"].includes(String(s)))throw new Error(`${e}.effect is invalid.`);let i=n.credentialEnv===void 0?void 0:Xe(n.credentialEnv,`${e}.credentialEnv`);return{cardUrl:r,...i?{credentialEnv:i}:{},effect:s}}o(Qt,"parseOutboundAgent");function We(t,e,n){let r=E(t,e),s;try{s=new URL(r)}catch(a){throw new Error(`${e} must be an absolute HTTP URL.`,{cause:a})}if(s.username||s.password)throw new Error(`${e} must not contain embedded credentials.`);let i=["localhost","127.0.0.1","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&i&&n))throw new Error(`${e} must use HTTPS or explicit loopback HTTP.`);return s.toString()}o(We,"parseHttpUrl");function Xe(t,e){let n=E(t,e);if(!Gt.test(n))throw new Error(`${e} must be an environment variable name.`);return n}o(Xe,"parseEnvironmentName");function Vt(t){if(t===void 0)return{mode:"managed"};let e=x(t,"A2A server execution.workspace");if(e.mode==="managed")return k(e,["mode"],"A2A server execution.workspace"),{mode:"managed"};if(e.mode!=="fixed")throw new Error("A2A server execution.workspace.mode is invalid.");k(e,["mode","root"],"A2A server execution.workspace");let n=E(e.root,"A2A server execution.workspace.root");if(!se.isAbsolute(n))throw new Error("Fixed A2A workspace root must be absolute.");return{mode:"fixed",root:se.resolve(n)}}o(Vt,"parseWorkspace");function Zt(t){return{workspace:t.mode==="managed"?"write":"read",process:"deny",network:{mode:"deny"},tools:[],mcp:{},skillScripts:{},subagents:"deny"}}o(Zt,"defaultToolPolicy");function Yt(t){let e=x(t,"A2A toolPolicy.network");if(e.mode==="deny")return k(e,["mode"],"A2A toolPolicy.network"),{mode:"deny"};if(e.mode!=="allowlist")throw new Error("A2A toolPolicy.network.mode is invalid.");k(e,["mode","origins"],"A2A toolPolicy.network");let n=X(e.origins,"A2A toolPolicy.network.origins").map(r=>{let s;try{s=new URL(r)}catch(i){throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.",{cause:i})}if(!["http:","https:"].includes(s.protocol)||s.origin==="null")throw new Error("A2A toolPolicy network origins must be absolute HTTP origins.");return s.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(Yt,"parseNetworkPolicy");function en(t){let e=Je(t,"A2A toolPolicy.skillScripts");for(let[n,r]of Object.entries(e))e[n]=r.map(s=>{if(s.includes("\\")||se.posix.isAbsolute(s))throw new Error("A2A skillScripts paths must use relative POSIX scripts/... paths.");let i=se.posix.normalize(s);if(!i.startsWith("scripts/")||i.includes("../"))throw new Error("A2A skillScripts paths must remain below the Skill scripts directory.");return i});return e}o(en,"parseSkillScripts");function tn(t,e){if(t===void 0)return Zt(e);let n=x(t,"A2A server execution.toolPolicy"),r=["workspace","process","network","tools","mcp","skillScripts","subagents"];if(k(n,r,"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 s=en(n.skillScripts),i=Object.values(s).reduce((a,d)=>a+d.length,0);if(n.process==="deny"&&i>0)throw new Error("A2A toolPolicy process deny requires empty skillScripts.");if(n.process==="isolated"&&i===0)throw new Error("A2A toolPolicy process isolated requires non-empty skillScripts.");return{workspace:n.workspace,process:n.process,network:Yt(n.network),tools:Fe(n.tools,"A2A toolPolicy.tools"),mcp:Je(n.mcp,"A2A toolPolicy.mcp"),skillScripts:s,subagents:n.subagents}}o(tn,"parseToolPolicy");function nn(t){let e=x(t,"A2A server execution"),n=Vt(e.workspace),r=tn(e.toolPolicy,n),s=e.profileId===void 0?void 0:E(e.profileId,"A2A server execution.profileId");if(e.kind==="runtime-default")return k(e,["kind","workspace","toolPolicy","profileId"],"A2A server execution"),{kind:"runtime-default",workspace:n,toolPolicy:r,...s?{profileId:s}:{}};if(e.kind!=="local-agent")throw new Error("A2A server execution.kind is invalid.");k(e,["kind","agentRef","workspace","toolPolicy","profileId"],"A2A server execution");let i=x(e.agentRef,"A2A server execution.agentRef");if(k(i,["source","name"],"A2A server execution.agentRef"),i.source!=="markdown:user")throw new Error("A2A local Agent source must be markdown:user.");let a=E(i.name,"A2A server execution.agentRef.name");if(!ie.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,...s?{profileId:s}:{}}}o(nn,"parseExecution");function rn(t,e){let n=`A2A server published.skills[${e}]`,r=x(t,n);return k(r,["id","name","description","tags"],n),{id:E(r.id,`${n}.id`),name:E(r.name,`${n}.name`),description:E(r.description,`${n}.description`),tags:X(r.tags,`${n}.tags`,!0)}}o(rn,"parsePublishedSkill");function sn(t){let e=x(t,"A2A server published");if(k(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(rn),r=n.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("A2A published Skill ids must be unique.");return{name:E(e.name,"A2A server published.name"),description:E(e.description,"A2A server published.description"),version:E(e.version,"A2A server published.version"),skills:n,inputModes:X(e.inputModes,"A2A server published.inputModes"),outputModes:X(e.outputModes,"A2A server published.outputModes")}}o(sn,"parsePublished");function on(t){let e=x(t,"A2A server authentication");if(k(e,["type","tokenEnv","principalId"],"A2A server authentication"),e.type!=="bearer-env")throw new Error("A2A authentication type must be bearer-env.");return{type:"bearer-env",tokenEnv:Xe(e.tokenEnv,"A2A server authentication.tokenEnv"),principalId:E(e.principalId,"A2A server authentication.principalId")}}o(on,"parseAuthentication");function an(t,e){if(!Number.isSafeInteger(t)||Number(t)<=0)throw new Error(`${e} must be a positive safe integer.`);return Number(t)}o(an,"positiveInteger");function dn(t,e){let n=t===void 0?{}:x(t,"A2A server limits");k(n,ze,"A2A server limits");let r=Object.fromEntries(ze.map(i=>[i,n[i]===void 0?He[i]:an(n[i],`A2A server limits.${i}`)]));if(r.maxPartBytes>r.maxRequestBytes)throw new Error("A2A server limits.maxPartBytes must not exceed maxRequestBytes.");let s=e.workspace.mode==="fixed"&&e.toolPolicy.workspace==="write";if(s&&n.maxConcurrentTasks===void 0)return{...r,maxConcurrentTasks:1};if(s&&r.maxConcurrentTasks!==1)throw new Error("A2A fixed writable workspace requires maxConcurrentTasks 1.");return r}o(dn,"parseLimits");function cn(t){let e=x(t,"A2A server");k(e,["execution","published","publicBaseUrl","authentication","limits","dataDir"],"A2A server");let n=nn(e.execution),r=e.publicBaseUrl===void 0?void 0:We(e.publicBaseUrl,"A2A server.publicBaseUrl",!0);return{execution:n,published:sn(e.published),...r?{publicBaseUrl:r}:{},authentication:on(e.authentication),limits:dn(e.limits,n),dataDir:E(e.dataDir,"A2A server.dataDir")}}o(cn,"parseServer");function oe(t){let e=x(t,"A2A integration config");if(k(e,["version","agents","server"],"A2A integration config"),e.version!==1)throw new Error("A2A integration config version must be 1.");let n=x(e.agents,"A2A integration config agents"),r={};for(let[s,i]of Object.entries(n)){if(!ie.test(s))throw new Error(`A2A outbound Agent name "${s}" is invalid.`);r[s]=Qt(i,`A2A outbound Agent "${s}"`)}return{version:1,agents:r,...e.server===void 0?{}:{server:cn(e.server)}}}o(oe,"parseA2AIntegrationDocument");function un(t){return Jt("sha256").update(t).digest("hex")}o(un,"hash");function G(t){let e=Se("a2a",t),n=Wt(e),r=n?Xt(e,"utf8"):JSON.stringify({version:1,agents:{}}),s;try{s=JSON.parse(r)}catch(i){throw new Error("Invalid A2A integration JSON.",{cause:i})}return{domain:"a2a",source:n?"user":"default",path:e,revision:un(r),document:oe(s),loadedAt:new Date().toISOString()}}o(G,"readA2AIntegration");function Te(t,e,n){return Re({domain:"a2a",configHome:t,document:e,validate:oe,...n?{expectedRevision:n}:{}})}o(Te,"writeA2AIntegration");function lr(t,e,n,r){if(!ie.test(e))throw new Error("A2A outbound Agent name is invalid.");let s=G(t);return Te(t,{...s.document,agents:{...s.document.agents,[e]:n}},r??(s.source==="user"?s.revision:void 0))}o(lr,"upsertA2AOutboundAgent");function Ar(t,e,n){let r=G(t);if(r.document.agents[e]===void 0)return!1;let s={...r.document.agents};return delete s[e],Te(t,{...r.document,agents:s},n??(r.source==="user"?r.revision:void 0)),!0}o(Ar,"removeA2AOutboundAgent");function pr(t,e,n){let r=G(t),s=e===void 0?{version:1,agents:r.document.agents}:{...r.document,server:e};return Te(t,s,n??(r.source==="user"?r.revision:void 0))}o(pr,"setA2AServerConfig");function fr(t,e){if(ke(t,e))return{kind:"none",fields:[]};if(t===void 0||e===void 0)return{kind:"restart-required",fields:["server"]};let n=["execution","dataDir"].filter(s=>!ke(t[s],e[s])),r=["published","publicBaseUrl","authentication","limits"].filter(s=>!ke(t[s],e[s]));return n.length>0?{kind:"restart-required",fields:[...n,...r]}:{kind:"hot",fields:r}}o(fr,"classifyA2AServerChange");import{timingSafeEqual as ln}from"node:crypto";import Ge from"node:os";import Qe from"node:path";function An(t){return t==="~"?Ge.homedir():t.startsWith("~/")||t.startsWith("~\\")?Qe.join(Ge.homedir(),t.slice(2)):Qe.resolve(t)}o(An,"expandHome");function pn(t){let e=t.headers.get("authorization");return(e?/^Bearer ([^\s]+)$/i.exec(e):null)?.[1]}o(pn,"bearerToken");function fn(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.byteLength===r.byteLength&&ln(n,r)}o(fn,"equalSecret");function Ve(t,e=process.env){let n=e[t.tokenEnv];if(!n)throw new Error(`A2A bearer token environment variable is unset: ${t.tokenEnv}.`);return{securitySchemes:{bearer:{httpAuthSecurityScheme:{scheme:"Bearer",bearerFormat:"opaque"}}},securityRequirements:[{schemes:{bearer:{list:[]}}}],async authenticate(r){let s=pn(r);return s&&fn(n,s)?{subject:t.principalId,scopes:["a2a:invoke"]}:null}}}o(Ve,"createBearerEnvA2AAuthentication");function Ze(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(Ze,"publishedAgent");function Ye(){return Promise.resolve(!0)}o(Ye,"authorization");function kr(t){return{runtime:t.runtime,agent:Ze(t.config,t.listenBaseUrl),execution:t.config.execution,dataDir:An(t.config.dataDir),limits:t.config.limits,authentication:Ve(t.config.authentication,t.env),authorize:Ye}}o(kr,"createA2AServerOptionsFromConfig");function Tr(t){return{agent:Ze(t.config,t.listenBaseUrl),limits:t.config.limits,authentication:Ve(t.config.authentication,t.env),authorize:Ye}}o(Tr,"createA2AServerHotOptions");function gn(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="127.0.0.1"||e==="::1"}o(gn,"isExactLoopback");function et(t){return{allowedOrigins:[t.origin],allowPrivateAddresses:gn(t.hostname),requestTimeoutMs:1e4,maxResponseBytes:1e6,maxRedirects:3}}o(et,"networkPolicy");function mn(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(mn,"registrationUrl");function yn(){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(yn,"environmentCredentialBroker");function hn(t,e){return{agentId:`external:${t}`,agentCardUrl:e.cardUrl,...e.credentialEnv?{credentialRef:`env:${e.credentialEnv}`}:{},effects:{remote:e.effect}}}o(hn,"registrationInput");function Pr(t){return{runtimeOptions:{factories:[Le(n=>({networkPolicy:et(mn(n)),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}}))],policy:o(()=>({allowed:!0}),"policy"),credentialBroker:yn()},async start(n){let r=new Ee({domain:"a2a",configHome:t.configHome,validate:oe,read:o(()=>G(t.configHome),"read")}),s=o(async a=>{let d=await n.admin.agentRegistrations.list(),c=new Set(d.filter(A=>A.executorId===j).map(A=>A.agentId));for(let[A,l]of Object.entries(a.agents)){let p=`external:${A}`;try{let g=new URL(l.cardUrl),m=await Ue(hn(A,l),{networkPolicy:et(g),pollIntervalMs:500,...t.fetch?{fetch:t.fetch}:{}});await n.admin.agentRegistrations.upsert(m.registration),c.delete(p)}catch(g){q({source:"a2a.runtime-config",level:"warn",message:`A2A Agent "${A}" refresh failed; last-known-good registration retained.`,detail:g}),t.onEvent?.(`A2A Agent "${A}" could not be refreshed; its last-known-good registration was retained.`),c.delete(p)}}for(let A of c)await n.admin.agentRegistrations.remove(A)},"reconcile"),i=await r.initialize();return await s(i.document),r.subscribe(async(a,d)=>{a.revision!==d?.revision&&(await s(a.document),t.onEvent?.(`A2A configuration hot-reloaded (${Object.keys(a.document.agents).length} outbound Agents).`))}),r.startWatching(),{status:o(()=>r.status(),"status"),async reload(){await r.reload()},close(){r.close()}}}}}o(Pr,"createConfiguredA2ARuntimeIntegration");export{u as A2AError,j as A2A_EXECUTOR_ID,N as A2A_PROTOCOL_VERSION,lt as assertSafeA2AUrl,fr as classifyA2AServerChange,Le as createA2AAgentExecutorFactory,Tr as createA2AServerHotOptions,kr as createA2AServerOptionsFromConfig,Ve as createBearerEnvA2AAuthentication,Pr as createConfiguredA2ARuntimeIntegration,nr as createKodaXA2AServer,Y as decodeUtf8,Ue as discoverA2ARegistration,V as errorMessage,f as isRecord,xe as parseA2AAgentCard,oe as parseA2AIntegrationDocument,v as parseA2AMessage,Ie as parseA2APart,_ as parseA2ATask,be as parseJsonRpcRequest,rr as prepareKodaXA2AServer,G as readA2AIntegration,Ar as removeA2AOutboundAgent,Z as safeA2AFetch,pr as setA2AServerConfig,lr as upsertA2AOutboundAgent};
@@ -7,7 +7,7 @@ import { T as KodaXTaskResultSource, S as KodaXTaskResultMetadata, i as KodaXIma
7
7
  export { K as KodaXAssuranceIntent, c as KodaXContentBlock, f as KodaXExecutionMode, g as KodaXExecutionPattern, m as KodaXMutationSurface, q as KodaXProviderConfig, y as KodaXProviderStreamOptions, B as KodaXReasoningCapability, F as KodaXReasoningMode, H as KodaXReasoningRequest, I as KodaXRedactedThinkingBlock, L as KodaXRiskLevel, N as KodaXStreamResult, O as KodaXTaskActionability, P as KodaXTaskBudgetOverrides, Q as KodaXTaskComplexity, R as KodaXTaskFamily, U as KodaXTaskRoutingDecision, V as KodaXTaskType, W as KodaXTaskWorkIntent, X as KodaXTextBlock, Y as KodaXThinkingBlock, Z as KodaXThinkingBudgetMap, _ as KodaXThinkingDepth, a0 as KodaXTokenUsage, a2 as KodaXToolResultBlock } from './types-chunks/types.d-TTvpAGWf.js';
8
8
  import { C as CapabilityCache, b as CapabilityCacheSource } from './types-chunks/capability-learning.d-WtsyRv3O.js';
9
9
  export { a as CapabilityCacheEntry } from './types-chunks/capability-learning.d-WtsyRv3O.js';
10
- export { C as CapabilityKind, a as CapabilityProvider, b as CapabilityResult } from './types-chunks/capability.d-3C62G8Eq.js';
10
+ export { C as CapabilityKind, a as CapabilityProvider, b as CapabilityResult, c as CapabilitySearchFailure, d as CapabilitySearchFreshness, e as CapabilitySearchOptions, f as CapabilitySearchSnapshot } from './types-chunks/capability.d-K664nHOS.js';
11
11
  import { ChildProcess } from 'node:child_process';
12
12
  import { c as QueuedMessage, a as MessagePriority, b as QueuedInputArtifact, M as MessageMode } from './types-chunks/types.d-CJR7t6iW.js';
13
13
  export { D as DequeueFilter, E as EnqueueInput } from './types-chunks/types.d-CJR7t6iW.js';
@@ -15,7 +15,7 @@ import { K as KodaXBaseProvider } from './types-chunks/base.d-CYjtB68X.js';
15
15
  import { l as SkillSource } from './types-chunks/types.d-vJExiRje.js';
16
16
  export { I as ISkillRegistry, a as IVariableResolver, S as Skill, b as SkillArtifact, c as SkillContext, d as SkillDynamicContextExecutor, e as SkillFile, f as SkillFrontmatter, g as SkillHook, h as SkillHooks, i as SkillMetadata, j as SkillPathsConfig, k as SkillResult, m as getDefaultSkillPaths, n as getSkillPathsFlat } from './types-chunks/types.d-vJExiRje.js';
17
17
  export { M as McpConnectMode, a as McpServerConfig, b as McpServersConfig, c as McpTransportKind } from './types-chunks/config.d-CJy1WENT.js';
18
- export { M as McpCapabilityDescriptor, a as McpCapabilityKind, b as McpCapabilityProvider, c as McpCapabilityRisk, d as McpCatalogItem, e as McpElicitRequest, f as McpElicitResult, g as McpIcon, h as McpManager, i as McpProviderOptions, j as McpReverseCapabilities, k as McpRoot, l as McpSamplingRequest, m as McpSamplingResult, n as McpServerCatalog, o as McpServerCatalogSnapshot, p as McpServerLogs, q as McpServerRuntime, r as McpServerRuntimeDiagnostics, s as McpServerStatus, t as McpServerToolList, u as McpToolTaskSupport, v as buildInitializeCapabilities, w as createMcpCapabilityId, x as createMcpManager, y as defaultMcpCacheDir, z as getMcpCachePaths, A as normalizeMcpCapabilityId, B as parseMcpCapabilityId, C as searchMcpCatalog } from './types-chunks/manager.d-CoEuPRAo.js';
18
+ export { M as McpCapabilityDescriptor, a as McpCapabilityKind, b as McpCapabilityProvider, c as McpCapabilityRisk, d as McpCatalogItem, e as McpDiscoveryCatalog, f as McpElicitRequest, g as McpElicitResult, h as McpIcon, i as McpManager, j as McpProviderOptions, k as McpReverseCapabilities, l as McpRoot, m as McpSamplingRequest, n as McpSamplingResult, o as McpServerCatalog, p as McpServerCatalogSnapshot, q as McpServerLogs, r as McpServerRuntime, s as McpServerRuntimeDiagnostics, t as McpServerStatus, u as McpServerToolList, v as McpToolTaskSupport, w as buildInitializeCapabilities, x as createMcpCapabilityId, y as createMcpManager, z as defaultMcpCacheDir, A as getMcpCachePaths, B as normalizeMcpCapabilityId, C as parseMcpCapabilityId, D as searchMcpCatalog } from './types-chunks/manager.d-B67TmPO1.js';
19
19
  export { A as AuthorizationServerMetadata, D as DiscoveredOAuthEndpoints, M as McpAuthRequiredError, a as McpExpiredSessionError, b as McpTransport, c as McpTransportEvents, O as OAuthClientInfo, d as OAuthLoginConsent, P as PerformOAuthLoginOptions, e as ProtectedResourceMetadata, W as WwwAuthenticateChallenge, f as createMcpTransport, g as discoverAuthorizationServerMetadata, h as discoverOAuthEndpoints, i as discoverProtectedResourceMetadata, j as extractInsufficientScope, k as extractResourceMetadataUrl, l as loadValidToken, p as performOAuthLogin, r as registerOAuthClient } from './types-chunks/oauth-login.d-Bgb4rdLN.js';
20
20
  export { createMcpTestServerFixture } from './sdk-mcp.js';
21
21
  export { DiscoveryResult, ExecutionMode, ExecutionOptions, SkillExecutor, SkillExpansionResult, SkillRegistry, VariableResolver, clearPluginSkillPaths, createExecutor, createResolver, discoverSkills, discoverSkillsWithMonorepo, executeSkill, expandSkillForLLM, formatSkillActivationMessage, getNestedSkillPaths, getSkillRegistry, initializeSkillRegistry, listPluginSkillPaths, loadFullSkill, loadSkillFileContent, loadSkillMetadata, parseArguments, parseSkillMarkdown, registerPluginSkillPath, resetSkillRegistry, resolveSkillContent, unregisterPluginSkillPath } from './sdk-skills.js';
package/dist/sdk-agent.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{$ as Go,$a as Kr,$b as Mf,$c as Mm,A as mo,Aa as pr,Ab as cf,Ac as dm,Ad as dp,B as po,Ba as tr,Bb as df,Bc as gm,Bd as gp,C as to,Ca as dr,Cb as gf,Cc as hm,Cd as hp,D as xo,Da as gr,Db as hf,Dc as im,Dd as ip,E as ao,Ea as hr,Eb as jf,Ec as jm,Ed as jp,F as bo,Fa as ir,Fb as kf,Fc as km,Fd as kp,G as co,Ga as jr,Gb as lf,Gc as lm,Gd as lp,H as go,Ha as kr,Hb as nf,Hc as nm,Hd as np,I as ho,Ia as lr,Ib as qf,Ic as qm,Id as qp,J as io,Ja as nr,Jb as sf,Jc as sm,Jd as sp,K as jo,Ka as qr,Kb as uf,Kc as um,Kd as up,L as ko,La as sr,Lb as vf,Lc as vm,Ld as vp,M as lo,Ma as ur,Mb as wf,Mc as wm,Md as wp,N as no,Na as vr,Nb as yf,Nc as ym,Nd as yp,O as qo,Oa as wr,Ob as zf,Oc as zm,Od as zp,P as so,Pa as yr,Pb as Af,Pc as Am,Pd as Ap,Q as uo,Qa as zr,Qb as Bf,Qc as Bm,Qd as Bp,R as vo,Ra as Ar,Rb as Cf,Rc as Cm,Rd as Cp,S as wo,Sa as Br,Sb as Df,Sc as Dm,Sd as Dp,T as yo,Ta as Cr,Tb as Ef,Tc as Em,U as zo,Ua as Dr,Ub as Ff,Uc as Fm,V as Ao,Va as Er,Vb as Gf,Vc as Gm,W as Bo,Wa as Fr,Wb as Hf,Wc as Hm,X as Co,Xa as Gr,Xb as If,Xc as Im,Y as Do,Ya as Hr,Yb as Jf,Yc as Jm,Z as Eo,Za as Ir,Zb as Kf,Zc as Km,_ as Fo,_a as Jr,_b as Lf,_c as Lm,a as D,aa as Ho,ab as Lr,ac as Nf,ad as Nm,b as E,ba as Io,bb as Mr,bc as Of,bd as Om,c as F,ca as Jo,cb as Nr,cc as Pf,cd as Pm,d as G,da as Ko,db as Or,dc as Qf,dd as Qm,e as H,ea as Lo,eb as Pr,ec as Rf,ed as Rm,f as I,fa as Mo,fb as Qr,fc as Sf,fd as Sm,g as J,ga as No,gb as Rr,gc as Tf,gd as Tm,h as K,ha as Oo,hb as Sr,hc as Uf,hd as Um,i as L,ia as Po,ib as Tr,ic as Vf,id as Vm,j as M,ja as Qo,jb as Ur,jc as Wf,jd as Wm,k as N,ka as Ro,kb as Vr,kc as Xf,kd as Xm,l as O,la as So,lb as Wr,lc as Yf,ld as Ym,m as P,ma as To,mb as Xr,mc as Zf,md as Zm,n as Q,na as Uo,nb as Yr,nc as _f,nd as _m,o as R,oa as Vo,ob as Zr,oc as $f,od as $m,p as S,pa as Wo,pb as _r,pc as om,pd as op,q as T,qa as Xo,qb as $r,qc as rm,qd as rp,r as U,ra as Yo,rb as oe,rc as em,rd as ep,s as Y,sa as Zo,sb as re,sc as fm,sd as fp,t as Z,ta as _o,tb as ee,tc as mm,td as mp,u as _,ua as $o,ub as fe,uc as pm,ud as pp,v as $,va as or,vb as me,vc as tm,vd as tp,w as oo,wa as rr,wb as pe,wc as xm,wd as xp,x as ro,xa as er,xb as te,xc as am,xd as ap,y as eo,ya as fr,yb as af,yc as bm,yd as bp,z as fo,za as mr,zb as bf,zc as cm,zd as cp}from"./chunks/chunk-VYKFM3TB.js";import{$ as Ye,A as Ae,B as Be,C as Ce,D as De,E as Ee,I as Fe,J as Ge,K as He,L as Ie,M as Je,N as Ke,O as Le,P as Me,Q as Ne,R as Oe,S as Pe,T as Qe,U as Re,V as Se,W as Te,X as Ue,Y as Ve,Z as We,_ as Xe,a as V,aa as Ze,b as W,ba as _e,c as X,ca as $e,d as xr,da as of,e as ar,ea as rf,f as br,fa as ef,g as cr,ga as ff,h as xe,ha as mf,i as ae,ia as pf,j as be,ja as tf,k as ce,ka as xf,l as de,m as ge,n as he,o as ie,p as je,q as ke,r as le,s as ne,t as qe,u as se,v as ue,w as ve,x as we,y as ye,z as ze}from"./chunks/chunk-AWMTNUDS.js";import{A,B,C,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunks/chunk-F7C7J6IM.js";import"./chunks/chunk-NGHQIGVW.js";import"./chunks/chunk-ONUPGMER.js";export{Er as ASK_USER_BACK_SIGNAL,Fr as ASK_USER_CUSTOM_INPUT_SIGNAL,Bp as AgentCancellationUncertainError,Ap as AgentStartUncertainError,dr as CAPABILITY_CACHE_FILENAME,Lm as COMPACTION_SUMMARY_PREFIX,P as CONTEXT_SAFETY_FLOOR_TOKENS,Q as CONTEXT_SAFETY_RATIO,pr as CORE_INVARIANTS,go as ConsoleTracingProcessor,R as ContextCapacityError,Xm as DEFAULT_CONTEXT_WINDOW,Rr as DEFAULT_IDLE_YIELD_MAX_ITERATIONS,Pm as DEFAULT_MICROCOMPACTION_CONFIG,pm as DEFAULT_POST_COMPACT_CONFIG,Gm as DEFAULT_SUMMARY_PROMPT,zo as DEFAULT_SYSTEM_CAP,Hm as DEFAULT_UPDATE_SUMMARY_PROMPT,$ as DefaultSummaryCompaction,Tm as FileExtensionStore,ho as FileTracingProcessor,No as GuardrailBlockedError,Oo as GuardrailEscalateError,nr as HARDENED_ENV_VARS,qr as HARDENING_OPT_OUT_ENV,r as ImageResizeError,Fo as InvariantSession,L as KODAX_API_MIN_INTERVAL,E as KODAX_DEFAULT_TIMEOUT,n as KODAX_FILE_MEDIA_TYPES,F as KODAX_HARD_TIMEOUT,k as KODAX_IMAGE_MEDIA_TYPES,I as KODAX_MAX_INCOMPLETE_RETRIES,J as KODAX_MAX_MAXTOKENS_RETRIES,G as KODAX_MAX_RETRIES,D as KODAX_MAX_TOKENS,H as KODAX_RETRY_BASE_DELAY,K as KODAX_STAGGER_DELAY,l as KODAX_VIDEO_MEDIA_TYPES,o as KodaXMediaError,Xf as LINEAGE_ENTRY_TYPES,Zf as LineageCompaction,Yf as LineageExtension,x as MAX_DIMENSION,we as MAX_ENTRYPOINT_BYTES,ve as MAX_ENTRYPOINT_LINES,df as MAX_SKILL_MD_BYTES,gf as MAX_SKILL_SUPPORT_FILE_BYTES,Ho as MAX_TOOL_LOOP_ITERATIONS,ce as MEMORY_POLICY_VERSION,Hf as McpAuthRequiredError,Tf as McpCapabilityProvider,Gf as McpExpiredSessionError,Uf as McpManager,Sf as McpServerRuntime,ef as MemoryControlPlane,u as MessageQueue,g as PASTE_TMP_DIR_ENV,h as PASTE_TMP_TTL_MS,mm as POST_COMPACT_MAX_TOKENS_PER_FILE,fm as POST_COMPACT_TOKEN_BUDGET,M as PROMISE_PATTERN,Km as PROTECTED_TOOL_NAMES,Lr as QueuedInputArtifactError,or as Runner,Ue as SkillExecutor,Qe as SkillRegistry,oo as SpanImpl,a as TARGET_RAW_SIZE_BYTES,bo as Tracer,Ne as VariableResolver,dp as WORKFLOW_CAPSULE_API_VERSION,bp as WORKFLOW_CAPSULE_FORMAT,cp as WORKFLOW_CAPSULE_VERSION,rp as WORKFLOW_PATTERN_IDS,kp as WorkflowAbortError,np as WorkflowBudgetError,Zm as WorkflowEventRecorder,lp as WorkflowLimitError,pp as WorkflowScriptExecutionError,qp as WorkflowTaskFailedError,y as YIELD_TOOL_NAMES,to as _emitSpanEnd,po as _emitSpanStart,xo as _emitTraceEnd,mo as _getRegisteredProcessors,wo as _resetAdmissionMetrics,Eo as _resetAdmittedAgentBindings,qo as _resetInvariantRegistry,w as _resetMessageQueueForTests,_o as _resetPresetDispatchers,eo as addTracingProcessor,zm as appendGoalEntry,om as appendMemoryClientNotice,_f as appendMemoryOutcomeDigest,$f as appendMemoryReviewReceipt,im as appendSessionLineageLabel,km as applyLineageTruncation,io as applyManifestPatch,sr as applyProcessHardening,jm as applySessionCompaction,jf as applySkillLearningProposal,kf as approveStoredLearningProposal,vm as archiveOldIslands,Hr as asSingleSelection,mp as assertRestrictedWorkflowQuality,Xo as attachRunnerRecoveryTranscript,oe as bootstrapTeamMode,Lo as buildAssistantMessageFromLlmResult,Im as buildCompactionPromptSnapshot,am as buildFileContentMessages,Rf as buildInitializeCapabilities,Yr as buildOtherInstancesPromptBlock,tm as buildPostCompactAttachments,Sm as buildRecoverySeed,sm as buildSessionTree,$o as buildSystemPrompt,Mo as buildToolResultMessage,jp as buildWorkflowCapsuleIntent,S as calculateContextSafetyMargin,U as calculateMaxContextInputTokens,bf as canMarkCreatedByAgent,ee as cleanupIncompleteToolCalls,Dr as cleanupRegisteredManagedChildren,kr as clearCapabilityCache,Ce as clearPluginSkillPaths,Po as collectGuardrails,Om as compact,pf as completeEpisodeReview,Qr as composeIdleYieldUserMessage,jo as composePatches,yf as computeSkillConsumerImpact,um as countActiveLineageMessages,Nr as countLastAssistantToolCalls,O as countTokens,Y as createAgent,Cp as createAgentExecutorPlane,Ve as createExecutor,Um as createExtensionStore,p as createFileArtifactFromPath,Z as createHandoff,m as createImageArtifactFromPath,_ as createInMemorySession,Go as createInvariantSessionForAgent,te as createLlmJudgedStopHook,Bf as createMcpCapabilityId,Vf as createMcpManager,Wf as createMcpTestServerFixture,If as createMcpTransport,zp as createMemoryAgentExecutorPlaneStore,rf as createMemoryControlPlane,Dp as createReferenceAgentExecutorFactory,Oe as createResolver,ap as createRestrictedWorkflowModule,bm as createSessionLineage,Wr as createStateWriter,ro as createTrace,t as createVideoArtifactFromPath,hp as createWorkflowCapsule,ip as createWorkflowModuleFromCapsule,op as createWorkflowProcessTracker,wp as createWorkflowRunManager,up as createWorkflowRuntime,cf as decideSkillGovernance,Af as defaultMcpCacheDir,co as defaultTracer,Uo as detectHandoffSignal,Or as detectIdleYield,Ao as detectInstructionsInjection,Mf as discoverAuthorizationServerMetadata,Xr as discoverInstances,Nf as discoverOAuthEndpoints,Lf as discoverProtectedResourceMetadata,Je as discoverSkills,Le as discoverSkillsWithMonorepo,xf as drainPendingEpisodeReviews,fe as editDistance,Wo as emitHandoffSpan,W as emitKodaXDiagnostic,B as enqueueChildTaskNotification,C as enqueueWithArtifacts,N as estimateTokens,er as evidenceTrail,T as exceedsContextCapacity,Ko as executeRunnerToolCall,We as executeSkill,Xe as expandSkillForLLM,Dm as extractArtifactLedger,rr as extractAssistantTextFromMessage,Bm as extractFileOps,Kf as extractInsufficientScope,Jf as extractResourceMetadataUrl,em as extractTitleFromMessages,fr as finalOwner,me as findFuzzyToolMatch,lm as findPreviousUserEntryId,qm as forkSessionLineage,X as formatKodaXDiagnostic,Ye as formatSkillActivationMessage,rm as generateSessionId,Jm as generateSummary,_r as getActiveTeamModeWriter,Jr as getActiveUserInteraction,vo as getAdmissionMetricsSnapshot,Do as getAdmittedAgentBindings,ar as getAgentConfigHome,br as getAgentConfigPath,cr as getAppDataDir,ir as getCachedRejectedEfforts,gr as getCapabilityCacheFile,De as getDefaultSkillPaths,yp as getDefaultWorkflowRunManager,lo as getInvariant,Ff as getMcpCachePaths,v as getMessageQueue,q as getModelInputCapabilities,Ke as getNestedSkillPaths,cm as getSessionLineagePath,dm as getSessionMessagesFromLineage,Ee as getSkillPathsFlat,Re as getSkillRegistry,Wm as gracefulCompactDegradation,mr as handoffLegality,ge as hashCwd,ae as hashMemoryIdentityComponent,e as inferImageMediaType,f as inferVideoMediaType,Se as initializeSkillRegistry,xm as injectPostCompactAttachments,pe as invokeLlmJudge,yo as isAdmissionDebugEnabled,Gr as isAskUserCustomInputAnswer,le as isAutoManagedMemoryFile,vr as isChildProcessExited,Mm as isEmptyLikeSummary,_m as isFinalWorkflowProcessStatus,Am as isGoalEntry,Mr as isIdleYieldEnabled,Io as isRunnableTool,Jo as isRunnerLlmResult,Ar as killChildProcessTree,Br as killChildProcessTreeSync,yr as killPidTree,zr as killPidTreeSync,fp as lintRestrictedWorkflowSource,mf as listPendingEpisodeReviews,Be as listPluginSkillPaths,no as listRegisteredInvariants,hr as loadCapabilityCache,He as loadFullSkill,Ie as loadSkillFileContent,Ge as loadSkillMetadata,Qf as loadValidToken,xe as matchesMemoryApplicability,A as maybeDrainMidTurn,be as memoryApplicabilityFingerprint,Em as mergeArtifactLedger,Cm as mergeFileOps,Qm as microcompact,z as midTurnDrainPriority,Nm as needsCompaction,$m as normalizeHostMetadata,Cf as normalizeMcpCapabilityId,b as normalizePastedImage,Rm as normalizeRecoveryPrompt,sp as normalizeWorkflowLimits,Me as parseArguments,Df as parseMcpCapabilityId,se as parseMemoryFile,qe as parseMemoryType,ne as parseMemoryTypeFromFilename,ue as parseScalarFields,Fe as parseSkillMarkdown,Pf as performOAuthLogin,i as persistImageAsBlock,ff as persistPendingEpisodeReview,j as prunePasteTmpDir,d as readAndNormalizeClipboardImage,c as readClipboardImage,wm as readLatestGoalFromBranch,ym as readLatestGoalState,Ze as readLearningProposalStore,Yo as readRunnerRecoveryTranscript,vf as readSkillTrustLedger,sf as readSkillUsageLedger,zf as recordCompletedTurnLearning,lf as recordProceduralLearning,jr as recordRejectedEffort,uf as recordSkillUsage,Kr as registerChildTask,tr as registerCoreInvariants,ko as registerInvariant,Cr as registerManagedChildProcess,Of as registerOAuthClient,ze as registerPluginSkillPath,Zo as registerPresetDispatcher,Vo as replaceSystemMessage,Vr as requestTaskStop,lr as resetCapabilityCacheMemoForTesting,Te as resetSkillRegistry,Ym as resolveContextWindow,uo as resolveEffectiveInvariants,$e as resolveLearningProposalStore,je as resolveMemoryEntrypoint,ie as resolveMemoryRoot,so as resolveRequiredInvariants,ke as resolveScopedMemoryRoot,gm as resolveSessionLineageTarget,Pe as resolveSkillContent,hf as resolveSkillSnapshotLocation,qf as resolveSkillTrustLedger,nf as resolveSkillUsageLedger,tf as rewindPendingEpisodeReviews,nm as rewindSessionLineage,Ur as routeMessage,Bo as runAdmissionAudit,Tr as runFanOut,Qo as runInputGuardrails,Ro as runOutputGuardrails,xp as runRestrictedWorkflowScript,To as runToolAfterGuardrails,So as runToolBeforeGuardrails,Sr as runWithIdleYield,vp as runWorkflow,de as sanitizeProjectKey,Ef as searchMcpCatalog,Fm as serializeConversation,Zr as setActiveTeamModeWriter,Ir as setActiveUserInteraction,Co as setAdmittedAgentBindings,xr as setAgentConfigHome,V as setKodaXDiagnosticSink,hm as setSessionLineageActiveEntry,fo as setTracingProcessors,Vm as shouldCompact,ao as shutdownTracing,ur as stripHardenedEnvVars,af as triageProceduralLearning,ye as truncateEntrypointContent,he as tryGitRemote,Ae as unregisterPluginSkillPath,$r as updateActiveTeamMode,of as updateLearningProposalStatus,wf as updateSkillTrustLedger,_e as upsertLearningProposal,re as validateAndFixToolHistory,s as validateInputArtifactsForModel,tp as validateRestrictedWorkflowSource,gp as validateWorkflowCapsule,ep as validateWorkflowScriptManifest,wr as waitForChildProcessExit,Pr as waitForWakeEvent};
2
+ import{$ as Go,$a as Kr,$b as Mf,$c as Mm,A as mo,Aa as pr,Ab as cf,Ac as dm,Ad as dp,B as po,Ba as tr,Bb as df,Bc as gm,Bd as gp,C as to,Ca as dr,Cb as gf,Cc as hm,Cd as hp,D as xo,Da as gr,Db as hf,Dc as im,Dd as ip,E as ao,Ea as hr,Eb as jf,Ec as jm,Ed as jp,F as bo,Fa as ir,Fb as kf,Fc as km,Fd as kp,G as co,Ga as jr,Gb as lf,Gc as lm,Gd as lp,H as go,Ha as kr,Hb as nf,Hc as nm,Hd as np,I as ho,Ia as lr,Ib as qf,Ic as qm,Id as qp,J as io,Ja as nr,Jb as sf,Jc as sm,Jd as sp,K as jo,Ka as qr,Kb as uf,Kc as um,Kd as up,L as ko,La as sr,Lb as vf,Lc as vm,Ld as vp,M as lo,Ma as ur,Mb as wf,Mc as wm,Md as wp,N as no,Na as vr,Nb as yf,Nc as ym,Nd as yp,O as qo,Oa as wr,Ob as zf,Oc as zm,Od as zp,P as so,Pa as yr,Pb as Af,Pc as Am,Pd as Ap,Q as uo,Qa as zr,Qb as Bf,Qc as Bm,Qd as Bp,R as vo,Ra as Ar,Rb as Cf,Rc as Cm,Rd as Cp,S as wo,Sa as Br,Sb as Df,Sc as Dm,Sd as Dp,T as yo,Ta as Cr,Tb as Ef,Tc as Em,U as zo,Ua as Dr,Ub as Ff,Uc as Fm,V as Ao,Va as Er,Vb as Gf,Vc as Gm,W as Bo,Wa as Fr,Wb as Hf,Wc as Hm,X as Co,Xa as Gr,Xb as If,Xc as Im,Y as Do,Ya as Hr,Yb as Jf,Yc as Jm,Z as Eo,Za as Ir,Zb as Kf,Zc as Km,_ as Fo,_a as Jr,_b as Lf,_c as Lm,a as D,aa as Ho,ab as Lr,ac as Nf,ad as Nm,b as E,ba as Io,bb as Mr,bc as Of,bd as Om,c as F,ca as Jo,cb as Nr,cc as Pf,cd as Pm,d as G,da as Ko,db as Or,dc as Qf,dd as Qm,e as H,ea as Lo,eb as Pr,ec as Rf,ed as Rm,f as I,fa as Mo,fb as Qr,fc as Sf,fd as Sm,g as J,ga as No,gb as Rr,gc as Tf,gd as Tm,h as K,ha as Oo,hb as Sr,hc as Uf,hd as Um,i as L,ia as Po,ib as Tr,ic as Vf,id as Vm,j as M,ja as Qo,jb as Ur,jc as Wf,jd as Wm,k as N,ka as Ro,kb as Vr,kc as Xf,kd as Xm,l as O,la as So,lb as Wr,lc as Yf,ld as Ym,m as P,ma as To,mb as Xr,mc as Zf,md as Zm,n as Q,na as Uo,nb as Yr,nc as _f,nd as _m,o as R,oa as Vo,ob as Zr,oc as $f,od as $m,p as S,pa as Wo,pb as _r,pc as om,pd as op,q as T,qa as Xo,qb as $r,qc as rm,qd as rp,r as U,ra as Yo,rb as oe,rc as em,rd as ep,s as Y,sa as Zo,sb as re,sc as fm,sd as fp,t as Z,ta as _o,tb as ee,tc as mm,td as mp,u as _,ua as $o,ub as fe,uc as pm,ud as pp,v as $,va as or,vb as me,vc as tm,vd as tp,w as oo,wa as rr,wb as pe,wc as xm,wd as xp,x as ro,xa as er,xb as te,xc as am,xd as ap,y as eo,ya as fr,yb as af,yc as bm,yd as bp,z as fo,za as mr,zb as bf,zc as cm,zd as cp}from"./chunks/chunk-7PV577LP.js";import{$ as Ye,A as Ae,B as Be,C as Ce,D as De,E as Ee,I as Fe,J as Ge,K as He,L as Ie,M as Je,N as Ke,O as Le,P as Me,Q as Ne,R as Oe,S as Pe,T as Qe,U as Re,V as Se,W as Te,X as Ue,Y as Ve,Z as We,_ as Xe,a as V,aa as Ze,b as W,ba as _e,c as X,ca as $e,d as xr,da as of,e as ar,ea as rf,f as br,fa as ef,g as cr,ga as ff,h as xe,ha as mf,i as ae,ia as pf,j as be,ja as tf,k as ce,ka as xf,l as de,m as ge,n as he,o as ie,p as je,q as ke,r as le,s as ne,t as qe,u as se,v as ue,w as ve,x as we,y as ye,z as ze}from"./chunks/chunk-AWMTNUDS.js";import{A,B,C,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunks/chunk-F7C7J6IM.js";import"./chunks/chunk-NGHQIGVW.js";import"./chunks/chunk-ONUPGMER.js";export{Er as ASK_USER_BACK_SIGNAL,Fr as ASK_USER_CUSTOM_INPUT_SIGNAL,Bp as AgentCancellationUncertainError,Ap as AgentStartUncertainError,dr as CAPABILITY_CACHE_FILENAME,Lm as COMPACTION_SUMMARY_PREFIX,P as CONTEXT_SAFETY_FLOOR_TOKENS,Q as CONTEXT_SAFETY_RATIO,pr as CORE_INVARIANTS,go as ConsoleTracingProcessor,R as ContextCapacityError,Xm as DEFAULT_CONTEXT_WINDOW,Rr as DEFAULT_IDLE_YIELD_MAX_ITERATIONS,Pm as DEFAULT_MICROCOMPACTION_CONFIG,pm as DEFAULT_POST_COMPACT_CONFIG,Gm as DEFAULT_SUMMARY_PROMPT,zo as DEFAULT_SYSTEM_CAP,Hm as DEFAULT_UPDATE_SUMMARY_PROMPT,$ as DefaultSummaryCompaction,Tm as FileExtensionStore,ho as FileTracingProcessor,No as GuardrailBlockedError,Oo as GuardrailEscalateError,nr as HARDENED_ENV_VARS,qr as HARDENING_OPT_OUT_ENV,r as ImageResizeError,Fo as InvariantSession,L as KODAX_API_MIN_INTERVAL,E as KODAX_DEFAULT_TIMEOUT,n as KODAX_FILE_MEDIA_TYPES,F as KODAX_HARD_TIMEOUT,k as KODAX_IMAGE_MEDIA_TYPES,I as KODAX_MAX_INCOMPLETE_RETRIES,J as KODAX_MAX_MAXTOKENS_RETRIES,G as KODAX_MAX_RETRIES,D as KODAX_MAX_TOKENS,H as KODAX_RETRY_BASE_DELAY,K as KODAX_STAGGER_DELAY,l as KODAX_VIDEO_MEDIA_TYPES,o as KodaXMediaError,Xf as LINEAGE_ENTRY_TYPES,Zf as LineageCompaction,Yf as LineageExtension,x as MAX_DIMENSION,we as MAX_ENTRYPOINT_BYTES,ve as MAX_ENTRYPOINT_LINES,df as MAX_SKILL_MD_BYTES,gf as MAX_SKILL_SUPPORT_FILE_BYTES,Ho as MAX_TOOL_LOOP_ITERATIONS,ce as MEMORY_POLICY_VERSION,Hf as McpAuthRequiredError,Tf as McpCapabilityProvider,Gf as McpExpiredSessionError,Uf as McpManager,Sf as McpServerRuntime,ef as MemoryControlPlane,u as MessageQueue,g as PASTE_TMP_DIR_ENV,h as PASTE_TMP_TTL_MS,mm as POST_COMPACT_MAX_TOKENS_PER_FILE,fm as POST_COMPACT_TOKEN_BUDGET,M as PROMISE_PATTERN,Km as PROTECTED_TOOL_NAMES,Lr as QueuedInputArtifactError,or as Runner,Ue as SkillExecutor,Qe as SkillRegistry,oo as SpanImpl,a as TARGET_RAW_SIZE_BYTES,bo as Tracer,Ne as VariableResolver,dp as WORKFLOW_CAPSULE_API_VERSION,bp as WORKFLOW_CAPSULE_FORMAT,cp as WORKFLOW_CAPSULE_VERSION,rp as WORKFLOW_PATTERN_IDS,kp as WorkflowAbortError,np as WorkflowBudgetError,Zm as WorkflowEventRecorder,lp as WorkflowLimitError,pp as WorkflowScriptExecutionError,qp as WorkflowTaskFailedError,y as YIELD_TOOL_NAMES,to as _emitSpanEnd,po as _emitSpanStart,xo as _emitTraceEnd,mo as _getRegisteredProcessors,wo as _resetAdmissionMetrics,Eo as _resetAdmittedAgentBindings,qo as _resetInvariantRegistry,w as _resetMessageQueueForTests,_o as _resetPresetDispatchers,eo as addTracingProcessor,zm as appendGoalEntry,om as appendMemoryClientNotice,_f as appendMemoryOutcomeDigest,$f as appendMemoryReviewReceipt,im as appendSessionLineageLabel,km as applyLineageTruncation,io as applyManifestPatch,sr as applyProcessHardening,jm as applySessionCompaction,jf as applySkillLearningProposal,kf as approveStoredLearningProposal,vm as archiveOldIslands,Hr as asSingleSelection,mp as assertRestrictedWorkflowQuality,Xo as attachRunnerRecoveryTranscript,oe as bootstrapTeamMode,Lo as buildAssistantMessageFromLlmResult,Im as buildCompactionPromptSnapshot,am as buildFileContentMessages,Rf as buildInitializeCapabilities,Yr as buildOtherInstancesPromptBlock,tm as buildPostCompactAttachments,Sm as buildRecoverySeed,sm as buildSessionTree,$o as buildSystemPrompt,Mo as buildToolResultMessage,jp as buildWorkflowCapsuleIntent,S as calculateContextSafetyMargin,U as calculateMaxContextInputTokens,bf as canMarkCreatedByAgent,ee as cleanupIncompleteToolCalls,Dr as cleanupRegisteredManagedChildren,kr as clearCapabilityCache,Ce as clearPluginSkillPaths,Po as collectGuardrails,Om as compact,pf as completeEpisodeReview,Qr as composeIdleYieldUserMessage,jo as composePatches,yf as computeSkillConsumerImpact,um as countActiveLineageMessages,Nr as countLastAssistantToolCalls,O as countTokens,Y as createAgent,Cp as createAgentExecutorPlane,Ve as createExecutor,Um as createExtensionStore,p as createFileArtifactFromPath,Z as createHandoff,m as createImageArtifactFromPath,_ as createInMemorySession,Go as createInvariantSessionForAgent,te as createLlmJudgedStopHook,Bf as createMcpCapabilityId,Vf as createMcpManager,Wf as createMcpTestServerFixture,If as createMcpTransport,zp as createMemoryAgentExecutorPlaneStore,rf as createMemoryControlPlane,Dp as createReferenceAgentExecutorFactory,Oe as createResolver,ap as createRestrictedWorkflowModule,bm as createSessionLineage,Wr as createStateWriter,ro as createTrace,t as createVideoArtifactFromPath,hp as createWorkflowCapsule,ip as createWorkflowModuleFromCapsule,op as createWorkflowProcessTracker,wp as createWorkflowRunManager,up as createWorkflowRuntime,cf as decideSkillGovernance,Af as defaultMcpCacheDir,co as defaultTracer,Uo as detectHandoffSignal,Or as detectIdleYield,Ao as detectInstructionsInjection,Mf as discoverAuthorizationServerMetadata,Xr as discoverInstances,Nf as discoverOAuthEndpoints,Lf as discoverProtectedResourceMetadata,Je as discoverSkills,Le as discoverSkillsWithMonorepo,xf as drainPendingEpisodeReviews,fe as editDistance,Wo as emitHandoffSpan,W as emitKodaXDiagnostic,B as enqueueChildTaskNotification,C as enqueueWithArtifacts,N as estimateTokens,er as evidenceTrail,T as exceedsContextCapacity,Ko as executeRunnerToolCall,We as executeSkill,Xe as expandSkillForLLM,Dm as extractArtifactLedger,rr as extractAssistantTextFromMessage,Bm as extractFileOps,Kf as extractInsufficientScope,Jf as extractResourceMetadataUrl,em as extractTitleFromMessages,fr as finalOwner,me as findFuzzyToolMatch,lm as findPreviousUserEntryId,qm as forkSessionLineage,X as formatKodaXDiagnostic,Ye as formatSkillActivationMessage,rm as generateSessionId,Jm as generateSummary,_r as getActiveTeamModeWriter,Jr as getActiveUserInteraction,vo as getAdmissionMetricsSnapshot,Do as getAdmittedAgentBindings,ar as getAgentConfigHome,br as getAgentConfigPath,cr as getAppDataDir,ir as getCachedRejectedEfforts,gr as getCapabilityCacheFile,De as getDefaultSkillPaths,yp as getDefaultWorkflowRunManager,lo as getInvariant,Ff as getMcpCachePaths,v as getMessageQueue,q as getModelInputCapabilities,Ke as getNestedSkillPaths,cm as getSessionLineagePath,dm as getSessionMessagesFromLineage,Ee as getSkillPathsFlat,Re as getSkillRegistry,Wm as gracefulCompactDegradation,mr as handoffLegality,ge as hashCwd,ae as hashMemoryIdentityComponent,e as inferImageMediaType,f as inferVideoMediaType,Se as initializeSkillRegistry,xm as injectPostCompactAttachments,pe as invokeLlmJudge,yo as isAdmissionDebugEnabled,Gr as isAskUserCustomInputAnswer,le as isAutoManagedMemoryFile,vr as isChildProcessExited,Mm as isEmptyLikeSummary,_m as isFinalWorkflowProcessStatus,Am as isGoalEntry,Mr as isIdleYieldEnabled,Io as isRunnableTool,Jo as isRunnerLlmResult,Ar as killChildProcessTree,Br as killChildProcessTreeSync,yr as killPidTree,zr as killPidTreeSync,fp as lintRestrictedWorkflowSource,mf as listPendingEpisodeReviews,Be as listPluginSkillPaths,no as listRegisteredInvariants,hr as loadCapabilityCache,He as loadFullSkill,Ie as loadSkillFileContent,Ge as loadSkillMetadata,Qf as loadValidToken,xe as matchesMemoryApplicability,A as maybeDrainMidTurn,be as memoryApplicabilityFingerprint,Em as mergeArtifactLedger,Cm as mergeFileOps,Qm as microcompact,z as midTurnDrainPriority,Nm as needsCompaction,$m as normalizeHostMetadata,Cf as normalizeMcpCapabilityId,b as normalizePastedImage,Rm as normalizeRecoveryPrompt,sp as normalizeWorkflowLimits,Me as parseArguments,Df as parseMcpCapabilityId,se as parseMemoryFile,qe as parseMemoryType,ne as parseMemoryTypeFromFilename,ue as parseScalarFields,Fe as parseSkillMarkdown,Pf as performOAuthLogin,i as persistImageAsBlock,ff as persistPendingEpisodeReview,j as prunePasteTmpDir,d as readAndNormalizeClipboardImage,c as readClipboardImage,wm as readLatestGoalFromBranch,ym as readLatestGoalState,Ze as readLearningProposalStore,Yo as readRunnerRecoveryTranscript,vf as readSkillTrustLedger,sf as readSkillUsageLedger,zf as recordCompletedTurnLearning,lf as recordProceduralLearning,jr as recordRejectedEffort,uf as recordSkillUsage,Kr as registerChildTask,tr as registerCoreInvariants,ko as registerInvariant,Cr as registerManagedChildProcess,Of as registerOAuthClient,ze as registerPluginSkillPath,Zo as registerPresetDispatcher,Vo as replaceSystemMessage,Vr as requestTaskStop,lr as resetCapabilityCacheMemoForTesting,Te as resetSkillRegistry,Ym as resolveContextWindow,uo as resolveEffectiveInvariants,$e as resolveLearningProposalStore,je as resolveMemoryEntrypoint,ie as resolveMemoryRoot,so as resolveRequiredInvariants,ke as resolveScopedMemoryRoot,gm as resolveSessionLineageTarget,Pe as resolveSkillContent,hf as resolveSkillSnapshotLocation,qf as resolveSkillTrustLedger,nf as resolveSkillUsageLedger,tf as rewindPendingEpisodeReviews,nm as rewindSessionLineage,Ur as routeMessage,Bo as runAdmissionAudit,Tr as runFanOut,Qo as runInputGuardrails,Ro as runOutputGuardrails,xp as runRestrictedWorkflowScript,To as runToolAfterGuardrails,So as runToolBeforeGuardrails,Sr as runWithIdleYield,vp as runWorkflow,de as sanitizeProjectKey,Ef as searchMcpCatalog,Fm as serializeConversation,Zr as setActiveTeamModeWriter,Ir as setActiveUserInteraction,Co as setAdmittedAgentBindings,xr as setAgentConfigHome,V as setKodaXDiagnosticSink,hm as setSessionLineageActiveEntry,fo as setTracingProcessors,Vm as shouldCompact,ao as shutdownTracing,ur as stripHardenedEnvVars,af as triageProceduralLearning,ye as truncateEntrypointContent,he as tryGitRemote,Ae as unregisterPluginSkillPath,$r as updateActiveTeamMode,of as updateLearningProposalStatus,wf as updateSkillTrustLedger,_e as upsertLearningProposal,re as validateAndFixToolHistory,s as validateInputArtifactsForModel,tp as validateRestrictedWorkflowSource,gp as validateWorkflowCapsule,ep as validateWorkflowScriptManifest,wr as waitForChildProcessExit,Pr as waitForWakeEvent};