@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,658 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Public tool helpers for the MANTYX SDK.
5
+ *
6
+ * Server-resolved (executed by MANTYX):
7
+ * mantyxTool(id) → existing workspace `Tool` row by id
8
+ * mantyxPluginTool(name) → built-in plugin tool by `@plugin/tool` name
9
+ * mantyxA2A({...}) → remote Agent2Agent peer, dialed by MANTYX
10
+ * mantyxMcp({...}) → remote MCP server (Streamable HTTP), proxied by MANTYX
11
+ *
12
+ * Client-resolved (executed in this process; the SDK shuttles inputs and
13
+ * outputs over the agent loop):
14
+ * defineLocalTool({...}) → generic local tool with a Zod parameter schema
15
+ * defineLocalA2A({...}) → A2A peer the SDK can reach but MANTYX cannot —
16
+ * pass an `agentCardUrl`; the SDK fetches the
17
+ * Agent Card and speaks A2A `message/send` for you.
18
+ * defineLocalMcp({...}) → MCP server the SDK manages — pass either a
19
+ * Streamable HTTP `url` or a stdio
20
+ * `command`; the SDK runs `Initialize` +
21
+ * `tools/list` and forwards `tools/call` for you.
22
+ *
23
+ * The server emits a `local_tool_call` event for every client-resolved
24
+ * invocation. The event carries a `kind` discriminator (`"local"` is implied
25
+ * when omitted, `"a2a_local"` and `"mcp_local"` are explicit) so the SDK can
26
+ * dispatch to the right handler.
27
+ */
28
+
29
+ type ZodLikeObject = z.ZodType<Record<string, unknown>> & {
30
+ _def?: unknown;
31
+ parse?: (value: unknown) => unknown;
32
+ };
33
+ /**
34
+ * Provider-thinking knob, mapped server-side onto each LLM's native dial:
35
+ * `reasoning.effort` (OpenAI), `thinkingConfig.thinkingLevel` / `thinkingBudget`
36
+ * (Gemini), or extended-thinking budget (Anthropic / Bedrock-Anthropic).
37
+ *
38
+ * Pass either a string anchor (`"off" | "low" | "medium" | "high"`) or an
39
+ * integer in `0..100` (where `0` explicitly disables provider thinking).
40
+ */
41
+ type ReasoningLevel = "off" | "low" | "medium" | "high" | number;
42
+ interface LocalTool<TArgs = Record<string, unknown>> {
43
+ readonly kind: "local";
44
+ readonly name: string;
45
+ readonly description: string;
46
+ readonly parameters: ZodLikeObject | undefined;
47
+ readonly execute: (args: TArgs) => Promise<string> | string;
48
+ }
49
+ interface DefineLocalToolOptions<T extends ZodLikeObject | undefined> {
50
+ /** Lowercase alphanumeric + underscore, max 64 chars. */
51
+ name: string;
52
+ description?: string;
53
+ parameters?: T;
54
+ execute: (args: T extends ZodLikeObject ? z.infer<T> : Record<string, unknown>) => Promise<string> | string;
55
+ }
56
+ declare function defineLocalTool<T extends ZodLikeObject | undefined>(opts: DefineLocalToolOptions<T>): LocalTool;
57
+ interface MantyxToolRef {
58
+ readonly kind: "mantyx";
59
+ readonly id: string;
60
+ }
61
+ interface MantyxPluginToolRef {
62
+ readonly kind: "mantyx_plugin";
63
+ readonly name: string;
64
+ }
65
+ declare function mantyxTool(id: string): MantyxToolRef;
66
+ declare function mantyxPluginTool(name: string): MantyxPluginToolRef;
67
+ /**
68
+ * Reference to a remote Agent2Agent peer reachable from MANTYX (server-resolved).
69
+ * MANTYX dials `agentCardUrl` over A2A's `message/send` RPC and forwards the
70
+ * remote agent's reply as the tool result.
71
+ */
72
+ interface A2AToolRef {
73
+ readonly kind: "a2a";
74
+ readonly name: string;
75
+ readonly description?: string;
76
+ readonly agentCardUrl: string;
77
+ readonly headers?: Record<string, string>;
78
+ readonly contextId?: string;
79
+ }
80
+ interface MantyxA2AOptions {
81
+ /** Tool name surfaced to the model; must match `^[a-zA-Z0-9_]{1,64}$`. */
82
+ name: string;
83
+ description?: string;
84
+ /** Remote Agent Card URL (`/.well-known/agent-card.json`) or JSON-RPC root. */
85
+ agentCardUrl: string;
86
+ /** Per-request HTTP headers (typically `Authorization`). */
87
+ headers?: Record<string, string>;
88
+ /** Optional A2A `contextId` to thread multiple delegations. */
89
+ contextId?: string;
90
+ }
91
+ declare function mantyxA2A(opts: MantyxA2AOptions): A2AToolRef;
92
+ /**
93
+ * Local A2A peer — the SDK fetches the Agent Card from `agentCardUrl` on
94
+ * the first run, ships the resolved card with the spec, and speaks A2A
95
+ * `message/send` to `agentCard.url` whenever MANTYX emits a
96
+ * `local_tool_call` for this tool. You only supply the URL.
97
+ *
98
+ * The model addresses this tool by `name` and always passes
99
+ * `{ message: string }` as arguments.
100
+ *
101
+ * Resolution is lazy: the card is fetched on the first `runAgent` /
102
+ * `streamAgent` / `createSession` (or `session.send`) call and cached on
103
+ * the tool ref for the rest of the process lifetime. Re-construct the ref
104
+ * to force a refetch.
105
+ */
106
+ interface LocalA2ATool {
107
+ readonly kind: "a2a_local";
108
+ readonly name: string;
109
+ /** Where the SDK fetches the Agent Card from. Cached after the first hit. */
110
+ readonly agentCardUrl: string;
111
+ /**
112
+ * Headers used for **both** the card fetch and every `message/send` POST
113
+ * (typically `Authorization` for intranet peers).
114
+ */
115
+ readonly headers: Record<string, string> | undefined;
116
+ /**
117
+ * Internal cache of the resolved Agent Card. Populated lazily by the
118
+ * client on the first run; not part of the user contract.
119
+ * @internal
120
+ */
121
+ _resolvedCard?: ResolvedAgentCard;
122
+ }
123
+ /** Internal: the snapshot of a resolved A2A Agent Card. */
124
+ interface ResolvedAgentCard {
125
+ /** Required by the A2A spec; used for the synthesized tool description. */
126
+ readonly name: string;
127
+ /** Peer's A2A endpoint — where the SDK POSTs `message/send`. */
128
+ readonly url?: string;
129
+ /** Anything else the peer publishes; forwarded verbatim onto the wire. */
130
+ readonly [k: string]: unknown;
131
+ }
132
+ interface DefineLocalA2AOptions {
133
+ /** Tool name surfaced to the model. Must match `^[a-zA-Z0-9_]{1,64}$`. */
134
+ name: string;
135
+ /**
136
+ * URL of the peer's Agent Card (`/.well-known/agent-card.json` is the
137
+ * conventional path). The SDK fetches this on the first run, parses it,
138
+ * and ships the resolved card with the spec. The resolved card's `url`
139
+ * field is then used as the `message/send` target.
140
+ */
141
+ agentCardUrl: string;
142
+ /**
143
+ * Headers attached to **both** the card fetch and every `message/send`
144
+ * POST (typically `Authorization` for intranet peers).
145
+ */
146
+ headers?: Record<string, string>;
147
+ }
148
+ declare function defineLocalA2A(opts: DefineLocalA2AOptions): LocalA2ATool;
149
+ /**
150
+ * Reference to a remote MCP server (Streamable HTTP) discovered + proxied by
151
+ * MANTYX. Each tool in the catalog is exposed to the model as `<name>_<tool>`.
152
+ */
153
+ interface McpToolRef {
154
+ readonly kind: "mcp";
155
+ readonly name: string;
156
+ readonly url: string;
157
+ readonly headers?: Record<string, string>;
158
+ readonly toolFilter?: string[];
159
+ }
160
+ interface MantyxMcpOptions {
161
+ /** Server label; used to prefix every discovered tool. */
162
+ name: string;
163
+ /** Streamable HTTP MCP endpoint. */
164
+ url: string;
165
+ headers?: Record<string, string>;
166
+ /** Optional allowlist of MCP tool names. */
167
+ toolFilter?: string[];
168
+ }
169
+ declare function mantyxMcp(opts: MantyxMcpOptions): McpToolRef;
170
+ /**
171
+ * Streamable HTTP transport spec for {@link defineLocalMcp}.
172
+ */
173
+ interface LocalMcpHttpTransport {
174
+ /** Streamable HTTP MCP endpoint (e.g. `http://localhost:8080/mcp`). */
175
+ url: string;
176
+ /** HTTP headers sent on every MCP request (typically `Authorization`). */
177
+ headers?: Record<string, string>;
178
+ }
179
+ /**
180
+ * stdio transport spec for {@link defineLocalMcp}. The SDK spawns the
181
+ * specified executable with the given arguments and speaks JSON-RPC over
182
+ * its stdin/stdout streams.
183
+ */
184
+ interface LocalMcpStdioTransport {
185
+ /** Executable to launch (e.g. `mcp-server-filesystem`, `node`, `uvx`). */
186
+ command: string;
187
+ /** Arguments passed verbatim. */
188
+ args?: string[];
189
+ /** Environment variables for the child process. Inherited if undefined. */
190
+ env?: Record<string, string>;
191
+ /** Working directory for the child process. */
192
+ cwd?: string;
193
+ }
194
+ /**
195
+ * Local MCP server — the SDK manages the entire MCP lifecycle for you.
196
+ *
197
+ * Pass either a Streamable HTTP `url` or an stdio `command` (mutually
198
+ * exclusive). On the first run, the SDK opens the transport, runs MCP's
199
+ * `Initialize` (capturing the `Implementation` block) and `tools/list`
200
+ * (capturing the catalog), and ships both inline as part of the spec. On
201
+ * every `local_tool_call` with `kind: "mcp_local"` the SDK forwards the
202
+ * call to MCP `tools/call` on the cached connection and POSTs the
203
+ * flattened text response back to MANTYX.
204
+ *
205
+ * Connections are reused across runs and across messages within a session
206
+ * and closed on `runAgent` completion / `session.end()`.
207
+ */
208
+ interface LocalMcpServer {
209
+ readonly kind: "mcp_local";
210
+ readonly name: string;
211
+ /** One-of with {@link stdio} — the transport spec is mutually exclusive. */
212
+ readonly http: LocalMcpHttpTransport | undefined;
213
+ /** One-of with {@link http} — the transport spec is mutually exclusive. */
214
+ readonly stdio: LocalMcpStdioTransport | undefined;
215
+ /**
216
+ * Internal cache of the resolved MCP client + catalog. Populated lazily
217
+ * by the run driver on the first run; not part of the user contract.
218
+ * @internal
219
+ */
220
+ _resolved?: ResolvedMcpServer;
221
+ }
222
+ /**
223
+ * Internal: the live MCP client + the snapshot the SDK ships on the wire.
224
+ */
225
+ interface ResolvedMcpServer {
226
+ /** The MCP `Implementation` block from `Initialize`. */
227
+ readonly serverInfo: {
228
+ name: string;
229
+ version?: string;
230
+ [k: string]: unknown;
231
+ };
232
+ /** Verbatim `tools/list` output. */
233
+ readonly tools: ReadonlyArray<{
234
+ readonly name: string;
235
+ readonly description?: string;
236
+ readonly inputSchema: Record<string, unknown>;
237
+ readonly annotations?: Record<string, unknown>;
238
+ readonly [k: string]: unknown;
239
+ }>;
240
+ /**
241
+ * The live MCP client. Used by the run driver to call `tools/call`. The
242
+ * concrete type depends on the transport — kept loose so this header
243
+ * file doesn't have to import the MCP SDK type.
244
+ */
245
+ readonly client: McpClientLike;
246
+ /** Closes the MCP transport (idempotent). */
247
+ readonly close: () => Promise<void>;
248
+ }
249
+ /** Minimal interface this SDK uses against an MCP client. */
250
+ interface McpClientLike {
251
+ callTool(params: {
252
+ name: string;
253
+ arguments?: Record<string, unknown>;
254
+ }): Promise<{
255
+ content?: Array<{
256
+ type: string;
257
+ text?: string;
258
+ [k: string]: unknown;
259
+ }>;
260
+ isError?: boolean;
261
+ [k: string]: unknown;
262
+ }>;
263
+ }
264
+ interface DefineLocalMcpOptions {
265
+ /**
266
+ * Server label echoed back as `mcpServer` on every `local_tool_call`. The
267
+ * SDK auto-prefixes each discovered tool's wire-level `name` with
268
+ * `<this>_` so the model sees a non-colliding `<server>_<tool>` surface
269
+ * — mirroring how MANTYX prefixes for `kind: "mcp"`.
270
+ */
271
+ name: string;
272
+ /**
273
+ * Streamable HTTP transport. Mutually exclusive with {@link command}.
274
+ */
275
+ url?: string;
276
+ /**
277
+ * Headers attached to every MCP request when using the HTTP transport.
278
+ */
279
+ headers?: Record<string, string>;
280
+ /**
281
+ * stdio transport: executable to launch. Mutually exclusive with
282
+ * {@link url}.
283
+ */
284
+ command?: string;
285
+ /** Arguments for the stdio child process. */
286
+ args?: string[];
287
+ /** Environment variables for the stdio child process. */
288
+ env?: Record<string, string>;
289
+ /** Working directory for the stdio child process. */
290
+ cwd?: string;
291
+ }
292
+ declare function defineLocalMcp(opts: DefineLocalMcpOptions): LocalMcpServer;
293
+ type ToolRef = MantyxToolRef | MantyxPluginToolRef | LocalTool | A2AToolRef | LocalA2ATool | McpToolRef | LocalMcpServer;
294
+ declare function isLocalTool(t: ToolRef): t is LocalTool;
295
+ declare function isLocalA2ATool(t: ToolRef): t is LocalA2ATool;
296
+ declare function isLocalMcpServer(t: ToolRef): t is LocalMcpServer;
297
+
298
+ declare const DEFAULT_BASE_URL = "https://app.mantyx.io";
299
+ interface MantyxClientOptions {
300
+ apiKey: string;
301
+ workspaceSlug: string;
302
+ /** Defaults to `https://app.mantyx.io`. Override for self-hosted instances. */
303
+ baseUrl?: string;
304
+ /** Optional `fetch` override (e.g. node-fetch wrapper, or a custom HTTP client). */
305
+ fetch?: typeof fetch;
306
+ /** Default per-request timeout in milliseconds. Default: 60s. */
307
+ timeoutMs?: number;
308
+ }
309
+ interface ModelInfo {
310
+ id: string;
311
+ label: string;
312
+ provider: string;
313
+ vendorModelId: string;
314
+ source: "workspace_provider" | "platform_offering";
315
+ contextWindowTokens: number | null;
316
+ pricing: {
317
+ inputPer1MUsd: number | null;
318
+ outputPer1MUsd: number | null;
319
+ cacheReadPer1MUsd: number | null;
320
+ } | null;
321
+ }
322
+ interface ModelCatalog {
323
+ models: ModelInfo[];
324
+ defaultModelId: string | null;
325
+ }
326
+ interface AgentSpecBase {
327
+ name?: string;
328
+ /**
329
+ * Reference to a persisted MANTYX agent in this workspace. When set, the
330
+ * server hydrates `systemPrompt`, `modelId`, and the agent's own tools
331
+ * (memory, skills, plugin tools, …) from the Agent row at run time, and any
332
+ * `tools` you supply here are merged on top — typically `local` tools the
333
+ * SDK wants the agent to be able to call back into.
334
+ *
335
+ * Either `agentId` or `systemPrompt` must be set.
336
+ */
337
+ agentId?: string;
338
+ /** Required unless `agentId` is set. */
339
+ systemPrompt?: string;
340
+ modelId?: string;
341
+ tools?: ToolRef[];
342
+ /**
343
+ * Provider thinking strength: a string anchor (`"off" | "low" | "medium" |
344
+ * "high"`) or an integer in `0..100` (where `0` explicitly disables provider
345
+ * thinking on reasoning models). The server maps this onto each LLM's
346
+ * native dial — see `docs/agent-runs-protocol.md` §4.4.
347
+ *
348
+ * For session-scoped runs the session value sets the default; per-message
349
+ * overrides on `session.send` apply to that single run.
350
+ */
351
+ reasoningLevel?: ReasoningLevel;
352
+ budgets?: {
353
+ maxToolTurns?: number;
354
+ };
355
+ /**
356
+ * Constrains the model's **final assistant text** to a JSON document
357
+ * matching a JSON Schema. The terminal `result` event still carries the
358
+ * reply as `text: string`, but that string is guaranteed-parseable JSON.
359
+ *
360
+ * `name` (optional) is a stable identifier the server forwards to the
361
+ * provider (OpenAI `text.format.name`, Anthropic synthetic-tool name).
362
+ * Defaults to `"output"`. Must match `/^[a-zA-Z0-9_-]{1,64}$/`.
363
+ *
364
+ * `schema` is a JSON Schema describing the final assistant text. Its
365
+ * root must be a JSON **object** — most providers reject array / scalar
366
+ * roots in structured-output mode. The schema is shipped verbatim;
367
+ * MANTYX does not validate its contents (the provider does).
368
+ *
369
+ * Use {@link parseRunOutput} on the resulting `RunResult` to JSON.parse
370
+ * the reply (and optionally re-validate against your own zod / typebox /
371
+ * ajv schema). See `docs/wire-protocol.md` §7.
372
+ */
373
+ outputSchema?: OutputSchema;
374
+ /**
375
+ * Flat string→string KV carried alongside the run / session for
376
+ * observability. Use it to tag runs with your own application identifiers
377
+ * (customer id, environment, workflow name, …) — the values are visible in
378
+ * the MANTYX dashboard and can be filtered there.
379
+ *
380
+ * Limits enforced server-side: max 16 entries; keys match
381
+ * `[A-Za-z0-9._-]{1,64}`; values are strings ≤ 256 chars; serialized JSON
382
+ * ≤ 4 KB. For session-scoped runs, the session's metadata is inherited and
383
+ * any per-message override is merged on top.
384
+ */
385
+ metadata?: Record<string, string>;
386
+ }
387
+ interface RunSpec extends AgentSpecBase {
388
+ prompt?: string;
389
+ messages?: Array<{
390
+ role: "user" | "assistant" | "system";
391
+ content: string;
392
+ }>;
393
+ /** Receives streaming assistant text deltas. */
394
+ onAssistantDelta?: (delta: string) => void;
395
+ /** Receives raw events (assistant_message, local_tool_call, tool_result, ...) for advanced consumers. */
396
+ onEvent?: (event: RunEvent) => void;
397
+ /** Aborts the run on the client and best-effort cancels server-side. */
398
+ signal?: AbortSignal;
399
+ }
400
+ type SessionSpec = AgentSpecBase;
401
+ /**
402
+ * Constrains the final assistant text to a JSON document matching a
403
+ * JSON Schema. See {@link AgentSpecBase.outputSchema} for the full
404
+ * semantics.
405
+ */
406
+ interface OutputSchema {
407
+ /** Optional. Defaults to `"output"`. Must match `/^[a-zA-Z0-9_-]{1,64}$/`. */
408
+ name?: string;
409
+ /** Required. JSON Schema describing the final assistant text. Root must be a JSON object. */
410
+ schema: Record<string, unknown>;
411
+ }
412
+ interface RunResult {
413
+ runId: string;
414
+ text: string;
415
+ events: RunEvent[];
416
+ }
417
+ interface RunEventBase {
418
+ seq: number;
419
+ type: string;
420
+ }
421
+ interface AssistantDeltaEvent extends RunEventBase {
422
+ type: "assistant_delta";
423
+ text: string;
424
+ }
425
+ interface ThinkingDeltaEvent extends RunEventBase {
426
+ type: "thinking_delta";
427
+ text: string;
428
+ }
429
+ interface AssistantMessageEvent extends RunEventBase {
430
+ type: "assistant_message";
431
+ text: string;
432
+ }
433
+ interface ServerToolResultEvent extends RunEventBase {
434
+ type: "tool_result";
435
+ name: string;
436
+ args?: Record<string, unknown>;
437
+ ok?: boolean;
438
+ summary?: string;
439
+ phase?: "start" | "end";
440
+ }
441
+ interface LocalToolCallEvent extends RunEventBase {
442
+ type: "local_tool_call";
443
+ toolUseId: string;
444
+ /**
445
+ * The model-facing tool name. For `kind: "mcp_local"` events this is the
446
+ * `<server>_<tool>` name the SDK declared on the wire; the SDK looks up
447
+ * the local MCP server via `mcpServer` and forwards `mcpToolName` to
448
+ * `tools/call` rather than parsing the prefix itself.
449
+ */
450
+ name: string;
451
+ args: Record<string, unknown>;
452
+ /**
453
+ * Discriminator for which client-resolved handler should run.
454
+ * - `"local"` (or omitted) — generic local tool
455
+ * - `"a2a_local"` — local Agent2Agent peer
456
+ * - `"mcp_local"` — local MCP server tool
457
+ */
458
+ kind?: "local" | "a2a_local" | "mcp_local";
459
+ /**
460
+ * Present on `kind: "a2a_local"` — the full A2A Agent Card the SDK shipped
461
+ * with the spec, echoed back unchanged. Surfaced for advanced consumers
462
+ * (`onEvent` / `streamAgent` callers); the built-in dispatcher ignores it
463
+ * because it already has the cached card from the original
464
+ * `defineLocalA2A` resolution.
465
+ */
466
+ agentCard?: {
467
+ name: string;
468
+ url?: string;
469
+ [k: string]: unknown;
470
+ };
471
+ /** Present on `kind: "mcp_local"` — server label declared via `defineLocalMcp`. */
472
+ mcpServer?: string;
473
+ /**
474
+ * Present on `kind: "mcp_local"` — the model-facing tool name as declared on
475
+ * the wire. Always equals `name`; surfaced as a separate field for the SDK's
476
+ * convenience when dispatching into a local MCP client.
477
+ */
478
+ mcpToolName?: string;
479
+ /**
480
+ * Present on `kind: "mcp_local"` — the verbatim `Implementation` block from
481
+ * MCP `Initialize`, echoed back for observability.
482
+ */
483
+ mcpServerInfo?: {
484
+ name: string;
485
+ version?: string;
486
+ [k: string]: unknown;
487
+ };
488
+ }
489
+ interface LocalToolResultInEvent extends RunEventBase {
490
+ type: "local_tool_result_in";
491
+ toolUseId: string;
492
+ result?: string;
493
+ error?: string;
494
+ }
495
+ interface ResultEvent extends RunEventBase {
496
+ type: "result";
497
+ subtype: string;
498
+ text?: string;
499
+ error?: string;
500
+ }
501
+ interface ErrorEvent extends RunEventBase {
502
+ type: "error";
503
+ error: string;
504
+ code?: string;
505
+ }
506
+ interface CancelledEvent extends RunEventBase {
507
+ type: "cancelled";
508
+ reason?: string;
509
+ }
510
+ type RunEvent = AssistantDeltaEvent | ThinkingDeltaEvent | AssistantMessageEvent | ServerToolResultEvent | LocalToolCallEvent | LocalToolResultInEvent | ResultEvent | ErrorEvent | CancelledEvent | (RunEventBase & {
511
+ type: string;
512
+ [key: string]: unknown;
513
+ });
514
+ interface SessionInfo {
515
+ id: string;
516
+ name: string;
517
+ status: "active" | "ended";
518
+ createdAt: string;
519
+ lastUsedAt: string;
520
+ endedAt: string | null;
521
+ agentSpec: AgentSpecBase;
522
+ messages: Array<{
523
+ role: "user" | "assistant" | "system";
524
+ content: string;
525
+ }>;
526
+ /** Metadata that was attached to the session at create time, returned for observability. */
527
+ metadata: Record<string, string>;
528
+ }
529
+ declare class MantyxClient {
530
+ readonly options: Required<Pick<MantyxClientOptions, "apiKey" | "workspaceSlug" | "baseUrl">> & {
531
+ fetch: typeof fetch;
532
+ timeoutMs: number;
533
+ };
534
+ constructor(opts: MantyxClientOptions);
535
+ listModels(): Promise<ModelCatalog>;
536
+ runAgent(spec: RunSpec): Promise<RunResult>;
537
+ streamAgent(spec: RunSpec): AsyncGenerator<RunEvent, void, void>;
538
+ /**
539
+ * Internal registry of client-resolved tool handlers. Exposed for callers
540
+ * who drive the run loop manually via `driveRun` / `streamRunEvents`.
541
+ */
542
+ collectHandlers(tools: ToolRef[]): LocalHandlers;
543
+ createSession(spec: SessionSpec): Promise<AgentSession>;
544
+ /**
545
+ * Re-emit a `local_tool_call` event into the right local handler. Useful
546
+ * for tests and for users who consume events via `streamAgent` themselves.
547
+ */
548
+ dispatchLocalToolFromEvent(runId: string, ev: LocalToolCallEvent, handlers: LocalHandlers): Promise<void>;
549
+ resumeSession(sessionId: string, opts?: {
550
+ tools?: ToolRef[];
551
+ }): Promise<AgentSession>;
552
+ endSession(sessionId: string): Promise<void>;
553
+ getSessionInfo(sessionId: string): Promise<SessionInfo>;
554
+ /** Drive an existing run to completion (collect events, dispatch local tools). */
555
+ driveRun(runId: string, handlers: LocalHandlers, opts?: {
556
+ onAssistantDelta?: (delta: string) => void;
557
+ onEvent?: (event: RunEvent) => void;
558
+ signal?: AbortSignal;
559
+ }): Promise<RunResult>;
560
+ streamRunEvents(runId: string, handlers: LocalHandlers, signal?: AbortSignal): AsyncGenerator<RunEvent, void, void>;
561
+ dispatchLocalTool(runId: string, ev: LocalToolCallEvent, handlers: LocalHandlers): Promise<void>;
562
+ postToolResult(runId: string, toolUseId: string, payload: {
563
+ result?: string;
564
+ error?: string;
565
+ }): Promise<void>;
566
+ cancelRun(runId: string): Promise<void>;
567
+ private absoluteUrl;
568
+ private authHeaders;
569
+ request<T>(args: {
570
+ method: string;
571
+ path: string;
572
+ body?: unknown;
573
+ timeoutMs?: number;
574
+ }): Promise<T>;
575
+ private errorFromResponse;
576
+ }
577
+ declare class AgentSession {
578
+ readonly id: string;
579
+ readonly client: MantyxClient;
580
+ private readonly handlers;
581
+ private readonly tools;
582
+ constructor(client: MantyxClient, id: string, handlers: LocalHandlers, tools?: ToolRef[]);
583
+ send(prompt: string, opts?: {
584
+ onAssistantDelta?: (s: string) => void;
585
+ signal?: AbortSignal;
586
+ /**
587
+ * Per-message metadata override. Server-side this is merged on top of
588
+ * the session's metadata at run-creation time (run-level keys win).
589
+ * Useful for tagging individual turns (e.g. `{ "trace_id": "abc" }`).
590
+ */
591
+ metadata?: Record<string, string>;
592
+ /**
593
+ * Per-message override for `reasoningLevel`. Applies only to this run
594
+ * and does not mutate the session's stored value.
595
+ */
596
+ reasoningLevel?: ReasoningLevel;
597
+ /**
598
+ * Per-message override for `outputSchema`. Applies only to this run
599
+ * and does not mutate the session's stored value.
600
+ */
601
+ outputSchema?: OutputSchema;
602
+ }): Promise<RunResult>;
603
+ stream(prompt: string, opts?: {
604
+ signal?: AbortSignal;
605
+ metadata?: Record<string, string>;
606
+ reasoningLevel?: ReasoningLevel;
607
+ outputSchema?: OutputSchema;
608
+ }): AsyncGenerator<RunEvent, void, void>;
609
+ private buildSessionMessageBody;
610
+ history(): Promise<Array<{
611
+ role: "user" | "assistant" | "system";
612
+ content: string;
613
+ }>>;
614
+ info(): Promise<SessionInfo>;
615
+ end(): Promise<void>;
616
+ }
617
+ /** Internal registry of client-resolved handlers, indexed by `kind`. */
618
+ interface LocalHandlers {
619
+ /** `kind: "local"` — generic local tools, indexed by tool name. */
620
+ localTools: Map<string, LocalTool>;
621
+ /** `kind: "a2a_local"` — local A2A peers, indexed by tool name. */
622
+ a2aTools: Map<string, LocalA2ATool>;
623
+ /** `kind: "mcp_local"` — local MCP servers, indexed by server name. */
624
+ mcpServers: Map<string, LocalMcpServer>;
625
+ }
626
+ /**
627
+ * Parse the terminal text of a `RunResult` as JSON.
628
+ *
629
+ * When the run was submitted with `outputSchema`, MANTYX (via the LLM
630
+ * provider) guarantees the reply parses as JSON in the *vast* majority of
631
+ * cases. Transient model errors (refusal text, truncation under
632
+ * `max_tokens` pressure, exotic Unicode) can still produce strings that
633
+ * fail to `JSON.parse` in rare edge cases — this helper centralises that
634
+ * brittle step and surfaces a typed {@link MantyxParseError} on failure
635
+ * with the original text preserved on `err.text`.
636
+ *
637
+ * Pass an optional `validator` (zod's `.parse`, an Ajv compiled validator,
638
+ * or any function) to re-validate against your source-of-truth schema. The
639
+ * validator's return value (or thrown error) is forwarded to the caller.
640
+ *
641
+ * @example
642
+ * ```ts
643
+ * import { z } from "zod";
644
+ * import { parseRunOutput } from "@mantyx/sdk";
645
+ *
646
+ * const Schema = z.object({ city: z.string(), temperature_c: z.number() });
647
+ * const result = await client.runAgent({
648
+ * systemPrompt: "...",
649
+ * prompt: "What's the weather in SF?",
650
+ * outputSchema: { name: "weather_report", schema: weatherJsonSchema },
651
+ * });
652
+ * const report = parseRunOutput(result, Schema.parse.bind(Schema));
653
+ * // ^? { city: string; temperature_c: number }
654
+ * ```
655
+ */
656
+ declare function parseRunOutput<T = unknown>(result: RunResult, validator?: (value: unknown) => T): T;
657
+
658
+ export { type A2AToolRef as A, type RunSpec as B, type CancelledEvent as C, DEFAULT_BASE_URL as D, type ErrorEvent as E, type SessionInfo as F, type SessionSpec as G, type ThinkingDeltaEvent as H, defineLocalA2A as I, defineLocalMcp as J, defineLocalTool as K, type LocalA2ATool as L, MantyxClient as M, isLocalA2ATool as N, type OutputSchema as O, isLocalMcpServer as P, isLocalTool as Q, type ReasoningLevel as R, type ServerToolResultEvent as S, type ToolRef as T, mantyxA2A as U, mantyxMcp as V, mantyxPluginTool as W, mantyxTool as X, parseRunOutput as Y, type ZodLikeObject as Z, AgentSession as a, type AgentSpecBase as b, type AssistantDeltaEvent as c, type AssistantMessageEvent as d, type DefineLocalA2AOptions as e, type DefineLocalMcpOptions as f, type DefineLocalToolOptions as g, type LocalHandlers as h, type LocalMcpHttpTransport as i, type LocalMcpServer as j, type LocalMcpStdioTransport as k, type LocalTool as l, type LocalToolCallEvent as m, type LocalToolResultInEvent as n, type MantyxA2AOptions as o, type MantyxClientOptions as p, type MantyxMcpOptions as q, type MantyxPluginToolRef as r, type MantyxToolRef as s, type McpToolRef as t, type ModelCatalog as u, type ModelInfo as v, type ResultEvent as w, type RunEvent as x, type RunEventBase as y, type RunResult as z };