Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cyclops-cs): add command help skills (#7174)

r33drichardsc684305abdfc
diff --git a/libs/fleet/agent.test.ts b/libs/fleet/agent.test.ts
index ddd464e04f..65f5edfb27 100644
--- a/libs/fleet/agent.test.ts
+++ b/libs/fleet/agent.test.ts
@@ -9,8 +9,18 @@ import {
type AgentEvent,
type TurnClient,
} from "./src/browser-agent.ts"
-import { createBrowserMcpCommands, createBrowserMcpToolCaller, type McpClient } from "./src/browser-mcp-commands.ts"
-import { createBrowserSdkCommands, type BrowserSdk } from "./src/browser-sdk-commands.ts"
+import { isHelpRequest, renderCommandHelp } from "./src/browser-command-help.ts"
+import {
+ BROWSER_MCP_COMMAND_NAMES,
+ createBrowserMcpCommands,
+ createBrowserMcpToolCaller,
+ type McpClient,
+} from "./src/browser-mcp-commands.ts"
+import {
+ BROWSER_SDK_COMMAND_NAMES,
+ createBrowserSdkCommands,
+ type BrowserSdk,
+} from "./src/browser-sdk-commands.ts"
import { gzipSync, gunzipSync } from "./src/node-zlib-browser.ts"
@@ -35,6 +45,81 @@ function sdkShell(overrides: Partial<BrowserSdk> = {}): Bash {
return new Bash({ customCommands: createBrowserSdkCommands(sdk) })
}
+test("renders command help with stable skill sections", () => {
+ const help = renderCommandHelp("example", {
+ summary: "Inspect an example resource.",
+ usage: "example '[name]'",
+ arguments: ["name: Resource name."],
+ output: "A JSON object.",
+ presentation: ["Use a concise Markdown table."],
+ safety: "Read-only.",
+ examples: ["example '[\"demo\"]'"],
+ })
+
+ assert.equal(
+ help,
+ [
+ "Inspect an example resource.",
+ "",
+ "Usage:",
+ " example '[name]'",
+ "",
+ "Arguments:",
+ " name: Resource name.",
+ "",
+ "Output:",
+ " A JSON object.",
+ "",
+ "Present to the user:",
+ " Use a concise Markdown table.",
+ "",
+ "Safety:",
+ " Read-only.",
+ "",
+ "Examples:",
+ " example '[\"demo\"]'",
+ "",
+ ].join("\n"),
+ )
+ assert.equal(isHelpRequest(["-h"]), true)
+ assert.equal(isHelpRequest(["--help"]), true)
+ assert.equal(isHelpRequest(["-h", "extra"]), false)
+ assert.equal(isHelpRequest([]), false)
+})
+
+test("every SDK command exposes help without calling the SDK", async () => {
+ let calls = 0
+ const sdk = Object.fromEntries(
+ BROWSER_SDK_COMMAND_NAMES.map(name => [name, async () => {
+ calls += 1
+ return undefined
+ }]),
+ ) as unknown as BrowserSdk
+ const shell = new Bash({ customCommands: createBrowserSdkCommands(sdk) })
+
+ for (const name of BROWSER_SDK_COMMAND_NAMES) {
+ for (const flag of ["-h", "--help"]) {
+ const result = await shell.exec(`${name} ${flag}`)
+ assert.equal(result.exitCode, 0, `${name} ${flag}`)
+ assert.match(result.stdout, new RegExp(`Usage:\\n ${name}`))
+ assert.match(result.stdout, /Present to the user:/)
+ assert.equal(result.stderr, "")
+ }
+ }
+
+ assert.equal(calls, 0)
+})
+
+test("listPools help defines the linked table presentation", async () => {
+ const result = await sdkShell().exec("listPools -h")
+
+ assert.equal(result.exitCode, 0)
+ assert.match(result.stdout, /Pool \| Replicas \| Available \| Phase/)
+ assert.match(result.stdout, /Omit Namespace/)
+ assert.match(result.stdout, /Markdown link/)
+ assert.match(result.stdout, /\/pools\/<URL-encoded namespace>\/<URL-encoded pool name>/)
+})
+
test("exposes SDK methods as composable bash commands", async () => {
const shell = sdkShell({
listPools: async () => [
@@ -128,6 +213,28 @@ test("exposes exact MCP tool names as composable bash commands", async () => {
assert.equal(result.stderr, "")
})
+test("every MCP command exposes help without connecting or calling tools", async () => {
+ let calls = 0
+ const shell = new Bash({
+ customCommands: createBrowserMcpCommands(async () => {
+ calls += 1
+ return {}
+ }),
+ })
+
+ for (const name of BROWSER_MCP_COMMAND_NAMES) {
+ for (const flag of ["-h", "--help"]) {
+ const result = await shell.exec(`${name} ${flag}`)
+ assert.equal(result.exitCode, 0, `${name} ${flag}`)
+ assert.match(result.stdout, /Present to the user:/)
+ assert.match(result.stdout, /cite/i)
+ assert.equal(result.stderr, "")
+ }
+ }
+
+ assert.equal(calls, 0)
+})
+
test("reads MCP tool arguments from stdin", async () => {
const calls: Array<{ name: string; arguments: Record<string, unknown> }> = []
const shell = new Bash({
diff --git a/libs/fleet/backend/chat/litellm.go b/libs/fleet/backend/chat/litellm.go
index 982126cf33..f0971c48a6 100644
--- a/libs/fleet/backend/chat/litellm.go
+++ b/libs/fleet/backend/chat/litellm.go
@@ -18,28 +18,17 @@ const (
liteLLMResponseMaxBytes = 128 << 10
cyclopsSystemPrompt = `You are the Cyclops CS assistant. Treat unqualified product terms as Cyclops concepts: pools are Cyclops sandbox warm pools, claims are allocated sandboxes, and namespaces scope those resources.
-Use browser Bash when it helps. Ordinary Bash has an isolated in-memory filesystem with no network access and no host filesystem access. These authenticated Cyclops SDK methods are available as first-class Bash commands:
-listNamespaces []
-listPools []
-getPool [namespace, name]
-createPool [name, poolTemplateConfig]
-updatePoolServices [namespace, name, services]
-deletePool [namespace, name]
-listClaims [namespace]
-createClaim [namespace, poolName]
-getClaim [namespace, name]
-deleteClaim [namespace, name]
-listUserKeys []
-createUserKey [name, scopes?]
-deleteUserKey [id]
-
-These read-only CUA documentation and versioned code MCP tools are also available as first-class Bash commands:
-query_docs_db {"sql": string}
-query_docs_vectors {"query": string, "limit"?: number, "where"?: string, "select"?: string[]}
-query_code_db {"sql": string}
-query_code_vectors {"query": string, "limit"?: number, "where"?: string, "select"?: string[], "component"?: string}
-
-Pass Cyclops SDK method arguments as one JSON array argument. Pass MCP tool arguments as one JSON object argument. Either form can instead be piped to the command through stdin. Commands write JSON results to stdout, write errors to stderr, and compose with jq, pipes, redirects, files, conditionals, and loops. Use the SDK commands for live Cyclops state instead of guessing. Use the MCP commands for CUA documentation and versioned source questions, and cite returned documentation URLs or code sources as component@version:path. Do not claim that ordinary Bash can reach APIs; only the registered commands bridge to their services. Before a mutating command, state the intended change and use the exact arguments supplied by the user; ask only for missing required values. Be concise and action-oriented; ask a clarifying question only when the Cyclops interpretation is genuinely ambiguous.`
+Use browser Bash when it helps. Ordinary Bash has an isolated in-memory filesystem with no network access and no host filesystem access. Registered commands are the only bridges to authenticated Cyclops APIs and the read-only CUA documentation and code service.
+
+Authenticated Cyclops SDK commands:
+listNamespaces, listPools, getPool, createPool, updatePoolServices, deletePool, listClaims, createClaim, getClaim, deleteClaim, listUserKeys, createUserKey, deleteUserKey
+
+Read-only CUA documentation and versioned code commands:
+query_docs_db, query_docs_vectors, query_code_db, query_code_vectors
+
+You must, before first use of any registered command in a conversation, run exactly <command> -h in a separate Bash tool call and read its full help. The help is that command's skill: follow its Usage, Arguments, Output, Present to the user, Safety, and Examples guidance. After learning a command, do not repeat its help in the same conversation unless you need a refresher. Never guess a command's arguments, behavior, safety, or output presentation instead of reading its help.
+
+Commands write JSON results to stdout, write errors to stderr, and compose with jq, pipes, redirects, files, conditionals, and loops. Use SDK commands for live Cyclops state rather than guessing. Use documentation and code commands for CUA reference questions. Do not claim ordinary Bash can reach APIs or arbitrary network services. Before a mutating command, state the intended change and use the exact values supplied by the user; ask only for missing required values. Be concise and action-oriented; ask a clarifying question only when the Cyclops interpretation is genuinely ambiguous.`
)
// ModelClient produces one assistant response while streaming content deltas.
diff --git a/libs/fleet/backend/chat/litellm_test.go b/libs/fleet/backend/chat/litellm_test.go
index adeba604d3..cf3b087164 100644
--- a/libs/fleet/backend/chat/litellm_test.go
+++ b/libs/fleet/backend/chat/litellm_test.go
@@ -61,7 +61,7 @@ func TestLiteLLMCompleteStreamsContentAndRequest(t *testing.T) {
if body.Messages[0].Role != "system" {
t.Fatalf("first message role = %q, want system", body.Messages[0].Role)
}
- for _, fragment := range []string{"Cyclops CS", "listPools", "getPool", "listClaims", "JSON array", "query_docs_db", "query_docs_vectors", "query_code_db", "query_code_vectors", "JSON object", "component@version:path", "no network access"} {
+ for _, fragment := range []string{"Cyclops CS", "listPools", "getPool", "listClaims", "query_docs_db", "query_docs_vectors", "query_code_db", "query_code_vectors", "-h", "before first use", "same conversation", "Present to the user", "no network access"} {
if !strings.Contains(body.Messages[0].Content, fragment) {
t.Errorf("system prompt missing %q", fragment)
}
diff --git a/libs/fleet/docs/browser-agent.md b/libs/fleet/docs/browser-agent.md
index ae7f83a20a..15a643ac50 100644
--- a/libs/fleet/docs/browser-agent.md
+++ b/libs/fleet/docs/browser-agent.md
@@ -3,7 +3,9 @@
Cyclops includes an authenticated chat UI whose agent loop runs inside the
browser. The model may request a single `bash` function tool implemented with
`just-bash/browser`; the browser executes it in a temporary virtual filesystem
-and returns the result to the backend for the next model turn.
+and returns the result to the backend for the next model turn. Registered Bash
+commands bridge that isolated shell to the authenticated Cyclops SDK and the
+read-only CUA documentation and versioned code MCP service.
The Go backend owns conversation history, authentication, authorization, and
LiteLLM access. The current conversation store is in memory, so history is lost
@@ -27,8 +29,27 @@ The bash runtime is browser-local and isolated:
output at 128 KiB. The in-memory backend also caps each owner at 100
conversations and the process-wide transcript store at 64 MiB.
-There is no MCP integration, Playwright tool, browser automation, Chromium
-process, or Node sidecar. The frontend does not receive LiteLLM credentials.
+There is no Playwright tool, browser automation, Chromium process, Node
+sidecar, or arbitrary Bash networking. Four explicit read-only MCP commands are
+registered for CUA documentation and code lookup. The frontend does not receive
+LiteLLM credentials.
+
+## Command help skills
+
+Every registered SDK and MCP command supports `-h` and `--help`. Help is the
+command's progressively disclosed skill: it describes purpose, usage,
+arguments, output shape, user-facing presentation, safety, and examples without
+calling the backing SDK or MCP service.
+
+The system prompt contains only the compact command catalog. Before first use
+of a command in a conversation, the agent runs `<command> -h` in a separate
+Bash call and follows the returned guidance. It does not repeat help for that
+command in the same conversation unless it needs a refresher.
+
+Presentation rules live with command execution metadata. For example,
+`listPools -h` requires a Markdown table with `Pool`, `Replicas`, `Available`,
+and `Phase`; omits the redundant Namespace column; and links each pool name to
+`/pools/<namespace>/<name>` using URL-encoded path segments.
## Local development
diff --git a/libs/fleet/e2e/agent-chat.spec.ts b/libs/fleet/e2e/agent-chat.spec.ts
index 6f6aae5e8b..183dbac090 100644
--- a/libs/fleet/e2e/agent-chat.spec.ts
+++ b/libs/fleet/e2e/agent-chat.spec.ts
@@ -595,9 +595,9 @@ test("renders and sanitizes Markdown in user and assistant messages", async ({
id: "markdown-assistant",
role: "assistant",
content: [
- "| Pool | Phase |",
- "| --- | --- |",
- "| demo | Ready |",
+ "| Pool | Replicas | Available | Phase |",
+ "| --- | ---: | ---: | --- |",
+ "| [demo](/pools/team/demo) | 2 | 1 | Ready |",
"",
"```ts",
"const ready = true",
@@ -627,6 +627,11 @@ test("renders and sanitizes Markdown in user and assistant messages", async ({
/.+/,
);
await expect(assistantBubble.getByRole("table")).toBeVisible();
+ await expect(assistantBubble.getByRole("columnheader", { name: "Namespace" })).toHaveCount(0);
+ await expect(assistantBubble.getByRole("link", { name: "demo" })).toHaveAttribute(
+ "href",
+ "/pools/team/demo",
+ );
await expect(assistantBubble.locator("pre code")).toContainText(
"const ready = true",
);
diff --git a/libs/fleet/src/browser-command-help.ts b/libs/fleet/src/browser-command-help.ts
new file mode 100644
index 0000000000..c95c598bd1
--- /dev/null
+++ b/libs/fleet/src/browser-command-help.ts
@@ -0,0 +1,28 @@
+export interface BrowserCommandHelp {
+ summary: string
+ usage: string
+ arguments?: string[]
+ output: string
+ presentation: string[]
+ safety: string
+ examples?: string[]
+}
+
+export function isHelpRequest(args: string[]): boolean {
+ return args.length === 1 && (args[0] === "-h" || args[0] === "--help")
+}
+
+function appendSection(lines: string[], heading: string, values: string[]): void {
+ lines.push(heading, ...values.map(value => ` ${value}`), "")
+}
+
+export function renderCommandHelp(name: string, help: BrowserCommandHelp): string {
+ const lines = [help.summary, ""]
+ appendSection(lines, "Usage:", [help.usage || name])
+ if (help.arguments?.length) appendSection(lines, "Arguments:", help.arguments)
+ appendSection(lines, "Output:", [help.output])
+ appendSection(lines, "Present to the user:", help.presentation)
+ appendSection(lines, "Safety:", [help.safety])
+ if (help.examples?.length) appendSection(lines, "Examples:", help.examples)
+ return lines.join("\n")
+}
diff --git a/libs/fleet/src/browser-mcp-commands.ts b/libs/fleet/src/browser-mcp-commands.ts
index 389f3b9564..13470dbddc 100644
--- a/libs/fleet/src/browser-mcp-commands.ts
+++ b/libs/fleet/src/browser-mcp-commands.ts
@@ -1,6 +1,11 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import { defineCommand, type Command } from "just-bash/browser"
+import {
+ isHelpRequest,
+ renderCommandHelp,
+ type BrowserCommandHelp,
+} from "./browser-command-help.js"
const CUA_DOCS_MCP_URL = "https://vk-mcp.cua.ai/mcp"
@@ -13,6 +18,72 @@ export const BROWSER_MCP_COMMAND_NAMES = [
export type BrowserMcpCommandName = (typeof BROWSER_MCP_COMMAND_NAMES)[number]
+const MCP_COMMAND_HELP: Record<BrowserMcpCommandName, BrowserCommandHelp> = {
+ query_docs_db: {
+ summary: "Run a read-only SQL query against the indexed CUA documentation database.",
+ usage: "query_docs_db '{\"sql\":\"SELECT ...\"}'",
+ arguments: ["sql: Read-only SQL query supported by the documentation service."],
+ output: "An MCP result object containing structured rows and/or text content.",
+ presentation: [
+ "Answer the user's question directly; do not dump the MCP wrapper object.",
+ "Cite relevant documentation URLs returned by the query next to the claims they support.",
+ "Use a table only when the result is naturally tabular.",
+ ],
+ safety: "Read-only remote query. Ordinary browser Bash still has no general network access.",
+ examples: ["query_docs_db '{\"sql\":\"SELECT title, url FROM documents LIMIT 10\"}' | jq"],
+ },
+ query_docs_vectors: {
+ summary: "Search CUA documentation semantically.",
+ usage: "query_docs_vectors '{\"query\":\"text\",\"limit\":5}'",
+ arguments: [
+ "query: Natural-language search text.",
+ "limit: Optional result limit.",
+ "where: Optional service-supported filter.",
+ "select: Optional fields to return.",
+ ],
+ output: "An MCP result object containing ranked documentation matches.",
+ presentation: [
+ "Synthesize the matches into a concise answer instead of listing raw embeddings or scores.",
+ "Cite the returned documentation URLs next to the claims they support.",
+ "Mention uncertainty when the matches do not directly answer the question.",
+ ],
+ safety: "Read-only remote search. Ordinary browser Bash still has no general network access.",
+ examples: ["query_docs_vectors '{\"query\":\"create a warm pool\",\"limit\":5}' | jq"],
+ },
+ query_code_db: {
+ summary: "Run a read-only SQL query against indexed versioned CUA source code.",
+ usage: "query_code_db '{\"sql\":\"SELECT ...\"}'",
+ arguments: ["sql: Read-only SQL query supported by the code index."],
+ output: "An MCP result object containing structured code-index rows and/or text content.",
+ presentation: [
+ "Explain the relevant implementation rather than dumping raw rows.",
+ "Cite each source as component@version:path, adding line information when returned.",
+ "Use short code excerpts only when needed to explain behavior.",
+ ],
+ safety: "Read-only remote query. Results describe indexed code and do not execute it.",
+ examples: ["query_code_db '{\"sql\":\"SELECT component, version, path FROM code_files LIMIT 10\"}' | jq"],
+ },
+ query_code_vectors: {
+ summary: "Search indexed versioned CUA source code semantically.",
+ usage: "query_code_vectors '{\"query\":\"text\",\"limit\":5}'",
+ arguments: [
+ "query: Natural-language code search text.",
+ "limit: Optional result limit.",
+ "where: Optional service-supported filter.",
+ "select: Optional fields to return.",
+ "component: Optional CUA component filter.",
+ ],
+ output: "An MCP result object containing ranked versioned code matches.",
+ presentation: [
+ "Summarize how the matching code works and distinguish direct evidence from inference.",
+ "Cite each source as component@version:path, adding line information when returned.",
+ "Do not present similarity scores unless the user asks for search diagnostics.",
+ ],
+ safety: "Read-only remote search. Results describe indexed code and do not execute it.",
+ examples: ["query_code_vectors '{\"query\":\"browser agent bash commands\",\"limit\":5,\"component\":\"cloud\"}' | jq"],
+ },
+}
+
export interface McpToolResult {
content?: Array<{ type: string; text?: string; [key: string]: unknown }>
structuredContent?: Record<string, unknown>
@@ -86,6 +157,9 @@ export function createBrowserMcpToolCaller(connect: McpConnector = connectCuaDoc
export function createBrowserMcpCommands(callTool: McpToolCaller = createBrowserMcpToolCaller()): Command[] {
return BROWSER_MCP_COMMAND_NAMES.map(name =>
defineCommand(name, async (args, context) => {
+ if (isHelpRequest(args)) {
+ return { stdout: renderCommandHelp(name, MCP_COMMAND_HELP[name]), stderr: "", exitCode: 0 }
+ }
try {
const arguments_ = parseArguments(args, decodeStdin(context.stdin))
const result = await callTool(name, arguments_)
diff --git a/libs/fleet/src/browser-sdk-commands.ts b/libs/fleet/src/browser-sdk-commands.ts
index f14d4d1090..d08f5a8b3d 100644
--- a/libs/fleet/src/browser-sdk-commands.ts
+++ b/libs/fleet/src/browser-sdk-commands.ts
@@ -1,4 +1,9 @@
import { defineCommand, type Command } from "just-bash/browser"
+import {
+ isHelpRequest,
+ renderCommandHelp,
+ type BrowserCommandHelp,
+} from "./browser-command-help.js"
export type BrowserSdkMethod = (...args: never[]) => Promise<unknown>
@@ -34,6 +39,173 @@ export const BROWSER_SDK_COMMAND_NAMES = [
"deleteUserKey",
] as const satisfies readonly (keyof BrowserSdk)[]
+type BrowserSdkCommandName = (typeof BROWSER_SDK_COMMAND_NAMES)[number]
+
+const SDK_COMMAND_HELP: Record<BrowserSdkCommandName, BrowserCommandHelp> = {
+ listNamespaces: {
+ summary: "List namespaces visible to the current user.",
+ usage: "listNamespaces",
+ output: "A JSON array of namespace objects.",
+ presentation: [
+ "Use a short bullet list unless the user asks for raw JSON.",
+ "Do not include namespaces in pool listings; list them only when namespaces are the requested subject.",
+ ],
+ safety: "Read-only.",
+ examples: ["listNamespaces | jq -r '.[].name'"],
+ },
+ listPools: {
+ summary: "List all pools visible to the current user.",
+ usage: "listPools",
+ output: "A JSON array with name, namespace, replicas, availableCount, and phase for each pool.",
+ presentation: [
+ "Use a concise Markdown table with exactly these columns: Pool | Replicas | Available | Phase.",
+ "Omit Namespace; it is implementation detail and redundant in this listing.",
+ "Render each pool name as a Markdown link to /pools/<URL-encoded namespace>/<URL-encoded pool name>.",
+ "After the table, summarize the total pool count and total available sandboxes in one sentence.",
+ ],
+ safety: "Read-only.",
+ examples: ["listPools", "listPools | jq '[length, (map(.availableCount) | add // 0)]'"],
+ },
+ getPool: {
+ summary: "Get the full configuration and live status of one pool.",
+ usage: "getPool '[\"namespace\",\"name\"]'",
+ arguments: ["namespace: Pool namespace.", "name: Pool name."],
+ output: "A JSON pool object including capacity, image, resources, services, probes, and autoscaling.",
+ presentation: [
+ "Use the linked pool name as the heading: [name](/pools/<URL-encoded namespace>/<URL-encoded name>), followed by compact status and configuration sections.",
+ "Do not repeat the namespace unless it disambiguates the result or the user explicitly asks for it.",
+ "Omit empty optional sections rather than displaying null or empty values.",
+ ],
+ safety: "Read-only.",
+ examples: ["getPool '[\"team\",\"browser-pool\"]' | jq"],
+ },
+ createPool: {
+ summary: "Create a pool and its sandbox template.",
+ usage: "createPool '[\"name\",poolTemplateConfig]'",
+ arguments: [
+ "name: New pool name; the namespace is created with the same name.",
+ "poolTemplateConfig: Object containing cpu, ram, ociImage, replicas, and optional firmware, services, probes, or autoscaling.",
+ ],
+ output: "The created pool object.",
+ presentation: [
+ "Before execution, state the exact pool name and requested capacity.",
+ "After success, link the pool name to /pools/<URL-encoded namespace>/<URL-encoded pool name> and summarize its key configuration.",
+ "Never display raw internal objects unless requested.",
+ ],
+ safety: "Mutating. Confirm all required values are supplied and use exactly the user's requested configuration.",
+ examples: ["createPool '[\"demo\",{\"cpu\":2,\"ram\":\"4Gi\",\"ociImage\":\"ghcr.io/trycua/cua:latest\",\"replicas\":1}]'"],
+ },
+ updatePoolServices: {
+ summary: "Replace the service definitions exposed by a pool.",
+ usage: "updatePoolServices '[\"namespace\",\"name\",services]'",
+ arguments: ["namespace: Pool namespace.", "name: Pool name.", "services: Complete replacement array of service definitions."],
+ output: "No stdout on success.",
+ presentation: [
+ "Before execution, state that the complete service list will be replaced.",
+ "After success, link the pool name to /pools/<URL-encoded namespace>/<URL-encoded name> and list the resulting services concisely.",
+ ],
+ safety: "Mutating. This replaces, rather than merges, the pool's service list.",
+ examples: ["updatePoolServices '[\"team\",\"browser-pool\",[{\"name\":\"desktop\",\"targetPort\":6901,\"protocol\":\"TCP\"}]]'"],
+ },
+ deletePool: {
+ summary: "Delete a pool and its associated namespace resources.",
+ usage: "deletePool '[\"namespace\",\"name\"]'",
+ arguments: ["namespace: Pool namespace.", "name: Pool name."],
+ output: "No stdout on success.",
+ presentation: [
+ "Before execution, explicitly name the pool being deleted and describe the destructive effect.",
+ "After success, confirm deletion in one sentence without inventing deleted resource counts.",
+ ],
+ safety: "Destructive. Run only when the user clearly requested deletion of this exact pool.",
+ examples: ["deletePool '[\"team\",\"browser-pool\"]'"],
+ },
+ listClaims: {
+ summary: "List sandbox claims in one namespace.",
+ usage: "listClaims '[\"namespace\"]'",
+ arguments: ["namespace: Namespace whose claims should be listed."],
+ output: "A JSON array with claim name, pool, phase, sandbox details, and creation time.",
+ presentation: [
+ "Use a concise Markdown table with Claim, Pool, Phase, Sandbox, and Created columns.",
+ "Omit Namespace because the command already scopes the result to one namespace.",
+ "Link claim names to /pools/<URL-encoded namespace>/<URL-encoded pool name>/claims/<URL-encoded claim name> when the pool name is available.",
+ ],
+ safety: "Read-only.",
+ examples: ["listClaims '[\"team\"]' | jq"],
+ },
+ createClaim: {
+ summary: "Allocate a sandbox claim from a pool.",
+ usage: "createClaim '[\"namespace\",\"poolName\"]'",
+ arguments: ["namespace: Pool namespace.", "poolName: Pool that should supply the sandbox."],
+ output: "The created claim object.",
+ presentation: [
+ "Before execution, state which linked pool will allocate the sandbox.",
+ "After success, report the claim name and phase, and link the claim to its detail page.",
+ ],
+ safety: "Mutating. Creates a claim that consumes pool capacity.",
+ examples: ["createClaim '[\"team\",\"browser-pool\"]'"],
+ },
+ getClaim: {
+ summary: "Get the live state of one sandbox claim.",
+ usage: "getClaim '[\"namespace\",\"name\"]'",
+ arguments: ["namespace: Claim namespace.", "name: Claim name."],
+ output: "A JSON claim object with pool, phase, sandbox endpoint fields, and creation time.",
+ presentation: [
+ "Show the claim name, linked pool, phase, sandbox name, service endpoint, and creation time.",
+ "Omit fields that are absent while the claim is pending.",
+ ],
+ safety: "Read-only.",
+ examples: ["getClaim '[\"team\",\"claim-one\"]' | jq"],
+ },
+ deleteClaim: {
+ summary: "Delete a claim and return its sandbox capacity to the pool.",
+ usage: "deleteClaim '[\"namespace\",\"name\"]'",
+ arguments: ["namespace: Claim namespace.", "name: Claim name."],
+ output: "No stdout on success.",
+ presentation: [
+ "Before execution, explicitly name the claim being released.",
+ "After success, confirm that the claim was deleted and its sandbox capacity was returned to the pool.",
+ ],
+ safety: "Destructive. Run only when the user clearly requested release of this exact claim.",
+ examples: ["deleteClaim '[\"team\",\"claim-one\"]'"],
+ },
+ listUserKeys: {
+ summary: "List API keys owned by the current user without revealing secrets.",
+ usage: "listUserKeys",
+ output: "A JSON array containing key IDs, client IDs, names, and scopes.",
+ presentation: [
+ "Use a concise Markdown table with Name, Client ID, and Scopes.",
+ "Do not display internal key IDs unless the user needs one for deletion.",
+ ],
+ safety: "Read-only. Existing client secrets are never returned.",
+ examples: ["listUserKeys | jq"],
+ },
+ createUserKey: {
+ summary: "Create a user API key whose secret is shown once.",
+ usage: "createUserKey '[\"name\",[\"scope\"]]'",
+ arguments: ["name: Human-readable key name.", "scopes: Optional array of scopes."],
+ output: "A JSON object containing clientId, clientSecret, tokenUrl, name, and scopes.",
+ presentation: [
+ "Warn before execution that a new credential will be created.",
+ "After success, clearly state that the client secret is shown once and render the credential fields in a fenced text block.",
+ "Do not repeat the client secret later in the response or include it in a table.",
+ ],
+ safety: "Sensitive mutation. Create only with the user's requested name and scopes; never expose the secret beyond the immediate result.",
+ examples: ["createUserKey '[\"automation\",[\"fleets:read\"]]'"],
+ },
+ deleteUserKey: {
+ summary: "Revoke one user API key by ID.",
+ usage: "deleteUserKey '[\"id\"]'",
+ arguments: ["id: Internal key ID, obtainable from listUserKeys."],
+ output: "No stdout on success.",
+ presentation: [
+ "Before execution, identify the human-readable key name and client ID when available, not only its internal ID.",
+ "After success, confirm revocation in one sentence.",
+ ],
+ safety: "Destructive credential operation. Verify the exact key before revoking it.",
+ examples: ["deleteUserKey '[\"key-id\"]'"],
+ },
+}
+
function decodeStdin(stdin: unknown): string {
const bytes = Uint8Array.from(stdin as string, character => character.charCodeAt(0))
return new TextDecoder().decode(bytes)
@@ -61,6 +233,9 @@ function errorMessage(error: unknown): string {
export function createBrowserSdkCommands(sdk: BrowserSdk): Command[] {
return BROWSER_SDK_COMMAND_NAMES.map(name =>
defineCommand(name, async (args, context) => {
+ if (isHelpRequest(args)) {
+ return { stdout: renderCommandHelp(name, SDK_COMMAND_HELP[name]), stderr: "", exitCode: 0 }
+ }
try {
const methodArguments = parseArguments(args, decodeStdin(context.stdin))
const method = sdk[name] as (...args: unknown[]) => Promise<unknown>