@mantyx/sdk 0.21.0 → 0.22.1

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/a2a-server.cjs.map +1 -1
  3. package/dist/a2a-server.d.ts +13 -16
  4. package/dist/a2a-server.d.ts.map +1 -0
  5. package/dist/a2a-server.js +1 -1
  6. package/dist/{chunk-QMUVI3Y3.js → chunk-STB4Z6F4.js} +54 -8
  7. package/dist/chunk-STB4Z6F4.js.map +1 -0
  8. package/dist/{client-C7TzTpNW.d.ts → client.d.ts} +83 -831
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/{computer-use-4QzI3lGU.d.ts → computer-use.d.ts} +21 -22
  11. package/dist/computer-use.d.ts.map +1 -0
  12. package/dist/errors.d.ts +153 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/index.cjs +54 -8
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +44 -55
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +2 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/local-resolver.d.ts +49 -0
  21. package/dist/local-resolver.d.ts.map +1 -0
  22. package/dist/oauth.d.ts +189 -0
  23. package/dist/oauth.d.ts.map +1 -0
  24. package/dist/playwright.d.ts +6 -11
  25. package/dist/playwright.d.ts.map +1 -0
  26. package/dist/sse.d.ts +27 -0
  27. package/dist/sse.d.ts.map +1 -0
  28. package/dist/tools.d.ts +426 -0
  29. package/dist/tools.d.ts.map +1 -0
  30. package/dist/version.d.ts +5 -0
  31. package/dist/version.d.ts.map +1 -0
  32. package/dist/zod-to-json-schema.d.ts +25 -0
  33. package/dist/zod-to-json-schema.d.ts.map +1 -0
  34. package/package.json +11 -11
  35. package/dist/a2a-server.d.cts +0 -176
  36. package/dist/chunk-QMUVI3Y3.js.map +0 -1
  37. package/dist/client-C7TzTpNW.d.cts +0 -2033
  38. package/dist/computer-use-1m6E_VIl.d.cts +0 -193
  39. package/dist/index.d.cts +0 -61
  40. package/dist/playwright.d.cts +0 -88
@@ -1,2033 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- /**
4
- * Error types raised by the MANTYX SDK.
5
- */
6
- declare class MantyxError extends Error {
7
- readonly code: string;
8
- readonly status: number | undefined;
9
- readonly hint: string | undefined;
10
- constructor(message: string, opts?: {
11
- code?: string;
12
- status?: number;
13
- hint?: string;
14
- });
15
- }
16
- declare class MantyxNetworkError extends MantyxError {
17
- constructor(message: string, opts?: {
18
- cause?: unknown;
19
- });
20
- }
21
- declare class MantyxAuthError extends MantyxError {
22
- constructor(message?: string);
23
- }
24
- /**
25
- * Raised on `403 insufficient_scope`, returned when an OAuth access token
26
- * is missing one of the scopes a route demands (see
27
- * `docs/agent-runs-protocol.md` §2.2 for the per-endpoint table).
28
- *
29
- * `requiredScopes` carries the verbatim `required` value from the
30
- * server's response — a single scope for most routes, an array when the
31
- * route demands more than one. The SDK is expected to surface this so
32
- * callers can drive a re-consent flow (e.g. "please re-authorise the
33
- * app with `sessions:write` enabled").
34
- *
35
- * Workspace API keys never trip this error — they carry no granular
36
- * scopes. It is OAuth-only.
37
- */
38
- declare class MantyxScopeError extends MantyxError {
39
- /**
40
- * Scope(s) the route demanded. Always at least one entry; usually
41
- * exactly one. New routes may demand more scopes in the future.
42
- */
43
- readonly requiredScopes: readonly string[];
44
- constructor(message: string, requiredScopes: readonly string[]);
45
- }
46
- declare class MantyxToolError extends MantyxError {
47
- readonly toolName: string;
48
- constructor(toolName: string, message: string);
49
- }
50
- /**
51
- * Per-run token totals attached to terminal `result` / `error`
52
- * events. See `docs/agent-runs-protocol.md` §7.1 for the per-provider
53
- * mapping and the relationship between buckets. Re-exported from
54
- * `client.ts` so error consumers can pattern-match the triple without
55
- * a second import.
56
- */
57
- interface MantyxRunErrorTokens {
58
- inputTokens: number;
59
- cachedTokens: number;
60
- reasoningTokens: number;
61
- outputTokens: number;
62
- }
63
- /**
64
- * Resolved model that executed the run. Surfaced on terminal events
65
- * by MANTYX ≥ 2026-09. See `docs/agent-runs-protocol.md` §7.1. The
66
- * `provider` empty / undefined is the "no usage data" sentinel.
67
- */
68
- interface MantyxRunErrorModel {
69
- id: string;
70
- provider: string;
71
- vendorModelId: string;
72
- reasoningEffort?: string;
73
- }
74
- /**
75
- * Optional triage attributes the runner attaches to terminal `error`
76
- * events. Mirrors the wire fields described in
77
- * `docs/agent-runs-protocol.md` §7 ("error event payload fields") so SDK
78
- * callers can render structured UI status notes ("model truncated — JSON
79
- * likely incomplete") and drive retry policy without re-parsing the
80
- * human-readable `message`.
81
- */
82
- interface MantyxRunErrorInit {
83
- /**
84
- * Canonical category of failure. One of `"rate_limit"`, `"overloaded"`,
85
- * `"server"`, `"context_window"`, `"truncation"`, `"invalid_request"`,
86
- * `"auth"`, `"timeout"`, `"local_timeout"`, `"upstream_deadline"`,
87
- * `"unknown"`. New categories may land additively — callers should
88
- * default-branch to `"unknown"` for unrecognized values.
89
- */
90
- errorClass?: string;
91
- /**
92
- * Canonical lowercase stop reason normalized across providers
93
- * (`"max_tokens"`, `"refusal"`, `"malformed_function_call"`, …). When
94
- * present, mirrors the value carried on the last `assistant_message`
95
- * event preceding the failure.
96
- */
97
- finishReason?: string | null;
98
- /**
99
- * **Best-effort raw bytes** the model emitted before the failure. For
100
- * `outputSchema` runs this is likely **incomplete JSON** that will
101
- * fail `JSON.parse` — treat it as diagnostic data, never as a
102
- * schema-conformant reply.
103
- */
104
- partialText?: string;
105
- /**
106
- * Coarse retry hint inherited from the pipeline's error classifier.
107
- * Informational; the SDK still owns the actual retry decision.
108
- */
109
- retryable?: boolean;
110
- /**
111
- * Per-run token totals from the terminal event. Present against
112
- * MANTYX ≥ 2026-09 — see {@link MantyxRunErrorTokens} and
113
- * `docs/agent-runs-protocol.md` §7.1. Includes the failing model
114
- * call's usage when the run errored mid-loop.
115
- */
116
- tokens?: MantyxRunErrorTokens;
117
- /** Total model invocations for the run, including the failing call. */
118
- turns?: number;
119
- /** Resolved model that executed the run. See {@link MantyxRunErrorModel}. */
120
- model?: MantyxRunErrorModel;
121
- }
122
- declare class MantyxRunError extends MantyxError {
123
- readonly runId: string;
124
- readonly subtype: string;
125
- /** See {@link MantyxRunErrorInit.errorClass}. */
126
- readonly errorClass: string | undefined;
127
- /** See {@link MantyxRunErrorInit.finishReason}. */
128
- readonly finishReason: string | null | undefined;
129
- /** See {@link MantyxRunErrorInit.partialText}. */
130
- readonly partialText: string | undefined;
131
- /** See {@link MantyxRunErrorInit.retryable}. */
132
- readonly retryable: boolean | undefined;
133
- /** See {@link MantyxRunErrorInit.tokens}. */
134
- readonly tokens: MantyxRunErrorTokens | undefined;
135
- /** See {@link MantyxRunErrorInit.turns}. */
136
- readonly turns: number | undefined;
137
- /** See {@link MantyxRunErrorInit.model}. */
138
- readonly model: MantyxRunErrorModel | undefined;
139
- constructor(runId: string, subtype: string, message: string, init?: MantyxRunErrorInit);
140
- }
141
- /**
142
- * Thrown by {@link parseRunOutput} when the run's terminal text was supposed
143
- * to be a JSON document (because `outputSchema` was set on the spec) but
144
- * either failed to JSON.parse or failed the user-supplied validator.
145
- *
146
- * The original `text` is preserved on the `text` field so callers can log
147
- * the raw model output for debugging.
148
- */
149
- declare class MantyxParseError extends MantyxError {
150
- readonly text: string;
151
- constructor(message: string, text: string, opts?: {
152
- cause?: unknown;
153
- });
154
- }
155
-
156
- /**
157
- * MANTYX OAuth 2.0 refresh client: trade a stored refresh token for
158
- * short-lived access tokens, revoke tokens at sign-out, and expose
159
- * a {@link TokenSource} the {@link MantyxClient} HTTP layer calls
160
- * before every request (and again on 401).
161
- *
162
- * The library is intentionally **refresh-only**. It assumes the caller
163
- * already obtained the refresh token through their own sign-in flow
164
- * (Authorization Code + PKCE in a browser, native redirect, server-
165
- * side exchange — whatever fits the host application). The SDK does
166
- * not drive consent, does not initiate auth-code exchanges, and does
167
- * not bundle PKCE helpers.
168
- *
169
- * Wire contract (`docs/oauth.md`):
170
- *
171
- * - Token endpoint: `POST <baseUrl>/api/oauth/token`, form-encoded,
172
- * `grant_type=refresh_token`. Echoes back the same `refresh_token`
173
- * the client sent (refresh tokens are persistent and non-rotating).
174
- * - Revoke endpoint: `POST <baseUrl>/api/oauth/revoke`, form-encoded.
175
- * - Access tokens (`mantyx_at_…`) live 1 hour (`expires_in: 3600`).
176
- * - Refresh tokens (`mantyx_rt_…`) are long-lived; the caller persists
177
- * them once at first sign-in (encrypted at rest) and the SDK re-mints
178
- * access tokens from the same value on demand.
179
- */
180
-
181
- declare const DEFAULT_OAUTH_BASE_URL = "https://app.mantyx.io";
182
- /** Skew (ms) before `expiresAt` at which a TokenSource will pre-emptively refresh. Default 60s. */
183
- declare const DEFAULT_REFRESH_SKEW_MS = 60000;
184
- /**
185
- * Raised on a non-2xx response from `POST /api/oauth/token` or
186
- * `POST /api/oauth/revoke`. Carries the RFC 6749 `error` discriminator
187
- * (`"invalid_grant"`, `"invalid_client"`, `"unsupported_grant_type"`,
188
- * …) and the optional `error_description` so callers can branch on
189
- * machine-readable values without parsing the human message.
190
- *
191
- * `invalid_grant` from the refresh path specifically signals that the
192
- * refresh token has been revoked (or the OAuth grant / application
193
- * was deleted). The SDK never loops on this — callers should route
194
- * the user back to a fresh sign-in.
195
- */
196
- declare class MantyxOAuthError extends MantyxError {
197
- readonly oauthError: string;
198
- readonly oauthErrorDescription: string | undefined;
199
- constructor(oauthError: string, oauthErrorDescription: string | undefined, status: number);
200
- }
201
- /**
202
- * Decoded `POST /api/oauth/token` response, augmented with an absolute
203
- * `expiresAt` timestamp the SDK uses to decide when to refresh.
204
- *
205
- * On the refresh grant the response's `refreshToken` is identical to
206
- * the value the client just sent (refresh tokens never rotate). The
207
- * field is surfaced for symmetry with whatever the calling app's
208
- * sign-in flow already does.
209
- */
210
- interface OAuthToken {
211
- readonly accessToken: string;
212
- readonly refreshToken: string | undefined;
213
- readonly tokenType: string;
214
- readonly expiresIn: number;
215
- /** Absolute Unix-ms timestamp set when the SDK parsed the response. */
216
- readonly expiresAt: number;
217
- readonly scope: string | undefined;
218
- }
219
- /** Why the SDK asked the {@link TokenSource} for the current access token. */
220
- type TokenRequestReason = "initial" | "expired" | "unauthorized";
221
- /**
222
- * A `TokenSource` produces the current access token on demand. The
223
- * {@link MantyxClient} HTTP layer calls it before every request. When
224
- * called with `reason: "unauthorized"` the source MUST force a refresh
225
- * (do not return a cached value); this is how the SDK recovers from
226
- * 401s caused by a token that the server already invalidated.
227
- *
228
- * Implementations should be safe to call from many concurrent requests.
229
- */
230
- type TokenSource = (reason?: TokenRequestReason) => Promise<string>;
231
- /** Caller-supplied options for `MantyxOAuthClient`. */
232
- interface MantyxOAuthClientOptions {
233
- /**
234
- * OAuth `client_id` issued at app registration (token prefix
235
- * `mantyx_oa_`).
236
- */
237
- clientId: string;
238
- /**
239
- * OAuth `client_secret` issued at app registration (token prefix
240
- * `mantyx_oas_`). Every MANTYX OAuth app is a confidential client,
241
- * so this is always required for token + revoke calls. Treat as a
242
- * deployment secret — do not bundle into browser builds.
243
- */
244
- clientSecret: string;
245
- /**
246
- * Origin of the MANTYX deployment. Defaults to `https://app.mantyx.io`.
247
- * The OAuth endpoints are mounted at `<baseUrl>/api/oauth/...`.
248
- */
249
- baseUrl?: string;
250
- /** Optional `fetch` override (e.g. node-fetch wrapper). Default: global `fetch`. */
251
- fetch?: typeof fetch;
252
- /** Default per-request timeout in milliseconds. Default: 30s. */
253
- timeoutMs?: number;
254
- }
255
- interface RefreshOptions {
256
- refreshToken: string;
257
- /**
258
- * Optional scope narrowing. Must be a subset of the scopes already
259
- * granted to the refresh token (server enforces this). Useful when
260
- * an SDK consumer wants a short-scope access token for a specific
261
- * sub-operation.
262
- */
263
- scope?: string | readonly string[];
264
- }
265
- interface RevokeOptions {
266
- token: string;
267
- }
268
- interface RefreshTokenSourceOptions {
269
- refreshToken: string;
270
- /** Optional scope narrowing applied on every refresh. */
271
- scope?: string | readonly string[];
272
- /**
273
- * How many ms before `expiresAt` the source proactively refreshes.
274
- * Defaults to {@link DEFAULT_REFRESH_SKEW_MS} (60s).
275
- */
276
- refreshSkewMs?: number;
277
- /**
278
- * Optional initial access token + expiry to seed the source's cache
279
- * with (e.g. the token already in hand from the host application's
280
- * sign-in flow). When omitted, the source mints one on the first
281
- * call.
282
- */
283
- initialToken?: OAuthToken;
284
- }
285
- /**
286
- * Refresh-only wrapper around the MANTYX OAuth 2.0 authorization-server
287
- * endpoints. App-scoped (one per `{clientId, clientSecret}` pair);
288
- * construct independently of {@link MantyxClient}, then either call
289
- * {@link refresh} / {@link revoke} directly or hand a `TokenSource`
290
- * produced by {@link refreshTokenSource} to `MantyxClient` for fully
291
- * transparent refresh on every request.
292
- *
293
- * The client deliberately does **not** drive the authorization-code
294
- * exchange or any other "initiate sign-in" grant. The caller is
295
- * expected to obtain the refresh token through their own consent flow
296
- * and persist it before constructing this client.
297
- */
298
- declare class MantyxOAuthClient {
299
- readonly clientId: string;
300
- readonly baseUrl: string;
301
- private readonly clientSecret;
302
- private readonly fetchImpl;
303
- private readonly timeoutMs;
304
- constructor(opts: MantyxOAuthClientOptions);
305
- /**
306
- * Mint a fresh access token from a stored refresh token. The
307
- * returned `refreshToken` is identical to the input — refresh
308
- * tokens are persistent and non-rotating, so the field is
309
- * surfaced only for symmetry with the response shape.
310
- *
311
- * On `400 invalid_grant` the refresh token has been revoked (or its
312
- * grant / app was deleted); the SDK surfaces a
313
- * {@link MantyxOAuthError} and callers must drive a fresh sign-in.
314
- */
315
- refresh(opts: RefreshOptions): Promise<OAuthToken>;
316
- /**
317
- * Revoke an access or refresh token (RFC 7009). The server always
318
- * returns 200, even for unknown tokens. Revoking a **refresh**
319
- * token kills the refresh and every live access token tied to its
320
- * grant; revoking an **access** token kills only that one.
321
- */
322
- revoke(opts: RevokeOptions): Promise<void>;
323
- /**
324
- * Build a long-lived {@link TokenSource} that re-mints access
325
- * tokens from the supplied refresh token. Pass the returned source
326
- * to `new MantyxClient({ tokenSource, workspaceSlug, ... })`. The
327
- * source caches the access token in-memory and refreshes
328
- * proactively when the cached value is within `refreshSkewMs` of
329
- * `expiresAt`, or eagerly when `MantyxClient` reports a 401.
330
- *
331
- * Pass `initialToken` if the calling app already has a non-expired
332
- * access token in hand (e.g. straight out of the sign-in flow) to
333
- * avoid an extra round-trip on the first request.
334
- */
335
- refreshTokenSource(opts: RefreshTokenSourceOptions): TokenSource;
336
- /**
337
- * POST `application/x-www-form-urlencoded` to `/api/oauth/token` and
338
- * decode the {@link OAuthToken} response. Always injects `client_id`
339
- * + `client_secret` from the constructor.
340
- */
341
- private token;
342
- private formPost;
343
- }
344
-
345
- /**
346
- * Public tool helpers for the MANTYX SDK.
347
- *
348
- * Server-resolved (executed by MANTYX):
349
- * mantyxTool(id) → existing workspace `Tool` row by id
350
- * mantyxPluginTool(name) → built-in plugin tool by `@plugin/tool` name
351
- * mantyxA2A({...}) → remote Agent2Agent peer, dialed by MANTYX
352
- * mantyxMcp({...}) → remote MCP server (Streamable HTTP), proxied by MANTYX
353
- *
354
- * Client-resolved (executed in this process; the SDK shuttles inputs and
355
- * outputs over the agent loop):
356
- * defineLocalTool({...}) → generic local tool with a Zod parameter schema
357
- * defineLocalA2A({...}) → A2A peer the SDK can reach but MANTYX cannot —
358
- * pass an `agentCardUrl`; the SDK fetches the
359
- * Agent Card and speaks A2A `message/send` for you.
360
- * defineLocalMcp({...}) → MCP server the SDK manages — pass either a
361
- * Streamable HTTP `url` or a stdio
362
- * `command`; the SDK runs `Initialize` +
363
- * `tools/list` and forwards `tools/call` for you.
364
- *
365
- * The server emits a `local_tool_call` event for every client-resolved
366
- * invocation. The event carries a `kind` discriminator (`"local"` is implied
367
- * when omitted, `"a2a_local"` and `"mcp_local"` are explicit) so the SDK can
368
- * dispatch to the right handler.
369
- */
370
-
371
- type ZodLikeObject = z.ZodType<Record<string, unknown>> & {
372
- _def?: unknown;
373
- parse?: (value: unknown) => unknown;
374
- };
375
- /**
376
- * Provider-thinking knob, mapped server-side onto each LLM's native dial:
377
- * `reasoning.effort` (OpenAI), `thinkingConfig.thinkingLevel` / `thinkingBudget`
378
- * (Gemini), or extended-thinking budget (Anthropic / Bedrock-Anthropic).
379
- *
380
- * Pass either a string anchor (`"off" | "low" | "medium" | "high"`) or an
381
- * integer in `0..100` (where `0` explicitly disables provider thinking).
382
- */
383
- type ReasoningLevel = "off" | "low" | "medium" | "high" | number;
384
- /**
385
- * A file produced by a client-resolved tool, returned alongside the textual
386
- * `result`. The bytes are surfaced to the model on the next turn as native
387
- * file parts (Anthropic / Gemini / Bedrock inside the `tool_result`; OpenAI
388
- * as a synthetic follow-up user turn) — the same pipeline used by
389
- * server-resolved tools that return files.
390
- *
391
- * Limits (enforced server-side): up to 20 files per result, `mimeType` must
392
- * be an allowed attachment type, and the combined decoded size is capped
393
- * (currently 5 MB). Files over the inline threshold are persisted to object
394
- * storage and forwarded by reference. For larger artifacts, upload them out
395
- * of band and reference a URL in `result` instead. See
396
- * `docs/agent-runs-protocol.md` §8 and `docs/wire-protocol.md` §4.
397
- */
398
- interface ToolResultFile {
399
- /** Display filename surfaced to the model (e.g. `"chart.png"`). */
400
- filename: string;
401
- /** Allowed attachment MIME type (e.g. `"image/png"`, `"text/plain"`). */
402
- mimeType: string;
403
- /** Base64-encoded file bytes — **no** `data:` URL prefix. */
404
- data: string;
405
- }
406
- /**
407
- * Rich return value for a {@link LocalTool}'s `execute`. Return this (instead
408
- * of a bare string) when the tool needs to hand files back to the model in
409
- * addition to — or instead of — its textual result.
410
- *
411
- * `result` is the same string a tool would normally return; omit it (or pass
412
- * the empty string) when the files are the whole payload. `files` is ignored
413
- * when the tool throws — errors are surfaced to the model as a tool-error
414
- * response with no attachments.
415
- */
416
- interface LocalToolResult {
417
- /** Textual result. Optional when `files` carries the payload. */
418
- result?: string;
419
- /** Files to surface to the model on the next turn. */
420
- files?: ToolResultFile[];
421
- }
422
- /**
423
- * What a {@link LocalTool}'s `execute` may return: a bare string (the common
424
- * case) or a {@link LocalToolResult} carrying files. Non-string, non-result
425
- * values are JSON-serialized by the SDK before being posted back.
426
- */
427
- type LocalToolOutput = string | LocalToolResult;
428
- /**
429
- * Either a Zod schema (auto-converted to JSON Schema by the SDK) or a
430
- * pre-shaped JSON Schema object. Used for both `parameters` and the new
431
- * `outputSchema` field — same conversion path either way.
432
- */
433
- type LocalToolSchemaInput = ZodLikeObject | Record<string, unknown>;
434
- interface LocalTool<TArgs = Record<string, unknown>> {
435
- readonly kind: "local";
436
- readonly name: string;
437
- readonly description: string;
438
- readonly parameters: ZodLikeObject | undefined;
439
- /**
440
- * Optional JSON Schema (or Zod schema, auto-converted) describing the
441
- * tool's structured return value. Forwarded to providers with per-tool
442
- * response schemas (Gemini's `responseJsonSchema` on the
443
- * FunctionDeclaration); other engines surface it through the description
444
- * and rely on host-side validation. The model uses it to plan follow-up
445
- * arguments more reliably. See `docs/wire-protocol.md` §3.1.
446
- */
447
- readonly outputSchema: LocalToolSchemaInput | undefined;
448
- /**
449
- * When `true`, MANTYX appends a stable hint to the model-facing
450
- * description telling the model not to re-issue calls while a previous
451
- * invocation is still pending. Useful for tools that may yield a
452
- * `pending` / status response and the SDK polls on its own; without the
453
- * hint, models routinely fire repeat calls and waste turns. Pure
454
- * declarative — MANTYX does not change scheduling.
455
- */
456
- readonly longRunning: boolean;
457
- /**
458
- * When `true`, this tool may run **in parallel** with other read-only
459
- * tools the model emits in the same turn: MANTYX publishes every such
460
- * `local_tool_call` concurrently and resolves them together instead of
461
- * one-at-a-time in model-emit order. Set this only for side-effect-free
462
- * tools whose results don't depend on each other. Mutating tools (the
463
- * default, `false`) stay strictly sequential. See
464
- * `docs/agent-runs-protocol.md` §4.1.1.
465
- */
466
- readonly readOnly: boolean;
467
- /**
468
- * When `true`, the tool's result is **persisted with the session and
469
- * replayed to the model on later turns** — reconstructed as a
470
- * `tool_use` + `tool_result` pair in its original place in the
471
- * transcript. Only meaningful for session-scoped runs. Keep outputs
472
- * small (text only, ~8 KB cap). See `docs/agent-runs-protocol.md`
473
- * §4.1.1.
474
- */
475
- readonly retain: boolean;
476
- readonly execute: (args: TArgs) => Promise<LocalToolOutput> | LocalToolOutput;
477
- }
478
- interface DefineLocalToolOptions<T extends ZodLikeObject | undefined> {
479
- /** Lowercase alphanumeric + underscore, max 64 chars. */
480
- name: string;
481
- description?: string;
482
- parameters?: T;
483
- /**
484
- * Optional JSON Schema (or Zod schema) describing the tool's return
485
- * value. See {@link LocalTool.outputSchema}.
486
- */
487
- outputSchema?: LocalToolSchemaInput;
488
- /**
489
- * Annotate the tool as long-running so the model doesn't double-call
490
- * while a previous invocation is still pending. See
491
- * {@link LocalTool.longRunning}.
492
- */
493
- longRunning?: boolean;
494
- /**
495
- * Mark the tool as read-only so MANTYX may run it in parallel with other
496
- * read-only tools the model emits in the same turn. See
497
- * {@link LocalTool.readOnly}.
498
- */
499
- readOnly?: boolean;
500
- /**
501
- * Persist the tool result across session turns so follow-ups can
502
- * reference values the model can no longer recompute. See
503
- * {@link LocalTool.retain}.
504
- */
505
- retain?: boolean;
506
- execute: (args: T extends ZodLikeObject ? z.infer<T> : Record<string, unknown>) => Promise<LocalToolOutput> | LocalToolOutput;
507
- }
508
- declare function defineLocalTool<T extends ZodLikeObject | undefined>(opts: DefineLocalToolOptions<T>): LocalTool;
509
- interface MantyxToolRef {
510
- readonly kind: "mantyx";
511
- readonly id: string;
512
- }
513
- interface MantyxPluginToolRef {
514
- readonly kind: "mantyx_plugin";
515
- readonly name: string;
516
- }
517
- declare function mantyxTool(id: string): MantyxToolRef;
518
- declare function mantyxPluginTool(name: string): MantyxPluginToolRef;
519
- /**
520
- * Reference to a remote Agent2Agent peer reachable from MANTYX (server-resolved).
521
- * MANTYX dials `agentCardUrl` over A2A's `message/send` RPC and forwards the
522
- * remote agent's reply as the tool result.
523
- */
524
- interface A2AToolRef {
525
- readonly kind: "a2a";
526
- readonly name: string;
527
- readonly description?: string;
528
- readonly agentCardUrl: string;
529
- readonly headers?: Record<string, string>;
530
- readonly contextId?: string;
531
- }
532
- interface MantyxA2AOptions {
533
- /** Tool name surfaced to the model; must match `^[a-zA-Z0-9_]{1,64}$`. */
534
- name: string;
535
- description?: string;
536
- /** Remote Agent Card URL (`/.well-known/agent-card.json`) or JSON-RPC root. */
537
- agentCardUrl: string;
538
- /** Per-request HTTP headers (typically `Authorization`). */
539
- headers?: Record<string, string>;
540
- /** Optional A2A `contextId` to thread multiple delegations. */
541
- contextId?: string;
542
- }
543
- declare function mantyxA2A(opts: MantyxA2AOptions): A2AToolRef;
544
- /**
545
- * Local A2A peer — the SDK fetches the Agent Card from `agentCardUrl` on
546
- * the first run, ships the resolved card with the spec, and speaks A2A
547
- * `message/send` to `agentCard.url` whenever MANTYX emits a
548
- * `local_tool_call` for this tool. You only supply the URL.
549
- *
550
- * The model addresses this tool by `name` and always passes
551
- * `{ message: string }` as arguments.
552
- *
553
- * Resolution is lazy: the card is fetched on the first `runAgent` /
554
- * `streamAgent` / `createSession` (or `session.send`) call and cached on
555
- * the tool ref for the rest of the process lifetime. Re-construct the ref
556
- * to force a refetch.
557
- */
558
- interface LocalA2ATool {
559
- readonly kind: "a2a_local";
560
- readonly name: string;
561
- /** Where the SDK fetches the Agent Card from. Cached after the first hit. */
562
- readonly agentCardUrl: string;
563
- /**
564
- * Headers used for **both** the card fetch and every `message/send` POST
565
- * (typically `Authorization` for intranet peers).
566
- */
567
- readonly headers: Record<string, string> | undefined;
568
- /**
569
- * Internal cache of the resolved Agent Card. Populated lazily by the
570
- * client on the first run; not part of the user contract.
571
- * @internal
572
- */
573
- _resolvedCard?: ResolvedAgentCard;
574
- }
575
- /** Internal: the snapshot of a resolved A2A Agent Card. */
576
- interface ResolvedAgentCard {
577
- /** Required by the A2A spec; used for the synthesized tool description. */
578
- readonly name: string;
579
- /** Peer's A2A endpoint — where the SDK POSTs `message/send`. */
580
- readonly url?: string;
581
- /** Anything else the peer publishes; forwarded verbatim onto the wire. */
582
- readonly [k: string]: unknown;
583
- }
584
- interface DefineLocalA2AOptions {
585
- /** Tool name surfaced to the model. Must match `^[a-zA-Z0-9_]{1,64}$`. */
586
- name: string;
587
- /**
588
- * URL of the peer's Agent Card (`/.well-known/agent-card.json` is the
589
- * conventional path). The SDK fetches this on the first run, parses it,
590
- * and ships the resolved card with the spec. The resolved card's `url`
591
- * field is then used as the `message/send` target.
592
- */
593
- agentCardUrl: string;
594
- /**
595
- * Headers attached to **both** the card fetch and every `message/send`
596
- * POST (typically `Authorization` for intranet peers).
597
- */
598
- headers?: Record<string, string>;
599
- }
600
- declare function defineLocalA2A(opts: DefineLocalA2AOptions): LocalA2ATool;
601
- /**
602
- * Reference to a remote MCP server (Streamable HTTP) discovered + proxied by
603
- * MANTYX. Each tool in the catalog is exposed to the model as `<name>_<tool>`.
604
- */
605
- interface McpToolRef {
606
- readonly kind: "mcp";
607
- readonly name: string;
608
- readonly url: string;
609
- readonly headers?: Record<string, string>;
610
- readonly toolFilter?: string[];
611
- }
612
- interface MantyxMcpOptions {
613
- /** Server label; used to prefix every discovered tool. */
614
- name: string;
615
- /** Streamable HTTP MCP endpoint. */
616
- url: string;
617
- headers?: Record<string, string>;
618
- /** Optional allowlist of MCP tool names. */
619
- toolFilter?: string[];
620
- }
621
- declare function mantyxMcp(opts: MantyxMcpOptions): McpToolRef;
622
- /**
623
- * Streamable HTTP transport spec for {@link defineLocalMcp}.
624
- */
625
- interface LocalMcpHttpTransport {
626
- /** Streamable HTTP MCP endpoint (e.g. `http://localhost:8080/mcp`). */
627
- url: string;
628
- /** HTTP headers sent on every MCP request (typically `Authorization`). */
629
- headers?: Record<string, string>;
630
- }
631
- /**
632
- * stdio transport spec for {@link defineLocalMcp}. The SDK spawns the
633
- * specified executable with the given arguments and speaks JSON-RPC over
634
- * its stdin/stdout streams.
635
- */
636
- interface LocalMcpStdioTransport {
637
- /** Executable to launch (e.g. `mcp-server-filesystem`, `node`, `uvx`). */
638
- command: string;
639
- /** Arguments passed verbatim. */
640
- args?: string[];
641
- /** Environment variables for the child process. Inherited if undefined. */
642
- env?: Record<string, string>;
643
- /** Working directory for the child process. */
644
- cwd?: string;
645
- }
646
- /**
647
- * Local MCP server — the SDK manages the entire MCP lifecycle for you.
648
- *
649
- * Pass either a Streamable HTTP `url` or an stdio `command` (mutually
650
- * exclusive). On the first run, the SDK opens the transport, runs MCP's
651
- * `Initialize` (capturing the `Implementation` block) and `tools/list`
652
- * (capturing the catalog), and ships both inline as part of the spec. On
653
- * every `local_tool_call` with `kind: "mcp_local"` the SDK forwards the
654
- * call to MCP `tools/call` on the cached connection and POSTs the
655
- * flattened text response back to MANTYX.
656
- *
657
- * Connections are reused across runs and across messages within a session
658
- * and closed on `runAgent` completion / `session.end()`.
659
- */
660
- interface LocalMcpServer {
661
- readonly kind: "mcp_local";
662
- readonly name: string;
663
- /** One-of with {@link stdio} — the transport spec is mutually exclusive. */
664
- readonly http: LocalMcpHttpTransport | undefined;
665
- /** One-of with {@link http} — the transport spec is mutually exclusive. */
666
- readonly stdio: LocalMcpStdioTransport | undefined;
667
- /**
668
- * Internal cache of the resolved MCP client + catalog. Populated lazily
669
- * by the run driver on the first run; not part of the user contract.
670
- * @internal
671
- */
672
- _resolved?: ResolvedMcpServer;
673
- }
674
- /**
675
- * Internal: the live MCP client + the snapshot the SDK ships on the wire.
676
- */
677
- interface ResolvedMcpServer {
678
- /** The MCP `Implementation` block from `Initialize`. */
679
- readonly serverInfo: {
680
- name: string;
681
- version?: string;
682
- [k: string]: unknown;
683
- };
684
- /** Verbatim `tools/list` output. */
685
- readonly tools: ReadonlyArray<{
686
- readonly name: string;
687
- readonly description?: string;
688
- readonly inputSchema: Record<string, unknown>;
689
- readonly annotations?: Record<string, unknown>;
690
- readonly [k: string]: unknown;
691
- }>;
692
- /**
693
- * The live MCP client. Used by the run driver to call `tools/call`. The
694
- * concrete type depends on the transport — kept loose so this header
695
- * file doesn't have to import the MCP SDK type.
696
- */
697
- readonly client: McpClientLike;
698
- /** Closes the MCP transport (idempotent). */
699
- readonly close: () => Promise<void>;
700
- }
701
- /** Minimal interface this SDK uses against an MCP client. */
702
- interface McpClientLike {
703
- callTool(params: {
704
- name: string;
705
- arguments?: Record<string, unknown>;
706
- }): Promise<{
707
- content?: Array<{
708
- type: string;
709
- text?: string;
710
- [k: string]: unknown;
711
- }>;
712
- isError?: boolean;
713
- [k: string]: unknown;
714
- }>;
715
- }
716
- interface DefineLocalMcpOptions {
717
- /**
718
- * Server label echoed back as `mcpServer` on every `local_tool_call`. The
719
- * SDK auto-prefixes each discovered tool's wire-level `name` with
720
- * `<this>_` so the model sees a non-colliding `<server>_<tool>` surface
721
- * — mirroring how MANTYX prefixes for `kind: "mcp"`.
722
- */
723
- name: string;
724
- /**
725
- * Streamable HTTP transport. Mutually exclusive with {@link command}.
726
- */
727
- url?: string;
728
- /**
729
- * Headers attached to every MCP request when using the HTTP transport.
730
- */
731
- headers?: Record<string, string>;
732
- /**
733
- * stdio transport: executable to launch. Mutually exclusive with
734
- * {@link url}.
735
- */
736
- command?: string;
737
- /** Arguments for the stdio child process. */
738
- args?: string[];
739
- /** Environment variables for the stdio child process. */
740
- env?: Record<string, string>;
741
- /** Working directory for the stdio child process. */
742
- cwd?: string;
743
- }
744
- declare function defineLocalMcp(opts: DefineLocalMcpOptions): LocalMcpServer;
745
- type ToolRef = MantyxToolRef | MantyxPluginToolRef | LocalTool | A2AToolRef | LocalA2ATool | McpToolRef | LocalMcpServer;
746
- declare function isLocalTool(t: ToolRef): t is LocalTool;
747
- declare function isLocalA2ATool(t: ToolRef): t is LocalA2ATool;
748
- declare function isLocalMcpServer(t: ToolRef): t is LocalMcpServer;
749
-
750
- declare const DEFAULT_BASE_URL = "https://app.mantyx.io";
751
- /** Inline file bytes for a user message (base64, no data-URL prefix). */
752
- interface InputFileAttachment {
753
- type: "input_file";
754
- mimeType: string;
755
- filename: string;
756
- data: string;
757
- }
758
- /** HTTPS URL the provider fetches as a user-message file input. */
759
- interface InputFileUrlAttachment {
760
- type: "input_file_url";
761
- url: string;
762
- mimeType?: string;
763
- filename?: string;
764
- }
765
- /** File input attached to a user message on `POST /agent-runs` or session turns. */
766
- type MessageAttachment = InputFileAttachment | InputFileUrlAttachment;
767
- /** Metadata for an inline file on replay-only `user_message` frames (no bytes). */
768
- interface InputFileAttachmentMetadata {
769
- type: "input_file";
770
- mimeType: string;
771
- filename: string;
772
- size: number;
773
- }
774
- /** Metadata for a URL file on replay-only `user_message` frames. */
775
- interface InputFileUrlAttachmentMetadata {
776
- type: "input_file_url";
777
- url: string;
778
- mimeType?: string;
779
- filename?: string;
780
- }
781
- /** Attachment metadata on session-event `user_message` replay frames. */
782
- type AttachmentMetadata = InputFileAttachmentMetadata | InputFileUrlAttachmentMetadata;
783
- /** One entry in a multi-role `messages` array. */
784
- interface ConversationMessage {
785
- role: "user" | "assistant" | "system";
786
- content: string;
787
- attachments?: MessageAttachment[];
788
- }
789
- /** Build an inline file attachment for the last user message in a run. */
790
- declare function inputFileAttachment(opts: {
791
- mimeType: string;
792
- filename: string;
793
- data: string;
794
- }): InputFileAttachment;
795
- /** Build a URL file attachment for the last user message in a run. */
796
- declare function inputFileUrlAttachment(opts: {
797
- url: string;
798
- mimeType?: string;
799
- filename?: string;
800
- }): InputFileUrlAttachment;
801
- /** Thumbs up/down verdict for {@link MantyxClient.submitRunFeedback}. */
802
- type RunFeedbackVerdict = "UP" | "DOWN";
803
- /** Body for `POST /agent-runs/:runId/feedback`. See §9a. */
804
- interface RunFeedbackInput {
805
- verdict: RunFeedbackVerdict;
806
- /** Optional free-text note (≤ 8000 characters). */
807
- explanation?: string;
808
- /** Optional snapshot of the rated content; defaults to the run's final text. */
809
- contentSnapshot?: string;
810
- }
811
- /** Response from `POST /agent-runs/:runId/feedback`. */
812
- interface RunFeedbackResult {
813
- id: string;
814
- verdict: RunFeedbackVerdict;
815
- targetKind: string;
816
- agentRunId: string;
817
- }
818
- /** Terminal statuses for {@link EvalRunDetail} and {@link EvalRunSummary}. */
819
- type EvalRunStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled";
820
- /** One case in an inline eval dataset (`POST /eval-runs` `dataset`). */
821
- interface InlineEvalCaseSpec {
822
- name?: string;
823
- input: {
824
- role?: "user";
825
- content: string;
826
- expected?: string | null;
827
- };
828
- scorers?: Record<string, unknown>[];
829
- toolMocks?: Record<string, unknown>;
830
- tags?: string[];
831
- }
832
- /** Inline eval dataset blob (`POST /eval-runs` `dataset`). */
833
- interface InlineEvalDatasetSpec {
834
- name?: string;
835
- toolMocks?: Record<string, unknown>;
836
- cases: InlineEvalCaseSpec[];
837
- }
838
- /** Saved-agent overrides on `POST /eval-runs` (ignored for inline `agent`). */
839
- interface AgentEvalOverrides {
840
- systemPrompt?: string;
841
- systemPromptAppend?: string;
842
- model?: string;
843
- llmProviderId?: string;
844
- reasoningLevel?: "low" | "medium" | "high";
845
- disableTools?: boolean;
846
- toolAllowlist?: string[];
847
- disabledMocks?: string[];
848
- }
849
- /** Body for `POST /eval-runs`. Exactly one of `datasetId`/`dataset` and `agentId`/`agent`. */
850
- interface CreateEvalRunRequest {
851
- datasetId?: string;
852
- dataset?: InlineEvalDatasetSpec;
853
- agentId?: string;
854
- agent?: AgentSpecBase;
855
- /** Client-resolved tools merged onto a saved `agentId` eval run. */
856
- tools?: ToolRef[];
857
- modelId?: string;
858
- overrides?: AgentEvalOverrides;
859
- }
860
- interface EvalDatasetSummary {
861
- id: string;
862
- name: string;
863
- description: string | null;
864
- caseCount: number;
865
- runCount: number;
866
- createdAt: string;
867
- updatedAt: string;
868
- }
869
- interface EvalDatasetList {
870
- datasets: EvalDatasetSummary[];
871
- }
872
- interface EvalCase {
873
- id: string;
874
- name: string;
875
- input: Record<string, unknown>;
876
- scorers: Record<string, unknown>[];
877
- tags: string[];
878
- toolMocks: Record<string, unknown> | null;
879
- createdAt: string;
880
- updatedAt: string;
881
- }
882
- interface EvalDatasetDetail {
883
- id: string;
884
- name: string;
885
- description: string | null;
886
- toolMocks: Record<string, unknown> | null;
887
- cases: EvalCase[];
888
- createdAt: string;
889
- updatedAt: string;
890
- }
891
- interface EvalRunAccepted {
892
- runId: string;
893
- status: string;
894
- streamUrl: string;
895
- }
896
- interface EvalRunSummary {
897
- id: string;
898
- datasetId: string;
899
- datasetName: string;
900
- agentId: string | null;
901
- inlineAgent: boolean;
902
- status: EvalRunStatus;
903
- totalCases: number;
904
- completedCases: number;
905
- passedCases: number;
906
- score: number | null;
907
- tokenUsage: Record<string, unknown> | null;
908
- error: string | null;
909
- agentOverrides: Record<string, unknown> | null;
910
- startedAt: string | null;
911
- finishedAt: string | null;
912
- createdAt: string;
913
- }
914
- interface EvalCaseResult {
915
- id: string;
916
- caseId: string;
917
- case: EvalCase;
918
- finalText: string | null;
919
- toolCalls: Record<string, unknown>[];
920
- scores: Record<string, unknown>[];
921
- passed: boolean;
922
- score: number;
923
- tokens: Record<string, unknown> | null;
924
- latencyMs: number | null;
925
- error: string | null;
926
- createdAt: string;
927
- }
928
- interface EvalRunDetail extends EvalRunSummary {
929
- inlineAgentSpec: Record<string, unknown> | null;
930
- agentSpecSnapshot: Record<string, unknown> | null;
931
- updatedAt: string;
932
- results: EvalCaseResult[];
933
- }
934
- interface EvalRunList {
935
- runs: EvalRunSummary[];
936
- limit: number;
937
- offset: number;
938
- }
939
- interface EvalRunCompareSide {
940
- id: string;
941
- agentId: string | null;
942
- inlineAgent: boolean;
943
- status: string;
944
- totalCases: number;
945
- completedCases: number;
946
- passedCases: number;
947
- score: number | null;
948
- tokenUsage: Record<string, unknown> | null;
949
- agentOverrides: Record<string, unknown> | null;
950
- agentSpecSnapshot: Record<string, unknown> | null;
951
- startedAt: string | null;
952
- finishedAt: string | null;
953
- createdAt: string;
954
- }
955
- interface EvalRunCompareCase {
956
- caseId: string;
957
- caseName: string;
958
- caseInput: Record<string, unknown> | null;
959
- a: Record<string, unknown> | null;
960
- b: Record<string, unknown> | null;
961
- }
962
- interface EvalRunCompare {
963
- datasetId: string;
964
- datasetName: string;
965
- runA: EvalRunCompareSide;
966
- runB: EvalRunCompareSide;
967
- cases: EvalRunCompareCase[];
968
- }
969
- /** One SSE frame from `GET /eval-runs/:runId/stream`. */
970
- interface EvalRunEvent {
971
- type: string;
972
- [key: string]: unknown;
973
- }
974
- interface ListEvalRunsOptions {
975
- datasetId?: string;
976
- agentId?: string;
977
- status?: EvalRunStatus | string;
978
- limit?: number;
979
- offset?: number;
980
- }
981
- interface RunEvalOptions {
982
- /** Client-resolved tools to register for the eval run. */
983
- tools?: ToolRef[];
984
- /** Called for each SSE frame while the run is in flight. */
985
- onEvent?: (event: EvalRunEvent) => void;
986
- /** Poll interval when SSE is unavailable or ends early. Default 1000ms. */
987
- pollIntervalMs?: number;
988
- signal?: AbortSignal;
989
- }
990
- interface MantyxClientOptions {
991
- /**
992
- * Workspace API key (token prefix `mantyx_`) **or** a MANTYX OAuth 2.0
993
- * access token (token prefix `mantyx_at_`). The server resolves either
994
- * kind by token-prefix, so the SDK uses a single credential code path.
995
- *
996
- * Prefer the {@link accessToken} alias when wiring up an OAuth-based
997
- * application — the two options are semantically identical (the value
998
- * is forwarded as `Authorization: Bearer <credential>`), but
999
- * `accessToken` makes the intent obvious at the call site.
1000
- *
1001
- * Exactly one of `apiKey` / `accessToken` must be set. Passing both —
1002
- * even to the same value — throws `MantyxError` at construction time.
1003
- *
1004
- * See `docs/agent-runs-protocol.md` §2 for the full credential table
1005
- * (including which prefix means what, scope semantics, and the
1006
- * `insufficient_scope` 403 SDKs surface via
1007
- * {@link MantyxScopeError}).
1008
- */
1009
- apiKey?: string;
1010
- /**
1011
- * MANTYX OAuth 2.0 access token (token prefix `mantyx_at_…`). Exactly
1012
- * one of {@link apiKey} / `accessToken` / {@link tokenSource} must be
1013
- * set; passing more than one throws `MantyxError` at construction
1014
- * time.
1015
- *
1016
- * Functionally identical to {@link apiKey} — the SDK ships either
1017
- * value verbatim on `Authorization: Bearer <credential>` — but using
1018
- * the OAuth-specific name makes scope-driven applications easier to
1019
- * read.
1020
- *
1021
- * OAuth tokens additionally enforce per-route **scopes**
1022
- * (`runs:read`, `runs:write`, `sessions:read`, `sessions:write`,
1023
- * `models:read`, `feedback:write`, `evals:read`, `evals:write`,
1024
- * `mantyx.identity:read`); see
1025
- * `docs/agent-runs-protocol.md` §2.2 for the table. Missing scopes
1026
- * land as {@link MantyxScopeError} so callers can route the user
1027
- * back to a re-consent flow.
1028
- *
1029
- * Static `accessToken` values are 1-hour-lived per `docs/oauth.md`
1030
- * §"Token lifetimes & lifecycle" — for long-running processes
1031
- * prefer {@link tokenSource} so the SDK can refresh transparently.
1032
- */
1033
- accessToken?: string;
1034
- /**
1035
- * Dynamic credential provider. The SDK calls it before every request
1036
- * to obtain the current access token, and again with
1037
- * `reason: "unauthorized"` after a 401 so it can refresh and retry
1038
- * the request exactly once.
1039
- *
1040
- * Build one via `oauthClient.refreshTokenSource({ refreshToken })`
1041
- * or `oauthClient.clientCredentialsTokenSource()` — see
1042
- * [`./oauth.ts`](./oauth.ts) for the helpers, or pass any function
1043
- * matching the {@link TokenSource} signature for full custom
1044
- * control (e.g. tokens minted by an upstream auth proxy).
1045
- *
1046
- * Exactly one of {@link apiKey} / {@link accessToken} / `tokenSource`
1047
- * must be set.
1048
- */
1049
- tokenSource?: TokenSource;
1050
- workspaceSlug: string;
1051
- /** Defaults to `https://app.mantyx.io`. Override for self-hosted instances. */
1052
- baseUrl?: string;
1053
- /** Optional `fetch` override (e.g. node-fetch wrapper, or a custom HTTP client). */
1054
- fetch?: typeof fetch;
1055
- /** Default per-request timeout in milliseconds. Default: 60s. */
1056
- timeoutMs?: number;
1057
- }
1058
- interface ModelInfo {
1059
- id: string;
1060
- label: string;
1061
- provider: string;
1062
- vendorModelId: string;
1063
- source: "workspace_provider" | "platform_offering";
1064
- contextWindowTokens: number | null;
1065
- pricing: {
1066
- inputPer1MUsd: number | null;
1067
- outputPer1MUsd: number | null;
1068
- cacheReadPer1MUsd: number | null;
1069
- } | null;
1070
- }
1071
- interface ModelCatalog {
1072
- models: ModelInfo[];
1073
- defaultModelId: string | null;
1074
- }
1075
- interface AgentSpecBase {
1076
- name?: string;
1077
- /**
1078
- * Reference to a persisted MANTYX agent in this workspace. When set, the
1079
- * server hydrates `systemPrompt`, `modelId`, and the agent's own tools
1080
- * (memory, skills, plugin tools, …) from the Agent row at run time, and any
1081
- * `tools` you supply here are merged on top — typically `local` tools the
1082
- * SDK wants the agent to be able to call back into.
1083
- *
1084
- * Either `agentId` or `systemPrompt` must be set.
1085
- */
1086
- agentId?: string;
1087
- /** Required unless `agentId` is set. */
1088
- systemPrompt?: string;
1089
- modelId?: string;
1090
- tools?: ToolRef[];
1091
- /**
1092
- * Provider thinking strength: a string anchor (`"off" | "low" | "medium" |
1093
- * "high"`) or an integer in `0..100` (where `0` explicitly disables provider
1094
- * thinking on reasoning models). The server maps this onto each LLM's
1095
- * native dial — see `docs/agent-runs-protocol.md` §4.4.
1096
- *
1097
- * For session-scoped runs the session value sets the default; per-message
1098
- * overrides on `session.send` apply to that single run.
1099
- */
1100
- reasoningLevel?: ReasoningLevel;
1101
- budgets?: {
1102
- maxToolTurns?: number;
1103
- };
1104
- /**
1105
- * Constrains the model's **final assistant text** to a JSON document
1106
- * matching a JSON Schema. The terminal `result` event still carries the
1107
- * reply as `text: string`, but that string is guaranteed-parseable JSON.
1108
- *
1109
- * `name` (optional) is a stable identifier the server forwards to the
1110
- * provider (OpenAI `text.format.name`, Anthropic synthetic-tool name).
1111
- * Defaults to `"output"`. Must match `/^[a-zA-Z0-9_-]{1,64}$/`.
1112
- *
1113
- * `schema` is a JSON Schema describing the final assistant text. Its
1114
- * root must be a JSON **object** — most providers reject array / scalar
1115
- * roots in structured-output mode. The schema is shipped verbatim;
1116
- * MANTYX does not validate its contents (the provider does).
1117
- *
1118
- * Use {@link parseRunOutput} on the resulting `RunResult` to JSON.parse
1119
- * the reply (and optionally re-validate against your own zod / typebox /
1120
- * ajv schema). See `docs/wire-protocol.md` §7.
1121
- */
1122
- outputSchema?: OutputSchema;
1123
- /**
1124
- * Loop-detection guard. Tracks an order-invariant `(toolName, args)`
1125
- * signature for every assistant turn that emits one or more tool calls;
1126
- * when the same signature repeats consecutively the pipeline first injects
1127
- * a steering nudge ("either deliver a final answer or change strategy")
1128
- * and eventually forces a tools-disabled finalise turn.
1129
- *
1130
- * Pass an object to override the default thresholds, or `false` to
1131
- * explicitly disable the guard for this run / session. When omitted, the
1132
- * MANTYX runtime defaults apply (`{ consecutiveThreshold: 3,
1133
- * hardCutoffThreshold: 6 }`). See `docs/agent-runs-protocol.md` §4.6.
1134
- *
1135
- * Each intervention emits an observability-only `loop_detected` SSE event
1136
- * the SDK surfaces on the run-event stream (`tools` lists the looping
1137
- * batch; `hardCutoff: false` is the soft nudge round, `true` is the
1138
- * forced finalise). The synthetic skip + nudge are emitted on the normal
1139
- * `tool_result` / `assistant_delta` channels — the SDK does not need to
1140
- * act on the event itself.
1141
- */
1142
- loopDetection?: LoopDetection | false;
1143
- /**
1144
- * Per-tool call caps enforced over the **lifetime of the run** (across
1145
- * every LLM turn). Calls under the cap run normally; calls past the cap
1146
- * are intercepted before execution and returned to the model as a
1147
- * synthetic "budget exceeded — pivot or finalize" tool result.
1148
- *
1149
- * Keys are the model-facing tool names (the same string on
1150
- * `local_tool_call.name`); values are `{ maxCalls: number }`. `maxCalls:
1151
- * 0` disables the tool entirely (the first attempt returns the synthetic
1152
- * body). Budgets are **per-tool, not pooled**.
1153
- *
1154
- * Pass `{}` to start from a clean slate (no defaults applied on top —
1155
- * useful for runs that intentionally want unbounded research). Omit
1156
- * entirely to keep the runtime defaults. Each interception emits an
1157
- * observability-only `tool_budget_exceeded` SSE event. See
1158
- * `docs/agent-runs-protocol.md` §4.7.
1159
- */
1160
- toolBudgets?: ToolBudgets;
1161
- /**
1162
- * Run-supervisor (platform LLM judge). Periodically reviews the agent's
1163
- * transcript and may steer the run (`on_track`, `redirect`, `finalize`).
1164
- *
1165
- * Pass an object to override the review interval, or `false` to explicitly
1166
- * disable the platform judge for this run / session. When omitted on
1167
- * ephemeral API runs, MANTYX enables the supervisor (default interval `5`).
1168
- * SDK-only runs (`runAgent` without the HTTP API) keep the supervisor off
1169
- * unless you pass a value here. See `docs/agent-runs-protocol.md` §4.8.
1170
- *
1171
- * Each review emits an observability-only `supervisor` SSE event — including
1172
- * `on_track` checks — so the SDK can render supervisor activity. When
1173
- * `action` is `redirect` or `finalize`, the pipeline has already applied
1174
- * the verdict by the time the event arrives.
1175
- */
1176
- supervisor?: Supervisor | false;
1177
- /**
1178
- * In-product **task plan** — live checklist emitted as `task_plan` SSE
1179
- * events and (for `planOnly` runs) returned on the terminal `result`.
1180
- * Opt-in: every planned run pays for at least one classifier LLM call.
1181
- *
1182
- * - `true` — auto-classify; track step statuses during the run when warranted.
1183
- * - `{ steps?, brief? }` — caller-provided checklist (skips the classifier).
1184
- * - `{ planOnly: true, steps?, brief? }` — produce the plan and **stop**
1185
- * without executing the agent loop; read the final checklist from
1186
- * {@link RunResult.plan}.
1187
- * - `false` — no planning (default when omitted).
1188
- *
1189
- * See `docs/agent-runs-protocol.md` §4.9. Prefer {@link MantyxClient.runPlan}
1190
- * for plan-only runs.
1191
- */
1192
- plan?: PlanSpec;
1193
- /**
1194
- * Flat string→string KV carried alongside the run / session for
1195
- * observability. Use it to tag runs with your own application identifiers
1196
- * (customer id, environment, workflow name, …) — the values are visible in
1197
- * the MANTYX dashboard and can be filtered there.
1198
- *
1199
- * Limits enforced server-side: max 16 entries; keys match
1200
- * `[A-Za-z0-9._-]{1,64}`; values are strings ≤ 256 chars; serialized JSON
1201
- * ≤ 4 KB. For session-scoped runs, the session's metadata is inherited and
1202
- * any per-message override is merged on top.
1203
- */
1204
- metadata?: Record<string, string>;
1205
- }
1206
- interface RunSpec extends AgentSpecBase {
1207
- prompt?: string;
1208
- messages?: ConversationMessage[];
1209
- /**
1210
- * Shorthand for a single user turn with file inputs. When `prompt` is set
1211
- * and `messages` is omitted, the SDK builds a one-entry `messages` array.
1212
- * Ignored when `messages` is provided. See `docs/agent-runs-protocol.md`
1213
- * §4.0.1.
1214
- */
1215
- attachments?: MessageAttachment[];
1216
- /** Receives streaming assistant text deltas. */
1217
- onAssistantDelta?: (delta: string) => void;
1218
- /** Receives raw events (assistant_message, local_tool_call, tool_result, ...) for advanced consumers. */
1219
- onEvent?: (event: RunEvent) => void;
1220
- /** Aborts the run on the client and best-effort cancels server-side. */
1221
- signal?: AbortSignal;
1222
- }
1223
- type SessionSpec = AgentSpecBase;
1224
- /**
1225
- * Either a Zod schema (auto-converted to JSON Schema by the SDK) or a
1226
- * pre-shaped JSON Schema object. Mirrors {@link LocalToolSchemaInput} and
1227
- * Go's `OutputSchema.Schema any` (struct reflection) — pass your
1228
- * source-of-truth schema and the SDK serialises it for the wire.
1229
- */
1230
- type OutputSchemaValue = LocalToolSchemaInput;
1231
- /**
1232
- * Constrains the final assistant text to a JSON document matching a
1233
- * JSON Schema. See {@link AgentSpecBase.outputSchema} for the full
1234
- * semantics.
1235
- */
1236
- interface OutputSchema {
1237
- /** Optional. Defaults to `"output"`. Must match `/^[a-zA-Z0-9_-]{1,64}$/`. */
1238
- name?: string;
1239
- /** Required. Zod schema or JSON Schema describing the final assistant text. Root must be a JSON object. */
1240
- schema: OutputSchemaValue;
1241
- }
1242
- /**
1243
- * Loop-detection thresholds. See {@link AgentSpecBase.loopDetection} for the
1244
- * full semantics. Pass `false` (instead of an object) to disable the guard.
1245
- *
1246
- * Both fields are optional; omitted ones inherit the MANTYX runtime
1247
- * defaults (`consecutiveThreshold: 3`, `hardCutoffThreshold: 6`).
1248
- */
1249
- interface LoopDetection {
1250
- /**
1251
- * Number of identical consecutive tool-call batches that triggers the
1252
- * **soft nudge** — the pipeline injects a steering message ("either
1253
- * deliver a final answer or change strategy"). Default `3`. Must be
1254
- * `>= 2` (one identical batch is just a single tool call, not a loop).
1255
- * Server-side upper bound: `100`.
1256
- */
1257
- consecutiveThreshold?: number;
1258
- /**
1259
- * Number of identical consecutive tool-call batches that triggers the
1260
- * **hard cutoff** — the pipeline forces a tools-disabled finalise turn.
1261
- * Default `6`. Must be strictly greater than `consecutiveThreshold` (so
1262
- * the soft nudge has a chance to land). Server-side upper bound: `100`.
1263
- */
1264
- hardCutoffThreshold?: number;
1265
- }
1266
- /**
1267
- * Per-tool call cap. See {@link AgentSpecBase.toolBudgets} for the full
1268
- * semantics.
1269
- */
1270
- interface ToolBudget {
1271
- /**
1272
- * Hard cap on executed calls per run. `0` disables the tool entirely
1273
- * (every attempt returns the synthetic "budget exceeded" body on the
1274
- * first try). Server-side upper bound: `1000` (functionally unlimited;
1275
- * the in-runtime `maxToolTurns: 100` fires first).
1276
- */
1277
- maxCalls: number;
1278
- }
1279
- /**
1280
- * Map of model-facing tool name → cap. See
1281
- * {@link AgentSpecBase.toolBudgets}. Pass an empty object (`{}`) to start
1282
- * from a clean slate (no runtime defaults applied on top); omit the field
1283
- * entirely to keep the defaults.
1284
- */
1285
- type ToolBudgets = Record<string, ToolBudget>;
1286
- /**
1287
- * Run-supervisor configuration. See {@link AgentSpecBase.supervisor} for the
1288
- * full semantics. Pass `false` (instead of an object) to disable the platform
1289
- * judge for the run / session.
1290
- *
1291
- * `interval` is optional; when omitted the MANTYX runtime default is **5**
1292
- * LLM calls between reviews. Server-side upper bound: `100`.
1293
- *
1294
- * `reasoningTrigger` controls mid-turn reasoning reviews (default
1295
- * `{ chars: 3000, ms: 30000 }`). Pass `false` to only review at tool-round
1296
- * boundaries.
1297
- */
1298
- interface Supervisor {
1299
- /** LLM calls (`completeTurn` invocations) between supervisor reviews. */
1300
- interval?: number;
1301
- /** Mid-turn reasoning trigger, or `false` to disable. */
1302
- reasoningTrigger?: ReasoningTrigger | false;
1303
- }
1304
- /** Mid-turn supervisor review trigger (reasoning span length / duration). */
1305
- interface ReasoningTrigger {
1306
- /** Reasoning characters per span before review. Default `3000`, max `50000`. */
1307
- chars?: number;
1308
- /** Milliseconds per reasoning span before review. Default `30000`, max `600000`. */
1309
- ms?: number;
1310
- }
1311
- /** Verdict from a run-supervisor review. */
1312
- type SupervisorAction = "on_track" | "redirect" | "finalize";
1313
- /** When a supervisor review fired relative to the model turn. */
1314
- type SupervisorPhase = "turn_boundary" | "reasoning";
1315
- /** Status of one step in an in-product task plan. */
1316
- type TaskPlanStepStatus = "pending" | "in_progress" | "done";
1317
- /** One checklist row in a {@link TaskPlan}. */
1318
- interface TaskPlanStep {
1319
- title: string;
1320
- status: TaskPlanStepStatus;
1321
- }
1322
- /**
1323
- * Structured task plan surfaced on `task_plan` events and (for plan-only runs)
1324
- * on {@link RunResult.plan}. See `docs/agent-runs-protocol.md` §4.9.
1325
- */
1326
- interface TaskPlan {
1327
- /** Optional one-line objective summary. */
1328
- brief?: string;
1329
- steps: TaskPlanStep[];
1330
- }
1331
- /**
1332
- * Caller-supplied plan options. Pass `true` / `false` at the top level via
1333
- * {@link PlanSpec} for auto-classify / disable.
1334
- */
1335
- interface PlanOptions {
1336
- /** When `true`, produce the plan and terminate without executing the agent loop. */
1337
- planOnly?: boolean;
1338
- /** One-line objective for a caller-provided plan. Clamped server-side. */
1339
- brief?: string;
1340
- /** Caller-provided checklist titles. Omit to let the classifier decide. */
1341
- steps?: string[];
1342
- }
1343
- /** `true` (auto-classify) | options object | `false` (disable). */
1344
- type PlanSpec = boolean | PlanOptions;
1345
- /**
1346
- * Build a {@link PlanSpec} for plan-only runs. Equivalent to
1347
- * `{ planOnly: true, steps?, brief? }`.
1348
- */
1349
- declare function planOnly(options?: {
1350
- steps?: string[];
1351
- brief?: string;
1352
- }): PlanOptions;
1353
- /**
1354
- * Per-run token totals attached to terminal `result` / `error` events
1355
- * (and to the `GET /agent-runs/:runId` snapshot) by MANTYX ≥ 2026-09.
1356
- *
1357
- * Aggregated across every model invocation for the run. See
1358
- * `docs/agent-runs-protocol.md` §7.1 for the per-provider mapping and
1359
- * the relationship between buckets (`inputTokens` / `outputTokens` are
1360
- * the billable totals; `cachedTokens` and `reasoningTokens` are
1361
- * diagnostic breakdowns _inside_ those two totals, not separate
1362
- * additive buckets).
1363
- *
1364
- * Older servers omit the cost-attribution triple entirely; SDK callers
1365
- * detect "no usage data" by checking `result.model?.provider` is empty
1366
- * / undefined.
1367
- */
1368
- interface RunTokenUsage {
1369
- /**
1370
- * Total billable input tokens — fresh prompt tokens plus the
1371
- * cached-read slice the provider still bills (at a discount) plus
1372
- * any cache-creation tokens plus tool-prompt tokens. Equal to the
1373
- * sum of every provider-reported input bucket for the run.
1374
- */
1375
- inputTokens: number;
1376
- /**
1377
- * The discounted slice of `inputTokens` that came from a prompt
1378
- * cache hit (Anthropic prompt caching, OpenAI cached prompt, Gemini
1379
- * implicit cache). `0` when the provider doesn't report cache reads
1380
- * or the run didn't hit cache.
1381
- */
1382
- cachedTokens: number;
1383
- /**
1384
- * Non-visible thinking tokens. **Already counted inside
1385
- * `outputTokens`** — surfaced separately so dashboards can break out
1386
- * "thinking cost" vs visible output. `0` when the model didn't
1387
- * reason or didn't report it.
1388
- */
1389
- reasoningTokens: number;
1390
- /**
1391
- * All tokens the model emitted for this run, visible + reasoning.
1392
- * Matches the provider's "completion tokens" / "output tokens"
1393
- * billing line.
1394
- */
1395
- outputTokens: number;
1396
- }
1397
- /**
1398
- * The resolved model the platform stamped onto the run, surfaced on
1399
- * terminal `result` / `error` events (and `GET /agent-runs/:runId`)
1400
- * by MANTYX ≥ 2026-09. See `docs/agent-runs-protocol.md` §7.1.
1401
- */
1402
- interface RunModelInfo {
1403
- /**
1404
- * Catalog id — the same string a caller would pass back as
1405
- * `modelId` to re-select this exact entry (e.g. `"platform:demo"`,
1406
- * `"provider:cmf…"`). Empty string against legacy fallbacks that
1407
- * didn't synthesise a catalog id.
1408
- */
1409
- id: string;
1410
- /**
1411
- * Lowercase provider id: `"openai"`, `"anthropic"`, `"google"`,
1412
- * `"azure-openai"`. Empty string against legacy runners that don't
1413
- * report usage data — SDK callers use that as the "no usage data"
1414
- * signal.
1415
- */
1416
- provider: string;
1417
- /**
1418
- * The model id the platform actually sent to the provider (e.g.
1419
- * `"gpt-5.4-mini"`, `"claude-opus-4-7"`, `"gemini-2.5-pro"`).
1420
- */
1421
- vendorModelId: string;
1422
- /**
1423
- * `"off" | "low" | "medium" | "high"`. Omitted when the provider
1424
- * doesn't expose a reasoning-level knob or the run didn't request
1425
- * one.
1426
- */
1427
- reasoningEffort?: string;
1428
- }
1429
- interface RunResult {
1430
- runId: string;
1431
- text: string;
1432
- events: RunEvent[];
1433
- /**
1434
- * Per-run token totals from the terminal event. Undefined against
1435
- * MANTYX servers older than 2026-09 (the "no usage data" signal is
1436
- * `result.model?.provider` being empty / undefined). See
1437
- * {@link RunTokenUsage} and `docs/agent-runs-protocol.md` §7.1.
1438
- */
1439
- tokens?: RunTokenUsage;
1440
- /**
1441
- * Total `engine.completeTurn(...)` invocations for the run,
1442
- * including the failing call when a run errored mid-loop. A
1443
- * single-shot run reports `1`; a tool loop is `>= 2`. Undefined
1444
- * against legacy MANTYX servers.
1445
- */
1446
- turns?: number;
1447
- /** Resolved model that executed the run. See {@link RunModelInfo}. */
1448
- model?: RunModelInfo;
1449
- /**
1450
- * Final structured checklist for `planOnly` runs. Undefined for normal
1451
- * executed runs (use `task_plan` events for live progress). See
1452
- * `docs/agent-runs-protocol.md` §4.9.
1453
- */
1454
- plan?: TaskPlan;
1455
- }
1456
- interface RunEventBase {
1457
- seq: number;
1458
- type: string;
1459
- }
1460
- interface AssistantDeltaEvent extends RunEventBase {
1461
- type: "assistant_delta";
1462
- text: string;
1463
- }
1464
- interface ThinkingDeltaEvent extends RunEventBase {
1465
- type: "thinking_delta";
1466
- text: string;
1467
- }
1468
- interface AssistantMessageEvent extends RunEventBase {
1469
- type: "assistant_message";
1470
- /**
1471
- * Full assistant text for this turn (concatenation of every preceding
1472
- * `assistant_delta` for the turn, plus any non-streaming snapshot the
1473
- * engine appended at close). May be empty when the turn was tool-only.
1474
- */
1475
- text: string;
1476
- /**
1477
- * 0-based tool-turn index this assistant message closes. Useful for
1478
- * SDK clients pairing the message with the subsequent `tool_result`
1479
- * rows.
1480
- */
1481
- turn?: number;
1482
- /**
1483
- * Canonical lowercase stop reason normalized across providers
1484
- * (`"end_turn"`, `"tool_use"`, `"max_tokens"`, `"refusal"`,
1485
- * `"malformed_function_call"`, …). `null` / omitted when the provider
1486
- * did not report one.
1487
- */
1488
- finishReason?: string | null;
1489
- /**
1490
- * Tool calls the model emitted on this turn. Omitted when the model
1491
- * did not call any tools.
1492
- */
1493
- toolCalls?: Array<{
1494
- id: string;
1495
- name: string;
1496
- input: Record<string, unknown>;
1497
- }>;
1498
- }
1499
- interface ServerToolResultEvent extends RunEventBase {
1500
- type: "tool_result";
1501
- name: string;
1502
- args?: Record<string, unknown>;
1503
- ok?: boolean;
1504
- summary?: string;
1505
- phase?: "start" | "end";
1506
- }
1507
- interface LocalToolCallEvent extends RunEventBase {
1508
- type: "local_tool_call";
1509
- toolUseId: string;
1510
- /**
1511
- * The model-facing tool name. For `kind: "mcp_local"` events this is the
1512
- * `<server>_<tool>` name the SDK declared on the wire; the SDK looks up
1513
- * the local MCP server via `mcpServer` and forwards `mcpToolName` to
1514
- * `tools/call` rather than parsing the prefix itself.
1515
- */
1516
- name: string;
1517
- args: Record<string, unknown>;
1518
- /**
1519
- * Discriminator for which client-resolved handler should run.
1520
- * - `"local"` (or omitted) — generic local tool
1521
- * - `"a2a_local"` — local Agent2Agent peer
1522
- * - `"mcp_local"` — local MCP server tool
1523
- */
1524
- kind?: "local" | "a2a_local" | "mcp_local";
1525
- /**
1526
- * Present on `kind: "a2a_local"` — the full A2A Agent Card the SDK shipped
1527
- * with the spec, echoed back unchanged. Surfaced for advanced consumers
1528
- * (`onEvent` / `streamAgent` callers); the built-in dispatcher ignores it
1529
- * because it already has the cached card from the original
1530
- * `defineLocalA2A` resolution.
1531
- */
1532
- agentCard?: {
1533
- name: string;
1534
- url?: string;
1535
- [k: string]: unknown;
1536
- };
1537
- /** Present on `kind: "mcp_local"` — server label declared via `defineLocalMcp`. */
1538
- mcpServer?: string;
1539
- /**
1540
- * Present on `kind: "mcp_local"` — the model-facing tool name as declared on
1541
- * the wire. Always equals `name`; surfaced as a separate field for the SDK's
1542
- * convenience when dispatching into a local MCP client.
1543
- */
1544
- mcpToolName?: string;
1545
- /**
1546
- * Present on `kind: "mcp_local"` — the verbatim `Implementation` block from
1547
- * MCP `Initialize`, echoed back for observability.
1548
- */
1549
- mcpServerInfo?: {
1550
- name: string;
1551
- version?: string;
1552
- [k: string]: unknown;
1553
- };
1554
- }
1555
- interface LocalToolResultInEvent extends RunEventBase {
1556
- type: "local_tool_result_in";
1557
- toolUseId: string;
1558
- result?: string;
1559
- error?: string;
1560
- }
1561
- /**
1562
- * Observability event fired when the loop-detection guard intervenes.
1563
- * The synthetic skip + steering nudge are emitted on the normal
1564
- * `tool_result` / `assistant_delta` channels; this event lets the SDK
1565
- * render a status note (`looping — nudged` / `looping — gave up`).
1566
- *
1567
- * `hardCutoff: false` is the soft nudge round; `true` is the forced
1568
- * finalise. The same run may emit one of each.
1569
- */
1570
- interface LoopDetectedEvent extends RunEventBase {
1571
- type: "loop_detected";
1572
- /** Length of the identical-batch streak that just tripped the threshold. */
1573
- consecutiveCount: number;
1574
- /** `false` for the soft nudge round; `true` once the pipeline forces finalisation. */
1575
- hardCutoff: boolean;
1576
- /** Names of the tool calls in the looping batch (no args). */
1577
- tools: string[];
1578
- }
1579
- /**
1580
- * Observability event fired when a tool-budget interception happens. The
1581
- * synthetic "budget exceeded — pivot or finalize" tool result lands on the
1582
- * normal `tool_result` channel before this event fires; the SDK uses this
1583
- * event to render UI banners (`memory budget exhausted` etc.) without
1584
- * re-parsing tool-result bodies.
1585
- */
1586
- interface ToolBudgetExceededEvent extends RunEventBase {
1587
- type: "tool_budget_exceeded";
1588
- /** Logical tool name (matches the key in `spec.toolBudgets`). */
1589
- tool: string;
1590
- /** Configured cap. */
1591
- maxCalls: number;
1592
- /**
1593
- * 1-based count of attempts to call this tool over the run lifetime.
1594
- * Always strictly greater than `maxCalls`.
1595
- */
1596
- callIndex: number;
1597
- }
1598
- /**
1599
- * Observability event fired on every run-supervisor review — including
1600
- * `on_track` checks. When `action` is `redirect` or `finalize`, the pipeline
1601
- * has already injected the steering message or forced a tools-disabled turn
1602
- * by the time this event arrives; the SDK should render a status note and
1603
- * keep consuming the stream.
1604
- */
1605
- interface SupervisorEvent extends RunEventBase {
1606
- type: "supervisor";
1607
- /** One of `"on_track"`, `"redirect"`, `"finalize"`. */
1608
- action: SupervisorAction;
1609
- /** One- or two-sentence explanation from the judge. */
1610
- reason: string;
1611
- /**
1612
- * Present when `action === "redirect"`: the steering user message injected
1613
- * into the conversation. Omitted for `on_track` / `finalize`.
1614
- */
1615
- redirect?: string;
1616
- /**
1617
- * Number of LLM calls completed when this review fired. Matches the
1618
- * pipeline's `modelInvocations` counter at the check boundary.
1619
- */
1620
- llmCalls: number;
1621
- /**
1622
- * `"turn_boundary"` (default cadence review) or `"reasoning"` (mid-turn
1623
- * review while a long reasoning span was still streaming). Omitted is
1624
- * equivalent to `"turn_boundary"`.
1625
- */
1626
- phase?: SupervisorPhase;
1627
- }
1628
- /**
1629
- * Live checklist update for an in-product task plan. Non-terminal — the run
1630
- * continues until `result` / `error` / `cancelled`. See §4.9.
1631
- */
1632
- interface TaskPlanEvent extends RunEventBase {
1633
- type: "task_plan";
1634
- brief?: string;
1635
- steps: TaskPlanStep[];
1636
- }
1637
- interface ResultEvent extends RunEventBase {
1638
- type: "result";
1639
- subtype: string;
1640
- text?: string;
1641
- error?: string;
1642
- /** Present on plan-only terminal results. See {@link RunResult.plan}. */
1643
- plan?: TaskPlan;
1644
- /**
1645
- * Per-run token totals. Present against MANTYX ≥ 2026-09 — see
1646
- * {@link RunTokenUsage} and `docs/agent-runs-protocol.md` §7.1.
1647
- */
1648
- tokens?: RunTokenUsage;
1649
- /** Total model invocations for the run. See {@link RunResult.turns}. */
1650
- turns?: number;
1651
- /** Resolved model that executed the run. See {@link RunModelInfo}. */
1652
- model?: RunModelInfo;
1653
- }
1654
- interface ErrorEvent extends RunEventBase {
1655
- type: "error";
1656
- /** Human-readable failure message. */
1657
- error: string;
1658
- /**
1659
- * Legacy alias for {@link errorClass}. Equals `errorClass` when present;
1660
- * otherwise a small lowercase token (`"error"`, `"invalid_spec"`,
1661
- * `"worker_error"`, …).
1662
- */
1663
- code?: string;
1664
- /**
1665
- * Canonical failure category. One of `"rate_limit"`, `"overloaded"`,
1666
- * `"server"`, `"context_window"`, `"truncation"`, `"invalid_request"`,
1667
- * `"auth"`, `"timeout"`, `"local_timeout"`, `"upstream_deadline"`,
1668
- * `"unknown"`. New categories may land additively. See
1669
- * `docs/agent-runs-protocol.md` §7 for the full list.
1670
- */
1671
- errorClass?: string;
1672
- /**
1673
- * Canonical lowercase stop reason normalized across providers
1674
- * (`"max_tokens"`, `"refusal"`, `"malformed_function_call"`, …). When
1675
- * present, mirrors the value on the last `assistant_message` event.
1676
- */
1677
- finishReason?: string | null;
1678
- /**
1679
- * **Best-effort raw bytes** the model emitted before the failure. For
1680
- * `outputSchema` runs this is likely **incomplete JSON** that will
1681
- * fail `JSON.parse` — see the wire-protocol truncation contract. Also
1682
- * persisted on `EphemeralAgentRun.finalText` so SDKs can recover it
1683
- * via `GET /agent-runs/:runId` after the SSE stream closes.
1684
- */
1685
- partialText?: string;
1686
- /**
1687
- * Coarse retry hint inherited from the pipeline's error classifier.
1688
- * Informational; the SDK still owns the actual retry decision.
1689
- */
1690
- retryable?: boolean;
1691
- /**
1692
- * Per-run token totals. Present against MANTYX ≥ 2026-09 — see
1693
- * {@link RunTokenUsage} and `docs/agent-runs-protocol.md` §7.1.
1694
- * The pipeline counts the failing model call too, so a run that
1695
- * threw on the first turn reports `turns: 1` with that call's
1696
- * tokens already aggregated.
1697
- */
1698
- tokens?: RunTokenUsage;
1699
- /** Total model invocations for the run, including the failing call. */
1700
- turns?: number;
1701
- /** Resolved model that executed the run. See {@link RunModelInfo}. */
1702
- model?: RunModelInfo;
1703
- }
1704
- interface CancelledEvent extends RunEventBase {
1705
- type: "cancelled";
1706
- reason?: string;
1707
- }
1708
- /**
1709
- * Replay/restore-only frame returned by {@link MantyxClient.getSessionEvents}
1710
- * (and the `GET /agent-sessions/:id/events` endpoint). The live SSE stream
1711
- * never emits this — the client already knows the prompt it sent — but
1712
- * conversation restoration needs it to rebuild the user side of the thread.
1713
- */
1714
- interface UserMessageEvent extends RunEventBase {
1715
- type: "user_message";
1716
- text: string;
1717
- /** Present on session-event replay when the user turn carried file inputs. */
1718
- attachments?: AttachmentMetadata[];
1719
- }
1720
- type RunEvent = AssistantDeltaEvent | ThinkingDeltaEvent | AssistantMessageEvent | UserMessageEvent | ServerToolResultEvent | LocalToolCallEvent | LocalToolResultInEvent | LoopDetectedEvent | ToolBudgetExceededEvent | SupervisorEvent | TaskPlanEvent | ResultEvent | ErrorEvent | CancelledEvent | (RunEventBase & {
1721
- type: string;
1722
- [key: string]: unknown;
1723
- });
1724
- interface SessionInfo {
1725
- id: string;
1726
- name: string;
1727
- status: "active" | "ended";
1728
- createdAt: string;
1729
- lastUsedAt: string;
1730
- endedAt: string | null;
1731
- agentSpec: AgentSpecBase;
1732
- messages: ConversationMessage[];
1733
- /** Metadata that was attached to the session at create time, returned for observability. */
1734
- metadata: Record<string, string>;
1735
- }
1736
- /** One row from {@link MantyxClient.listSessions}. */
1737
- interface SessionSummary {
1738
- sessionId: string;
1739
- /** ISO 8601 creation timestamp. */
1740
- creationDate: string;
1741
- /** ISO 8601 timestamp of the most recent message run. */
1742
- lastInteractionDate: string;
1743
- /** Best-effort label derived from the first user prompt (sessions have no title). */
1744
- summary: string;
1745
- metadata: Record<string, string>;
1746
- status: "active" | "ended";
1747
- }
1748
- /** Paginated result of {@link MantyxClient.listSessions}. */
1749
- interface SessionListResult {
1750
- total: number;
1751
- limit: number;
1752
- offset: number;
1753
- sessions: SessionSummary[];
1754
- }
1755
- declare class MantyxClient {
1756
- readonly options: Required<Pick<MantyxClientOptions, "workspaceSlug" | "baseUrl">> & {
1757
- /**
1758
- * Single resolved bearer credential — either a workspace API key
1759
- * (token prefix `mantyx_`) or an OAuth access token (`mantyx_at_…`).
1760
- * The SDK does not need to distinguish them on the wire; the value
1761
- * is forwarded verbatim on `Authorization: Bearer …`.
1762
- *
1763
- * Kept as `apiKey` (instead of e.g. `credential`) for backwards
1764
- * compatibility — older releases exposed it under this name.
1765
- *
1766
- * Empty string when a {@link tokenSource} is configured — every
1767
- * request resolves the bearer from the source instead.
1768
- */
1769
- apiKey: string;
1770
- fetch: typeof fetch;
1771
- timeoutMs: number;
1772
- /**
1773
- * Dynamic credential provider when constructed with
1774
- * `tokenSource` — see {@link MantyxClientOptions.tokenSource}.
1775
- * `null` for static `apiKey` / `accessToken` clients.
1776
- */
1777
- tokenSource: TokenSource | null;
1778
- };
1779
- constructor(opts: MantyxClientOptions);
1780
- listModels(): Promise<ModelCatalog>;
1781
- runAgent(spec: RunSpec): Promise<RunResult>;
1782
- /**
1783
- * Plan-only run: classify (or accept caller `steps`) and return the
1784
- * structured checklist without executing the agent loop. Sugar for
1785
- * `runAgent({ ..., plan: planOnly({ steps, brief }) })`.
1786
- *
1787
- * The final checklist is on {@link RunResult.plan}; intermediate
1788
- * progress is available via `task_plan` events when streaming.
1789
- */
1790
- runPlan(spec: Omit<RunSpec, "plan"> & {
1791
- steps?: string[];
1792
- brief?: string;
1793
- }): Promise<RunResult>;
1794
- streamAgent(spec: RunSpec): AsyncGenerator<RunEvent, void, void>;
1795
- /**
1796
- * Internal registry of client-resolved tool handlers. Exposed for callers
1797
- * who drive the run loop manually via `driveRun` / `streamRunEvents`.
1798
- */
1799
- collectHandlers(tools: ToolRef[]): LocalHandlers;
1800
- createSession(spec: SessionSpec): Promise<AgentSession>;
1801
- /**
1802
- * Re-emit a `local_tool_call` event into the right local handler. Useful
1803
- * for tests and for users who consume events via `streamAgent` themselves.
1804
- */
1805
- dispatchLocalToolFromEvent(runId: string, ev: LocalToolCallEvent, handlers: LocalHandlers): Promise<void>;
1806
- resumeSession(sessionId: string, opts?: {
1807
- tools?: ToolRef[];
1808
- }): Promise<AgentSession>;
1809
- endSession(sessionId: string): Promise<void>;
1810
- getSessionInfo(sessionId: string): Promise<SessionInfo>;
1811
- /**
1812
- * List the workspace's sessions, most-recently-used first. Filter by the
1813
- * metadata you attached at create time so you can find earlier sessions by
1814
- * your own identifiers (customer id, environment, …). Multiple metadata
1815
- * entries are AND-combined server-side.
1816
- */
1817
- listSessions(opts?: {
1818
- metadata?: Record<string, string>;
1819
- status?: "active" | "ended";
1820
- limit?: number;
1821
- offset?: number;
1822
- }): Promise<SessionListResult>;
1823
- /**
1824
- * Fetch a session's conversation as realtime-style event frames so a UI can
1825
- * restore the thread through the same handler it uses for the live stream.
1826
- * Returns `user_message` / `assistant_message` frames (see the wire protocol
1827
- * §6.2). Pass `lastMessages` to fetch only the most recent turns, or
1828
- * `full: true` for the entire history (the default).
1829
- */
1830
- getSessionEvents(sessionId: string, opts?: {
1831
- full?: boolean;
1832
- lastMessages?: number;
1833
- }): Promise<RunEvent[]>;
1834
- /** Drive an existing run to completion (collect events, dispatch local tools). */
1835
- driveRun(runId: string, handlers: LocalHandlers, opts?: {
1836
- onAssistantDelta?: (delta: string) => void;
1837
- onEvent?: (event: RunEvent) => void;
1838
- signal?: AbortSignal;
1839
- }): Promise<RunResult>;
1840
- streamRunEvents(runId: string, handlers: LocalHandlers, signal?: AbortSignal): AsyncGenerator<RunEvent, void, void>;
1841
- dispatchLocalTool(runId: string, ev: LocalToolCallEvent, handlers: LocalHandlers): Promise<void>;
1842
- postToolResult(runId: string, toolUseId: string, payload: {
1843
- result?: string;
1844
- error?: string;
1845
- files?: ToolResultFile[];
1846
- }): Promise<void>;
1847
- cancelRun(runId: string): Promise<void>;
1848
- /**
1849
- * Record thumbs up/down feedback on a run. Requires the `feedback:write`
1850
- * OAuth scope (workspace API keys have implicit access). Idempotent per
1851
- * run — the first call returns HTTP 201, updates return 200; both carry
1852
- * the same response body. See `docs/agent-runs-protocol.md` §9a.
1853
- */
1854
- submitRunFeedback(runId: string, input: RunFeedbackInput): Promise<RunFeedbackResult>;
1855
- listEvalDatasets(): Promise<EvalDatasetList>;
1856
- getEvalDataset(datasetId: string): Promise<EvalDatasetDetail>;
1857
- createEvalRun(spec: CreateEvalRunRequest): Promise<EvalRunAccepted>;
1858
- listEvalRuns(options?: ListEvalRunsOptions): Promise<EvalRunList>;
1859
- compareEvalRuns(runA: string, runB: string): Promise<EvalRunCompare>;
1860
- getEvalRun(runId: string): Promise<EvalRunDetail>;
1861
- streamEvalRun(runId: string, signal?: AbortSignal): AsyncGenerator<EvalRunEvent, void, void>;
1862
- cancelEvalRun(runId: string): Promise<{
1863
- ok: boolean;
1864
- }>;
1865
- /**
1866
- * Start an eval run and block until it reaches a terminal status.
1867
- * Tails the SSE stream for live `onEvent` callbacks while polling
1868
- * `getEvalRun` until `status` is terminal.
1869
- */
1870
- runEval(spec: CreateEvalRunRequest, options?: RunEvalOptions): Promise<EvalRunDetail>;
1871
- private absoluteUrl;
1872
- /**
1873
- * Resolve the bearer credential to send on the next request. With a
1874
- * static `apiKey` / `accessToken` this is a synchronous reach into
1875
- * `options.apiKey`; with a {@link TokenSource} it delegates so the
1876
- * source can refresh expired access tokens before we hit the wire.
1877
- *
1878
- * The `reason` is forwarded to the source verbatim. Pass
1879
- * `"unauthorized"` immediately after a 401 so the source forces a
1880
- * refresh rather than handing back its (now-invalid) cached value.
1881
- */
1882
- private resolveBearer;
1883
- /**
1884
- * Open an SSE stream against `reqUrl` with at-most-one refresh +
1885
- * retry on 401. The caller is responsible for the subsequent
1886
- * `readSseStream` loop; this helper only handles the initial GET.
1887
- * Mid-stream 401s propagate as `MantyxNetworkError` from the read
1888
- * loop and trigger a reconnect via the outer `while` in
1889
- * {@link streamRunEvents}.
1890
- */
1891
- private openSseStream;
1892
- private authHeaders;
1893
- request<T>(args: {
1894
- method: string;
1895
- path: string;
1896
- body?: unknown;
1897
- /**
1898
- * Optional query params. Array values are repeated (`?k=a&k=b`); `undefined`
1899
- * entries are dropped. Used by the list endpoints (e.g. repeated `metadata`).
1900
- */
1901
- query?: Record<string, string | string[] | number | undefined>;
1902
- timeoutMs?: number;
1903
- }): Promise<T>;
1904
- private requestWithRetry;
1905
- private errorFromResponse;
1906
- }
1907
- declare class AgentSession {
1908
- readonly id: string;
1909
- readonly client: MantyxClient;
1910
- private readonly handlers;
1911
- private readonly tools;
1912
- constructor(client: MantyxClient, id: string, handlers: LocalHandlers, tools?: ToolRef[]);
1913
- send(promptOrMessages: string | ConversationMessage[], opts?: {
1914
- onAssistantDelta?: (s: string) => void;
1915
- signal?: AbortSignal;
1916
- /**
1917
- * File inputs for a single `prompt` turn. Ignored when the first
1918
- * argument is a `messages` array. See `docs/agent-runs-protocol.md`
1919
- * §4.0.1.
1920
- */
1921
- attachments?: MessageAttachment[];
1922
- /**
1923
- * Per-message metadata override. Server-side this is merged on top of
1924
- * the session's metadata at run-creation time (run-level keys win).
1925
- * Useful for tagging individual turns (e.g. `{ "trace_id": "abc" }`).
1926
- */
1927
- metadata?: Record<string, string>;
1928
- /**
1929
- * Per-message override for `reasoningLevel`. Applies only to this run
1930
- * and does not mutate the session's stored value.
1931
- */
1932
- reasoningLevel?: ReasoningLevel;
1933
- /**
1934
- * Per-message override for `outputSchema`. Applies only to this run
1935
- * and does not mutate the session's stored value.
1936
- */
1937
- outputSchema?: OutputSchema;
1938
- /**
1939
- * Per-message override for `loopDetection`. Applies only to this run
1940
- * and does not mutate the session's stored value. Pass `false` to
1941
- * disable the guard for this single turn.
1942
- */
1943
- loopDetection?: LoopDetection | false;
1944
- /**
1945
- * Per-message override for `toolBudgets`. Applies only to this run
1946
- * and does not mutate the session's stored value.
1947
- */
1948
- toolBudgets?: ToolBudgets;
1949
- /**
1950
- * Per-message override for `supervisor`. Applies only to this run
1951
- * and does not mutate the session's stored value. Pass `false` to
1952
- * disable the platform judge for this single turn.
1953
- */
1954
- supervisor?: Supervisor | false;
1955
- /**
1956
- * Per-message override for `plan`. Applies only to this run and does
1957
- * not mutate the session's stored value. See {@link AgentSpecBase.plan}.
1958
- */
1959
- plan?: PlanSpec;
1960
- }): Promise<RunResult>;
1961
- stream(promptOrMessages: string | ConversationMessage[], opts?: {
1962
- signal?: AbortSignal;
1963
- attachments?: MessageAttachment[];
1964
- metadata?: Record<string, string>;
1965
- reasoningLevel?: ReasoningLevel;
1966
- outputSchema?: OutputSchema;
1967
- loopDetection?: LoopDetection | false;
1968
- toolBudgets?: ToolBudgets;
1969
- supervisor?: Supervisor | false;
1970
- plan?: PlanSpec;
1971
- }): AsyncGenerator<RunEvent, void, void>;
1972
- private buildSessionMessageBody;
1973
- /**
1974
- * Plan-only session turn. Sugar for `send(prompt, { plan: planOnly(...) })`.
1975
- */
1976
- runPlan(promptOrMessages: string | ConversationMessage[], opts?: {
1977
- onAssistantDelta?: (s: string) => void;
1978
- signal?: AbortSignal;
1979
- metadata?: Record<string, string>;
1980
- reasoningLevel?: ReasoningLevel;
1981
- outputSchema?: OutputSchema;
1982
- loopDetection?: LoopDetection | false;
1983
- toolBudgets?: ToolBudgets;
1984
- supervisor?: Supervisor | false;
1985
- steps?: string[];
1986
- brief?: string;
1987
- }): Promise<RunResult>;
1988
- history(): Promise<ConversationMessage[]>;
1989
- info(): Promise<SessionInfo>;
1990
- end(): Promise<void>;
1991
- }
1992
- /** Internal registry of client-resolved handlers, indexed by `kind`. */
1993
- interface LocalHandlers {
1994
- /** `kind: "local"` — generic local tools, indexed by tool name. */
1995
- localTools: Map<string, LocalTool>;
1996
- /** `kind: "a2a_local"` — local A2A peers, indexed by tool name. */
1997
- a2aTools: Map<string, LocalA2ATool>;
1998
- /** `kind: "mcp_local"` — local MCP servers, indexed by server name. */
1999
- mcpServers: Map<string, LocalMcpServer>;
2000
- }
2001
- /**
2002
- * Parse the terminal text of a `RunResult` as JSON.
2003
- *
2004
- * When the run was submitted with `outputSchema`, MANTYX (via the LLM
2005
- * provider) guarantees the reply parses as JSON in the *vast* majority of
2006
- * cases. Transient model errors (refusal text, truncation under
2007
- * `max_tokens` pressure, exotic Unicode) can still produce strings that
2008
- * fail to `JSON.parse` in rare edge cases — this helper centralises that
2009
- * brittle step and surfaces a typed {@link MantyxParseError} on failure
2010
- * with the original text preserved on `err.text`.
2011
- *
2012
- * Pass an optional `validator` (zod's `.parse`, an Ajv compiled validator,
2013
- * or any function) to re-validate against your source-of-truth schema. The
2014
- * validator's return value (or thrown error) is forwarded to the caller.
2015
- *
2016
- * @example
2017
- * ```ts
2018
- * import { z } from "zod";
2019
- * import { parseRunOutput } from "@mantyx/sdk";
2020
- *
2021
- * const Schema = z.object({ city: z.string(), temperature_c: z.number() });
2022
- * const result = await client.runAgent({
2023
- * systemPrompt: "...",
2024
- * prompt: "What's the weather in SF?",
2025
- * outputSchema: { name: "weather_report", schema: weatherJsonSchema },
2026
- * });
2027
- * const report = parseRunOutput(result, Schema.parse.bind(Schema));
2028
- * // ^? { city: string; temperature_c: number }
2029
- * ```
2030
- */
2031
- declare function parseRunOutput<T = unknown>(result: RunResult, validator?: (value: unknown) => T): T;
2032
-
2033
- export { type LoopDetection as $, type A2AToolRef as A, type EvalRunSummary as B, type CancelledEvent as C, DEFAULT_BASE_URL as D, type ErrorEvent as E, type InlineEvalDatasetSpec as F, type InputFileAttachment as G, type InputFileAttachmentMetadata as H, type InlineEvalCaseSpec as I, type InputFileUrlAttachment as J, type InputFileUrlAttachmentMetadata as K, type ListEvalRunsOptions as L, MantyxClient as M, type LocalA2ATool as N, type OutputSchema as O, type LocalHandlers as P, type LocalMcpHttpTransport as Q, type ReasoningLevel as R, type LocalMcpServer as S, type ToolRef as T, type LocalMcpStdioTransport as U, type LocalTool as V, type LocalToolCallEvent as W, type LocalToolOutput as X, type LocalToolResult as Y, type LocalToolResultInEvent as Z, type LoopDetectedEvent as _, type AgentEvalOverrides as a, defineLocalA2A as a$, type MantyxA2AOptions as a0, MantyxAuthError as a1, type MantyxClientOptions as a2, MantyxError as a3, type MantyxMcpOptions as a4, MantyxNetworkError as a5, MantyxOAuthClient as a6, type MantyxOAuthClientOptions as a7, MantyxOAuthError as a8, MantyxParseError as a9, type RunFeedbackVerdict as aA, type RunModelInfo as aB, type RunResult as aC, type RunSpec as aD, type RunTokenUsage as aE, type ServerToolResultEvent as aF, type SessionInfo as aG, type SessionListResult as aH, type SessionSpec as aI, type SessionSummary as aJ, type Supervisor as aK, type SupervisorAction as aL, type SupervisorEvent as aM, type SupervisorPhase as aN, type TaskPlan as aO, type TaskPlanEvent as aP, type TaskPlanStep as aQ, type TaskPlanStepStatus as aR, type ThinkingDeltaEvent as aS, type TokenRequestReason as aT, type TokenSource as aU, type ToolBudget as aV, type ToolBudgetExceededEvent as aW, type ToolBudgets as aX, type ToolResultFile as aY, type UserMessageEvent as aZ, type ZodLikeObject as a_, type MantyxPluginToolRef as aa, MantyxRunError as ab, type MantyxRunErrorInit as ac, type MantyxRunErrorModel as ad, type MantyxRunErrorTokens as ae, MantyxScopeError as af, MantyxToolError as ag, type MantyxToolRef as ah, type McpToolRef as ai, type MessageAttachment as aj, type ModelCatalog as ak, type ModelInfo as al, type OAuthToken as am, type OutputSchemaValue as an, type PlanOptions as ao, type PlanSpec as ap, type ReasoningTrigger as aq, type RefreshOptions as ar, type RefreshTokenSourceOptions as as, type ResultEvent as at, type RevokeOptions as au, type RunEvalOptions as av, type RunEvent as aw, type RunEventBase as ax, type RunFeedbackInput as ay, type RunFeedbackResult as az, AgentSession as b, defineLocalMcp as b0, defineLocalTool as b1, inputFileAttachment as b2, inputFileUrlAttachment as b3, isLocalA2ATool as b4, isLocalMcpServer as b5, isLocalTool as b6, mantyxA2A as b7, mantyxMcp as b8, mantyxPluginTool as b9, mantyxTool as ba, parseRunOutput as bb, planOnly as bc, type AgentSpecBase as c, type AssistantDeltaEvent as d, type AssistantMessageEvent as e, type AttachmentMetadata as f, type ConversationMessage as g, type CreateEvalRunRequest as h, DEFAULT_OAUTH_BASE_URL as i, DEFAULT_REFRESH_SKEW_MS as j, type DefineLocalA2AOptions as k, type DefineLocalMcpOptions as l, type DefineLocalToolOptions as m, type EvalCase as n, type EvalCaseResult as o, type EvalDatasetDetail as p, type EvalDatasetList as q, type EvalDatasetSummary as r, type EvalRunAccepted as s, type EvalRunCompare as t, type EvalRunCompareCase as u, type EvalRunCompareSide as v, type EvalRunDetail as w, type EvalRunEvent as x, type EvalRunList as y, type EvalRunStatus as z };