openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
16 lines (15 loc) • 27 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as filterStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{s as raceWithTimeout}from"./src-De06gkOi.mjs";import{t as DEFAULT_ACCOUNT_ID}from"./account-id-3yqrEsRn.mjs";import{r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import{Et as _enum,Fn as object,Jn as string,Lt as boolean,Nt as array,Pn as number,Un as record,kt as _null,or as union,sr as unknown,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{t as truncateUtf8Prefix}from"./utf8-truncate-B8GdsL7T.mjs";import{r as registerPluginHttpRoute}from"./http-registry-DZEFGoNA.mjs";import{p as isHostNoticePayload,y as isReplyPayloadTerminalContent}from"./reply-payload-C7eQHHoS.mjs";import{t as boundedJsonUtf8Bytes}from"./json-utf8-bytes-BzjXgHQ3.mjs";import{o as resolveAgentRoute}from"./resolve-route-DpjPYoyg.mjs";import{n as logError}from"./logger-BHIcoxTH.mjs";import{f as sendHttpRequestRejection,i as isRequestBodyLimitError,o as readRequestBodyWithLimit}from"./http-body-CsPV_uT5.mjs";import{g as ssrfPolicyFromHttpBaseUrlAllowedOrigin}from"./ssrf-BzkUH7oD.mjs";import{i as fetchWithSsrFGuard}from"./fetch-guard-B_7-F5Lc.mjs";import{h as readProviderJsonResponse}from"./provider-http-errors-CWZQ78Qm.mjs";import{v as defineChannelMessageAdapter,w as waitUntilAbort}from"./channel-outbound-BZrgY7lw.mjs";import"./reply-payload-C6sYX5Rf.mjs";import{n as sendJsonNoStore}from"./http-json-g_k96dZ_.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./logging-core-CC7KLfEO.mjs";import"./ssrf-runtime-Dx9DKr_m.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import"./webhook-ingress-HlX1K-r7.mjs";import{l as runDetachedWebhookWork}from"./webhook-request-guards-DdSp767W.mjs";import"./time-runtime-SSNrsaM_.mjs";import{r as PlatformMessageNotDispatchedError}from"./deliver-types-QUMIGH6t.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./concurrency-runtime-A2TPGCdf.mjs";import{t as createMessageReceiptFromOutboundResults}from"./receipt-DMUG87P5.mjs";import"./routing-BMFcTEzQ.mjs";import{t as listAgentIdsCompatibility}from"./agent-scope-runtime-DKb8jQZx.mjs";import{n as createChatChannelPlugin,s as buildChannelOutboundSessionRoute}from"./core-CdcdyLUh.mjs";import{b as resolveEnabledConfiguredAccountId,d as createDefaultChannelRuntimeState,p as readAccountStatusSnapshot,u as createComputedAccountStatusAdapter}from"./status-helpers-BjQONSrT.mjs";import{n as createChannelInboundEnvelopeBuilderAsync}from"./envelope-BKdDYYXy.mjs";import"./channel-inbound-DZDqWdoL.mjs";import{i as channelStoppedPatch,n as channelReadyPatch}from"./channel-status-patches-BfGfaRTa.mjs";import"./gateway-runtime-CCd3DVdi.mjs";import"./channel-core-Cs-2GaqZ.mjs";import"./provider-http-D0sVd8r_.mjs";import{r as resolveA2aChannelAccount,t as a2aChannelSetupPlugin}from"./channel-base-EUQiKLsk.mjs";import{t as getA2aChannelRuntime}from"./runtime-CPXk4UC8.mjs";import{createHash,randomUUID,timingSafeEqual}from"node:crypto";
//!extensions/a2a/src/reply-payload.ts
function filterA2aReplyPayload(e){return isHostNoticePayload(e)||!isReplyPayloadTerminalContent(e)?null:e}
//!extensions/a2a/src/inbound.ts
const activeRuns=/* @__PURE__ */ new Map;async function dispatchA2aInbound(e){const reportPersistenceError=e=>{logError(`A2A task persistence failed: ${String(e)}`)};if(e.text.trimStart().startsWith(`/`)){await e.store.reject(e.taskId,`A2A peers cannot execute slash commands. Send a task in plain text; only users can issue commands.`);return}const t=resolveAgentRoute({cfg:e.config,channel:`a2a`,accountId:e.account.accountId,peer:{kind:`direct`,id:`${e.peerName}:${e.contextId}`},parentPeer:{kind:`direct`,id:e.peerName},dmScope:`per-account-channel-peer`});const n=await e.channelRuntime.inbound.ingress.resolveStable({channelId:`a2a`,accountId:e.account.accountId,cfg:e.config,identity:{key:`sender`,entryIdPrefix:`a2a-entry`},subject:{stableId:e.peerName},conversation:{kind:`direct`,id:e.contextId},contextBinding:{agentId:t.agentId,sessionKey:t.sessionKey,messageId:e.messageId,inboundEventKind:`user_request`},dmPolicy:`allowlist`,allowFrom:Object.keys(e.account.config.peers??{})});if(n.ingress.admission!==`dispatch`){await e.store.reject(e.taskId,`A2A peer was blocked by channel ingress policy`);return}const r=Date.now();const i=`a2a:${e.peerName}`;const a=(await createChannelInboundEnvelopeBuilderAsync({cfg:e.config,route:t}))({channel:`A2A`,from:e.peerName,timestamp:r,body:e.text});const o=e.channelRuntime.inbound.buildContext({channel:`a2a`,accountId:t.accountId??e.account.accountId,messageId:e.messageId,messageIdFull:e.messageId,timestamp:r,from:i,sender:{id:e.peerName,name:e.peerName},conversation:{kind:`direct`,id:e.contextId,label:e.peerName},route:{agentId:t.agentId,dmScope:t.dmScope,accountId:t.accountId,routeSessionKey:t.sessionKey,dispatchSessionKey:t.sessionKey},reply:{to:i,originatingTo:i},message:{body:a,bodyForAgent:e.text,rawBody:e.text,commandBody:e.text},channelIngress:n,extra:{CommandInterpretationSuppressed:true}});const settle=async(t,n)=>{if(n.kind!==`completed`){await e.store.fail(e.taskId,`Agent run ${n.kind}`);return}const r=t.filter(e=>filterA2aReplyPayload(e)!==null).map(e=>e.text).filter(Boolean).join(`
`);await e.store.complete(e.taskId,r)};const s={finals:[],steered:[]};const finishRun=async e=>{if(activeRuns.get(t.sessionKey)===s)activeRuns.delete(t.sessionKey);s.completion=e;await Promise.all(s.steered.map(t=>t(e)))};const deliverQueuedReply=async e=>{if(e.completion.kind!==`progress`){s.finals.push(...e.payloads);await settle(e.payloads,e.completion);await finishRun(e.completion)}};deliverQueuedReply.ownsCompletion=e=>e===`a2a`;const c=activeRuns.get(t.sessionKey);const l=c?.finals.length??0;if(!c)activeRuns.set(t.sessionKey,s);let u=false;let d=false;let f=false;let p=false;try{const n=await e.channelRuntime.inbound.dispatch({cfg:e.config,channel:`a2a`,accountId:e.account.accountId,route:{agentId:t.agentId,dmScope:t.dmScope,sessionKey:t.sessionKey},ctxPayload:o,delivery:{deliver:async(t,n)=>{if(n.kind===`final`){s.finals.push(t);await e.store.complete(e.taskId,t.text)}},onError:t=>{f=true;e.store.fail(e.taskId,t).catch(reportPersistenceError)}},replyOptions:{sourceReplyDeliveryMode:`automatic`,onQueuedFollowupReplyBatch:deliverQueuedReply,onPreparedAgentRunStart:()=>{d=true;activeRuns.set(t.sessionKey,s)},onAgentRunTerminalOutcome:t=>{if(t===`completed`)p=true;else{f=true;e.store.fail(e.taskId,`Agent run failed`).catch(reportPersistenceError)}}},replyPipeline:{}});if(n.admission.kind!==`dispatch`)await e.store.reject(e.taskId,`A2A channel declined the turn: ${n.admission.kind}`);else if(!n.dispatched)await e.store.fail(e.taskId,`A2A channel accepted the turn without dispatching it`);else if(n.dispatchResult.deferredToActiveRun===`steer`&&c){const settleSteered=e=>settle(c.finals.slice(l),e);if(c.completion)await settleSteered(c.completion);else c.steered.push(settleSteered)}else if(n.dispatchResult.deferredToActiveRun===`followup`){u=true;if(!d&&activeRuns.get(t.sessionKey)===s)activeRuns.delete(t.sessionKey)}else if(!n.dispatchResult.deferredToActiveRun)await e.store.complete(e.taskId,void 0)}catch(e){f=true;throw e}finally{if(!u)await finishRun(f?{kind:`failed`,error:`Agent run failed`}:p?{kind:`completed`}:{kind:`aborted`})}}
//!extensions/a2a/src/outbound.ts
const A2A_OUTBOUND_TIMEOUT_MS=3e4;const A2aOutboundResponseSchema=object({error:object({code:number(),message:string()}).optional(),result:object({task:object({id:string().optional()}).optional()}).optional()});async function sendA2aChannelText(e){const t=resolveA2aChannelAccount({cfg:e.cfg,accountId:e.accountId});const n=e.to.replace(/^a2a:/i,``).trim();const r=t.config.peers?.[n];if(!r?.url)throw new PlatformMessageNotDispatchedError(`peer ${n} has no url configured for outbound A2A`,{cause:void 0,retryable:false});if(t.unresolvedOutboundPeers.includes(n))throw new PlatformMessageNotDispatchedError(`peer ${n} outboundToken reference did not resolve; set the variable and reload before sending`,{cause:void 0,retryable:false});const i=randomUUID();const a=randomUUID();const o={"content-type":`application/json`};if(r.outboundToken)o.authorization=`Bearer ${r.outboundToken}`;const s={jsonrpc:`2.0`,id:a,method:`SendMessage`,params:{message:{messageId:i,role:`ROLE_USER`,contextId:`ctx-oc-${n}`,parts:[{text:e.text}]},configuration:{returnImmediately:true}}};const c=AbortSignal.timeout(A2A_OUTBOUND_TIMEOUT_MS);for(let t=0;t<2;t+=1){const{response:a,release:l}=await fetchWithSsrFGuard({url:r.url,timeoutMs:A2A_OUTBOUND_TIMEOUT_MS,signal:c,policy:ssrfPolicyFromHttpBaseUrlAllowedOrigin(r.url),auditContext:`a2a.outbound_send`,maxRedirects:0,beforeRequest:e.assertDirectAdapterHandoff,init:{method:`POST`,headers:o,body:JSON.stringify(s)}});try{if(!a.ok)throw new Error(`outbound A2A request to peer ${n} failed (HTTP ${a.status})`);const r=A2aOutboundResponseSchema.safeParse(await readProviderJsonResponse(a,`peer ${n} A2A response`,{requestHeaders:o}));if(!r.success)throw new Error(`peer ${n} returned an invalid A2A JSON-RPC response`);if(r.data.error){if(t===0&&r.data.error.code===-32601){s.method=`message/send`;continue}throw new Error(`outbound A2A request to peer ${n} failed: ${r.data.error.message}`)}if(!r.data.result)throw new Error(`peer ${n} returned an A2A response without a result`);return{to:e.to,messageId:r.data.result.task?.id??i}}finally{await l()}}throw new Error(`outbound A2A request to peer ${n} exhausted its compatibility retry`)}
//!extensions/a2a/src/protocol.ts
const A2A_CONTEXT_PATTERN=/^[A-Za-z0-9._:-]{1,128}$/;const A2A_MESSAGE_MAX_BYTES=65536;const A2A_TRUNCATION_MARKER=`\n[message truncated at ${A2A_MESSAGE_MAX_BYTES} bytes]`;const A2aRpcRequestSchema=object({jsonrpc:literal(`2.0`),id:union([string(),number().finite(),_null()]).optional(),method:string().min(1),params:unknown().optional()});const A2aMetadataSchema=record(string(),unknown());const A2aInboundPartSchema=object({text:string().optional(),data:unknown().optional()});const A2aSendMessageParamsSchema=object({message:object({messageId:string().min(1).optional(),contextId:string().regex(A2A_CONTEXT_PATTERN).optional(),taskId:string().min(1).optional(),role:_enum([`ROLE_USER`,`ROLE_AGENT`,`user`,`agent`]),parts:array(unknown()),metadata:A2aMetadataSchema.optional()}),configuration:object({acceptedOutputModes:array(string()).optional(),historyLength:number().int().nonnegative().optional(),returnImmediately:boolean().optional()}).optional(),tenant:string().optional(),metadata:A2aMetadataSchema.optional()});const A2aTaskRequestParamsSchema=object({id:string().min(1),historyLength:number().int().nonnegative().optional(),tenant:string().optional()});const A2A_METHOD_ALIASES={SendMessage:`SendMessage`,GetTask:`GetTask`,"message/send":`SendMessage`,"tasks/get":`GetTask`};const A2A_UNSUPPORTED_METHODS=/* @__PURE__ */ new Set([`CancelTask`,`tasks/cancel`,`ListTasks`,`SendStreamingMessage`,`SubscribeToTask`,`GetExtendedAgentCard`]);const A2A_UNSUPPORTED_PUSH_METHODS=/* @__PURE__ */ new Set([`CreateTaskPushNotificationConfig`,`SetTaskPushNotificationConfig`,`GetTaskPushNotificationConfig`,`ListTaskPushNotificationConfig`,`ListTaskPushNotificationConfigs`,`DeleteTaskPushNotificationConfig`]);function resolveA2aRpcMethod(e){if(Object.hasOwn(A2A_METHOD_ALIASES,e))return A2A_METHOD_ALIASES[e];if(A2A_UNSUPPORTED_PUSH_METHODS.has(e))throw new A2aProtocolError(-32003,`Push notifications are not supported`);return A2A_UNSUPPORTED_METHODS.has(e)?`unsupported`:void 0}function extractA2aMessageText(e){const t=[];for(const n of e){const e=A2aInboundPartSchema.safeParse(n);if(!e.success)continue;if(e.data.text!==void 0)t.push(e.data.text);else if(Object.hasOwn(e.data,`data`)&&e.data.data!==void 0)t.push(JSON.stringify(e.data.data))}const n=t.join(`
`);if(!n.trim())return;if(Buffer.byteLength(n)<=A2A_MESSAGE_MAX_BYTES)return n;const r=A2A_MESSAGE_MAX_BYTES-Buffer.byteLength(A2A_TRUNCATION_MARKER);return truncateUtf8Prefix(n,r).replace(/^\uFEFF/,``)+A2A_TRUNCATION_MARKER}var A2aProtocolError=class extends Error{constructor(e,t){super(t);this.code=e;this.name=`A2aProtocolError`}};
//!extensions/a2a/src/task-store.ts
const A2A_TERMINAL_MAX_TASKS=500;const A2A_TERMINAL_RETENTION_MS=864e5;const A2A_ERROR_MAX_LENGTH=512;function openTerminalStore(e,t){return e.state.openKeyedStoreV2({namespace:`a2a-terminal-${t}`,maxEntries:A2A_TERMINAL_MAX_TASKS,defaultTtlMs:A2A_TERMINAL_RETENTION_MS})}function isTerminalTask(e){return[`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_REJECTED`].includes(e.status.state)}function createStatusMessage(e,t){return{messageId:randomUUID(),contextId:e,role:`ROLE_AGENT`,parts:[{text:truncateUtf16Safe(t,A2A_ERROR_MAX_LENGTH)}]}}var A2aTaskStore=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Map;#n=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ new Map;#i=/* @__PURE__ */ new Map;#a=/* @__PURE__ */ new Map;#o=/* @__PURE__ */ new Map;#s=0;constructor(e){this.terminalStore=e}async restore(){const e=await this.terminalStore.entries();for(const{key:t,value:n}of e){const{task:e,ownerPeer:r,messageKey:i,finishedAt:a}=n;const o=Number(t.split(`:`)[0]);if(!Number.isSafeInteger(o)||o<0)throw new Error(`Invalid persisted A2A terminal task key`);this.#s=Math.max(this.#s,o);if(!t.endsWith(`:${e.id}`)||!isTerminalTask(e)||!Number.isFinite(a))throw new Error(`Invalid persisted A2A terminal task`);this.#e.set(e.id,e);this.#t.set(e.id,r);this.#n.set(i,e);this.#r.set(e.id,i);this.#i.set(e.id,a)}this.#u()}create(e,t,n){this.#u();const r=JSON.stringify([t,n]);const i=this.#n.get(r);if(i)return i;const a={id:randomUUID(),contextId:e,status:{state:`TASK_STATE_SUBMITTED`,timestamp:(/* @__PURE__ */ new Date()).toISOString()},artifacts:[],history:[]};this.#e.set(a.id,a);this.#t.set(a.id,t);this.#n.set(r,a);this.#r.set(a.id,r);return a}get(e,t){this.#u();if(this.#t.get(e)!==t)return;return this.#e.get(e)}start(e){const t=this.#e.get(e);if(t?.status.state!==`TASK_STATE_SUBMITTED`)return;t.status={state:`TASK_STATE_WORKING`,timestamp:(/* @__PURE__ */ new Date()).toISOString()};return t}async complete(e,t){const n=this.#e.get(e);if(!n||isTerminalTask(n))return n;const r={...n};if(t?.trim())r.artifacts=[{artifactId:randomUUID(),parts:[{text:t}]}];r.status={state:`TASK_STATE_COMPLETED`,timestamp:(/* @__PURE__ */ new Date()).toISOString(),...!t?.trim()?{message:createStatusMessage(n.contextId,`Agent completed without reply text`)}:{}};return this.#l(n,r)}async fail(e,t){const n=t instanceof Error?t.message:String(t);return this.#c(e,`TASK_STATE_FAILED`,n)}async reject(e,t){return this.#c(e,`TASK_STATE_REJECTED`,t)}wait(e,t){if(isTerminalTask(e))return Promise.resolve(e);const n=e.id;const r=createDeferredCore();const i=this.#a.get(n)??/* @__PURE__ */ new Set;i.add(r.resolve);this.#a.set(n,i);return raceWithTimeout(r.promise,t,()=>e).finally(()=>{i.delete(r.resolve);if(i.size===0)this.#a.delete(n)})}async stop(){const e=(await Promise.allSettled([...this.#e.values()].map(e=>this.fail(e.id,`A2A channel stopped before completing the task`)))).find(e=>e.status===`rejected`);if(e?.status===`rejected`)throw e.reason;this.#o.clear();this.#n.clear();this.#r.clear();this.#i.clear();this.#t.clear();this.#e.clear()}async#c(e,t,n){const r=this.#e.get(e);if(!r||isTerminalTask(r))return r;const i={...r};i.status={state:t,timestamp:(/* @__PURE__ */ new Date()).toISOString(),message:createStatusMessage(r.contextId,n)};return this.#l(r,i)}#l(e,t){const n=this.#o.get(e.id);if(n)return n;const r=Date.now();this.#s=Math.max(r,this.#s+1);const i=`${String(this.#s).padStart(16,`0`)}:${e.id}`;const a=(async()=>{try{await this.terminalStore.register(i,{task:t,ownerPeer:this.#t.get(e.id),messageKey:this.#r.get(e.id),finishedAt:r},{ttlMs:Math.max(1,r+A2A_TERMINAL_RETENTION_MS-Date.now())})}catch(n){if(!(n instanceof Error)||!(`code`in n)||n.code!==`PLUGIN_STATE_LIMIT_EXCEEDED`&&n.code!==`PLUGIN_STATE_INVALID_INPUT`)throw n;t.status={state:`TASK_STATE_FAILED`,timestamp:(/* @__PURE__ */ new Date()).toISOString(),message:createStatusMessage(e.contextId,`A2A terminal result could not be stored; it will not survive a Gateway restart (${n.code})`)}}Object.assign(e,t);this.#i.set(e.id,r);const n=this.#a.get(e.id);this.#a.delete(e.id);for(const t of n??[])t(e);this.#u();return e})();this.#o.set(e.id,a);return a}#u(){const e=Date.now()-A2A_TERMINAL_RETENTION_MS;for(const[t,n]of this.#i){if(n>e&&this.#i.size<=A2A_TERMINAL_MAX_TASKS)break;const r=this.#r.get(t);if(r!==void 0){this.#n.delete(r);this.#r.delete(t)}this.#o.delete(t);this.#i.delete(t);this.#t.delete(t);this.#e.delete(t)}}};
//!extensions/a2a/src/channel.ts
const MAX_REQUEST_BODY_BYTES=1048576;const MAX_RESPONSE_BODY_BYTES=1048576;const MAX_BATCH_REQUESTS=30;const DEFAULT_REPLY_TIMEOUT_MS=12e4;const DEFAULT_RATE_LIMIT_PER_MINUTE=30;const RATE_LIMIT_WINDOW_MS=6e4;function createRpcError(e,t,n){return{jsonrpc:`2.0`,id:e,error:{code:t,message:n}}}function writeRpcResponse(e,t){if(boundedJsonUtf8Bytes(t,MAX_RESPONSE_BODY_BYTES).complete){sendJsonNoStore(e,200,t);return}const n=`A2A response exceeds the 1 MiB limit`;const r=Array.isArray(t)?t.map(e=>createRpcError(e.id,-32e3,n)):createRpcError(t.id,-32e3,n);const i=boundedJsonUtf8Bytes(r,MAX_RESPONSE_BODY_BYTES).complete?r:Array.isArray(r)?r.map(()=>createRpcError(null,-32e3,n)):createRpcError(null,-32e3,n);sendJsonNoStore(e,200,i)}function resolvePeerName(e,t){const n=e.headers.authorization?.match(/^Bearer\s+([^\s]+)$/i)?.[1];if(!n)return;const r=createHash(`sha256`).update(n).digest();for(const[e,n]of Object.entries(t.peers??{})){const t=createHash(`sha256`).update(n.token).digest();if(timingSafeEqual(r,t))return e}}function resolveRequestOrigin(e){const t=`encrypted`in e.socket&&e.socket.encrypted;try{return new URL(`${t?`https`:`http`}://${e.headers.host??`localhost`}`).origin}catch{return`${t?`https`:`http`}://localhost`}}const a2aGatewayRoutePaths=[`/.well-known/agent-card.json`,`/.well-known/agent.json`,`/a2a/v1`];const A2A_ACCOUNT_STATUS_FIELDS=[`unresolvedPeers`,`unresolvedOutboundPeers`];function normalizeA2aChannelTarget(e){const t=e.trim().replace(/^a2a:/i,``);return/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t)?t:void 0}const a2aChannelMessageAdapter=defineChannelMessageAdapter({id:`a2a`,durableFinal:{capabilities:{text:true}},send:{text:async e=>{const t=await sendA2aChannelText({cfg:e.cfg,accountId:e.accountId,to:e.to,text:e.text,assertDirectAdapterHandoff:e.assertDirectAdapterHandoff});return{messageId:t.messageId,receipt:createMessageReceiptFromOutboundResults({results:[{channel:`a2a`,messageId:t.messageId}],kind:`text`})}}}});const a2aChannelPlugin=createChatChannelPlugin({base:{...a2aChannelSetupPlugin,messaging:{transformReplyPayload:({payload:e})=>filterA2aReplyPayload(e),normalizeTarget:normalizeA2aChannelTarget,inferTargetChatType:()=>`direct`,targetResolver:{looksLikeId:e=>normalizeA2aChannelTarget(e)!==void 0,hint:`<a2a-peer-name>`},resolveOutboundSessionRoute:({cfg:e,agentId:t,accountId:n,target:r})=>{const i=normalizeA2aChannelTarget(r);if(!i)return null;return buildChannelOutboundSessionRoute({cfg:e,agentId:t,channel:`a2a`,accountId:n,recipientSessionExact:true,peer:{kind:`direct`,id:i},chatType:`direct`,from:`${`a2a`}:${n??`default`}`,to:i})}},status:createComputedAccountStatusAdapter({defaultRuntime:createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),collectStatusIssues:e=>{const t=[];for(const n of e){const e=readAccountStatusSnapshot(n,A2A_ACCOUNT_STATUS_FIELDS);if(!e)continue;const r=resolveEnabledConfiguredAccountId(e)??e.accountId;if(e.enabled===false||typeof r!==`string`||!r)continue;const addIssue=(e,n)=>t.push({channel:`a2a`,accountId:r,kind:`config`,message:e,fix:n});const i=filterStringEntries(e.unresolvedPeers).filter(Boolean);if(i.length>0)addIssue(`A2A peer${i.length===1?``:`s`} ${i.join(`, `)} cannot authenticate: the inbound token reference did not resolve, so requests from ${i.length===1?`it are`:`them are`} rejected with 401.`,`Set the environment variable referenced by channels.a2a.peers.<name>.token for ${i.join(`, `)}, then reload or restart the gateway.`);const a=filterStringEntries(e.unresolvedOutboundPeers).filter(Boolean);if(a.length>0)addIssue(`Sends to A2A peer${a.length===1?``:`s`} ${a.join(`, `)} are refused: the outbound token reference did not resolve.`,`Set the environment variable referenced by channels.a2a.peers.<name>.outboundToken for ${a.join(`, `)}, then reload or restart the gateway.`)}return t},buildChannelSummary:({snapshot:e})=>({configured:e.configured??false,running:e.running??false}),resolveAccountSnapshot:({account:e})=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured,extra:{peerCount:Object.keys(e.config.peers??{}).length,...e.unresolvedPeers.length>0?{unresolvedPeers:e.unresolvedPeers}:{},...e.unresolvedOutboundPeers.length>0?{unresolvedOutboundPeers:e.unresolvedOutboundPeers}:{}}})}),gateway:{startAccount:async e=>{const{account:t}=e;const n=e.cfg;if(!t.configured)throw new Error(`A2A channel is not configured for account "${t.accountId}"`);e.setStatus({accountId:t.accountId,running:true,lifecycle:`starting`,configured:true,enabled:t.enabled});const r=getA2aChannelRuntime();const i=t.config;const a=r.version;const o=e.channelRuntime??r.channel;const s=new A2aTaskStore(openTerminalStore(r,t.accountId));await s.restore();const c=[];function createAgentCard(e){const t=i.exposeAgents;const r=listAgentIdsCompatibility(n).filter(e=>!t?.length||t.includes(e));return{name:(r[0]?resolveAgentConfig(n,r[0])?.name?.trim():void 0)||`OpenClaw`,description:`OpenClaw agent gateway using the Agent2Agent protocol.`,supportedInterfaces:[{url:`${(i.advertisedUrl??resolveRequestOrigin(e)).replace(/\/+$/,``)}/a2a/v1`,protocolBinding:`JSONRPC`,protocolVersion:`1.0`}],version:a,capabilities:{streaming:false,pushNotifications:false},defaultInputModes:[`text/plain`],defaultOutputModes:[`text/plain`],skills:r.map(e=>({id:e,name:e,description:`OpenClaw agent ${e}.`,tags:[`openclaw`]}))}}try{const r=/* @__PURE__ */ new Map;function isRateLimited(e){const t=i.rateLimitPerMinute??DEFAULT_RATE_LIMIT_PER_MINUTE;if(t===0)return false;const n=Date.now();const a=(r.get(e)??[]).filter(e=>n-e<RATE_LIMIT_WINDOW_MS);if(a.length>=t){r.set(e,a);return true}a.push(n);r.set(e,a);return false}async function processRpcRequest(r,a){const c=A2aRpcRequestSchema.safeParse(r);const l=isRecord(r)?r.id:void 0;const u=typeof l===`string`||typeof l===`number`?l:null;const d=c.success&&!Object.hasOwn(c.data,`id`);if(isRateLimited(a))return d?void 0:createRpcError(u,-32e3,`Peer is rate limited`);if(!c.success)return createRpcError(u,-32600,`Invalid JSON-RPC request`);const f=c.data;let p;try{const r=resolveA2aRpcMethod(f.method);if(r===void 0)throw new A2aProtocolError(-32601,`Method not found: ${f.method}`);if(r===`unsupported`)throw new A2aProtocolError(-32004,`Unsupported operation; supported methods are SendMessage and GetTask`);if(r===`SendMessage`){const r=A2aSendMessageParamsSchema.safeParse(f.params);if(!r.success)throw new A2aProtocolError(-32602,`Invalid SendMessage params: message and parts required`);const c=r.data.message;const l=extractA2aMessageText(c.parts);if(!l)throw new A2aProtocolError(-32602,`Message must contain at least one usable text part`);if(c.taskId!==void 0){const e=s.get(c.taskId,a);if(!e)throw new A2aProtocolError(-32001,`Task not found`);if(c.contextId!==void 0&&c.contextId!==e.contextId)throw new A2aProtocolError(-32602,`Message contextId does not match the referenced task`);throw new A2aProtocolError(-32004,`Task continuation is not supported; omit taskId and reuse contextId to start a new task`)}const u=c.messageId??randomUUID();const d=s.create(c.contextId??`ctx-${randomUUID()}`,a,u);if(s.start(d.id))runDetachedWebhookWork(async()=>{await dispatchA2aInbound({account:t,config:n,channelRuntime:o,store:s,taskId:d.id,contextId:d.contextId,messageId:u,peerName:a,text:l})}).catch(e=>s.fail(d.id,e)).catch(t=>{e.log?.error(`A2A task persistence failed: ${String(t)}`)});if(!r.data.configuration?.returnImmediately){const e=i.replyTimeoutMs??DEFAULT_REPLY_TIMEOUT_MS;await s.wait(d,e)}p={task:d}}else{const e=A2aTaskRequestParamsSchema.safeParse(f.params);if(!e.success)throw new A2aProtocolError(-32602,`Invalid task params: id is required`);const t=s.get(e.data.id,a);if(!t)throw new A2aProtocolError(-32001,`Task not found`);p=t}}catch(e){if(d)return;if(e instanceof A2aProtocolError)return createRpcError(u,e.code,e.message);return createRpcError(u,-32e3,`A2A request could not be processed`)}return d?void 0:{jsonrpc:`2.0`,id:u,result:p}}const handler=async(e,t)=>{const n=new URL(e.url??`/`,`http://localhost`).pathname;if(e.method===`GET`&&(n===`/.well-known/agent-card.json`||n===`/.well-known/agent.json`)){sendJsonNoStore(t,200,createAgentCard(e));return true}if(e.method!==`POST`||n!==`/a2a/v1`){sendJsonNoStore(t,404,{error:`Not found`});return true}const r=resolvePeerName(e,i);if(!r){sendJsonNoStore(t,401,{error:`Unauthorized; configure channels.a2a.peers with a matching Bearer token`});return true}let a;try{a=await readRequestBodyWithLimit(e,{maxBytes:MAX_REQUEST_BODY_BYTES,destroyOnLimit:false})}catch(n){const r=isRequestBodyLimitError(n,`PAYLOAD_TOO_LARGE`)?{statusCode:413,body:{error:`Request body exceeds the 1 MiB limit`}}:isRequestBodyLimitError(n,`REQUEST_BODY_TIMEOUT`)?{statusCode:200,body:createRpcError(null,-32e3,`Request body could not be read`)}:void 0;if(r){t.setHeader(`cache-control`,`no-store`);await sendHttpRequestRejection(e,t,r.statusCode,JSON.stringify(r.body),`application/json; charset=utf-8`);return true}sendJsonNoStore(t,200,createRpcError(null,-32e3,`Request body could not be read`));return true}let o;try{o=JSON.parse(a)}catch{sendJsonNoStore(t,200,createRpcError(null,-32700,`Parse error`));return true}let s;if(Array.isArray(o)){if(o.length===0){sendJsonNoStore(t,200,createRpcError(null,-32600,`Invalid JSON-RPC request`));return true}if(o.length>MAX_BATCH_REQUESTS){writeRpcResponse(t,isRateLimited(r)?createRpcError(null,-32e3,`Peer is rate limited`):createRpcError(null,-32e3,`A2A batch exceeds the ${MAX_BATCH_REQUESTS} request limit`));return true}const e=(await Promise.all(o.map(e=>processRpcRequest(e,r)))).filter(e=>e!==void 0);s=e.length>0?e:void 0}else s=await processRpcRequest(o,r);if(s)writeRpcResponse(t,s);else{t.statusCode=200;t.end()}return true};for(const e of a2aGatewayRoutePaths)c.push(registerPluginHttpRoute({path:e,auth:`plugin`,match:`exact`,pluginId:`a2a`,source:`a2a-gateway`,accountId:t.accountId,throwOnFailure:true,handler}));e.setStatus(channelReadyPatch({accountId:t.accountId}));await waitUntilAbort(e.abortSignal)}finally{for(const e of c.toReversed())e();await s.stop();e.setStatus(channelStoppedPatch({accountId:t.accountId}))}}},message:a2aChannelMessageAdapter},outbound:{base:{deliveryMode:`direct`},attachedResults:{channel:`a2a`,sendText:sendA2aChannelText}}});export{a2aChannelPlugin as t};