@mantyx/sdk 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -843,6 +843,22 @@ interface AgentSpecBase {
843
843
  * `docs/agent-runs-protocol.md` §4.7.
844
844
  */
845
845
  toolBudgets?: ToolBudgets;
846
+ /**
847
+ * Run-supervisor (platform LLM judge). Periodically reviews the agent's
848
+ * transcript and may steer the run (`on_track`, `redirect`, `finalize`).
849
+ *
850
+ * Pass an object to override the review interval, or `false` to explicitly
851
+ * disable the platform judge for this run / session. When omitted on
852
+ * ephemeral API runs, MANTYX enables the supervisor (default interval `5`).
853
+ * SDK-only runs (`runAgent` without the HTTP API) keep the supervisor off
854
+ * unless you pass a value here. See `docs/agent-runs-protocol.md` §4.8.
855
+ *
856
+ * Each review emits an observability-only `supervisor` SSE event — including
857
+ * `on_track` checks — so the SDK can render supervisor activity. When
858
+ * `action` is `redirect` or `finalize`, the pipeline has already applied
859
+ * the verdict by the time the event arrives.
860
+ */
861
+ supervisor?: Supervisor | false;
846
862
  /**
847
863
  * Flat string→string KV carried alongside the run / session for
848
864
  * observability. Use it to tag runs with your own application identifiers
@@ -870,6 +886,13 @@ interface RunSpec extends AgentSpecBase {
870
886
  signal?: AbortSignal;
871
887
  }
872
888
  type SessionSpec = AgentSpecBase;
889
+ /**
890
+ * Either a Zod schema (auto-converted to JSON Schema by the SDK) or a
891
+ * pre-shaped JSON Schema object. Mirrors {@link LocalToolSchemaInput} and
892
+ * Go's `OutputSchema.Schema any` (struct reflection) — pass your
893
+ * source-of-truth schema and the SDK serialises it for the wire.
894
+ */
895
+ type OutputSchemaValue = LocalToolSchemaInput;
873
896
  /**
874
897
  * Constrains the final assistant text to a JSON document matching a
875
898
  * JSON Schema. See {@link AgentSpecBase.outputSchema} for the full
@@ -878,8 +901,8 @@ type SessionSpec = AgentSpecBase;
878
901
  interface OutputSchema {
879
902
  /** Optional. Defaults to `"output"`. Must match `/^[a-zA-Z0-9_-]{1,64}$/`. */
880
903
  name?: string;
881
- /** Required. JSON Schema describing the final assistant text. Root must be a JSON object. */
882
- schema: Record<string, unknown>;
904
+ /** Required. Zod schema or JSON Schema describing the final assistant text. Root must be a JSON object. */
905
+ schema: OutputSchemaValue;
883
906
  }
884
907
  /**
885
908
  * Loop-detection thresholds. See {@link AgentSpecBase.loopDetection} for the
@@ -925,6 +948,20 @@ interface ToolBudget {
925
948
  * entirely to keep the defaults.
926
949
  */
927
950
  type ToolBudgets = Record<string, ToolBudget>;
951
+ /**
952
+ * Run-supervisor configuration. See {@link AgentSpecBase.supervisor} for the
953
+ * full semantics. Pass `false` (instead of an object) to disable the platform
954
+ * judge for the run / session.
955
+ *
956
+ * `interval` is optional; when omitted the MANTYX runtime default is **5**
957
+ * LLM calls between reviews. Server-side upper bound: `100`.
958
+ */
959
+ interface Supervisor {
960
+ /** LLM calls (`completeTurn` invocations) between supervisor reviews. */
961
+ interval?: number;
962
+ }
963
+ /** Verdict from a run-supervisor review. */
964
+ type SupervisorAction = "on_track" | "redirect" | "finalize";
928
965
  /**
929
966
  * Per-run token totals attached to terminal `result` / `error` events
930
967
  * (and to the `GET /agent-runs/:runId` snapshot) by MANTYX ≥ 2026-09.
@@ -1164,6 +1201,30 @@ interface ToolBudgetExceededEvent extends RunEventBase {
1164
1201
  */
1165
1202
  callIndex: number;
1166
1203
  }
1204
+ /**
1205
+ * Observability event fired on every run-supervisor review — including
1206
+ * `on_track` checks. When `action` is `redirect` or `finalize`, the pipeline
1207
+ * has already injected the steering message or forced a tools-disabled turn
1208
+ * by the time this event arrives; the SDK should render a status note and
1209
+ * keep consuming the stream.
1210
+ */
1211
+ interface SupervisorEvent extends RunEventBase {
1212
+ type: "supervisor";
1213
+ /** One of `"on_track"`, `"redirect"`, `"finalize"`. */
1214
+ action: SupervisorAction;
1215
+ /** One- or two-sentence explanation from the judge. */
1216
+ reason: string;
1217
+ /**
1218
+ * Present when `action === "redirect"`: the steering user message injected
1219
+ * into the conversation. Omitted for `on_track` / `finalize`.
1220
+ */
1221
+ redirect?: string;
1222
+ /**
1223
+ * Number of LLM calls completed when this review fired. Matches the
1224
+ * pipeline's `modelInvocations` counter at the check boundary.
1225
+ */
1226
+ llmCalls: number;
1227
+ }
1167
1228
  interface ResultEvent extends RunEventBase {
1168
1229
  type: "result";
1169
1230
  subtype: string;
@@ -1233,7 +1294,17 @@ interface CancelledEvent extends RunEventBase {
1233
1294
  type: "cancelled";
1234
1295
  reason?: string;
1235
1296
  }
1236
- type RunEvent = AssistantDeltaEvent | ThinkingDeltaEvent | AssistantMessageEvent | ServerToolResultEvent | LocalToolCallEvent | LocalToolResultInEvent | LoopDetectedEvent | ToolBudgetExceededEvent | ResultEvent | ErrorEvent | CancelledEvent | (RunEventBase & {
1297
+ /**
1298
+ * Replay/restore-only frame returned by {@link MantyxClient.getSessionEvents}
1299
+ * (and the `GET /agent-sessions/:id/events` endpoint). The live SSE stream
1300
+ * never emits this — the client already knows the prompt it sent — but
1301
+ * conversation restoration needs it to rebuild the user side of the thread.
1302
+ */
1303
+ interface UserMessageEvent extends RunEventBase {
1304
+ type: "user_message";
1305
+ text: string;
1306
+ }
1307
+ type RunEvent = AssistantDeltaEvent | ThinkingDeltaEvent | AssistantMessageEvent | UserMessageEvent | ServerToolResultEvent | LocalToolCallEvent | LocalToolResultInEvent | LoopDetectedEvent | ToolBudgetExceededEvent | SupervisorEvent | ResultEvent | ErrorEvent | CancelledEvent | (RunEventBase & {
1237
1308
  type: string;
1238
1309
  [key: string]: unknown;
1239
1310
  });
@@ -1252,6 +1323,25 @@ interface SessionInfo {
1252
1323
  /** Metadata that was attached to the session at create time, returned for observability. */
1253
1324
  metadata: Record<string, string>;
1254
1325
  }
1326
+ /** One row from {@link MantyxClient.listSessions}. */
1327
+ interface SessionSummary {
1328
+ sessionId: string;
1329
+ /** ISO 8601 creation timestamp. */
1330
+ creationDate: string;
1331
+ /** ISO 8601 timestamp of the most recent message run. */
1332
+ lastInteractionDate: string;
1333
+ /** Best-effort label derived from the first user prompt (sessions have no title). */
1334
+ summary: string;
1335
+ metadata: Record<string, string>;
1336
+ status: "active" | "ended";
1337
+ }
1338
+ /** Paginated result of {@link MantyxClient.listSessions}. */
1339
+ interface SessionListResult {
1340
+ total: number;
1341
+ limit: number;
1342
+ offset: number;
1343
+ sessions: SessionSummary[];
1344
+ }
1255
1345
  declare class MantyxClient {
1256
1346
  readonly options: Required<Pick<MantyxClientOptions, "workspaceSlug" | "baseUrl">> & {
1257
1347
  /**
@@ -1296,6 +1386,29 @@ declare class MantyxClient {
1296
1386
  }): Promise<AgentSession>;
1297
1387
  endSession(sessionId: string): Promise<void>;
1298
1388
  getSessionInfo(sessionId: string): Promise<SessionInfo>;
1389
+ /**
1390
+ * List the workspace's sessions, most-recently-used first. Filter by the
1391
+ * metadata you attached at create time so you can find earlier sessions by
1392
+ * your own identifiers (customer id, environment, …). Multiple metadata
1393
+ * entries are AND-combined server-side.
1394
+ */
1395
+ listSessions(opts?: {
1396
+ metadata?: Record<string, string>;
1397
+ status?: "active" | "ended";
1398
+ limit?: number;
1399
+ offset?: number;
1400
+ }): Promise<SessionListResult>;
1401
+ /**
1402
+ * Fetch a session's conversation as realtime-style event frames so a UI can
1403
+ * restore the thread through the same handler it uses for the live stream.
1404
+ * Returns `user_message` / `assistant_message` frames (see the wire protocol
1405
+ * §6.2). Pass `lastMessages` to fetch only the most recent turns, or
1406
+ * `full: true` for the entire history (the default).
1407
+ */
1408
+ getSessionEvents(sessionId: string, opts?: {
1409
+ full?: boolean;
1410
+ lastMessages?: number;
1411
+ }): Promise<RunEvent[]>;
1299
1412
  /** Drive an existing run to completion (collect events, dispatch local tools). */
1300
1413
  driveRun(runId: string, handlers: LocalHandlers, opts?: {
1301
1414
  onAssistantDelta?: (delta: string) => void;
@@ -1335,6 +1448,11 @@ declare class MantyxClient {
1335
1448
  method: string;
1336
1449
  path: string;
1337
1450
  body?: unknown;
1451
+ /**
1452
+ * Optional query params. Array values are repeated (`?k=a&k=b`); `undefined`
1453
+ * entries are dropped. Used by the list endpoints (e.g. repeated `metadata`).
1454
+ */
1455
+ query?: Record<string, string | string[] | number | undefined>;
1338
1456
  timeoutMs?: number;
1339
1457
  }): Promise<T>;
1340
1458
  private requestWithRetry;
@@ -1376,6 +1494,12 @@ declare class AgentSession {
1376
1494
  * and does not mutate the session's stored value.
1377
1495
  */
1378
1496
  toolBudgets?: ToolBudgets;
1497
+ /**
1498
+ * Per-message override for `supervisor`. Applies only to this run
1499
+ * and does not mutate the session's stored value. Pass `false` to
1500
+ * disable the platform judge for this single turn.
1501
+ */
1502
+ supervisor?: Supervisor | false;
1379
1503
  }): Promise<RunResult>;
1380
1504
  stream(prompt: string, opts?: {
1381
1505
  signal?: AbortSignal;
@@ -1384,6 +1508,7 @@ declare class AgentSession {
1384
1508
  outputSchema?: OutputSchema;
1385
1509
  loopDetection?: LoopDetection | false;
1386
1510
  toolBudgets?: ToolBudgets;
1511
+ supervisor?: Supervisor | false;
1387
1512
  }): AsyncGenerator<RunEvent, void, void>;
1388
1513
  private buildSessionMessageBody;
1389
1514
  history(): Promise<Array<{
@@ -1434,4 +1559,4 @@ interface LocalHandlers {
1434
1559
  */
1435
1560
  declare function parseRunOutput<T = unknown>(result: RunResult, validator?: (value: unknown) => T): T;
1436
1561
 
1437
- export { type RunEvent as $, type A2AToolRef as A, MantyxOAuthError as B, type CancelledEvent as C, DEFAULT_BASE_URL as D, type ErrorEvent as E, MantyxParseError as F, type MantyxPluginToolRef as G, MantyxRunError as H, type MantyxRunErrorInit as I, type MantyxRunErrorModel as J, type MantyxRunErrorTokens as K, type LocalA2ATool as L, MantyxClient as M, MantyxScopeError as N, MantyxToolError as O, type MantyxToolRef as P, type McpToolRef as Q, type ReasoningLevel as R, type ModelCatalog as S, type ToolRef as T, type ModelInfo as U, type OAuthToken as V, type OutputSchema as W, type RefreshOptions as X, type RefreshTokenSourceOptions as Y, type ResultEvent as Z, type RevokeOptions as _, AgentSession as a, type RunEventBase as a0, type RunModelInfo as a1, type RunResult as a2, type RunSpec as a3, type RunTokenUsage as a4, type ServerToolResultEvent as a5, type SessionInfo as a6, type SessionSpec as a7, type ThinkingDeltaEvent as a8, type TokenRequestReason as a9, type TokenSource as aa, type ToolBudget as ab, type ToolBudgetExceededEvent as ac, type ToolBudgets as ad, type ZodLikeObject as ae, defineLocalA2A as af, defineLocalMcp as ag, defineLocalTool as ah, isLocalA2ATool as ai, isLocalMcpServer as aj, isLocalTool as ak, mantyxA2A as al, mantyxMcp as am, mantyxPluginTool as an, mantyxTool as ao, parseRunOutput as ap, type AgentSpecBase as b, type AssistantDeltaEvent as c, type AssistantMessageEvent as d, DEFAULT_OAUTH_BASE_URL as e, DEFAULT_REFRESH_SKEW_MS as f, type DefineLocalA2AOptions as g, type DefineLocalMcpOptions as h, type DefineLocalToolOptions as i, type LocalHandlers as j, type LocalMcpHttpTransport as k, type LocalMcpServer as l, type LocalMcpStdioTransport as m, type LocalTool as n, type LocalToolCallEvent as o, type LocalToolResultInEvent as p, type LoopDetectedEvent as q, type LoopDetection as r, type MantyxA2AOptions as s, MantyxAuthError as t, type MantyxClientOptions as u, MantyxError as v, type MantyxMcpOptions as w, MantyxNetworkError as x, MantyxOAuthClient as y, type MantyxOAuthClientOptions as z };
1562
+ export { type RevokeOptions as $, type A2AToolRef as A, MantyxOAuthError as B, type CancelledEvent as C, DEFAULT_BASE_URL as D, type ErrorEvent as E, MantyxParseError as F, type MantyxPluginToolRef as G, MantyxRunError as H, type MantyxRunErrorInit as I, type MantyxRunErrorModel as J, type MantyxRunErrorTokens as K, type LocalA2ATool as L, MantyxClient as M, MantyxScopeError as N, type OutputSchema as O, MantyxToolError as P, type MantyxToolRef as Q, type ReasoningLevel as R, type McpToolRef as S, type ToolRef as T, type ModelCatalog as U, type ModelInfo as V, type OAuthToken as W, type OutputSchemaValue as X, type RefreshOptions as Y, type RefreshTokenSourceOptions as Z, type ResultEvent as _, AgentSession as a, type RunEvent as a0, type RunEventBase as a1, type RunModelInfo as a2, type RunResult as a3, type RunSpec as a4, type RunTokenUsage as a5, type ServerToolResultEvent as a6, type SessionInfo as a7, type SessionListResult as a8, type SessionSpec as a9, type SessionSummary as aa, type Supervisor as ab, type SupervisorAction as ac, type SupervisorEvent as ad, type ThinkingDeltaEvent as ae, type TokenRequestReason as af, type TokenSource as ag, type ToolBudget as ah, type ToolBudgetExceededEvent as ai, type ToolBudgets as aj, type UserMessageEvent as ak, type ZodLikeObject as al, defineLocalA2A as am, defineLocalMcp as an, defineLocalTool as ao, isLocalA2ATool as ap, isLocalMcpServer as aq, isLocalTool as ar, mantyxA2A as as, mantyxMcp as at, mantyxPluginTool as au, mantyxTool as av, parseRunOutput as aw, type AgentSpecBase as b, type AssistantDeltaEvent as c, type AssistantMessageEvent as d, DEFAULT_OAUTH_BASE_URL as e, DEFAULT_REFRESH_SKEW_MS as f, type DefineLocalA2AOptions as g, type DefineLocalMcpOptions as h, type DefineLocalToolOptions as i, type LocalHandlers as j, type LocalMcpHttpTransport as k, type LocalMcpServer as l, type LocalMcpStdioTransport as m, type LocalTool as n, type LocalToolCallEvent as o, type LocalToolResultInEvent as p, type LoopDetectedEvent as q, type LoopDetection as r, type MantyxA2AOptions as s, MantyxAuthError as t, type MantyxClientOptions as u, MantyxError as v, type MantyxMcpOptions as w, MantyxNetworkError as x, MantyxOAuthClient as y, type MantyxOAuthClientOptions as z };
package/dist/index.cjs CHANGED
@@ -658,6 +658,19 @@ function toToolParametersWire(parameters) {
658
658
 
659
659
  // src/client.ts
660
660
  var DEFAULT_BASE_URL = "https://app.mantyx.io";
661
+ function buildQueryString(query) {
662
+ if (!query) return "";
663
+ const parts = [];
664
+ for (const [key, value] of Object.entries(query)) {
665
+ if (value === void 0) continue;
666
+ const values = Array.isArray(value) ? value : [value];
667
+ for (const v of values) {
668
+ if (v === void 0) continue;
669
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);
670
+ }
671
+ }
672
+ return parts.length > 0 ? `?${parts.join("&")}` : "";
673
+ }
661
674
  var MantyxClient = class {
662
675
  options;
663
676
  constructor(opts) {
@@ -775,6 +788,47 @@ var MantyxClient = class {
775
788
  path: `/agent-sessions/${encodeURIComponent(sessionId)}`
776
789
  });
777
790
  }
791
+ /**
792
+ * List the workspace's sessions, most-recently-used first. Filter by the
793
+ * metadata you attached at create time so you can find earlier sessions by
794
+ * your own identifiers (customer id, environment, …). Multiple metadata
795
+ * entries are AND-combined server-side.
796
+ */
797
+ async listSessions(opts = {}) {
798
+ const query = {};
799
+ if (opts.metadata) {
800
+ const pairs = Object.entries(opts.metadata).map(([k, v]) => `${k}:${v}`);
801
+ if (pairs.length > 0) query.metadata = pairs;
802
+ }
803
+ if (opts.status) query.status = opts.status;
804
+ if (typeof opts.limit === "number") query.limit = opts.limit;
805
+ if (typeof opts.offset === "number") query.offset = opts.offset;
806
+ return this.request({
807
+ method: "GET",
808
+ path: "/agent-sessions",
809
+ query
810
+ });
811
+ }
812
+ /**
813
+ * Fetch a session's conversation as realtime-style event frames so a UI can
814
+ * restore the thread through the same handler it uses for the live stream.
815
+ * Returns `user_message` / `assistant_message` frames (see the wire protocol
816
+ * §6.2). Pass `lastMessages` to fetch only the most recent turns, or
817
+ * `full: true` for the entire history (the default).
818
+ */
819
+ async getSessionEvents(sessionId, opts = {}) {
820
+ const query = {};
821
+ if (opts.full) query.full = "1";
822
+ else if (typeof opts.lastMessages === "number") {
823
+ query.lastMessages = opts.lastMessages;
824
+ }
825
+ const res = await this.request({
826
+ method: "GET",
827
+ path: `/agent-sessions/${encodeURIComponent(sessionId)}/events`,
828
+ query
829
+ });
830
+ return res.events ?? [];
831
+ }
778
832
  // ----------------------------------------------------------- Internals
779
833
  /** Drive an existing run to completion (collect events, dispatch local tools). */
780
834
  async driveRun(runId, handlers, opts = {}) {
@@ -993,7 +1047,7 @@ var MantyxClient = class {
993
1047
  return this.requestWithRetry(args, "initial");
994
1048
  }
995
1049
  async requestWithRetry(args, reason) {
996
- const url = this.absoluteUrl(args.path);
1050
+ const url = this.absoluteUrl(args.path) + buildQueryString(args.query);
997
1051
  const ctrl = new AbortController();
998
1052
  const t = setTimeout(() => ctrl.abort(), args.timeoutMs ?? this.options.timeoutMs);
999
1053
  try {
@@ -1102,6 +1156,9 @@ var AgentSession = class {
1102
1156
  if (opts.toolBudgets !== void 0) {
1103
1157
  body.toolBudgets = normalizeToolBudgets(opts.toolBudgets);
1104
1158
  }
1159
+ if (opts.supervisor !== void 0) {
1160
+ body.supervisor = normalizeSupervisor(opts.supervisor);
1161
+ }
1105
1162
  return body;
1106
1163
  }
1107
1164
  async history() {
@@ -1142,6 +1199,9 @@ function serializeAgentSpec(spec, extra = {}) {
1142
1199
  if (spec.toolBudgets !== void 0) {
1143
1200
  body.toolBudgets = normalizeToolBudgets(spec.toolBudgets);
1144
1201
  }
1202
+ if (spec.supervisor !== void 0) {
1203
+ body.supervisor = normalizeSupervisor(spec.supervisor);
1204
+ }
1145
1205
  if (spec.budgets) body.budgets = spec.budgets;
1146
1206
  if (spec.metadata && Object.keys(spec.metadata).length > 0) body.metadata = spec.metadata;
1147
1207
  if (extra.prompt !== void 0) body.prompt = extra.prompt;
@@ -1277,10 +1337,12 @@ function normalizeOutputSchema(value) {
1277
1337
  }
1278
1338
  out.name = value.name;
1279
1339
  }
1280
- const schema = value.schema;
1340
+ const schema = toToolParametersWire(
1341
+ value.schema
1342
+ );
1281
1343
  if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
1282
1344
  throw new MantyxError(
1283
- `outputSchema.schema must be a non-null JSON object (the JSON Schema root)`
1345
+ `outputSchema.schema must be a Zod schema or a non-null JSON object (the JSON Schema root)`
1284
1346
  );
1285
1347
  }
1286
1348
  out.schema = schema;
@@ -1346,6 +1408,19 @@ function assertThreshold(label, value, min) {
1346
1408
  var TOOL_BUDGETS_MAX_ENTRIES = 32;
1347
1409
  var TOOL_BUDGET_MAX_NAME_LEN = 120;
1348
1410
  var TOOL_BUDGET_MAX_CALLS = 1e3;
1411
+ function normalizeSupervisor(value) {
1412
+ if (value === false) return false;
1413
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1414
+ throw new MantyxError(
1415
+ `supervisor must be an object or the literal \`false\`, got ${JSON.stringify(value)}`
1416
+ );
1417
+ }
1418
+ const out = {};
1419
+ if (value.interval !== void 0) {
1420
+ out.interval = assertThreshold("supervisor.interval", value.interval, 1);
1421
+ }
1422
+ return out;
1423
+ }
1349
1424
  function normalizeToolBudgets(value) {
1350
1425
  if (!value || typeof value !== "object" || Array.isArray(value)) {
1351
1426
  throw new MantyxError(
@@ -1700,7 +1775,7 @@ function normalizeScope(scope) {
1700
1775
  }
1701
1776
 
1702
1777
  // src/version.ts
1703
- var SDK_VERSION = "0.11.0";
1778
+ var SDK_VERSION = "0.13.0";
1704
1779
  // Annotate the CommonJS export names for ESM import in node:
1705
1780
  0 && (module.exports = {
1706
1781
  AgentSession,