@mantyx/sdk 0.12.0 → 0.14.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.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
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, e as DEFAULT_OAUTH_BASE_URL, f as DEFAULT_REFRESH_SKEW_MS, g as DefineLocalA2AOptions, h as DefineLocalMcpOptions, i as DefineLocalToolOptions, E as ErrorEvent, L as LocalA2ATool, j as LocalHandlers, k as LocalMcpHttpTransport, l as LocalMcpServer, m as LocalMcpStdioTransport, n as LocalTool, o as LocalToolCallEvent, p as LocalToolResultInEvent, q as LoopDetectedEvent, r as LoopDetection, s as MantyxA2AOptions, t as MantyxAuthError, M as MantyxClient, u as MantyxClientOptions, v as MantyxError, w as MantyxMcpOptions, x as MantyxNetworkError, y as MantyxOAuthClient, z as MantyxOAuthClientOptions, B as MantyxOAuthError, F as MantyxParseError, G as MantyxPluginToolRef, H as MantyxRunError, I as MantyxRunErrorInit, J as MantyxRunErrorModel, K as MantyxRunErrorTokens, N as MantyxScopeError, O as MantyxToolError, P as MantyxToolRef, Q as McpToolRef, S as ModelCatalog, U as ModelInfo, V as OAuthToken, W as OutputSchema, R as ReasoningLevel, X as RefreshOptions, Y as RefreshTokenSourceOptions, Z as ResultEvent, _ as RevokeOptions, $ as RunEvent, a0 as RunEventBase, a1 as RunModelInfo, a2 as RunResult, a3 as RunSpec, a4 as RunTokenUsage, a5 as ServerToolResultEvent, a6 as SessionInfo, a7 as SessionSpec, a8 as Supervisor, a9 as SupervisorAction, aa as SupervisorEvent, ab as ThinkingDeltaEvent, ac as TokenRequestReason, ad as TokenSource, ae as ToolBudget, af as ToolBudgetExceededEvent, ag as ToolBudgets, T as ToolRef, ah as ZodLikeObject, ai as defineLocalA2A, aj as defineLocalMcp, ak as defineLocalTool, al as isLocalA2ATool, am as isLocalMcpServer, an as isLocalTool, ao as mantyxA2A, ap as mantyxMcp, aq as mantyxPluginTool, ar as mantyxTool, as as parseRunOutput } from './client-LQlx7iYY.cjs';
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, e as DEFAULT_OAUTH_BASE_URL, f as DEFAULT_REFRESH_SKEW_MS, g as DefineLocalA2AOptions, h as DefineLocalMcpOptions, i as DefineLocalToolOptions, E as ErrorEvent, L as LocalA2ATool, j as LocalHandlers, k as LocalMcpHttpTransport, l as LocalMcpServer, m as LocalMcpStdioTransport, n as LocalTool, o as LocalToolCallEvent, p as LocalToolResultInEvent, q as LoopDetectedEvent, r as LoopDetection, s as MantyxA2AOptions, t as MantyxAuthError, M as MantyxClient, u as MantyxClientOptions, v as MantyxError, w as MantyxMcpOptions, x as MantyxNetworkError, y as MantyxOAuthClient, z as MantyxOAuthClientOptions, B as MantyxOAuthError, F as MantyxParseError, G as MantyxPluginToolRef, H as MantyxRunError, I as MantyxRunErrorInit, J as MantyxRunErrorModel, K as MantyxRunErrorTokens, N as MantyxScopeError, P as MantyxToolError, Q as MantyxToolRef, S as McpToolRef, U as ModelCatalog, V as ModelInfo, W as OAuthToken, O as OutputSchema, X as OutputSchemaValue, Y as PlanOptions, Z as PlanSpec, R as ReasoningLevel, _ as RefreshOptions, $ as RefreshTokenSourceOptions, a0 as ResultEvent, a1 as RevokeOptions, a2 as RunEvent, a3 as RunEventBase, a4 as RunModelInfo, a5 as RunResult, a6 as RunSpec, a7 as RunTokenUsage, a8 as ServerToolResultEvent, a9 as SessionInfo, aa as SessionListResult, ab as SessionSpec, ac as SessionSummary, ad as Supervisor, ae as SupervisorAction, af as SupervisorEvent, ag as TaskPlan, ah as TaskPlanEvent, ai as TaskPlanStep, aj as TaskPlanStepStatus, ak as ThinkingDeltaEvent, al as TokenRequestReason, am as TokenSource, an as ToolBudget, ao as ToolBudgetExceededEvent, ap as ToolBudgets, T as ToolRef, aq as UserMessageEvent, ar as ZodLikeObject, as as defineLocalA2A, at as defineLocalMcp, au as defineLocalTool, av as isLocalA2ATool, aw as isLocalMcpServer, ax as isLocalTool, ay as mantyxA2A, az as mantyxMcp, aA as mantyxPluginTool, aB as mantyxTool, aC as parseRunOutput, aD as planOnly } from './client-Ct6G4TVc.cjs';
2
2
  import { z } from 'zod';
3
3
 
4
4
  /**
@@ -52,6 +52,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
52
52
  /**
53
53
  * Release version — synced from repo root VERSION (`npm run sync-version`).
54
54
  */
55
- declare const SDK_VERSION = "0.12.0";
55
+ declare const SDK_VERSION = "0.14.0";
56
56
 
57
57
  export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
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, e as DEFAULT_OAUTH_BASE_URL, f as DEFAULT_REFRESH_SKEW_MS, g as DefineLocalA2AOptions, h as DefineLocalMcpOptions, i as DefineLocalToolOptions, E as ErrorEvent, L as LocalA2ATool, j as LocalHandlers, k as LocalMcpHttpTransport, l as LocalMcpServer, m as LocalMcpStdioTransport, n as LocalTool, o as LocalToolCallEvent, p as LocalToolResultInEvent, q as LoopDetectedEvent, r as LoopDetection, s as MantyxA2AOptions, t as MantyxAuthError, M as MantyxClient, u as MantyxClientOptions, v as MantyxError, w as MantyxMcpOptions, x as MantyxNetworkError, y as MantyxOAuthClient, z as MantyxOAuthClientOptions, B as MantyxOAuthError, F as MantyxParseError, G as MantyxPluginToolRef, H as MantyxRunError, I as MantyxRunErrorInit, J as MantyxRunErrorModel, K as MantyxRunErrorTokens, N as MantyxScopeError, O as MantyxToolError, P as MantyxToolRef, Q as McpToolRef, S as ModelCatalog, U as ModelInfo, V as OAuthToken, W as OutputSchema, R as ReasoningLevel, X as RefreshOptions, Y as RefreshTokenSourceOptions, Z as ResultEvent, _ as RevokeOptions, $ as RunEvent, a0 as RunEventBase, a1 as RunModelInfo, a2 as RunResult, a3 as RunSpec, a4 as RunTokenUsage, a5 as ServerToolResultEvent, a6 as SessionInfo, a7 as SessionSpec, a8 as Supervisor, a9 as SupervisorAction, aa as SupervisorEvent, ab as ThinkingDeltaEvent, ac as TokenRequestReason, ad as TokenSource, ae as ToolBudget, af as ToolBudgetExceededEvent, ag as ToolBudgets, T as ToolRef, ah as ZodLikeObject, ai as defineLocalA2A, aj as defineLocalMcp, ak as defineLocalTool, al as isLocalA2ATool, am as isLocalMcpServer, an as isLocalTool, ao as mantyxA2A, ap as mantyxMcp, aq as mantyxPluginTool, ar as mantyxTool, as as parseRunOutput } from './client-LQlx7iYY.js';
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, e as DEFAULT_OAUTH_BASE_URL, f as DEFAULT_REFRESH_SKEW_MS, g as DefineLocalA2AOptions, h as DefineLocalMcpOptions, i as DefineLocalToolOptions, E as ErrorEvent, L as LocalA2ATool, j as LocalHandlers, k as LocalMcpHttpTransport, l as LocalMcpServer, m as LocalMcpStdioTransport, n as LocalTool, o as LocalToolCallEvent, p as LocalToolResultInEvent, q as LoopDetectedEvent, r as LoopDetection, s as MantyxA2AOptions, t as MantyxAuthError, M as MantyxClient, u as MantyxClientOptions, v as MantyxError, w as MantyxMcpOptions, x as MantyxNetworkError, y as MantyxOAuthClient, z as MantyxOAuthClientOptions, B as MantyxOAuthError, F as MantyxParseError, G as MantyxPluginToolRef, H as MantyxRunError, I as MantyxRunErrorInit, J as MantyxRunErrorModel, K as MantyxRunErrorTokens, N as MantyxScopeError, P as MantyxToolError, Q as MantyxToolRef, S as McpToolRef, U as ModelCatalog, V as ModelInfo, W as OAuthToken, O as OutputSchema, X as OutputSchemaValue, Y as PlanOptions, Z as PlanSpec, R as ReasoningLevel, _ as RefreshOptions, $ as RefreshTokenSourceOptions, a0 as ResultEvent, a1 as RevokeOptions, a2 as RunEvent, a3 as RunEventBase, a4 as RunModelInfo, a5 as RunResult, a6 as RunSpec, a7 as RunTokenUsage, a8 as ServerToolResultEvent, a9 as SessionInfo, aa as SessionListResult, ab as SessionSpec, ac as SessionSummary, ad as Supervisor, ae as SupervisorAction, af as SupervisorEvent, ag as TaskPlan, ah as TaskPlanEvent, ai as TaskPlanStep, aj as TaskPlanStepStatus, ak as ThinkingDeltaEvent, al as TokenRequestReason, am as TokenSource, an as ToolBudget, ao as ToolBudgetExceededEvent, ap as ToolBudgets, T as ToolRef, aq as UserMessageEvent, ar as ZodLikeObject, as as defineLocalA2A, at as defineLocalMcp, au as defineLocalTool, av as isLocalA2ATool, aw as isLocalMcpServer, ax as isLocalTool, ay as mantyxA2A, az as mantyxMcp, aA as mantyxPluginTool, aB as mantyxTool, aC as parseRunOutput, aD as planOnly } from './client-Ct6G4TVc.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  /**
@@ -52,6 +52,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
52
52
  /**
53
53
  * Release version — synced from repo root VERSION (`npm run sync-version`).
54
54
  */
55
- declare const SDK_VERSION = "0.12.0";
55
+ declare const SDK_VERSION = "0.14.0";
56
56
 
57
57
  export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
package/dist/index.js CHANGED
@@ -20,10 +20,11 @@ import {
20
20
  mantyxPluginTool,
21
21
  mantyxTool,
22
22
  parseRunOutput,
23
+ planOnly,
23
24
  readSseStream,
24
25
  toToolParametersWire,
25
26
  zodToJsonSchema
26
- } from "./chunk-2K4BGJGJ.js";
27
+ } from "./chunk-XENCO3EF.js";
27
28
 
28
29
  // src/oauth.ts
29
30
  var DEFAULT_OAUTH_BASE_URL = "https://app.mantyx.io";
@@ -245,7 +246,7 @@ function normalizeScope(scope) {
245
246
  }
246
247
 
247
248
  // src/version.ts
248
- var SDK_VERSION = "0.12.0";
249
+ var SDK_VERSION = "0.14.0";
249
250
  export {
250
251
  AgentSession,
251
252
  DEFAULT_BASE_URL,
@@ -273,6 +274,7 @@ export {
273
274
  mantyxPluginTool,
274
275
  mantyxTool,
275
276
  parseRunOutput,
277
+ planOnly,
276
278
  readSseStream,
277
279
  toToolParametersWire,
278
280
  zodToJsonSchema
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.12.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;AAAA,EAEjB,YAAY,MAAgC;AAC1C,QAAI,CAAC,KA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AO;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.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,SA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A,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":[]}
@@ -124,7 +124,9 @@ two differences:
124
124
  | `POST .../agent-runs/{runId}/cancel` | `runs:write` |
125
125
  | `POST .../agent-runs/{runId}/tool-results` | `runs:write` |
126
126
  | `POST .../agent-sessions` | `sessions:write` |
127
+ | `GET .../agent-sessions` | `sessions:read` |
127
128
  | `GET .../agent-sessions/{sessionId}` | `sessions:read` |
129
+ | `GET .../agent-sessions/{sessionId}/events` | `sessions:read` |
128
130
  | `DELETE .../agent-sessions/{sessionId}` | `sessions:write` |
129
131
  | `POST .../agent-sessions/{sessionId}/messages` | `sessions:write` |
130
132
  | `GET /api/oauth/userinfo` | `mantyx.identity:read` |
@@ -199,8 +201,8 @@ platform-hosted offerings visible to the workspace's tier.
199
201
  {
200
202
  "models": [
201
203
  {
202
- "id": "platform:cm6abc123",
203
- "label": "Anthropic Claude Sonnet 4.5 (platform)",
204
+ "id": "anthropic/claude-sonnet-4-5",
205
+ "label": "anthropic · claude-sonnet-4-5",
204
206
  "provider": "anthropic",
205
207
  "vendorModelId": "claude-sonnet-4-5",
206
208
  "source": "platform_offering",
@@ -212,8 +214,8 @@ platform-hosted offerings visible to the workspace's tier.
212
214
  },
213
215
  },
214
216
  {
215
- "id": "provider:cm6def456",
216
- "label": "OpenAI (workspace BYOK) — gpt-5.5",
217
+ "id": "openai/gpt-5.5",
218
+ "label": "openai · gpt-5.5",
217
219
  "provider": "openai",
218
220
  "vendorModelId": "gpt-5.5",
219
221
  "source": "workspace_provider",
@@ -221,15 +223,21 @@ platform-hosted offerings visible to the workspace's tier.
221
223
  "pricing": null,
222
224
  },
223
225
  ],
224
- "defaultModelId": "platform:cm6abc123",
226
+ "defaultModelId": "openai/gpt-5.5",
225
227
  }
226
228
  ```
227
229
 
228
230
  The `id` is the canonical value the SDK passes back as `RunSpec.modelId` /
229
- `SessionSpec.modelId`. The server accepts three additional shorthand forms:
231
+ `SessionSpec.modelId`. Catalog ids use the `{provider}/{vendorModelId}` slug
232
+ (for example `openai/gpt-5.5` or `openrouter/anthropic/claude-sonnet-4`).
233
+ Each workspace may have at most one connection per provider + vendor model pair.
230
234
 
231
- - `provider:<id>:<vendor>` — pin a specific BYOK provider but override the
232
- vendor model id.
235
+ The server also accepts these forms:
236
+
237
+ - `{provider}/{vendorModelId}` — same slug as the catalog `id` (preferred).
238
+ - `platform:<offeringId>` — hosted catalog entry by internal id.
239
+ - `provider:<id>` / `provider:<id>:<vendor>` — BYOK provider by row id, with
240
+ optional vendor model override.
233
241
  - `<vendorModelId>` — bare vendor id; only succeeds if exactly one workspace
234
242
  provider can run it.
235
243
  - `undefined`/omitted — falls back to the workspace default provider's
@@ -365,8 +373,9 @@ The agent spec is the body shape used by `POST /agent-runs` and `POST
365
373
  // optional, see §4.8 — platform LLM judge; pass false to disable
366
374
  "interval": 5,
367
375
  },
376
+ "plan": true, // optional, see §4.9 — in-product task plan (opt-in)
368
377
  "metadata": {
369
- // optional, see §4.9
378
+ // optional, see §4.10
370
379
  "customer": "acme",
371
380
  "env": "prod",
372
381
  },
@@ -864,7 +873,8 @@ the bottom of tool-emitting rounds. Default interval is **5** when enabled.
864
873
 
865
874
  ```jsonc
866
875
  "supervisor": {
867
- "interval": 5 // optional — LLM calls between reviews; default 5
876
+ "interval": 5,
877
+ "modelId": "platform:demo"
868
878
  }
869
879
 
870
880
  // or:
@@ -874,6 +884,7 @@ the bottom of tool-emitting rounds. Default interval is **5** when enabled.
874
884
  | Field | Type | Required | Notes |
875
885
  | ----------------- | --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
876
886
  | `interval` | integer ≥ 1 | no | Defaults to **5** when the supervisor is enabled and `interval` is omitted. Capped at **100** server-side. |
887
+ | `modelId` | string | no | Judge model selector (same grammar as `modelId`). Falls back to workspace `defaultSupervisorModelId`, then workspace default model. |
877
888
  | (literal `false`) | `false` | no | Disables the run supervisor for this run. `loopDetection` and `toolBudgets` still apply. |
878
889
 
879
890
  **Defaults.** When `supervisor` is **omitted**, MANTYX enables the platform
@@ -905,7 +916,52 @@ including `on_track` checks — so SDK clients can render supervisor activity.
905
916
  When `action` is `redirect` or `finalize`, the pipeline has already applied
906
917
  the verdict by the time the event arrives.
907
918
 
908
- ### 4.9 `metadata` (developer-supplied KV for filtering)
919
+ ### 4.9 `plan` (task plan / plan-only)
920
+
921
+ `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
+ (unlike the supervisor, which is default-on) because every planned run pays
924
+ for at least one extra classifier LLM call.
925
+
926
+ ```jsonc
927
+ "plan": true // auto: classify, emit a task_plan event, track during the run
928
+
929
+ "plan": { // caller-provided checklist — skips the classifier
930
+ "brief": "Migrate the billing tables and backfill", // optional
931
+ "steps": ["Snapshot current schema", "Apply migration", "Backfill rows", "Verify counts"]
932
+ }
933
+
934
+ "plan": { "planOnly": true } // produce the plan, do NOT run the agent
935
+ "plan": { "planOnly": true, "steps": ["…", "…"] } // plan-only with a caller-provided checklist
936
+
937
+ "plan": false // (or omit) no planning — a plain run
938
+ ```
939
+
940
+ | Form | Behavior |
941
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
942
+ | omitted / `false` | No planning. Default. |
943
+ | `true` | Pre-flight classifier decides whether a multi-step plan is warranted. If so, a `task_plan` event is emitted (see §7), the checklist is injected into the user turn, and step statuses are tracked (advancing on tool activity and supervisor reviews) until the run ends. If it declines, the run proceeds with no plan. |
944
+ | `{ steps, brief? }` | Caller-provided checklist used verbatim — **skips** the classifier (and its `MIN_STEPS` gate). Injected + tracked like the auto case. |
945
+ | `{ planOnly: true, steps? }` | Produce the plan (classifier when `steps` omitted, otherwise the provided checklist) and **terminate without executing the agent loop**. The terminal `result` carries `data.plan` (see §7). |
946
+
947
+ | Field | Type | Required | Notes |
948
+ | ---------- | -------- | -------- | ---------------------------------------------------------------------------------------------------- |
949
+ | `planOnly` | boolean | no | When `true`, the run stops after producing the plan. |
950
+ | `brief` | string | no | One-line objective for a caller-provided plan. Clamped server-side. |
951
+ | `steps` | string[] | no | Caller-provided checklist titles. Empty/omitted ⇒ auto-classify. Count + per-step length clamped server-side. |
952
+
953
+ Plan-only runs do **not** append an assistant turn to a session (the plan is
954
+ not the answer). Planner LLM usage (classifier + per-run tracker) is metered
955
+ under the `task_planning` usage surface.
956
+
957
+ **Inheritance for sessions.**
958
+
959
+ - `POST /agent-sessions { plan }` — sets the session-default, applied to every
960
+ subsequent message run.
961
+ - `POST /agent-sessions/:id/messages { plan }` — optional per-message override;
962
+ applies to that one run only and does not mutate the session's stored value.
963
+
964
+ ### 4.10 `metadata` (developer-supplied KV for filtering)
909
965
 
910
966
  `metadata` is a flat string→string KV that is **persisted alongside the run /
911
967
  session** and surfaced in the MANTYX dashboard. Use it to tag runs with your
@@ -932,9 +988,11 @@ For session-scoped runs the inheritance rules are:
932
988
  metadata do not retroactively rewrite past runs.
933
989
 
934
990
  Metadata is returned on every read: `GET /agent-runs/:id`,
935
- `GET /agent-sessions/:id`, and the admin list/detail endpoints. Filtering on
936
- the admin list endpoints uses repeated `?metadata=key:value` query params,
937
- AND-combined; see `docs/agent-runs.md` §"Web UI" for details.
991
+ `GET /agent-sessions/:id`, the public session list (`GET /agent-sessions`,
992
+ see §6.1), and the admin list/detail endpoints. Filtering uses repeated
993
+ `?metadata=key:value` query params, AND-combined — supported on both the
994
+ public `GET /agent-sessions` endpoint and the admin list endpoints; see
995
+ `docs/agent-runs.md` §"Web UI" for the admin surface.
938
996
 
939
997
  ## 5. One-shot runs
940
998
 
@@ -966,7 +1024,9 @@ runs or attributing spend after the SSE stream was already consumed.
966
1024
 
967
1025
  ```
968
1026
  POST /api/v1/workspaces/{slug}/agent-sessions
1027
+ GET /api/v1/workspaces/{slug}/agent-sessions
969
1028
  GET /api/v1/workspaces/{slug}/agent-sessions/{sessionId}
1029
+ GET /api/v1/workspaces/{slug}/agent-sessions/{sessionId}/events
970
1030
  POST /api/v1/workspaces/{slug}/agent-sessions/{sessionId}/messages
971
1031
  DELETE /api/v1/workspaces/{slug}/agent-sessions/{sessionId}
972
1032
  ```
@@ -979,6 +1039,87 @@ Returns:
979
1039
  { "sessionId": "ses_abc" }
980
1040
  ```
981
1041
 
1042
+ ### 6.1 Listing sessions (`GET /agent-sessions`)
1043
+
1044
+ Lists the workspace's sessions, most-recently-used first. Supports paging
1045
+ and metadata filtering so callers can find earlier sessions by the
1046
+ application identifiers they attached at create time (see §4.9).
1047
+
1048
+ | Query param | Notes |
1049
+ | ----------- | ------------------------------------------------------------------------------------------- |
1050
+ | `metadata` | Repeatable `key:value` filter; AND-combined. Malformed entries return `400 invalid_request`. |
1051
+ | `status` | Optional exact match (`active` / `ended`). |
1052
+ | `limit` | Default `50`, max `200`. |
1053
+ | `offset` | Default `0`. |
1054
+
1055
+ ```http
1056
+ GET /api/v1/workspaces/acme/agent-sessions?metadata=customer:acme&metadata=env:prod&limit=20
1057
+ ```
1058
+
1059
+ ```jsonc
1060
+ {
1061
+ "total": 1,
1062
+ "limit": 20,
1063
+ "offset": 0,
1064
+ "sessions": [
1065
+ {
1066
+ "sessionId": "ses_abc",
1067
+ "creationDate": "2026-06-08T17:00:00.000Z", // ISO 8601 — when created
1068
+ "lastInteractionDate": "2026-06-08T17:42:10.000Z", // ISO 8601 — last message run
1069
+ "summary": "How do I reset my password?", // derived from the first user prompt
1070
+ "metadata": { "customer": "acme", "env": "prod" },
1071
+ "status": "active"
1072
+ }
1073
+ ]
1074
+ }
1075
+ ```
1076
+
1077
+ `summary` is a best-effort label derived from the conversation's first user
1078
+ prompt (sessions have no title); when the opener is very short the following
1079
+ messages are appended until it is informative.
1080
+
1081
+ ### 6.2 Replaying a session as events (`GET /agent-sessions/{sessionId}/events`)
1082
+
1083
+ Returns the session's stored conversation as realtime-style event frames so a
1084
+ UI can restore the thread through the same handler it uses for the live SSE
1085
+ stream (§7). Unknown session ids return `404 not_found`.
1086
+
1087
+ | Query param | Notes |
1088
+ | -------------- | ---------------------------------------------------------------------------------------------- |
1089
+ | `full` | `1` / `true` returns every message (the default when no paging param is given). |
1090
+ | `lastMessages` | Return only the last `N` messages. Ignored when `full` is set. |
1091
+
1092
+ ```http
1093
+ GET /api/v1/workspaces/acme/agent-sessions/ses_abc/events?lastMessages=2
1094
+ ```
1095
+
1096
+ ```jsonc
1097
+ {
1098
+ "sessionId": "ses_abc",
1099
+ "total": 4, // total messages in the session (not the page size)
1100
+ "events": [
1101
+ { "seq": 3, "type": "user_message", "text": "three" },
1102
+ { "seq": 4, "type": "assistant_message", "text": "four" }
1103
+ ]
1104
+ }
1105
+ ```
1106
+
1107
+ Frames use the flattened wire shape clients already consume from SSE
1108
+ (`{ seq, type, ...payload }`). `seq` is the message's position in the full
1109
+ conversation (stable across paging). Reconstructed turns map as:
1110
+
1111
+ | Stored role | Frame `type` |
1112
+ | ----------- | ------------------- |
1113
+ | `user` | `user_message` |
1114
+ | `assistant` | `assistant_message` |
1115
+ | other | `message` (carries a `role` field) |
1116
+
1117
+ `user_message` is a **replay/restore-only** frame — the live SSE stream never
1118
+ emits it (the client already knows the prompt it sent), but history
1119
+ restoration needs it to rebuild the user side of the conversation. This first
1120
+ cut reconstructs from the durable transcript (`role`/`content` only); tool
1121
+ calls are not replayed here.
1122
+
982
1123
  `POST /agent-sessions/{id}/messages` queues a new run scoped to the session
983
1124
  and returns `{ runId, streamUrl }` just like a one-shot run. Body:
984
1125
 
@@ -1060,10 +1201,15 @@ data: <utf-8 JSON>
1060
1201
  { "seq": 7, "type": "tool_budget_exceeded", "data": { "tool": "recall", "maxCalls": 4, "callIndex": 5 } }
1061
1202
 
1062
1203
  // run-supervisor check (see §4.8). Fired on every review — on_track included.
1063
- { "seq": 7, "type": "supervisor", "data": { "action": "on_track", "reason": "Agent is making progress.", "llmCalls": 5 } }
1204
+ { "seq": 7, "type": "supervisor", "data": { "action": "on_track", "reason": "Agent is making progress.", "llmCalls": 5, "model": { "id": "platform:demo", "provider": "openai", "vendorModelId": "gpt-4o-mini" } } }
1064
1205
  { "seq": 8, "type": "supervisor", "data": { "action": "redirect", "reason": "Stuck re-querying.", "redirect": "Answer from the data you already have.", "llmCalls": 10 } }
1065
1206
  { "seq": 9, "type": "supervisor", "data": { "action": "finalize", "reason": "Enough to answer.", "llmCalls": 15 } }
1066
1207
 
1208
+ // in-product task plan (see §4.9). Emitted only when the run carries a `plan` spec
1209
+ // field: once after classify / caller-supplied plan, then on each tracker advance.
1210
+ // Non-terminal — render as a live checklist. status ∈ "pending" | "in_progress" | "done".
1211
+ { "seq": 4, "type": "task_plan", "data": { "brief": "Compare Q3 vs Q4 revenue.", "steps": [ { "title": "Pull revenue", "status": "in_progress" }, { "title": "Compute deltas", "status": "pending" } ] } }
1212
+
1067
1213
  // terminal event
1068
1214
  // Every terminal `result` event also carries `tokens`, `turns`, and `model`
1069
1215
  // for cost attribution and dashboards — see §7.1. Older platforms (pre-
@@ -1083,6 +1229,17 @@ data: <utf-8 JSON>
1083
1229
  "turns": 2,
1084
1230
  "model": { "id": "platform:demo", "provider": "anthropic", "vendorModelId": "claude-opus-4-7" }
1085
1231
  } }
1232
+ // plan-only terminal result (see §4.9): the agent loop did NOT run. `data.plan`
1233
+ // carries the structured checklist; `turns` is 0 and `tokens` are zeroed
1234
+ // (classifier usage is metered separately under the `task_planning` surface).
1235
+ { "seq": 5, "type": "result", "data": {
1236
+ "subtype": "success",
1237
+ "text": "Compare Q3 vs Q4 revenue.\n\n1. Pull revenue\n2. Compute deltas",
1238
+ "plan": { "brief": "Compare Q3 vs Q4 revenue.", "steps": [ { "title": "Pull revenue", "status": "pending" }, { "title": "Compute deltas", "status": "pending" } ] },
1239
+ "tokens": { "inputTokens": 0, "cachedTokens": 0, "reasoningTokens": 0, "outputTokens": 0 },
1240
+ "turns": 0,
1241
+ "model": { "id": "platform:demo", "provider": "openai", "vendorModelId": "gpt-5.4-mini" }
1242
+ } }
1086
1243
  { "seq": 8, "type": "cancelled", "data": {} }
1087
1244
  ```
1088
1245
 
@@ -1316,6 +1473,11 @@ A reference SDK should:
1316
1473
  the SDK's job is just to surface the event to the caller (status banner,
1317
1474
  log line, telemetry). Do **not** abort the run on these events; the run
1318
1475
  continues through `result` / `error` / `cancelled` as usual.
1476
+ - Accept `plan` from the caller (`true` | `{ steps?, brief?, planOnly? }` |
1477
+ `false`) and pass it through unchanged (see §4.9). It is opt-in — omitting
1478
+ it (or `false`) means no planning. Render `task_plan` events as a live,
1479
+ non-terminal checklist; for `planOnly` runs read the final checklist from
1480
+ the terminal `result.data.plan`.
1319
1481
  - On terminal `result`, resolve the call. On `error` subtype, throw.
1320
1482
  4. Re-emit assistant deltas/events as a stream/iterator for callers who care
1321
1483
  about live output.