@mantyx/sdk 0.2.0 → 0.4.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,170 @@
1
+ import { AgentCard } from '@a2a-js/sdk';
2
+ export { AgentCard, Message, MessageSendParams, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '@a2a-js/sdk';
3
+ import { AgentExecutor, RequestContext, ExecutionEventBus } from '@a2a-js/sdk/server';
4
+ export { AgentExecutor, ExecutionEventBus, RequestContext } from '@a2a-js/sdk/server';
5
+ import { M as MantyxClient, T as ToolRef, R as ReasoningLevel } from './client-ChxfhYBJ.cjs';
6
+ import 'zod';
7
+
8
+ /**
9
+ * Expose a MANTYX agent over the [Agent2Agent (A2A)](https://google-a2a.github.io/A2A/)
10
+ * protocol so other agents can talk to it as a peer.
11
+ *
12
+ * This module is loaded from a separate sub-export (`@mantyx/sdk/a2a-server`) so
13
+ * apps that don't need it never pay the bundle cost of the official A2A SDK or
14
+ * Express. To use it, install the optional peer deps:
15
+ *
16
+ * npm install @a2a-js/sdk express
17
+ *
18
+ * @example
19
+ * import { MantyxClient } from "@mantyx/sdk";
20
+ * import { serveAgentOverA2A } from "@mantyx/sdk/a2a-server";
21
+ *
22
+ * const client = new MantyxClient({
23
+ * apiKey: process.env.MANTYX_API_KEY!,
24
+ * workspaceSlug: process.env.MANTYX_WORKSPACE_SLUG!,
25
+ * });
26
+ *
27
+ * const server = await serveAgentOverA2A({
28
+ * client,
29
+ * port: 4000,
30
+ * agent: { agentId: "agent_cm6abc123" },
31
+ * agentCard: {
32
+ * name: "Acme Support",
33
+ * description: "Answers billing and account questions.",
34
+ * protocolVersion: "0.3.0",
35
+ * version: "1.0.0",
36
+ * url: "http://localhost:4000",
37
+ * skills: [{ id: "support", name: "Support", description: "Customer support",
38
+ * tags: ["support"] }],
39
+ * capabilities: { streaming: true, pushNotifications: false },
40
+ * defaultInputModes: ["text"],
41
+ * defaultOutputModes: ["text"],
42
+ * },
43
+ * });
44
+ *
45
+ * console.log(`Listening on ${server.url}`);
46
+ */
47
+
48
+ /**
49
+ * Description of the MANTYX agent that should answer A2A requests.
50
+ *
51
+ * Mirrors the existing `runAgent` / `createSession` argument shape:
52
+ * - `agentId` triggers a persisted workspace agent.
53
+ * - `systemPrompt` (with optional `modelId`, `tools`, …) defines an ephemeral
54
+ * agent inline.
55
+ *
56
+ * Either `agentId` or `systemPrompt` is required.
57
+ */
58
+ interface MantyxAgentSpec {
59
+ /** Reference to a persisted MANTYX agent. Mutually exclusive with `systemPrompt`. */
60
+ agentId?: string;
61
+ /** System prompt for an inline / ephemeral agent. Mutually exclusive with `agentId`. */
62
+ systemPrompt?: string;
63
+ modelId?: string;
64
+ tools?: ToolRef[];
65
+ reasoningLevel?: ReasoningLevel;
66
+ metadata?: Record<string, string>;
67
+ budgets?: {
68
+ maxToolTurns?: number;
69
+ };
70
+ /**
71
+ * Optional human-readable display name for runs created against MANTYX.
72
+ * Visible in the dashboard. Has no effect on the A2A side.
73
+ */
74
+ name?: string;
75
+ }
76
+ interface MantyxAgentExecutorOptions {
77
+ client: MantyxClient;
78
+ agent: MantyxAgentSpec;
79
+ /**
80
+ * How to map an incoming A2A `contextId` onto a MANTYX session.
81
+ *
82
+ * - `"auto"` (default): each unique `contextId` opens a MANTYX session on
83
+ * first contact and reuses it for subsequent messages with the same
84
+ * `contextId`. Gives you multi-turn out of the box.
85
+ * - `"stateless"`: every A2A message becomes an independent `runAgent`. No
86
+ * conversational memory; simpler resource model.
87
+ */
88
+ conversation?: "auto" | "stateless";
89
+ /**
90
+ * LRU cap on the in-memory `contextId -> AgentSession` table. When the cap
91
+ * is exceeded the oldest session is `end()`-ed and evicted. Default: 1024.
92
+ * Only consulted when `conversation: "auto"`.
93
+ */
94
+ maxSessions?: number;
95
+ /**
96
+ * Receives streaming MANTYX `assistant_delta` text. The default behaviour
97
+ * forwards every delta as a `TaskStatusUpdateEvent` (state: "working")
98
+ * containing the delta as a `text` part — this is what enables A2A
99
+ * `message/stream` clients to see real-time tokens. Override only if you
100
+ * need to swallow them or transform the wire shape.
101
+ */
102
+ onAssistantDelta?: (delta: string, ctx: RequestContext, eventBus: ExecutionEventBus) => void;
103
+ }
104
+ interface ServeAgentOverA2AOptions extends MantyxAgentExecutorOptions {
105
+ /** A2A Agent Card published at `/.well-known/agent-card.json`. */
106
+ agentCard: AgentCard;
107
+ /** TCP port to listen on. Default: 0 (let the OS pick). */
108
+ port?: number;
109
+ /** Bind address. Default: `"0.0.0.0"`. */
110
+ host?: string;
111
+ /** Path that serves the Agent Card JSON. Default: `"/.well-known/agent-card.json"`. */
112
+ agentCardPath?: string;
113
+ /** Path that serves the JSON-RPC endpoint. Default: `"/"`. */
114
+ jsonRpcPath?: string;
115
+ /**
116
+ * Path that serves the HTTP+JSON/REST endpoint. Default: `"/v1"`.
117
+ * Set to `false` to disable the REST mount entirely.
118
+ */
119
+ restPath?: string | false;
120
+ }
121
+ interface ServeAgentOverA2AHandle {
122
+ /** Origin of the running server, e.g. `"http://localhost:4000"`. */
123
+ url: string;
124
+ /** Resolved port number (useful when you let the OS pick one). */
125
+ port: number;
126
+ /** Stop the HTTP server, end every cached MANTYX session, and free MCP transports. */
127
+ close: () => Promise<void>;
128
+ }
129
+ /**
130
+ * Implementation of `@a2a-js/sdk`'s `AgentExecutor` that backs a MANTYX agent.
131
+ *
132
+ * Most callers want `serveAgentOverA2A` instead; reach for this class directly
133
+ * when you need to mount the executor inside an existing Express, Fastify, or
134
+ * Connect app.
135
+ */
136
+ declare class MantyxAgentExecutor implements AgentExecutor {
137
+ readonly client: MantyxClient;
138
+ readonly agent: MantyxAgentSpec;
139
+ readonly conversation: "auto" | "stateless";
140
+ readonly maxSessions: number;
141
+ readonly onAssistantDelta?: MantyxAgentExecutorOptions["onAssistantDelta"];
142
+ /** contextId -> live MANTYX session. Maintained as an LRU map. */
143
+ private readonly sessions;
144
+ /** taskIds we've been asked to cancel; checked between turns. */
145
+ private readonly cancelled;
146
+ /** Pending AbortControllers per task, used for cooperative cancel. */
147
+ private readonly inFlight;
148
+ constructor(options: MantyxAgentExecutorOptions);
149
+ execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void>;
150
+ cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>;
151
+ /**
152
+ * Close every cached session. Idempotent. Safe to call from server shutdown
153
+ * paths.
154
+ */
155
+ close(): Promise<void>;
156
+ private runOnce;
157
+ private getOrCreateSession;
158
+ private evictIfNeeded;
159
+ }
160
+ /**
161
+ * Spin up a small HTTP server that exposes a MANTYX agent as an A2A peer.
162
+ * Mounts the Agent Card, JSON-RPC, and (optionally) REST endpoints from the
163
+ * official `@a2a-js/sdk` library.
164
+ *
165
+ * Throws if `express` / `@a2a-js/sdk` aren't installed; install them as peer
166
+ * deps with `npm install express @a2a-js/sdk`.
167
+ */
168
+ declare function serveAgentOverA2A(options: ServeAgentOverA2AOptions): Promise<ServeAgentOverA2AHandle>;
169
+
170
+ export { MantyxAgentExecutor, type MantyxAgentExecutorOptions, type MantyxAgentSpec, type ServeAgentOverA2AHandle, type ServeAgentOverA2AOptions, serveAgentOverA2A };
@@ -0,0 +1,170 @@
1
+ import { AgentCard } from '@a2a-js/sdk';
2
+ export { AgentCard, Message, MessageSendParams, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '@a2a-js/sdk';
3
+ import { AgentExecutor, RequestContext, ExecutionEventBus } from '@a2a-js/sdk/server';
4
+ export { AgentExecutor, ExecutionEventBus, RequestContext } from '@a2a-js/sdk/server';
5
+ import { M as MantyxClient, T as ToolRef, R as ReasoningLevel } from './client-ChxfhYBJ.js';
6
+ import 'zod';
7
+
8
+ /**
9
+ * Expose a MANTYX agent over the [Agent2Agent (A2A)](https://google-a2a.github.io/A2A/)
10
+ * protocol so other agents can talk to it as a peer.
11
+ *
12
+ * This module is loaded from a separate sub-export (`@mantyx/sdk/a2a-server`) so
13
+ * apps that don't need it never pay the bundle cost of the official A2A SDK or
14
+ * Express. To use it, install the optional peer deps:
15
+ *
16
+ * npm install @a2a-js/sdk express
17
+ *
18
+ * @example
19
+ * import { MantyxClient } from "@mantyx/sdk";
20
+ * import { serveAgentOverA2A } from "@mantyx/sdk/a2a-server";
21
+ *
22
+ * const client = new MantyxClient({
23
+ * apiKey: process.env.MANTYX_API_KEY!,
24
+ * workspaceSlug: process.env.MANTYX_WORKSPACE_SLUG!,
25
+ * });
26
+ *
27
+ * const server = await serveAgentOverA2A({
28
+ * client,
29
+ * port: 4000,
30
+ * agent: { agentId: "agent_cm6abc123" },
31
+ * agentCard: {
32
+ * name: "Acme Support",
33
+ * description: "Answers billing and account questions.",
34
+ * protocolVersion: "0.3.0",
35
+ * version: "1.0.0",
36
+ * url: "http://localhost:4000",
37
+ * skills: [{ id: "support", name: "Support", description: "Customer support",
38
+ * tags: ["support"] }],
39
+ * capabilities: { streaming: true, pushNotifications: false },
40
+ * defaultInputModes: ["text"],
41
+ * defaultOutputModes: ["text"],
42
+ * },
43
+ * });
44
+ *
45
+ * console.log(`Listening on ${server.url}`);
46
+ */
47
+
48
+ /**
49
+ * Description of the MANTYX agent that should answer A2A requests.
50
+ *
51
+ * Mirrors the existing `runAgent` / `createSession` argument shape:
52
+ * - `agentId` triggers a persisted workspace agent.
53
+ * - `systemPrompt` (with optional `modelId`, `tools`, …) defines an ephemeral
54
+ * agent inline.
55
+ *
56
+ * Either `agentId` or `systemPrompt` is required.
57
+ */
58
+ interface MantyxAgentSpec {
59
+ /** Reference to a persisted MANTYX agent. Mutually exclusive with `systemPrompt`. */
60
+ agentId?: string;
61
+ /** System prompt for an inline / ephemeral agent. Mutually exclusive with `agentId`. */
62
+ systemPrompt?: string;
63
+ modelId?: string;
64
+ tools?: ToolRef[];
65
+ reasoningLevel?: ReasoningLevel;
66
+ metadata?: Record<string, string>;
67
+ budgets?: {
68
+ maxToolTurns?: number;
69
+ };
70
+ /**
71
+ * Optional human-readable display name for runs created against MANTYX.
72
+ * Visible in the dashboard. Has no effect on the A2A side.
73
+ */
74
+ name?: string;
75
+ }
76
+ interface MantyxAgentExecutorOptions {
77
+ client: MantyxClient;
78
+ agent: MantyxAgentSpec;
79
+ /**
80
+ * How to map an incoming A2A `contextId` onto a MANTYX session.
81
+ *
82
+ * - `"auto"` (default): each unique `contextId` opens a MANTYX session on
83
+ * first contact and reuses it for subsequent messages with the same
84
+ * `contextId`. Gives you multi-turn out of the box.
85
+ * - `"stateless"`: every A2A message becomes an independent `runAgent`. No
86
+ * conversational memory; simpler resource model.
87
+ */
88
+ conversation?: "auto" | "stateless";
89
+ /**
90
+ * LRU cap on the in-memory `contextId -> AgentSession` table. When the cap
91
+ * is exceeded the oldest session is `end()`-ed and evicted. Default: 1024.
92
+ * Only consulted when `conversation: "auto"`.
93
+ */
94
+ maxSessions?: number;
95
+ /**
96
+ * Receives streaming MANTYX `assistant_delta` text. The default behaviour
97
+ * forwards every delta as a `TaskStatusUpdateEvent` (state: "working")
98
+ * containing the delta as a `text` part — this is what enables A2A
99
+ * `message/stream` clients to see real-time tokens. Override only if you
100
+ * need to swallow them or transform the wire shape.
101
+ */
102
+ onAssistantDelta?: (delta: string, ctx: RequestContext, eventBus: ExecutionEventBus) => void;
103
+ }
104
+ interface ServeAgentOverA2AOptions extends MantyxAgentExecutorOptions {
105
+ /** A2A Agent Card published at `/.well-known/agent-card.json`. */
106
+ agentCard: AgentCard;
107
+ /** TCP port to listen on. Default: 0 (let the OS pick). */
108
+ port?: number;
109
+ /** Bind address. Default: `"0.0.0.0"`. */
110
+ host?: string;
111
+ /** Path that serves the Agent Card JSON. Default: `"/.well-known/agent-card.json"`. */
112
+ agentCardPath?: string;
113
+ /** Path that serves the JSON-RPC endpoint. Default: `"/"`. */
114
+ jsonRpcPath?: string;
115
+ /**
116
+ * Path that serves the HTTP+JSON/REST endpoint. Default: `"/v1"`.
117
+ * Set to `false` to disable the REST mount entirely.
118
+ */
119
+ restPath?: string | false;
120
+ }
121
+ interface ServeAgentOverA2AHandle {
122
+ /** Origin of the running server, e.g. `"http://localhost:4000"`. */
123
+ url: string;
124
+ /** Resolved port number (useful when you let the OS pick one). */
125
+ port: number;
126
+ /** Stop the HTTP server, end every cached MANTYX session, and free MCP transports. */
127
+ close: () => Promise<void>;
128
+ }
129
+ /**
130
+ * Implementation of `@a2a-js/sdk`'s `AgentExecutor` that backs a MANTYX agent.
131
+ *
132
+ * Most callers want `serveAgentOverA2A` instead; reach for this class directly
133
+ * when you need to mount the executor inside an existing Express, Fastify, or
134
+ * Connect app.
135
+ */
136
+ declare class MantyxAgentExecutor implements AgentExecutor {
137
+ readonly client: MantyxClient;
138
+ readonly agent: MantyxAgentSpec;
139
+ readonly conversation: "auto" | "stateless";
140
+ readonly maxSessions: number;
141
+ readonly onAssistantDelta?: MantyxAgentExecutorOptions["onAssistantDelta"];
142
+ /** contextId -> live MANTYX session. Maintained as an LRU map. */
143
+ private readonly sessions;
144
+ /** taskIds we've been asked to cancel; checked between turns. */
145
+ private readonly cancelled;
146
+ /** Pending AbortControllers per task, used for cooperative cancel. */
147
+ private readonly inFlight;
148
+ constructor(options: MantyxAgentExecutorOptions);
149
+ execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void>;
150
+ cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>;
151
+ /**
152
+ * Close every cached session. Idempotent. Safe to call from server shutdown
153
+ * paths.
154
+ */
155
+ close(): Promise<void>;
156
+ private runOnce;
157
+ private getOrCreateSession;
158
+ private evictIfNeeded;
159
+ }
160
+ /**
161
+ * Spin up a small HTTP server that exposes a MANTYX agent as an A2A peer.
162
+ * Mounts the Agent Card, JSON-RPC, and (optionally) REST endpoints from the
163
+ * official `@a2a-js/sdk` library.
164
+ *
165
+ * Throws if `express` / `@a2a-js/sdk` aren't installed; install them as peer
166
+ * deps with `npm install express @a2a-js/sdk`.
167
+ */
168
+ declare function serveAgentOverA2A(options: ServeAgentOverA2AOptions): Promise<ServeAgentOverA2AHandle>;
169
+
170
+ export { MantyxAgentExecutor, type MantyxAgentExecutorOptions, type MantyxAgentSpec, type ServeAgentOverA2AHandle, type ServeAgentOverA2AOptions, serveAgentOverA2A };
@@ -0,0 +1,344 @@
1
+ import {
2
+ MantyxError,
3
+ MantyxRunError
4
+ } from "./chunk-UVIVQD4O.js";
5
+
6
+ // src/a2a-server.ts
7
+ var MantyxAgentExecutor = class {
8
+ client;
9
+ agent;
10
+ conversation;
11
+ maxSessions;
12
+ onAssistantDelta;
13
+ /** contextId -> live MANTYX session. Maintained as an LRU map. */
14
+ sessions = /* @__PURE__ */ new Map();
15
+ /** taskIds we've been asked to cancel; checked between turns. */
16
+ cancelled = /* @__PURE__ */ new Set();
17
+ /** Pending AbortControllers per task, used for cooperative cancel. */
18
+ inFlight = /* @__PURE__ */ new Map();
19
+ constructor(options) {
20
+ if (!options.client) {
21
+ throw new MantyxError("MantyxAgentExecutor: `client` is required");
22
+ }
23
+ validateAgentSpec(options.agent);
24
+ this.client = options.client;
25
+ this.agent = options.agent;
26
+ this.conversation = options.conversation ?? "auto";
27
+ this.maxSessions = options.maxSessions ?? 1024;
28
+ if (options.onAssistantDelta) this.onAssistantDelta = options.onAssistantDelta;
29
+ }
30
+ async execute(requestContext, eventBus) {
31
+ const { userMessage, taskId, contextId, task } = requestContext;
32
+ const userText = extractText(userMessage);
33
+ const abort = new AbortController();
34
+ this.inFlight.set(taskId, abort);
35
+ try {
36
+ if (!task) {
37
+ eventBus.publish({
38
+ kind: "task",
39
+ id: taskId,
40
+ contextId,
41
+ status: { state: "submitted", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
42
+ history: [userMessage]
43
+ });
44
+ }
45
+ eventBus.publish(statusUpdate(taskId, contextId, "working", false));
46
+ if (this.cancelled.has(taskId)) {
47
+ eventBus.publish(statusUpdate(taskId, contextId, "canceled", true));
48
+ eventBus.finished();
49
+ return;
50
+ }
51
+ const onDelta = (delta) => {
52
+ if (this.onAssistantDelta) {
53
+ this.onAssistantDelta(delta, requestContext, eventBus);
54
+ return;
55
+ }
56
+ eventBus.publish(deltaStatusUpdate(taskId, contextId, delta));
57
+ };
58
+ let result;
59
+ try {
60
+ result = await this.runOnce(contextId, userText, onDelta, abort.signal);
61
+ } catch (err) {
62
+ eventBus.publish(
63
+ completedStatusUpdate(
64
+ taskId,
65
+ contextId,
66
+ this.cancelled.has(taskId) ? "canceled" : "failed",
67
+ errorText(err)
68
+ )
69
+ );
70
+ eventBus.finished();
71
+ return;
72
+ }
73
+ eventBus.publish(completedStatusUpdate(taskId, contextId, "completed", result.text ?? ""));
74
+ eventBus.finished();
75
+ } finally {
76
+ this.inFlight.delete(taskId);
77
+ this.cancelled.delete(taskId);
78
+ }
79
+ }
80
+ async cancelTask(taskId, eventBus) {
81
+ this.cancelled.add(taskId);
82
+ const ctrl = this.inFlight.get(taskId);
83
+ if (ctrl) ctrl.abort();
84
+ void eventBus;
85
+ }
86
+ /**
87
+ * Close every cached session. Idempotent. Safe to call from server shutdown
88
+ * paths.
89
+ */
90
+ async close() {
91
+ const sessions = Array.from(this.sessions.values());
92
+ this.sessions.clear();
93
+ await Promise.allSettled(sessions.map((s) => s.end()));
94
+ }
95
+ // -------------------------------------------------- private session helpers
96
+ async runOnce(contextId, prompt, onAssistantDelta, signal) {
97
+ if (this.conversation === "stateless") {
98
+ const runSpec = {
99
+ ...specForRun(this.agent),
100
+ prompt,
101
+ onAssistantDelta,
102
+ signal
103
+ };
104
+ return this.client.runAgent(runSpec);
105
+ }
106
+ const session = await this.getOrCreateSession(contextId);
107
+ return session.send(prompt, { onAssistantDelta, signal });
108
+ }
109
+ async getOrCreateSession(contextId) {
110
+ const existing = this.sessions.get(contextId);
111
+ if (existing) {
112
+ this.sessions.delete(contextId);
113
+ this.sessions.set(contextId, existing);
114
+ return existing;
115
+ }
116
+ const sessionSpec = specForSession(this.agent, contextId);
117
+ const session = await this.client.createSession(sessionSpec);
118
+ this.sessions.set(contextId, session);
119
+ await this.evictIfNeeded();
120
+ return session;
121
+ }
122
+ async evictIfNeeded() {
123
+ while (this.sessions.size > this.maxSessions) {
124
+ const oldestKey = this.sessions.keys().next().value;
125
+ if (!oldestKey) break;
126
+ const oldest = this.sessions.get(oldestKey);
127
+ this.sessions.delete(oldestKey);
128
+ try {
129
+ await oldest.end();
130
+ } catch {
131
+ }
132
+ }
133
+ }
134
+ };
135
+ async function serveAgentOverA2A(options) {
136
+ const a2a = await loadServerSdk();
137
+ const expressMod = await loadExpress();
138
+ const executor = new MantyxAgentExecutor(options);
139
+ const requestHandler = new a2a.DefaultRequestHandler(
140
+ options.agentCard,
141
+ new a2a.InMemoryTaskStore(),
142
+ executor
143
+ );
144
+ const app = expressMod();
145
+ app.use(expressMod.json());
146
+ const cardPath = options.agentCardPath ?? "/.well-known/agent-card.json";
147
+ const jsonRpcPath = options.jsonRpcPath ?? "/";
148
+ const restPath = options.restPath === void 0 ? "/v1" : options.restPath;
149
+ app.use(
150
+ cardPath,
151
+ a2a.expressApp.agentCardHandler({ agentCardProvider: requestHandler })
152
+ );
153
+ if (restPath !== false) {
154
+ app.use(
155
+ restPath,
156
+ a2a.expressApp.restHandler({
157
+ requestHandler,
158
+ userBuilder: a2a.expressApp.UserBuilder.noAuthentication
159
+ })
160
+ );
161
+ }
162
+ app.use(
163
+ jsonRpcPath,
164
+ a2a.expressApp.jsonRpcHandler({
165
+ requestHandler,
166
+ userBuilder: a2a.expressApp.UserBuilder.noAuthentication
167
+ })
168
+ );
169
+ const port = options.port ?? 0;
170
+ const host = options.host ?? "0.0.0.0";
171
+ const server = app.listen(port, host);
172
+ await new Promise((resolve, reject) => {
173
+ server.once("listening", resolve);
174
+ server.once("error", reject);
175
+ });
176
+ const address = server.address();
177
+ if (!address || typeof address === "string") {
178
+ server.close();
179
+ throw new MantyxError("serveAgentOverA2A: failed to bind HTTP listener");
180
+ }
181
+ return {
182
+ port: address.port,
183
+ url: `http://${displayHost(host)}:${address.port}`,
184
+ close: async () => {
185
+ await new Promise(
186
+ (resolve, reject) => server.close((err) => err ? reject(err) : resolve())
187
+ );
188
+ await executor.close();
189
+ }
190
+ };
191
+ }
192
+ function statusUpdate(taskId, contextId, state, final) {
193
+ return {
194
+ kind: "status-update",
195
+ taskId,
196
+ contextId,
197
+ status: { state, timestamp: (/* @__PURE__ */ new Date()).toISOString() },
198
+ final
199
+ };
200
+ }
201
+ function deltaStatusUpdate(taskId, contextId, delta) {
202
+ return {
203
+ kind: "status-update",
204
+ taskId,
205
+ contextId,
206
+ status: {
207
+ state: "working",
208
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
209
+ message: {
210
+ kind: "message",
211
+ messageId: randomMessageId(),
212
+ role: "agent",
213
+ parts: [{ kind: "text", text: delta }],
214
+ contextId,
215
+ taskId
216
+ }
217
+ },
218
+ final: false
219
+ };
220
+ }
221
+ function completedStatusUpdate(taskId, contextId, state, text) {
222
+ return {
223
+ kind: "status-update",
224
+ taskId,
225
+ contextId,
226
+ status: {
227
+ state,
228
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
229
+ message: {
230
+ kind: "message",
231
+ messageId: randomMessageId(),
232
+ role: "agent",
233
+ parts: [{ kind: "text", text }],
234
+ contextId,
235
+ taskId
236
+ }
237
+ },
238
+ final: true
239
+ };
240
+ }
241
+ function extractText(message) {
242
+ if (!message) return "";
243
+ const parts = message.parts ?? [];
244
+ const out = [];
245
+ for (const p of parts) {
246
+ if (p.kind === "text") {
247
+ const t = p.text;
248
+ if (typeof t === "string") out.push(t);
249
+ }
250
+ }
251
+ return out.join("\n");
252
+ }
253
+ function specForRun(spec) {
254
+ const out = {};
255
+ if (spec.agentId) out.agentId = spec.agentId;
256
+ if (spec.systemPrompt) out.systemPrompt = spec.systemPrompt;
257
+ if (spec.modelId) out.modelId = spec.modelId;
258
+ if (spec.tools) out.tools = spec.tools;
259
+ if (spec.reasoningLevel !== void 0) out.reasoningLevel = spec.reasoningLevel;
260
+ if (spec.metadata) out.metadata = spec.metadata;
261
+ if (spec.budgets) out.budgets = spec.budgets;
262
+ if (spec.name) out.name = spec.name;
263
+ return out;
264
+ }
265
+ function specForSession(spec, contextId) {
266
+ const out = {};
267
+ if (spec.agentId) out.agentId = spec.agentId;
268
+ if (spec.systemPrompt) out.systemPrompt = spec.systemPrompt;
269
+ if (spec.modelId) out.modelId = spec.modelId;
270
+ if (spec.tools) out.tools = spec.tools;
271
+ if (spec.reasoningLevel !== void 0) out.reasoningLevel = spec.reasoningLevel;
272
+ const meta = { ...spec.metadata ?? {} };
273
+ if (!meta.a2a_context_id) meta.a2a_context_id = contextId;
274
+ out.metadata = meta;
275
+ if (spec.budgets) out.budgets = spec.budgets;
276
+ if (spec.name) out.name = spec.name;
277
+ return out;
278
+ }
279
+ function validateAgentSpec(spec) {
280
+ if (!spec.agentId && (!spec.systemPrompt || spec.systemPrompt.length === 0)) {
281
+ throw new MantyxError(
282
+ "MantyxAgentExecutor: `agent.agentId` or `agent.systemPrompt` is required"
283
+ );
284
+ }
285
+ }
286
+ function errorText(err) {
287
+ if (err instanceof MantyxRunError) {
288
+ return `MANTYX run failed (${err.subtype ?? "unknown"}): ${err.message}`;
289
+ }
290
+ if (err instanceof Error) return err.message;
291
+ try {
292
+ return String(err);
293
+ } catch {
294
+ return "unknown error";
295
+ }
296
+ }
297
+ function randomMessageId() {
298
+ if (typeof globalThis.crypto?.randomUUID === "function") {
299
+ return globalThis.crypto.randomUUID();
300
+ }
301
+ return `msg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
302
+ }
303
+ function displayHost(host) {
304
+ if (host === "0.0.0.0" || host === "::") return "localhost";
305
+ return host;
306
+ }
307
+ async function loadExpress() {
308
+ try {
309
+ const mod = await import("express");
310
+ return "default" in mod ? mod.default : mod;
311
+ } catch (err) {
312
+ throw new MantyxError(
313
+ "serveAgentOverA2A: `express` is required but not installed. Run `npm install express @a2a-js/sdk` to enable the A2A server."
314
+ );
315
+ }
316
+ }
317
+ async function loadServerSdk() {
318
+ let server;
319
+ let express;
320
+ try {
321
+ server = await import("@a2a-js/sdk/server");
322
+ } catch (err) {
323
+ throw new MantyxError(
324
+ "serveAgentOverA2A: `@a2a-js/sdk` is required but not installed. Run `npm install @a2a-js/sdk express` to enable the A2A server."
325
+ );
326
+ }
327
+ try {
328
+ express = await import("@a2a-js/sdk/server/express");
329
+ } catch (err) {
330
+ throw new MantyxError(
331
+ "serveAgentOverA2A: `@a2a-js/sdk/server/express` could not be loaded; ensure the installed `@a2a-js/sdk` is at least v0.3."
332
+ );
333
+ }
334
+ return {
335
+ DefaultRequestHandler: server.DefaultRequestHandler,
336
+ InMemoryTaskStore: server.InMemoryTaskStore,
337
+ expressApp: express
338
+ };
339
+ }
340
+ export {
341
+ MantyxAgentExecutor,
342
+ serveAgentOverA2A
343
+ };
344
+ //# sourceMappingURL=a2a-server.js.map