@mantyx/sdk 0.14.0 → 0.15.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.
- package/CHANGELOG.md +14 -0
- package/dist/a2a-server.cjs.map +1 -1
- package/dist/a2a-server.d.cts +1 -1
- package/dist/a2a-server.d.ts +1 -1
- package/dist/a2a-server.js +1 -1
- package/dist/{chunk-XENCO3EF.js → chunk-YXTU725K.js} +103 -31
- package/dist/chunk-YXTU725K.js.map +1 -0
- package/dist/{client-Ct6G4TVc.d.cts → client-fu11V4HX.d.cts} +73 -16
- package/dist/{client-Ct6G4TVc.d.ts → client-fu11V4HX.d.ts} +73 -16
- package/dist/index.cjs +105 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/docs/agent-runs-protocol.md +79 -17
- package/docs/wire-protocol.md +56 -21
- package/package.json +1 -1
- package/dist/chunk-XENCO3EF.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, C as CancelledEvent, D as DEFAULT_BASE_URL,
|
|
1
|
+
export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, e as AttachmentMetadata, C as CancelledEvent, f as ConversationMessage, D as DEFAULT_BASE_URL, g as DEFAULT_OAUTH_BASE_URL, h as DEFAULT_REFRESH_SKEW_MS, i as DefineLocalA2AOptions, j as DefineLocalMcpOptions, k as DefineLocalToolOptions, E as ErrorEvent, I as InputFileAttachment, l as InputFileAttachmentMetadata, m as InputFileUrlAttachment, n as InputFileUrlAttachmentMetadata, L as LocalA2ATool, o as LocalHandlers, p as LocalMcpHttpTransport, q as LocalMcpServer, r as LocalMcpStdioTransport, s as LocalTool, t as LocalToolCallEvent, u as LocalToolResultInEvent, v as LoopDetectedEvent, w as LoopDetection, x as MantyxA2AOptions, y as MantyxAuthError, M as MantyxClient, z as MantyxClientOptions, B as MantyxError, F as MantyxMcpOptions, G as MantyxNetworkError, H as MantyxOAuthClient, J as MantyxOAuthClientOptions, K as MantyxOAuthError, N as MantyxParseError, P as MantyxPluginToolRef, Q as MantyxRunError, S as MantyxRunErrorInit, U as MantyxRunErrorModel, V as MantyxRunErrorTokens, W as MantyxScopeError, X as MantyxToolError, Y as MantyxToolRef, Z as McpToolRef, _ as MessageAttachment, $ as ModelCatalog, a0 as ModelInfo, a1 as OAuthToken, O as OutputSchema, a2 as OutputSchemaValue, a3 as PlanOptions, a4 as PlanSpec, R as ReasoningLevel, a5 as RefreshOptions, a6 as RefreshTokenSourceOptions, a7 as ResultEvent, a8 as RevokeOptions, a9 as RunEvent, aa as RunEventBase, ab as RunModelInfo, ac as RunResult, ad as RunSpec, ae as RunTokenUsage, af as ServerToolResultEvent, ag as SessionInfo, ah as SessionListResult, ai as SessionSpec, aj as SessionSummary, ak as Supervisor, al as SupervisorAction, am as SupervisorEvent, an as TaskPlan, ao as TaskPlanEvent, ap as TaskPlanStep, aq as TaskPlanStepStatus, ar as ThinkingDeltaEvent, as as TokenRequestReason, at as TokenSource, au as ToolBudget, av as ToolBudgetExceededEvent, aw as ToolBudgets, T as ToolRef, ax as UserMessageEvent, ay as ZodLikeObject, az as defineLocalA2A, aA as defineLocalMcp, aB as defineLocalTool, aC as inputFileAttachment, aD as inputFileUrlAttachment, aE as isLocalA2ATool, aF as isLocalMcpServer, aG as isLocalTool, aH as mantyxA2A, aI as mantyxMcp, aJ as mantyxPluginTool, aK as mantyxTool, aL as parseRunOutput, aM as planOnly } from './client-fu11V4HX.cjs';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Lightweight Zod → JSON Schema converter for tool parameter definitions.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* Resolution order:
|
|
8
|
+
* 1. `schema.toJSONSchema()` on the instance (Zod v4; works across package
|
|
9
|
+
* copies when the user's `zod` and the SDK's `zod` are different installs)
|
|
10
|
+
* 2. `z.toJSONSchema(schema)` from the SDK's `zod` import (Zod v4, same copy)
|
|
11
|
+
* 3. Hand-rolled walker for Zod v3 `typeName` and Zod v4 `_def.type`
|
|
9
12
|
*
|
|
10
13
|
* The output is a JSON-Schema-shaped object with `type: "object"`, `properties`,
|
|
11
14
|
* and `required`. The MANTYX server feeds this to LLM providers verbatim, so
|
|
@@ -52,6 +55,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
|
|
|
52
55
|
/**
|
|
53
56
|
* Release version — synced from repo root VERSION (`npm run sync-version`).
|
|
54
57
|
*/
|
|
55
|
-
declare const SDK_VERSION = "0.
|
|
58
|
+
declare const SDK_VERSION = "0.15.1";
|
|
56
59
|
|
|
57
60
|
export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, C as CancelledEvent, D as DEFAULT_BASE_URL,
|
|
1
|
+
export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, e as AttachmentMetadata, C as CancelledEvent, f as ConversationMessage, D as DEFAULT_BASE_URL, g as DEFAULT_OAUTH_BASE_URL, h as DEFAULT_REFRESH_SKEW_MS, i as DefineLocalA2AOptions, j as DefineLocalMcpOptions, k as DefineLocalToolOptions, E as ErrorEvent, I as InputFileAttachment, l as InputFileAttachmentMetadata, m as InputFileUrlAttachment, n as InputFileUrlAttachmentMetadata, L as LocalA2ATool, o as LocalHandlers, p as LocalMcpHttpTransport, q as LocalMcpServer, r as LocalMcpStdioTransport, s as LocalTool, t as LocalToolCallEvent, u as LocalToolResultInEvent, v as LoopDetectedEvent, w as LoopDetection, x as MantyxA2AOptions, y as MantyxAuthError, M as MantyxClient, z as MantyxClientOptions, B as MantyxError, F as MantyxMcpOptions, G as MantyxNetworkError, H as MantyxOAuthClient, J as MantyxOAuthClientOptions, K as MantyxOAuthError, N as MantyxParseError, P as MantyxPluginToolRef, Q as MantyxRunError, S as MantyxRunErrorInit, U as MantyxRunErrorModel, V as MantyxRunErrorTokens, W as MantyxScopeError, X as MantyxToolError, Y as MantyxToolRef, Z as McpToolRef, _ as MessageAttachment, $ as ModelCatalog, a0 as ModelInfo, a1 as OAuthToken, O as OutputSchema, a2 as OutputSchemaValue, a3 as PlanOptions, a4 as PlanSpec, R as ReasoningLevel, a5 as RefreshOptions, a6 as RefreshTokenSourceOptions, a7 as ResultEvent, a8 as RevokeOptions, a9 as RunEvent, aa as RunEventBase, ab as RunModelInfo, ac as RunResult, ad as RunSpec, ae as RunTokenUsage, af as ServerToolResultEvent, ag as SessionInfo, ah as SessionListResult, ai as SessionSpec, aj as SessionSummary, ak as Supervisor, al as SupervisorAction, am as SupervisorEvent, an as TaskPlan, ao as TaskPlanEvent, ap as TaskPlanStep, aq as TaskPlanStepStatus, ar as ThinkingDeltaEvent, as as TokenRequestReason, at as TokenSource, au as ToolBudget, av as ToolBudgetExceededEvent, aw as ToolBudgets, T as ToolRef, ax as UserMessageEvent, ay as ZodLikeObject, az as defineLocalA2A, aA as defineLocalMcp, aB as defineLocalTool, aC as inputFileAttachment, aD as inputFileUrlAttachment, aE as isLocalA2ATool, aF as isLocalMcpServer, aG as isLocalTool, aH as mantyxA2A, aI as mantyxMcp, aJ as mantyxPluginTool, aK as mantyxTool, aL as parseRunOutput, aM as planOnly } from './client-fu11V4HX.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Lightweight Zod → JSON Schema converter for tool parameter definitions.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* Resolution order:
|
|
8
|
+
* 1. `schema.toJSONSchema()` on the instance (Zod v4; works across package
|
|
9
|
+
* copies when the user's `zod` and the SDK's `zod` are different installs)
|
|
10
|
+
* 2. `z.toJSONSchema(schema)` from the SDK's `zod` import (Zod v4, same copy)
|
|
11
|
+
* 3. Hand-rolled walker for Zod v3 `typeName` and Zod v4 `_def.type`
|
|
9
12
|
*
|
|
10
13
|
* The output is a JSON-Schema-shaped object with `type: "object"`, `properties`,
|
|
11
14
|
* and `required`. The MANTYX server feeds this to LLM providers verbatim, so
|
|
@@ -52,6 +55,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
|
|
|
52
55
|
/**
|
|
53
56
|
* Release version — synced from repo root VERSION (`npm run sync-version`).
|
|
54
57
|
*/
|
|
55
|
-
declare const SDK_VERSION = "0.
|
|
58
|
+
declare const SDK_VERSION = "0.15.1";
|
|
56
59
|
|
|
57
60
|
export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,8 @@ import {
|
|
|
12
12
|
defineLocalA2A,
|
|
13
13
|
defineLocalMcp,
|
|
14
14
|
defineLocalTool,
|
|
15
|
+
inputFileAttachment,
|
|
16
|
+
inputFileUrlAttachment,
|
|
15
17
|
isLocalA2ATool,
|
|
16
18
|
isLocalMcpServer,
|
|
17
19
|
isLocalTool,
|
|
@@ -24,7 +26,7 @@ import {
|
|
|
24
26
|
readSseStream,
|
|
25
27
|
toToolParametersWire,
|
|
26
28
|
zodToJsonSchema
|
|
27
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-YXTU725K.js";
|
|
28
30
|
|
|
29
31
|
// src/oauth.ts
|
|
30
32
|
var DEFAULT_OAUTH_BASE_URL = "https://app.mantyx.io";
|
|
@@ -246,7 +248,7 @@ function normalizeScope(scope) {
|
|
|
246
248
|
}
|
|
247
249
|
|
|
248
250
|
// src/version.ts
|
|
249
|
-
var SDK_VERSION = "0.
|
|
251
|
+
var SDK_VERSION = "0.15.1";
|
|
250
252
|
export {
|
|
251
253
|
AgentSession,
|
|
252
254
|
DEFAULT_BASE_URL,
|
|
@@ -266,6 +268,8 @@ export {
|
|
|
266
268
|
defineLocalA2A,
|
|
267
269
|
defineLocalMcp,
|
|
268
270
|
defineLocalTool,
|
|
271
|
+
inputFileAttachment,
|
|
272
|
+
inputFileUrlAttachment,
|
|
269
273
|
isLocalA2ATool,
|
|
270
274
|
isLocalMcpServer,
|
|
271
275
|
isLocalTool,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/oauth.ts","../src/version.ts"],"sourcesContent":["/**\n * MANTYX OAuth 2.0 refresh client: trade a stored refresh token for\n * short-lived access tokens, revoke tokens at sign-out, and expose\n * a {@link TokenSource} the {@link MantyxClient} HTTP layer calls\n * before every request (and again on 401).\n *\n * The library is intentionally **refresh-only**. It assumes the caller\n * already obtained the refresh token through their own sign-in flow\n * (Authorization Code + PKCE in a browser, native redirect, server-\n * side exchange — whatever fits the host application). The SDK does\n * not drive consent, does not initiate auth-code exchanges, and does\n * not bundle PKCE helpers.\n *\n * Wire contract (`docs/oauth.md`):\n *\n * - Token endpoint: `POST <baseUrl>/api/oauth/token`, form-encoded,\n * `grant_type=refresh_token`. Echoes back the same `refresh_token`\n * the client sent (refresh tokens are persistent and non-rotating).\n * - Revoke endpoint: `POST <baseUrl>/api/oauth/revoke`, form-encoded.\n * - Access tokens (`mantyx_at_…`) live 1 hour (`expires_in: 3600`).\n * - Refresh tokens (`mantyx_rt_…`) are long-lived; the caller persists\n * them once at first sign-in (encrypted at rest) and the SDK re-mints\n * access tokens from the same value on demand.\n */\n\nimport { MantyxError, MantyxNetworkError } from \"./errors.js\";\n\nexport const DEFAULT_OAUTH_BASE_URL = \"https://app.mantyx.io\";\n\n/** Skew (ms) before `expiresAt` at which a TokenSource will pre-emptively refresh. Default 60s. */\nexport const DEFAULT_REFRESH_SKEW_MS = 60_000;\n\n/**\n * Raised on a non-2xx response from `POST /api/oauth/token` or\n * `POST /api/oauth/revoke`. Carries the RFC 6749 `error` discriminator\n * (`\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`,\n * …) and the optional `error_description` so callers can branch on\n * machine-readable values without parsing the human message.\n *\n * `invalid_grant` from the refresh path specifically signals that the\n * refresh token has been revoked (or the OAuth grant / application\n * was deleted). The SDK never loops on this — callers should route\n * the user back to a fresh sign-in.\n */\nexport class MantyxOAuthError extends MantyxError {\n readonly oauthError: string;\n readonly oauthErrorDescription: string | undefined;\n\n constructor(\n oauthError: string,\n oauthErrorDescription: string | undefined,\n status: number,\n ) {\n const message = oauthErrorDescription\n ? `OAuth ${oauthError}: ${oauthErrorDescription}`\n : `OAuth ${oauthError}`;\n super(message, { code: oauthError, status });\n this.name = \"MantyxOAuthError\";\n this.oauthError = oauthError;\n this.oauthErrorDescription = oauthErrorDescription;\n }\n}\n\n/**\n * Decoded `POST /api/oauth/token` response, augmented with an absolute\n * `expiresAt` timestamp the SDK uses to decide when to refresh.\n *\n * On the refresh grant the response's `refreshToken` is identical to\n * the value the client just sent (refresh tokens never rotate). The\n * field is surfaced for symmetry with whatever the calling app's\n * sign-in flow already does.\n */\nexport interface OAuthToken {\n readonly accessToken: string;\n readonly refreshToken: string | undefined;\n readonly tokenType: string;\n readonly expiresIn: number;\n /** Absolute Unix-ms timestamp set when the SDK parsed the response. */\n readonly expiresAt: number;\n readonly scope: string | undefined;\n}\n\n/** Why the SDK asked the {@link TokenSource} for the current access token. */\nexport type TokenRequestReason = \"initial\" | \"expired\" | \"unauthorized\";\n\n/**\n * A `TokenSource` produces the current access token on demand. The\n * {@link MantyxClient} HTTP layer calls it before every request. When\n * called with `reason: \"unauthorized\"` the source MUST force a refresh\n * (do not return a cached value); this is how the SDK recovers from\n * 401s caused by a token that the server already invalidated.\n *\n * Implementations should be safe to call from many concurrent requests.\n */\nexport type TokenSource = (reason?: TokenRequestReason) => Promise<string>;\n\n/** Caller-supplied options for `MantyxOAuthClient`. */\nexport interface MantyxOAuthClientOptions {\n /**\n * OAuth `client_id` issued at app registration (token prefix\n * `mantyx_oa_`).\n */\n clientId: string;\n /**\n * OAuth `client_secret` issued at app registration (token prefix\n * `mantyx_oas_`). Every MANTYX OAuth app is a confidential client,\n * so this is always required for token + revoke calls. Treat as a\n * deployment secret — do not bundle into browser builds.\n */\n clientSecret: string;\n /**\n * Origin of the MANTYX deployment. Defaults to `https://app.mantyx.io`.\n * The OAuth endpoints are mounted at `<baseUrl>/api/oauth/...`.\n */\n baseUrl?: string;\n /** Optional `fetch` override (e.g. node-fetch wrapper). Default: global `fetch`. */\n fetch?: typeof fetch;\n /** Default per-request timeout in milliseconds. Default: 30s. */\n timeoutMs?: number;\n}\n\nexport interface RefreshOptions {\n refreshToken: string;\n /**\n * Optional scope narrowing. Must be a subset of the scopes already\n * granted to the refresh token (server enforces this). Useful when\n * an SDK consumer wants a short-scope access token for a specific\n * sub-operation.\n */\n scope?: string | readonly string[];\n}\n\nexport interface RevokeOptions {\n token: string;\n}\n\nexport interface RefreshTokenSourceOptions {\n refreshToken: string;\n /** Optional scope narrowing applied on every refresh. */\n scope?: string | readonly string[];\n /**\n * How many ms before `expiresAt` the source proactively refreshes.\n * Defaults to {@link DEFAULT_REFRESH_SKEW_MS} (60s).\n */\n refreshSkewMs?: number;\n /**\n * Optional initial access token + expiry to seed the source's cache\n * with (e.g. the token already in hand from the host application's\n * sign-in flow). When omitted, the source mints one on the first\n * call.\n */\n initialToken?: OAuthToken;\n}\n\n/**\n * Refresh-only wrapper around the MANTYX OAuth 2.0 authorization-server\n * endpoints. App-scoped (one per `{clientId, clientSecret}` pair);\n * construct independently of {@link MantyxClient}, then either call\n * {@link refresh} / {@link revoke} directly or hand a `TokenSource`\n * produced by {@link refreshTokenSource} to `MantyxClient` for fully\n * transparent refresh on every request.\n *\n * The client deliberately does **not** drive the authorization-code\n * exchange or any other \"initiate sign-in\" grant. The caller is\n * expected to obtain the refresh token through their own consent flow\n * and persist it before constructing this client.\n */\nexport class MantyxOAuthClient {\n readonly clientId: string;\n readonly baseUrl: string;\n private readonly clientSecret: string;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n\n constructor(opts: MantyxOAuthClientOptions) {\n if (!opts.clientId) {\n throw new MantyxError(\"`clientId` is required for MantyxOAuthClient\");\n }\n if (!opts.clientSecret) {\n throw new MantyxError(\"`clientSecret` is required for MantyxOAuthClient\");\n }\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new MantyxError(\n \"Global fetch is not available; pass a custom `fetch` implementation in MantyxOAuthClientOptions.\",\n );\n }\n this.clientId = opts.clientId;\n this.clientSecret = opts.clientSecret;\n this.baseUrl = (opts.baseUrl ?? DEFAULT_OAUTH_BASE_URL).replace(/\\/+$/, \"\");\n this.fetchImpl = f;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n /**\n * Mint a fresh access token from a stored refresh token. The\n * returned `refreshToken` is identical to the input — refresh\n * tokens are persistent and non-rotating, so the field is\n * surfaced only for symmetry with the response shape.\n *\n * On `400 invalid_grant` the refresh token has been revoked (or its\n * grant / app was deleted); the SDK surfaces a\n * {@link MantyxOAuthError} and callers must drive a fresh sign-in.\n */\n async refresh(opts: RefreshOptions): Promise<OAuthToken> {\n if (!opts.refreshToken) {\n throw new MantyxError(\"`refreshToken` is required for MantyxOAuthClient.refresh\");\n }\n const body: Record<string, string> = {\n grant_type: \"refresh_token\",\n refresh_token: opts.refreshToken,\n };\n const scope = normalizeScope(opts.scope);\n if (scope !== undefined) body.scope = scope;\n return this.token(body);\n }\n\n /**\n * Revoke an access or refresh token (RFC 7009). The server always\n * returns 200, even for unknown tokens. Revoking a **refresh**\n * token kills the refresh and every live access token tied to its\n * grant; revoking an **access** token kills only that one.\n */\n async revoke(opts: RevokeOptions): Promise<void> {\n if (!opts.token) {\n throw new MantyxError(\"`token` is required for MantyxOAuthClient.revoke\");\n }\n await this.formPost(\"/api/oauth/revoke\", {\n token: opts.token,\n });\n }\n\n /**\n * Build a long-lived {@link TokenSource} that re-mints access\n * tokens from the supplied refresh token. Pass the returned source\n * to `new MantyxClient({ tokenSource, workspaceSlug, ... })`. The\n * source caches the access token in-memory and refreshes\n * proactively when the cached value is within `refreshSkewMs` of\n * `expiresAt`, or eagerly when `MantyxClient` reports a 401.\n *\n * Pass `initialToken` if the calling app already has a non-expired\n * access token in hand (e.g. straight out of the sign-in flow) to\n * avoid an extra round-trip on the first request.\n */\n refreshTokenSource(opts: RefreshTokenSourceOptions): TokenSource {\n if (!opts.refreshToken) {\n throw new MantyxError(\"`refreshToken` is required for MantyxOAuthClient.refreshTokenSource\");\n }\n const skew = opts.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;\n const cache: TokenCache = { token: opts.initialToken, inflight: null };\n const refreshToken = opts.refreshToken;\n return makeTokenSource(cache, skew, async () => {\n return this.refresh({ refreshToken, scope: opts.scope });\n });\n }\n\n // -------------------------------------------------------------- internals\n\n /**\n * POST `application/x-www-form-urlencoded` to `/api/oauth/token` and\n * decode the {@link OAuthToken} response. Always injects `client_id`\n * + `client_secret` from the constructor.\n */\n private async token(body: Record<string, string>): Promise<OAuthToken> {\n const res = await this.formPost(\"/api/oauth/token\", body);\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (await res.json()) as Record<string, unknown>;\n } catch {\n throw new MantyxOAuthError(\n \"invalid_response\",\n \"Token endpoint returned a non-JSON response\",\n res.status,\n );\n }\n const accessToken = typeof parsed.access_token === \"string\" ? parsed.access_token : \"\";\n if (!accessToken) {\n throw new MantyxOAuthError(\n \"invalid_response\",\n \"Token endpoint response is missing `access_token`\",\n res.status,\n );\n }\n const expiresIn = typeof parsed.expires_in === \"number\" ? parsed.expires_in : 3600;\n return {\n accessToken,\n refreshToken: typeof parsed.refresh_token === \"string\" ? parsed.refresh_token : undefined,\n tokenType: typeof parsed.token_type === \"string\" ? parsed.token_type : \"Bearer\",\n expiresIn,\n expiresAt: Date.now() + expiresIn * 1000,\n scope: typeof parsed.scope === \"string\" ? parsed.scope : undefined,\n };\n }\n\n private async formPost(path: string, body: Record<string, string>): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const params = new URLSearchParams({\n ...body,\n client_id: this.clientId,\n client_secret: this.clientSecret,\n });\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: params.toString(),\n signal: ctrl.signal,\n });\n } catch (err) {\n if (ctrl.signal.aborted) {\n throw new MantyxNetworkError(`OAuth request timed out after ${this.timeoutMs}ms`);\n }\n throw new MantyxNetworkError(`OAuth network error: ${(err as Error).message}`, {\n cause: err,\n });\n } finally {\n clearTimeout(t);\n }\n if (!res.ok) {\n let errBody: { error?: unknown; error_description?: unknown } = {};\n try {\n errBody = (await res.json()) as typeof errBody;\n } catch {\n // ignore\n }\n const oauthError = typeof errBody.error === \"string\" ? errBody.error : `http_${res.status}`;\n const desc =\n typeof errBody.error_description === \"string\" ? errBody.error_description : undefined;\n throw new MantyxOAuthError(oauthError, desc, res.status);\n }\n return res;\n }\n}\n\n// -------------------------------------------------------------- internals\n\ninterface TokenCache {\n token: OAuthToken | undefined;\n inflight: Promise<OAuthToken> | null;\n}\n\n/**\n * Wrap a `mintToken` thunk into a single-flight {@link TokenSource}\n * with a cache + proactive-refresh skew. The cache is overwritten\n * atomically on every successful mint; the in-flight promise\n * collapses N concurrent expired-token observers into one mint call.\n *\n * Single-flight is an efficiency, not a correctness requirement —\n * `docs/oauth.md` explicitly allows multiple concurrent refreshes\n * against the same refresh token — but it keeps the token-endpoint\n * QPS reasonable when an SDK consumer fans out work in parallel.\n */\nfunction makeTokenSource(\n cache: TokenCache,\n skewMs: number,\n mint: () => Promise<OAuthToken>,\n): TokenSource {\n return async (reason: TokenRequestReason = \"initial\"): Promise<string> => {\n if (reason !== \"unauthorized\" && cache.token && !isExpiring(cache.token, skewMs)) {\n return cache.token.accessToken;\n }\n if (cache.inflight) {\n const t = await cache.inflight;\n if (reason === \"unauthorized\" && t === cache.token) {\n // If the inflight refresh was triggered by a benign cache miss\n // and we observed an unauthorized hint after it started, fall\n // through and mint again so the caller never gets a stale token.\n } else {\n return t.accessToken;\n }\n }\n cache.inflight = mint().then(\n (t) => {\n cache.token = t;\n return t;\n },\n (err: unknown) => {\n throw err;\n },\n );\n try {\n const t = await cache.inflight;\n return t.accessToken;\n } finally {\n cache.inflight = null;\n }\n };\n}\n\nfunction isExpiring(token: OAuthToken, skewMs: number): boolean {\n return token.expiresAt - Date.now() <= skewMs;\n}\n\nfunction normalizeScope(scope: string | readonly string[] | undefined): string | undefined {\n if (scope === undefined) return undefined;\n if (typeof scope === \"string\") {\n const trimmed = scope.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n const joined = scope.filter((s) => typeof s === \"string\" && s.length > 0).join(\" \");\n return joined.length > 0 ? joined : undefined;\n}\n","/**\n * Release version — synced from repo root VERSION (`npm run sync-version`).\n */\nexport const SDK_VERSION = \"0.14.0\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,IAAM,yBAAyB;AAG/B,IAAM,0BAA0B;AAchC,IAAM,mBAAN,cAA+B,YAAY;AAAA,EACvC;AAAA,EACA;AAAA,EAET,YACE,YACA,uBACA,QACA;AACA,UAAM,UAAU,wBACZ,SAAS,UAAU,KAAK,qBAAqB,KAC7C,SAAS,UAAU;AACvB,UAAM,SAAS,EAAE,MAAM,YAAY,OAAO,CAAC;AAC3C,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,wBAAwB;AAAA,EAC/B;AACF;AA0GO,IAAM,oBAAN,MAAwB;AAAA,EACpB;AAAA,EACA;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AA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A,MACtB,CAAC,MAAM;AACL,cAAM,QAAQ;AACd,eAAO;AAAA,MACT;AAAA,MACA,CAAC,QAAiB;AAChB,cAAM;AAAA,MACR;AAAA,IACF;AACA,QAAI;AACF,YAAM,IAAI,MAAM,MAAM;AACtB,aAAO,EAAE;AAAA,IACX,UAAE;AACA,YAAM,WAAW;AAAA,IACnB;AAAA,EACF;AACF;AAEA,SAAS,WAAW,OAAmB,QAAyB;AAC9D,SAAO,MAAM,YAAY,KAAK,IAAI,KAAK;AACzC;AAEA,SAAS,eAAe,OAAmE;AACzF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,WAAO,QAAQ,SAAS,IAAI,UAAU;AAAA,EACxC;AACA,QAAM,SAAS,MAAM,OAAO,CAAC,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,EAAE,KAAK,GAAG;AAClF,SAAO,OAAO,SAAS,IAAI,SAAS;AACtC;;;ACpZO,IAAM,cAAc;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/oauth.ts","../src/version.ts"],"sourcesContent":["/**\n * MANTYX OAuth 2.0 refresh client: trade a stored refresh token for\n * short-lived access tokens, revoke tokens at sign-out, and expose\n * a {@link TokenSource} the {@link MantyxClient} HTTP layer calls\n * before every request (and again on 401).\n *\n * The library is intentionally **refresh-only**. It assumes the caller\n * already obtained the refresh token through their own sign-in flow\n * (Authorization Code + PKCE in a browser, native redirect, server-\n * side exchange — whatever fits the host application). The SDK does\n * not drive consent, does not initiate auth-code exchanges, and does\n * not bundle PKCE helpers.\n *\n * Wire contract (`docs/oauth.md`):\n *\n * - Token endpoint: `POST <baseUrl>/api/oauth/token`, form-encoded,\n * `grant_type=refresh_token`. Echoes back the same `refresh_token`\n * the client sent (refresh tokens are persistent and non-rotating).\n * - Revoke endpoint: `POST <baseUrl>/api/oauth/revoke`, form-encoded.\n * - Access tokens (`mantyx_at_…`) live 1 hour (`expires_in: 3600`).\n * - Refresh tokens (`mantyx_rt_…`) are long-lived; the caller persists\n * them once at first sign-in (encrypted at rest) and the SDK re-mints\n * access tokens from the same value on demand.\n */\n\nimport { MantyxError, MantyxNetworkError } from \"./errors.js\";\n\nexport const DEFAULT_OAUTH_BASE_URL = \"https://app.mantyx.io\";\n\n/** Skew (ms) before `expiresAt` at which a TokenSource will pre-emptively refresh. Default 60s. */\nexport const DEFAULT_REFRESH_SKEW_MS = 60_000;\n\n/**\n * Raised on a non-2xx response from `POST /api/oauth/token` or\n * `POST /api/oauth/revoke`. Carries the RFC 6749 `error` discriminator\n * (`\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`,\n * …) and the optional `error_description` so callers can branch on\n * machine-readable values without parsing the human message.\n *\n * `invalid_grant` from the refresh path specifically signals that the\n * refresh token has been revoked (or the OAuth grant / application\n * was deleted). The SDK never loops on this — callers should route\n * the user back to a fresh sign-in.\n */\nexport class MantyxOAuthError extends MantyxError {\n readonly oauthError: string;\n readonly oauthErrorDescription: string | undefined;\n\n constructor(\n oauthError: string,\n oauthErrorDescription: string | undefined,\n status: number,\n ) {\n const message = oauthErrorDescription\n ? `OAuth ${oauthError}: ${oauthErrorDescription}`\n : `OAuth ${oauthError}`;\n super(message, { code: oauthError, status });\n this.name = \"MantyxOAuthError\";\n this.oauthError = oauthError;\n this.oauthErrorDescription = oauthErrorDescription;\n }\n}\n\n/**\n * Decoded `POST /api/oauth/token` response, augmented with an absolute\n * `expiresAt` timestamp the SDK uses to decide when to refresh.\n *\n * On the refresh grant the response's `refreshToken` is identical to\n * the value the client just sent (refresh tokens never rotate). The\n * field is surfaced for symmetry with whatever the calling app's\n * sign-in flow already does.\n */\nexport interface OAuthToken {\n readonly accessToken: string;\n readonly refreshToken: string | undefined;\n readonly tokenType: string;\n readonly expiresIn: number;\n /** Absolute Unix-ms timestamp set when the SDK parsed the response. */\n readonly expiresAt: number;\n readonly scope: string | undefined;\n}\n\n/** Why the SDK asked the {@link TokenSource} for the current access token. */\nexport type TokenRequestReason = \"initial\" | \"expired\" | \"unauthorized\";\n\n/**\n * A `TokenSource` produces the current access token on demand. The\n * {@link MantyxClient} HTTP layer calls it before every request. When\n * called with `reason: \"unauthorized\"` the source MUST force a refresh\n * (do not return a cached value); this is how the SDK recovers from\n * 401s caused by a token that the server already invalidated.\n *\n * Implementations should be safe to call from many concurrent requests.\n */\nexport type TokenSource = (reason?: TokenRequestReason) => Promise<string>;\n\n/** Caller-supplied options for `MantyxOAuthClient`. */\nexport interface MantyxOAuthClientOptions {\n /**\n * OAuth `client_id` issued at app registration (token prefix\n * `mantyx_oa_`).\n */\n clientId: string;\n /**\n * OAuth `client_secret` issued at app registration (token prefix\n * `mantyx_oas_`). Every MANTYX OAuth app is a confidential client,\n * so this is always required for token + revoke calls. Treat as a\n * deployment secret — do not bundle into browser builds.\n */\n clientSecret: string;\n /**\n * Origin of the MANTYX deployment. Defaults to `https://app.mantyx.io`.\n * The OAuth endpoints are mounted at `<baseUrl>/api/oauth/...`.\n */\n baseUrl?: string;\n /** Optional `fetch` override (e.g. node-fetch wrapper). Default: global `fetch`. */\n fetch?: typeof fetch;\n /** Default per-request timeout in milliseconds. Default: 30s. */\n timeoutMs?: number;\n}\n\nexport interface RefreshOptions {\n refreshToken: string;\n /**\n * Optional scope narrowing. Must be a subset of the scopes already\n * granted to the refresh token (server enforces this). Useful when\n * an SDK consumer wants a short-scope access token for a specific\n * sub-operation.\n */\n scope?: string | readonly string[];\n}\n\nexport interface RevokeOptions {\n token: string;\n}\n\nexport interface RefreshTokenSourceOptions {\n refreshToken: string;\n /** Optional scope narrowing applied on every refresh. */\n scope?: string | readonly string[];\n /**\n * How many ms before `expiresAt` the source proactively refreshes.\n * Defaults to {@link DEFAULT_REFRESH_SKEW_MS} (60s).\n */\n refreshSkewMs?: number;\n /**\n * Optional initial access token + expiry to seed the source's cache\n * with (e.g. the token already in hand from the host application's\n * sign-in flow). When omitted, the source mints one on the first\n * call.\n */\n initialToken?: OAuthToken;\n}\n\n/**\n * Refresh-only wrapper around the MANTYX OAuth 2.0 authorization-server\n * endpoints. App-scoped (one per `{clientId, clientSecret}` pair);\n * construct independently of {@link MantyxClient}, then either call\n * {@link refresh} / {@link revoke} directly or hand a `TokenSource`\n * produced by {@link refreshTokenSource} to `MantyxClient` for fully\n * transparent refresh on every request.\n *\n * The client deliberately does **not** drive the authorization-code\n * exchange or any other \"initiate sign-in\" grant. The caller is\n * expected to obtain the refresh token through their own consent flow\n * and persist it before constructing this client.\n */\nexport class MantyxOAuthClient {\n readonly clientId: string;\n readonly baseUrl: string;\n private readonly clientSecret: string;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n\n constructor(opts: MantyxOAuthClientOptions) {\n if (!opts.clientId) {\n throw new MantyxError(\"`clientId` is required for MantyxOAuthClient\");\n }\n if (!opts.clientSecret) {\n throw new MantyxError(\"`clientSecret` is required for MantyxOAuthClient\");\n }\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new MantyxError(\n \"Global fetch is not available; pass a custom `fetch` implementation in MantyxOAuthClientOptions.\",\n );\n }\n this.clientId = opts.clientId;\n this.clientSecret = opts.clientSecret;\n this.baseUrl = (opts.baseUrl ?? DEFAULT_OAUTH_BASE_URL).replace(/\\/+$/, \"\");\n this.fetchImpl = f;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n /**\n * Mint a fresh access token from a stored refresh token. The\n * returned `refreshToken` is identical to the input — refresh\n * tokens are persistent and non-rotating, so the field is\n * surfaced only for symmetry with the response shape.\n *\n * On `400 invalid_grant` the refresh token has been revoked (or its\n * grant / app was deleted); the SDK surfaces a\n * {@link MantyxOAuthError} and callers must drive a fresh sign-in.\n */\n async refresh(opts: RefreshOptions): Promise<OAuthToken> {\n if (!opts.refreshToken) {\n throw new MantyxError(\"`refreshToken` is required for MantyxOAuthClient.refresh\");\n }\n const body: Record<string, string> = {\n grant_type: \"refresh_token\",\n refresh_token: opts.refreshToken,\n };\n const scope = normalizeScope(opts.scope);\n if (scope !== undefined) body.scope = scope;\n return this.token(body);\n }\n\n /**\n * Revoke an access or refresh token (RFC 7009). The server always\n * returns 200, even for unknown tokens. Revoking a **refresh**\n * token kills the refresh and every live access token tied to its\n * grant; revoking an **access** token kills only that one.\n */\n async revoke(opts: RevokeOptions): Promise<void> {\n if (!opts.token) {\n throw new MantyxError(\"`token` is required for MantyxOAuthClient.revoke\");\n }\n await this.formPost(\"/api/oauth/revoke\", {\n token: opts.token,\n });\n }\n\n /**\n * Build a long-lived {@link TokenSource} that re-mints access\n * tokens from the supplied refresh token. Pass the returned source\n * to `new MantyxClient({ tokenSource, workspaceSlug, ... })`. The\n * source caches the access token in-memory and refreshes\n * proactively when the cached value is within `refreshSkewMs` of\n * `expiresAt`, or eagerly when `MantyxClient` reports a 401.\n *\n * Pass `initialToken` if the calling app already has a non-expired\n * access token in hand (e.g. straight out of the sign-in flow) to\n * avoid an extra round-trip on the first request.\n */\n refreshTokenSource(opts: RefreshTokenSourceOptions): TokenSource {\n if (!opts.refreshToken) {\n throw new MantyxError(\"`refreshToken` is required for MantyxOAuthClient.refreshTokenSource\");\n }\n const skew = opts.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;\n const cache: TokenCache = { token: opts.initialToken, inflight: null };\n const refreshToken = opts.refreshToken;\n return makeTokenSource(cache, skew, async () => {\n return this.refresh({ refreshToken, scope: opts.scope });\n });\n }\n\n // -------------------------------------------------------------- internals\n\n /**\n * POST `application/x-www-form-urlencoded` to `/api/oauth/token` and\n * decode the {@link OAuthToken} response. Always injects `client_id`\n * + `client_secret` from the constructor.\n */\n private async token(body: Record<string, string>): Promise<OAuthToken> {\n const res = await this.formPost(\"/api/oauth/token\", body);\n let parsed: Record<string, unknown> = {};\n try {\n parsed = (await res.json()) as Record<string, unknown>;\n } catch {\n throw new MantyxOAuthError(\n \"invalid_response\",\n \"Token endpoint returned a non-JSON response\",\n res.status,\n );\n }\n const accessToken = typeof parsed.access_token === \"string\" ? parsed.access_token : \"\";\n if (!accessToken) {\n throw new MantyxOAuthError(\n \"invalid_response\",\n \"Token endpoint response is missing `access_token`\",\n res.status,\n );\n }\n const expiresIn = typeof parsed.expires_in === \"number\" ? parsed.expires_in : 3600;\n return {\n accessToken,\n refreshToken: typeof parsed.refresh_token === \"string\" ? parsed.refresh_token : undefined,\n tokenType: typeof parsed.token_type === \"string\" ? parsed.token_type : \"Bearer\",\n expiresIn,\n expiresAt: Date.now() + expiresIn * 1000,\n scope: typeof parsed.scope === \"string\" ? parsed.scope : undefined,\n };\n }\n\n private async formPost(path: string, body: Record<string, string>): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const params = new URLSearchParams({\n ...body,\n client_id: this.clientId,\n client_secret: this.clientSecret,\n });\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: params.toString(),\n signal: ctrl.signal,\n });\n } catch (err) {\n if (ctrl.signal.aborted) {\n throw new MantyxNetworkError(`OAuth request timed out after ${this.timeoutMs}ms`);\n }\n throw new MantyxNetworkError(`OAuth network error: ${(err as Error).message}`, {\n cause: err,\n });\n } finally {\n clearTimeout(t);\n }\n if (!res.ok) {\n let errBody: { error?: unknown; error_description?: unknown } = {};\n try {\n errBody = (await res.json()) as typeof errBody;\n } catch {\n // ignore\n }\n const oauthError = typeof errBody.error === \"string\" ? errBody.error : `http_${res.status}`;\n const desc =\n typeof errBody.error_description === \"string\" ? errBody.error_description : undefined;\n throw new MantyxOAuthError(oauthError, desc, res.status);\n }\n return res;\n }\n}\n\n// -------------------------------------------------------------- internals\n\ninterface TokenCache {\n token: OAuthToken | undefined;\n inflight: Promise<OAuthToken> | null;\n}\n\n/**\n * Wrap a `mintToken` thunk into a single-flight {@link TokenSource}\n * with a cache + proactive-refresh skew. The cache is overwritten\n * atomically on every successful mint; the in-flight promise\n * collapses N concurrent expired-token observers into one mint call.\n *\n * Single-flight is an efficiency, not a correctness requirement —\n * `docs/oauth.md` explicitly allows multiple concurrent refreshes\n * against the same refresh token — but it keeps the token-endpoint\n * QPS reasonable when an SDK consumer fans out work in parallel.\n */\nfunction makeTokenSource(\n cache: TokenCache,\n skewMs: number,\n mint: () => Promise<OAuthToken>,\n): TokenSource {\n return async (reason: TokenRequestReason = \"initial\"): Promise<string> => {\n if (reason !== \"unauthorized\" && cache.token && !isExpiring(cache.token, skewMs)) {\n return cache.token.accessToken;\n }\n if (cache.inflight) {\n const t = await cache.inflight;\n if (reason === \"unauthorized\" && t === cache.token) {\n // If the inflight refresh was triggered by a benign cache miss\n // and we observed an unauthorized hint after it started, fall\n // through and mint again so the caller never gets a stale token.\n } else {\n return t.accessToken;\n }\n }\n cache.inflight = mint().then(\n (t) => {\n cache.token = t;\n return t;\n },\n (err: unknown) => {\n throw err;\n },\n );\n try {\n const t = await cache.inflight;\n return t.accessToken;\n } finally {\n cache.inflight = null;\n }\n };\n}\n\nfunction isExpiring(token: OAuthToken, skewMs: number): boolean {\n return token.expiresAt - Date.now() <= skewMs;\n}\n\nfunction normalizeScope(scope: string | readonly string[] | undefined): string | undefined {\n if (scope === undefined) return undefined;\n if (typeof scope === \"string\") {\n const trimmed = scope.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n const joined = scope.filter((s) => typeof s === \"string\" && s.length > 0).join(\" \");\n return joined.length > 0 ? joined : undefined;\n}\n","/**\n * Release version — synced from repo root VERSION (`npm run sync-version`).\n */\nexport const SDK_VERSION = \"0.15.1\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,IAAM,yBAAyB;AAG/B,IAAM,0BAA0B;AAchC,IAAM,mBAAN,cAA+B,YAAY;AAAA,EACvC;AAAA,EACA;AAAA,EAET,YACE,YACA,uBACA,QACA;AACA,UAAM,UAAU,wBACZ,SAAS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AW,MAAM,OAAO,MAAM,GAAG;AAChF,aAAO,MAAM,MAAM;AAAA,IACrB;AACA,QAAI,MAAM,UAAU;AAClB,YAAM,IAAI,MAAM,MAAM;AACtB,UAAI,WAAW,kBAAkB,MAAM,MAAM,OAAO;AAAA,MAIpD,OAAO;AACL,eAAO,EAAE;AAAA,MACX;AAAA,IACF;AACA,UAAM,WAAW,KAAK,EAAE;AAAA,MACtB,CAAC,MAAM;AACL,cAAM,QAAQ;AACd,eAAO;AAAA,MACT;AAAA,MACA,CAAC,QAAiB;AAChB,cAAM;AAAA,MACR;AAAA,IACF;AACA,QAAI;AACF,YAAM,IAAI,MAAM,MAAM;AACtB,aAAO,EAAE;AAAA,IACX,UAAE;AACA,YAAM,WAAW;AAAA,IACnB;AAAA,EACF;AACF;AAEA,SAAS,WAAW,OAAmB,QAAyB;AAC9D,SAAO,MAAM,YAAY,KAAK,IAAI,KAAK;AACzC;AAEA,SAAS,eAAe,OAAmE;AACzF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,WAAO,QAAQ,SAAS,IAAI,UAAU;AAAA,EACxC;AACA,QAAM,SAAS,MAAM,OAAO,CAAC,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,EAAE,KAAK,GAAG;AAClF,SAAO,OAAO,SAAS,IAAI,SAAS;AACtC;;;ACpZO,IAAM,cAAc;","names":[]}
|
|
@@ -382,8 +382,59 @@ The agent spec is the body shape used by `POST /agent-runs` and `POST
|
|
|
382
382
|
}
|
|
383
383
|
```
|
|
384
384
|
|
|
385
|
-
`POST /agent-runs` additionally accepts `prompt` _or_ `messages
|
|
386
|
-
|
|
385
|
+
`POST /agent-runs` additionally accepts `prompt` _or_ `messages`. Sending both,
|
|
386
|
+
or neither, is a `400 invalid_request`. See [§4.0.1](#401-multi-role-messages-and-file-inputs)
|
|
387
|
+
for the `messages` shape and file attachments.
|
|
388
|
+
|
|
389
|
+
### 4.0.1 Multi-role `messages` and file inputs
|
|
390
|
+
|
|
391
|
+
Instead of a single `prompt` string, supply a `messages` array to send a
|
|
392
|
+
multi-role conversation in one request. The same shape is accepted on
|
|
393
|
+
`POST /agent-sessions/:id/messages` (where it represents the new turn(s) to
|
|
394
|
+
append to the session).
|
|
395
|
+
|
|
396
|
+
```jsonc
|
|
397
|
+
{
|
|
398
|
+
"modelId": "openai:gpt-5.5",
|
|
399
|
+
"messages": [
|
|
400
|
+
{ "role": "system", "content": "You are a terse assistant." },
|
|
401
|
+
{ "role": "user", "content": "Earlier question" },
|
|
402
|
+
{ "role": "assistant", "content": "Earlier answer" },
|
|
403
|
+
{
|
|
404
|
+
"role": "user",
|
|
405
|
+
"content": "What's in this file?",
|
|
406
|
+
"attachments": [
|
|
407
|
+
{ "type": "input_file", "mimeType": "application/pdf", "filename": "report.pdf", "data": "<base64>" },
|
|
408
|
+
{ "type": "input_file_url", "url": "https://example.com/image.png", "mimeType": "image/png" }
|
|
409
|
+
]
|
|
410
|
+
}
|
|
411
|
+
]
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
Rules:
|
|
416
|
+
|
|
417
|
+
- **`role`** is one of `user`, `assistant`, `system`. `system` messages are
|
|
418
|
+
applied as additional system context, **appended after** the spec's
|
|
419
|
+
`systemPrompt` (both apply). A run is valid when it has an `agentId`, a
|
|
420
|
+
`systemPrompt`, **or** at least one non-empty `system` message in `messages`.
|
|
421
|
+
- The **last non-system message must be `role: "user"`** (`400` otherwise) —
|
|
422
|
+
it is the current turn the model responds to, and the only message whose
|
|
423
|
+
`attachments` are sent to the model.
|
|
424
|
+
- Max 200 messages; each `content` ≤ 200,000 characters.
|
|
425
|
+
|
|
426
|
+
**File attachments** (`attachments` on the last `user` message, max 20):
|
|
427
|
+
|
|
428
|
+
| `type` | Fields | Notes |
|
|
429
|
+
| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
430
|
+
| `input_file` | `mimeType`, `filename`, `data` (base64, no data-URL prefix) | Inline bytes. Total inline bytes per run are capped (currently 5 MB); larger files must use a URL. |
|
|
431
|
+
| `input_file_url` | `url` (https only), `mimeType?`, `filename?` | Publicly fetchable HTTPS URL. The provider fetches it directly. |
|
|
432
|
+
|
|
433
|
+
Allowed MIME types match the workspace chat allowlist (images, PDF, DOCX,
|
|
434
|
+
and `text/*` subtypes). Disallowed types, non-HTTPS URLs, malformed base64, or
|
|
435
|
+
oversized inline payloads return `400 invalid_request`. Attachments on older
|
|
436
|
+
history turns are not re-sent to the model (text only); only the current
|
|
437
|
+
turn's files reach the LLM.
|
|
387
438
|
|
|
388
439
|
### 4.1 Triggering a persisted MANTYX agent (`agentId`)
|
|
389
440
|
|
|
@@ -872,23 +923,27 @@ Reviews fire every **`interval` LLM calls** (`completeTurn` invocations) at
|
|
|
872
923
|
the bottom of tool-emitting rounds. Default interval is **5** when enabled.
|
|
873
924
|
|
|
874
925
|
```jsonc
|
|
926
|
+
"supervisor": true // enable with platform defaults
|
|
927
|
+
|
|
875
928
|
"supervisor": {
|
|
876
929
|
"interval": 5,
|
|
877
930
|
"modelId": "platform:demo"
|
|
878
931
|
}
|
|
879
932
|
|
|
880
933
|
// or:
|
|
881
|
-
"supervisor": false // explicitly disable
|
|
934
|
+
"supervisor": false // explicitly disable (same as omitting the field)
|
|
882
935
|
```
|
|
883
936
|
|
|
884
937
|
| Field | Type | Required | Notes |
|
|
885
938
|
| ----------------- | --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
939
|
+
| (literal `true`) | `true` | no | Enables the run supervisor with platform defaults (`interval` 5, workspace judge model). |
|
|
886
940
|
| `interval` | integer ≥ 1 | no | Defaults to **5** when the supervisor is enabled and `interval` is omitted. Capped at **100** server-side. |
|
|
887
941
|
| `modelId` | string | no | Judge model selector (same grammar as `modelId`). Falls back to workspace `defaultSupervisorModelId`, then workspace default model. |
|
|
888
942
|
| (literal `false`) | `false` | no | Disables the run supervisor for this run. `loopDetection` and `toolBudgets` still apply. |
|
|
889
943
|
|
|
890
|
-
**Defaults.** When `supervisor` is **omitted
|
|
891
|
-
LLM judge on ephemeral runs. Pass `"supervisor":
|
|
944
|
+
**Defaults.** When `supervisor` is **omitted** (or `false`), MANTYX does **not**
|
|
945
|
+
run the platform LLM judge on ephemeral API runs. Pass `"supervisor": true`,
|
|
946
|
+
`"supervisor": {}`, or a config object to opt in.
|
|
892
947
|
|
|
893
948
|
**SDK-only usage.** When calling `@mantyx/ts-sdk` directly (not via
|
|
894
949
|
`POST /agent-runs`), the supervisor is **off unless explicitly configured**:
|
|
@@ -919,9 +974,8 @@ the verdict by the time the event arrives.
|
|
|
919
974
|
### 4.9 `plan` (task plan / plan-only)
|
|
920
975
|
|
|
921
976
|
`plan` turns on the in-product **task plan** — the same live-checklist engine
|
|
922
|
-
that powers MANTYX chat / Hive Mind. It is **opt-in** on API/ephemeral runs
|
|
923
|
-
|
|
924
|
-
for at least one extra classifier LLM call.
|
|
977
|
+
that powers MANTYX chat / Hive Mind. It is **opt-in** on API/ephemeral runs,
|
|
978
|
+
same as `supervisor` (§4.8), because both features add extra LLM calls.
|
|
925
979
|
|
|
926
980
|
```jsonc
|
|
927
981
|
"plan": true // auto: classify, emit a task_plan event, track during the run
|
|
@@ -1117,11 +1171,17 @@ conversation (stable across paging). Reconstructed turns map as:
|
|
|
1117
1171
|
`user_message` is a **replay/restore-only** frame — the live SSE stream never
|
|
1118
1172
|
emits it (the client already knows the prompt it sent), but history
|
|
1119
1173
|
restoration needs it to rebuild the user side of the conversation. This first
|
|
1120
|
-
cut reconstructs from the durable transcript (`role`/`content`
|
|
1121
|
-
calls are not replayed here.
|
|
1174
|
+
cut reconstructs from the durable transcript (`role`/`content`); tool
|
|
1175
|
+
calls are not replayed here. When a user turn carried file inputs, the frame
|
|
1176
|
+
also includes an `attachments` array of **metadata** (no bytes):
|
|
1177
|
+
`{ type: "input_file", mimeType, filename, size }` or
|
|
1178
|
+
`{ type: "input_file_url", url, mimeType?, filename? }`.
|
|
1122
1179
|
|
|
1123
1180
|
`POST /agent-sessions/{id}/messages` queues a new run scoped to the session
|
|
1124
|
-
and returns `{ runId, streamUrl }` just like a one-shot run. Body
|
|
1181
|
+
and returns `{ runId, streamUrl }` just like a one-shot run. Body accepts a
|
|
1182
|
+
single `prompt` **or** a `messages` array (same shape and file-attachment
|
|
1183
|
+
rules as [§4.0.1](#401-multi-role-messages-and-file-inputs); the messages
|
|
1184
|
+
represent the new turn(s) appended to the session):
|
|
1125
1185
|
|
|
1126
1186
|
```jsonc
|
|
1127
1187
|
{
|
|
@@ -1133,7 +1193,8 @@ and returns `{ runId, streamUrl }` just like a one-shot run. Body:
|
|
|
1133
1193
|
```
|
|
1134
1194
|
|
|
1135
1195
|
The server prepends the session's prior messages, runs the model, and on
|
|
1136
|
-
success appends the new user/assistant turns back to the session row
|
|
1196
|
+
success appends the new user/assistant turns back to the session row (file
|
|
1197
|
+
attachments are stored as metadata only). Local
|
|
1137
1198
|
tool **handlers** are _not_ persisted: the session stores definitions
|
|
1138
1199
|
(name, schema, description) so that a restarted SDK can re-bind handlers and
|
|
1139
1200
|
keep going.
|
|
@@ -1462,11 +1523,12 @@ A reference SDK should:
|
|
|
1462
1523
|
them by default. Their presence depends on `reasoningLevel > 0` and
|
|
1463
1524
|
on the active model exposing thought parts.
|
|
1464
1525
|
- Accept `loopDetection`, `toolBudgets`, and `supervisor` from the caller
|
|
1465
|
-
and pass them through unchanged (see §4.6 / §4.7 / §4.8).
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1526
|
+
and pass them through unchanged (see §4.6 / §4.7 / §4.8). `loopDetection`
|
|
1527
|
+
and `toolBudgets` are additive: omitting them keeps MANTYX's runtime
|
|
1528
|
+
defaults; passing `loopDetection: false` opts out; passing `toolBudgets: {}`
|
|
1529
|
+
clears the defaults. `supervisor` and `plan` are opt-in — omitting them
|
|
1530
|
+
keeps both off; pass `supervisor: true` / `{}` / `{ interval?, modelId? }`
|
|
1531
|
+
or `plan: true` / `{ … }` to enable.
|
|
1470
1532
|
- Treat `loop_detected`, `tool_budget_exceeded`, and `supervisor` SSE
|
|
1471
1533
|
events as observability-only — the server already substituted synthetic
|
|
1472
1534
|
tool-results / steering nudges / supervisor verdicts where applicable, so
|
package/docs/wire-protocol.md
CHANGED
|
@@ -142,13 +142,41 @@ short-circuit, etc.) see `agent-runs-protocol.md` §4.
|
|
|
142
142
|
}
|
|
143
143
|
```
|
|
144
144
|
|
|
145
|
+
### 2.1.1 `messages` and file inputs
|
|
146
|
+
|
|
147
|
+
Instead of `prompt`, send a `messages` array for multi-role input. Each entry
|
|
148
|
+
is `{ role: "user" | "assistant" | "system", content, attachments? }`. `system`
|
|
149
|
+
messages are merged after `systemPrompt`; the last non-system message must be a
|
|
150
|
+
`user` turn. The last user message may carry up to 20 `attachments`:
|
|
151
|
+
|
|
152
|
+
```jsonc
|
|
153
|
+
{
|
|
154
|
+
"type": "input_file",
|
|
155
|
+
"mimeType": "application/pdf",
|
|
156
|
+
"filename": "report.pdf",
|
|
157
|
+
"data": "<base64>", // inline bytes; total inline ≤ 5 MB per run
|
|
158
|
+
}
|
|
159
|
+
// — or —
|
|
160
|
+
{
|
|
161
|
+
"type": "input_file_url",
|
|
162
|
+
"url": "https://example.com/image.png", // https only; provider fetches it
|
|
163
|
+
"mimeType": "image/png", // optional
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
See [`agent-runs-protocol.md` §4.0.1](./agent-runs-protocol.md) for the full
|
|
168
|
+
rules (allowed MIME types, size caps, validation errors). On session-events
|
|
169
|
+
replay, `user_message` frames include `attachments` **metadata** (no bytes).
|
|
170
|
+
|
|
145
171
|
### 2.2 Sessions
|
|
146
172
|
|
|
147
|
-
Same body shape, posted to `POST /agent-sessions/:id/messages
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
173
|
+
Same body shape, posted to `POST /agent-sessions/:id/messages` (accepts either
|
|
174
|
+
`prompt` or `messages`, including file attachments — the messages are the new
|
|
175
|
+
turn(s) appended to the session). The session keeps the conversation history;
|
|
176
|
+
per-message `tools`, `reasoningLevel`, `outputSchema`, `loopDetection`,
|
|
177
|
+
`toolBudgets`, `supervisor`, and `plan` _replace_ the session's defaults for
|
|
178
|
+
that single run only — the next run falls back to whatever the session was
|
|
179
|
+
created with.
|
|
152
180
|
|
|
153
181
|
---
|
|
154
182
|
|
|
@@ -683,9 +711,9 @@ appended (`redirect`) or the next turn was forced tools-disabled
|
|
|
683
711
|
(`finalize`). SDK clients should render a status note and **not** try to
|
|
684
712
|
steer the run themselves.
|
|
685
713
|
|
|
686
|
-
Pass `"supervisor":
|
|
687
|
-
for a run. Omission
|
|
688
|
-
ephemeral runs
|
|
714
|
+
Pass `"supervisor": true` or `"supervisor": {}` in the spec (§8.4) to enable
|
|
715
|
+
the platform judge for a run. Omission (or `"supervisor": false`) keeps the
|
|
716
|
+
supervisor **off** on ephemeral API runs.
|
|
689
717
|
|
|
690
718
|
### 4.8 Terminal events
|
|
691
719
|
|
|
@@ -1137,17 +1165,20 @@ measured at the bottom of tool-emitting rounds. Default interval is **5**
|
|
|
1137
1165
|
when the field is omitted.
|
|
1138
1166
|
|
|
1139
1167
|
```jsonc
|
|
1168
|
+
"supervisor": true // enable with platform defaults (interval 5, workspace judge model)
|
|
1169
|
+
|
|
1140
1170
|
"supervisor": {
|
|
1141
1171
|
"interval": 5, // optional — LLM calls between reviews; default 5
|
|
1142
1172
|
"modelId": "platform:demo" // optional — judge model; see resolution below
|
|
1143
1173
|
}
|
|
1144
1174
|
|
|
1145
1175
|
// or:
|
|
1146
|
-
"supervisor": false // explicitly disable
|
|
1176
|
+
"supervisor": false // explicitly disable (same as omitting the field)
|
|
1147
1177
|
```
|
|
1148
1178
|
|
|
1149
1179
|
| Field | Type | Notes |
|
|
1150
1180
|
| ---------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
1181
|
+
| (literal `true`) | `true` | Enables the run supervisor with platform defaults (`interval` 5, workspace judge model). |
|
|
1151
1182
|
| `interval` | integer ≥ 1 | Optional. Default **5** when omitted. Capped at **100** server-side. |
|
|
1152
1183
|
| `modelId` | string | Optional. Same selector grammar as top-level `modelId` (§2). When omitted, the platform resolves the judge model from the workspace default supervisor model, then the workspace default model. |
|
|
1153
1184
|
| (literal `false`) | `false` | Disables the run supervisor for this run. Loop detection and tool budgets still apply. |
|
|
@@ -1158,15 +1189,17 @@ when the field is omitted.
|
|
|
1158
1189
|
2. Workspace `defaultSupervisorModelId` (Settings → Workspace → General)
|
|
1159
1190
|
3. Workspace default model (same as omitting top-level `modelId`)
|
|
1160
1191
|
|
|
1161
|
-
**Defaults.** When `supervisor` is **omitted
|
|
1162
|
-
LLM judge on ephemeral runs
|
|
1163
|
-
|
|
1192
|
+
**Defaults.** When `supervisor` is **omitted** (or `false`), MANTYX does **not**
|
|
1193
|
+
run the platform LLM judge on ephemeral API runs — same opt-in semantics as
|
|
1194
|
+
`plan` (§8.5). Pass `"supervisor": true`, `"supervisor": {}`, or a config
|
|
1195
|
+
object to enable. Web chat enables the supervisor separately via the chat
|
|
1196
|
+
runner.
|
|
1164
1197
|
|
|
1165
1198
|
**SDK-only runs.** When a caller uses `@mantyx/ts-sdk` directly (not via
|
|
1166
1199
|
`POST /agent-runs`), the supervisor is **off unless explicitly configured**:
|
|
1167
1200
|
pass a `RunAgentSupervisor` object with a `review` callback to enable it, or
|
|
1168
|
-
|
|
1169
|
-
|
|
1201
|
+
omit the field to keep it disabled. The wire field above controls the
|
|
1202
|
+
**platform-hosted** judge on ephemeral API runs only.
|
|
1170
1203
|
|
|
1171
1204
|
Each review emits a SSE `supervisor` event (§4.7). Supervisor LLM usage is
|
|
1172
1205
|
recorded under the `supervisor` usage surface for cost attribution.
|
|
@@ -1175,8 +1208,8 @@ recorded under the `supervisor` usage surface for cost attribution.
|
|
|
1175
1208
|
|
|
1176
1209
|
The optional `plan` field turns on the in-product **task plan** — the same
|
|
1177
1210
|
engine that drives the live checklist in MANTYX chat / Hive Mind. It is
|
|
1178
|
-
**opt-in** on ephemeral runs
|
|
1179
|
-
|
|
1211
|
+
**opt-in** on ephemeral runs, same as `supervisor` (§8.4), because both
|
|
1212
|
+
features add extra LLM calls.
|
|
1180
1213
|
|
|
1181
1214
|
```jsonc
|
|
1182
1215
|
"plan": true // auto: pre-flight classify, emit task_plan, track during the run
|
|
@@ -1406,11 +1439,13 @@ A reference SDK should:
|
|
|
1406
1439
|
JSON shape via the provider, but transient model errors can still
|
|
1407
1440
|
produce strings that fail to parse in rare cases.
|
|
1408
1441
|
- [ ] Accept `loopDetection`, `toolBudgets`, and `supervisor` from the caller
|
|
1409
|
-
and pass them through unchanged (see §8).
|
|
1410
|
-
omitting them keeps the runtime defaults;
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1442
|
+
and pass them through unchanged (see §8). `loopDetection` and
|
|
1443
|
+
`toolBudgets` are additive — omitting them keeps the runtime defaults;
|
|
1444
|
+
passing `loopDetection: false` opts out; passing `toolBudgets: {}`
|
|
1445
|
+
clears the defaults. `supervisor` and `plan` are opt-in — omitting them
|
|
1446
|
+
keeps both off; pass `supervisor: true` / `{}` / `{ interval?, modelId? }`
|
|
1447
|
+
or `plan: true` / `{ … }` to enable. Do **not** translate to
|
|
1448
|
+
vendor-specific knobs.
|
|
1414
1449
|
- [ ] Treat `loop_detected`, `tool_budget_exceeded`, and `supervisor` SSE
|
|
1415
1450
|
events as observability-only (see §4.5 / §4.6 / §4.7). Surface them as
|
|
1416
1451
|
status notes / log lines / telemetry — the server already substituted
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mantyx/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.1",
|
|
4
4
|
"description": "MANTYX as a hosted agent runtime: define ephemeral agents, mix server-side MANTYX tools with locally-executed tools, run them remotely.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|