@agentium/transport 4.1.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ import type { A2AServerOptions } from "./types.cjs";
2
+ /**
3
+ * Mount an A2A-compliant server on an Express app.
4
+ *
5
+ * - Serves `/.well-known/agent.json` with the Agent Card
6
+ * - Handles JSON-RPC 2.0 requests at the basePath for message/send, message/stream, tasks/get, tasks/cancel
7
+ */
8
+ export declare function createA2AServer(app: any, opts: A2AServerOptions): void;
9
+ //# sourceMappingURL=a2a-server.d.ts.map
@@ -0,0 +1,17 @@
1
+ import type { A2AAgentCard, Agent } from "@agentium/core";
2
+ /**
3
+ * Generate an A2A Agent Card from a Agentium Agent.
4
+ * The card is served at /.well-known/agent.json per the A2A spec.
5
+ */
6
+ export declare function generateAgentCard(agent: Agent, serverUrl: string, provider?: {
7
+ organization: string;
8
+ url?: string;
9
+ }, version?: string): A2AAgentCard;
10
+ /**
11
+ * Generate a combined Agent Card that lists multiple agents as skills.
12
+ */
13
+ export declare function generateMultiAgentCard(agents: Record<string, Agent>, serverUrl: string, provider?: {
14
+ organization: string;
15
+ url?: string;
16
+ }, version?: string): A2AAgentCard;
17
+ //# sourceMappingURL=agent-card.d.ts.map
@@ -0,0 +1,17 @@
1
+ import type { DurableReader } from "@agentium/core";
2
+ import type { Request, Router } from "express";
3
+ import { type DurableProtocolHost } from "../durable/protocol-host.cjs";
4
+ export interface DurableA2AV1ServerOptions extends DurableProtocolHost {
5
+ name: string;
6
+ /** Absolute public JSON-RPC URL; mount the returned router at its origin. */
7
+ url: string;
8
+ audience: string;
9
+ authenticate(request: Request, audience: string): Promise<DurableReader | null>;
10
+ cardPath?: string;
11
+ /** Blocking SendMessage waits only this long; timeout does not cancel admitted work. */
12
+ waitTimeoutMs?: number;
13
+ pollIntervalMs?: number;
14
+ }
15
+ /** Optional A2A 1.0 JSON-RPC bridge. Polling only; all state remains in the durable store. */
16
+ export declare function createDurableA2AV1Server(options: DurableA2AV1ServerOptions): Promise<Router>;
17
+ //# sourceMappingURL=durable-v1-server.d.ts.map
@@ -0,0 +1,13 @@
1
+ import type { Agent } from "@agentium/core";
2
+ export interface A2AServerOptions {
3
+ agents: Record<string, Agent>;
4
+ basePath?: string;
5
+ provider?: {
6
+ organization: string;
7
+ url?: string;
8
+ };
9
+ version?: string;
10
+ /** Maximum process-local tasks, including active work. Default 10000. */
11
+ maxTasks?: number;
12
+ }
13
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,27 @@
1
+ import type { A2AV1Card, Agent, RunOutput } from "@agentium/core";
2
+ import type { Express, Request } from "express";
3
+ export interface A2AV1Identity {
4
+ tenantId: string;
5
+ userId: string;
6
+ }
7
+ export interface A2AV1ServerOptions {
8
+ agents: Record<string, Pick<Agent, "name" | "run">>;
9
+ /** Absolute URL of this JSON-RPC endpoint. */
10
+ url: string;
11
+ basePath?: string;
12
+ cardPath?: string;
13
+ /** Passed to the host verifier; the verifier must validate token audience. */
14
+ audience: string;
15
+ authenticate: (request: Request, audience: string) => Promise<A2AV1Identity | null>;
16
+ maxTasks?: number;
17
+ /** Local history retention and follow-up admission bound; default 128. */
18
+ maxHistoryMessages?: number;
19
+ /** Domain-specific interrupted results remain distinguishable from success. */
20
+ completionState?: (output: RunOutput) => "TASK_STATE_COMPLETED" | "TASK_STATE_INPUT_REQUIRED" | "TASK_STATE_AUTH_REQUIRED" | "TASK_STATE_FAILED";
21
+ }
22
+ /** A2A 1.0 JSON-RPC using the optional official SDK. Local task state is
23
+ * process-local and ownership-scoped; this adapter does not promise recovery. */
24
+ export declare function createA2AV1Server(app: Express, options: A2AV1ServerOptions): Promise<{
25
+ card: A2AV1Card;
26
+ }>;
27
+ //# sourceMappingURL=v1-server.d.ts.map
@@ -0,0 +1,56 @@
1
+ import type { DurableJSON, DurableReader, DurableTaskKey, DurableTaskRecord, DurableTaskSupervisor } from "@agentium/core";
2
+ export type DurableProtocolPart = {
3
+ text: string;
4
+ } | {
5
+ data: DurableJSON;
6
+ };
7
+ export type DurableProtocolAdmission = {
8
+ protocol: "a2a-1.0";
9
+ name: string;
10
+ messageId: string;
11
+ parts: DurableProtocolPart[];
12
+ } | {
13
+ protocol: "mcp-2026-07-28";
14
+ name: string;
15
+ arguments: Record<string, DurableJSON>;
16
+ };
17
+ export interface DurableProtocolApprovalResponse {
18
+ approvalId: string;
19
+ preparedHash: string;
20
+ approved: boolean;
21
+ }
22
+ export interface DurableProtocolOutput {
23
+ text?: string;
24
+ data?: DurableJSON;
25
+ /** A completed tool result can contain a domain error without becoming a protocol failure. */
26
+ isError?: boolean;
27
+ }
28
+ /** Trusted admission boundary; protocol payloads cannot select identity, policy or grants. */
29
+ export interface DurableProtocolHost {
30
+ supervisor: DurableTaskSupervisor;
31
+ /** Persist an owned task before returning. Mint/validate immutable refs and deduplicate message IDs here. */
32
+ admit(identity: DurableReader, input: DurableProtocolAdmission): Promise<DurableTaskKey>;
33
+ authorize(identity: DurableReader, task: Readonly<DurableTaskRecord>, operation: "read" | "cancel" | "input" | "wake"): Promise<boolean>;
34
+ /** Re-deliver a persisted task to its registered driver. Failure leaves it available for host recovery. */
35
+ wake(key: DurableTaskKey): Promise<unknown>;
36
+ /** Explicit trusted human-consent channel. Persist via DurableActionLedger.decide; never trust tool text. */
37
+ respond?(identity: DurableReader, task: Readonly<DurableTaskRecord>, response: DurableProtocolApprovalResponse): Promise<void>;
38
+ /** Return only authorized public output. Resolve artifacts through DurableRunRecords; no automatic URLs. */
39
+ output?(identity: DurableReader, task: Readonly<DurableTaskRecord>): Promise<DurableProtocolOutput>;
40
+ }
41
+ export declare class DurableProtocolError extends Error {
42
+ readonly code: "invalid" | "not-found" | "unsupported";
43
+ constructor(code: "invalid" | "not-found" | "unsupported", message: string);
44
+ }
45
+ export declare function protocolId(value: unknown): string;
46
+ /** Bounds both recursion and encoded size before host callbacks. Rejects unsafe/non-JSON values. */
47
+ export declare function protocolJSON(value: unknown, maxBytes?: number): DurableJSON;
48
+ export declare function protocolObject(value: unknown): Record<string, DurableJSON>;
49
+ export declare function assertProtocolHost(host: DurableProtocolHost): void;
50
+ export declare function ownedTask(host: DurableProtocolHost, identity: DurableReader, id: string, operation?: Parameters<DurableProtocolHost["authorize"]>[2]): Promise<DurableTaskRecord>;
51
+ export declare function wakeTask(host: DurableProtocolHost, identity: DurableReader, id: string): Promise<void>;
52
+ export declare function admitTask(host: DurableProtocolHost, identity: DurableReader, input: DurableProtocolAdmission): Promise<DurableTaskRecord>;
53
+ export declare function pendingApprovals(task: DurableTaskRecord, identity: DurableReader): import("@agentium/core").DurableApproval[];
54
+ export declare function respondToApproval(host: DurableProtocolHost, identity: DurableReader, taskId: string, response: DurableProtocolApprovalResponse): Promise<void>;
55
+ export declare function publicOutput(host: DurableProtocolHost, identity: DurableReader, task: DurableTaskRecord): Promise<DurableProtocolOutput>;
56
+ //# sourceMappingURL=protocol-host.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { MCPManager } from "./mcp-manager.cjs";
2
+ export interface AdminRouterOptions {
3
+ /** Shared MCPManager instance. If omitted, a new one is created. */
4
+ mcpManager?: MCPManager;
5
+ /**
6
+ * Express middleware for authentication/authorization.
7
+ * **IMPORTANT**: These endpoints can add MCP servers and execute tools.
8
+ * Always add auth middleware in production.
9
+ */
10
+ middleware?: any[];
11
+ }
12
+ /**
13
+ * Creates an Express sub-router with admin endpoints for managing
14
+ * MCP servers and the toolkit catalog at runtime.
15
+ *
16
+ * Mount under a prefix: `app.use("/admin", createAdminRouter())`
17
+ *
18
+ * Routes:
19
+ * GET /mcp — list MCP servers
20
+ * POST /mcp — add + connect an MCP server
21
+ * GET /mcp/:id — single server details
22
+ * POST /mcp/:id/connect — connect a server
23
+ * POST /mcp/:id/disconnect — disconnect
24
+ * DELETE /mcp/:id — remove a server
25
+ * GET /mcp/:id/tools — tools from a specific server
26
+ * GET /mcp/tools — all tools across connected servers
27
+ *
28
+ * GET /toolkits — list toolkit catalog
29
+ * GET /toolkits/:id — single toolkit meta
30
+ * POST /toolkits/:id — instantiate a toolkit with config
31
+ */
32
+ export declare function createAdminRouter(opts?: AdminRouterOptions): {
33
+ router: any;
34
+ mcpManager: MCPManager;
35
+ };
36
+ //# sourceMappingURL=admin-router.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { type DurableReader, type DurableRunRecords, type DurableTaskKey, type DurableTaskRecord, type DurableTaskSupervisor } from "@agentium/core";
2
+ import type { Request, Router } from "express";
3
+ export interface DurableTaskRouterOptions {
4
+ supervisor: DurableTaskSupervisor;
5
+ records: DurableRunRecords;
6
+ /** Verify credentials/audience. Returned identity must never come from body/query claims. */
7
+ authenticate: (request: Request) => Promise<DurableReader | null>;
8
+ /** Recheck current host policy/grants on every request, including event reconnections. */
9
+ authorize: (identity: DurableReader, task: Readonly<DurableTaskRecord>, operation: "read" | "cancel") => Promise<boolean>;
10
+ /** Re-deliver cancellation to a worker. Cancellation remains persisted if Redis is unavailable. */
11
+ wake: (key: DurableTaskKey) => Promise<unknown>;
12
+ }
13
+ /** Authenticated control and bounded replay for tasks already admitted by the host.
14
+ * Event responses close after the retained batch; reconnect with Last-Event-ID.
15
+ * This is an Agentium endpoint, not an A2A or MCP wire-protocol endpoint.
16
+ */
17
+ export declare function createDurableTaskRouter(options: DurableTaskRouterOptions): Router;
18
+ //# sourceMappingURL=durable-router.d.ts.map
@@ -0,0 +1,11 @@
1
+ export interface FileUploadOptions {
2
+ maxFileSize?: number;
3
+ maxFiles?: number;
4
+ maxFields?: number;
5
+ maxFieldSize?: number;
6
+ allowedMimeTypes?: string[];
7
+ }
8
+ export declare function createFileUploadMiddleware(opts?: FileUploadOptions): (req: any, res: any, next: (error?: unknown) => void) => void;
9
+ export declare function filesToContentParts(files: any[]): any[];
10
+ export declare function buildMultiModalInput(body: any, files?: any[]): string | any[];
11
+ //# sourceMappingURL=file-upload.d.ts.map
@@ -0,0 +1,16 @@
1
+ import type { RouterOptions } from "./types.cjs";
2
+ export interface RemoteEndpoint {
3
+ baseUrl: string;
4
+ agents?: string[];
5
+ teams?: string[];
6
+ workflows?: string[];
7
+ headers?: Record<string, string>;
8
+ healthPath?: string;
9
+ }
10
+ export interface GatewayConfig {
11
+ locals?: RouterOptions;
12
+ remotes: RemoteEndpoint[];
13
+ healthCheckIntervalMs?: number;
14
+ }
15
+ export declare function createGatewayRouter(config: GatewayConfig): any;
16
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1,10 @@
1
+ export interface JwtConfig {
2
+ secret: string;
3
+ algorithm?: string;
4
+ issuer?: string;
5
+ audience?: string;
6
+ extractFrom?: "header" | "cookie";
7
+ cookieName?: string;
8
+ }
9
+ export declare function createJwtMiddleware(config: JwtConfig): (req: any, res: any, next: any) => any;
10
+ //# sourceMappingURL=jwt-middleware.d.ts.map
@@ -0,0 +1,52 @@
1
+ import type { MCPToolProviderConfig, ToolDef } from "@agentium/core";
2
+ import { MCPToolProvider } from "@agentium/core";
3
+ export interface MCPServerEntry {
4
+ id: string;
5
+ config: MCPToolProviderConfig;
6
+ provider: MCPToolProvider;
7
+ status: "disconnected" | "connecting" | "connected" | "error";
8
+ error?: string;
9
+ toolCount: number;
10
+ connectedAt?: Date;
11
+ }
12
+ export interface MCPServerSummary {
13
+ id: string;
14
+ name: string;
15
+ transport: string;
16
+ url?: string;
17
+ command?: string;
18
+ status: string;
19
+ toolCount: number;
20
+ error?: string;
21
+ connectedAt?: string;
22
+ }
23
+ /**
24
+ * Manages multiple MCP server connections at runtime.
25
+ * Servers can be added/removed/connected/disconnected dynamically,
26
+ * and their tools can be collected for injection into agents.
27
+ */
28
+ export declare class MCPManager {
29
+ private servers;
30
+ /** Add a server config. Auto-generates an id from the name if not provided. */
31
+ add(config: MCPToolProviderConfig, id?: string): MCPServerSummary;
32
+ /** Connect a server by id. Discovers tools on success. */
33
+ connect(id: string): Promise<MCPServerSummary>;
34
+ /** Disconnect a server by id. */
35
+ disconnect(id: string): Promise<MCPServerSummary>;
36
+ /** Remove a server entirely. Disconnects first if connected. */
37
+ remove(id: string): Promise<void>;
38
+ /** Get all tools from all connected servers, merged into one array. */
39
+ getAllTools(): Promise<ToolDef[]>;
40
+ /** Get tools from a specific server. */
41
+ getTools(id: string): Promise<ToolDef[]>;
42
+ /** List all registered servers. */
43
+ list(): MCPServerSummary[];
44
+ /** Get a single server summary. */
45
+ get(id: string): MCPServerSummary;
46
+ has(id: string): boolean;
47
+ /** Disconnect all servers. */
48
+ closeAll(): Promise<void>;
49
+ private getEntry;
50
+ private summarize;
51
+ }
52
+ //# sourceMappingURL=mcp-manager.d.ts.map
@@ -0,0 +1,7 @@
1
+ export declare function errorHandler(options?: {
2
+ logger?: Pick<Console, "error">;
3
+ }): (err: any, _req: any, res: any, _next: any) => void;
4
+ export declare function requestLogger(options?: {
5
+ logger?: Pick<Console, "log">;
6
+ }): (req: any, _res: any, next: any) => void;
7
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1,11 @@
1
+ export interface RbacConfig {
2
+ scopeField?: string;
3
+ /** Override an exact route pattern. Empty scopes explicitly permit authenticated access. */
4
+ defaultScopes?: Record<string, string[]>;
5
+ agentScopes?: Record<string, string[]>;
6
+ /** Explicit routes accessible without authentication. Use only for intentionally public endpoints. */
7
+ publicRoutes?: string[];
8
+ }
9
+ export declare function routeMatches(actual: string, pattern: string): boolean;
10
+ export declare function createRbacMiddleware(config?: RbacConfig): (req: any, res: any, next: any) => any;
11
+ //# sourceMappingURL=rbac-middleware.d.ts.map
@@ -0,0 +1,3 @@
1
+ import type { RouterOptions } from "./types.cjs";
2
+ export declare function createAgentRouter(opts: RouterOptions): any;
3
+ //# sourceMappingURL=router-factory.d.ts.map
@@ -0,0 +1,30 @@
1
+ import type { RouterOptions, SwaggerOptions } from "./types.cjs";
2
+ interface OpenAPISpec {
3
+ openapi: string;
4
+ info: {
5
+ title: string;
6
+ description: string;
7
+ version: string;
8
+ };
9
+ servers?: Array<{
10
+ url: string;
11
+ description?: string;
12
+ }>;
13
+ paths: Record<string, Record<string, unknown>>;
14
+ components: {
15
+ schemas: Record<string, unknown>;
16
+ securitySchemes?: Record<string, unknown>;
17
+ };
18
+ security?: Array<Record<string, string[]>>;
19
+ tags: Array<{
20
+ name: string;
21
+ description: string;
22
+ }>;
23
+ }
24
+ export declare function generateOpenAPISpec(routerOpts: RouterOptions, swaggerOpts?: SwaggerOptions): OpenAPISpec;
25
+ export declare function serveSwaggerUI(spec: OpenAPISpec): {
26
+ setup: any;
27
+ serve: any;
28
+ };
29
+ export {};
30
+ //# sourceMappingURL=swagger.d.ts.map
@@ -0,0 +1,125 @@
1
+ import type { Agent, Registry, Servable, ServableAgent, Team, ToolDef, Toolkit, Workflow } from "@agentium/core";
2
+ import type { FileUploadOptions } from "./file-upload.cjs";
3
+ import type { MCPManager } from "./mcp-manager.cjs";
4
+ export interface SwaggerOptions {
5
+ /** Enable Swagger UI at /docs. Default: false */
6
+ enabled?: boolean;
7
+ /** API title shown in Swagger UI */
8
+ title?: string;
9
+ /** API description shown in Swagger UI */
10
+ description?: string;
11
+ /** API version string */
12
+ version?: string;
13
+ /** Route prefix used in path generation (e.g. "/api") */
14
+ routePrefix?: string;
15
+ /** Server URLs for the spec */
16
+ servers?: Array<{
17
+ url: string;
18
+ description?: string;
19
+ }>;
20
+ /** Path to serve Swagger UI. Default: "/docs" */
21
+ docsPath?: string;
22
+ /** Path to serve the raw OpenAPI JSON spec. Default: "/docs/spec.json" */
23
+ specPath?: string;
24
+ }
25
+ /** Identity derived only from credentials verified by host middleware or JWT. */
26
+ export interface HostedIdentity {
27
+ userId: string;
28
+ tenantId?: string;
29
+ }
30
+ export interface HostedResourceRequest {
31
+ identity: Readonly<HostedIdentity>;
32
+ operation: string;
33
+ resource: {
34
+ kind: "session" | "run" | "approval" | "checkpoint" | "correction" | "schedule" | "admin";
35
+ id?: string;
36
+ agentName?: string;
37
+ /** Requested correction visibility, for host policy evaluation. */
38
+ scope?: string;
39
+ };
40
+ }
41
+ export type HostedSecurityOptions = {
42
+ mode: "local";
43
+ } | {
44
+ mode: "authenticated";
45
+ /** Receives req.user after trusted middleware/JWT verification; never the request body. */
46
+ resolveIdentity: (verifiedClaims: unknown) => HostedIdentity | null | Promise<HostedIdentity | null>;
47
+ /**
48
+ * Check authoritative owner records. Unknown/ownerless records MUST return false.
49
+ * session:create MUST atomically bind this new opaque ID to identity before returning true.
50
+ * Collection operations grant access to the entire collection; deny when that is inappropriate.
51
+ * Scopes (including admin:*) never bypass this authorization.
52
+ */
53
+ authorizeResource: (request: HostedResourceRequest) => boolean | Promise<boolean>;
54
+ };
55
+ export interface RouterOptions {
56
+ /** Required explicit boundary. JWT/RBAC require authenticated mode and both host hooks. */
57
+ security: HostedSecurityOptions;
58
+ /**
59
+ * Use a Registry for live auto-discovery. The router creates dynamic routes
60
+ * that resolve agents/teams/workflows at request time — any instance created
61
+ * after the router is mounted is automatically available.
62
+ *
63
+ * When omitted, falls back to the global registry from `@agentium/core`.
64
+ * Pass `false` to disable registry-based routing entirely (use explicit maps only).
65
+ *
66
+ * @example
67
+ * createAgentRouter({ security: { mode: "local" }, cors: true });
68
+ * new Agent({ name: "bot", model: openai("gpt-4o") }); // immediately routable
69
+ */
70
+ registry?: Registry | false;
71
+ /**
72
+ * Auto-discover agents, teams, and workflows from a mixed array.
73
+ * Each item is classified by its `.kind` and keyed by `.name`.
74
+ */
75
+ serve?: Servable[];
76
+ agents?: Record<string, Agent | ServableAgent>;
77
+ teams?: Record<string, Team>;
78
+ workflows?: Record<string, Workflow<any>>;
79
+ middleware?: any[];
80
+ /** Swagger / OpenAPI configuration */
81
+ swagger?: SwaggerOptions;
82
+ /** Connection-owned text response limits. */
83
+ textStream?: import("../text-stream.cjs").TextStreamLimits;
84
+ /** File upload configuration for multi-modal inputs */
85
+ fileUpload?: boolean | FileUploadOptions;
86
+ /** CORS configuration. Pass true or '*' for permissive, a string for a single origin, or an array for multiple origins. */
87
+ cors?: string | string[] | boolean;
88
+ /** Rate limiting configuration. Pass true for defaults (100 req/min), or an object to customize. */
89
+ rateLimit?: {
90
+ windowMs?: number;
91
+ max?: number;
92
+ } | boolean;
93
+ /** Named tool library exposed via GET /tools. Tools from toolkits are auto-collected. */
94
+ toolLibrary?: Record<string, ToolDef>;
95
+ /** Toolkit instances whose tools are exposed via GET /tools. Merged with toolLibrary. */
96
+ toolkits?: Toolkit[];
97
+ /**
98
+ * Enable admin routes under `/admin` for managing MCP servers and the toolkit catalog.
99
+ * Pass `true` to use defaults, or provide an MCPManager instance to share state.
100
+ */
101
+ admin?: boolean | {
102
+ mcpManager?: MCPManager;
103
+ middleware?: any[];
104
+ };
105
+ /**
106
+ * Enable schedule management routes under `/schedules`.
107
+ * Pass an AgentQueue instance from `@agentium/queue`.
108
+ */
109
+ scheduler?: any;
110
+ /**
111
+ * MetricsExporter instance from `@agentium/observability` for `/metrics` endpoints.
112
+ */
113
+ metricsExporter?: any;
114
+ /**
115
+ * JWT authentication middleware. Verifies tokens and attaches decoded payload to `req.user`.
116
+ * Requires `jsonwebtoken` package.
117
+ */
118
+ jwt?: import("./jwt-middleware.cjs").JwtConfig;
119
+ /**
120
+ * Role-based access control. Checks `req.user.scopes` against required scopes per route.
121
+ * Requires `jwt` to be configured first.
122
+ */
123
+ rbac?: import("./rbac-middleware.cjs").RbacConfig;
124
+ }
125
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,78 @@
1
+ import type { Agent } from "@agentium/core";
2
+ /**
3
+ * Vercel AI SDK UI Message Stream adapter.
4
+ *
5
+ * Converts the chunks emitted by `agent.stream(...)` into the line-delimited
6
+ * JSON protocol consumed by Vercel's `useChat` / `createAgentUIStreamResponse`.
7
+ *
8
+ * Spec: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol
9
+ */
10
+ export interface AgentUIStreamOptions {
11
+ /** sessionId forwarded to `agent.run` / `agent.stream`. */
12
+ sessionId?: string;
13
+ /** userId forwarded to `agent.run` / `agent.stream`. */
14
+ userId?: string;
15
+ /** Optional per-request API key override. */
16
+ apiKey?: string;
17
+ /** Optional abort signal to cancel the run. */
18
+ signal?: AbortSignal;
19
+ }
20
+ interface AgentLikeChunk {
21
+ type?: string;
22
+ text?: string;
23
+ delta?: string;
24
+ toolCallId?: string;
25
+ toolName?: string;
26
+ arguments?: unknown;
27
+ args?: unknown;
28
+ input?: unknown;
29
+ output?: unknown;
30
+ result?: unknown;
31
+ finishReason?: string;
32
+ usage?: {
33
+ promptTokens?: number;
34
+ completionTokens?: number;
35
+ totalTokens?: number;
36
+ };
37
+ error?: string | {
38
+ message?: string;
39
+ };
40
+ reasoning?: string;
41
+ thinking?: string;
42
+ }
43
+ interface AgentLike {
44
+ stream(input: string, opts?: {
45
+ sessionId?: string;
46
+ userId?: string;
47
+ apiKey?: string;
48
+ signal?: AbortSignal;
49
+ }): AsyncIterable<AgentLikeChunk>;
50
+ }
51
+ /**
52
+ * Render an `agent.stream()` source as a Vercel-compatible UI message stream.
53
+ *
54
+ * The returned `ReadableStream<Uint8Array>` can be wrapped in a `Response`
55
+ * (web / edge / fetch) or piped to a Node `ServerResponse`.
56
+ */
57
+ export declare function agentUIStream(agent: Agent | AgentLike, input: string, options?: AgentUIStreamOptions): ReadableStream<Uint8Array>;
58
+ /**
59
+ * Create a `Response` whose body streams Vercel UI messages. Use as the return
60
+ * value of a Web / Edge / Next.js Route Handler.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * import { createAgentUIStreamResponse } from "@agentium/transport";
65
+ *
66
+ * export async function POST(req: Request) {
67
+ * const { input, sessionId } = await req.json();
68
+ * return createAgentUIStreamResponse(agent, input, { sessionId });
69
+ * }
70
+ * ```
71
+ */
72
+ export declare function createAgentUIStreamResponse(agent: Agent | AgentLike, input: string, options?: AgentUIStreamOptions): Response;
73
+ /**
74
+ * Pipe a Vercel UI message stream into a Node `ServerResponse` (Express style).
75
+ */
76
+ export declare function pipeAgentUIStreamToResponse(agent: Agent | AgentLike, input: string, res: any, options?: AgentUIStreamOptions): Promise<void>;
77
+ export {};
78
+ //# sourceMappingURL=ui-stream.d.ts.map
@@ -0,0 +1,42 @@
1
+ export { createA2AServer } from "./a2a/a2a-server.cjs";
2
+ export { generateAgentCard, generateMultiAgentCard } from "./a2a/agent-card.cjs";
3
+ export type { DurableA2AV1ServerOptions } from "./a2a/durable-v1-server.cjs";
4
+ export { createDurableA2AV1Server } from "./a2a/durable-v1-server.cjs";
5
+ export type { A2AServerOptions } from "./a2a/types.cjs";
6
+ export type { A2AV1Identity, A2AV1ServerOptions } from "./a2a/v1-server.cjs";
7
+ export { createA2AV1Server } from "./a2a/v1-server.cjs";
8
+ export type { DurableProtocolAdmission, DurableProtocolApprovalResponse, DurableProtocolHost, DurableProtocolOutput, DurableProtocolPart, } from "./durable/protocol-host.cjs";
9
+ export type { AdminRouterOptions } from "./express/admin-router.cjs";
10
+ export { createAdminRouter } from "./express/admin-router.cjs";
11
+ export type { DurableTaskRouterOptions } from "./express/durable-router.cjs";
12
+ export { createDurableTaskRouter } from "./express/durable-router.cjs";
13
+ export type { FileUploadOptions } from "./express/file-upload.cjs";
14
+ export { buildMultiModalInput, createFileUploadMiddleware } from "./express/file-upload.cjs";
15
+ export type { GatewayConfig, RemoteEndpoint } from "./express/gateway.cjs";
16
+ export { createGatewayRouter } from "./express/gateway.cjs";
17
+ export type { JwtConfig } from "./express/jwt-middleware.cjs";
18
+ export { createJwtMiddleware } from "./express/jwt-middleware.cjs";
19
+ export type { MCPServerEntry, MCPServerSummary } from "./express/mcp-manager.cjs";
20
+ export { MCPManager } from "./express/mcp-manager.cjs";
21
+ export { errorHandler, requestLogger } from "./express/middleware.cjs";
22
+ export type { RbacConfig } from "./express/rbac-middleware.cjs";
23
+ export { createRbacMiddleware } from "./express/rbac-middleware.cjs";
24
+ export { createAgentRouter } from "./express/router-factory.cjs";
25
+ export { generateOpenAPISpec } from "./express/swagger.cjs";
26
+ export type { HostedIdentity, HostedResourceRequest, HostedSecurityOptions, RouterOptions, SwaggerOptions, } from "./express/types.cjs";
27
+ export type { AgentUIStreamOptions } from "./express/ui-stream.cjs";
28
+ export { agentUIStream, createAgentUIStreamResponse, pipeAgentUIStreamToResponse } from "./express/ui-stream.cjs";
29
+ export type { DurableMCPTaskHandler, DurableMCPTaskHandlerOptions, DurableMCPTaskTool, } from "./mcp/durable-task-handler.cjs";
30
+ export { createDurableMCPTaskHandler } from "./mcp/durable-task-handler.cjs";
31
+ export type { BrowserGatewayOptions } from "./socketio/browser-gateway.cjs";
32
+ export { createBrowserGateway } from "./socketio/browser-gateway.cjs";
33
+ export { createAgentGateway } from "./socketio/gateway.cjs";
34
+ export type { GatewayOptions, GatewayResourceRequest, GatewaySecurityOptions } from "./socketio/types.cjs";
35
+ export type { VisionGatewayOptions } from "./socketio/vision-gateway.cjs";
36
+ export { createVisionGateway } from "./socketio/vision-gateway.cjs";
37
+ export type { VoiceGatewayOptions } from "./socketio/voice-gateway.cjs";
38
+ export { createVoiceGateway } from "./socketio/voice-gateway.cjs";
39
+ export type { InMemoryEventLogConfig, SSEEvent, SSEEventLog } from "./sse-event-log.cjs";
40
+ export { defaultEventLog, formatSSEEvent, InMemoryEventLog } from "./sse-event-log.cjs";
41
+ export type { TextStreamLimits } from "./text-stream.cjs";
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,24 @@
1
+ import type { DurableReader } from "@agentium/core";
2
+ import { type DurableProtocolHost } from "../durable/protocol-host.cjs";
3
+ export interface DurableMCPTaskTool {
4
+ name: string;
5
+ description?: string;
6
+ inputSchema: Record<string, unknown>;
7
+ }
8
+ export interface DurableMCPTaskHandlerOptions extends DurableProtocolHost {
9
+ name: string;
10
+ audience: string;
11
+ authenticate(request: Request, audience: string): Promise<DurableReader | null>;
12
+ tools: readonly DurableMCPTaskTool[];
13
+ pollIntervalMs?: number;
14
+ }
15
+ export interface DurableMCPTaskHandler {
16
+ fetch(request: Request): Promise<Response>;
17
+ close(): Promise<void>;
18
+ }
19
+ /** Pinned modern HTTP/Tasks extension adapter. SDK handles discovery/schema framing;
20
+ * task extension methods are explicitly implemented here, not by the base SDK.
21
+ * The modern protocol negotiates capabilities in each validated request envelope.
22
+ */
23
+ export declare function createDurableMCPTaskHandler(options: DurableMCPTaskHandlerOptions): Promise<DurableMCPTaskHandler>;
24
+ //# sourceMappingURL=durable-task-handler.d.ts.map
@@ -0,0 +1,62 @@
1
+ import type { EventBus } from "@agentium/core";
2
+ /**
3
+ * Minimal interface for a BrowserAgent — avoids a hard dependency on @agentium/browser.
4
+ * Any object that matches this shape (e.g. a real BrowserAgent) works.
5
+ */
6
+ interface BrowserAgentLike {
7
+ name: string;
8
+ eventBus: EventBus;
9
+ run(task: string, opts?: {
10
+ startUrl?: string;
11
+ apiKey?: string;
12
+ sessionId?: string;
13
+ }): Promise<{
14
+ result: string;
15
+ success: boolean;
16
+ finalUrl: string;
17
+ durationMs: number;
18
+ videoPath?: string;
19
+ steps: Array<{
20
+ index: number;
21
+ action: unknown;
22
+ screenshot: Buffer;
23
+ pageUrl: string;
24
+ pageTitle: string;
25
+ dom?: string;
26
+ }>;
27
+ }>;
28
+ }
29
+ export interface BrowserGatewayOptions {
30
+ /** Named BrowserAgent instances. Clients select one via agentName. */
31
+ agents: Record<string, BrowserAgentLike>;
32
+ /** Socket.IO server instance */
33
+ io: any;
34
+ /** Socket.IO namespace. Default: "/agentium-browser" */
35
+ namespace?: string;
36
+ /** Optional auth middleware applied to the namespace */
37
+ authMiddleware?: (socket: any, next: (err?: Error) => void) => void;
38
+ /**
39
+ * Stream screenshots to the client in real-time.
40
+ * Default: true. Disable for bandwidth-constrained clients.
41
+ */
42
+ streamScreenshots?: boolean;
43
+ }
44
+ /**
45
+ * Create a Socket.IO gateway that streams BrowserAgent execution in real-time.
46
+ *
47
+ * ## Client → Server events
48
+ * - `browser.start` — kick off a browser task
49
+ * - `browser.stop` — cancel a running task
50
+ *
51
+ * ## Server → Client events
52
+ * - `browser.started` — task accepted
53
+ * - `browser.screenshot` — live screenshot (base64 PNG)
54
+ * - `browser.action` — action about to execute
55
+ * - `browser.step` — full step with screenshot + DOM
56
+ * - `browser.done` — task finished (result, success, duration, video)
57
+ * - `browser.error` — error occurred
58
+ * - `browser.stopped` — task was cancelled
59
+ */
60
+ export declare function createBrowserGateway(opts: BrowserGatewayOptions): void;
61
+ export {};
62
+ //# sourceMappingURL=browser-gateway.d.ts.map
@@ -0,0 +1,3 @@
1
+ import type { GatewayOptions } from "./types.cjs";
2
+ export declare function createAgentGateway(options: GatewayOptions): void;
3
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1,2 @@
1
+ export { createAgentGateway } from "./gateway.cjs";
2
+ //# sourceMappingURL=handlers.d.ts.map
@@ -0,0 +1,58 @@
1
+ import type { Agent, Registry, Servable, ServableAgent, Team, ToolDef, Toolkit } from "@agentium/core";
2
+ export interface GatewayResourceRequest {
3
+ identity: Readonly<import("../express/types.cjs").HostedIdentity>;
4
+ operation: "discover" | "execute" | "session:create" | "session:use" | "run:cancel";
5
+ resource: {
6
+ kind: "agent" | "team" | "workflow" | "tool" | "session" | "run";
7
+ id: string;
8
+ target?: string;
9
+ };
10
+ }
11
+ export type GatewaySecurityOptions = {
12
+ mode: "local";
13
+ } | {
14
+ mode: "authenticated";
15
+ /** Read only host-verified socket.data, never handshake payload claims. */
16
+ resolveIdentity: (verifiedState: unknown) => import("../express/types.cjs").HostedIdentity | null | Promise<import("../express/types.cjs").HostedIdentity | null>;
17
+ /** session:create must atomically bind the generated ID; deny unknown session:use. */
18
+ authorizeResource: (request: GatewayResourceRequest) => boolean | Promise<boolean>;
19
+ };
20
+ export interface GatewayOptions {
21
+ security: GatewaySecurityOptions;
22
+ /** Bounds apply per socket; outgoing frames use the Engine.IO drain contract. */
23
+ textStream?: import("../text-stream.cjs").TextStreamLimits;
24
+ maxConcurrentRuns?: number;
25
+ /** Maximum collected final Agent text bytes. Default 256 KiB. */
26
+ maxOutputBytes?: number;
27
+ /**
28
+ * Use a Registry for live auto-discovery. The gateway resolves agents/teams
29
+ * at event time — any instance created after the gateway starts is automatically
30
+ * reachable.
31
+ *
32
+ * When omitted, falls back to the global registry from `@agentium/core`.
33
+ * Pass `false` to disable registry-based lookup (use explicit maps only).
34
+ *
35
+ * @example
36
+ * createAgentGateway({ io, security: { mode: "local" } });
37
+ * new Agent({ name: "bot", model: openai("gpt-4o") }); // immediately reachable
38
+ */
39
+ registry?: Registry | false;
40
+ /**
41
+ * Auto-discover agents and teams from a mixed array.
42
+ * Each item is classified by its `.kind` and keyed by `.name`.
43
+ */
44
+ serve?: Servable[];
45
+ agents?: Record<string, Agent | ServableAgent>;
46
+ teams?: Record<string, Team>;
47
+ io: any;
48
+ namespace?: string;
49
+ /** Must call next; thrown/rejected errors deny access. Returned promises settle before admission. */
50
+ authMiddleware?: (socket: any, next: (err?: Error) => void) => void | Promise<void>;
51
+ /** Max requests per minute per socket. Default: 60 */
52
+ maxRequestsPerMinute?: number;
53
+ /** Named tool library exposed via tools.list event. */
54
+ toolLibrary?: Record<string, ToolDef>;
55
+ /** Toolkit instances whose tools are exposed via tools.list. Merged with toolLibrary. */
56
+ toolkits?: Toolkit[];
57
+ }
58
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,9 @@
1
+ import type { VisionAgent } from "@agentium/core";
2
+ export interface VisionGatewayOptions {
3
+ agents: Record<string, VisionAgent>;
4
+ io: any;
5
+ namespace?: string;
6
+ authMiddleware?: (socket: any, next: (err?: Error) => void) => void;
7
+ }
8
+ export declare function createVisionGateway(opts: VisionGatewayOptions): void;
9
+ //# sourceMappingURL=vision-gateway.d.ts.map
@@ -0,0 +1,14 @@
1
+ import type { VoiceAgent } from "@agentium/core";
2
+ export interface VoiceGatewayOptions {
3
+ agents: Record<string, VoiceAgent>;
4
+ io: any;
5
+ namespace?: string;
6
+ /** Establish trusted identity in socket.data.auth {userId,tenantId,sessionId}. */
7
+ authMiddleware?: (socket: any, next: (err?: Error) => void) => void;
8
+ maxAudioFrameBytes?: number;
9
+ maxPendingAudioBytes?: number;
10
+ playbackAckTimeoutMs?: number;
11
+ }
12
+ /** Bounded per-connection audio delivery; each output frame must be acknowledged by the client. */
13
+ export declare function createVoiceGateway(opts: VoiceGatewayOptions): void;
14
+ //# sourceMappingURL=voice-gateway.d.ts.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Per-run in-memory ring buffer of SSE events. Each event gets a monotonically
3
+ * increasing numeric `id` so clients can pass `Last-Event-ID` on reconnect and
4
+ * replay missed events.
5
+ *
6
+ * Storage is intentionally in-process; for multi-instance deployments, plug a
7
+ * Redis-backed implementation behind the same interface.
8
+ */
9
+ export interface SSEEvent {
10
+ /** Monotonic numeric ID. */
11
+ id: number;
12
+ /** Optional `event:` line value. Default omitted. */
13
+ event?: string;
14
+ /** Payload (will be JSON-stringified into the `data:` field). */
15
+ payload: unknown;
16
+ /** Wall-clock time the event was recorded. */
17
+ recordedAt: number;
18
+ }
19
+ export interface SSEEventLog {
20
+ /** Record a new event and return its assigned id. */
21
+ record(runId: string, event: Omit<SSEEvent, "id" | "recordedAt">): SSEEvent;
22
+ /** Return events for a run with id greater than `afterId`. */
23
+ since(runId: string, afterId: number): SSEEvent[];
24
+ /** All events for a run. */
25
+ all(runId: string): SSEEvent[];
26
+ /** Mark a run completed (frees buffers after `ttlMs`). */
27
+ finalize(runId: string): void;
28
+ /** Remove a run's buffer immediately. */
29
+ drop(runId: string): void;
30
+ }
31
+ export interface InMemoryEventLogConfig {
32
+ /** Max events kept per run. Oldest evicted when exceeded. Default: 1024. */
33
+ maxEventsPerRun?: number;
34
+ /** Milliseconds after finalize before a run's buffer is dropped. Default: 300_000 (5min). */
35
+ ttlMs?: number;
36
+ }
37
+ export declare class InMemoryEventLog implements SSEEventLog {
38
+ private buffers;
39
+ private nextIds;
40
+ private finalizeTimers;
41
+ private maxEvents;
42
+ private ttlMs;
43
+ constructor(config?: InMemoryEventLogConfig);
44
+ record(runId: string, event: Omit<SSEEvent, "id" | "recordedAt">): SSEEvent;
45
+ since(runId: string, afterId: number): SSEEvent[];
46
+ all(runId: string): SSEEvent[];
47
+ finalize(runId: string): void;
48
+ drop(runId: string): void;
49
+ }
50
+ /** Format an `SSEEvent` for the wire. */
51
+ export declare function formatSSEEvent(ev: SSEEvent): string;
52
+ /** Process-wide default log so multiple endpoints can share one buffer. */
53
+ export declare const defaultEventLog: InMemoryEventLog;
54
+ //# sourceMappingURL=sse-event-log.d.ts.map
@@ -0,0 +1,33 @@
1
+ import type { ServerResponse } from "node:http";
2
+ export interface TextStreamLimits {
3
+ /** Maximum encoded frame and queued response bytes. Default 256 KiB each. */
4
+ maxFrameBytes?: number;
5
+ maxBufferedBytes?: number;
6
+ /** Maximum wait for a writable drain. Default 10 seconds. */
7
+ writeTimeoutMs?: number;
8
+ }
9
+ export declare function textStreamLimits(options?: TextStreamLimits): {
10
+ maxFrameBytes: number;
11
+ maxBufferedBytes: number;
12
+ writeTimeoutMs: number;
13
+ };
14
+ /** One owner for the response lifetime. Cancellation remains cooperative. */
15
+ export declare function responseLifetime(res: ServerResponse): {
16
+ controller: AbortController;
17
+ dispose(): void;
18
+ };
19
+ export declare class BoundedSSEWriter {
20
+ private readonly res;
21
+ private readonly signal;
22
+ private readonly limits;
23
+ constructor(res: ServerResponse, signal: AbortSignal, options?: TextStreamLimits);
24
+ write(frame: string): Promise<void>;
25
+ }
26
+ /** Initiate return on abort even for iterators whose next() settles only after return(). */
27
+ export declare function ownIterator(iterator: AsyncIterator<unknown>, signal: AbortSignal): {
28
+ close: () => Promise<unknown>;
29
+ dispose: () => void;
30
+ };
31
+ /** Pull only after the previous frame drained; settle iterator cleanup before terminal output. */
32
+ export declare function serveTextStream(res: ServerResponse, source: (signal: AbortSignal) => AsyncIterable<unknown>, options?: TextStreamLimits): Promise<void>;
33
+ //# sourceMappingURL=text-stream.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentium/transport",
3
- "version": "4.1.0",
3
+ "version": "4.6.0",
4
4
  "description": "HTTP and WebSocket transport layer for Agentium agents",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -25,9 +25,14 @@
25
25
  "types": "./dist/index.d.ts",
26
26
  "exports": {
27
27
  ".": {
28
- "types": "./dist/index.d.ts",
29
- "import": "./dist/index.js",
30
- "require": "./dist/index.cjs",
28
+ "import": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/index.d.cts",
34
+ "default": "./dist/index.cjs"
35
+ },
31
36
  "default": "./dist/index.js"
32
37
  }
33
38
  },
@@ -35,7 +40,7 @@
35
40
  "dist"
36
41
  ],
37
42
  "scripts": {
38
- "build": "tsdown --config ../../tsdown.config.ts && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --pretty false",
43
+ "build": "tsdown --config ../../tsdown.config.ts && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --pretty false && node ../../scripts/cjs-declarations.mjs",
39
44
  "dev": "tsdown --config ../../tsdown.config.ts --watch",
40
45
  "prepublishOnly": "npm run build"
41
46
  },
@@ -45,7 +50,7 @@
45
50
  "tsdown": "0.23.0"
46
51
  },
47
52
  "peerDependencies": {
48
- "@agentium/core": "^4.1.0",
53
+ "@agentium/core": "^4.6.0",
49
54
  "@types/express": "^4.0.0 || ^5.0.0",
50
55
  "express": "^4.21.2 || ^5.2.1",
51
56
  "multer": "^2.3.0",