@mantyx/sdk 0.22.1 → 0.23.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.ts CHANGED
@@ -33,8 +33,8 @@
33
33
  *
34
34
  * console.log(result.text);
35
35
  */
36
- export { MantyxClient, AgentSession, DEFAULT_BASE_URL, parseRunOutput, planOnly, inputFileAttachment, inputFileUrlAttachment, } from "./client.js";
37
- export type { MantyxClientOptions, ModelInfo, ModelCatalog, AgentSpecBase, RunSpec, SessionSpec, OutputSchema, OutputSchemaValue, LoopDetection, ToolBudget, ToolBudgets, Supervisor, SupervisorAction, SupervisorPhase, ReasoningTrigger, PlanOptions, PlanSpec, TaskPlan, TaskPlanStep, TaskPlanStepStatus, RunResult, RunTokenUsage, RunModelInfo, RunEvent, RunEventBase, AssistantDeltaEvent, ThinkingDeltaEvent, AssistantMessageEvent, UserMessageEvent, InputFileAttachment, InputFileUrlAttachment, MessageAttachment, InputFileAttachmentMetadata, InputFileUrlAttachmentMetadata, AttachmentMetadata, ConversationMessage, ServerToolResultEvent, LocalToolCallEvent, LocalToolResultInEvent, LoopDetectedEvent, ToolBudgetExceededEvent, SupervisorEvent, TaskPlanEvent, ResultEvent, ErrorEvent, CancelledEvent, SessionInfo, SessionSummary, SessionListResult, LocalHandlers, RunFeedbackVerdict, RunFeedbackInput, RunFeedbackResult, EvalRunStatus, InlineEvalCaseSpec, InlineEvalDatasetSpec, AgentEvalOverrides, CreateEvalRunRequest, EvalDatasetSummary, EvalDatasetList, EvalCase, EvalDatasetDetail, EvalRunAccepted, EvalRunSummary, EvalCaseResult, EvalRunDetail, EvalRunList, EvalRunCompareSide, EvalRunCompareCase, EvalRunCompare, EvalRunEvent, ListEvalRunsOptions, RunEvalOptions, } from "./client.js";
36
+ export { MantyxClient, AgentSession, DEFAULT_BASE_URL, parseRunOutput, planOnly, taskPlanFromEventData, inputFileAttachment, inputFileUrlAttachment, } from "./client.js";
37
+ export type { MantyxClientOptions, ModelInfo, ModelCatalog, AgentSpecBase, RunSpec, SessionSpec, OutputSchema, OutputSchemaValue, LoopDetection, ToolBudget, ToolBudgets, Supervisor, SupervisorAction, SupervisorPhase, ReasoningTrigger, PlanOptions, PlanMode, PlanSpec, TaskPlan, TaskPlanStep, TaskPlanStepStatus, TaskPlanTransition, RunResult, RunTokenUsage, RunModelInfo, RunEvent, RunEventBase, AssistantDeltaEvent, ThinkingDeltaEvent, AssistantMessageEvent, UserMessageEvent, InputFileAttachment, InputFileUrlAttachment, MessageAttachment, InputFileAttachmentMetadata, InputFileUrlAttachmentMetadata, AttachmentMetadata, ConversationMessage, ServerToolResultEvent, LocalToolCallEvent, LocalToolResultInEvent, LoopDetectedEvent, ToolBudgetExceededEvent, SupervisorEvent, TaskPlanEvent, ResultEvent, ErrorEvent, CancelledEvent, SessionInfo, SessionSummary, SessionListResult, LocalHandlers, RunFeedbackVerdict, RunFeedbackInput, RunFeedbackResult, EvalRunStatus, InlineEvalCaseSpec, InlineEvalDatasetSpec, AgentEvalOverrides, CreateEvalRunRequest, EvalDatasetSummary, EvalDatasetList, EvalCase, EvalDatasetDetail, EvalRunAccepted, EvalRunSummary, EvalCaseResult, EvalRunDetail, EvalRunList, EvalRunCompareSide, EvalRunCompareCase, EvalRunCompare, EvalRunEvent, ListEvalRunsOptions, RunEvalOptions, } from "./client.js";
38
38
  export { defineLocalTool, mantyxTool, mantyxPluginTool, mantyxA2A, defineLocalA2A, mantyxMcp, defineLocalMcp, isLocalTool, isLocalA2ATool, isLocalMcpServer, } from "./tools.js";
39
39
  export type { LocalTool, LocalToolResult, LocalToolOutput, ToolResultFile, MantyxToolRef, MantyxPluginToolRef, ToolRef, ZodLikeObject, DefineLocalToolOptions, ReasoningLevel, A2AToolRef, LocalA2ATool, McpToolRef, LocalMcpServer, LocalMcpHttpTransport, LocalMcpStdioTransport, MantyxA2AOptions, DefineLocalA2AOptions, MantyxMcpOptions, DefineLocalMcpOptions, } from "./tools.js";
40
40
  export { MantyxError, MantyxAuthError, MantyxNetworkError, MantyxParseError, MantyxScopeError, MantyxToolError, MantyxRunError, } from "./errors.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,QAAQ,EACR,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,mBAAmB,EACnB,SAAS,EACT,YAAY,EACZ,aAAa,EACb,OAAO,EACP,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,aAAa,EACb,UAAU,EACV,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,YAAY,EACZ,QAAQ,EACR,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,2BAA2B,EAC3B,8BAA8B,EAC9B,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,uBAAuB,EACvB,eAAe,EACf,aAAa,EACb,WAAW,EACX,UAAU,EACV,cAAc,EACd,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,qBAAqB,EACrB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,cAAc,EACd,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,kBAAkB,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AAC;AAE3B,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,YAAY,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE3D,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,QAAQ,EACR,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,mBAAmB,EACnB,SAAS,EACT,YAAY,EACZ,aAAa,EACb,OAAO,EACP,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,aAAa,EACb,UAAU,EACV,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,YAAY,EACZ,QAAQ,EACR,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,2BAA2B,EAC3B,8BAA8B,EAC9B,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,uBAAuB,EACvB,eAAe,EACf,aAAa,EACb,WAAW,EACX,UAAU,EACV,cAAc,EACd,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,kBAAkB,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ACV,iBAAiB,EACjB,QAAQ,EACR,UAAU,EACV,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,YAAY,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE3D,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -24,9 +24,10 @@ import {
24
24
  parseRunOutput,
25
25
  planOnly,
26
26
  readSseStream,
27
+ taskPlanFromEventData,
27
28
  toToolParametersWire,
28
29
  zodToJsonSchema
29
- } from "./chunk-STB4Z6F4.js";
30
+ } from "./chunk-OUK6ZZ5H.js";
30
31
 
31
32
  // src/oauth.ts
32
33
  var DEFAULT_OAUTH_BASE_URL = "https://app.mantyx.io";
@@ -602,7 +603,7 @@ async function runComputerUse(opts) {
602
603
  }
603
604
 
604
605
  // src/version.ts
605
- var SDK_VERSION = "0.22.1";
606
+ var SDK_VERSION = "0.23.0";
606
607
  export {
607
608
  AgentSession,
608
609
  COMPUTER_USE_ACTIONS,
@@ -640,6 +641,7 @@ export {
640
641
  planOnly,
641
642
  readSseStream,
642
643
  runComputerUse,
644
+ taskPlanFromEventData,
643
645
  toToolParametersWire,
644
646
  zodToJsonSchema
645
647
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/oauth.ts","../src/computer-use.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 * Computer use — an SDK-level browser-control loop built on the existing\n * MANTYX primitives (local tools + sessions + file attachments).\n *\n * Unlike a provider's dedicated \"computer use\" model, this implementation is\n * **model-agnostic**: it works with any vision-capable model in your\n * workspace. The trade-off is that a general model grounds pixel coordinates\n * less precisely than a model tuned for GUI control; the upside is you keep\n * full access to everything the wire protocol offers (loop detection, tool\n * budgets, the supervisor judge, observability) and you are not locked to one\n * vendor.\n *\n * How it works:\n *\n * 1. The action vocabulary (`click_at`, `type_text_at`, `scroll_at`, …) is\n * exposed as ordinary {@link defineLocalTool | local tools}. The model\n * emits a `local_tool_call`, the SDK runs it against your\n * {@link BrowserController}, and posts a short text ack back.\n * 2. Screenshots flow the other direction. Tool results are string-only on\n * the wire, so each step the loop takes a fresh screenshot and sends it\n * as a **user-message attachment** on the next turn (see\n * `docs/agent-runs-protocol.md` §4.0.1). That is what the model \"sees\".\n * 3. {@link runComputerUse} owns the outer loop: screenshot → send → let the\n * model take one action → repeat, until the model answers with plain\n * text (no tool call) or `maxSteps` is hit.\n *\n * Coordinates from the model are on a normalized 0-1000 grid (resolution\n * independent). Each action tool denormalizes against\n * {@link BrowserController.viewport} before calling the controller, so your\n * controller always works in real pixels.\n */\nimport { z } from \"zod\";\nimport { inputFileAttachment } from \"./client.js\";\nimport type { AgentSession, MantyxClient, RunEvent, RunResult } from \"./client.js\";\nimport { defineLocalTool, type LocalTool, type ReasoningLevel } from \"./tools.js\";\n\n// --------------------------------------------------------------- Controller\n\n/** Scroll direction shared by `scroll_at` / `scroll_document`. */\nexport type ScrollDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/** Pixel viewport of the controlled surface, used to denormalize coordinates. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n\n/** A captured screenshot, base64-encoded (no `data:` prefix). */\nexport interface Screenshot {\n /** Base64-encoded image bytes (no `data:` URL prefix). */\n data: string;\n /** Image MIME type, e.g. `\"image/jpeg\"` or `\"image/png\"`. */\n mimeType: string;\n /** Optional filename for the attachment; a default is generated otherwise. */\n filename?: string;\n}\n\n/** Options forwarded to {@link BrowserController.typeTextAt}. */\nexport interface TypeTextOptions {\n /** Press Enter after typing. */\n pressEnter: boolean;\n /** Clear the field before typing. */\n clearBeforeTyping: boolean;\n}\n\n/**\n * The execution surface the computer-use tools drive. Coordinates passed to\n * these methods are **already denormalized to pixels** against\n * {@link viewport}. Implement this with Playwright, Puppeteer, a remote\n * browser, a mobile driver, etc. For Playwright, use\n * {@link PlaywrightController} from `@mantyx/sdk/playwright`.\n *\n * Every method may be sync or async. Methods for actions you exclude via\n * {@link DefineComputerUseToolsOptions.excludeActions} are never called and\n * can be omitted.\n */\nexport interface BrowserController {\n /** Current pixel viewport. Used to denormalize the model's 0-1000 coords. */\n viewport(): Viewport | Promise<Viewport>;\n /** Capture the current screen. Called once per loop step. */\n screenshot(): Screenshot | Promise<Screenshot>;\n /** Current page URL, if meaningful for the environment. Optional. */\n currentUrl?(): string | Promise<string>;\n /** Navigate directly to a URL. */\n navigate?(url: string): void | Promise<void>;\n /** Click at a pixel coordinate. */\n clickAt(x: number, y: number): void | Promise<void>;\n /** Hover at a pixel coordinate. */\n hoverAt?(x: number, y: number): void | Promise<void>;\n /** Type `text` at a pixel coordinate. */\n typeTextAt(x: number, y: number, text: string, opts: TypeTextOptions): void | Promise<void>;\n /** Press a key or chord, e.g. `\"Enter\"` or `\"Control+C\"`. */\n keyCombination?(keys: string): void | Promise<void>;\n /** Scroll the element at a pixel coordinate by `magnitude` pixels. */\n scrollAt?(\n x: number,\n y: number,\n direction: ScrollDirection,\n magnitude: number,\n ): void | Promise<void>;\n /** Scroll the whole document. */\n scrollDocument?(direction: ScrollDirection): void | Promise<void>;\n /** Drag from one pixel coordinate to another. */\n dragAndDrop?(x: number, y: number, destinationX: number, destinationY: number): void | Promise<void>;\n /** Navigate back in history. */\n goBack?(): void | Promise<void>;\n /** Navigate forward in history. */\n goForward?(): void | Promise<void>;\n}\n\n// --------------------------------------------------------------- Coordinates\n\n/**\n * Convert a normalized coordinate (0-1000 grid, matching the convention used\n * by GUI-control models) to an actual pixel value.\n */\nexport function denormalizeCoordinate(value: number, size: number): number {\n return Math.round((value / 1000) * size);\n}\n\n// --------------------------------------------------------------- Tool factory\n\n/** The canonical computer-use action tool names. */\nexport const COMPUTER_USE_ACTIONS = [\n \"navigate\",\n \"click_at\",\n \"hover_at\",\n \"type_text_at\",\n \"key_combination\",\n \"scroll_at\",\n \"scroll_document\",\n \"drag_and_drop\",\n \"go_back\",\n \"go_forward\",\n \"wait\",\n] as const;\n\nexport type ComputerUseAction = (typeof COMPUTER_USE_ACTIONS)[number];\n\nexport interface DefineComputerUseToolsOptions {\n /**\n * Predefined actions to omit (mirrors a dedicated model's\n * `excluded_predefined_functions`). Useful when an environment cannot\n * support an action, e.g. excluding `drag_and_drop` or the navigation\n * actions for a kiosk.\n */\n excludeActions?: ComputerUseAction[];\n /**\n * Include a `request_confirmation` tool the model is told to call before\n * consequential or irreversible actions. The returned promise/boolean from\n * `confirm` decides whether the model is cleared to proceed. Defaults to\n * `true`; when no `confirm` is supplied, confirmation requests are denied.\n */\n requestConfirmation?: boolean;\n /**\n * Human-in-the-loop gate invoked by the `request_confirmation` tool. Return\n * `true` to allow the model to continue with the action it described.\n */\n confirm?: (reason: string) => boolean | Promise<boolean>;\n}\n\nconst WAIT_HINT =\n \"Action performed. A fresh screenshot will be provided in the next message; do not call another action until you have seen it.\";\n\n/**\n * Build the set of computer-use action tools bound to a\n * {@link BrowserController}. Pass the result as `tools` on a session / run, or\n * let {@link runComputerUse} wire everything for you.\n */\nexport function defineComputerUseTools(\n controller: BrowserController,\n opts: DefineComputerUseToolsOptions = {},\n): LocalTool[] {\n const excluded = new Set<ComputerUseAction>(opts.excludeActions ?? []);\n const includeConfirm = opts.requestConfirmation ?? true;\n\n const px = async (x: number, y: number): Promise<{ x: number; y: number }> => {\n const vp = await controller.viewport();\n return { x: denormalizeCoordinate(x, vp.width), y: denormalizeCoordinate(y, vp.height) };\n };\n\n const ack = async (note?: string): Promise<string> => {\n let url: string | undefined;\n if (controller.currentUrl) {\n try {\n url = await controller.currentUrl();\n } catch {\n // currentUrl is best-effort; ignore failures.\n }\n }\n return JSON.stringify({\n status: \"ok\",\n ...(note ? { note } : {}),\n ...(url ? { url } : {}),\n hint: WAIT_HINT,\n });\n };\n\n const tools: LocalTool[] = [];\n const add = (action: ComputerUseAction, build: () => LocalTool): void => {\n if (!excluded.has(action)) tools.push(build());\n };\n\n add(\"navigate\", () =>\n defineLocalTool({\n name: \"navigate\",\n description: \"Navigate the browser directly to a URL.\",\n parameters: z.object({ url: z.string().describe(\"Absolute URL to open.\") }),\n execute: async ({ url }) => {\n if (!controller.navigate) return errorResult(\"navigate is not supported by this environment\");\n await controller.navigate(url);\n return ack();\n },\n }),\n );\n\n add(\"click_at\", () =>\n defineLocalTool({\n name: \"click_at\",\n description:\n \"Click at a coordinate. x and y are on a 0-1000 grid scaled to the screen.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n }),\n execute: async ({ x, y }) => {\n const p = await px(x, y);\n await controller.clickAt(p.x, p.y);\n return ack();\n },\n }),\n );\n\n add(\"hover_at\", () =>\n defineLocalTool({\n name: \"hover_at\",\n description:\n \"Hover the mouse at a coordinate (useful to reveal menus). x and y are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n }),\n execute: async ({ x, y }) => {\n if (!controller.hoverAt) return errorResult(\"hover_at is not supported by this environment\");\n const p = await px(x, y);\n await controller.hoverAt(p.x, p.y);\n return ack();\n },\n }),\n );\n\n add(\"type_text_at\", () =>\n defineLocalTool({\n name: \"type_text_at\",\n description:\n \"Type text at a coordinate. By default clears the field first and presses Enter after typing. x and y are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n text: z.string().describe(\"Text to type.\"),\n press_enter: z.boolean().optional().describe(\"Press Enter after typing. Default true.\"),\n clear_before_typing: z\n .boolean()\n .optional()\n .describe(\"Clear the field before typing. Default true.\"),\n }),\n execute: async ({ x, y, text, press_enter, clear_before_typing }) => {\n const p = await px(x, y);\n await controller.typeTextAt(p.x, p.y, text, {\n pressEnter: press_enter ?? true,\n clearBeforeTyping: clear_before_typing ?? true,\n });\n return ack();\n },\n }),\n );\n\n add(\"key_combination\", () =>\n defineLocalTool({\n name: \"key_combination\",\n description:\n 'Press a key or chord, e.g. \"Enter\", \"Control+C\", \"Control+A\". Useful for submitting or clipboard actions.',\n parameters: z.object({\n keys: z.string().describe('Key or chord, e.g. \"Enter\" or \"Control+C\".'),\n }),\n execute: async ({ keys }) => {\n if (!controller.keyCombination)\n return errorResult(\"key_combination is not supported by this environment\");\n await controller.keyCombination(keys);\n return ack();\n },\n }),\n );\n\n add(\"scroll_at\", () =>\n defineLocalTool({\n name: \"scroll_at\",\n description:\n \"Scroll the area at a coordinate in a direction by a pixel magnitude (default 800). Coordinates are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n direction: z.enum([\"up\", \"down\", \"left\", \"right\"]),\n magnitude: z.number().optional().describe(\"Scroll distance in pixels. Default 800.\"),\n }),\n execute: async ({ x, y, direction, magnitude }) => {\n if (!controller.scrollAt) return errorResult(\"scroll_at is not supported by this environment\");\n const p = await px(x, y);\n await controller.scrollAt(p.x, p.y, direction, magnitude ?? 800);\n return ack();\n },\n }),\n );\n\n add(\"scroll_document\", () =>\n defineLocalTool({\n name: \"scroll_document\",\n description: 'Scroll the whole page \"up\", \"down\", \"left\", or \"right\".',\n parameters: z.object({ direction: z.enum([\"up\", \"down\", \"left\", \"right\"]) }),\n execute: async ({ direction }) => {\n if (!controller.scrollDocument)\n return errorResult(\"scroll_document is not supported by this environment\");\n await controller.scrollDocument(direction);\n return ack();\n },\n }),\n );\n\n add(\"drag_and_drop\", () =>\n defineLocalTool({\n name: \"drag_and_drop\",\n description:\n \"Drag from a starting coordinate and drop at a destination coordinate. All coordinates are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Start horizontal, 0-1000.\"),\n y: z.number().describe(\"Start vertical, 0-1000.\"),\n destination_x: z.number().describe(\"Destination horizontal, 0-1000.\"),\n destination_y: z.number().describe(\"Destination vertical, 0-1000.\"),\n }),\n execute: async ({ x, y, destination_x, destination_y }) => {\n if (!controller.dragAndDrop)\n return errorResult(\"drag_and_drop is not supported by this environment\");\n const from = await px(x, y);\n const to = await px(destination_x, destination_y);\n await controller.dragAndDrop(from.x, from.y, to.x, to.y);\n return ack();\n },\n }),\n );\n\n add(\"go_back\", () =>\n defineLocalTool({\n name: \"go_back\",\n description: \"Navigate to the previous page in history.\",\n parameters: z.object({}),\n execute: async () => {\n if (!controller.goBack) return errorResult(\"go_back is not supported by this environment\");\n await controller.goBack();\n return ack();\n },\n }),\n );\n\n add(\"go_forward\", () =>\n defineLocalTool({\n name: \"go_forward\",\n description: \"Navigate to the next page in history.\",\n parameters: z.object({}),\n execute: async () => {\n if (!controller.goForward)\n return errorResult(\"go_forward is not supported by this environment\");\n await controller.goForward();\n return ack();\n },\n }),\n );\n\n add(\"wait\", () =>\n defineLocalTool({\n name: \"wait\",\n description: \"Pause to let dynamic content load or animations finish.\",\n parameters: z.object({\n seconds: z.number().optional().describe(\"Seconds to wait. Default 1, max 10.\"),\n }),\n execute: async ({ seconds }) => {\n const s = Math.min(Math.max(seconds ?? 1, 0), 10);\n await new Promise((resolve) => setTimeout(resolve, s * 1000));\n return ack(`waited ${s}s`);\n },\n }),\n );\n\n if (includeConfirm) {\n tools.push(\n defineLocalTool({\n name: \"request_confirmation\",\n description:\n \"Ask the human operator to approve a consequential or irreversible action BEFORE performing it (e.g. submitting a form, sending a message, making a purchase, accepting terms, solving a CAPTCHA, logging in). Returns whether you are cleared to proceed.\",\n parameters: z.object({\n reason: z.string().describe(\"What you are about to do and why confirmation is needed.\"),\n }),\n execute: async ({ reason }) => {\n const approved = opts.confirm ? await opts.confirm(reason) : false;\n return JSON.stringify({\n approved,\n ...(approved\n ? { note: \"Operator approved. Proceed with the action, then stop and wait for the next screenshot.\" }\n : { note: \"Operator denied. Do not perform the action; choose a different approach or stop and report back.\" }),\n });\n },\n }),\n );\n }\n\n return tools;\n}\n\nfunction errorResult(message: string): string {\n return JSON.stringify({ status: \"error\", error: message });\n}\n\n// --------------------------------------------------------------- System prompt\n\nexport interface ComputerUseSystemPromptOptions {\n /** Environment label injected into the prompt, e.g. `\"web browser\"`. */\n environment?: string;\n /** Extra task-specific context appended to the standard instructions. */\n extraInstructions?: string;\n /** Whether the `request_confirmation` tool is available (adds safety rules). */\n requestConfirmation?: boolean;\n}\n\n/**\n * Build the system prompt that drives the loop: it teaches the model the\n * screenshot-per-step protocol, the 0-1000 coordinate grid, the one-action-per-turn\n * discipline, when to stop, and the human-in-the-loop safety rules.\n */\nexport function buildComputerUseSystemPrompt(\n opts: ComputerUseSystemPromptOptions = {},\n): string {\n const environment = opts.environment ?? \"web browser\";\n const confirmation = opts.requestConfirmation ?? true;\n\n const lines: string[] = [\n `You are an agent that controls a ${environment} by looking at screenshots and taking UI actions.`,\n \"\",\n \"Protocol:\",\n `- Before every step you receive a screenshot of the current ${environment} as an image attachment. Study it carefully.`,\n \"- Choose EXACTLY ONE action and call the matching tool. Coordinates use a 0-1000 grid (top-left is 0,0; bottom-right is 1000,1000), scaled automatically to the screen.\",\n \"- After the tool runs, STOP and wait. You will be given a new screenshot reflecting the result; only then decide the next action.\",\n \"- Do not chain multiple actions in one turn and do not guess what happened — always rely on the next screenshot.\",\n \"- Scroll to reveal content before concluding something is missing.\",\n \"\",\n \"Finishing:\",\n \"- When the task is complete (or you have gathered enough information to answer), reply with a plain-text final answer and DO NOT call any tool. That ends the session.\",\n \"- If you get stuck or cannot proceed, explain why in plain text without calling a tool.\",\n ];\n\n if (confirmation) {\n lines.push(\n \"\",\n \"Safety — you MUST call `request_confirmation` and wait for approval BEFORE any consequential or irreversible action, including:\",\n \"- Accepting terms of service, privacy policies, cookie banners, or other agreements.\",\n \"- Solving or bypassing CAPTCHAs or other human-verification checks.\",\n \"- Completing a purchase, moving money, or any financial transaction.\",\n \"- Sending an email or message, or posting content.\",\n \"- Logging into an account, or accessing/modifying sensitive personal data.\",\n \"- Downloading, saving, sharing, or transferring files or user data.\",\n \"For these, do all preparatory steps first, then call `request_confirmation` immediately BEFORE the final irreversible click. If denied, do not perform the action.\",\n );\n }\n\n if (opts.extraInstructions) {\n lines.push(\"\", opts.extraInstructions);\n }\n\n return lines.join(\"\\n\");\n}\n\n// --------------------------------------------------------------- Loop driver\n\n/** One action the model invoked on a turn (derived from `local_tool_call` events). */\nexport interface ComputerUseActionCall {\n name: string;\n input: Record<string, unknown>;\n}\n\n/** A single iteration of the computer-use loop. */\nexport interface ComputerUseStep {\n /** 1-based step index. */\n step: number;\n /** The screenshot sent to the model at the start of this step. */\n screenshot: Screenshot;\n /** The full run result for the turn. */\n result: RunResult;\n /** Actions the model invoked this turn (empty when it produced a final answer). */\n actions: ComputerUseActionCall[];\n}\n\nexport interface RunComputerUseOptions {\n /** MANTYX client used to open the session. */\n client: MantyxClient;\n /** The user's goal, sent on the first turn. */\n goal: string;\n /** Drives the actual UI actions and screenshots. */\n controller: BrowserController;\n /** Vision-capable model id (`modelId`). Omit to use the workspace default. */\n model?: string;\n /** Max loop iterations before stopping. Default 20. */\n maxSteps?: number;\n /** Override the generated system prompt entirely. */\n systemPrompt?: string;\n /** Tweaks for the generated system prompt (ignored when `systemPrompt` is set). */\n systemPromptOptions?: ComputerUseSystemPromptOptions;\n /** Actions to omit from the tool surface. */\n excludeActions?: ComputerUseAction[];\n /** Human-in-the-loop gate for `request_confirmation`. Omit to disable confirmations. */\n confirm?: (reason: string) => boolean | Promise<boolean>;\n /** Disable the `request_confirmation` tool entirely. Default false (it is included). */\n disableConfirmation?: boolean;\n /** Provider reasoning strength for the session. */\n reasoningLevel?: ReasoningLevel;\n /** Observability metadata stored on the session. */\n metadata?: Record<string, string>;\n /** Text sent alongside the screenshot on every turn after the first. */\n continueText?: string;\n /** Invoked after each step (await is honored), e.g. for logging. */\n onStep?: (step: ComputerUseStep) => void | Promise<void>;\n /** Streams assistant text deltas. */\n onAssistantDelta?: (delta: string) => void;\n /** Aborts the loop and the in-flight turn. */\n signal?: AbortSignal;\n}\n\nexport interface ComputerUseResult {\n /** The model's final plain-text answer (text of the last turn). */\n finalText: string;\n /** Every step taken, in order. */\n steps: ComputerUseStep[];\n /** The session that ran the loop (already ended). */\n sessionId: string;\n /** Why the loop stopped. */\n stoppedReason: \"completed\" | \"max_steps\";\n}\n\nconst DEFAULT_CONTINUE_TEXT =\n \"Here is the screen after your last action. Continue toward the goal, or give your final answer if the task is done.\";\n\n/** Pull the actions the model invoked this turn from the run's events. */\nexport function extractActions(result: RunResult): ComputerUseActionCall[] {\n const actions: ComputerUseActionCall[] = [];\n for (const ev of result.events as RunEvent[]) {\n if (ev.type === \"local_tool_call\") {\n const e = ev as { name?: string; args?: Record<string, unknown> };\n actions.push({ name: e.name ?? \"\", input: e.args ?? {} });\n }\n }\n return actions;\n}\n\nfunction screenshotExtension(mimeType: string): string {\n if (mimeType.includes(\"png\")) return \"png\";\n if (mimeType.includes(\"webp\")) return \"webp\";\n return \"jpg\";\n}\n\n/**\n * Run a model-agnostic computer-use loop: screenshot → send → one action →\n * repeat, until the model answers in plain text or `maxSteps` is reached. The\n * session is created internally and ended on return.\n *\n * @example\n * const out = await runComputerUse({\n * client,\n * model: \"google/gemini-3-flash\",\n * goal: \"Find the cheapest 2-door smart fridge on the site and report its price.\",\n * controller: playwrightController, // implements BrowserController\n * confirm: async (reason) => askOperator(reason),\n * });\n * console.log(out.finalText);\n */\nexport async function runComputerUse(opts: RunComputerUseOptions): Promise<ComputerUseResult> {\n const maxSteps = opts.maxSteps ?? 20;\n if (maxSteps < 1) throw new Error(\"runComputerUse: maxSteps must be >= 1\");\n\n const requestConfirmation = !opts.disableConfirmation;\n const tools = defineComputerUseTools(opts.controller, {\n ...(opts.excludeActions ? { excludeActions: opts.excludeActions } : {}),\n requestConfirmation,\n ...(opts.confirm ? { confirm: opts.confirm } : {}),\n });\n\n const systemPrompt =\n opts.systemPrompt ??\n buildComputerUseSystemPrompt({\n ...(opts.systemPromptOptions ?? {}),\n requestConfirmation,\n });\n\n const session: AgentSession = await opts.client.createSession({\n systemPrompt,\n ...(opts.model ? { modelId: opts.model } : {}),\n tools,\n ...(opts.reasoningLevel !== undefined ? { reasoningLevel: opts.reasoningLevel } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n\n const steps: ComputerUseStep[] = [];\n let finalText = \"\";\n let stoppedReason: \"completed\" | \"max_steps\" = \"max_steps\";\n\n try {\n for (let i = 0; i < maxSteps; i++) {\n const screenshot = await opts.controller.screenshot();\n const filename =\n screenshot.filename ?? `screenshot-${i + 1}.${screenshotExtension(screenshot.mimeType)}`;\n const attachment = inputFileAttachment({\n mimeType: screenshot.mimeType,\n filename,\n data: screenshot.data,\n });\n\n const turnText = i === 0 ? opts.goal : opts.continueText ?? DEFAULT_CONTINUE_TEXT;\n const result = await session.send(turnText, {\n attachments: [attachment],\n ...(opts.onAssistantDelta ? { onAssistantDelta: opts.onAssistantDelta } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n\n const actions = extractActions(result);\n const step: ComputerUseStep = { step: i + 1, screenshot, result, actions };\n steps.push(step);\n finalText = result.text;\n\n if (opts.onStep) await opts.onStep(step);\n\n if (actions.length === 0) {\n stoppedReason = \"completed\";\n break;\n }\n }\n\n return { finalText, steps, sessionId: session.id, stoppedReason };\n } finally {\n await session.end().catch(() => {\n // Best-effort cleanup; surfacing an end() failure would mask the real result.\n });\n }\n}\n","/**\n * Release version — synced from repo root VERSION (`npm run sync-version`).\n */\nexport const SDK_VERSION = \"0.22.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,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,KAAK,UAAU;AAClB,YAAM,IAAI,YAAY,8CAA8C;AAAA,IACtE;AACA,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,YAAY,kDAAkD;AAAA,IAC1E;AACA,UAAM,IAAI,KAAK,SAAS,WAAW;AACnC,QAAI,OAAO,MAAM,YAAY;AAC3B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,SAAK,WAAW,KAAK;AACrB,SAAK,eAAe,KAAK;AACzB,SAAK,WAAW,KAAK,WAAW,wBAAwB,QAAQ,QAAQ,EAAE;AAC1E,SAAK,YAAY;AACjB,SAAK,YAAY,KAAK,aAAa;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,QAAQ,MAA2C;AACvD,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,YAAY,0DAA0D;AAAA,IAClF;AACA,UAAM,OAA+B;AA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AAED,YAAM,WAAW,MAAM,IAAI,KAAK,OAAO,KAAK,gBAAgB;AAC5D,YAAM,SAAS,MAAM,QAAQ,KAAK,UAAU;AAAA,QAC1C,aAAa,CAAC,UAAU;AAAA,QACxB,GAAI,KAAK,mBAAmB,EAAE,kBAAkB,KAAK,iBAAiB,IAAI,CAAC;AAAA,QAC3E,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,MAC/C,CAAC;AAED,YAAM,UAAU,eAAe,MAAM;AACrC,YAAM,OAAwB,EAAE,MAAM,IAAI,GAAG,YAAY,QAAQ,QAAQ;AACzE,YAAM,KAAK,IAAI;AACf,kBAAY,OAAO;AAEnB,UAAI,KAAK,OAAQ,OAAM,KAAK,OAAO,IAAI;AAEvC,UAAI,QAAQ,WAAW,GAAG;AACxB,wBAAgB;AAChB;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,WAAW,OAAO,WAAW,QAAQ,IAAI,cAAc;AAAA,EAClE,UAAE;AACA,UAAM,QAAQ,IAAI,EAAE,MAAM,MAAM;AAAA,IAEhC,CAAC;AAAA,EACH;AACF;;;ACroBO,IAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/oauth.ts","../src/computer-use.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 * Computer use — an SDK-level browser-control loop built on the existing\n * MANTYX primitives (local tools + sessions + file attachments).\n *\n * Unlike a provider's dedicated \"computer use\" model, this implementation is\n * **model-agnostic**: it works with any vision-capable model in your\n * workspace. The trade-off is that a general model grounds pixel coordinates\n * less precisely than a model tuned for GUI control; the upside is you keep\n * full access to everything the wire protocol offers (loop detection, tool\n * budgets, the supervisor judge, observability) and you are not locked to one\n * vendor.\n *\n * How it works:\n *\n * 1. The action vocabulary (`click_at`, `type_text_at`, `scroll_at`, …) is\n * exposed as ordinary {@link defineLocalTool | local tools}. The model\n * emits a `local_tool_call`, the SDK runs it against your\n * {@link BrowserController}, and posts a short text ack back.\n * 2. Screenshots flow the other direction. Tool results are string-only on\n * the wire, so each step the loop takes a fresh screenshot and sends it\n * as a **user-message attachment** on the next turn (see\n * `docs/agent-runs-protocol.md` §4.0.1). That is what the model \"sees\".\n * 3. {@link runComputerUse} owns the outer loop: screenshot → send → let the\n * model take one action → repeat, until the model answers with plain\n * text (no tool call) or `maxSteps` is hit.\n *\n * Coordinates from the model are on a normalized 0-1000 grid (resolution\n * independent). Each action tool denormalizes against\n * {@link BrowserController.viewport} before calling the controller, so your\n * controller always works in real pixels.\n */\nimport { z } from \"zod\";\nimport { inputFileAttachment } from \"./client.js\";\nimport type { AgentSession, MantyxClient, RunEvent, RunResult } from \"./client.js\";\nimport { defineLocalTool, type LocalTool, type ReasoningLevel } from \"./tools.js\";\n\n// --------------------------------------------------------------- Controller\n\n/** Scroll direction shared by `scroll_at` / `scroll_document`. */\nexport type ScrollDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/** Pixel viewport of the controlled surface, used to denormalize coordinates. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n\n/** A captured screenshot, base64-encoded (no `data:` prefix). */\nexport interface Screenshot {\n /** Base64-encoded image bytes (no `data:` URL prefix). */\n data: string;\n /** Image MIME type, e.g. `\"image/jpeg\"` or `\"image/png\"`. */\n mimeType: string;\n /** Optional filename for the attachment; a default is generated otherwise. */\n filename?: string;\n}\n\n/** Options forwarded to {@link BrowserController.typeTextAt}. */\nexport interface TypeTextOptions {\n /** Press Enter after typing. */\n pressEnter: boolean;\n /** Clear the field before typing. */\n clearBeforeTyping: boolean;\n}\n\n/**\n * The execution surface the computer-use tools drive. Coordinates passed to\n * these methods are **already denormalized to pixels** against\n * {@link viewport}. Implement this with Playwright, Puppeteer, a remote\n * browser, a mobile driver, etc. For Playwright, use\n * {@link PlaywrightController} from `@mantyx/sdk/playwright`.\n *\n * Every method may be sync or async. Methods for actions you exclude via\n * {@link DefineComputerUseToolsOptions.excludeActions} are never called and\n * can be omitted.\n */\nexport interface BrowserController {\n /** Current pixel viewport. Used to denormalize the model's 0-1000 coords. */\n viewport(): Viewport | Promise<Viewport>;\n /** Capture the current screen. Called once per loop step. */\n screenshot(): Screenshot | Promise<Screenshot>;\n /** Current page URL, if meaningful for the environment. Optional. */\n currentUrl?(): string | Promise<string>;\n /** Navigate directly to a URL. */\n navigate?(url: string): void | Promise<void>;\n /** Click at a pixel coordinate. */\n clickAt(x: number, y: number): void | Promise<void>;\n /** Hover at a pixel coordinate. */\n hoverAt?(x: number, y: number): void | Promise<void>;\n /** Type `text` at a pixel coordinate. */\n typeTextAt(x: number, y: number, text: string, opts: TypeTextOptions): void | Promise<void>;\n /** Press a key or chord, e.g. `\"Enter\"` or `\"Control+C\"`. */\n keyCombination?(keys: string): void | Promise<void>;\n /** Scroll the element at a pixel coordinate by `magnitude` pixels. */\n scrollAt?(\n x: number,\n y: number,\n direction: ScrollDirection,\n magnitude: number,\n ): void | Promise<void>;\n /** Scroll the whole document. */\n scrollDocument?(direction: ScrollDirection): void | Promise<void>;\n /** Drag from one pixel coordinate to another. */\n dragAndDrop?(x: number, y: number, destinationX: number, destinationY: number): void | Promise<void>;\n /** Navigate back in history. */\n goBack?(): void | Promise<void>;\n /** Navigate forward in history. */\n goForward?(): void | Promise<void>;\n}\n\n// --------------------------------------------------------------- Coordinates\n\n/**\n * Convert a normalized coordinate (0-1000 grid, matching the convention used\n * by GUI-control models) to an actual pixel value.\n */\nexport function denormalizeCoordinate(value: number, size: number): number {\n return Math.round((value / 1000) * size);\n}\n\n// --------------------------------------------------------------- Tool factory\n\n/** The canonical computer-use action tool names. */\nexport const COMPUTER_USE_ACTIONS = [\n \"navigate\",\n \"click_at\",\n \"hover_at\",\n \"type_text_at\",\n \"key_combination\",\n \"scroll_at\",\n \"scroll_document\",\n \"drag_and_drop\",\n \"go_back\",\n \"go_forward\",\n \"wait\",\n] as const;\n\nexport type ComputerUseAction = (typeof COMPUTER_USE_ACTIONS)[number];\n\nexport interface DefineComputerUseToolsOptions {\n /**\n * Predefined actions to omit (mirrors a dedicated model's\n * `excluded_predefined_functions`). Useful when an environment cannot\n * support an action, e.g. excluding `drag_and_drop` or the navigation\n * actions for a kiosk.\n */\n excludeActions?: ComputerUseAction[];\n /**\n * Include a `request_confirmation` tool the model is told to call before\n * consequential or irreversible actions. The returned promise/boolean from\n * `confirm` decides whether the model is cleared to proceed. Defaults to\n * `true`; when no `confirm` is supplied, confirmation requests are denied.\n */\n requestConfirmation?: boolean;\n /**\n * Human-in-the-loop gate invoked by the `request_confirmation` tool. Return\n * `true` to allow the model to continue with the action it described.\n */\n confirm?: (reason: string) => boolean | Promise<boolean>;\n}\n\nconst WAIT_HINT =\n \"Action performed. A fresh screenshot will be provided in the next message; do not call another action until you have seen it.\";\n\n/**\n * Build the set of computer-use action tools bound to a\n * {@link BrowserController}. Pass the result as `tools` on a session / run, or\n * let {@link runComputerUse} wire everything for you.\n */\nexport function defineComputerUseTools(\n controller: BrowserController,\n opts: DefineComputerUseToolsOptions = {},\n): LocalTool[] {\n const excluded = new Set<ComputerUseAction>(opts.excludeActions ?? []);\n const includeConfirm = opts.requestConfirmation ?? true;\n\n const px = async (x: number, y: number): Promise<{ x: number; y: number }> => {\n const vp = await controller.viewport();\n return { x: denormalizeCoordinate(x, vp.width), y: denormalizeCoordinate(y, vp.height) };\n };\n\n const ack = async (note?: string): Promise<string> => {\n let url: string | undefined;\n if (controller.currentUrl) {\n try {\n url = await controller.currentUrl();\n } catch {\n // currentUrl is best-effort; ignore failures.\n }\n }\n return JSON.stringify({\n status: \"ok\",\n ...(note ? { note } : {}),\n ...(url ? { url } : {}),\n hint: WAIT_HINT,\n });\n };\n\n const tools: LocalTool[] = [];\n const add = (action: ComputerUseAction, build: () => LocalTool): void => {\n if (!excluded.has(action)) tools.push(build());\n };\n\n add(\"navigate\", () =>\n defineLocalTool({\n name: \"navigate\",\n description: \"Navigate the browser directly to a URL.\",\n parameters: z.object({ url: z.string().describe(\"Absolute URL to open.\") }),\n execute: async ({ url }) => {\n if (!controller.navigate) return errorResult(\"navigate is not supported by this environment\");\n await controller.navigate(url);\n return ack();\n },\n }),\n );\n\n add(\"click_at\", () =>\n defineLocalTool({\n name: \"click_at\",\n description:\n \"Click at a coordinate. x and y are on a 0-1000 grid scaled to the screen.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n }),\n execute: async ({ x, y }) => {\n const p = await px(x, y);\n await controller.clickAt(p.x, p.y);\n return ack();\n },\n }),\n );\n\n add(\"hover_at\", () =>\n defineLocalTool({\n name: \"hover_at\",\n description:\n \"Hover the mouse at a coordinate (useful to reveal menus). x and y are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n }),\n execute: async ({ x, y }) => {\n if (!controller.hoverAt) return errorResult(\"hover_at is not supported by this environment\");\n const p = await px(x, y);\n await controller.hoverAt(p.x, p.y);\n return ack();\n },\n }),\n );\n\n add(\"type_text_at\", () =>\n defineLocalTool({\n name: \"type_text_at\",\n description:\n \"Type text at a coordinate. By default clears the field first and presses Enter after typing. x and y are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n text: z.string().describe(\"Text to type.\"),\n press_enter: z.boolean().optional().describe(\"Press Enter after typing. Default true.\"),\n clear_before_typing: z\n .boolean()\n .optional()\n .describe(\"Clear the field before typing. Default true.\"),\n }),\n execute: async ({ x, y, text, press_enter, clear_before_typing }) => {\n const p = await px(x, y);\n await controller.typeTextAt(p.x, p.y, text, {\n pressEnter: press_enter ?? true,\n clearBeforeTyping: clear_before_typing ?? true,\n });\n return ack();\n },\n }),\n );\n\n add(\"key_combination\", () =>\n defineLocalTool({\n name: \"key_combination\",\n description:\n 'Press a key or chord, e.g. \"Enter\", \"Control+C\", \"Control+A\". Useful for submitting or clipboard actions.',\n parameters: z.object({\n keys: z.string().describe('Key or chord, e.g. \"Enter\" or \"Control+C\".'),\n }),\n execute: async ({ keys }) => {\n if (!controller.keyCombination)\n return errorResult(\"key_combination is not supported by this environment\");\n await controller.keyCombination(keys);\n return ack();\n },\n }),\n );\n\n add(\"scroll_at\", () =>\n defineLocalTool({\n name: \"scroll_at\",\n description:\n \"Scroll the area at a coordinate in a direction by a pixel magnitude (default 800). Coordinates are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Horizontal coordinate, 0-1000.\"),\n y: z.number().describe(\"Vertical coordinate, 0-1000.\"),\n direction: z.enum([\"up\", \"down\", \"left\", \"right\"]),\n magnitude: z.number().optional().describe(\"Scroll distance in pixels. Default 800.\"),\n }),\n execute: async ({ x, y, direction, magnitude }) => {\n if (!controller.scrollAt) return errorResult(\"scroll_at is not supported by this environment\");\n const p = await px(x, y);\n await controller.scrollAt(p.x, p.y, direction, magnitude ?? 800);\n return ack();\n },\n }),\n );\n\n add(\"scroll_document\", () =>\n defineLocalTool({\n name: \"scroll_document\",\n description: 'Scroll the whole page \"up\", \"down\", \"left\", or \"right\".',\n parameters: z.object({ direction: z.enum([\"up\", \"down\", \"left\", \"right\"]) }),\n execute: async ({ direction }) => {\n if (!controller.scrollDocument)\n return errorResult(\"scroll_document is not supported by this environment\");\n await controller.scrollDocument(direction);\n return ack();\n },\n }),\n );\n\n add(\"drag_and_drop\", () =>\n defineLocalTool({\n name: \"drag_and_drop\",\n description:\n \"Drag from a starting coordinate and drop at a destination coordinate. All coordinates are on a 0-1000 grid.\",\n parameters: z.object({\n x: z.number().describe(\"Start horizontal, 0-1000.\"),\n y: z.number().describe(\"Start vertical, 0-1000.\"),\n destination_x: z.number().describe(\"Destination horizontal, 0-1000.\"),\n destination_y: z.number().describe(\"Destination vertical, 0-1000.\"),\n }),\n execute: async ({ x, y, destination_x, destination_y }) => {\n if (!controller.dragAndDrop)\n return errorResult(\"drag_and_drop is not supported by this environment\");\n const from = await px(x, y);\n const to = await px(destination_x, destination_y);\n await controller.dragAndDrop(from.x, from.y, to.x, to.y);\n return ack();\n },\n }),\n );\n\n add(\"go_back\", () =>\n defineLocalTool({\n name: \"go_back\",\n description: \"Navigate to the previous page in history.\",\n parameters: z.object({}),\n execute: async () => {\n if (!controller.goBack) return errorResult(\"go_back is not supported by this environment\");\n await controller.goBack();\n return ack();\n },\n }),\n );\n\n add(\"go_forward\", () =>\n defineLocalTool({\n name: \"go_forward\",\n description: \"Navigate to the next page in history.\",\n parameters: z.object({}),\n execute: async () => {\n if (!controller.goForward)\n return errorResult(\"go_forward is not supported by this environment\");\n await controller.goForward();\n return ack();\n },\n }),\n );\n\n add(\"wait\", () =>\n defineLocalTool({\n name: \"wait\",\n description: \"Pause to let dynamic content load or animations finish.\",\n parameters: z.object({\n seconds: z.number().optional().describe(\"Seconds to wait. Default 1, max 10.\"),\n }),\n execute: async ({ seconds }) => {\n const s = Math.min(Math.max(seconds ?? 1, 0), 10);\n await new Promise((resolve) => setTimeout(resolve, s * 1000));\n return ack(`waited ${s}s`);\n },\n }),\n );\n\n if (includeConfirm) {\n tools.push(\n defineLocalTool({\n name: \"request_confirmation\",\n description:\n \"Ask the human operator to approve a consequential or irreversible action BEFORE performing it (e.g. submitting a form, sending a message, making a purchase, accepting terms, solving a CAPTCHA, logging in). Returns whether you are cleared to proceed.\",\n parameters: z.object({\n reason: z.string().describe(\"What you are about to do and why confirmation is needed.\"),\n }),\n execute: async ({ reason }) => {\n const approved = opts.confirm ? await opts.confirm(reason) : false;\n return JSON.stringify({\n approved,\n ...(approved\n ? { note: \"Operator approved. Proceed with the action, then stop and wait for the next screenshot.\" }\n : { note: \"Operator denied. Do not perform the action; choose a different approach or stop and report back.\" }),\n });\n },\n }),\n );\n }\n\n return tools;\n}\n\nfunction errorResult(message: string): string {\n return JSON.stringify({ status: \"error\", error: message });\n}\n\n// --------------------------------------------------------------- System prompt\n\nexport interface ComputerUseSystemPromptOptions {\n /** Environment label injected into the prompt, e.g. `\"web browser\"`. */\n environment?: string;\n /** Extra task-specific context appended to the standard instructions. */\n extraInstructions?: string;\n /** Whether the `request_confirmation` tool is available (adds safety rules). */\n requestConfirmation?: boolean;\n}\n\n/**\n * Build the system prompt that drives the loop: it teaches the model the\n * screenshot-per-step protocol, the 0-1000 coordinate grid, the one-action-per-turn\n * discipline, when to stop, and the human-in-the-loop safety rules.\n */\nexport function buildComputerUseSystemPrompt(\n opts: ComputerUseSystemPromptOptions = {},\n): string {\n const environment = opts.environment ?? \"web browser\";\n const confirmation = opts.requestConfirmation ?? true;\n\n const lines: string[] = [\n `You are an agent that controls a ${environment} by looking at screenshots and taking UI actions.`,\n \"\",\n \"Protocol:\",\n `- Before every step you receive a screenshot of the current ${environment} as an image attachment. Study it carefully.`,\n \"- Choose EXACTLY ONE action and call the matching tool. Coordinates use a 0-1000 grid (top-left is 0,0; bottom-right is 1000,1000), scaled automatically to the screen.\",\n \"- After the tool runs, STOP and wait. You will be given a new screenshot reflecting the result; only then decide the next action.\",\n \"- Do not chain multiple actions in one turn and do not guess what happened — always rely on the next screenshot.\",\n \"- Scroll to reveal content before concluding something is missing.\",\n \"\",\n \"Finishing:\",\n \"- When the task is complete (or you have gathered enough information to answer), reply with a plain-text final answer and DO NOT call any tool. That ends the session.\",\n \"- If you get stuck or cannot proceed, explain why in plain text without calling a tool.\",\n ];\n\n if (confirmation) {\n lines.push(\n \"\",\n \"Safety — you MUST call `request_confirmation` and wait for approval BEFORE any consequential or irreversible action, including:\",\n \"- Accepting terms of service, privacy policies, cookie banners, or other agreements.\",\n \"- Solving or bypassing CAPTCHAs or other human-verification checks.\",\n \"- Completing a purchase, moving money, or any financial transaction.\",\n \"- Sending an email or message, or posting content.\",\n \"- Logging into an account, or accessing/modifying sensitive personal data.\",\n \"- Downloading, saving, sharing, or transferring files or user data.\",\n \"For these, do all preparatory steps first, then call `request_confirmation` immediately BEFORE the final irreversible click. If denied, do not perform the action.\",\n );\n }\n\n if (opts.extraInstructions) {\n lines.push(\"\", opts.extraInstructions);\n }\n\n return lines.join(\"\\n\");\n}\n\n// --------------------------------------------------------------- Loop driver\n\n/** One action the model invoked on a turn (derived from `local_tool_call` events). */\nexport interface ComputerUseActionCall {\n name: string;\n input: Record<string, unknown>;\n}\n\n/** A single iteration of the computer-use loop. */\nexport interface ComputerUseStep {\n /** 1-based step index. */\n step: number;\n /** The screenshot sent to the model at the start of this step. */\n screenshot: Screenshot;\n /** The full run result for the turn. */\n result: RunResult;\n /** Actions the model invoked this turn (empty when it produced a final answer). */\n actions: ComputerUseActionCall[];\n}\n\nexport interface RunComputerUseOptions {\n /** MANTYX client used to open the session. */\n client: MantyxClient;\n /** The user's goal, sent on the first turn. */\n goal: string;\n /** Drives the actual UI actions and screenshots. */\n controller: BrowserController;\n /** Vision-capable model id (`modelId`). Omit to use the workspace default. */\n model?: string;\n /** Max loop iterations before stopping. Default 20. */\n maxSteps?: number;\n /** Override the generated system prompt entirely. */\n systemPrompt?: string;\n /** Tweaks for the generated system prompt (ignored when `systemPrompt` is set). */\n systemPromptOptions?: ComputerUseSystemPromptOptions;\n /** Actions to omit from the tool surface. */\n excludeActions?: ComputerUseAction[];\n /** Human-in-the-loop gate for `request_confirmation`. Omit to disable confirmations. */\n confirm?: (reason: string) => boolean | Promise<boolean>;\n /** Disable the `request_confirmation` tool entirely. Default false (it is included). */\n disableConfirmation?: boolean;\n /** Provider reasoning strength for the session. */\n reasoningLevel?: ReasoningLevel;\n /** Observability metadata stored on the session. */\n metadata?: Record<string, string>;\n /** Text sent alongside the screenshot on every turn after the first. */\n continueText?: string;\n /** Invoked after each step (await is honored), e.g. for logging. */\n onStep?: (step: ComputerUseStep) => void | Promise<void>;\n /** Streams assistant text deltas. */\n onAssistantDelta?: (delta: string) => void;\n /** Aborts the loop and the in-flight turn. */\n signal?: AbortSignal;\n}\n\nexport interface ComputerUseResult {\n /** The model's final plain-text answer (text of the last turn). */\n finalText: string;\n /** Every step taken, in order. */\n steps: ComputerUseStep[];\n /** The session that ran the loop (already ended). */\n sessionId: string;\n /** Why the loop stopped. */\n stoppedReason: \"completed\" | \"max_steps\";\n}\n\nconst DEFAULT_CONTINUE_TEXT =\n \"Here is the screen after your last action. Continue toward the goal, or give your final answer if the task is done.\";\n\n/** Pull the actions the model invoked this turn from the run's events. */\nexport function extractActions(result: RunResult): ComputerUseActionCall[] {\n const actions: ComputerUseActionCall[] = [];\n for (const ev of result.events as RunEvent[]) {\n if (ev.type === \"local_tool_call\") {\n const e = ev as { name?: string; args?: Record<string, unknown> };\n actions.push({ name: e.name ?? \"\", input: e.args ?? {} });\n }\n }\n return actions;\n}\n\nfunction screenshotExtension(mimeType: string): string {\n if (mimeType.includes(\"png\")) return \"png\";\n if (mimeType.includes(\"webp\")) return \"webp\";\n return \"jpg\";\n}\n\n/**\n * Run a model-agnostic computer-use loop: screenshot → send → one action →\n * repeat, until the model answers in plain text or `maxSteps` is reached. The\n * session is created internally and ended on return.\n *\n * @example\n * const out = await runComputerUse({\n * client,\n * model: \"google/gemini-3-flash\",\n * goal: \"Find the cheapest 2-door smart fridge on the site and report its price.\",\n * controller: playwrightController, // implements BrowserController\n * confirm: async (reason) => askOperator(reason),\n * });\n * console.log(out.finalText);\n */\nexport async function runComputerUse(opts: RunComputerUseOptions): Promise<ComputerUseResult> {\n const maxSteps = opts.maxSteps ?? 20;\n if (maxSteps < 1) throw new Error(\"runComputerUse: maxSteps must be >= 1\");\n\n const requestConfirmation = !opts.disableConfirmation;\n const tools = defineComputerUseTools(opts.controller, {\n ...(opts.excludeActions ? { excludeActions: opts.excludeActions } : {}),\n requestConfirmation,\n ...(opts.confirm ? { confirm: opts.confirm } : {}),\n });\n\n const systemPrompt =\n opts.systemPrompt ??\n buildComputerUseSystemPrompt({\n ...(opts.systemPromptOptions ?? {}),\n requestConfirmation,\n });\n\n const session: AgentSession = await opts.client.createSession({\n systemPrompt,\n ...(opts.model ? { modelId: opts.model } : {}),\n tools,\n ...(opts.reasoningLevel !== undefined ? { reasoningLevel: opts.reasoningLevel } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n\n const steps: ComputerUseStep[] = [];\n let finalText = \"\";\n let stoppedReason: \"completed\" | \"max_steps\" = \"max_steps\";\n\n try {\n for (let i = 0; i < maxSteps; i++) {\n const screenshot = await opts.controller.screenshot();\n const filename =\n screenshot.filename ?? `screenshot-${i + 1}.${screenshotExtension(screenshot.mimeType)}`;\n const attachment = inputFileAttachment({\n mimeType: screenshot.mimeType,\n filename,\n data: screenshot.data,\n });\n\n const turnText = i === 0 ? opts.goal : opts.continueText ?? DEFAULT_CONTINUE_TEXT;\n const result = await session.send(turnText, {\n attachments: [attachment],\n ...(opts.onAssistantDelta ? { onAssistantDelta: opts.onAssistantDelta } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n\n const actions = extractActions(result);\n const step: ComputerUseStep = { step: i + 1, screenshot, result, actions };\n steps.push(step);\n finalText = result.text;\n\n if (opts.onStep) await opts.onStep(step);\n\n if (actions.length === 0) {\n stoppedReason = \"completed\";\n break;\n }\n }\n\n return { finalText, steps, sessionId: session.id, stoppedReason };\n } finally {\n await session.end().catch(() => {\n // Best-effort cleanup; surfacing an end() failure would mask the real result.\n });\n }\n}\n","/**\n * Release version — synced from repo root VERSION (`npm run sync-version`).\n */\nexport const SDK_VERSION = \"0.23.0\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,IAAM,yBAAyB;AAG/B,IAAM,0BAA0B;AAchC,IAAM,mBAAN,cAA+B,YAAY;AAAA,EACvC;AAAA,EACA;AAAA,EAET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C,CAAC;AAED,YAAM,UAAU,eAAe,MAAM;AACrC,YAAM,OAAwB,EAAE,MAAM,IAAI,GAAG,YAAY,QAAQ,QAAQ;AACzE,YAAM,KAAK,IAAI;AACf,kBAAY,OAAO;AAEnB,UAAI,KAAK,OAAQ,OAAM,KAAK,OAAO,IAAI;AAEvC,UAAI,QAAQ,WAAW,GAAG;AACxB,wBAAgB;AAChB;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,WAAW,OAAO,WAAW,QAAQ,IAAI,cAAc;AAAA,EAClE,UAAE;AACA,UAAM,QAAQ,IAAI,EAAE,MAAM,MAAM;AAAA,IAEhC,CAAC;AAAA,EACH;AACF;;;ACroBO,IAAM,cAAc;","names":[]}
package/dist/version.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * Release version — synced from repo root VERSION (`npm run sync-version`).
3
3
  */
4
- export declare const SDK_VERSION = "0.22.1";
4
+ export declare const SDK_VERSION = "0.23.0";
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -993,12 +993,17 @@ the verdict by the time the event arrives.
993
993
 
994
994
  `plan` turns on the in-product **task plan** — the same live-checklist engine
995
995
  that powers MANTYX chat / Hive Mind. It is **opt-in** on API/ephemeral runs,
996
- same as `supervisor` (§4.8), because both features add extra LLM calls.
996
+ same as `supervisor` (§4.8). Active plans are owned by the executing agent
997
+ through the host `update_task_plan` tool; there is no pre-flight classifier or
998
+ separate tracker LLM call.
997
999
 
998
1000
  ```jsonc
999
- "plan": true // auto: classify, emit a task_plan event, track during the run
1001
+ "plan": true // compatibility alias for "auto"
1002
+ "plan": "auto" // agent decides during its normal first turn
1003
+ "plan": "required" // agent must initialize a plan before substantive tools
1000
1004
 
1001
1005
  "plan": { // caller-provided checklist — skips the classifier
1006
+ "mode": "required",
1002
1007
  "brief": "Migrate the billing tables and backfill", // optional
1003
1008
  "steps": ["Snapshot current schema", "Apply migration", "Backfill rows", "Verify counts"]
1004
1009
  }
@@ -1012,19 +1017,22 @@ same as `supervisor` (§4.8), because both features add extra LLM calls.
1012
1017
  | Form | Behavior |
1013
1018
  | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1014
1019
  | omitted / `false` | No planning. Default. |
1015
- | `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. |
1016
- | `{ steps, brief? }` | Caller-provided checklist used verbatim — **skips** the classifier (and its `MIN_STEPS` gate). Injected + tracked like the auto case. |
1020
+ | `true` / `"auto"` | Exposes `update_task_plan`; the executing agent decides during its normal first turn whether multi-step tracking is useful. No separate planning LLM call. |
1021
+ | `"required"` | Requires `update_task_plan` before substantive tools and rejects premature final answers while required steps remain unfinished (bounded continuation guard). |
1022
+ | `{ mode?, steps, brief? }` | Seeds an authoritative checklist. `mode` defaults to `auto`; use `required` to enforce initialization/execution. |
1017
1023
  | `{ 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). |
1018
1024
 
1019
1025
  | Field | Type | Required | Notes |
1020
1026
  | ---------- | -------- | -------- | ---------------------------------------------------------------------------------------------------- |
1021
1027
  | `planOnly` | boolean | no | When `true`, the run stops after producing the plan. |
1028
+ | `mode` | string | no | `off`, `auto`, or `required`. Defaults to `auto`. |
1022
1029
  | `brief` | string | no | One-line objective for a caller-provided plan. Clamped server-side. |
1023
1030
  | `steps` | string[] | no | Caller-provided checklist titles. Empty/omitted ⇒ auto-classify. Count + per-step length clamped server-side. |
1024
1031
 
1025
1032
  Plan-only runs do **not** append an assistant turn to a session (the plan is
1026
- not the answer). Planner LLM usage (classifier + per-run tracker) is metered
1027
- under the `task_planning` usage surface.
1033
+ not the answer). When no steps are supplied, this compatibility-only path
1034
+ still uses the one-shot planner and meters it under `task_planning`; executed
1035
+ runs do not use the classifier/tracker path.
1028
1036
 
1029
1037
  **Inheritance for sessions.**
1030
1038
 
@@ -1293,10 +1301,37 @@ data: <utf-8 JSON>
1293
1301
  // mid-turn reasoning review (phase: "reasoning") — fired while the agent was still thinking
1294
1302
  { "seq": 6, "type": "supervisor", "data": { "action": "redirect", "phase": "reasoning", "reason": "Overthinking a simple case.", "redirect": "Commit and answer.", "llmCalls": 4 } }
1295
1303
 
1296
- // in-product task plan (see §4.9). Emitted only when the run carries a `plan` spec
1297
- // field: once after classify / caller-supplied plan, then on each tracker advance.
1298
- // Non-terminal — render as a live checklist. status ∈ "pending" | "in_progress" | "done".
1299
- { "seq": 4, "type": "task_plan", "data": { "brief": "Compare Q3 vs Q4 revenue.", "steps": [ { "title": "Pull revenue", "status": "in_progress" }, { "title": "Compute deltas", "status": "pending" } ] } }
1304
+ // Agent-owned task plan (see §4.9). Every transition carries the canonical
1305
+ // post-transition snapshot. `revision` is monotonic per plan; run-event `seq`
1306
+ // orders multiple transitions in one accepted update. `brief` and `steps`
1307
+ // remain mirrored at the top level for pre-v2 SDK clients.
1308
+ // status ∈ pending | in_progress | done | blocked | skipped.
1309
+ { "seq": 4, "type": "task_plan", "data": {
1310
+ "v": 2,
1311
+ "planId": "3b5f...",
1312
+ "revision": 2,
1313
+ "mode": "required",
1314
+ "source": "agent",
1315
+ "transition": { "kind": "step_completed", "stepId": "step-1" },
1316
+ "transitionIndex": 0,
1317
+ "transitionCount": 2,
1318
+ "brief": "Compare Q3 vs Q4 revenue.",
1319
+ "steps": [
1320
+ { "id": "step-1", "title": "Pull revenue", "status": "done" },
1321
+ { "id": "step-2", "title": "Compute deltas", "status": "in_progress" }
1322
+ ],
1323
+ "plan": {
1324
+ "v": 2,
1325
+ "planId": "3b5f...",
1326
+ "revision": 2,
1327
+ "mode": "required",
1328
+ "brief": "Compare Q3 vs Q4 revenue.",
1329
+ "steps": [
1330
+ { "id": "step-1", "title": "Pull revenue", "status": "done" },
1331
+ { "id": "step-2", "title": "Compute deltas", "status": "in_progress" }
1332
+ ]
1333
+ }
1334
+ } }
1300
1335
 
1301
1336
  // terminal event
1302
1337
  // Every terminal `result` event also carries `tokens`, `turns`, and `model`
@@ -1604,18 +1639,19 @@ A reference SDK should:
1604
1639
  defaults; passing `loopDetection: false` opts out; passing `toolBudgets: {}`
1605
1640
  clears the defaults. `supervisor` and `plan` are opt-in — omitting them
1606
1641
  keeps both off; pass `supervisor: true` / `{}` / `{ interval?, modelId? }`
1607
- or `plan: true` / `{ … }` to enable.
1642
+ or `plan: "auto"` / `"required"` / `{ … }` to enable.
1608
1643
  - Treat `loop_detected`, `tool_budget_exceeded`, and `supervisor` SSE
1609
1644
  events as observability-only — the server already substituted synthetic
1610
1645
  tool-results / steering nudges / supervisor verdicts where applicable, so
1611
1646
  the SDK's job is just to surface the event to the caller (status banner,
1612
1647
  log line, telemetry). Do **not** abort the run on these events; the run
1613
1648
  continues through `result` / `error` / `cancelled` as usual.
1614
- - Accept `plan` from the caller (`true` | `{ steps?, brief?, planOnly? }` |
1615
- `false`) and pass it through unchanged (see §4.9). It is opt-in — omitting
1616
- it (or `false`) means no planning. Render `task_plan` events as a live,
1617
- non-terminal checklist; for `planOnly` runs read the final checklist from
1618
- the terminal `result.data.plan`.
1649
+ - Accept `plan` from the caller (`off` / `auto` / `required`, the boolean
1650
+ compatibility aliases, or `{ mode?, steps?, brief?, planOnly? }`) and pass
1651
+ it through unchanged (see §4.9). Render `task_plan.data.plan` as the
1652
+ canonical checklist. Apply snapshots idempotently by `planId` + `revision`
1653
+ and use run-event `seq` to order multiple transitions in one revision.
1654
+ For `planOnly` runs read the final checklist from `result.data.plan`.
1619
1655
  - On terminal `result`, resolve the call. On `error` subtype, throw.
1620
1656
  4. Re-emit assistant deltas/events as a stream/iterator for callers who care
1621
1657
  about live output.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mantyx/sdk",
3
- "version": "0.22.1",
3
+ "version": "0.23.0",
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",