var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/server/express/index.ts var express_exports = {}; __export(express_exports, { A2AExpressApp: () => A2AExpressApp, UserBuilder: () => UserBuilder, agentCardHandler: () => agentCardHandler, jsonRpcHandler: () => jsonRpcHandler, restHandler: () => restHandler }); module.exports = __toCommonJS(express_exports); // src/server/express/a2a_express_app.ts var import_express3 = __toESM(require("express"), 1); // src/constants.ts var AGENT_CARD_PATH = ".well-known/agent-card.json"; var HTTP_EXTENSION_HEADER = "X-A2A-Extensions"; // src/server/express/json_rpc_handler.ts var import_express = __toESM(require("express"), 1); // src/server/error.ts var A2AError = class _A2AError extends Error { code; data; taskId; // Optional task ID context constructor(code, message, data, taskId) { super(message); this.name = "A2AError"; this.code = code; this.data = data; this.taskId = taskId; } /** * Formats the error into a standard JSON-RPC error object structure. */ toJSONRPCError() { const errorObject = { code: this.code, message: this.message }; if (this.data !== void 0) { errorObject.data = this.data; } return errorObject; } // Static factory methods for common errors static parseError(message, data) { return new _A2AError(-32700, message, data); } static invalidRequest(message, data) { return new _A2AError(-32600, message, data); } static methodNotFound(method) { return new _A2AError(-32601, `Method not found: ${method}`); } static invalidParams(message, data) { return new _A2AError(-32602, message, data); } static internalError(message, data) { return new _A2AError(-32603, message, data); } static taskNotFound(taskId) { return new _A2AError(-32001, `Task not found: ${taskId}`, void 0, taskId); } static taskNotCancelable(taskId) { return new _A2AError(-32002, `Task not cancelable: ${taskId}`, void 0, taskId); } static pushNotificationNotSupported() { return new _A2AError(-32003, "Push Notification is not supported"); } static unsupportedOperation(operation) { return new _A2AError(-32004, `Unsupported operation: ${operation}`); } static authenticatedExtendedCardNotConfigured() { return new _A2AError(-32007, `Extended card not configured.`); } }; // src/server/transports/jsonrpc/jsonrpc_transport_handler.ts var JsonRpcTransportHandler = class { requestHandler; constructor(requestHandler) { this.requestHandler = requestHandler; } /** * Handles an incoming JSON-RPC request. * For streaming methods, it returns an AsyncGenerator of JSONRPCResult. * For non-streaming methods, it returns a Promise of a single JSONRPCMessage (Result or ErrorResponse). */ async handle(requestBody, context) { let rpcRequest; try { if (typeof requestBody === "string") { rpcRequest = JSON.parse(requestBody); } else if (typeof requestBody === "object" && requestBody !== null) { rpcRequest = requestBody; } else { throw A2AError.parseError("Invalid request body type."); } if (!this.isRequestValid(rpcRequest)) { throw A2AError.invalidRequest("Invalid JSON-RPC Request."); } } catch (error) { const a2aError = error instanceof A2AError ? error : A2AError.parseError( error instanceof SyntaxError && error.message || "Failed to parse JSON request." ); return { jsonrpc: "2.0", id: rpcRequest?.id !== void 0 ? rpcRequest.id : null, error: a2aError.toJSONRPCError() }; } const { method, id: requestId = null } = rpcRequest; try { if (method !== "agent/getAuthenticatedExtendedCard" && !this.paramsAreValid(rpcRequest.params)) { throw A2AError.invalidParams(`Invalid method parameters.`); } if (method === "message/stream" || method === "tasks/resubscribe") { const params = rpcRequest.params; const agentCard = await this.requestHandler.getAgentCard(); if (!agentCard.capabilities.streaming) { throw A2AError.unsupportedOperation(`Method ${method} requires streaming capability.`); } const agentEventStream = method === "message/stream" ? this.requestHandler.sendMessageStream(params, context) : this.requestHandler.resubscribe(params, context); return (async function* jsonRpcEventStream() { try { for await (const event of agentEventStream) { yield { jsonrpc: "2.0", id: requestId, // Use the original request ID for all streamed responses result: event }; } } catch (streamError) { console.error( `Error in agent event stream for ${method} (request ${requestId}):`, streamError ); throw streamError; } })(); } else { let result; switch (method) { case "message/send": result = await this.requestHandler.sendMessage(rpcRequest.params, context); break; case "tasks/get": result = await this.requestHandler.getTask(rpcRequest.params, context); break; case "tasks/cancel": result = await this.requestHandler.cancelTask(rpcRequest.params, context); break; case "tasks/pushNotificationConfig/set": result = await this.requestHandler.setTaskPushNotificationConfig( rpcRequest.params, context ); break; case "tasks/pushNotificationConfig/get": result = await this.requestHandler.getTaskPushNotificationConfig( rpcRequest.params, context ); break; case "tasks/pushNotificationConfig/delete": await this.requestHandler.deleteTaskPushNotificationConfig(rpcRequest.params, context); result = null; break; case "tasks/pushNotificationConfig/list": result = await this.requestHandler.listTaskPushNotificationConfigs( rpcRequest.params, context ); break; case "agent/getAuthenticatedExtendedCard": result = await this.requestHandler.getAuthenticatedExtendedAgentCard(context); break; default: throw A2AError.methodNotFound(method); } return { jsonrpc: "2.0", id: requestId, result }; } } catch (error) { let a2aError; if (error instanceof A2AError) { a2aError = error; } else { a2aError = A2AError.internalError( error instanceof Error && error.message || "An unexpected error occurred." ); } return { jsonrpc: "2.0", id: requestId, error: a2aError.toJSONRPCError() }; } } // Validates the basic structure of a JSON-RPC request isRequestValid(rpcRequest) { if (rpcRequest.jsonrpc !== "2.0") { return false; } if ("id" in rpcRequest) { const id = rpcRequest.id; const isString = typeof id === "string"; const isInteger = typeof id === "number" && Number.isInteger(id); const isNull = id === null; if (!isString && !isInteger && !isNull) { return false; } } if (!rpcRequest.method || typeof rpcRequest.method !== "string") { return false; } return true; } // Validates that params is an object with non-empty string keys paramsAreValid(params) { if (typeof params !== "object" || params === null || Array.isArray(params)) { return false; } for (const key of Object.keys(params)) { if (key === "") { return false; } } return true; } }; // src/extensions.ts var Extensions = { /** * Creates new {@link Extensions} from `current` and `additional`. * If `current` already contains `additional` it is returned unmodified. */ createFrom: (current, additional) => { if (current?.includes(additional)) { return current; } return [...current ?? [], additional]; }, /** * Creates {@link Extensions} from comma separated extensions identifiers as per * https://a2a-protocol.org/latest/specification/#326-service-parameters. * Parses the output of `toServiceParameter`. */ parseServiceParameter: (value) => { if (!value) { return []; } const unique = new Set( value.split(",").map((ext) => ext.trim()).filter((ext) => ext.length > 0) ); return Array.from(unique); }, /** * Converts {@link Extensions} to comma separated extensions identifiers as per * https://a2a-protocol.org/latest/specification/#326-service-parameters. */ toServiceParameter: (value) => { return value.join(","); } }; // src/server/context.ts var ServerCallContext = class { _requestedExtensions; _user; _activatedExtensions; constructor(requestedExtensions, user) { this._requestedExtensions = requestedExtensions; this._user = user; } get user() { return this._user; } get activatedExtensions() { return this._activatedExtensions; } get requestedExtensions() { return this._requestedExtensions; } addActivatedExtension(uri) { this._activatedExtensions = Extensions.createFrom(this._activatedExtensions, uri); } }; // src/sse_utils.ts var SSE_HEADERS = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", "X-Accel-Buffering": "no" // Disable buffering in nginx }; function formatSSEEvent(event) { return `data: ${JSON.stringify(event)} `; } function formatSSEErrorEvent(error) { return `event: error data: ${JSON.stringify(error)} `; } // src/server/express/json_rpc_handler.ts function jsonRpcHandler(options) { const jsonRpcTransportHandler = new JsonRpcTransportHandler(options.requestHandler); const router = import_express.default.Router(); router.use(import_express.default.json(), jsonErrorHandler); router.post("/", async (req, res) => { try { const user = await options.userBuilder(req); const context = new ServerCallContext( Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)), user ); const rpcResponseOrStream = await jsonRpcTransportHandler.handle(req.body, context); if (context.activatedExtensions) { res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions)); } if (typeof rpcResponseOrStream?.[Symbol.asyncIterator] === "function") { const stream = rpcResponseOrStream; Object.entries(SSE_HEADERS).forEach(([key, value]) => { res.setHeader(key, value); }); res.flushHeaders(); try { for await (const event of stream) { res.write(formatSSEEvent(event)); } } catch (streamError) { console.error(`Error during SSE streaming (request ${req.body?.id}):`, streamError); let a2aError; if (streamError instanceof A2AError) { a2aError = streamError; } else { a2aError = A2AError.internalError( streamError instanceof Error && streamError.message || "Streaming error." ); } const errorResponse = { jsonrpc: "2.0", id: req.body?.id || null, // Use original request ID if available error: a2aError.toJSONRPCError() }; if (!res.headersSent) { res.status(500).json(errorResponse); } else { res.write(formatSSEErrorEvent(errorResponse)); } } finally { if (!res.writableEnded) { res.end(); } } } else { const rpcResponse = rpcResponseOrStream; res.status(200).json(rpcResponse); } } catch (error) { console.error("Unhandled error in JSON-RPC POST handler:", error); const a2aError = error instanceof A2AError ? error : A2AError.internalError("General processing error."); const errorResponse = { jsonrpc: "2.0", id: req.body?.id || null, error: a2aError.toJSONRPCError() }; if (!res.headersSent) { res.status(500).json(errorResponse); } else if (!res.writableEnded) { res.end(); } } }); return router; } var jsonErrorHandler = (err, _req, res, next) => { if (err instanceof SyntaxError && "body" in err) { const a2aError = A2AError.parseError("Invalid JSON payload."); const errorResponse = { jsonrpc: "2.0", id: null, error: a2aError.toJSONRPCError() }; return res.status(400).json(errorResponse); } next(err); }; // src/server/express/agent_card_handler.ts var import_express2 = __toESM(require("express"), 1); function agentCardHandler(options) { const router = import_express2.default.Router(); const provider = typeof options.agentCardProvider === "function" ? options.agentCardProvider : options.agentCardProvider.getAgentCard.bind(options.agentCardProvider); router.get("/", async (_req, res) => { try { const agentCard = await provider(); res.json(agentCard); } catch (error) { console.error("Error fetching agent card:", error); res.status(500).json({ error: "Failed to retrieve agent card" }); } }); return router; } // src/server/authentication/user.ts var UnauthenticatedUser = class { get isAuthenticated() { return false; } get userName() { return ""; } }; // src/server/express/common.ts var UserBuilder = { noAuthentication: () => Promise.resolve(new UnauthenticatedUser()) }; // src/server/express/a2a_express_app.ts var A2AExpressApp = class { requestHandler; userBuilder; constructor(requestHandler, userBuilder = UserBuilder.noAuthentication) { this.requestHandler = requestHandler; this.userBuilder = userBuilder; } /** * Adds A2A routes to an existing Express app. * @param app Optional existing Express app. * @param baseUrl The base URL for A2A endpoints (e.g., "/a2a/api"). * @param middlewares Optional array of Express middlewares to apply to the A2A routes. * @param agentCardPath Optional custom path for the agent card endpoint (defaults to .well-known/agent-card.json). * @returns The Express app with A2A routes. */ setupRoutes(app, baseUrl = "", middlewares, agentCardPath = AGENT_CARD_PATH) { const router = import_express3.default.Router(); router.use(import_express3.default.json(), jsonErrorHandler); if (middlewares && middlewares.length > 0) { router.use(middlewares); } router.use( jsonRpcHandler({ requestHandler: this.requestHandler, userBuilder: this.userBuilder }) ); router.use(`/${agentCardPath}`, agentCardHandler({ agentCardProvider: this.requestHandler })); app.use(baseUrl, router); return app; } }; // src/server/express/rest_handler.ts var import_express4 = __toESM(require("express"), 1); // src/errors.ts var A2A_ERROR_CODE = { PARSE_ERROR: -32700, INVALID_REQUEST: -32600, METHOD_NOT_FOUND: -32601, INVALID_PARAMS: -32602, INTERNAL_ERROR: -32603, TASK_NOT_FOUND: -32001, TASK_NOT_CANCELABLE: -32002, PUSH_NOTIFICATION_NOT_SUPPORTED: -32003, UNSUPPORTED_OPERATION: -32004, CONTENT_TYPE_NOT_SUPPORTED: -32005, INVALID_AGENT_RESPONSE: -32006, AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007 }; // src/server/transports/rest/rest_transport_handler.ts var HTTP_STATUS = { OK: 200, CREATED: 201, ACCEPTED: 202, NO_CONTENT: 204, BAD_REQUEST: 400, UNAUTHORIZED: 401, NOT_FOUND: 404, CONFLICT: 409, INTERNAL_SERVER_ERROR: 500, NOT_IMPLEMENTED: 501 }; function mapErrorToStatus(errorCode) { switch (errorCode) { case A2A_ERROR_CODE.PARSE_ERROR: case A2A_ERROR_CODE.INVALID_REQUEST: case A2A_ERROR_CODE.INVALID_PARAMS: return HTTP_STATUS.BAD_REQUEST; case A2A_ERROR_CODE.METHOD_NOT_FOUND: case A2A_ERROR_CODE.TASK_NOT_FOUND: return HTTP_STATUS.NOT_FOUND; case A2A_ERROR_CODE.TASK_NOT_CANCELABLE: return HTTP_STATUS.CONFLICT; case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED: case A2A_ERROR_CODE.UNSUPPORTED_OPERATION: return HTTP_STATUS.BAD_REQUEST; default: return HTTP_STATUS.INTERNAL_SERVER_ERROR; } } function toHTTPError(error) { const errorObject = { code: error.code, message: error.message }; if (error.data !== void 0) { errorObject.data = error.data; } return errorObject; } var RestTransportHandler = class _RestTransportHandler { requestHandler; constructor(requestHandler) { this.requestHandler = requestHandler; } // ========================================================================== // Public API Methods // ========================================================================== /** * Gets the agent card (for capability checks). */ async getAgentCard() { return this.requestHandler.getAgentCard(); } /** * Gets the authenticated extended agent card. */ async getAuthenticatedExtendedAgentCard(context) { return this.requestHandler.getAuthenticatedExtendedAgentCard(context); } /** * Validate MessageSendParams. */ validateMessageSendParams(params) { if (!params.message) { throw A2AError.invalidParams("message is required"); } if (!params.message.messageId) { throw A2AError.invalidParams("message.messageId is required"); } } /** * Sends a message to the agent. */ async sendMessage(params, context) { this.validateMessageSendParams(params); return this.requestHandler.sendMessage(params, context); } /** * Sends a message with streaming response. * @throws {A2AError} UnsupportedOperation if streaming not supported */ async sendMessageStream(params, context) { await this.requireCapability("streaming"); this.validateMessageSendParams(params); return this.requestHandler.sendMessageStream(params, context); } /** * Gets a task by ID. * Validates historyLength parameter if provided. */ async getTask(taskId, context, historyLength) { const params = { id: taskId }; if (historyLength !== void 0) { params.historyLength = this.parseHistoryLength(historyLength); } return this.requestHandler.getTask(params, context); } /** * Cancels a task. */ async cancelTask(taskId, context) { const params = { id: taskId }; return this.requestHandler.cancelTask(params, context); } /** * Resubscribes to task updates. * Returns camelCase stream of task updates. * @throws {A2AError} UnsupportedOperation if streaming not supported */ async resubscribe(taskId, context) { await this.requireCapability("streaming"); const params = { id: taskId }; return this.requestHandler.resubscribe(params, context); } /** * Sets a push notification configuration. * @throws {A2AError} PushNotificationNotSupported if push notifications not supported */ async setTaskPushNotificationConfig(config, context) { await this.requireCapability("pushNotifications"); if (!config.taskId) { throw A2AError.invalidParams("taskId is required"); } if (!config.pushNotificationConfig) { throw A2AError.invalidParams("pushNotificationConfig is required"); } return this.requestHandler.setTaskPushNotificationConfig(config, context); } /** * Lists all push notification configurations for a task. */ async listTaskPushNotificationConfigs(taskId, context) { return this.requestHandler.listTaskPushNotificationConfigs({ id: taskId }, context); } /** * Gets a specific push notification configuration. */ async getTaskPushNotificationConfig(taskId, configId, context) { return this.requestHandler.getTaskPushNotificationConfig( { id: taskId, pushNotificationConfigId: configId }, context ); } /** * Deletes a push notification configuration. */ async deleteTaskPushNotificationConfig(taskId, configId, context) { await this.requestHandler.deleteTaskPushNotificationConfig( { id: taskId, pushNotificationConfigId: configId }, context ); } /** * Static map of capability to error for missing capabilities. */ static CAPABILITY_ERRORS = { streaming: () => A2AError.unsupportedOperation("Agent does not support streaming"), pushNotifications: () => A2AError.pushNotificationNotSupported() }; /** * Validates that the agent supports a required capability. * @throws {A2AError} UnsupportedOperation for streaming, PushNotificationNotSupported for push notifications */ async requireCapability(capability) { const agentCard = await this.getAgentCard(); if (!agentCard.capabilities?.[capability]) { throw _RestTransportHandler.CAPABILITY_ERRORS[capability](); } } /** * Parses and validates historyLength query parameter. */ parseHistoryLength(value) { if (value === void 0 || value === null) { throw A2AError.invalidParams("historyLength is required"); } const parsed = parseInt(String(value), 10); if (isNaN(parsed)) { throw A2AError.invalidParams("historyLength must be a valid integer"); } if (parsed < 0) { throw A2AError.invalidParams("historyLength must be non-negative"); } return parsed; } }; // src/types/pb/a2a_types.ts function taskStateFromJSON(object) { switch (object) { case 0: case "TASK_STATE_UNSPECIFIED": return 0 /* TASK_STATE_UNSPECIFIED */; case 1: case "TASK_STATE_SUBMITTED": return 1 /* TASK_STATE_SUBMITTED */; case 2: case "TASK_STATE_WORKING": return 2 /* TASK_STATE_WORKING */; case 3: case "TASK_STATE_COMPLETED": return 3 /* TASK_STATE_COMPLETED */; case 4: case "TASK_STATE_FAILED": return 4 /* TASK_STATE_FAILED */; case 5: case "TASK_STATE_CANCELLED": return 5 /* TASK_STATE_CANCELLED */; case 6: case "TASK_STATE_INPUT_REQUIRED": return 6 /* TASK_STATE_INPUT_REQUIRED */; case 7: case "TASK_STATE_REJECTED": return 7 /* TASK_STATE_REJECTED */; case 8: case "TASK_STATE_AUTH_REQUIRED": return 8 /* TASK_STATE_AUTH_REQUIRED */; case -1: case "UNRECOGNIZED": default: return -1 /* UNRECOGNIZED */; } } function taskStateToJSON(object) { switch (object) { case 0 /* TASK_STATE_UNSPECIFIED */: return "TASK_STATE_UNSPECIFIED"; case 1 /* TASK_STATE_SUBMITTED */: return "TASK_STATE_SUBMITTED"; case 2 /* TASK_STATE_WORKING */: return "TASK_STATE_WORKING"; case 3 /* TASK_STATE_COMPLETED */: return "TASK_STATE_COMPLETED"; case 4 /* TASK_STATE_FAILED */: return "TASK_STATE_FAILED"; case 5 /* TASK_STATE_CANCELLED */: return "TASK_STATE_CANCELLED"; case 6 /* TASK_STATE_INPUT_REQUIRED */: return "TASK_STATE_INPUT_REQUIRED"; case 7 /* TASK_STATE_REJECTED */: return "TASK_STATE_REJECTED"; case 8 /* TASK_STATE_AUTH_REQUIRED */: return "TASK_STATE_AUTH_REQUIRED"; case -1 /* UNRECOGNIZED */: default: return "UNRECOGNIZED"; } } function roleFromJSON(object) { switch (object) { case 0: case "ROLE_UNSPECIFIED": return 0 /* ROLE_UNSPECIFIED */; case 1: case "ROLE_USER": return 1 /* ROLE_USER */; case 2: case "ROLE_AGENT": return 2 /* ROLE_AGENT */; case -1: case "UNRECOGNIZED": default: return -1 /* UNRECOGNIZED */; } } function roleToJSON(object) { switch (object) { case 0 /* ROLE_UNSPECIFIED */: return "ROLE_UNSPECIFIED"; case 1 /* ROLE_USER */: return "ROLE_USER"; case 2 /* ROLE_AGENT */: return "ROLE_AGENT"; case -1 /* UNRECOGNIZED */: default: return "UNRECOGNIZED"; } } var SendMessageConfiguration = { fromJSON(object) { return { acceptedOutputModes: globalThis.Array.isArray(object?.acceptedOutputModes) ? object.acceptedOutputModes.map((e) => globalThis.String(e)) : globalThis.Array.isArray(object?.accepted_output_modes) ? object.accepted_output_modes.map( (e) => globalThis.String(e) ) : [], pushNotification: isSet(object.pushNotification) ? PushNotificationConfig.fromJSON(object.pushNotification) : isSet(object.push_notification) ? PushNotificationConfig.fromJSON(object.push_notification) : void 0, historyLength: isSet(object.historyLength) ? globalThis.Number(object.historyLength) : isSet(object.history_length) ? globalThis.Number(object.history_length) : 0, blocking: isSet(object.blocking) ? globalThis.Boolean(object.blocking) : false }; }, toJSON(message) { const obj = {}; if (message.acceptedOutputModes?.length) { obj.acceptedOutputModes = message.acceptedOutputModes; } if (message.pushNotification !== void 0) { obj.pushNotification = PushNotificationConfig.toJSON(message.pushNotification); } if (message.historyLength !== 0) { obj.historyLength = Math.round(message.historyLength); } if (message.blocking !== false) { obj.blocking = message.blocking; } return obj; } }; var Task = { fromJSON(object) { return { id: isSet(object.id) ? globalThis.String(object.id) : "", contextId: isSet(object.contextId) ? globalThis.String(object.contextId) : isSet(object.context_id) ? globalThis.String(object.context_id) : "", status: isSet(object.status) ? TaskStatus.fromJSON(object.status) : void 0, artifacts: globalThis.Array.isArray(object?.artifacts) ? object.artifacts.map((e) => Artifact.fromJSON(e)) : [], history: globalThis.Array.isArray(object?.history) ? object.history.map((e) => Message.fromJSON(e)) : [], metadata: isObject(object.metadata) ? object.metadata : void 0 }; }, toJSON(message) { const obj = {}; if (message.id !== "") { obj.id = message.id; } if (message.contextId !== "") { obj.contextId = message.contextId; } if (message.status !== void 0) { obj.status = TaskStatus.toJSON(message.status); } if (message.artifacts?.length) { obj.artifacts = message.artifacts.map((e) => Artifact.toJSON(e)); } if (message.history?.length) { obj.history = message.history.map((e) => Message.toJSON(e)); } if (message.metadata !== void 0) { obj.metadata = message.metadata; } return obj; } }; var TaskStatus = { fromJSON(object) { return { state: isSet(object.state) ? taskStateFromJSON(object.state) : 0, update: isSet(object.message) ? Message.fromJSON(object.message) : isSet(object.update) ? Message.fromJSON(object.update) : void 0, timestamp: isSet(object.timestamp) ? globalThis.String(object.timestamp) : void 0 }; }, toJSON(message) { const obj = {}; if (message.state !== 0) { obj.state = taskStateToJSON(message.state); } if (message.update !== void 0) { obj.message = Message.toJSON(message.update); } if (message.timestamp !== void 0) { obj.timestamp = message.timestamp; } return obj; } }; var Part = { fromJSON(object) { return { part: isSet(object.text) ? { $case: "text", value: globalThis.String(object.text) } : isSet(object.file) ? { $case: "file", value: FilePart.fromJSON(object.file) } : isSet(object.data) ? { $case: "data", value: DataPart.fromJSON(object.data) } : void 0 }; }, toJSON(message) { const obj = {}; if (message.part?.$case === "text") { obj.text = message.part.value; } else if (message.part?.$case === "file") { obj.file = FilePart.toJSON(message.part.value); } else if (message.part?.$case === "data") { obj.data = DataPart.toJSON(message.part.value); } return obj; } }; var FilePart = { fromJSON(object) { return { file: isSet(object.fileWithUri) ? { $case: "fileWithUri", value: globalThis.String(object.fileWithUri) } : isSet(object.file_with_uri) ? { $case: "fileWithUri", value: globalThis.String(object.file_with_uri) } : isSet(object.fileWithBytes) ? { $case: "fileWithBytes", value: Buffer.from(bytesFromBase64(object.fileWithBytes)) } : isSet(object.file_with_bytes) ? { $case: "fileWithBytes", value: Buffer.from(bytesFromBase64(object.file_with_bytes)) } : void 0, mimeType: isSet(object.mimeType) ? globalThis.String(object.mimeType) : isSet(object.mime_type) ? globalThis.String(object.mime_type) : "" }; }, toJSON(message) { const obj = {}; if (message.file?.$case === "fileWithUri") { obj.fileWithUri = message.file.value; } else if (message.file?.$case === "fileWithBytes") { obj.fileWithBytes = base64FromBytes(message.file.value); } if (message.mimeType !== "") { obj.mimeType = message.mimeType; } return obj; } }; var DataPart = { fromJSON(object) { return { data: isObject(object.data) ? object.data : void 0 }; }, toJSON(message) { const obj = {}; if (message.data !== void 0) { obj.data = message.data; } return obj; } }; var Message = { fromJSON(object) { return { messageId: isSet(object.messageId) ? globalThis.String(object.messageId) : isSet(object.message_id) ? globalThis.String(object.message_id) : "", contextId: isSet(object.contextId) ? globalThis.String(object.contextId) : isSet(object.context_id) ? globalThis.String(object.context_id) : "", taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : isSet(object.task_id) ? globalThis.String(object.task_id) : "", role: isSet(object.role) ? roleFromJSON(object.role) : 0, content: globalThis.Array.isArray(object?.content) ? object.content.map((e) => Part.fromJSON(e)) : [], metadata: isObject(object.metadata) ? object.metadata : void 0, extensions: globalThis.Array.isArray(object?.extensions) ? object.extensions.map((e) => globalThis.String(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.messageId !== "") { obj.messageId = message.messageId; } if (message.contextId !== "") { obj.contextId = message.contextId; } if (message.taskId !== "") { obj.taskId = message.taskId; } if (message.role !== 0) { obj.role = roleToJSON(message.role); } if (message.content?.length) { obj.content = message.content.map((e) => Part.toJSON(e)); } if (message.metadata !== void 0) { obj.metadata = message.metadata; } if (message.extensions?.length) { obj.extensions = message.extensions; } return obj; } }; var Artifact = { fromJSON(object) { return { artifactId: isSet(object.artifactId) ? globalThis.String(object.artifactId) : isSet(object.artifact_id) ? globalThis.String(object.artifact_id) : "", name: isSet(object.name) ? globalThis.String(object.name) : "", description: isSet(object.description) ? globalThis.String(object.description) : "", parts: globalThis.Array.isArray(object?.parts) ? object.parts.map((e) => Part.fromJSON(e)) : [], metadata: isObject(object.metadata) ? object.metadata : void 0, extensions: globalThis.Array.isArray(object?.extensions) ? object.extensions.map((e) => globalThis.String(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.artifactId !== "") { obj.artifactId = message.artifactId; } if (message.name !== "") { obj.name = message.name; } if (message.description !== "") { obj.description = message.description; } if (message.parts?.length) { obj.parts = message.parts.map((e) => Part.toJSON(e)); } if (message.metadata !== void 0) { obj.metadata = message.metadata; } if (message.extensions?.length) { obj.extensions = message.extensions; } return obj; } }; var TaskStatusUpdateEvent = { fromJSON(object) { return { taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : isSet(object.task_id) ? globalThis.String(object.task_id) : "", contextId: isSet(object.contextId) ? globalThis.String(object.contextId) : isSet(object.context_id) ? globalThis.String(object.context_id) : "", status: isSet(object.status) ? TaskStatus.fromJSON(object.status) : void 0, final: isSet(object.final) ? globalThis.Boolean(object.final) : false, metadata: isObject(object.metadata) ? object.metadata : void 0 }; }, toJSON(message) { const obj = {}; if (message.taskId !== "") { obj.taskId = message.taskId; } if (message.contextId !== "") { obj.contextId = message.contextId; } if (message.status !== void 0) { obj.status = TaskStatus.toJSON(message.status); } if (message.final !== false) { obj.final = message.final; } if (message.metadata !== void 0) { obj.metadata = message.metadata; } return obj; } }; var TaskArtifactUpdateEvent = { fromJSON(object) { return { taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : isSet(object.task_id) ? globalThis.String(object.task_id) : "", contextId: isSet(object.contextId) ? globalThis.String(object.contextId) : isSet(object.context_id) ? globalThis.String(object.context_id) : "", artifact: isSet(object.artifact) ? Artifact.fromJSON(object.artifact) : void 0, append: isSet(object.append) ? globalThis.Boolean(object.append) : false, lastChunk: isSet(object.lastChunk) ? globalThis.Boolean(object.lastChunk) : isSet(object.last_chunk) ? globalThis.Boolean(object.last_chunk) : false, metadata: isObject(object.metadata) ? object.metadata : void 0 }; }, toJSON(message) { const obj = {}; if (message.taskId !== "") { obj.taskId = message.taskId; } if (message.contextId !== "") { obj.contextId = message.contextId; } if (message.artifact !== void 0) { obj.artifact = Artifact.toJSON(message.artifact); } if (message.append !== false) { obj.append = message.append; } if (message.lastChunk !== false) { obj.lastChunk = message.lastChunk; } if (message.metadata !== void 0) { obj.metadata = message.metadata; } return obj; } }; var PushNotificationConfig = { fromJSON(object) { return { id: isSet(object.id) ? globalThis.String(object.id) : "", url: isSet(object.url) ? globalThis.String(object.url) : "", token: isSet(object.token) ? globalThis.String(object.token) : "", authentication: isSet(object.authentication) ? AuthenticationInfo.fromJSON(object.authentication) : void 0 }; }, toJSON(message) { const obj = {}; if (message.id !== "") { obj.id = message.id; } if (message.url !== "") { obj.url = message.url; } if (message.token !== "") { obj.token = message.token; } if (message.authentication !== void 0) { obj.authentication = AuthenticationInfo.toJSON(message.authentication); } return obj; } }; var AuthenticationInfo = { fromJSON(object) { return { schemes: globalThis.Array.isArray(object?.schemes) ? object.schemes.map((e) => globalThis.String(e)) : [], credentials: isSet(object.credentials) ? globalThis.String(object.credentials) : "" }; }, toJSON(message) { const obj = {}; if (message.schemes?.length) { obj.schemes = message.schemes; } if (message.credentials !== "") { obj.credentials = message.credentials; } return obj; } }; var AgentInterface = { fromJSON(object) { return { url: isSet(object.url) ? globalThis.String(object.url) : "", transport: isSet(object.transport) ? globalThis.String(object.transport) : "" }; }, toJSON(message) { const obj = {}; if (message.url !== "") { obj.url = message.url; } if (message.transport !== "") { obj.transport = message.transport; } return obj; } }; var AgentCard = { fromJSON(object) { return { protocolVersion: isSet(object.protocolVersion) ? globalThis.String(object.protocolVersion) : isSet(object.protocol_version) ? globalThis.String(object.protocol_version) : "", name: isSet(object.name) ? globalThis.String(object.name) : "", description: isSet(object.description) ? globalThis.String(object.description) : "", url: isSet(object.url) ? globalThis.String(object.url) : "", preferredTransport: isSet(object.preferredTransport) ? globalThis.String(object.preferredTransport) : isSet(object.preferred_transport) ? globalThis.String(object.preferred_transport) : "", additionalInterfaces: globalThis.Array.isArray(object?.additionalInterfaces) ? object.additionalInterfaces.map((e) => AgentInterface.fromJSON(e)) : globalThis.Array.isArray(object?.additional_interfaces) ? object.additional_interfaces.map((e) => AgentInterface.fromJSON(e)) : [], provider: isSet(object.provider) ? AgentProvider.fromJSON(object.provider) : void 0, version: isSet(object.version) ? globalThis.String(object.version) : "", documentationUrl: isSet(object.documentationUrl) ? globalThis.String(object.documentationUrl) : isSet(object.documentation_url) ? globalThis.String(object.documentation_url) : "", capabilities: isSet(object.capabilities) ? AgentCapabilities.fromJSON(object.capabilities) : void 0, securitySchemes: isObject(object.securitySchemes) ? globalThis.Object.entries(object.securitySchemes).reduce( (acc, [key, value]) => { acc[key] = SecurityScheme.fromJSON(value); return acc; }, {} ) : isObject(object.security_schemes) ? globalThis.Object.entries(object.security_schemes).reduce( (acc, [key, value]) => { acc[key] = SecurityScheme.fromJSON(value); return acc; }, {} ) : {}, security: globalThis.Array.isArray(object?.security) ? object.security.map((e) => Security.fromJSON(e)) : [], defaultInputModes: globalThis.Array.isArray(object?.defaultInputModes) ? object.defaultInputModes.map((e) => globalThis.String(e)) : globalThis.Array.isArray(object?.default_input_modes) ? object.default_input_modes.map((e) => globalThis.String(e)) : [], defaultOutputModes: globalThis.Array.isArray(object?.defaultOutputModes) ? object.defaultOutputModes.map((e) => globalThis.String(e)) : globalThis.Array.isArray(object?.default_output_modes) ? object.default_output_modes.map((e) => globalThis.String(e)) : [], skills: globalThis.Array.isArray(object?.skills) ? object.skills.map((e) => AgentSkill.fromJSON(e)) : [], supportsAuthenticatedExtendedCard: isSet(object.supportsAuthenticatedExtendedCard) ? globalThis.Boolean(object.supportsAuthenticatedExtendedCard) : isSet(object.supports_authenticated_extended_card) ? globalThis.Boolean(object.supports_authenticated_extended_card) : false, signatures: globalThis.Array.isArray(object?.signatures) ? object.signatures.map((e) => AgentCardSignature.fromJSON(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.protocolVersion !== "") { obj.protocolVersion = message.protocolVersion; } if (message.name !== "") { obj.name = message.name; } if (message.description !== "") { obj.description = message.description; } if (message.url !== "") { obj.url = message.url; } if (message.preferredTransport !== "") { obj.preferredTransport = message.preferredTransport; } if (message.additionalInterfaces?.length) { obj.additionalInterfaces = message.additionalInterfaces.map((e) => AgentInterface.toJSON(e)); } if (message.provider !== void 0) { obj.provider = AgentProvider.toJSON(message.provider); } if (message.version !== "") { obj.version = message.version; } if (message.documentationUrl !== "") { obj.documentationUrl = message.documentationUrl; } if (message.capabilities !== void 0) { obj.capabilities = AgentCapabilities.toJSON(message.capabilities); } if (message.securitySchemes) { const entries = globalThis.Object.entries(message.securitySchemes); if (entries.length > 0) { obj.securitySchemes = {}; entries.forEach(([k, v]) => { obj.securitySchemes[k] = SecurityScheme.toJSON(v); }); } } if (message.security?.length) { obj.security = message.security.map((e) => Security.toJSON(e)); } if (message.defaultInputModes?.length) { obj.defaultInputModes = message.defaultInputModes; } if (message.defaultOutputModes?.length) { obj.defaultOutputModes = message.defaultOutputModes; } if (message.skills?.length) { obj.skills = message.skills.map((e) => AgentSkill.toJSON(e)); } if (message.supportsAuthenticatedExtendedCard !== false) { obj.supportsAuthenticatedExtendedCard = message.supportsAuthenticatedExtendedCard; } if (message.signatures?.length) { obj.signatures = message.signatures.map((e) => AgentCardSignature.toJSON(e)); } return obj; } }; var AgentProvider = { fromJSON(object) { return { url: isSet(object.url) ? globalThis.String(object.url) : "", organization: isSet(object.organization) ? globalThis.String(object.organization) : "" }; }, toJSON(message) { const obj = {}; if (message.url !== "") { obj.url = message.url; } if (message.organization !== "") { obj.organization = message.organization; } return obj; } }; var AgentCapabilities = { fromJSON(object) { return { streaming: isSet(object.streaming) ? globalThis.Boolean(object.streaming) : false, pushNotifications: isSet(object.pushNotifications) ? globalThis.Boolean(object.pushNotifications) : isSet(object.push_notifications) ? globalThis.Boolean(object.push_notifications) : false, extensions: globalThis.Array.isArray(object?.extensions) ? object.extensions.map((e) => AgentExtension.fromJSON(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.streaming !== false) { obj.streaming = message.streaming; } if (message.pushNotifications !== false) { obj.pushNotifications = message.pushNotifications; } if (message.extensions?.length) { obj.extensions = message.extensions.map((e) => AgentExtension.toJSON(e)); } return obj; } }; var AgentExtension = { fromJSON(object) { return { uri: isSet(object.uri) ? globalThis.String(object.uri) : "", description: isSet(object.description) ? globalThis.String(object.description) : "", required: isSet(object.required) ? globalThis.Boolean(object.required) : false, params: isObject(object.params) ? object.params : void 0 }; }, toJSON(message) { const obj = {}; if (message.uri !== "") { obj.uri = message.uri; } if (message.description !== "") { obj.description = message.description; } if (message.required !== false) { obj.required = message.required; } if (message.params !== void 0) { obj.params = message.params; } return obj; } }; var AgentSkill = { fromJSON(object) { return { id: isSet(object.id) ? globalThis.String(object.id) : "", name: isSet(object.name) ? globalThis.String(object.name) : "", description: isSet(object.description) ? globalThis.String(object.description) : "", tags: globalThis.Array.isArray(object?.tags) ? object.tags.map((e) => globalThis.String(e)) : [], examples: globalThis.Array.isArray(object?.examples) ? object.examples.map((e) => globalThis.String(e)) : [], inputModes: globalThis.Array.isArray(object?.inputModes) ? object.inputModes.map((e) => globalThis.String(e)) : globalThis.Array.isArray(object?.input_modes) ? object.input_modes.map((e) => globalThis.String(e)) : [], outputModes: globalThis.Array.isArray(object?.outputModes) ? object.outputModes.map((e) => globalThis.String(e)) : globalThis.Array.isArray(object?.output_modes) ? object.output_modes.map((e) => globalThis.String(e)) : [], security: globalThis.Array.isArray(object?.security) ? object.security.map((e) => Security.fromJSON(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.id !== "") { obj.id = message.id; } if (message.name !== "") { obj.name = message.name; } if (message.description !== "") { obj.description = message.description; } if (message.tags?.length) { obj.tags = message.tags; } if (message.examples?.length) { obj.examples = message.examples; } if (message.inputModes?.length) { obj.inputModes = message.inputModes; } if (message.outputModes?.length) { obj.outputModes = message.outputModes; } if (message.security?.length) { obj.security = message.security.map((e) => Security.toJSON(e)); } return obj; } }; var AgentCardSignature = { fromJSON(object) { return { protected: isSet(object.protected) ? globalThis.String(object.protected) : "", signature: isSet(object.signature) ? globalThis.String(object.signature) : "", header: isObject(object.header) ? object.header : void 0 }; }, toJSON(message) { const obj = {}; if (message.protected !== "") { obj.protected = message.protected; } if (message.signature !== "") { obj.signature = message.signature; } if (message.header !== void 0) { obj.header = message.header; } return obj; } }; var TaskPushNotificationConfig = { fromJSON(object) { return { name: isSet(object.name) ? globalThis.String(object.name) : "", pushNotificationConfig: isSet(object.pushNotificationConfig) ? PushNotificationConfig.fromJSON(object.pushNotificationConfig) : isSet(object.push_notification_config) ? PushNotificationConfig.fromJSON(object.push_notification_config) : void 0 }; }, toJSON(message) { const obj = {}; if (message.name !== "") { obj.name = message.name; } if (message.pushNotificationConfig !== void 0) { obj.pushNotificationConfig = PushNotificationConfig.toJSON(message.pushNotificationConfig); } return obj; } }; var StringList = { fromJSON(object) { return { list: globalThis.Array.isArray(object?.list) ? object.list.map((e) => globalThis.String(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.list?.length) { obj.list = message.list; } return obj; } }; var Security = { fromJSON(object) { return { schemes: isObject(object.schemes) ? globalThis.Object.entries(object.schemes).reduce( (acc, [key, value]) => { acc[key] = StringList.fromJSON(value); return acc; }, {} ) : {} }; }, toJSON(message) { const obj = {}; if (message.schemes) { const entries = globalThis.Object.entries(message.schemes); if (entries.length > 0) { obj.schemes = {}; entries.forEach(([k, v]) => { obj.schemes[k] = StringList.toJSON(v); }); } } return obj; } }; var SecurityScheme = { fromJSON(object) { return { scheme: isSet(object.apiKeySecurityScheme) ? { $case: "apiKeySecurityScheme", value: APIKeySecurityScheme.fromJSON(object.apiKeySecurityScheme) } : isSet(object.api_key_security_scheme) ? { $case: "apiKeySecurityScheme", value: APIKeySecurityScheme.fromJSON(object.api_key_security_scheme) } : isSet(object.httpAuthSecurityScheme) ? { $case: "httpAuthSecurityScheme", value: HTTPAuthSecurityScheme.fromJSON(object.httpAuthSecurityScheme) } : isSet(object.http_auth_security_scheme) ? { $case: "httpAuthSecurityScheme", value: HTTPAuthSecurityScheme.fromJSON(object.http_auth_security_scheme) } : isSet(object.oauth2SecurityScheme) ? { $case: "oauth2SecurityScheme", value: OAuth2SecurityScheme.fromJSON(object.oauth2SecurityScheme) } : isSet(object.oauth2_security_scheme) ? { $case: "oauth2SecurityScheme", value: OAuth2SecurityScheme.fromJSON(object.oauth2_security_scheme) } : isSet(object.openIdConnectSecurityScheme) ? { $case: "openIdConnectSecurityScheme", value: OpenIdConnectSecurityScheme.fromJSON(object.openIdConnectSecurityScheme) } : isSet(object.open_id_connect_security_scheme) ? { $case: "openIdConnectSecurityScheme", value: OpenIdConnectSecurityScheme.fromJSON(object.open_id_connect_security_scheme) } : isSet(object.mtlsSecurityScheme) ? { $case: "mtlsSecurityScheme", value: MutualTlsSecurityScheme.fromJSON(object.mtlsSecurityScheme) } : isSet(object.mtls_security_scheme) ? { $case: "mtlsSecurityScheme", value: MutualTlsSecurityScheme.fromJSON(object.mtls_security_scheme) } : void 0 }; }, toJSON(message) { const obj = {}; if (message.scheme?.$case === "apiKeySecurityScheme") { obj.apiKeySecurityScheme = APIKeySecurityScheme.toJSON(message.scheme.value); } else if (message.scheme?.$case === "httpAuthSecurityScheme") { obj.httpAuthSecurityScheme = HTTPAuthSecurityScheme.toJSON(message.scheme.value); } else if (message.scheme?.$case === "oauth2SecurityScheme") { obj.oauth2SecurityScheme = OAuth2SecurityScheme.toJSON(message.scheme.value); } else if (message.scheme?.$case === "openIdConnectSecurityScheme") { obj.openIdConnectSecurityScheme = OpenIdConnectSecurityScheme.toJSON(message.scheme.value); } else if (message.scheme?.$case === "mtlsSecurityScheme") { obj.mtlsSecurityScheme = MutualTlsSecurityScheme.toJSON(message.scheme.value); } return obj; } }; var APIKeySecurityScheme = { fromJSON(object) { return { description: isSet(object.description) ? globalThis.String(object.description) : "", location: isSet(object.location) ? globalThis.String(object.location) : "", name: isSet(object.name) ? globalThis.String(object.name) : "" }; }, toJSON(message) { const obj = {}; if (message.description !== "") { obj.description = message.description; } if (message.location !== "") { obj.location = message.location; } if (message.name !== "") { obj.name = message.name; } return obj; } }; var HTTPAuthSecurityScheme = { fromJSON(object) { return { description: isSet(object.description) ? globalThis.String(object.description) : "", scheme: isSet(object.scheme) ? globalThis.String(object.scheme) : "", bearerFormat: isSet(object.bearerFormat) ? globalThis.String(object.bearerFormat) : isSet(object.bearer_format) ? globalThis.String(object.bearer_format) : "" }; }, toJSON(message) { const obj = {}; if (message.description !== "") { obj.description = message.description; } if (message.scheme !== "") { obj.scheme = message.scheme; } if (message.bearerFormat !== "") { obj.bearerFormat = message.bearerFormat; } return obj; } }; var OAuth2SecurityScheme = { fromJSON(object) { return { description: isSet(object.description) ? globalThis.String(object.description) : "", flows: isSet(object.flows) ? OAuthFlows.fromJSON(object.flows) : void 0, oauth2MetadataUrl: isSet(object.oauth2MetadataUrl) ? globalThis.String(object.oauth2MetadataUrl) : isSet(object.oauth2_metadata_url) ? globalThis.String(object.oauth2_metadata_url) : "" }; }, toJSON(message) { const obj = {}; if (message.description !== "") { obj.description = message.description; } if (message.flows !== void 0) { obj.flows = OAuthFlows.toJSON(message.flows); } if (message.oauth2MetadataUrl !== "") { obj.oauth2MetadataUrl = message.oauth2MetadataUrl; } return obj; } }; var OpenIdConnectSecurityScheme = { fromJSON(object) { return { description: isSet(object.description) ? globalThis.String(object.description) : "", openIdConnectUrl: isSet(object.openIdConnectUrl) ? globalThis.String(object.openIdConnectUrl) : isSet(object.open_id_connect_url) ? globalThis.String(object.open_id_connect_url) : "" }; }, toJSON(message) { const obj = {}; if (message.description !== "") { obj.description = message.description; } if (message.openIdConnectUrl !== "") { obj.openIdConnectUrl = message.openIdConnectUrl; } return obj; } }; var MutualTlsSecurityScheme = { fromJSON(object) { return { description: isSet(object.description) ? globalThis.String(object.description) : "" }; }, toJSON(message) { const obj = {}; if (message.description !== "") { obj.description = message.description; } return obj; } }; var OAuthFlows = { fromJSON(object) { return { flow: isSet(object.authorizationCode) ? { $case: "authorizationCode", value: AuthorizationCodeOAuthFlow.fromJSON(object.authorizationCode) } : isSet(object.authorization_code) ? { $case: "authorizationCode", value: AuthorizationCodeOAuthFlow.fromJSON(object.authorization_code) } : isSet(object.clientCredentials) ? { $case: "clientCredentials", value: ClientCredentialsOAuthFlow.fromJSON(object.clientCredentials) } : isSet(object.client_credentials) ? { $case: "clientCredentials", value: ClientCredentialsOAuthFlow.fromJSON(object.client_credentials) } : isSet(object.implicit) ? { $case: "implicit", value: ImplicitOAuthFlow.fromJSON(object.implicit) } : isSet(object.password) ? { $case: "password", value: PasswordOAuthFlow.fromJSON(object.password) } : void 0 }; }, toJSON(message) { const obj = {}; if (message.flow?.$case === "authorizationCode") { obj.authorizationCode = AuthorizationCodeOAuthFlow.toJSON(message.flow.value); } else if (message.flow?.$case === "clientCredentials") { obj.clientCredentials = ClientCredentialsOAuthFlow.toJSON(message.flow.value); } else if (message.flow?.$case === "implicit") { obj.implicit = ImplicitOAuthFlow.toJSON(message.flow.value); } else if (message.flow?.$case === "password") { obj.password = PasswordOAuthFlow.toJSON(message.flow.value); } return obj; } }; var AuthorizationCodeOAuthFlow = { fromJSON(object) { return { authorizationUrl: isSet(object.authorizationUrl) ? globalThis.String(object.authorizationUrl) : isSet(object.authorization_url) ? globalThis.String(object.authorization_url) : "", tokenUrl: isSet(object.tokenUrl) ? globalThis.String(object.tokenUrl) : isSet(object.token_url) ? globalThis.String(object.token_url) : "", refreshUrl: isSet(object.refreshUrl) ? globalThis.String(object.refreshUrl) : isSet(object.refresh_url) ? globalThis.String(object.refresh_url) : "", scopes: isObject(object.scopes) ? globalThis.Object.entries(object.scopes).reduce( (acc, [key, value]) => { acc[key] = globalThis.String(value); return acc; }, {} ) : {} }; }, toJSON(message) { const obj = {}; if (message.authorizationUrl !== "") { obj.authorizationUrl = message.authorizationUrl; } if (message.tokenUrl !== "") { obj.tokenUrl = message.tokenUrl; } if (message.refreshUrl !== "") { obj.refreshUrl = message.refreshUrl; } if (message.scopes) { const entries = globalThis.Object.entries(message.scopes); if (entries.length > 0) { obj.scopes = {}; entries.forEach(([k, v]) => { obj.scopes[k] = v; }); } } return obj; } }; var ClientCredentialsOAuthFlow = { fromJSON(object) { return { tokenUrl: isSet(object.tokenUrl) ? globalThis.String(object.tokenUrl) : isSet(object.token_url) ? globalThis.String(object.token_url) : "", refreshUrl: isSet(object.refreshUrl) ? globalThis.String(object.refreshUrl) : isSet(object.refresh_url) ? globalThis.String(object.refresh_url) : "", scopes: isObject(object.scopes) ? globalThis.Object.entries(object.scopes).reduce( (acc, [key, value]) => { acc[key] = globalThis.String(value); return acc; }, {} ) : {} }; }, toJSON(message) { const obj = {}; if (message.tokenUrl !== "") { obj.tokenUrl = message.tokenUrl; } if (message.refreshUrl !== "") { obj.refreshUrl = message.refreshUrl; } if (message.scopes) { const entries = globalThis.Object.entries(message.scopes); if (entries.length > 0) { obj.scopes = {}; entries.forEach(([k, v]) => { obj.scopes[k] = v; }); } } return obj; } }; var ImplicitOAuthFlow = { fromJSON(object) { return { authorizationUrl: isSet(object.authorizationUrl) ? globalThis.String(object.authorizationUrl) : isSet(object.authorization_url) ? globalThis.String(object.authorization_url) : "", refreshUrl: isSet(object.refreshUrl) ? globalThis.String(object.refreshUrl) : isSet(object.refresh_url) ? globalThis.String(object.refresh_url) : "", scopes: isObject(object.scopes) ? globalThis.Object.entries(object.scopes).reduce( (acc, [key, value]) => { acc[key] = globalThis.String(value); return acc; }, {} ) : {} }; }, toJSON(message) { const obj = {}; if (message.authorizationUrl !== "") { obj.authorizationUrl = message.authorizationUrl; } if (message.refreshUrl !== "") { obj.refreshUrl = message.refreshUrl; } if (message.scopes) { const entries = globalThis.Object.entries(message.scopes); if (entries.length > 0) { obj.scopes = {}; entries.forEach(([k, v]) => { obj.scopes[k] = v; }); } } return obj; } }; var PasswordOAuthFlow = { fromJSON(object) { return { tokenUrl: isSet(object.tokenUrl) ? globalThis.String(object.tokenUrl) : isSet(object.token_url) ? globalThis.String(object.token_url) : "", refreshUrl: isSet(object.refreshUrl) ? globalThis.String(object.refreshUrl) : isSet(object.refresh_url) ? globalThis.String(object.refresh_url) : "", scopes: isObject(object.scopes) ? globalThis.Object.entries(object.scopes).reduce( (acc, [key, value]) => { acc[key] = globalThis.String(value); return acc; }, {} ) : {} }; }, toJSON(message) { const obj = {}; if (message.tokenUrl !== "") { obj.tokenUrl = message.tokenUrl; } if (message.refreshUrl !== "") { obj.refreshUrl = message.refreshUrl; } if (message.scopes) { const entries = globalThis.Object.entries(message.scopes); if (entries.length > 0) { obj.scopes = {}; entries.forEach(([k, v]) => { obj.scopes[k] = v; }); } } return obj; } }; var SendMessageRequest = { fromJSON(object) { return { request: isSet(object.message) ? Message.fromJSON(object.message) : isSet(object.request) ? Message.fromJSON(object.request) : void 0, configuration: isSet(object.configuration) ? SendMessageConfiguration.fromJSON(object.configuration) : void 0, metadata: isObject(object.metadata) ? object.metadata : void 0 }; }, toJSON(message) { const obj = {}; if (message.request !== void 0) { obj.message = Message.toJSON(message.request); } if (message.configuration !== void 0) { obj.configuration = SendMessageConfiguration.toJSON(message.configuration); } if (message.metadata !== void 0) { obj.metadata = message.metadata; } return obj; } }; var CreateTaskPushNotificationConfigRequest = { fromJSON(object) { return { parent: isSet(object.parent) ? globalThis.String(object.parent) : "", configId: isSet(object.configId) ? globalThis.String(object.configId) : isSet(object.config_id) ? globalThis.String(object.config_id) : "", config: isSet(object.config) ? TaskPushNotificationConfig.fromJSON(object.config) : void 0 }; }, toJSON(message) { const obj = {}; if (message.parent !== "") { obj.parent = message.parent; } if (message.configId !== "") { obj.configId = message.configId; } if (message.config !== void 0) { obj.config = TaskPushNotificationConfig.toJSON(message.config); } return obj; } }; var SendMessageResponse = { fromJSON(object) { return { payload: isSet(object.task) ? { $case: "task", value: Task.fromJSON(object.task) } : isSet(object.message) ? { $case: "msg", value: Message.fromJSON(object.message) } : isSet(object.msg) ? { $case: "msg", value: Message.fromJSON(object.msg) } : void 0 }; }, toJSON(message) { const obj = {}; if (message.payload?.$case === "task") { obj.task = Task.toJSON(message.payload.value); } else if (message.payload?.$case === "msg") { obj.message = Message.toJSON(message.payload.value); } return obj; } }; var StreamResponse = { fromJSON(object) { return { payload: isSet(object.task) ? { $case: "task", value: Task.fromJSON(object.task) } : isSet(object.message) ? { $case: "msg", value: Message.fromJSON(object.message) } : isSet(object.msg) ? { $case: "msg", value: Message.fromJSON(object.msg) } : isSet(object.statusUpdate) ? { $case: "statusUpdate", value: TaskStatusUpdateEvent.fromJSON(object.statusUpdate) } : isSet(object.status_update) ? { $case: "statusUpdate", value: TaskStatusUpdateEvent.fromJSON(object.status_update) } : isSet(object.artifactUpdate) ? { $case: "artifactUpdate", value: TaskArtifactUpdateEvent.fromJSON(object.artifactUpdate) } : isSet(object.artifact_update) ? { $case: "artifactUpdate", value: TaskArtifactUpdateEvent.fromJSON(object.artifact_update) } : void 0 }; }, toJSON(message) { const obj = {}; if (message.payload?.$case === "task") { obj.task = Task.toJSON(message.payload.value); } else if (message.payload?.$case === "msg") { obj.message = Message.toJSON(message.payload.value); } else if (message.payload?.$case === "statusUpdate") { obj.statusUpdate = TaskStatusUpdateEvent.toJSON(message.payload.value); } else if (message.payload?.$case === "artifactUpdate") { obj.artifactUpdate = TaskArtifactUpdateEvent.toJSON(message.payload.value); } return obj; } }; var ListTaskPushNotificationConfigResponse = { fromJSON(object) { return { configs: globalThis.Array.isArray(object?.configs) ? object.configs.map((e) => TaskPushNotificationConfig.fromJSON(e)) : [], nextPageToken: isSet(object.nextPageToken) ? globalThis.String(object.nextPageToken) : isSet(object.next_page_token) ? globalThis.String(object.next_page_token) : "" }; }, toJSON(message) { const obj = {}; if (message.configs?.length) { obj.configs = message.configs.map((e) => TaskPushNotificationConfig.toJSON(e)); } if (message.nextPageToken !== "") { obj.nextPageToken = message.nextPageToken; } return obj; } }; function bytesFromBase64(b64) { return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); } function base64FromBytes(arr) { return globalThis.Buffer.from(arr).toString("base64"); } function isObject(value) { return typeof value === "object" && value !== null; } function isSet(value) { return value !== null && value !== void 0; } // src/types/converters/id_decoding.ts var CONFIG_REGEX = /^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/; var TASK_ONLY_REGEX = /^tasks\/([^/]+)(?:\/|$)/; var extractTaskId = (name) => { const match = name.match(TASK_ONLY_REGEX); if (!match) { throw A2AError.invalidParams(`Invalid or missing task ID in: "${name}"`); } return match[1]; }; var generateTaskName = (taskId) => { return `tasks/${taskId}`; }; var extractTaskAndPushNotificationConfigId = (name) => { const match = name.match(CONFIG_REGEX); if (!match) { throw A2AError.invalidParams(`Invalid or missing config ID in: "${name}"`); } return { taskId: match[1], configId: match[2] }; }; var generatePushNotificationConfigName = (taskId, configId) => { return `tasks/${taskId}/pushNotificationConfigs/${configId}`; }; // src/types/converters/from_proto.ts var FromProto = class _FromProto { static taskQueryParams(request) { return { id: extractTaskId(request.name), historyLength: request.historyLength }; } static taskIdParams(request) { return { id: extractTaskId(request.name) }; } static getTaskPushNotificationConfigParams(request) { const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name); return { id: taskId, pushNotificationConfigId: configId }; } static listTaskPushNotificationConfigParams(request) { return { id: extractTaskId(request.parent) }; } static createTaskPushNotificationConfig(request) { if (!request.config?.pushNotificationConfig) { throw A2AError.invalidParams( "Request must include a `config` object with a `pushNotificationConfig`" ); } return { taskId: extractTaskId(request.parent), pushNotificationConfig: _FromProto.pushNotificationConfig( request.config.pushNotificationConfig ) }; } static deleteTaskPushNotificationConfigParams(request) { const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name); return { id: taskId, pushNotificationConfigId: configId }; } static message(message) { if (!message) { return void 0; } return { kind: "message", messageId: message.messageId, parts: message.content.map((p) => _FromProto.part(p)), contextId: message.contextId || void 0, taskId: message.taskId || void 0, role: _FromProto.role(message.role), metadata: message.metadata, extensions: message.extensions }; } static role(role) { switch (role) { case 2 /* ROLE_AGENT */: return "agent"; case 1 /* ROLE_USER */: return "user"; default: throw A2AError.invalidParams(`Invalid role: ${role}`); } } static messageSendConfiguration(configuration) { if (!configuration) { return void 0; } return { blocking: configuration.blocking, acceptedOutputModes: configuration.acceptedOutputModes, pushNotificationConfig: _FromProto.pushNotificationConfig(configuration.pushNotification) }; } static pushNotificationConfig(config) { if (!config) { return void 0; } return { id: config.id, url: config.url, token: config.token || void 0, authentication: _FromProto.pushNotificationAuthenticationInfo(config.authentication) }; } static pushNotificationAuthenticationInfo(authInfo) { if (!authInfo) { return void 0; } return { schemes: authInfo.schemes, credentials: authInfo.credentials }; } static part(part) { if (part.part?.$case === "text") { return { kind: "text", text: part.part.value }; } if (part.part?.$case === "file") { const filePart = part.part.value; if (filePart.file?.$case === "fileWithUri") { return { kind: "file", file: { uri: filePart.file.value, mimeType: filePart.mimeType } }; } else if (filePart.file?.$case === "fileWithBytes") { return { kind: "file", file: { bytes: filePart.file.value.toString("base64"), mimeType: filePart.mimeType } }; } throw A2AError.invalidParams("Invalid file part type"); } if (part.part?.$case === "data") { return { kind: "data", data: part.part.value.data }; } throw A2AError.invalidParams("Invalid part type"); } static messageSendParams(request) { return { message: _FromProto.message(request.request), configuration: _FromProto.messageSendConfiguration(request.configuration), metadata: request.metadata }; } static sendMessageResult(response) { if (response.payload?.$case === "task") { return _FromProto.task(response.payload.value); } else if (response.payload?.$case === "msg") { return _FromProto.message(response.payload.value); } throw A2AError.invalidParams("Invalid SendMessageResponse: missing result"); } static task(task) { return { kind: "task", id: task.id, status: _FromProto.taskStatus(task.status), contextId: task.contextId, artifacts: task.artifacts?.map((a) => _FromProto.artifact(a)), history: task.history?.map((h) => _FromProto.message(h)), metadata: task.metadata }; } static taskStatus(status) { return { message: _FromProto.message(status.update), state: _FromProto.taskState(status.state), timestamp: status.timestamp }; } static taskState(state) { switch (state) { case 1 /* TASK_STATE_SUBMITTED */: return "submitted"; case 2 /* TASK_STATE_WORKING */: return "working"; case 6 /* TASK_STATE_INPUT_REQUIRED */: return "input-required"; case 3 /* TASK_STATE_COMPLETED */: return "completed"; case 5 /* TASK_STATE_CANCELLED */: return "canceled"; case 4 /* TASK_STATE_FAILED */: return "failed"; case 7 /* TASK_STATE_REJECTED */: return "rejected"; case 8 /* TASK_STATE_AUTH_REQUIRED */: return "auth-required"; case 0 /* TASK_STATE_UNSPECIFIED */: return "unknown"; default: throw A2AError.invalidParams(`Invalid task state: ${state}`); } } static artifact(artifact) { return { artifactId: artifact.artifactId, name: artifact.name || void 0, description: artifact.description || void 0, parts: artifact.parts.map((p) => _FromProto.part(p)), metadata: artifact.metadata }; } static taskPushNotificationConfig(request) { return { taskId: extractTaskId(request.name), pushNotificationConfig: _FromProto.pushNotificationConfig(request.pushNotificationConfig) }; } static listTaskPushNotificationConfig(request) { return request.configs.map((c) => _FromProto.taskPushNotificationConfig(c)); } static agentCard(agentCard) { return { additionalInterfaces: agentCard.additionalInterfaces?.map((i) => _FromProto.agentInterface(i)), capabilities: agentCard.capabilities ? _FromProto.agentCapabilities(agentCard.capabilities) : {}, defaultInputModes: agentCard.defaultInputModes, defaultOutputModes: agentCard.defaultOutputModes, description: agentCard.description, documentationUrl: agentCard.documentationUrl || void 0, name: agentCard.name, preferredTransport: agentCard.preferredTransport, provider: agentCard.provider ? _FromProto.agentProvider(agentCard.provider) : void 0, protocolVersion: agentCard.protocolVersion, security: agentCard.security?.map((s) => _FromProto.security(s)), securitySchemes: agentCard.securitySchemes ? Object.fromEntries( Object.entries(agentCard.securitySchemes).map(([key, value]) => [ key, _FromProto.securityScheme(value) ]) ) : {}, skills: agentCard.skills.map((s) => _FromProto.skills(s)), signatures: agentCard.signatures?.map((s) => _FromProto.agentCardSignature(s)), supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard, url: agentCard.url, version: agentCard.version }; } static agentCapabilities(capabilities) { return { extensions: capabilities.extensions?.map((e) => _FromProto.agentExtension(e)), pushNotifications: capabilities.pushNotifications, streaming: capabilities.streaming }; } static agentExtension(extension) { return { uri: extension.uri, description: extension.description || void 0, required: extension.required, params: extension.params }; } static agentInterface(intf) { return { transport: intf.transport, url: intf.url }; } static agentProvider(provider) { return { organization: provider.organization, url: provider.url }; } static security(security) { return Object.fromEntries( Object.entries(security.schemes)?.map(([key, value]) => [key, value.list]) ); } static securityScheme(securitySchemes) { switch (securitySchemes.scheme?.$case) { case "apiKeySecurityScheme": return { type: "apiKey", name: securitySchemes.scheme.value.name, in: securitySchemes.scheme.value.location, description: securitySchemes.scheme.value.description || void 0 }; case "httpAuthSecurityScheme": return { type: "http", scheme: securitySchemes.scheme.value.scheme, bearerFormat: securitySchemes.scheme.value.bearerFormat || void 0, description: securitySchemes.scheme.value.description || void 0 }; case "mtlsSecurityScheme": return { type: "mutualTLS", description: securitySchemes.scheme.value.description || void 0 }; case "oauth2SecurityScheme": return { type: "oauth2", description: securitySchemes.scheme.value.description || void 0, flows: _FromProto.oauthFlows(securitySchemes.scheme.value.flows), oauth2MetadataUrl: securitySchemes.scheme.value.oauth2MetadataUrl || void 0 }; case "openIdConnectSecurityScheme": return { type: "openIdConnect", description: securitySchemes.scheme.value.description || void 0, openIdConnectUrl: securitySchemes.scheme.value.openIdConnectUrl }; default: throw A2AError.internalError(`Unsupported security scheme type`); } } static oauthFlows(flows) { switch (flows.flow?.$case) { case "implicit": return { implicit: { authorizationUrl: flows.flow.value.authorizationUrl, scopes: flows.flow.value.scopes, refreshUrl: flows.flow.value.refreshUrl || void 0 } }; case "password": return { password: { refreshUrl: flows.flow.value.refreshUrl || void 0, scopes: flows.flow.value.scopes, tokenUrl: flows.flow.value.tokenUrl } }; case "authorizationCode": return { authorizationCode: { refreshUrl: flows.flow.value.refreshUrl || void 0, authorizationUrl: flows.flow.value.authorizationUrl, scopes: flows.flow.value.scopes, tokenUrl: flows.flow.value.tokenUrl } }; case "clientCredentials": return { clientCredentials: { refreshUrl: flows.flow.value.refreshUrl || void 0, scopes: flows.flow.value.scopes, tokenUrl: flows.flow.value.tokenUrl } }; default: throw A2AError.internalError(`Unsupported OAuth flows`); } } static skills(skill) { return { id: skill.id, name: skill.name, description: skill.description, tags: skill.tags, examples: skill.examples, inputModes: skill.inputModes, outputModes: skill.outputModes, security: skill.security?.map((s) => _FromProto.security(s)) }; } static agentCardSignature(signatures) { return { protected: signatures.protected, signature: signatures.signature, header: signatures.header }; } static taskStatusUpdateEvent(event) { return { kind: "status-update", taskId: event.taskId, status: _FromProto.taskStatus(event.status), contextId: event.contextId, metadata: event.metadata, final: event.final }; } static taskArtifactUpdateEvent(event) { return { kind: "artifact-update", taskId: event.taskId, artifact: _FromProto.artifact(event.artifact), contextId: event.contextId, metadata: event.metadata, lastChunk: event.lastChunk }; } static messageStreamResult(event) { switch (event.payload?.$case) { case "msg": return _FromProto.message(event.payload.value); case "task": return _FromProto.task(event.payload.value); case "statusUpdate": return _FromProto.taskStatusUpdateEvent(event.payload.value); case "artifactUpdate": return _FromProto.taskArtifactUpdateEvent(event.payload.value); default: throw A2AError.internalError("Invalid event type in StreamResponse"); } } }; // src/types/converters/to_proto.ts var ToProto = class _ToProto { static agentCard(agentCard) { return { protocolVersion: agentCard.protocolVersion, name: agentCard.name, description: agentCard.description, url: agentCard.url, preferredTransport: agentCard.preferredTransport ?? "", additionalInterfaces: agentCard.additionalInterfaces?.map((i) => _ToProto.agentInterface(i)) ?? [], provider: _ToProto.agentProvider(agentCard.provider), version: agentCard.version, documentationUrl: agentCard.documentationUrl ?? "", capabilities: _ToProto.agentCapabilities(agentCard.capabilities), securitySchemes: agentCard.securitySchemes ? Object.fromEntries( Object.entries(agentCard.securitySchemes).map(([key, value]) => [ key, _ToProto.securityScheme(value) ]) ) : {}, security: agentCard.security?.map((s) => _ToProto.security(s)) ?? [], defaultInputModes: agentCard.defaultInputModes, defaultOutputModes: agentCard.defaultOutputModes, skills: agentCard.skills.map((s) => _ToProto.agentSkill(s)), supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard, signatures: agentCard.signatures?.map((s) => _ToProto.agentCardSignature(s)) ?? [] }; } static agentCardSignature(signatures) { return { protected: signatures.protected, signature: signatures.signature, header: signatures.header }; } static agentSkill(skill) { return { id: skill.id, name: skill.name, description: skill.description, tags: skill.tags ?? [], examples: skill.examples ?? [], inputModes: skill.inputModes ?? [], outputModes: skill.outputModes ?? [], security: skill.security ? skill.security.map((s) => _ToProto.security(s)) : [] }; } static security(security) { return { schemes: Object.fromEntries( Object.entries(security).map(([key, value]) => { return [key, { list: value }]; }) ) }; } static securityScheme(scheme) { switch (scheme.type) { case "apiKey": return { scheme: { $case: "apiKeySecurityScheme", value: { name: scheme.name, location: scheme.in, description: scheme.description ?? "" } } }; case "http": return { scheme: { $case: "httpAuthSecurityScheme", value: { description: scheme.description ?? "", scheme: scheme.scheme, bearerFormat: scheme.bearerFormat ?? "" } } }; case "mutualTLS": return { scheme: { $case: "mtlsSecurityScheme", value: { description: scheme.description ?? "" } } }; case "oauth2": return { scheme: { $case: "oauth2SecurityScheme", value: { description: scheme.description ?? "", flows: _ToProto.oauthFlows(scheme.flows), oauth2MetadataUrl: scheme.oauth2MetadataUrl ?? "" } } }; case "openIdConnect": return { scheme: { $case: "openIdConnectSecurityScheme", value: { description: scheme.description ?? "", openIdConnectUrl: scheme.openIdConnectUrl } } }; default: throw A2AError.internalError(`Unsupported security scheme type`); } } static oauthFlows(flows) { if (flows.implicit) { return { flow: { $case: "implicit", value: { authorizationUrl: flows.implicit.authorizationUrl, scopes: flows.implicit.scopes, refreshUrl: flows.implicit.refreshUrl ?? "" } } }; } else if (flows.password) { return { flow: { $case: "password", value: { tokenUrl: flows.password.tokenUrl, scopes: flows.password.scopes, refreshUrl: flows.password.refreshUrl ?? "" } } }; } else if (flows.clientCredentials) { return { flow: { $case: "clientCredentials", value: { tokenUrl: flows.clientCredentials.tokenUrl, scopes: flows.clientCredentials.scopes, refreshUrl: flows.clientCredentials.refreshUrl ?? "" } } }; } else if (flows.authorizationCode) { return { flow: { $case: "authorizationCode", value: { authorizationUrl: flows.authorizationCode.authorizationUrl, tokenUrl: flows.authorizationCode.tokenUrl, scopes: flows.authorizationCode.scopes, refreshUrl: flows.authorizationCode.refreshUrl ?? "" } } }; } else { throw A2AError.internalError(`Unsupported OAuth flows`); } } static agentInterface(agentInterface) { return { transport: agentInterface.transport, url: agentInterface.url }; } static agentProvider(agentProvider) { if (!agentProvider) { return void 0; } return { url: agentProvider.url, organization: agentProvider.organization }; } static agentCapabilities(capabilities) { return { streaming: capabilities.streaming, pushNotifications: capabilities.pushNotifications, extensions: capabilities.extensions ? capabilities.extensions.map((e) => _ToProto.agentExtension(e)) : [] }; } static agentExtension(extension) { return { uri: extension.uri, description: extension.description ?? "", required: extension.required ?? false, params: extension.params }; } static listTaskPushNotificationConfig(config) { return { configs: config.map((c) => _ToProto.taskPushNotificationConfig(c)), nextPageToken: "" }; } static getTaskPushNotificationConfigParams(config) { return { name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId) }; } static listTaskPushNotificationConfigParams(config) { return { parent: generateTaskName(config.id), pageToken: "", pageSize: 0 }; } static deleteTaskPushNotificationConfigParams(config) { return { name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId) }; } static taskPushNotificationConfig(config) { return { name: generatePushNotificationConfigName( config.taskId, config.pushNotificationConfig.id ?? "" ), pushNotificationConfig: _ToProto.pushNotificationConfig(config.pushNotificationConfig) }; } static taskPushNotificationConfigCreate(config) { return { parent: generateTaskName(config.taskId), config: _ToProto.taskPushNotificationConfig(config), configId: config.pushNotificationConfig.id }; } static pushNotificationConfig(config) { if (!config) { return void 0; } return { id: config.id ?? "", url: config.url, token: config.token ?? "", authentication: _ToProto.pushNotificationAuthenticationInfo(config.authentication) }; } static pushNotificationAuthenticationInfo(authInfo) { if (!authInfo) { return void 0; } return { schemes: authInfo.schemes, credentials: authInfo.credentials ?? "" }; } static messageStreamResult(event) { if (event.kind === "message") { return { payload: { $case: "msg", value: _ToProto.message(event) } }; } else if (event.kind === "task") { return { payload: { $case: "task", value: _ToProto.task(event) } }; } else if (event.kind === "status-update") { return { payload: { $case: "statusUpdate", value: _ToProto.taskStatusUpdateEvent(event) } }; } else if (event.kind === "artifact-update") { return { payload: { $case: "artifactUpdate", value: _ToProto.taskArtifactUpdateEvent(event) } }; } else { throw A2AError.internalError("Invalid event type"); } } static taskStatusUpdateEvent(event) { return { taskId: event.taskId, status: _ToProto.taskStatus(event.status), contextId: event.contextId, metadata: event.metadata, final: event.final }; } static taskArtifactUpdateEvent(event) { return { taskId: event.taskId, artifact: _ToProto.artifact(event.artifact), contextId: event.contextId, metadata: event.metadata, append: event.append, lastChunk: event.lastChunk }; } static messageSendResult(params) { if (params.kind === "message") { return { payload: { $case: "msg", value: _ToProto.message(params) } }; } else if (params.kind === "task") { return { payload: { $case: "task", value: _ToProto.task(params) } }; } } static message(message) { if (!message) { return void 0; } return { messageId: message.messageId, content: message.parts.map((p) => _ToProto.part(p)), contextId: message.contextId ?? "", taskId: message.taskId ?? "", role: _ToProto.role(message.role), metadata: message.metadata, extensions: message.extensions ?? [] }; } static role(role) { switch (role) { case "agent": return 2 /* ROLE_AGENT */; case "user": return 1 /* ROLE_USER */; default: throw A2AError.internalError(`Invalid role`); } } static task(task) { return { id: task.id, contextId: task.contextId, status: _ToProto.taskStatus(task.status), artifacts: task.artifacts?.map((a) => _ToProto.artifact(a)) ?? [], history: task.history?.map((m) => _ToProto.message(m)) ?? [], metadata: task.metadata }; } static taskStatus(status) { return { state: _ToProto.taskState(status.state), update: _ToProto.message(status.message), timestamp: status.timestamp }; } static artifact(artifact) { return { artifactId: artifact.artifactId, name: artifact.name ?? "", description: artifact.description ?? "", parts: artifact.parts.map((p) => _ToProto.part(p)), metadata: artifact.metadata, extensions: artifact.extensions ? artifact.extensions : [] }; } static taskState(state) { switch (state) { case "submitted": return 1 /* TASK_STATE_SUBMITTED */; case "working": return 2 /* TASK_STATE_WORKING */; case "input-required": return 6 /* TASK_STATE_INPUT_REQUIRED */; case "rejected": return 7 /* TASK_STATE_REJECTED */; case "auth-required": return 8 /* TASK_STATE_AUTH_REQUIRED */; case "completed": return 3 /* TASK_STATE_COMPLETED */; case "failed": return 4 /* TASK_STATE_FAILED */; case "canceled": return 5 /* TASK_STATE_CANCELLED */; case "unknown": return 0 /* TASK_STATE_UNSPECIFIED */; default: return -1 /* UNRECOGNIZED */; } } static part(part) { if (part.kind === "text") { return { part: { $case: "text", value: part.text } }; } if (part.kind === "file") { let filePart; if ("uri" in part.file) { filePart = { file: { $case: "fileWithUri", value: part.file.uri }, mimeType: part.file.mimeType }; } else if ("bytes" in part.file) { filePart = { file: { $case: "fileWithBytes", value: Buffer.from(part.file.bytes, "base64") }, mimeType: part.file.mimeType }; } else { throw A2AError.internalError("Invalid file part"); } return { part: { $case: "file", value: filePart } }; } if (part.kind === "data") { return { part: { $case: "data", value: { data: part.data } } }; } throw A2AError.internalError("Invalid part type"); } static messageSendParams(params) { return { request: _ToProto.message(params.message), configuration: _ToProto.configuration(params.configuration), metadata: params.metadata }; } static configuration(configuration) { if (!configuration) { return void 0; } return { blocking: configuration.blocking, acceptedOutputModes: configuration.acceptedOutputModes ?? [], pushNotification: _ToProto.pushNotificationConfig(configuration.pushNotificationConfig), historyLength: configuration.historyLength ?? 0 }; } static taskQueryParams(params) { return { name: generateTaskName(params.id), historyLength: params.historyLength ?? 0 }; } static cancelTaskRequest(params) { return { name: generateTaskName(params.id) }; } static taskIdParams(params) { return { name: generateTaskName(params.id) }; } static getAgentCardRequest() { return {}; } }; // src/server/express/rest_handler.ts var restErrorHandler = (err, _req, res, next) => { if (err instanceof SyntaxError && "body" in err) { const a2aError = A2AError.parseError("Invalid JSON payload."); return res.status(400).json(toHTTPError(a2aError)); } next(err); }; function restHandler(options) { const router = import_express4.default.Router(); const restTransportHandler = new RestTransportHandler(options.requestHandler); router.use(import_express4.default.json(), restErrorHandler); const buildContext = async (req) => { const user = await options.userBuilder(req); return new ServerCallContext( Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)), user ); }; const setExtensionsHeader = (res, context) => { if (context.activatedExtensions) { res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions)); } }; const sendResponse = (res, statusCode, context, body, responseType) => { setExtensionsHeader(res, context); res.status(statusCode); if (statusCode === HTTP_STATUS.NO_CONTENT) { res.end(); } else { if (!responseType || body === void 0) { throw new Error("Bug: toJson serializer and body must be provided for non-204 responses."); } res.json(responseType.toJSON(body)); } }; const sendStreamResponse = async (res, stream, context) => { const iterator = stream[Symbol.asyncIterator](); let firstResult; try { firstResult = await iterator.next(); } catch (error) { const a2aError = error instanceof A2AError ? error : A2AError.internalError(error instanceof Error ? error.message : "Streaming error"); const statusCode = mapErrorToStatus(a2aError.code); sendResponse(res, statusCode, context, toHTTPError(a2aError)); return; } Object.entries(SSE_HEADERS).forEach(([key, value]) => { res.setHeader(key, value); }); setExtensionsHeader(res, context); res.flushHeaders(); try { if (!firstResult.done) { const proto = ToProto.messageStreamResult(firstResult.value); const result = StreamResponse.toJSON(proto); res.write(formatSSEEvent(result)); } for await (const event of { [Symbol.asyncIterator]: () => iterator }) { const proto = ToProto.messageStreamResult(event); const result = StreamResponse.toJSON(proto); res.write(formatSSEEvent(result)); } } catch (streamError) { console.error("SSE streaming error:", streamError); const a2aError = streamError instanceof A2AError ? streamError : A2AError.internalError( streamError instanceof Error ? streamError.message : "Streaming error" ); if (!res.writableEnded) { res.write(formatSSEErrorEvent(toHTTPError(a2aError))); } } finally { if (!res.writableEnded) { res.end(); } } }; const handleError = (res, error) => { if (res.headersSent) { if (!res.writableEnded) { res.end(); } return; } const a2aError = error instanceof A2AError ? error : A2AError.internalError(error instanceof Error ? error.message : "Internal server error"); const statusCode = mapErrorToStatus(a2aError.code); res.status(statusCode).json(toHTTPError(a2aError)); }; const asyncHandler = (handler) => { return async (req, res) => { try { await handler(req, res); } catch (error) { handleError(res, error); } }; }; router.get( "/v1/card", asyncHandler(async (req, res) => { const context = await buildContext(req); const result = await restTransportHandler.getAuthenticatedExtendedAgentCard(context); const protoResult = ToProto.agentCard(result); sendResponse(res, HTTP_STATUS.OK, context, protoResult, AgentCard); }) ); router.post( "/v1/message\\:send", asyncHandler(async (req, res) => { const context = await buildContext(req); const protoReq = SendMessageRequest.fromJSON(req.body); const params = FromProto.messageSendParams(protoReq); const result = await restTransportHandler.sendMessage(params, context); const protoResult = ToProto.messageSendResult(result); sendResponse( res, HTTP_STATUS.CREATED, context, protoResult, SendMessageResponse ); }) ); router.post( "/v1/message\\:stream", asyncHandler(async (req, res) => { const context = await buildContext(req); const protoReq = SendMessageRequest.fromJSON(req.body); const params = FromProto.messageSendParams(protoReq); const stream = await restTransportHandler.sendMessageStream(params, context); await sendStreamResponse(res, stream, context); }) ); router.get( "/v1/tasks/:taskId", asyncHandler(async (req, res) => { const context = await buildContext(req); const result = await restTransportHandler.getTask( req.params.taskId, context, //TODO: clarify for version 1.0.0 the format of the historyLength query parameter, and if history should always be added to the returned object req.query.historyLength ?? req.query.history_length ); const protoResult = ToProto.task(result); sendResponse(res, HTTP_STATUS.OK, context, protoResult, Task); }) ); router.post( "/v1/tasks/:taskId\\:cancel", asyncHandler(async (req, res) => { const context = await buildContext(req); const result = await restTransportHandler.cancelTask(req.params.taskId, context); const protoResult = ToProto.task(result); sendResponse(res, HTTP_STATUS.ACCEPTED, context, protoResult, Task); }) ); router.post( "/v1/tasks/:taskId\\:subscribe", asyncHandler(async (req, res) => { const context = await buildContext(req); const stream = await restTransportHandler.resubscribe(req.params.taskId, context); await sendStreamResponse(res, stream, context); }) ); router.post( "/v1/tasks/:taskId/pushNotificationConfigs", asyncHandler(async (req, res) => { const context = await buildContext(req); const protoReq = CreateTaskPushNotificationConfigRequest.fromJSON(req.body); const params = FromProto.createTaskPushNotificationConfig(protoReq); const result = await restTransportHandler.setTaskPushNotificationConfig(params, context); const protoResult = ToProto.taskPushNotificationConfig(result); sendResponse( res, HTTP_STATUS.CREATED, context, protoResult, TaskPushNotificationConfig ); }) ); router.get( "/v1/tasks/:taskId/pushNotificationConfigs", asyncHandler(async (req, res) => { const context = await buildContext(req); const result = await restTransportHandler.listTaskPushNotificationConfigs( req.params.taskId, context ); const protoResult = ToProto.listTaskPushNotificationConfig(result); sendResponse( res, HTTP_STATUS.OK, context, protoResult, ListTaskPushNotificationConfigResponse ); }) ); router.get( "/v1/tasks/:taskId/pushNotificationConfigs/:configId", asyncHandler(async (req, res) => { const context = await buildContext(req); const result = await restTransportHandler.getTaskPushNotificationConfig( req.params.taskId, req.params.configId, context ); const protoResult = ToProto.taskPushNotificationConfig(result); sendResponse( res, HTTP_STATUS.OK, context, protoResult, TaskPushNotificationConfig ); }) ); router.delete( "/v1/tasks/:taskId/pushNotificationConfigs/:configId", asyncHandler(async (req, res) => { const context = await buildContext(req); await restTransportHandler.deleteTaskPushNotificationConfig( req.params.taskId, req.params.configId, context ); sendResponse(res, HTTP_STATUS.NO_CONTENT, context); }) ); return router; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { A2AExpressApp, UserBuilder, agentCardHandler, jsonRpcHandler, restHandler });