@mantyx/sdk 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, e as AttachmentMetadata, C as CancelledEvent, f as ConversationMessage, D as DEFAULT_BASE_URL, g as DEFAULT_OAUTH_BASE_URL, h as DEFAULT_REFRESH_SKEW_MS, i as DefineLocalA2AOptions, j as DefineLocalMcpOptions, k as DefineLocalToolOptions, E as ErrorEvent, I as InputFileAttachment, l as InputFileAttachmentMetadata, m as InputFileUrlAttachment, n as InputFileUrlAttachmentMetadata, L as LocalA2ATool, o as LocalHandlers, p as LocalMcpHttpTransport, q as LocalMcpServer, r as LocalMcpStdioTransport, s as LocalTool, t as LocalToolCallEvent, u as LocalToolOutput, v as LocalToolResult, w as LocalToolResultInEvent, x as LoopDetectedEvent, y as LoopDetection, z as MantyxA2AOptions, B as MantyxAuthError, M as MantyxClient, F as MantyxClientOptions, G as MantyxError, H as MantyxMcpOptions, J as MantyxNetworkError, K as MantyxOAuthClient, N as MantyxOAuthClientOptions, P as MantyxOAuthError, Q as MantyxParseError, S as MantyxPluginToolRef, U as MantyxRunError, V as MantyxRunErrorInit, W as MantyxRunErrorModel, X as MantyxRunErrorTokens, Y as MantyxScopeError, Z as MantyxToolError, _ as MantyxToolRef, $ as McpToolRef, a0 as MessageAttachment, a1 as ModelCatalog, a2 as ModelInfo, a3 as OAuthToken, O as OutputSchema, a4 as OutputSchemaValue, a5 as PlanOptions, a6 as PlanSpec, R as ReasoningLevel, a7 as ReasoningTrigger, a8 as RefreshOptions, a9 as RefreshTokenSourceOptions, aa as ResultEvent, ab as RevokeOptions, ac as RunEvent, ad as RunEventBase, ae as RunFeedbackInput, af as RunFeedbackResult, ag as RunFeedbackVerdict, ah as RunModelInfo, ai as RunResult, aj as RunSpec, ak as RunTokenUsage, al as ServerToolResultEvent, am as SessionInfo, an as SessionListResult, ao as SessionSpec, ap as SessionSummary, aq as Supervisor, ar as SupervisorAction, as as SupervisorEvent, at as SupervisorPhase, au as TaskPlan, av as TaskPlanEvent, aw as TaskPlanStep, ax as TaskPlanStepStatus, ay as ThinkingDeltaEvent, az as TokenRequestReason, aA as TokenSource, aB as ToolBudget, aC as ToolBudgetExceededEvent, aD as ToolBudgets, T as ToolRef, aE as ToolResultFile, aF as UserMessageEvent, aG as ZodLikeObject, aH as defineLocalA2A, aI as defineLocalMcp, aJ as defineLocalTool, aK as inputFileAttachment, aL as inputFileUrlAttachment, aM as isLocalA2ATool, aN as isLocalMcpServer, aO as isLocalTool, aP as mantyxA2A, aQ as mantyxMcp, aR as mantyxPluginTool, aS as mantyxTool, aT as parseRunOutput, aU as planOnly } from './client-CLT46vp5.cjs';
2
- export { B as BrowserController, C as COMPUTER_USE_ACTIONS, a as ComputerUseAction, b as ComputerUseActionCall, c as ComputerUseResult, d as ComputerUseStep, e as ComputerUseSystemPromptOptions, D as DefineComputerUseToolsOptions, R as RunComputerUseOptions, S as Screenshot, f as ScrollDirection, T as TypeTextOptions, V as Viewport, g as buildComputerUseSystemPrompt, h as defineComputerUseTools, i as denormalizeCoordinate, j as extractActions, r as runComputerUse } from './computer-use-CEiw-nJw.cjs';
1
+ export { A as A2AToolRef, a as AgentEvalOverrides, b as AgentSession, c as AgentSpecBase, d as AssistantDeltaEvent, e as AssistantMessageEvent, f as AttachmentMetadata, C as CancelledEvent, g as ConversationMessage, h as CreateEvalRunRequest, D as DEFAULT_BASE_URL, i as DEFAULT_OAUTH_BASE_URL, j as DEFAULT_REFRESH_SKEW_MS, k as DefineLocalA2AOptions, l as DefineLocalMcpOptions, m as DefineLocalToolOptions, E as ErrorEvent, n as EvalCase, o as EvalCaseResult, p as EvalDatasetDetail, q as EvalDatasetList, r as EvalDatasetSummary, s as EvalRunAccepted, t as EvalRunCompare, u as EvalRunCompareCase, v as EvalRunCompareSide, w as EvalRunDetail, x as EvalRunEvent, y as EvalRunList, z as EvalRunStatus, B as EvalRunSummary, I as InlineEvalCaseSpec, F as InlineEvalDatasetSpec, G as InputFileAttachment, H as InputFileAttachmentMetadata, J as InputFileUrlAttachment, K as InputFileUrlAttachmentMetadata, L as ListEvalRunsOptions, N as LocalA2ATool, P as LocalHandlers, Q as LocalMcpHttpTransport, S as LocalMcpServer, U as LocalMcpStdioTransport, V as LocalTool, W as LocalToolCallEvent, X as LocalToolOutput, Y as LocalToolResult, Z as LocalToolResultInEvent, _ as LoopDetectedEvent, $ as LoopDetection, a0 as MantyxA2AOptions, a1 as MantyxAuthError, M as MantyxClient, a2 as MantyxClientOptions, a3 as MantyxError, a4 as MantyxMcpOptions, a5 as MantyxNetworkError, a6 as MantyxOAuthClient, a7 as MantyxOAuthClientOptions, a8 as MantyxOAuthError, a9 as MantyxParseError, aa as MantyxPluginToolRef, ab as MantyxRunError, ac as MantyxRunErrorInit, ad as MantyxRunErrorModel, ae as MantyxRunErrorTokens, af as MantyxScopeError, ag as MantyxToolError, ah as MantyxToolRef, ai as McpToolRef, aj as MessageAttachment, ak as ModelCatalog, al as ModelInfo, am as OAuthToken, O as OutputSchema, an as OutputSchemaValue, ao as PlanOptions, ap as PlanSpec, R as ReasoningLevel, aq as ReasoningTrigger, ar as RefreshOptions, as as RefreshTokenSourceOptions, at as ResultEvent, au as RevokeOptions, av as RunEvalOptions, aw as RunEvent, ax as RunEventBase, ay as RunFeedbackInput, az as RunFeedbackResult, aA as RunFeedbackVerdict, aB as RunModelInfo, aC as RunResult, aD as RunSpec, aE as RunTokenUsage, aF as ServerToolResultEvent, aG as SessionInfo, aH as SessionListResult, aI as SessionSpec, aJ as SessionSummary, aK as Supervisor, aL as SupervisorAction, aM as SupervisorEvent, aN as SupervisorPhase, aO as TaskPlan, aP as TaskPlanEvent, aQ as TaskPlanStep, aR as TaskPlanStepStatus, aS as ThinkingDeltaEvent, aT as TokenRequestReason, aU as TokenSource, aV as ToolBudget, aW as ToolBudgetExceededEvent, aX as ToolBudgets, T as ToolRef, aY as ToolResultFile, aZ as UserMessageEvent, a_ as ZodLikeObject, a$ as defineLocalA2A, b0 as defineLocalMcp, b1 as defineLocalTool, b2 as inputFileAttachment, b3 as inputFileUrlAttachment, b4 as isLocalA2ATool, b5 as isLocalMcpServer, b6 as isLocalTool, b7 as mantyxA2A, b8 as mantyxMcp, b9 as mantyxPluginTool, ba as mantyxTool, bb as parseRunOutput, bc as planOnly } from './client-D4-MQANp.cjs';
2
+ export { B as BrowserController, C as COMPUTER_USE_ACTIONS, a as ComputerUseAction, b as ComputerUseActionCall, c as ComputerUseResult, d as ComputerUseStep, e as ComputerUseSystemPromptOptions, D as DefineComputerUseToolsOptions, R as RunComputerUseOptions, S as Screenshot, f as ScrollDirection, T as TypeTextOptions, V as Viewport, g as buildComputerUseSystemPrompt, h as defineComputerUseTools, i as denormalizeCoordinate, j as extractActions, r as runComputerUse } from './computer-use-D4hBi1Tm.cjs';
3
3
  import { z } from 'zod';
4
4
 
5
5
  /**
@@ -56,6 +56,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
56
56
  /**
57
57
  * Release version — synced from repo root VERSION (`npm run sync-version`).
58
58
  */
59
- declare const SDK_VERSION = "0.18.0";
59
+ declare const SDK_VERSION = "0.20.0";
60
60
 
61
61
  export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { A as A2AToolRef, a as AgentSession, b as AgentSpecBase, c as AssistantDeltaEvent, d as AssistantMessageEvent, e as AttachmentMetadata, C as CancelledEvent, f as ConversationMessage, D as DEFAULT_BASE_URL, g as DEFAULT_OAUTH_BASE_URL, h as DEFAULT_REFRESH_SKEW_MS, i as DefineLocalA2AOptions, j as DefineLocalMcpOptions, k as DefineLocalToolOptions, E as ErrorEvent, I as InputFileAttachment, l as InputFileAttachmentMetadata, m as InputFileUrlAttachment, n as InputFileUrlAttachmentMetadata, L as LocalA2ATool, o as LocalHandlers, p as LocalMcpHttpTransport, q as LocalMcpServer, r as LocalMcpStdioTransport, s as LocalTool, t as LocalToolCallEvent, u as LocalToolOutput, v as LocalToolResult, w as LocalToolResultInEvent, x as LoopDetectedEvent, y as LoopDetection, z as MantyxA2AOptions, B as MantyxAuthError, M as MantyxClient, F as MantyxClientOptions, G as MantyxError, H as MantyxMcpOptions, J as MantyxNetworkError, K as MantyxOAuthClient, N as MantyxOAuthClientOptions, P as MantyxOAuthError, Q as MantyxParseError, S as MantyxPluginToolRef, U as MantyxRunError, V as MantyxRunErrorInit, W as MantyxRunErrorModel, X as MantyxRunErrorTokens, Y as MantyxScopeError, Z as MantyxToolError, _ as MantyxToolRef, $ as McpToolRef, a0 as MessageAttachment, a1 as ModelCatalog, a2 as ModelInfo, a3 as OAuthToken, O as OutputSchema, a4 as OutputSchemaValue, a5 as PlanOptions, a6 as PlanSpec, R as ReasoningLevel, a7 as ReasoningTrigger, a8 as RefreshOptions, a9 as RefreshTokenSourceOptions, aa as ResultEvent, ab as RevokeOptions, ac as RunEvent, ad as RunEventBase, ae as RunFeedbackInput, af as RunFeedbackResult, ag as RunFeedbackVerdict, ah as RunModelInfo, ai as RunResult, aj as RunSpec, ak as RunTokenUsage, al as ServerToolResultEvent, am as SessionInfo, an as SessionListResult, ao as SessionSpec, ap as SessionSummary, aq as Supervisor, ar as SupervisorAction, as as SupervisorEvent, at as SupervisorPhase, au as TaskPlan, av as TaskPlanEvent, aw as TaskPlanStep, ax as TaskPlanStepStatus, ay as ThinkingDeltaEvent, az as TokenRequestReason, aA as TokenSource, aB as ToolBudget, aC as ToolBudgetExceededEvent, aD as ToolBudgets, T as ToolRef, aE as ToolResultFile, aF as UserMessageEvent, aG as ZodLikeObject, aH as defineLocalA2A, aI as defineLocalMcp, aJ as defineLocalTool, aK as inputFileAttachment, aL as inputFileUrlAttachment, aM as isLocalA2ATool, aN as isLocalMcpServer, aO as isLocalTool, aP as mantyxA2A, aQ as mantyxMcp, aR as mantyxPluginTool, aS as mantyxTool, aT as parseRunOutput, aU as planOnly } from './client-CLT46vp5.js';
2
- export { B as BrowserController, C as COMPUTER_USE_ACTIONS, a as ComputerUseAction, b as ComputerUseActionCall, c as ComputerUseResult, d as ComputerUseStep, e as ComputerUseSystemPromptOptions, D as DefineComputerUseToolsOptions, R as RunComputerUseOptions, S as Screenshot, f as ScrollDirection, T as TypeTextOptions, V as Viewport, g as buildComputerUseSystemPrompt, h as defineComputerUseTools, i as denormalizeCoordinate, j as extractActions, r as runComputerUse } from './computer-use-CRcsRq8T.js';
1
+ export { A as A2AToolRef, a as AgentEvalOverrides, b as AgentSession, c as AgentSpecBase, d as AssistantDeltaEvent, e as AssistantMessageEvent, f as AttachmentMetadata, C as CancelledEvent, g as ConversationMessage, h as CreateEvalRunRequest, D as DEFAULT_BASE_URL, i as DEFAULT_OAUTH_BASE_URL, j as DEFAULT_REFRESH_SKEW_MS, k as DefineLocalA2AOptions, l as DefineLocalMcpOptions, m as DefineLocalToolOptions, E as ErrorEvent, n as EvalCase, o as EvalCaseResult, p as EvalDatasetDetail, q as EvalDatasetList, r as EvalDatasetSummary, s as EvalRunAccepted, t as EvalRunCompare, u as EvalRunCompareCase, v as EvalRunCompareSide, w as EvalRunDetail, x as EvalRunEvent, y as EvalRunList, z as EvalRunStatus, B as EvalRunSummary, I as InlineEvalCaseSpec, F as InlineEvalDatasetSpec, G as InputFileAttachment, H as InputFileAttachmentMetadata, J as InputFileUrlAttachment, K as InputFileUrlAttachmentMetadata, L as ListEvalRunsOptions, N as LocalA2ATool, P as LocalHandlers, Q as LocalMcpHttpTransport, S as LocalMcpServer, U as LocalMcpStdioTransport, V as LocalTool, W as LocalToolCallEvent, X as LocalToolOutput, Y as LocalToolResult, Z as LocalToolResultInEvent, _ as LoopDetectedEvent, $ as LoopDetection, a0 as MantyxA2AOptions, a1 as MantyxAuthError, M as MantyxClient, a2 as MantyxClientOptions, a3 as MantyxError, a4 as MantyxMcpOptions, a5 as MantyxNetworkError, a6 as MantyxOAuthClient, a7 as MantyxOAuthClientOptions, a8 as MantyxOAuthError, a9 as MantyxParseError, aa as MantyxPluginToolRef, ab as MantyxRunError, ac as MantyxRunErrorInit, ad as MantyxRunErrorModel, ae as MantyxRunErrorTokens, af as MantyxScopeError, ag as MantyxToolError, ah as MantyxToolRef, ai as McpToolRef, aj as MessageAttachment, ak as ModelCatalog, al as ModelInfo, am as OAuthToken, O as OutputSchema, an as OutputSchemaValue, ao as PlanOptions, ap as PlanSpec, R as ReasoningLevel, aq as ReasoningTrigger, ar as RefreshOptions, as as RefreshTokenSourceOptions, at as ResultEvent, au as RevokeOptions, av as RunEvalOptions, aw as RunEvent, ax as RunEventBase, ay as RunFeedbackInput, az as RunFeedbackResult, aA as RunFeedbackVerdict, aB as RunModelInfo, aC as RunResult, aD as RunSpec, aE as RunTokenUsage, aF as ServerToolResultEvent, aG as SessionInfo, aH as SessionListResult, aI as SessionSpec, aJ as SessionSummary, aK as Supervisor, aL as SupervisorAction, aM as SupervisorEvent, aN as SupervisorPhase, aO as TaskPlan, aP as TaskPlanEvent, aQ as TaskPlanStep, aR as TaskPlanStepStatus, aS as ThinkingDeltaEvent, aT as TokenRequestReason, aU as TokenSource, aV as ToolBudget, aW as ToolBudgetExceededEvent, aX as ToolBudgets, T as ToolRef, aY as ToolResultFile, aZ as UserMessageEvent, a_ as ZodLikeObject, a$ as defineLocalA2A, b0 as defineLocalMcp, b1 as defineLocalTool, b2 as inputFileAttachment, b3 as inputFileUrlAttachment, b4 as isLocalA2ATool, b5 as isLocalMcpServer, b6 as isLocalTool, b7 as mantyxA2A, b8 as mantyxMcp, b9 as mantyxPluginTool, ba as mantyxTool, bb as parseRunOutput, bc as planOnly } from './client-D4-MQANp.js';
2
+ export { B as BrowserController, C as COMPUTER_USE_ACTIONS, a as ComputerUseAction, b as ComputerUseActionCall, c as ComputerUseResult, d as ComputerUseStep, e as ComputerUseSystemPromptOptions, D as DefineComputerUseToolsOptions, R as RunComputerUseOptions, S as Screenshot, f as ScrollDirection, T as TypeTextOptions, V as Viewport, g as buildComputerUseSystemPrompt, h as defineComputerUseTools, i as denormalizeCoordinate, j as extractActions, r as runComputerUse } from './computer-use-DUFbgsSU.js';
3
3
  import { z } from 'zod';
4
4
 
5
5
  /**
@@ -56,6 +56,6 @@ declare function readSseStream(body: ReadableStream<Uint8Array> | null, opts?: S
56
56
  /**
57
57
  * Release version — synced from repo root VERSION (`npm run sync-version`).
58
58
  */
59
- declare const SDK_VERSION = "0.18.0";
59
+ declare const SDK_VERSION = "0.20.0";
60
60
 
61
61
  export { SDK_VERSION, type SseEvent, type SseStreamOptions, readSseStream, toToolParametersWire, zodToJsonSchema };
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  readSseStream,
27
27
  toToolParametersWire,
28
28
  zodToJsonSchema
29
- } from "./chunk-JRENMLOL.js";
29
+ } from "./chunk-ZOFQ5AN6.js";
30
30
 
31
31
  // src/oauth.ts
32
32
  var DEFAULT_OAUTH_BASE_URL = "https://app.mantyx.io";
@@ -602,7 +602,7 @@ async function runComputerUse(opts) {
602
602
  }
603
603
 
604
604
  // src/version.ts
605
- var SDK_VERSION = "0.18.0";
605
+ var SDK_VERSION = "0.20.0";
606
606
  export {
607
607
  AgentSession,
608
608
  COMPUTER_USE_ACTIONS,
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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Aa,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.20.0\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,IAAM,yBAAyB;AAG/B,IAAM,0BAA0B;AAchC,IAAM,mBAAN,cAA+B,YAAY;AAAA,EACvC;AAAA,EACA;AAAA,EAET,YACE,YACA,uBACA,QACA;AACA,UAAM,UAAU,wBACZ,SAAS,UAAU,KAAK,qBAAqB,KAC7C,SAAS,UAAU;AACvB,UAAM,SAAS,EAAE,M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K,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,6 +1,6 @@
1
1
  import { Page } from 'playwright';
2
- import { B as BrowserController, V as Viewport, S as Screenshot, T as TypeTextOptions, f as ScrollDirection } from './computer-use-CEiw-nJw.cjs';
3
- import './client-CLT46vp5.cjs';
2
+ import { B as BrowserController, V as Viewport, S as Screenshot, T as TypeTextOptions, f as ScrollDirection } from './computer-use-D4hBi1Tm.cjs';
3
+ import './client-D4-MQANp.cjs';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  import { Page } from 'playwright';
2
- import { B as BrowserController, V as Viewport, S as Screenshot, T as TypeTextOptions, f as ScrollDirection } from './computer-use-CRcsRq8T.js';
3
- import './client-CLT46vp5.js';
2
+ import { B as BrowserController, V as Viewport, S as Screenshot, T as TypeTextOptions, f as ScrollDirection } from './computer-use-DUFbgsSU.js';
3
+ import './client-D4-MQANp.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -28,7 +28,7 @@ array:
28
28
  | --------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
29
  | `mantyx` | server | A workspace `Tool` row referenced by id (HTTP / Code / Plugin). |
30
30
  | `mantyx_plugin` | server | A platform plugin tool referenced by name. |
31
- | `local` | client | A custom tool defined and executed in the SDK's process. Carries `parameters` (input JSON Schema) plus optional `outputSchema` (return-value JSON Schema), `longRunning`, and `readOnly` (parallel-batch) flags — see §4.1.1. |
31
+ | `local` | client | A custom tool defined and executed in the SDK's process. Carries `parameters` (input JSON Schema) plus optional `outputSchema` (return-value JSON Schema), `longRunning`, `readOnly` (parallel-batch), and `retain` (cross-turn replay) flags — see §4.1.1. |
32
32
  | `a2a` | server | A _remote_ Agent2Agent peer MANTYX can reach; invoked via `message/send` and the reply is surfaced as the tool result. |
33
33
  | `a2a_local` | client | An A2A peer MANTYX **cannot** reach. SDK resolves the [Agent Card](https://google.github.io/A2A/specification/#agent-card) locally and ships it inline; MANTYX uses it for the model description and routes calls back to the SDK over SSE. |
34
34
  | `mcp` | server | A _remote_ MCP server (Streamable HTTP). At run start MANTYX lists the catalog and exposes every tool as `<server>_<tool>` (subject to `toolFilter`). |
@@ -283,6 +283,7 @@ The agent spec is the body shape used by `POST /agent-runs` and `POST
283
283
  },
284
284
  "longRunning": false, // optional — default false
285
285
  "readOnly": false, // optional — default false; true ⇒ may run in parallel with other reads
286
+ "retain": false, // optional — default false; true ⇒ result replayed on later session turns
286
287
  },
287
288
  {
288
289
  "kind": "a2a",
@@ -479,13 +480,15 @@ for the SDK to POST a tool-result.
479
480
  | `outputSchema` | no | JSON Schema for the structured value the tool returns. When present, forwarded to providers that accept per-tool response schemas (Gemini's `responseJsonSchema` on the FunctionDeclaration); other engines surface it through the description and rely on host-side validation. Helps the model emit follow-up arguments that round-trip cleanly. Must be an object schema; non-object roots are dropped server-side. |
480
481
  | `longRunning` | no | When `true`, MANTYX appends a stable hint to the model-facing description so every provider treats the tool as long-running:<br>_"NOTE: This is a long-running operation. Do not call this tool again if it has already returned an intermediate or pending status."_<br>Useful for tools that return `pending` and rely on SDK-side polling — without the hint the model routinely fires repeat calls and burns turns. Pure declarative — MANTYX does not change scheduling. |
481
482
  | `readOnly` | no | When `true`, the tool may run **in parallel** with other read-only tools the model emits in the same turn — MANTYX publishes every such `local_tool_call` concurrently and resolves them together, instead of one-at-a-time in model-emit order. Set this only for side-effect-free tools whose results don't depend on each other, and make sure your SDK can service several outstanding `local_tool_call` events at once (each carries its own `toolUseId`; post a tool-result per id in any order). Mutating tools (the default, `false`) stay strictly sequential. |
483
+ | `retain` | no | When `true`, the tool's result is **persisted with the session and replayed to the model on later turns** of the same session — reconstructed as a `tool_use` + `tool_result` pair in its original place in the transcript. Ordinary tool results only live for the current run (session history keeps user/assistant text only); a retained result survives so a follow-up turn can reference a value it can no longer recompute (a freshly minted id, a one-shot lookup, etc.). Only meaningful for **session-scoped** runs. Keep outputs small — they are stored verbatim (text only; file parts dropped) and capped (~8 KB). Defaults to `false`. |
482
484
 
483
- The `outputSchema`, `longRunning`, and `readOnly` fields are **additive**
484
- since wire protocol v1: SDKs that don't ship them keep working unchanged.
485
- Providers without per-tool response-schema support (OpenAI, Anthropic,
486
- Bedrock, Grok) accept the new fields silently — the schema is treated as a
487
- description hint and host-side validation still runs. `readOnly` defaults to
488
- `false`, so omitting it preserves the original sequential behavior.
485
+ The `outputSchema`, `longRunning`, `readOnly`, and `retain` fields are
486
+ **additive** since wire protocol v1: SDKs that don't ship them keep working
487
+ unchanged. Providers without per-tool response-schema support (OpenAI,
488
+ Anthropic, Bedrock, Grok) accept the new fields silently — the schema is
489
+ treated as a description hint and host-side validation still runs. `readOnly`
490
+ and `retain` both default to `false`, so omitting them preserves the original
491
+ behavior.
489
492
 
490
493
  ### 4.2 A2A tool refs
491
494
 
@@ -1256,6 +1259,10 @@ data: <utf-8 JSON>
1256
1259
  { "seq": 4, "type": "tool_call", "data": { "toolUseId": "...", "name": "...", "input": {...} } }
1257
1260
  { "seq": 5, "type": "tool_result", "data": { "toolUseId": "...", "name": "...", "ok": true, "summary": "..." } }
1258
1261
 
1262
+ // files a server-resolved tool produced (observability; precedes the tool_result above and shares `name`).
1263
+ // `storageKey` → fetch via the admin download route; inline base64 `data` (dev fallback) is redacted from the stream.
1264
+ { "seq": 5, "type": "tool_files", "data": { "name": "render_chart", "files": [ { "filename": "chart.png", "mimeType": "image/png", "sizeBytes": 20480, "storageKey": "chat-attachments/<tenant>/tool-results/<tool>/<uuid>.png" } ] } }
1265
+
1259
1266
  // LOCAL tool call — SDK MUST POST a tool-result for the same toolUseId.
1260
1267
  // `kind` carries the discriminator so the SDK can dispatch to the right
1261
1268
  // local handler (generic registry, A2A client, or MCP client). Older SDKs
@@ -1264,7 +1271,9 @@ data: <utf-8 JSON>
1264
1271
  { "seq": 6, "type": "local_tool_call", "data": { "toolUseId": "tu_y", "name": "intranet_hr_agent", "args": { "message": "When does PTO reset?" }, "kind": "a2a_local", "agentCard": { "name": "Acme HR", "url": "https://hr.intranet.acme/a2a", "skills": [ { "id": "pto_lookup", "name": "PTO lookup" } ] } } }
1265
1272
  { "seq": 6, "type": "local_tool_call", "data": { "toolUseId": "tu_z", "name": "fs_read_file", "args": { "path": "/etc/hosts" }, "kind": "mcp_local", "mcpServer": "fs", "mcpToolName": "fs_read_file", "mcpServerInfo": { "name": "mcp-server-filesystem", "version": "0.4.1" } } }
1266
1273
 
1267
- // echo of the SDK's POSTed tool-result, persisted for replay
1274
+ // echo of the SDK's POSTed tool-result, persisted for replay. Any `files` carry only
1275
+ // metadata on the wire — `{ filename, mimeType, sizeBytes }` — with base64 `data` redacted
1276
+ // (bytes are served on demand by the admin download route).
1268
1277
  { "seq": 7, "type": "local_tool_result_in", "data": { "toolUseId": "tu_x", "output": "127.0.0.1 ..." } }
1269
1278
 
1270
1279
  // loop-detection guard fired (see §4.6). Soft nudge: hardCutoff=false. Hard cutoff: hardCutoff=true.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mantyx/sdk",
3
- "version": "0.18.0",
3
+ "version": "0.20.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",