@auracheck-ai/cli 0.2.2 → 0.2.5

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/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,2EAA2E;AAC3E,wEAAwE;AACxE,+EAA+E;AAC/E,4DAA4D;AAC5D,MAAM,EAAE,OAAO,EAAE,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,iBAAiB,CAEnE,CAAC;AAEF;;;;GAIG;AACH,SAAS,kBAAkB;IACzB,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;IAC7D,OAAO,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC;AACxD,CAAC;AAED,KAAK,UAAU,IAAI;IACj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AAC;SACvE,MAAM,CAAC,KAAK,IAAI,EAAE;QACjB,MAAM,aAAa,EAAE,CAAC;IACxB,CAAC,CAAC,CAAC;IAEL,OAAO;SACJ,OAAO,CAAC,QAAQ,CAAC;SACjB,WAAW,CACV,sEAAsE,CACvE;SACA,MAAM,CAAC,KAAK,IAAI,EAAE;QACjB,MAAM,aAAa,EAAE,CAAC;IACxB,CAAC,CAAC,CAAC;IAEL,OAAO;SACJ,OAAO,CAAC,KAAK,CAAC;SACd,WAAW,CACV,iEAAiE,CAClE;SACA,MAAM,CACL,gBAAgB,EAChB,wEAAwE,CACzE;SACA,MAAM,CAAC,kBAAkB,EAAE,oBAAoB,CAAC;SAChD,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QACrB,MAAM,YAAY,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACzE,CAAC,CAAC,CAAC;IAEL,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACzC,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,YAAY,GAAG,EAAE,OAAO,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC;IAClE,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;QAC/B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
1
+ {"version":3,"sources":["../src/bin.ts","../src/commands/doctor.ts","../../mcp-core/src/api.ts","../../mcp-core/src/context.ts","../../mcp-core/src/errors.ts","../../mcp-core/src/knowledge.ts","../../mcp-core/src/register.ts","../../mcp-core/src/secrets.ts","../../mcp-core/src/tools/account.ts","../../mcp-core/src/types.ts","../../mcp-core/src/tools/bugs.ts","../../mcp-core/src/tools/exploration.ts","../../mcp-core/src/tools/features.ts","../../mcp-core/src/tools/runs.ts","../../mcp-core/src/tools/schedules.ts","../../mcp-core/src/tools/test-my-flow.ts","../../mcp-core/src/tools/testcases.ts","../../mcp-core/src/standard-schema.ts","../src/api.ts","../src/config.ts","../src/commands/init.ts","../src/commands/login.ts","../src/browser-login.ts","../src/commands/setup.ts","../src/commands/status.ts","../src/mcp/server.ts","../src/source-reader.ts"],"sourcesContent":["#!/usr/bin/env node\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { doctorCommand } from './commands/doctor.js';\nimport { initCommand } from './commands/init.js';\nimport {\n authStatusCommand,\n loginCommand,\n logoutCommand,\n} from './commands/login.js';\nimport { setupCommand } from './commands/setup.js';\nimport { statusCommand } from './commands/status.js';\nimport { runMcpServer } from './mcp/server.js';\n\n// Single-source the version from package.json, at build time (tsup's\n// `define`, see tsup.config.ts) rather than a runtime require: it used to be\n// typed here as well, and the two drifted (published npm package said 0.1.7\n// while `sixseven --version` still claimed 0.1.4). A runtime\n// `createRequire(...)('../package.json')` doesn't survive bundling — esbuild\n// rewrites the copied asset's relative path against the bundle's own output\n// layout, not the source layout, so it stops resolving once bin.ts is\n// bundled alongside the nested mcp/server.ts entry.\ndeclare const __CLI_VERSION__: string;\nconst version = __CLI_VERSION__;\n\n/**\n * `auracheck` is the published command (the `sixseven` alias was dropped in\n * 0.2.3 because it collided with the old @sixseven-ai/cli global install).\n * Show whichever name the person actually typed in --help/usage output.\n */\nfunction invokedCommandName(): string {\n const argv1 = process.argv[1] ?? '';\n const base = path.basename(argv1).replace(/\\.(c|m)?js$/, '');\n return base === 'sixseven' ? 'sixseven' : 'auracheck';\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name(invokedCommandName())\n .description(\n 'AuraCheck CLI — login, init repo, and run an MCP server so Claude Code can author whitebox testcases against your app. (`sixseven` also works, same command.)',\n )\n .version(version);\n\n program\n .command('setup')\n .description(\n 'Guided wizard: login → bind project → register MCP with Claude Code in one go',\n )\n .option('--base-url <url>', 'AuraCheck base URL')\n .option('--token <token>', 'CI token starting with 67ci_')\n .option('--project-id <id>', 'AuraCheck project id')\n .option('--skip-mcp', 'do not register the MCP server')\n .option('--non-interactive', 'fail instead of prompting')\n .action(async (opts) => {\n await setupCommand({\n baseUrl: opts.baseUrl,\n token: opts.token,\n projectId: opts.projectId,\n skipMcp: !!opts.skipMcp,\n nonInteractive: !!opts.nonInteractive,\n });\n });\n\n const loginOptions = (cmd: Command) =>\n cmd\n .option(\n '--base-url <url>',\n 'AuraCheck base URL (default: last login, else https://space.auracheck.ai.id)',\n )\n .option(\n '--token <token>',\n 'use a CI token (67ci_…) instead of the browser sign-in — for CI',\n )\n .option('--paste-token', 'prompt for a CI token instead of the browser')\n .option('--no-browser', 'print the sign-in link instead of opening it')\n .option('--label <name>', 'name shown under Active devices')\n .option('--non-interactive', 'fail instead of prompting');\n const runLogin = async (opts: any) => {\n await loginCommand({\n baseUrl: opts.baseUrl,\n token: opts.token,\n promptToken: !!opts.pasteToken,\n noBrowser: opts.browser === false,\n label: opts.label,\n nonInteractive: !!opts.nonInteractive,\n });\n };\n\n loginOptions(\n program\n .command('login')\n .description(\n 'Sign in through your browser (or with --token for CI); the CLI and MCP server use it',\n ),\n ).action(runLogin);\n\n program\n .command('logout')\n .description('Revoke this sign-in and forget the saved token')\n .option('--base-url <url>', 'AuraCheck base URL')\n .action(async (opts) => {\n await logoutCommand({ baseUrl: opts.baseUrl });\n });\n\n const auth = program\n .command('auth')\n .description(\n 'Sign-in commands: `auth status`, `auth login`, `auth logout`; `auth --token <t>` saves a CI token',\n )\n .option('--base-url <url>', 'AuraCheck base URL')\n .option('--token <token>', 'save a CI token (67ci_…) for this base URL')\n .action(async (opts) => {\n if (opts.token) {\n await loginCommand({\n baseUrl: opts.baseUrl,\n token: opts.token,\n nonInteractive: true,\n });\n return;\n }\n await authStatusCommand({ baseUrl: opts.baseUrl });\n });\n auth\n .command('status')\n .description(\n 'Show who the CLI/MCP is signed in as (never prints the token)',\n )\n .option('--base-url <url>', 'AuraCheck base URL')\n .action(async (opts, cmd) => {\n await authStatusCommand({\n baseUrl: opts.baseUrl ?? cmd.parent?.opts().baseUrl,\n });\n });\n loginOptions(\n auth.command('login').description('Same as `auracheck login`'),\n ).action(runLogin);\n auth\n .command('logout')\n .description('Same as `auracheck logout`')\n .option('--base-url <url>', 'AuraCheck base URL')\n .action(async (opts) => {\n await logoutCommand({ baseUrl: opts.baseUrl });\n });\n\n program\n .command('init')\n .description('Create .sixseven/config.json bound to an AuraCheck project')\n .option('--base-url <url>', 'AuraCheck base URL')\n .option('--project-id <id>', 'AuraCheck project id')\n .option('--non-interactive', 'fail instead of prompting')\n .action(async (opts) => {\n await initCommand({\n baseUrl: opts.baseUrl,\n projectId: opts.projectId,\n nonInteractive: !!opts.nonInteractive,\n });\n });\n\n program\n .command('status')\n .description('Show current binding, token validity, and project counts')\n .action(async () => {\n await statusCommand();\n });\n\n program\n .command('doctor')\n .description(\n 'Run diagnostics: config, token, backend reachability, project access',\n )\n .action(async () => {\n await doctorCommand();\n });\n\n program\n .command('mcp')\n .description(\n 'Start the AuraCheck MCP server on stdio (spawned by Claude Code)',\n )\n .option(\n '--project <id>',\n 'default project (else AURACHECK_PROJECT_ID, else .sixseven/config.json)',\n )\n .option('--base-url <url>', 'AuraCheck base URL')\n .action(async (opts) => {\n await runMcpServer({ projectId: opts.project, baseUrl: opts.baseUrl });\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((err) => {\n process.stderr.write(pc.red(`\\nerror: ${err?.message ?? err}\\n`));\n if (process.env.AURACHECK_DEBUG || process.env.SIXSEVEN_DEBUG) {\n process.stderr.write(`${String(err?.stack ?? '')}\\n`);\n }\n process.exit(1);\n});\n","import pc from 'picocolors';\nimport { fetch } from 'undici';\nimport { AuraCheckApi } from '../api.js';\nimport { findRepoRoot, getToken, readProjectConfig } from '../config.js';\n\nfunction ok(msg: string): void {\n process.stdout.write(pc.green(` ✓ ${msg}\\n`));\n}\nfunction bad(msg: string): void {\n process.stdout.write(pc.red(` ✗ ${msg}\\n`));\n process.exitCode = 1;\n}\nfunction warn(msg: string): void {\n process.stdout.write(pc.yellow(` ! ${msg}\\n`));\n}\n\nexport async function doctorCommand(): Promise<void> {\n process.stdout.write(pc.bold('AuraCheck CLI doctor\\n'));\n\n const repoRoot = await findRepoRoot(process.cwd());\n if (!repoRoot) {\n bad('No .sixseven/config.json found. Run `auracheck init`.');\n return;\n }\n ok(`repo root: ${repoRoot}`);\n\n let cfg;\n try {\n cfg = await readProjectConfig(repoRoot);\n ok(`config parsed: projectId=${cfg.projectId} platform=${cfg.platform}`);\n } catch (err: any) {\n bad(`config invalid: ${err.message}`);\n return;\n }\n\n const token = await getToken(cfg.baseUrl);\n if (!token) {\n bad(`no saved token for ${cfg.baseUrl}. Run \\`auracheck login\\`.`);\n return;\n }\n ok(`token present for ${cfg.baseUrl}`);\n\n try {\n const r = await fetch(`${cfg.baseUrl}/api/auth/me`);\n if (r.status >= 200 && r.status < 600)\n ok(`backend reachable (${r.status})`);\n else warn(`backend status ${r.status}`);\n } catch (err: any) {\n bad(`backend unreachable: ${err.message}`);\n return;\n }\n\n const api = new AuraCheckApi({ baseUrl: cfg.baseUrl, token });\n try {\n const user = await api.me();\n ok(`token valid: ${user.email} (${user.role})`);\n } catch (err: any) {\n bad(`token invalid: ${err.message}`);\n return;\n }\n\n let features: { id: string; name: string }[] = [];\n try {\n features = (await api.listFeatures(cfg.projectId)) as typeof features;\n ok(`project ${cfg.projectId} accessible, ${features.length} feature(s)`);\n } catch (err: any) {\n bad(`project access failed: ${err.message}`);\n return;\n }\n\n try {\n const project = await api.getProject(cfg.projectId);\n const supported = (project as { platforms?: string[] }).platforms ?? [];\n if (supported.length && !supported.includes(cfg.platform)) {\n warn(\n `default platform \"${cfg.platform}\" is NOT in project.platforms [${supported.join(', ')}] — auracheck.create_run will fail until you fix .sixseven/config.json`,\n );\n } else if (supported.length) {\n ok(`platform \"${cfg.platform}\" is supported by project`);\n }\n } catch {\n warn('could not verify project platforms (non-fatal)');\n }\n\n if (cfg.defaultFeatureId) {\n const exists = features.some((f) => f.id === cfg.defaultFeatureId);\n if (!exists) {\n warn(\n `defaultFeatureId ${cfg.defaultFeatureId} not found in project — clear it from .sixseven/config.json or pick a real feature id`,\n );\n } else {\n ok('defaultFeatureId resolves to a real feature');\n }\n }\n}\n","/**\n * AuraCheck REST API client. Fetch-only (global `fetch`/`Response`/`URL`) —\n * no `node:` imports, so this file runs unmodified inside a Cloudflare\n * Worker, the local stdio MCP server, or any other fetch-capable runtime.\n *\n * Moved from `packages/cli/src/api.ts` (cli-0.2.4). The one behaviour change\n * from that version: `downloadBlob` returns bytes instead of writing a file\n * — a Worker has no filesystem, so writing to disk is the caller's job now\n * (the local stdio adapter still does it, to keep CLI behaviour unchanged).\n */\n\nexport class ApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly bodyText: string,\n message: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\n/** Generic default for {@link authHint}'s 401 case; the local CLI overrides it. */\nexport const DEFAULT_SIGN_IN_HINT = 'Sign in again.';\n\n/**\n * What to tell a person (or an agent) when the server refuses the token —\n * the raw \"GET /x -> 401\" gave nobody a next step. `signInHint` is the\n * surface-specific call to action (e.g. the CLI's \"Run `auracheck login`…\",\n * passed via `ApiOptions.signInHint` so mcp-core itself stays neutral).\n */\nexport function authHint(\n status: number,\n serverError: string,\n signInHint: string = DEFAULT_SIGN_IN_HINT,\n): string | null {\n if (status === 401) {\n return `Your AuraCheck sign-in is missing, expired or revoked. ${signInHint}`;\n }\n if (status === 403 && /limited to another project/i.test(serverError)) {\n return 'This token is a project CI token and only reaches its own project. Sign in personally, or pass that projectId.';\n }\n return null;\n}\n\n/** Trim whitespace, control characters and trailing slashes off a base URL. */\nexport function normalizeBaseUrl(u: string): string {\n return u\n .replace(/\\p{Cc}/gu, '')\n .trim()\n .replace(/\\/+$/, '');\n}\n\nexport interface ApiOptions {\n baseUrl: string;\n token: string;\n timeoutMs?: number;\n /** Override for tests: replaces the global `fetch`. */\n fetchImpl?: typeof fetch;\n /** Extra headers sent on every request (e.g. `X-AC-Client` from the Worker). */\n extraHeaders?: Record<string, string>;\n /** Surface-specific call to action appended to a 401 message; see {@link authHint}. */\n signInHint?: string;\n /**\n * Node-only test hook: an undici `Dispatcher` (e.g. `MockAgent`) passed\n * through to `fetch`'s non-standard `dispatcher` option. Node's global\n * `fetch` is undici under the hood and honors it; a Workers runtime never\n * sets this, and `fetch` there ignores unknown init keys. Never required\n * in production code paths — tests only.\n */\n dispatcher?: unknown;\n}\n\nexport interface AuraCheckUser {\n id: string;\n email: string;\n name: string | null;\n role: string;\n companyId: string | null;\n}\n\nexport interface AuraCheckProject {\n id: string;\n name: string;\n companyId: string;\n [k: string]: unknown;\n}\n\nexport interface AuraCheckFeature {\n id: string;\n projectId: string;\n name: string;\n path: string | null;\n description: string;\n testCaseCount?: number;\n [k: string]: unknown;\n}\n\n/** One Midscene flow item, e.g. `{ aiTap: \"Sign in\" }` — no fixed shape. */\nexport type TestCaseStep = Record<string, unknown>;\n\nexport interface AuraCheckTestCase {\n id: string;\n featureId: string;\n name: string;\n // Stored/returned by the server as a YAML string (DB column is String).\n steps: string;\n priority?: string;\n category?: string;\n description?: string;\n expectedResult?: string;\n platforms?: string[];\n tags?: string[];\n prelationTestCaseId?: string | null;\n /** Joined by the server when prelationTestCaseId is set. */\n prelationTestCase?: {\n id: string;\n name: string;\n featureId: string;\n featureName: string;\n } | null;\n [k: string]: unknown;\n}\n\n/**\n * How `steps` may be supplied by callers. The server stores steps as a YAML\n * STRING and validates it has a top-level `tasks[]` array; the DB column is\n * `String`. Callers may pass any of these and `normalizeStepsToYaml`\n * serializes to that string:\n * - a YAML/JSON string (passed through untouched)\n * - a bare array of Midscene flow items, e.g. `[{ aiTap: 'Sign in' }]`\n * - an object shaped like `{ tasks: [{ name, flow }] }` or `{ flow: [...] }`\n */\nexport type StepsInput = string | TestCaseStep[] | Record<string, unknown>;\n\n/**\n * Serialize `steps` into the YAML string the AuraCheck server requires. JSON\n * is valid YAML (YAML ⊇ JSON), so structured input is JSON-stringified —\n * which the server's `yaml.load` parses and the DB's String column accepts.\n * A bare flow array is wrapped into the mandatory `{ tasks: [{ name, flow }] }`\n * shape.\n */\nexport function normalizeStepsToYaml(steps: StepsInput, caseName = ''): string {\n if (typeof steps === 'string') return steps;\n if (Array.isArray(steps)) {\n return JSON.stringify({\n tasks: [{ name: caseName || 'Main flow', flow: steps }],\n });\n }\n if (steps && typeof steps === 'object') {\n const obj = steps as Record<string, unknown>;\n if (Array.isArray(obj.tasks)) return JSON.stringify(obj);\n if (Array.isArray(obj.flow)) {\n return JSON.stringify({\n tasks: [{ name: caseName || 'Main flow', flow: obj.flow }],\n });\n }\n }\n throw new Error(\n 'steps must be a YAML string, an array of Midscene flow items ' +\n '(e.g. [{ aiTap: \"Sign in\" }, { aiInput: \"user@example.com\", locate: \"Email field\" }]), ' +\n 'or an object with a tasks[] array.',\n );\n}\n\nexport interface CreateTestCaseInput {\n name: string;\n steps: StepsInput;\n executionType?: 'automation' | 'manual';\n priority?: 'low' | 'medium' | 'high' | 'critical';\n category?: string;\n reason?: string;\n description?: string;\n expectedResult?: string;\n platforms?: string[];\n coveredScenarios?: string[];\n tags?: string[];\n prelationTestCaseId?: string | null;\n}\n\nexport class AuraCheckApi {\n private readonly baseUrl: string;\n private readonly token: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n private readonly extraHeaders: Record<string, string>;\n private readonly dispatcher: unknown;\n private readonly signInHint: string;\n\n constructor(opts: ApiOptions) {\n this.baseUrl = normalizeBaseUrl(opts.baseUrl);\n this.token = opts.token;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.extraHeaders = opts.extraHeaders ?? {};\n this.dispatcher = opts.dispatcher;\n this.signInHint = opts.signInHint ?? DEFAULT_SIGN_IN_HINT;\n }\n\n /** Spreads `{ dispatcher }` into a fetch init only when one was given. */\n private dispatcherInit(): Record<string, unknown> {\n return this.dispatcher ? { dispatcher: this.dispatcher } : {};\n }\n\n private async request<T>(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.token}`,\n Accept: 'application/json',\n ...this.extraHeaders,\n };\n let payload: string | undefined;\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n payload = JSON.stringify(body);\n }\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method,\n headers,\n body: payload,\n signal: controller.signal,\n ...this.dispatcherInit(),\n } as RequestInit);\n } catch (err: any) {\n throw new ApiError(0, '', `Network error calling ${url}: ${err.message}`);\n } finally {\n clearTimeout(timer);\n }\n const text = await res.text();\n if (!res.ok) {\n let msg = `${method} ${path} -> ${res.status}`;\n let serverError = '';\n try {\n const parsed = JSON.parse(text);\n if (parsed?.error) serverError = String(parsed.error);\n } catch {\n serverError = text.slice(0, 200);\n }\n if (serverError) msg += `: ${serverError}`;\n const hint = authHint(res.status, serverError, this.signInHint);\n if (hint) msg += `. ${hint}`;\n throw new ApiError(res.status, text, msg);\n }\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n }\n\n // --- Auth ---\n\n async me(): Promise<AuraCheckUser> {\n return this.request('GET', '/api/auth/me');\n }\n\n // --- MCP context (role/subscription awareness; §3.4) ---\n\n async mcpContext(): Promise<McpContext> {\n return this.request('GET', '/api/mcp/context');\n }\n\n // --- Projects ---\n\n async listProjects(): Promise<AuraCheckProject[]> {\n return this.request('GET', '/api/projects');\n }\n\n async getProject(projectId: string): Promise<AuraCheckProject> {\n return this.request('GET', `/api/projects/${projectId}`);\n }\n\n async createProject(input: {\n name: string;\n targetUrl?: string;\n platforms: string[];\n description?: string;\n }): Promise<AuraCheckProject> {\n return this.request('POST', '/api/projects', input);\n }\n\n // --- Features ---\n\n async listFeatures(projectId: string): Promise<AuraCheckFeature[]> {\n return this.request('GET', `/api/projects/${projectId}/features`);\n }\n\n async createFeature(\n projectId: string,\n input: {\n name: string;\n path?: string;\n description?: string;\n prdContent?: string;\n parentId?: string;\n },\n ): Promise<AuraCheckFeature> {\n return this.request('POST', `/api/projects/${projectId}/features`, input);\n }\n\n /** There is no `GET /api/features/:id`; look it up via the project's list. */\n async getFeature(\n id: string,\n projectId: string,\n ): Promise<AuraCheckFeature | null> {\n const all = await this.listFeatures(projectId);\n return all.find((f) => f.id === id) ?? null;\n }\n\n /**\n * Delete a feature. Not a blanket cascade: its own test cases that are\n * linked to a run are soft-deleted (reparented onto the feature's parent,\n * run history intact) while unlinked ones are hard-deleted; descendant\n * features are removed once their cases are cleared. `cascade` also\n * removes any sub-features (same per-case split applies to their cases).\n */\n async deleteFeature(id: string, cascade = false): Promise<void> {\n const qs = cascade ? '?cascade=true' : '';\n await this.request('DELETE', `/api/features/${id}${qs}`);\n }\n\n // --- Test cases ---\n\n async listTestCasesByProject(\n projectId: string,\n platform?: string,\n ): Promise<AuraCheckTestCase[]> {\n const qs = platform ? `?platform=${encodeURIComponent(platform)}` : '';\n return this.request('GET', `/api/projects/${projectId}/test-cases${qs}`);\n }\n\n async listTestCasesByFeature(\n featureId: string,\n ): Promise<AuraCheckTestCase[]> {\n return this.request('GET', `/api/features/${featureId}/test-cases`);\n }\n\n async createTestCase(\n featureId: string,\n input: CreateTestCaseInput,\n ): Promise<AuraCheckTestCase> {\n const body = {\n ...input,\n steps: normalizeStepsToYaml(input.steps, input.name),\n executionType: input.executionType ?? 'automation',\n };\n return this.request('POST', `/api/features/${featureId}/test-cases`, body);\n }\n\n /**\n * Fetch one test case. There is no `GET /api/test-cases/:id` on the server\n * — only PUT, DELETE and sub-routes — so this reads via the project list.\n */\n async getTestCase(id: string, projectId: string): Promise<AuraCheckTestCase> {\n const all = await this.listTestCasesByProject(projectId);\n const found = all.find((c) => c.id === id);\n if (!found) {\n throw new ApiError(\n 404,\n '',\n `Test case ${id} not found in project ${projectId}`,\n );\n }\n return found;\n }\n\n /**\n * Patch a test case. PUT, not PATCH: the server defines no PATCH handler\n * for this path, while its PUT handler is explicitly partial.\n */\n async updateTestCase(\n id: string,\n patch: Partial<CreateTestCaseInput>,\n ): Promise<AuraCheckTestCase> {\n const body =\n patch && typeof patch === 'object' && patch.steps !== undefined\n ? {\n ...patch,\n steps: normalizeStepsToYaml(\n patch.steps,\n typeof patch.name === 'string' ? patch.name : '',\n ),\n }\n : patch;\n return this.request('PUT', `/api/test-cases/${id}`, body);\n }\n\n /**\n * Delete test cases. A single id goes through `DELETE /api/test-cases/:id`;\n * several go through `DELETE /api/test-cases/bulk` (max 500 ids). Either\n * way the server splits per case: one already linked to a run is\n * soft-deleted, an unlinked one is hard-deleted.\n */\n async deleteTestCases(\n ids: string[],\n ): Promise<{ hardDeleted: number | null; softDeleted: number | null }> {\n if (ids.length === 1) {\n await this.request('DELETE', `/api/test-cases/${ids[0]}`);\n return { hardDeleted: null, softDeleted: null };\n }\n return this.request('DELETE', '/api/test-cases/bulk', { ids });\n }\n\n // --- Prompt-to-test (test_my_flow) ---\n\n async previewPromptTest(\n projectId: string,\n input: { url: string; prompt: string },\n ): Promise<{ plan: PromptPlan }> {\n return this.request(\n 'POST',\n `/api/projects/${projectId}/prompt-tests/preview`,\n input,\n );\n }\n\n async createPromptTestRun(\n projectId: string,\n input: { url: string; prompt: string; plan: PromptPlan },\n ): Promise<{ run: AuraCheckRun }> {\n return this.request('POST', `/api/projects/${projectId}/prompt-tests`, {\n url: input.url,\n prompt: input.prompt,\n plan: input.plan,\n });\n }\n\n // --- Runs ---\n\n async listRuns(\n projectId: string,\n platform?: string,\n ): Promise<AuraCheckRun[]> {\n const qs = platform ? `?platform=${encodeURIComponent(platform)}` : '';\n return this.request('GET', `/api/projects/${projectId}/runs${qs}`);\n }\n\n async createRun(\n projectId: string,\n input: CreateRunInput,\n ): Promise<\n AuraCheckRun & { includedCaseCount?: number; skippedCaseCount?: number }\n > {\n return this.request('POST', `/api/projects/${projectId}/runs`, input);\n }\n\n async getRun(runId: string): Promise<AuraCheckRun> {\n return this.request('GET', `/api/runs/${runId}`);\n }\n\n /** Result buckets the Run Report shows (bugs / script issues / blocked / passed). */\n async getRunReportBuckets(runId: string): Promise<Record<string, unknown>> {\n return this.request('GET', `/api/runs/${runId}/report-buckets`);\n }\n\n async getRunCaseStatusCounts(runId: string): Promise<Record<string, number>> {\n return this.request('GET', `/api/runs/${runId}/case-status-counts`);\n }\n\n async executeRun(\n runId: string,\n ): Promise<{ ok?: boolean; runId?: string; [k: string]: unknown }> {\n return this.request('POST', `/api/runs/${runId}/execute`, {});\n }\n\n async cancelRun(runId: string): Promise<unknown> {\n return this.request('POST', `/api/runs/${runId}/cancel`, {});\n }\n\n async listRunTestCases(runId: string): Promise<AuraCheckTestCase[]> {\n return this.request('GET', `/api/runs/${runId}/test-cases`);\n }\n\n async listRunCaseAttempts(\n runId: string,\n ): Promise<{ attempts: CaseAttempt[] }> {\n return this.request('GET', `/api/runs/${runId}/case-attempts`);\n }\n\n async listRunStepEvents(\n runId: string,\n testCaseId?: string,\n ): Promise<{ events: StepEvent[] }> {\n const qs = testCaseId\n ? `?testCaseId=${encodeURIComponent(testCaseId)}`\n : '';\n return this.request('GET', `/api/runs/${runId}/events${qs}`);\n }\n\n // --- Schedules (recurring runs) ---\n\n async listSchedules(projectId: string): Promise<TestSchedule[]> {\n return this.request('GET', `/api/projects/${projectId}/schedules`);\n }\n\n async createSchedule(\n projectId: string,\n input: CreateScheduleInput,\n ): Promise<TestSchedule> {\n return this.request('POST', `/api/projects/${projectId}/schedules`, input);\n }\n\n async getSchedule(id: string): Promise<TestSchedule> {\n return this.request('GET', `/api/schedules/${id}`);\n }\n\n async updateSchedule(\n id: string,\n patch: UpdateScheduleInput,\n ): Promise<TestSchedule> {\n return this.request('PATCH', `/api/schedules/${id}`, patch);\n }\n\n /** Server replies 204 with no body; resolves to void on success. */\n async deleteSchedule(id: string): Promise<void> {\n await this.request('DELETE', `/api/schedules/${id}`);\n }\n\n async listScheduleFires(\n id: string,\n page?: number,\n ): Promise<{ items: ScheduleFire[]; hasMore: boolean }> {\n const qs = page && page > 1 ? `?page=${page}` : '';\n return this.request('GET', `/api/schedules/${id}/fires${qs}`);\n }\n\n async listScheduleRecipients(\n projectId: string,\n ): Promise<{ id: string; email: string; name: string | null }[]> {\n return this.request(\n 'GET',\n `/api/projects/${projectId}/schedules/assignable-users`,\n );\n }\n\n /**\n * Fire a schedule immediately. The route answers 202 for `run_created` and\n * 409 for every skip (`skipped_overlap` above all). A skip is a real,\n * informative answer, not a transport failure, so it is unwrapped back\n * into a normal result; only a genuine error (404, 500, network) still\n * throws.\n */\n async runScheduleNow(\n id: string,\n ): Promise<{ outcome: ScheduleFireOutcome; skipped: boolean }> {\n try {\n const res = await this.request<{ outcome: ScheduleFireOutcome }>(\n 'POST',\n `/api/schedules/${id}/run-now`,\n {},\n );\n return { outcome: res.outcome, skipped: false };\n } catch (err) {\n if (err instanceof ApiError && err.status === 409) {\n try {\n const parsed = JSON.parse(err.bodyText) as {\n outcome?: ScheduleFireOutcome;\n };\n if (parsed?.outcome)\n return { outcome: parsed.outcome, skipped: true };\n } catch {\n /* fall through to rethrow below */\n }\n }\n throw err;\n }\n }\n\n // --- Issue reports (bugs) ---\n\n async createIssueReport(input: CreateIssueReportInput): Promise<IssueReport> {\n return this.request('POST', '/api/issue-reports', input);\n }\n\n async listIssueReports(projectId?: string): Promise<IssueReport[]> {\n const qs = projectId ? `?projectId=${encodeURIComponent(projectId)}` : '';\n const resp = await this.request<IssueReport[] | { reports: IssueReport[] }>(\n 'GET',\n `/api/issue-reports${qs}`,\n );\n if (Array.isArray(resp)) return resp;\n return resp.reports ?? [];\n }\n\n async getIssueReport(id: string): Promise<IssueReport> {\n return this.request('GET', `/api/issue-reports/${id}`);\n }\n\n // --- Exploration ---\n\n async startExploration(\n projectId: string,\n input: StartExplorationInput,\n ): Promise<ExploreSnapshot> {\n return this.request('POST', `/api/projects/${projectId}/explore`, input);\n }\n\n async getExploration(projectId: string): Promise<ExploreSnapshot | null> {\n return this.request('GET', `/api/projects/${projectId}/explore`);\n }\n\n /**\n * Fetch an authenticated blob (screenshot, report) and return its raw\n * bytes. No filesystem here — a Worker has none. Callers that want a file\n * on disk (the local stdio adapter) write the bytes themselves.\n *\n * `urlOrPath` accepts a bare path (as returned by get_evidence) or an\n * absolute URL — but only on the bound host. A URL elsewhere is refused\n * rather than followed, because following it would hand the bearer token\n * to whatever host the caller named.\n */\n async downloadBlob(\n urlOrPath: string,\n ): Promise<{ bytes: Uint8Array; contentType: string }> {\n let pathPart: string;\n if (/^https?:\\/\\//i.test(urlOrPath)) {\n const given = new URL(urlOrPath);\n const bound = new URL(this.baseUrl);\n if (given.host !== bound.host) {\n throw new ApiError(\n 0,\n '',\n `Refusing to download from host ${given.host}: only ${bound.host} is bound`,\n );\n }\n pathPart = `${given.pathname}${given.search}`;\n } else {\n pathPart = urlOrPath.startsWith('/') ? urlOrPath : `/${urlOrPath}`;\n }\n\n const url = `${this.baseUrl}${pathPart}`;\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.token}`,\n ...this.extraHeaders,\n },\n ...this.dispatcherInit(),\n } as RequestInit);\n } catch (err: any) {\n throw new ApiError(0, '', `Network error calling ${url}: ${err.message}`);\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new ApiError(\n res.status,\n text,\n `GET ${pathPart} -> ${res.status}${text ? `: ${text.slice(0, 200)}` : ''}`,\n );\n }\n const buf = new Uint8Array(await res.arrayBuffer());\n if (buf.length === 0) {\n throw new ApiError(\n res.status,\n '',\n `GET ${pathPart} returned an empty body`,\n );\n }\n return {\n bytes: buf,\n contentType:\n res.headers.get('content-type') ?? 'application/octet-stream',\n };\n }\n}\n\n// --- MCP context (§3.4) ---\n\nexport interface McpRunUsage {\n dailyCount: number;\n dailyLimit: number;\n monthlyCount: number;\n monthlyLimit: number;\n concurrentCount: number;\n concurrentLimit: number;\n}\n\nexport interface McpSubscription {\n status: string;\n planName: string;\n daysLeft: number | null;\n readOnly: boolean;\n inGrace: boolean;\n graceEnd?: string | null;\n billingEnabled: boolean;\n runUsage: McpRunUsage | null;\n}\n\nexport interface McpAdminContact {\n // User.name is nullable in the data model; fall back to email when rendering.\n name: string | null;\n email: string;\n}\n\n/**\n * `/api/mcp/context`'s `projects` is `{id, name}` only — a cheap \"pick a\n * project\" hint, not the full `GET /api/projects` shape (which carries\n * expensive per-project batched stats). Call `list_projects` for the rest.\n */\nexport interface McpContextProject {\n id: string;\n name: string;\n}\n\nexport interface McpContext {\n user: {\n id: string;\n name: string | null;\n email: string;\n roleLabel: string;\n capabilities: string[];\n };\n company: { id: string; name: string };\n projects: McpContextProject[];\n subscription: McpSubscription;\n adminContact: McpAdminContact | null;\n renewalUrl: string;\n minLocalMcp: string;\n}\n\n// --- Prompt-to-test (test_my_flow) ---\n\nexport interface PromptPlanStep {\n kind: 'action' | 'assertion';\n description: string;\n}\n\nexport interface PromptPlan {\n title: string;\n category: 'positive' | 'negative' | 'edge';\n steps: PromptPlanStep[];\n}\n\n// --- Issue reports (bugs) ---\n\nexport interface IssueReport {\n id: string;\n title: string;\n severity: 'critical' | 'high' | 'medium' | 'low' | string;\n description: string | null;\n pageUrl: string | null;\n status: string;\n reportedBy: string | null;\n projectId: string | null;\n evidences: string[];\n larkTaskUrl?: string | null;\n createdAt?: string;\n [k: string]: unknown;\n}\n\nexport interface CreateIssueReportInput {\n title: string;\n severity: 'critical' | 'high' | 'medium' | 'low';\n description?: string;\n pageUrl?: string;\n evidences?: string[];\n projectId?: string;\n}\n\n// --- Exploration ---\n\nexport interface ExploreSnapshot {\n jobId: string;\n projectId: string;\n status: 'running' | 'completed' | 'failed';\n visited: number;\n anchorsUpserted: number;\n seedUrls: string[];\n maxDepth: number;\n maxPages: number;\n loggedIn: boolean;\n startedAt: string;\n finishedAt: string | null;\n errors: { url: string; message: string }[];\n}\n\nexport interface StartExplorationInput {\n seedUrls: string[];\n configurationId?: string;\n maxDepth?: number;\n maxPages?: number;\n}\n\n// --- Schedules (recurring runs) ---\n\nexport type ScheduleFireOutcome =\n | 'run_created'\n | 'skipped_overlap'\n | 'skipped_misfire'\n | 'skipped_capacity'\n | 'no_cases'\n | 'error';\n\nexport interface ScheduleCaseFilter {\n mode: 'all' | 'feature';\n featureIds: string[];\n}\n\nexport interface TestSchedule {\n id: string;\n projectId: string;\n name: string;\n enabled: boolean;\n cronExpressions: string[];\n timezone: string;\n nextFireAt: string | null;\n lastFiredAt: string | null;\n platform: string;\n configurationId: string | null;\n caseFilter: ScheduleCaseFilter;\n notifyUserIds: string[];\n misfireGraceMinutes: number;\n createdBy: string | null;\n [k: string]: unknown;\n}\n\nexport interface ScheduleFire {\n id: string;\n scheduleId: string;\n firedAt: string;\n outcome: ScheduleFireOutcome;\n runId: string | null;\n message: string | null;\n}\n\nexport interface CreateScheduleInput {\n name: string;\n platform: string;\n cronExpressions: string[];\n timezone: string;\n enabled?: boolean;\n configurationId?: string | null;\n caseFilter?: ScheduleCaseFilter;\n notifyUserIds?: string[];\n misfireGraceMinutes?: number;\n}\n\nexport type UpdateScheduleInput = Partial<CreateScheduleInput>;\n\n// --- Run / step event types ---\n\nexport const TERMINAL_RUN_STATUSES = new Set([\n 'passed',\n 'failed',\n 'cancelled',\n 'error',\n]);\n\nexport interface AuraCheckRun {\n id: string;\n projectId: string;\n name: string;\n status: string;\n state?: string;\n platform: string;\n testCaseIds?: string[];\n featureIds?: string[];\n startedAt?: string | null;\n completedAt?: string | null;\n reportUrl?: string | null;\n results?: unknown[];\n [k: string]: unknown;\n}\n\nexport interface CreateRunInput {\n name: string;\n testCaseIds?: string[];\n featureIds?: string[];\n platform?: 'web' | 'android' | 'ios';\n milestoneId?: string;\n configurationId?: string;\n tags?: string[];\n notes?: string;\n caseSelectionMode?: 'all' | 'select';\n runType?: string;\n browserEngine?: 'chrome' | 'edge';\n}\n\nexport interface StepEvent {\n id: string;\n attemptId: string;\n testRunId: string;\n testCaseId: string | null;\n stepIndex: number | null;\n stepType: string | null;\n stepPrompt: string | null;\n status: string;\n startedAt: string | null;\n completedAt: string | null;\n durationMs: number | null;\n error: string | null;\n screenshotUrl: string | null;\n notes: string | null;\n stallDiagnostics?: Record<string, unknown> | null;\n [k: string]: unknown;\n}\n\nexport interface CaseAttempt {\n id: string;\n testRunId: string;\n testCaseId: string;\n status: string;\n startedAt: string | null;\n completedAt: string | null;\n reportUrl?: string | null;\n [k: string]: unknown;\n}\n\nexport async function pingBaseUrl(\n baseUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<boolean> {\n try {\n const res = await fetchImpl(`${normalizeBaseUrl(baseUrl)}/api/auth/me`, {\n method: 'GET',\n });\n // 401 means server reachable but unauthenticated, which is fine\n return res.status >= 200 && res.status < 500;\n } catch {\n return false;\n }\n}\n","import type { AuraCheckApi, McpContext } from './api.js';\n\n/** Which runtime is calling a tool. Some tools exist on only one surface. */\nexport type Surface = 'remote' | 'local';\n\n/**\n * Per-call context every tool handler receives. Fetch-only: nothing here\n * touches `node:fs` or any Node-only API — the Worker and the local stdio\n * adapter both build one of these per call.\n */\nexport interface ToolCtx {\n api: AuraCheckApi;\n surface: Surface;\n /** The app's web base URL (for building run/project view links). */\n appUrl: string;\n /** Config value RENEWAL_URL; default `${appUrl}/admin/billing`. */\n renewalUrl: string;\n /**\n * Cached `/api/mcp/context` response for this call. Resolved once per\n * request by the host (Worker: per MCP call; local: per tool call, cheap\n * enough not to cache across calls) and handed to every tool so role\n * filtering and billing messages don't each re-fetch it.\n */\n account: McpContext;\n /** The project this call should operate on: explicit arg, else null. */\n projectId: string | null;\n /**\n * Platform to assume when a run/schedule-creating tool call omits one.\n * Local: the repo's `.sixseven/config.json` platform (pre-existing\n * behaviour). Remote has no such binding, so hosts pass `'web'`.\n */\n defaultPlatform?: 'web' | 'android' | 'ios';\n /**\n * Advisory \"current project\" set by `set_project`. Remote is stateless\n * (no Durable Object), so this is per-request only — it exists so a\n * single call can validate + confirm a choice, not to persist it. The\n * local adapter wires this to `.sixseven/config.json` itself.\n */\n onSetProject?: (projectId: string) => void | Promise<void>;\n /**\n * Caps `wait_for_run`'s polling window. Worker: 45s (§3.1 \"no wall-clock\n * limit while connected, but cap at 45s\"). Local: 300s (existing CLI\n * default — no behaviour change).\n */\n waitForRunMaxSec: number;\n}\n\n/** Resolve the project id for a project-scoped tool call. */\nexport function requireProjectId(\n ctx: Pick<ToolCtx, 'projectId'>,\n explicit?: string | null,\n): string {\n const id = explicit?.trim() || ctx.projectId;\n if (!id) {\n throw new Error(\n 'No AuraCheck project for this call: pass `projectId` (find it with list_projects), or call set_project first.',\n );\n }\n return id;\n}\n","/**\n * Turns an `ApiError` into a plain-language tool RESULT (never a thrown\n * error) so the model relays it instead of retrying blindly. Shapes follow\n * the message table in MCP-remote-research.md §5. A result carries\n * `blocked: true` instead of MCP's `isError`, because these are expected,\n * actionable answers — not failures of the tool call itself.\n */\nimport type { ApiError } from './api.js';\nimport type { ToolCtx } from './context.js';\n\nexport interface BlockedResult {\n blocked: true;\n message: string;\n next?: string;\n}\n\ninterface QuotaErrorBody {\n error?: string;\n isCompanyAdmin?: boolean;\n adminContact?: { name: string | null; email: string } | null;\n}\n\nfunction parseBody(bodyText: string): QuotaErrorBody {\n try {\n return JSON.parse(bodyText) as QuotaErrorBody;\n } catch {\n return {};\n }\n}\n\n/** `User.name` is nullable; fall back to the email so a message never prints \"null\". */\nfunction contactName(contact: { name: string | null; email: string }): string {\n return contact.name ?? contact.email;\n}\n\n/** Friendly labels for the capabilities a 403 can name. Keep in sync with db.ts ALL_CAPABILITIES. */\nconst CAPABILITY_LABELS: Record<string, string> = {\n viewProject: 'View project',\n viewReports: 'View reports',\n manageTestCases: 'Manage test cases',\n manageRuns: 'Manage runs',\n runTests: 'Run tests',\n manageProjectSetup: 'Manage project setup',\n manageBugs: 'Manage bugs',\n};\n\nfunction capabilityLabel(cap: string | null | undefined): string {\n if (!cap) return 'this action';\n return CAPABILITY_LABELS[cap] ?? cap;\n}\n\n/**\n * Map an `ApiError` plus the tool's declared `requires` capability into a\n * §5 message. Returns `null` for a status this table doesn't cover, so the\n * caller can fall back to throwing the raw error.\n */\nexport function mapApiError(\n err: ApiError,\n ctx: Pick<ToolCtx, 'account' | 'renewalUrl' | 'surface'>,\n requiresCapability?: string | null,\n): BlockedResult | null {\n const body = parseBody(err.bodyText);\n const account = ctx.account;\n\n switch (err.status) {\n case 402: {\n if (body.isCompanyAdmin ?? isCompanyAdminRole(account)) {\n return {\n blocked: true,\n message: `Your AuraCheck plan has ended, so new runs are paused. Your existing runs and reports are still available. Renew here: ${ctx.renewalUrl}`,\n };\n }\n const contact = body.adminContact ?? account?.adminContact ?? null;\n return {\n blocked: true,\n message: contact\n ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${contactName(contact)} (${contact.email}) to renew. Existing results are still available.`\n : \"Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin to renew. Existing results are still available.\",\n };\n }\n case 429: {\n const text = body.error ?? '';\n const isConcurrent = /concurrent|already in progress|1 at a time/i.test(\n text,\n );\n if (isConcurrent) {\n return {\n blocked: true,\n message:\n \"A run is already in progress (trials run 1 at a time). I'll wait for it to finish, then start yours.\",\n };\n }\n const isAdmin = body.isCompanyAdmin ?? isCompanyAdminRole(account);\n const limit = account?.subscription.runUsage?.dailyLimit;\n const limitClause = limit\n ? `Your trial allows ${limit} runs per day and today's are used up.`\n : \"Your trial's daily run cap is used up.\";\n const contact = body.adminContact ?? account?.adminContact ?? null;\n const actionClause = isAdmin\n ? `Upgrade to remove the daily cap: ${ctx.renewalUrl}`\n : contact\n ? `Ask ${contactName(contact)} to upgrade.`\n : 'Ask your admin to upgrade.';\n return {\n blocked: true,\n message: `${limitClause} It resets at 07:00 WIB. ${actionClause}`,\n };\n }\n case 403: {\n if (/project CI token/i.test(body.error ?? '')) {\n return {\n blocked: true,\n message:\n 'This token can only reach its own project. Sign in personally, or pass that projectId.',\n };\n }\n const roleLabel = account?.user.roleLabel ?? 'your role';\n return {\n blocked: true,\n message: `Your AuraCheck role (${roleLabel}) can't do that. Ask your admin to give you the '${capabilityLabel(requiresCapability)}' permission.`,\n };\n }\n case 401: {\n // Local keeps its existing behaviour: surface the raw ApiError (whose\n // message already carries the CLI's own sign-in hint via\n // `AuraCheckApi`'s `signInHint` option) as a real tool error, rather\n // than this remote-facing \"disconnected\" wording.\n if (ctx.surface === 'local') return null;\n return {\n blocked: true,\n message:\n 'This AI app was disconnected from AuraCheck. Reconnect it from the app’s connector settings.',\n };\n }\n default:\n return null;\n }\n}\n\nfunction isCompanyAdminRole(account: ToolCtx['account'] | undefined): boolean {\n const caps = account?.user.capabilities ?? [];\n // admin_company/super_admin always carry the full capability set in\n // practice; the role label is the more direct signal when present.\n const label = account?.user.roleLabel?.toLowerCase() ?? '';\n return label.includes('admin') || caps.includes('manageProjectSetup');\n}\n\n/**\n * Android/iOS runs 422 `run_from_desktop`: not an error, an instruction.\n * `next` tells the model what the person should do.\n */\nexport const MOBILE_RUN_NEXT_STEP =\n 'Ask the person to open this run in the AuraCheck desktop app with the Android device or emulator connected and click \"Run on local\" (iOS: macOS desktop app, \"Run on iOS\"). Then call wait_for_run: it waits while the run is pending.';\n\n/**\n * Pre-existing local CLI shape (`auracheck.execute_run`), kept as the\n * contract for both surfaces: `{started:false, status:'run_from_desktop',\n * runId, platform, runUrl, message, next}`, not the `blocked:true` shape\n * most other §5 messages use. `runId` comes from the caller, since the\n * server's 422 body doesn't echo it back.\n */\nexport interface RunFromDesktopAnswer {\n started: false;\n status: 'run_from_desktop';\n runId: string;\n platform: string | null;\n runUrl: string | null;\n message: string | null;\n next: string;\n}\n\nexport function runFromDesktopAnswer(\n err: ApiError,\n runId: string,\n): RunFromDesktopAnswer | null {\n if (err.status !== 422) return null;\n let body: Record<string, unknown> = {};\n try {\n body = JSON.parse(err.bodyText) as Record<string, unknown>;\n } catch {\n return null;\n }\n if (body.code !== 'run_from_desktop') return null;\n return {\n started: false,\n status: 'run_from_desktop',\n runId,\n platform: (body.platform as string | undefined) ?? null,\n runUrl: (body.runUrl as string | undefined) ?? null,\n message: (body.error as string | undefined) ?? null,\n next: MOBILE_RUN_NEXT_STEP,\n };\n}\n\n/** The unreachable-URL message (§5), used by create_project_from_url / test_my_flow. */\nexport function unreachableUrlMessage(url: string): BlockedResult {\n return {\n blocked: true,\n message: `AuraCheck's cloud can't reach ${url} (private network or localhost). Use the AuraCheck desktop app or the local MCP.`,\n };\n}\n\n/** Grace-period notice appended to account_status / run starts (§5). */\nexport function graceNotice(\n graceEnd: string | null,\n renewalUrl: string,\n): string {\n return `Heads-up: payment is overdue; runs keep working until ${graceEnd ?? 'the grace period ends'}. Renew here: ${renewalUrl}`;\n}\n","/**\n * Knowledge layer (§5): server `instructions` and prompts. English only —\n * the model may still answer the user in whatever language they used.\n */\n\nexport const SERVER_INSTRUCTIONS = `You are connected to AuraCheck, an AI testing service that runs real browser tests on the user's website.\nStart every conversation with account_status. It tells you the user's role, plan, days/runs left and their projects.\nTalk in outcomes, not YAML. Many users are not engineers. Say \"I'll check that new users can sign up\" — not\n\"I'll create a Midscene flow\". After a run, report: what passed, what failed in one sentence each, the likely cause,\nthe run link, and a screenshot for the first failure. Only show steps/YAML if the user asks.\nBefore writing or running any test: (1) find the project (list_projects; ask if more than one fits);\n(2) PRELATION — decide whether the test needs a starting state (logged in, a specific page, seeded data). If yes,\nlist_testcases and reuse an existing setup case (e.g. \"Login\") via prelationTestCaseId. Never copy login steps into a\ntest. If none exists, ask the user for the test account to use, create the setup case first, then reference it.\nAuraCheck runs the setup case automatically — never add it to a run yourself. (3) check list_testcases for a duplicate.\nFor \"test this on my site\" requests use test_my_flow; it shows a plan first — confirm it with the user before running.\nRuns take minutes: start the run, give the link, then call wait_for_run; if it returns pollAgain, tell the user it's\nstill running and call it again (or come back later — they also get an email).\nNever ask for or repeat passwords, PINs or OTP codes in chat. Test accounts and secrets are stored in AuraCheck\n(Project → Test accounts); tell the user to add them there. Tool results never contain secret values.\nDelete tools are dry-run first: show what will be deleted and get an explicit \"yes\" before confirm:true.\nIf a tool says the plan is read-only or the trial limit is reached, relay its message and next step exactly; don't retry.\nApps on localhost, an office VPN or an intranet can't be reached by AuraCheck's cloud runner: suggest the AuraCheck\ndesktop app or the local MCP (npx @auracheck-ai/mcp). Android/iOS runs only start from the desktop app on the user's device.`;\n\n/** Appended locally only: the local server also exposes fs-backed code tools. */\nexport const LOCAL_CODE_TOOLS_PARAGRAPH = `This server also runs on your machine, so it additionally offers read_code, list_dir and search_code over the developer's repo (within configured codeRoots) — use them to understand routes, components, validators and fixtures before generating a testcase. It also offers login, logout and bind_project for local sign-in and project binding; account_status/whoami work here too.`;\n\nexport function serverInstructions(surface: 'remote' | 'local'): string {\n return surface === 'local'\n ? `${SERVER_INSTRUCTIONS}\\n\\n${LOCAL_CODE_TOOLS_PARAGRAPH}`\n : SERVER_INSTRUCTIONS;\n}\n\nexport const WRITE_TESTCASE_PROMPT = [\n 'Before calling create_testcase, check:',\n '- Prelation: does this case need a starting state (logged in, specific page, seeded data)? If so, find or create a setup case and set prelationTestCaseId instead of copying its steps in.',\n '- Reuse the setup case; never duplicate a login flow across cases.',\n '- Ask the user for the test account NAME to use, never the password — passwords live in AuraCheck (Project → Test accounts).',\n '- Platform: web, android, or ios? Matches the project/feature this case belongs to?',\n '- Steps: a non-empty Midscene flow (array or tasks[] YAML/JSON) — never an empty flow.',\n '- Expected result: is it stated, so a run that technically \"passes\" but does the wrong thing still gets caught?',\n '- executionType: automation (runs in CI/scheduled runs) or manual (a human does it, excluded from automation runs)?',\n '- Is there already a similar case (list_testcases) this would duplicate?',\n].join('\\n');\n\nexport const RUN_AND_EXPLAIN_PROMPT =\n 'Pick or create the cases → start_run → share link → wait_for_run until terminal → run_summary → for each failure get_evidence + one screenshot → explain in ≤5 bullets: what broke, where, likely bug vs. test issue, suggested fix/next step.';\n\nexport const ONBOARDING_PROMPT =\n 'account_status → if no project: ask for the website URL → create_project_from_url (or tell non-admins to ask their admin) → suggest 3 starter flows (sign-up, login, main purchase/contact form) → test_my_flow for the first one.';\n\nexport interface PromptDef {\n name: string;\n description: string;\n text: string;\n}\n\nexport const PROMPTS: PromptDef[] = [\n {\n name: 'write_testcase',\n description:\n 'Checklist to run through before authoring a new AuraCheck testcase.',\n text: WRITE_TESTCASE_PROMPT,\n },\n {\n name: 'run_and_explain',\n description:\n 'Run one or more testcases and explain the result in plain language.',\n text: RUN_AND_EXPLAIN_PROMPT,\n },\n {\n name: 'onboarding',\n description: 'First-run flow for a brand-new AuraCheck connection.',\n text: ONBOARDING_PROMPT,\n },\n];\n","import { zodToJsonSchema } from 'zod-to-json-schema';\nimport { ApiError } from './api.js';\nimport type { ToolCtx } from './context.js';\nimport { mapApiError } from './errors.js';\nimport { stripSecrets } from './secrets.js';\nimport { ACCOUNT_TOOLS } from './tools/account.js';\nimport { BUG_TOOLS } from './tools/bugs.js';\nimport { EXPLORATION_TOOLS } from './tools/exploration.js';\nimport { FEATURE_TOOLS } from './tools/features.js';\nimport { RUN_TOOLS } from './tools/runs.js';\nimport { SCHEDULE_TOOLS } from './tools/schedules.js';\nimport { TEST_MY_FLOW_TOOLS } from './tools/test-my-flow.js';\nimport { TESTCASE_TOOLS } from './tools/testcases.js';\nimport type { ToolDef } from './types.js';\n\n/**\n * Every tool mcp-core knows about, across both surfaces. Deliberately\n * framework-agnostic: this module never imports an MCP SDK, so it works\n * the same way whether the caller is the SDK v2 `McpServer` the Worker uses\n * or the SDK v1 `Server` the local stdio adapter still pins (§3.3 — local\n * upgrades to v2 later, together with the Worker, not as part of this\n * package).\n */\nexport const ALL_TOOLS: ToolDef[] = [\n ...ACCOUNT_TOOLS,\n ...FEATURE_TOOLS,\n ...TESTCASE_TOOLS,\n ...RUN_TOOLS,\n ...SCHEDULE_TOOLS,\n ...EXPLORATION_TOOLS,\n ...BUG_TOOLS,\n ...TEST_MY_FLOW_TOOLS,\n];\n\nconst TOOLS_BY_NAME = new Map(ALL_TOOLS.map((t) => [t.name, t]));\n\nexport function getTool(name: string): ToolDef | undefined {\n return TOOLS_BY_NAME.get(name);\n}\n\n/** A tool's locally-advertised name (without the `auracheck.` prefix). */\nexport function localName(t: ToolDef): string {\n return t.localAlias ?? t.name;\n}\n\nconst TOOLS_BY_LOCAL_NAME = new Map(ALL_TOOLS.map((t) => [localName(t), t]));\n\n/** Reverse of {@link localName}: resolve a bare local tool name back to its `ToolDef`. */\nexport function getToolByLocalName(name: string): ToolDef | undefined {\n return TOOLS_BY_LOCAL_NAME.get(name);\n}\n\n/**\n * Tools visible to this caller: right surface, and (when signed in) the\n * capability it `requires` is in `account.user.capabilities`. A tool with\n * `requires: null` is visible to everyone. (§3.4, §4 \"Perm\" column.)\n */\nexport function filterTools(\n ctx: Pick<ToolCtx, 'surface' | 'account'>,\n): ToolDef[] {\n const caps = new Set(ctx.account.user.capabilities);\n return ALL_TOOLS.filter(\n (t) =>\n t.surfaces.includes(ctx.surface) &&\n (t.requires === null || caps.has(t.requires)),\n );\n}\n\nexport interface ToolDescriptor {\n name: string;\n title: string;\n description: string;\n inputSchema: Record<string, unknown>;\n annotations?: ToolDef['annotations'];\n}\n\n/** JSON-Schema tool descriptors for `tools/list`, filtered for this caller. */\nexport function listToolDescriptors(\n ctx: Pick<ToolCtx, 'surface' | 'account'>,\n): ToolDescriptor[] {\n return filterTools(ctx).map((t) => ({\n name: t.name,\n title: t.title,\n description: t.description,\n inputSchema: zodToJsonSchema(t.input, { target: 'jsonSchema7' }) as Record<\n string,\n unknown\n >,\n annotations: t.annotations,\n }));\n}\n\nexport type CallResult =\n | { ok: true; result: unknown }\n | { ok: false; error: string };\n\n/**\n * Run one tool call end to end: look up, capability-check, validate args,\n * invoke the handler, map a known `ApiError` into a §5 blocked result\n * instead of throwing, and strip secrets from whatever goes back. Used by\n * both the Worker and the local stdio adapter so this behaviour — not just\n * the tool metadata — stays identical across surfaces.\n */\nexport async function callTool(\n name: string,\n rawArgs: unknown,\n ctx: ToolCtx,\n): Promise<CallResult> {\n const tool = getTool(name);\n if (!tool) {\n return { ok: false, error: `Unknown tool: ${name}` };\n }\n if (!tool.surfaces.includes(ctx.surface)) {\n return {\n ok: false,\n error: `Tool ${name} is not available on this surface.`,\n };\n }\n if (tool.requires && !ctx.account.user.capabilities.includes(tool.requires)) {\n const roleLabel = ctx.account.user.roleLabel;\n return {\n ok: false,\n error: `Your AuraCheck role (${roleLabel}) can't use ${name}. Ask your admin for the '${tool.requires}' permission.`,\n };\n }\n\n let args: unknown;\n try {\n args = tool.input.parse(rawArgs ?? {});\n } catch (err: any) {\n return {\n ok: false,\n error: `Invalid arguments for ${name}: ${err?.message ?? String(err)}`,\n };\n }\n\n try {\n const result = await tool.handler(args, ctx);\n return { ok: true, result: stripSecrets(result) };\n } catch (err) {\n if (err instanceof ApiError) {\n const mapped = mapApiError(err, ctx, tool.requires);\n if (mapped) return { ok: true, result: mapped };\n }\n return {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n","/**\n * Secret-stripping allowlist (§3.3, coverage checklist \"Secrets/PII\").\n *\n * `redactConfigSecretsInResponses` on the server masks config vars only for\n * users without `manageConfigurations`. mcp-core goes further and strips\n * for EVERY caller, on every tool result, regardless of role — an MCP\n * client (or a transcript of one) should never see a password, PIN, OTP or\n * raw token even if the signed-in user could see it in the web app.\n *\n * Implementation is a deny-list of key names (case-insensitive, substring\n * match on a conservative set) applied recursively to any JSON-shaped tool\n * result. A deny-list is used rather than a per-field allowlist per tool so\n * a new field on an existing API response is redacted by default instead of\n * leaking until someone remembers to allowlist it.\n */\n\nconst DENY_KEY_PATTERNS: RegExp[] = [\n /password/i,\n /pin$/i,\n /^pin/i,\n /otp/i,\n /secret/i,\n /token/i,\n /api[_-]?key/i,\n /authorization/i,\n /cookie/i,\n /credential/i,\n // Config-var payloads the server itself treats as secret.\n /^variables$/i,\n];\n\nconst REDACTED = '[redacted]';\nconst MAX_DEPTH = 12;\n\nfunction isSecretKey(key: string): boolean {\n return DENY_KEY_PATTERNS.some((re) => re.test(key));\n}\n\nexport function stripSecrets<T>(value: T, depth = 0): T {\n if (depth > MAX_DEPTH || value === null || value === undefined) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v) => stripSecrets(v, depth + 1)) as unknown as T;\n }\n if (typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (isSecretKey(k)) {\n out[k] = REDACTED;\n } else {\n out[k] = stripSecrets(v, depth + 1);\n }\n }\n return out as unknown as T;\n }\n return value;\n}\n","import { z } from 'zod';\nimport { ApiError } from '../api.js';\nimport { requireProjectId } from '../context.js';\nimport { graceNotice } from '../errors.js';\nimport { defineTool } from '../types.js';\n\n/**\n * `account_status` (≈ whoami): who am I, my role, my company's plan/trial,\n * days and runs left, what I can do. Built on `/api/mcp/context` (§3.4),\n * which the host already fetched into `ctx.account` for this call.\n */\nexport const accountStatus = defineTool({\n name: 'account_status',\n title: 'Account status',\n description:\n \"Who the signed-in user is, their role, their company's plan/trial state, days and runs left, and the projects they can reach. Call this first in every conversation.\",\n input: z.object({}),\n requires: null,\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async (_args, ctx) => {\n const { account } = ctx;\n const sub = account.subscription;\n const lines: string[] = [];\n if (sub.inGrace) {\n lines.push(graceNotice(sub.graceEnd ?? null, ctx.renewalUrl));\n } else if (!sub.readOnly && sub.runUsage) {\n lines.push(\n `Trial: ${sub.daysLeft ?? '?'} days left, ${Math.max(sub.runUsage.dailyLimit - sub.runUsage.dailyCount, 0)} runs left today (${Math.max(sub.runUsage.monthlyLimit - sub.runUsage.monthlyCount, 0)} this month).`,\n );\n } else if (sub.readOnly) {\n lines.push(\n account.adminContact\n ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${account.adminContact.name ?? account.adminContact.email} (${account.adminContact.email}) to renew. Existing results are still available.`\n : `Your AuraCheck plan has ended, so new runs are paused. Existing results are still available. Renew here: ${ctx.renewalUrl}`,\n );\n }\n return {\n user: account.user,\n company: account.company,\n subscription: sub,\n projects: account.projects,\n renewalUrl: ctx.renewalUrl,\n minLocalMcp: account.minLocalMcp,\n note: lines.join(' ') || null,\n };\n },\n});\n\nexport const listProjects = defineTool({\n name: 'list_projects',\n title: 'List projects',\n description:\n 'List the AuraCheck projects this sign-in can reach (id, name, platforms, defaultConfigurationId). Pass a project id as `projectId` to any project tool to work outside the currently set project.',\n input: z.object({}),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async (_args, ctx) => {\n const projects = await ctx.api.listProjects();\n return projects.map((p) => ({\n id: p.id,\n name: p.name,\n companyId: p.companyId,\n platforms: p.platforms,\n defaultConfigurationId: p.defaultConfigurationId ?? null,\n }));\n },\n});\n\n/**\n * Advisory only (§3.3): the Worker is stateless (no Durable Object session),\n * so this cannot persist a \"current project\" across calls by itself — every\n * project tool still takes `projectId`. It exists to (a) validate the id up\n * front and (b) let the local adapter persist it into\n * `.sixseven/config.json` via `ctx.onSetProject`.\n */\nexport const setProject = defineTool({\n name: 'set_project',\n title: 'Set project',\n description:\n 'Confirm an AuraCheck project id is reachable and set it as the project for this session. Advisory: still pass `projectId` explicitly to tools when working across more than one project in the same conversation.',\n input: z.object({ projectId: z.string().min(1) }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId }, ctx) => {\n const projects = await ctx.api.listProjects();\n const project = projects.find((p) => p.id === projectId);\n if (!project) {\n throw new Error(\n `${projectId} is not in the list of projects this sign-in can reach. Call list_projects.`,\n );\n }\n await ctx.onSetProject?.(projectId);\n return {\n ok: true,\n projectId,\n project: { id: project.id, name: project.name },\n };\n },\n});\n\nexport const createProjectFromUrl = defineTool({\n name: 'create_project_from_url',\n title: 'Create project from URL',\n description:\n '\"Start testing my website\": create a new AuraCheck project with the given URL as its web environment. Needs the manageProjectSetup permission.',\n input: z.object({\n name: z.string().min(1),\n targetUrl: z.string().url(),\n description: z.string().optional(),\n }),\n requires: 'manageProjectSetup',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async (args, ctx) => {\n try {\n const project = await ctx.api.createProject({\n name: args.name,\n targetUrl: args.targetUrl,\n platforms: ['web'],\n description: args.description,\n });\n await ctx.onSetProject?.(project.id);\n return {\n ok: true,\n project: { id: project.id, name: project.name },\n nextStep:\n 'Suggest 3 starter flows (sign-up, login, main purchase/contact form), then use test_my_flow for the first one.',\n };\n } catch (err) {\n // The server's own reachability probe (probe-url) runs during\n // project creation server-side; a network-shaped 400/422 from it\n // reads the same as \"can't reach this URL\" to the model.\n if (\n err instanceof ApiError &&\n /unreachable|ENOTFOUND|ECONNREFUSED/i.test(err.message)\n ) {\n return {\n blocked: true,\n message: `AuraCheck's cloud can't reach ${args.targetUrl} (private network or localhost). Use the AuraCheck desktop app or the local MCP.`,\n };\n }\n throw err;\n }\n },\n});\n\nexport const ACCOUNT_TOOLS = [\n accountStatus,\n listProjects,\n setProject,\n createProjectFromUrl,\n];\n\n// re-exported for tools that need to resolve a project id consistently\nexport { requireProjectId };\n","import type { z } from 'zod';\nimport type { Surface, ToolCtx } from './context.js';\n\n/**\n * Capability names checked server-side (db.ts `ALL_CAPABILITIES`). A tool\n * whose `requires` capability is missing from `account.user.capabilities`\n * is hidden from tools/list for that caller (§3.4, §4 \"Perm\" column).\n * `null` means every signed-in caller can see the tool.\n */\nexport type Capability =\n | 'viewProject'\n | 'viewReports'\n | 'manageTestCases'\n | 'manageRuns'\n | 'runTests'\n | 'manageProjectSetup'\n | 'manageBugs';\n\n/**\n * R = always allowed (viewing is never gated). W = allowed even when\n * read-only. Run = blocked when the account is read-only and counts\n * against the trial run cap (§4 \"Billing\" column).\n */\nexport type BillingBehaviour = 'read' | 'write' | 'run';\n\nexport interface ToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n}\n\nexport interface ToolDef<Input = any> {\n /** No prefix, no dots — the remote name (§3.3). Local adds `auracheck.`. */\n name: string;\n /**\n * A couple of tools kept their pre-existing local name when the doc\n * renamed the remote one for client compatibility (`start_run` vs. the\n * CLI's long-standing `execute_run`; `run_summary` vs. `get_run_report`).\n * When set, the local surface advertises `auracheck.<localAlias>` instead\n * of `auracheck.<name>` — \"no behaviour change\" for existing CLI users.\n */\n localAlias?: string;\n title: string;\n description: string;\n input: z.ZodType<Input>;\n annotations?: ToolAnnotations;\n requires: Capability | null;\n billing: BillingBehaviour;\n /** Which surface(s) advertise this tool. Both unless noted otherwise. */\n surfaces: Surface[];\n handler: (args: Input, ctx: ToolCtx) => Promise<unknown>;\n}\n\nexport function defineTool<Input>(def: ToolDef<Input>): ToolDef<Input> {\n return def;\n}\n","import { z } from 'zod';\nimport { requireProjectId } from '../context.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\nexport const fileBug = defineTool({\n name: 'file_bug',\n title: 'File bug',\n description:\n \"Open an issue report (bug) against a project. Use this only after the auto-fix loop has identified a real application defect (not a flaky testcase). Severity must be 'critical', 'high', 'medium', or 'low'. Pass evidence URLs (screenshotUrl from get_evidence) in evidences[].\",\n input: z.object({\n projectId: PROJECT_ID,\n title: z.string().min(1).max(200),\n severity: z.enum(['critical', 'high', 'medium', 'low']),\n description: z.string().optional(),\n pageUrl: z.string().optional(),\n evidences: z.array(z.string()).optional(),\n }),\n // manageBugs is proposed (§4): the route itself only checks requireAuth\n // today, so this is a client-side-only gate until the server catches up.\n requires: 'manageBugs',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, ...args }, ctx) =>\n ctx.api.createIssueReport({\n ...args,\n projectId: requireProjectId(ctx, projectId),\n }),\n});\n\nexport const listBugs = defineTool({\n name: 'list_bugs',\n title: 'List bugs',\n description:\n 'List issue reports (bugs) for a project. Use to check whether a defect has already been reported before filing a new one.',\n input: z.object({ projectId: PROJECT_ID }),\n requires: 'viewReports',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId }, ctx) =>\n ctx.api.listIssueReports(requireProjectId(ctx, projectId)),\n});\n\nexport const getBug = defineTool({\n name: 'get_bug',\n title: 'Get bug',\n description: 'Fetch a single issue report by id.',\n input: z.object({ id: z.string().min(1) }),\n requires: 'viewReports',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ id }, ctx) => ctx.api.getIssueReport(id),\n});\n\nexport const BUG_TOOLS = [fileBug, listBugs, getBug];\n","import { z } from 'zod';\nimport { requireProjectId } from '../context.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\nexport const startExploration = defineTool({\n name: 'start_exploration',\n title: 'Start exploration',\n description:\n \"Trigger AuraCheck's crawler on a set of seed URLs for a project. Returns a snapshot immediately (job runs in background); poll with get_exploration. One job per project at a time — calling this while a job is already running returns the live snapshot.\",\n input: z.object({\n projectId: PROJECT_ID,\n seedUrls: z.array(z.string().url()).min(1),\n configurationId: z.string().optional(),\n maxDepth: z.number().int().positive().max(20).optional(),\n maxPages: z.number().int().positive().max(500).optional(),\n }),\n requires: 'runTests',\n billing: 'run',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, ...args }, ctx) =>\n ctx.api.startExploration(requireProjectId(ctx, projectId), args),\n});\n\nexport const getExploration = defineTool({\n name: 'get_exploration',\n title: 'Get exploration',\n description:\n 'Return the latest exploration snapshot for a project (or null if none has ever run). Shape: { jobId, status, visited, anchorsUpserted, loggedIn, errors[] }. Use to await completion before generating testcases that depend on discovered routes/anchors.',\n input: z.object({ projectId: PROJECT_ID }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId }, ctx) =>\n ctx.api.getExploration(requireProjectId(ctx, projectId)),\n});\n\nexport const EXPLORATION_TOOLS = [startExploration, getExploration];\n","import { z } from 'zod';\nimport { ApiError } from '../api.js';\nimport { requireProjectId } from '../context.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\nexport const listFeatures = defineTool({\n name: 'list_features',\n title: 'List features',\n description:\n 'List features (groups of testcases) for a project. Each feature has an id and a name. Pick the most relevant feature id before creating a testcase.',\n input: z.object({ projectId: PROJECT_ID }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) =>\n ctx.api.listFeatures(requireProjectId(ctx, args.projectId)),\n});\n\nexport const createFeature = defineTool({\n name: 'create_feature',\n title: 'Create feature',\n description:\n 'Create a new feature in a project. Use when no existing feature fits the testcase you are about to create.',\n input: z.object({\n projectId: PROJECT_ID,\n name: z.string().min(1),\n path: z.string().optional(),\n description: z.string().optional(),\n prdContent: z.string().optional(),\n }),\n requires: 'manageTestCases',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, ...rest }, ctx) =>\n ctx.api.createFeature(requireProjectId(ctx, projectId), rest),\n});\n\nexport const deleteFeature = defineTool({\n name: 'delete_feature',\n title: 'Delete feature',\n description:\n \"Delete a feature. Requires manageTestCases. Without `confirm: true` this is a DRY RUN — it only shows the feature's name and how many testcases it holds; nothing is deleted on the first call. Testcases linked to a run are soft-deleted (reparented, run history kept); unlinked ones are removed permanently. Pass `cascade: true` to also remove sub-features.\",\n input: z.object({\n projectId: PROJECT_ID,\n featureId: z.string().min(1),\n cascade: z.boolean().optional(),\n confirm: z.boolean().optional(),\n }),\n requires: 'manageTestCases',\n billing: 'write',\n surfaces: ['remote', 'local'],\n annotations: { destructiveHint: true },\n handler: async ({ projectId, featureId, cascade, confirm }, ctx) => {\n const pid = requireProjectId(ctx, projectId);\n try {\n const feature = await ctx.api.getFeature(featureId, pid);\n if (!feature) {\n throw new Error(`Delete failed (404): feature ${featureId} not found.`);\n }\n if (!confirm) {\n const cases = await ctx.api\n .listTestCasesByFeature(featureId)\n .catch(() => []);\n return {\n dryRun: true,\n feature: { id: feature.id, name: feature.name },\n testCaseCount: cases.length,\n cascade: !!cascade,\n note: 'Testcases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete.',\n };\n }\n await ctx.api.deleteFeature(featureId, cascade);\n return { dryRun: false, deletedFeatureId: featureId, cascade: !!cascade };\n } catch (err) {\n if (err instanceof ApiError && err.status === 403) {\n throw new Error(\n \"Delete failed (403): this sign-in lacks manageTestCases, or this feature belongs to a project it can't reach.\",\n );\n }\n if (err instanceof ApiError && err.status === 404) {\n throw new Error(`Delete failed (404): feature ${featureId} not found.`);\n }\n throw err;\n }\n },\n});\n\nexport const FEATURE_TOOLS = [listFeatures, createFeature, deleteFeature];\n","import { z } from 'zod';\nimport { type StepEvent, TERMINAL_RUN_STATUSES } from '../api.js';\nimport { ApiError } from '../api.js';\nimport { requireProjectId } from '../context.js';\nimport { mapApiError, runFromDesktopAnswer } from '../errors.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\n/** The run page in the web app (runs live under their project). */\nfunction runViewUrl(appUrl: string, runId: string, projectId?: string | null) {\n return projectId\n ? `${appUrl}/projects/${projectId}/runs/${runId}`\n : `${appUrl}/runs/${runId}`;\n}\n\nexport const listRuns = defineTool({\n name: 'list_runs',\n title: 'List runs',\n description:\n 'List recent runs for a project, optionally filtered by platform.',\n input: z.object({\n projectId: PROJECT_ID,\n platform: z.enum(['web', 'android', 'ios']).optional(),\n }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId, platform }, ctx) =>\n ctx.api.listRuns(requireProjectId(ctx, projectId), platform),\n});\n\nexport const createRun = defineTool({\n name: 'create_run',\n title: 'Create run',\n description:\n 'Create a new run for one or more testcases. Defaults: caseSelectionMode=\"select\". Returns the created run object including its id. An android/ios run is created here as usual, but only a person can start it: in the AuraCheck desktop app on their device.',\n input: z.object({\n projectId: PROJECT_ID,\n name: z.string().min(1),\n testCaseIds: z.array(z.string()).optional(),\n featureIds: z.array(z.string()).optional(),\n platform: z.enum(['web', 'android', 'ios']).optional(),\n caseSelectionMode: z.enum(['all', 'select']).optional(),\n configurationId: z.string().optional(),\n milestoneId: z.string().optional(),\n tags: z.array(z.string()).optional(),\n notes: z.string().optional(),\n browserEngine: z.enum(['chrome', 'edge']).optional(),\n }),\n requires: 'runTests',\n billing: 'run',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, ...args }, ctx) => {\n const pid = requireProjectId(ctx, projectId);\n const body = {\n ...args,\n platform: args.platform ?? ctx.defaultPlatform ?? 'web',\n caseSelectionMode:\n args.caseSelectionMode ??\n (args.testCaseIds?.length ? ('select' as const) : ('all' as const)),\n };\n try {\n return await ctx.api.createRun(pid, body);\n } catch (err) {\n if (err instanceof ApiError) {\n const mapped = mapApiError(err, ctx, 'runTests');\n if (mapped) return mapped;\n }\n throw err;\n }\n },\n});\n\n/** `start_run` is `execute_run`'s remote-facing name (§4 \"start_run (= execute)\"). */\nexport const startRun = defineTool({\n name: 'start_run',\n // Existing local CLI name, kept so `auracheck.execute_run` doesn't break.\n localAlias: 'execute_run',\n title: 'Start run',\n description:\n \"Trigger execution of an existing WEB run. Fire-and-forget: the runner state lives in AuraCheck. Use wait_for_run to await terminal status. Android/iOS runs never execute on AuraCheck's servers: for those this returns a blocked result telling the person to open the run in the desktop app and click Run on local / Run on iOS.\",\n input: z.object({ runId: z.string().min(1) }),\n requires: 'runTests',\n billing: 'run',\n surfaces: ['remote', 'local'],\n handler: async ({ runId }, ctx) => {\n try {\n return await ctx.api.executeRun(runId);\n } catch (err) {\n if (err instanceof ApiError) {\n const answer =\n runFromDesktopAnswer(err, runId) ?? mapApiError(err, ctx, 'runTests');\n if (answer) return answer;\n }\n throw err;\n }\n },\n});\n\nexport const cancelRun = defineTool({\n name: 'cancel_run',\n title: 'Cancel run',\n description:\n 'Cancel an in-flight run. Idempotent for queued runs; for inline runs the cancel may take effect at the next case boundary.',\n input: z.object({ runId: z.string().min(1) }),\n requires: 'manageRuns',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ runId }, ctx) => ctx.api.cancelRun(runId),\n});\n\nexport const waitForRun = defineTool({\n name: 'wait_for_run',\n title: 'Wait for run',\n description:\n 'Poll a run until it reaches a terminal status (passed/failed/cancelled/error) or the timeout elapses. Returns the final run object plus a summary of per-case statuses. Remote caps the wait at 45s and returns `pollAgain:true` if still running — call it again (the user also gets an email when the run finishes). Local can wait up to 300s. An android/ios run stays pending until a person starts it in the AuraCheck desktop app.',\n input: z.object({\n runId: z.string().min(1),\n timeoutSec: z.number().int().positive().max(3600).optional(),\n pollMs: z.number().int().positive().max(30_000).optional(),\n }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n const requested = args.timeoutSec ?? ctx.waitForRunMaxSec;\n const timeoutMs = Math.min(requested, ctx.waitForRunMaxSec) * 1000;\n const pollMs = args.pollMs ?? 3000;\n const start = Date.now();\n let last = await ctx.api.getRun(args.runId);\n while (\n !TERMINAL_RUN_STATUSES.has(last.status) &&\n Date.now() - start < timeoutMs\n ) {\n await new Promise((resolve) => setTimeout(resolve, pollMs));\n last = await ctx.api.getRun(args.runId);\n }\n const terminal = TERMINAL_RUN_STATUSES.has(last.status);\n const attempts = await ctx.api\n .listRunCaseAttempts(args.runId)\n .catch(() => ({ attempts: [] }));\n const summary = attempts.attempts.reduce<Record<string, number>>(\n (acc, a) => {\n acc[a.status] = (acc[a.status] ?? 0) + 1;\n return acc;\n },\n {},\n );\n const pendingMobile =\n !terminal &&\n last.status === 'pending' &&\n (last.platform === 'android' || last.platform === 'ios');\n return {\n terminal,\n pollAgain: !terminal,\n elapsedMs: Date.now() - start,\n runId: args.runId,\n status: last.status,\n reportUrl: last.reportUrl ?? null,\n viewUrl: runViewUrl(ctx.appUrl, args.runId, last.projectId),\n completedAt: last.completedAt ?? null,\n caseStatusSummary: summary,\n ...(pendingMobile\n ? {\n message:\n 'Not started yet: Android/iOS runs are started by a person in the AuraCheck desktop app on their own device.',\n }\n : {}),\n run: last,\n };\n },\n});\n\nexport const getRun = defineTool({\n name: 'get_run',\n title: 'Get run',\n description:\n 'Fetch a single run by id including current status, started/completed timestamps, and reportUrl when available.',\n input: z.object({ runId: z.string().min(1) }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ runId }, ctx) => ctx.api.getRun(runId),\n});\n\nexport const runSummary = defineTool({\n name: 'run_summary',\n // Existing local CLI name, kept so `auracheck.get_run_report` doesn't break.\n localAlias: 'get_run_report',\n title: 'Run summary',\n description:\n 'Results of a run as the Run Report groups them: case counts (passed/failed/skipped/pending) plus buckets — potential bugs (with bug report, severity), script issues, blocked cases and passed cases. Read-only.',\n input: z.object({ runId: z.string().min(1) }),\n requires: 'viewReports',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ runId }, ctx) => {\n const [run, counts, buckets] = await Promise.all([\n ctx.api.getRun(runId),\n ctx.api.getRunCaseStatusCounts(runId),\n ctx.api.getRunReportBuckets(runId),\n ]);\n return {\n run: {\n id: run.id,\n name: run.name,\n status: run.status,\n reportUrl: (run as Record<string, unknown>).reportUrl ?? null,\n },\n counts,\n ...buckets,\n };\n },\n});\n\nexport const listRunTestcases = defineTool({\n name: 'list_run_testcases',\n title: 'List run testcases',\n description: 'List the testcases attached to a specific run.',\n input: z.object({ runId: z.string().min(1) }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ runId }, ctx) => ctx.api.listRunTestCases(runId),\n});\n\nexport const getEvidence = defineTool({\n name: 'get_evidence',\n title: 'Get evidence',\n description:\n 'Aggregate evidence for a finished (or in-progress) run: per-case attempts, latest step events, failed-step screenshots and error messages, and the AuraCheck report URL. A failed step that hung also carries stallDiagnostics. Filter by caseId to narrow scope. Use after wait_for_run to diagnose failures.',\n input: z.object({\n runId: z.string().min(1),\n caseId: z.string().optional(),\n maxEventsPerCase: z.number().int().positive().max(200).optional(),\n }),\n requires: 'viewReports',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n const max = args.maxEventsPerCase ?? 20;\n const [run, attemptsResp, eventsResp, runCases] = await Promise.all([\n ctx.api.getRun(args.runId),\n ctx.api.listRunCaseAttempts(args.runId),\n ctx.api.listRunStepEvents(args.runId, args.caseId),\n ctx.api.listRunTestCases(args.runId).catch(() => []),\n ]);\n\n const caseNameById = new Map(runCases.map((c) => [c.id, c.name]));\n const allEvents: StepEvent[] = eventsResp.events ?? [];\n const eventsByCase = new Map<string, StepEvent[]>();\n for (const e of allEvents) {\n const key = e.testCaseId ?? '__unbound__';\n if (args.caseId && key !== args.caseId) continue;\n const arr = eventsByCase.get(key) ?? [];\n arr.push(e);\n eventsByCase.set(key, arr);\n }\n\n const attempts = (attemptsResp.attempts ?? []).filter(\n (a) => !args.caseId || a.testCaseId === args.caseId,\n );\n\n const cases = attempts.map((attempt) => {\n const events = (eventsByCase.get(attempt.testCaseId) ?? [])\n .slice()\n .sort((a, b) => (a.stepIndex ?? 0) - (b.stepIndex ?? 0))\n .slice(0, max);\n const failedSteps = events.filter(\n (e) => e.status === 'failed' || e.error,\n );\n return {\n testCaseId: attempt.testCaseId,\n testCaseName: caseNameById.get(attempt.testCaseId) ?? null,\n attemptId: attempt.id,\n attemptStatus: attempt.status,\n attemptReportUrl: attempt.reportUrl ?? null,\n startedAt: attempt.startedAt,\n completedAt: attempt.completedAt,\n stepEvents: events.map((e) => ({\n stepIndex: e.stepIndex,\n stepType: e.stepType,\n stepPrompt: e.stepPrompt,\n status: e.status,\n durationMs: e.durationMs,\n error: e.error,\n screenshotUrl: e.screenshotUrl,\n notes: e.notes,\n })),\n failedSteps: failedSteps.map((e) => ({\n stepIndex: e.stepIndex,\n stepType: e.stepType,\n error: e.error,\n screenshotUrl: e.screenshotUrl,\n stallDiagnostics: e.stallDiagnostics ?? null,\n })),\n };\n });\n\n return {\n runId: args.runId,\n status: run.status,\n platform: run.platform,\n reportUrl: run.reportUrl ?? null,\n viewUrl: runViewUrl(ctx.appUrl, args.runId),\n cases,\n totals: {\n caseCount: cases.length,\n failedCaseCount: cases.filter((c) => c.attemptStatus === 'failed')\n .length,\n failedStepCount: cases.reduce((n, c) => n + c.failedSteps.length, 0),\n },\n };\n },\n});\n\n/**\n * Binary marker a host unwraps: the Worker returns MCP `image` content, the\n * local stdio adapter writes the bytes to a temp file (fs lives there, not\n * in mcp-core) and returns the path, matching the CLI's previous behaviour.\n */\nexport interface BinaryResult {\n __binary: true;\n bytes: Uint8Array;\n contentType: string;\n sourceUrl: string;\n}\n\nexport const getScreenshot = defineTool<{ url: string }>({\n name: 'get_screenshot',\n title: 'Get screenshot',\n description:\n \"Fetch a run screenshot (or any authenticated blob) so it can actually be SEEN. Pass a `screenshotUrl` straight from get_evidence. Remote returns it as inline MCP image content; local writes it to a file and returns the path. Reach for it whenever a failure's cause is visual.\",\n input: z.object({\n url: z\n .string()\n .min(1)\n .describe(\n \"screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host.\",\n ),\n }),\n requires: 'viewReports',\n billing: 'read',\n // Local keeps its pre-existing, richer implementation (optional outPath,\n // writes the file itself — mcp-core has no fs) in packages/cli directly;\n // this one only ever runs on the Worker.\n surfaces: ['remote'],\n annotations: { readOnlyHint: true },\n handler: async ({ url }, ctx): Promise<BinaryResult> => {\n const { bytes, contentType } = await ctx.api.downloadBlob(url);\n return { __binary: true, bytes, contentType, sourceUrl: url };\n },\n});\n\nexport const RUN_TOOLS = [\n listRuns,\n createRun,\n startRun,\n cancelRun,\n waitForRun,\n getRun,\n runSummary,\n listRunTestcases,\n getEvidence,\n getScreenshot,\n];\n","import { z } from 'zod';\nimport { requireProjectId } from '../context.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\nexport const listSchedules = defineTool({\n name: 'list_schedules',\n title: 'List schedules',\n description:\n 'List the recurring run schedules of a project. Each schedule carries its cron expressions, IANA timezone, computed nextFireAt (UTC), platform, case filter and notify recipients.',\n input: z.object({ projectId: PROJECT_ID }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId }, ctx) =>\n ctx.api.listSchedules(requireProjectId(ctx, projectId)),\n});\n\nexport const getSchedule = defineTool({\n name: 'get_schedule',\n title: 'Get schedule',\n description:\n 'Fetch a single schedule by id. lastFiredAt reflects CLOCK-driven fires only — run_schedule_now deliberately leaves it untouched; use list_schedule_fires for the full history.',\n input: z.object({ scheduleId: z.string().min(1) }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ scheduleId }, ctx) => ctx.api.getSchedule(scheduleId),\n});\n\nexport const createSchedule = defineTool({\n name: 'create_schedule',\n title: 'Create schedule',\n description:\n \"Create a recurring run schedule. cronExpressions is 5-field cron evaluated in `timezone` (IANA, e.g. 'Asia/Jakarta'); several expressions are allowed. caseFilter picks what runs: { mode: 'all' } for every case on the platform, or { mode: 'feature', featureIds } to narrow (get ids from list_features). notifyUserIds must come from list_schedule_recipients. Prefer enabled:false while testing, then enable once the cadence reads right.\",\n input: z.object({\n projectId: PROJECT_ID,\n name: z.string().min(1),\n cronExpressions: z.array(z.string().min(1)).min(1),\n timezone: z.string().min(1),\n platform: z.enum(['web', 'android', 'ios']).optional(),\n enabled: z.boolean().optional(),\n configurationId: z.string().optional(),\n caseFilter: z\n .object({\n mode: z.enum(['all', 'feature']),\n featureIds: z.array(z.string()).default([]),\n })\n .optional(),\n notifyUserIds: z.array(z.string()).optional(),\n misfireGraceMinutes: z.number().int().positive().optional(),\n }),\n requires: 'runTests',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, ...args }, ctx) => {\n const pid = requireProjectId(ctx, projectId);\n if (\n args.caseFilter?.mode === 'feature' &&\n !args.caseFilter.featureIds?.length\n ) {\n throw new Error(\n \"caseFilter.mode 'feature' needs at least one featureId — otherwise every fire resolves to zero cases. Call list_features, or use { mode: 'all' }.\",\n );\n }\n const schedule = await ctx.api.createSchedule(pid, {\n ...args,\n platform: args.platform ?? ctx.defaultPlatform ?? 'web',\n } as any);\n let warning: string | null = null;\n if (!schedule.configurationId) {\n const project = await ctx.api.getProject(pid).catch(() => null);\n if (project && !project.defaultConfigurationId) {\n warning =\n 'This schedule has no configurationId and the project has no default configuration, so its runs will start without a base URL and fail at the first navigation. Set configurationId via update_schedule.';\n }\n }\n return { ...schedule, warning };\n },\n});\n\nexport const updateSchedule = defineTool({\n name: 'update_schedule',\n title: 'Update schedule',\n description:\n 'Patch an existing schedule — pause it (enabled:false), change cadence, retarget its configuration, or edit notify recipients. Only the fields you pass are touched.',\n input: z.object({ scheduleId: z.string().min(1), patch: z.record(z.any()) }),\n requires: 'runTests',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ scheduleId, patch }, ctx) =>\n ctx.api.updateSchedule(scheduleId, patch),\n});\n\nexport const deleteSchedule = defineTool({\n name: 'delete_schedule',\n title: 'Delete schedule',\n description:\n 'Delete a schedule permanently. Runs it already created are kept; only the cadence goes away. Prefer update_schedule with enabled:false to pause it instead.',\n input: z.object({ scheduleId: z.string().min(1) }),\n requires: 'runTests',\n billing: 'write',\n surfaces: ['remote', 'local'],\n annotations: { destructiveHint: true },\n handler: async ({ scheduleId }, ctx) => {\n await ctx.api.deleteSchedule(scheduleId);\n return { ok: true, deletedScheduleId: scheduleId };\n },\n});\n\nexport const runScheduleNow = defineTool({\n name: 'run_schedule_now',\n title: 'Run schedule now',\n description:\n \"Fire a schedule immediately on the identical code path the clock uses — works on a paused schedule too. Returns { outcome, runId }: 'run_created' means a run was started (feed runId to wait_for_run), while 'skipped_overlap' means a previous run of this schedule is still live and 'no_cases' means the case filter matched nothing. Skips are reported, not thrown.\",\n input: z.object({ scheduleId: z.string().min(1) }),\n requires: 'runTests',\n billing: 'run',\n surfaces: ['remote', 'local'],\n handler: async ({ scheduleId }, ctx) => {\n const { outcome, skipped } = await ctx.api.runScheduleNow(scheduleId);\n let runId: string | null = null;\n if (outcome === 'run_created') {\n const fires = await ctx.api\n .listScheduleFires(scheduleId)\n .catch(() => ({ items: [], hasMore: false }));\n runId = fires.items[0]?.runId ?? null;\n }\n return {\n scheduleId,\n outcome,\n skipped,\n runId,\n viewUrl: runId ? `${ctx.appUrl}/runs/${runId}` : null,\n };\n },\n});\n\nexport const listScheduleFires = defineTool({\n name: 'list_schedule_fires',\n title: 'List schedule fires',\n description:\n \"History of a schedule's occurrences, newest first: when it fired, the outcome, and the run it created (if any).\",\n input: z.object({\n scheduleId: z.string().min(1),\n page: z.number().int().positive().optional(),\n }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ scheduleId, page }, ctx) =>\n ctx.api.listScheduleFires(scheduleId, page),\n});\n\nexport const listScheduleRecipients = defineTool({\n name: 'list_schedule_recipients',\n title: 'List schedule recipients',\n description:\n \"The users that may be put in a schedule's notifyUserIds. Resolved exactly the way the server resolves recipients at send time.\",\n input: z.object({ projectId: PROJECT_ID }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId }, ctx) =>\n ctx.api.listScheduleRecipients(requireProjectId(ctx, projectId)),\n});\n\nexport const SCHEDULE_TOOLS = [\n listSchedules,\n getSchedule,\n createSchedule,\n updateSchedule,\n deleteSchedule,\n runScheduleNow,\n listScheduleFires,\n listScheduleRecipients,\n];\n","import { z } from 'zod';\nimport { ApiError, type PromptPlan } from '../api.js';\nimport { requireProjectId } from '../context.js';\nimport { mapApiError, runFromDesktopAnswer } from '../errors.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\n/**\n * \"Check that sign-up works on my site\": plan from plain words, show the\n * plan, run it on confirm, summarize. Two-phase, same dry-run convention as\n * the delete tools: call once to get the plan, show it to the person, call\n * again with `confirm:true` once they say yes.\n *\n * Primary path uses the prompt-to-test routes (`…/prompt-tests/preview`,\n * `…/prompt-tests`) when the company has that feature enabled. The gate\n * 404s (by design — \"a hidden feature should look like it doesn't exist\")\n * when it is not, in which case this falls back to a single-step\n * `create_testcase` + `create_run` + `start_run` using the prompt verbatim\n * as one `aiAction` instruction — a plainer plan than the AI-authored one,\n * but a real, runnable test rather than a dead end.\n */\nexport const testMyFlow = defineTool({\n name: 'test_my_flow',\n title: 'Test my flow',\n description:\n 'One-shot: turn a plain-English request (\"check that sign-up works\") into a test plan, show it, then run it on confirmation and summarize the result with a link. Call once without `confirm` to see the plan; call again with `confirm:true` once the person agrees to run it.',\n input: z.object({\n projectId: PROJECT_ID,\n url: z.string().url(),\n prompt: z.string().min(8).max(4000),\n confirm: z.boolean().optional(),\n }),\n requires: 'manageTestCases',\n billing: 'run',\n surfaces: ['remote', 'local'],\n handler: async ({ projectId, url, prompt, confirm }, ctx) => {\n const pid = requireProjectId(ctx, projectId);\n\n let plan: PromptPlan | null = null;\n let promptToTestEnabled = true;\n try {\n const preview = await ctx.api.previewPromptTest(pid, { url, prompt });\n plan = preview.plan;\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n promptToTestEnabled = false;\n } else if (err instanceof ApiError) {\n const mapped = mapApiError(err, ctx, 'manageTestCases');\n if (mapped) return mapped;\n throw err;\n } else {\n throw err;\n }\n }\n\n if (!confirm) {\n if (plan) {\n return {\n dryRun: true,\n plan,\n note: 'Confirm this plan with the person, then call test_my_flow again with confirm:true to create and run it.',\n };\n }\n return {\n dryRun: true,\n plan: {\n title: prompt.slice(0, 120),\n category: 'positive' as const,\n steps: [{ kind: 'action' as const, description: prompt }],\n },\n note: \"This company doesn't have AI plan generation enabled for prompt-to-test, so this will run as a single step using your instruction verbatim. Confirm with the person, then call test_my_flow again with confirm:true.\",\n };\n }\n\n try {\n let runId: string;\n let viewUrl: string;\n if (promptToTestEnabled && plan) {\n const { run } = await ctx.api.createPromptTestRun(pid, {\n url,\n prompt,\n plan,\n });\n runId = run.id;\n viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;\n } else {\n // Fallback: no AI-authored plan, so author one plain aiAction step\n // directly from the prompt and run it the normal way.\n const features = await ctx.api.listFeatures(pid);\n let feature = features.find((f) => f.name === 'Prompt tests');\n if (!feature) {\n feature = await ctx.api.createFeature(pid, {\n name: 'Prompt tests',\n description:\n 'Cases created by test_my_flow (AI plan generation not enabled for this company).',\n });\n }\n const testCase = await ctx.api.createTestCase(feature.id, {\n name: prompt.slice(0, 120),\n steps: [{ aiAction: prompt }],\n executionType: 'automation',\n category: 'positive',\n description: prompt,\n });\n const run = await ctx.api.createRun(pid, {\n name: prompt.slice(0, 120),\n testCaseIds: [testCase.id],\n platform: 'web',\n caseSelectionMode: 'select',\n });\n runId = run.id;\n viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;\n }\n\n try {\n await ctx.api.executeRun(runId);\n } catch (err) {\n if (err instanceof ApiError) {\n const answer =\n runFromDesktopAnswer(err, runId) ??\n mapApiError(err, ctx, 'runTests');\n if (answer) return answer;\n }\n throw err;\n }\n\n return {\n started: true,\n runId,\n viewUrl,\n usedAiPlan: promptToTestEnabled,\n nextStep: 'Call wait_for_run with this runId, then run_summary.',\n };\n } catch (err) {\n if (err instanceof ApiError) {\n const mapped = mapApiError(err, ctx, 'runTests');\n if (mapped) return mapped;\n }\n throw err;\n }\n },\n});\n\nexport const TEST_MY_FLOW_TOOLS = [testMyFlow];\n","import { z } from 'zod';\nimport { ApiError } from '../api.js';\nimport { requireProjectId } from '../context.js';\nimport { defineTool } from '../types.js';\n\nconst PROJECT_ID = z\n .string()\n .optional()\n .describe(\n 'AuraCheck project id (see list_projects). Defaults to the project set for this session.',\n );\n\nconst STEPS_SCHEMA = z.union([\n z.array(z.record(z.any())).min(1),\n z.string().min(1),\n z.record(z.any()),\n]);\n\nconst STEPS_DESCRIPTION =\n 'Array of Midscene flow items (auto-wrapped into tasks[]), or a YAML/JSON string shaped as `tasks: [{ name, flow }]`. Recognized action keys: aiTap, aiInput, aiAssert, aiQuery, aiHover, aiWaitFor, aiKeyboardPress, aiScroll, aiAction, sleep, javascript, aiUploadFile, aiHumanInput, aiExpectDownload, mailTmInbox, mailTmWaitOtp, mailTmWaitLink, otpInbox, otpWaitOtp.';\n\nexport const listTestcases = defineTool({\n name: 'list_testcases',\n title: 'List testcases',\n description:\n 'List testcases for a project, optionally filtered by platform (web/android/ios). Each case carries `prelationTestCaseId` and, when set, a joined `prelationTestCase` — the setup case AuraCheck runs automatically right before it. Use this to find an existing login/setup case before creating a new one.',\n input: z.object({\n projectId: PROJECT_ID,\n platform: z.enum(['web', 'android', 'ios']).optional(),\n }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId, platform }, ctx) =>\n ctx.api.listTestCasesByProject(requireProjectId(ctx, projectId), platform),\n});\n\nexport const getTestcase = defineTool({\n name: 'get_testcase',\n title: 'Get testcase',\n description:\n 'Fetch a single testcase by id. `steps` comes back as the Midscene YAML/JSON string the server stores, not an array — parse it before editing, and pass it back through update_testcase in either form. Also carries `prelationTestCaseId` and, when set, a joined `prelationTestCase`.',\n input: z.object({ projectId: PROJECT_ID, id: z.string().min(1) }),\n requires: 'viewProject',\n billing: 'read',\n surfaces: ['remote', 'local'],\n annotations: { readOnlyHint: true },\n handler: async ({ projectId, id }, ctx) =>\n ctx.api.getTestCase(id, requireProjectId(ctx, projectId)),\n});\n\nexport const createTestcase = defineTool({\n name: 'create_testcase',\n title: 'Create testcase',\n description: `Create a new testcase under an AuraCheck feature. \\`steps\\` is the Midscene flow: pass EITHER an array of flow items (each item one action, e.g. { aiTap: \"Sign in\" }, { aiInput: \"user@example.com\", locate: \"Email field\" }, { aiAssert: \"Dashboard is visible\" }) OR a YAML/JSON string shaped as tasks[]. ${STEPS_DESCRIPTION} A bare array is auto-wrapped. Android/iOS cases are authored here exactly like web ones; they are RUN by a person in the AuraCheck desktop app on their own device (see start_run).\n\nPRELATION — before writing \\`steps\\`, decide whether this case needs a starting state (logged in, on a specific page, seeded data). If it does, set \\`prelationTestCaseId\\` to an existing setup case (find one with list_testcases) instead of copying its steps into every case; create the setup case first if none exists. AuraCheck runs the prelation case automatically immediately before this one every time it runs — never add the prelation case to a run yourself. A prelation must be in the same project and never points at itself or forms a cycle.`,\n input: z.object({\n projectId: PROJECT_ID,\n featureId: z.string().optional(),\n name: z.string().min(1),\n steps: STEPS_SCHEMA,\n executionType: z.enum(['automation', 'manual']).default('automation'),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n category: z.string().optional(),\n reason: z.string().optional(),\n description: z.string().optional(),\n expectedResult: z.string().optional(),\n platforms: z.array(z.string()).optional(),\n coveredScenarios: z.array(z.string()).optional(),\n tags: z.array(z.string()).optional(),\n prelationTestCaseId: z.string().optional(),\n }),\n requires: 'manageTestCases',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async (args, ctx) => {\n requireProjectId(ctx, args.projectId);\n const { projectId: _ignore, featureId, ...rest } = args;\n if (!featureId) {\n throw new Error(\n 'No featureId provided. Call list_features or create_feature first.',\n );\n }\n return ctx.api.createTestCase(featureId, rest);\n },\n});\n\nexport const updateTestcase = defineTool({\n name: 'update_testcase',\n title: 'Update testcase',\n description:\n \"Patch an existing testcase — only the fields you pass are touched. Useful in the auto-fix loop after reading evidence from a failed run. A `steps` patch accepts the same shapes as create_testcase. `patch.prelationTestCaseId` sets/replaces the setup case AuraCheck runs automatically before this one; pass `null` to clear it. It cannot be set to the case's own id, a case from another project, or create a cycle — the server rejects those.\",\n input: z.object({ id: z.string().min(1), patch: z.record(z.any()) }),\n requires: 'manageTestCases',\n billing: 'write',\n surfaces: ['remote', 'local'],\n handler: async ({ id, patch }, ctx) => ctx.api.updateTestCase(id, patch),\n});\n\nexport const deleteTestcase = defineTool({\n name: 'delete_testcase',\n title: 'Delete testcase',\n description:\n 'Delete 1–500 testcases. Requires manageTestCases. Without `confirm: true` this is a DRY RUN — it only lists what would be deleted and asks you to re-call with confirm:true; nothing is deleted on the first call. A case already linked to a run is soft-deleted (run history kept); a case never attached to a run is removed permanently.',\n input: z.object({\n projectId: PROJECT_ID,\n testCaseIds: z.array(z.string().min(1)).min(1).max(500),\n confirm: z.boolean().optional(),\n }),\n requires: 'manageTestCases',\n billing: 'write',\n surfaces: ['remote', 'local'],\n annotations: { destructiveHint: true },\n handler: async ({ projectId, testCaseIds, confirm }, ctx) => {\n const pid = requireProjectId(ctx, projectId);\n try {\n if (!confirm) {\n const all = await ctx.api.listTestCasesByProject(pid);\n const byId = new Map(all.map((c) => [c.id, c]));\n const found = testCaseIds.map((id) => {\n const c = byId.get(id);\n return c\n ? { id, name: c.name, featureId: c.featureId }\n : { id, name: null, featureId: null, notFound: true };\n });\n return {\n dryRun: true,\n wouldDelete: found,\n note: 'Cases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete.',\n };\n }\n const result = await ctx.api.deleteTestCases(testCaseIds);\n return { dryRun: false, deletedIds: testCaseIds, ...result };\n } catch (err) {\n if (err instanceof ApiError && err.status === 403) {\n throw new Error(\n \"Delete failed (403): this sign-in lacks manageTestCases, or one of these cases belongs to a project it can't reach.\",\n );\n }\n if (err instanceof ApiError && err.status === 404) {\n throw new Error(\n 'Delete failed (404): one of these test case ids does not exist.',\n );\n }\n throw err;\n }\n },\n});\n\nexport const TESTCASE_TOOLS = [\n listTestcases,\n getTestcase,\n createTestcase,\n updateTestcase,\n deleteTestcase,\n];\n","import type { z } from 'zod';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\n\n/**\n * `@modelcontextprotocol/server`'s `registerTool` accepts an `inputSchema`\n * that implements the Standard Schema spec (standardschema.dev) PLUS a\n * `~standard.jsonSchema` converter (\"StandardSchemaWithJSON\"). Zod v4,\n * ArkType and Valibot implement that combined interface — zod v3 (which\n * mcp-core's `ToolDef.input` uses, shared with the local stdio server)\n * implements only plain Standard Schema validation, not the JSON Schema\n * half, and `agents` pins zod v4 as its own peer — a second zod major\n * version we don't want as a real dependency here.\n *\n * Rather than add zod v4 (and reconcile two validator libraries), this\n * hand-builds the small Standard-Schema-with-JSON duck type directly on\n * top of a zod v3 schema's own `.safeParse()` and `zod-to-json-schema`\n * output. No zod v4 import anywhere in this Worker.\n */\nexport function toStandardSchemaWithJSON(schema: z.ZodTypeAny) {\n const jsonSchema = zodToJsonSchema(schema, {\n target: 'jsonSchema7',\n }) as Record<string, unknown>;\n return {\n '~standard': {\n version: 1 as const,\n vendor: 'auracheck-mcp-core',\n validate(value: unknown) {\n const result = schema.safeParse(value);\n if (result.success) return { value: result.data };\n return {\n issues: result.error.issues.map((issue) => ({\n message: issue.message,\n path: issue.path,\n })),\n };\n },\n jsonSchema: {\n input: () => jsonSchema,\n output: () => jsonSchema,\n },\n },\n };\n}\n","/**\n * `AuraCheckApi` and its types moved to `@auracheck-ai/mcp-core` (shared\n * with the Worker). This file re-exports them for every existing import\n * site (`commands/*.ts`, `mcp/server.ts`, tests), plus `exchangeCliCode` —\n * the CLI's own `/api/auth/cli/exchange` flow, which is unrelated to the\n * MCP OAuth flow and stays here.\n */\nexport * from '@auracheck-ai/mcp-core';\n\nimport { normalizeBaseUrl } from '@auracheck-ai/mcp-core';\nimport type { AuraCheckUser } from '@auracheck-ai/mcp-core';\nimport { ApiError } from '@auracheck-ai/mcp-core';\n\nexport interface CliExchangeResult {\n token: string;\n tokenId: string;\n label: string;\n user: AuraCheckUser;\n}\n\nexport interface CliTokenInfo {\n id: string;\n label: string;\n tokenPrefix: string;\n createdAt: string;\n lastUsedAt: string | null;\n current: boolean;\n}\n\n/** The caller's personal CLI tokens (`auracheck login`), never the secret. */\nexport async function listCliTokens(opts: {\n baseUrl: string;\n token: string;\n}): Promise<{ tokens: CliTokenInfo[] }> {\n const res = await fetch(\n `${normalizeBaseUrl(opts.baseUrl)}/api/auth/cli-tokens`,\n {\n headers: {\n Authorization: `Bearer ${opts.token}`,\n Accept: 'application/json',\n },\n },\n );\n const text = await res.text();\n if (!res.ok)\n throw new ApiError(\n res.status,\n text,\n `GET /api/auth/cli-tokens -> ${res.status}`,\n );\n return JSON.parse(text);\n}\n\nexport async function revokeCliToken(\n opts: { baseUrl: string; token: string },\n id: string,\n): Promise<{ ok: true }> {\n const res = await fetch(\n `${normalizeBaseUrl(opts.baseUrl)}/api/auth/cli-tokens/${encodeURIComponent(id)}`,\n {\n method: 'DELETE',\n headers: {\n Authorization: `Bearer ${opts.token}`,\n Accept: 'application/json',\n },\n },\n );\n const text = await res.text();\n if (!res.ok) {\n throw new ApiError(\n res.status,\n text,\n `DELETE /api/auth/cli-tokens/${id} -> ${res.status}`,\n );\n }\n return text ? JSON.parse(text) : { ok: true };\n}\n\n/**\n * Redeem the one-time code from the browser sign-in (`auracheck login`) for a\n * personal CLI token. Unauthenticated by design: the PKCE verifier is the proof.\n */\nexport async function exchangeCliCode(\n baseUrl: string,\n input: {\n code: string;\n codeVerifier: string;\n redirectUri: string;\n label: string;\n },\n): Promise<CliExchangeResult> {\n const url = `${normalizeBaseUrl(baseUrl)}/api/auth/cli/exchange`;\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(input),\n });\n } catch (err: any) {\n throw new ApiError(0, '', `Network error calling ${url}: ${err.message}`);\n }\n const text = await res.text();\n let parsed: any = null;\n try {\n parsed = JSON.parse(text);\n } catch {\n // not JSON (e.g. an old server's SPA fallback)\n }\n if (res.status === 404 || (res.ok && !parsed?.token)) {\n throw new ApiError(\n res.status,\n text,\n `${normalizeBaseUrl(baseUrl)} does not support browser sign-in for the CLI yet. Use \\`auracheck login --token <67ci_…>\\` with a CI token from the project's Integrations page.`,\n );\n }\n if (!res.ok) {\n throw new ApiError(\n res.status,\n text,\n `Sign-in failed (${res.status}): ${parsed?.error ?? text.slice(0, 200)}`,\n );\n }\n return parsed as CliExchangeResult;\n}\n","import { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\nimport { z } from 'zod';\n\nconst DEFAULT_EXCLUDE = [\n 'node_modules',\n 'dist',\n 'build',\n '.git',\n '.next',\n '.turbo',\n 'coverage',\n '.cache',\n];\n\n// Intentionally left as `.sixseven/` — it's a file path committed into every\n// bound repo already; renaming it would break every existing checkout's\n// config on upgrade. Not part of the sixseven->auracheck wording rename.\nexport const PROJECT_CONFIG_FILENAME = '.sixseven/config.json';\n\n/** The AuraCheck platform (formerly sixseven-space.sprout.co.id). */\nexport const DEFAULT_BASE_URL = 'https://space.auracheck.ai.id';\n\n/**\n * Hosts BytePlus served before AuraCheck moved off it (BytePlus switched off\n * 2026-11-09). Same backend/account behind {@link DEFAULT_BASE_URL}, so a\n * token saved for one of these keeps working once rewritten.\n */\nexport const LEGACY_BASE_URLS = [\n 'https://sixseven-space.sprout.co.id',\n 'https://sixseven.sprout.co.id',\n 'https://sixseven-api.sprout.co.id',\n];\n\n/** Any retired BytePlus host maps to {@link DEFAULT_BASE_URL}; anything else passes through normalized. */\nexport function migrateLegacyBaseUrl(url: string): string {\n const normalized = normalizeBaseUrl(url);\n return LEGACY_BASE_URLS.includes(normalized) ? DEFAULT_BASE_URL : normalized;\n}\n\n/**\n * Resolve credentials directory. Honors `AURACHECK_HOME` for sandboxed runs\n * (CI, tests); `SIXSEVEN_HOME` is still read as a deprecated fallback so an\n * existing CI config keeps working. Falls back to `~/.auracheck`.\n */\nexport function credentialsDir(): string {\n return (\n process.env.AURACHECK_HOME ??\n process.env.SIXSEVEN_HOME ??\n path.join(homedir(), '.auracheck')\n );\n}\n\nexport function credentialsFile(): string {\n return path.join(credentialsDir(), 'credentials');\n}\n\n/**\n * The old credentials dir (`~/.sixseven`), only used as a one-time migration\n * source — never written to again. `AURACHECK_HOME`/`SIXSEVEN_HOME`\n * overrides (CI/tests) opt out of migration entirely: a sandboxed run should\n * never reach outside its own temp HOME.\n */\nfunction legacyCredentialsDir(): string | null {\n if (process.env.AURACHECK_HOME || process.env.SIXSEVEN_HOME) return null;\n return path.join(homedir(), '.sixseven');\n}\n\nfunction legacyCredentialsFile(): string | null {\n const dir = legacyCredentialsDir();\n return dir ? path.join(dir, 'credentials') : null;\n}\n\nexport const projectConfigSchema = z.object({\n baseUrl: z.string().url(),\n projectId: z.string().min(1),\n defaultFeatureId: z.string().nullish(),\n codeRoots: z.array(z.string().min(1)).default(['.']),\n exclude: z.array(z.string()).default(DEFAULT_EXCLUDE),\n platform: z.enum(['web', 'android', 'ios']).default('web'),\n});\n\nexport type ProjectConfig = z.infer<typeof projectConfigSchema>;\n\nexport const credentialsSchema = z.object({\n tokens: z.record(z.string()).default({}),\n /** Base URL of the last `auracheck login`; used when no project config names one. */\n defaultBaseUrl: z.string().optional(),\n /** Base URLs whose saved token was pasted with `--token` (not created by this sign-in). */\n pasted: z.array(z.string()).optional(),\n /**\n * Machine-wide default project, set by `auracheck.bind_project` (MCP) when\n * run outside a bound repo — i.e. there's no `.sixseven/config.json` to\n * write a per-repo binding into. A per-repo binding always wins over this.\n */\n defaultProjectId: z.string().optional(),\n});\n\nexport type Credentials = z.infer<typeof credentialsSchema>;\n\nexport interface LoadedConfig {\n config: ProjectConfig;\n configPath: string;\n repoRoot: string;\n token: string;\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function findRepoRoot(start: string): Promise<string | null> {\n let cur = path.resolve(start);\n // walk up looking for .sixseven/config.json\n while (true) {\n if (await fileExists(path.join(cur, PROJECT_CONFIG_FILENAME))) {\n return cur;\n }\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n\nexport async function readProjectConfig(\n repoRoot: string,\n): Promise<ProjectConfig> {\n const p = path.join(repoRoot, PROJECT_CONFIG_FILENAME);\n const raw = await fs.readFile(p, 'utf8');\n const parsed = JSON.parse(raw);\n const config = projectConfigSchema.parse(parsed);\n // .sixseven/config.json is usually committed and shared, so a retired host\n // is corrected for this run only — the file on disk is left for the person\n // to update themselves.\n const baseUrl = migrateLegacyBaseUrl(config.baseUrl);\n if (baseUrl !== normalizeBaseUrl(config.baseUrl)) {\n process.stderr.write(\n `AuraCheck CLI: ${PROJECT_CONFIG_FILENAME} points at a retired host; using ${baseUrl} for this run. Update \"baseUrl\" in that file to stop seeing this.\\n`,\n );\n return { ...config, baseUrl };\n }\n return config;\n}\n\nexport async function writeProjectConfig(\n repoRoot: string,\n cfg: ProjectConfig,\n): Promise<string> {\n const dir = path.join(repoRoot, '.sixseven');\n await fs.mkdir(dir, { recursive: true });\n const p = path.join(dir, 'config.json');\n await fs.writeFile(p, `${JSON.stringify(cfg, null, 2)}\\n`, 'utf8');\n return p;\n}\n\nexport interface CredentialsMigration {\n creds: Credentials;\n changed: boolean;\n /** Normalized legacy base URLs that had a token moved off them. */\n migratedFrom: string[];\n}\n\n/**\n * Rewrite any credentials entry keyed by a retired BytePlus host to\n * {@link DEFAULT_BASE_URL}, keeping the token. A token already saved for the\n * new host always wins over a migrated legacy one for the same account.\n */\nexport function migrateLegacyCredentials(\n creds: Credentials,\n): CredentialsMigration {\n const tokens: Record<string, string> = {};\n // Pass 1: entries that are not on a legacy host win outright.\n for (const [key, token] of Object.entries(creds.tokens)) {\n const normalized = normalizeBaseUrl(key);\n if (migrateLegacyBaseUrl(key) === normalized) tokens[normalized] = token;\n }\n // Pass 2: legacy entries fill in the new host only if nothing claimed it yet.\n const migratedFrom = new Set<string>();\n for (const [key, token] of Object.entries(creds.tokens)) {\n const normalized = normalizeBaseUrl(key);\n const mapped = migrateLegacyBaseUrl(key);\n if (mapped === normalized) continue;\n migratedFrom.add(normalized);\n if (!(mapped in tokens)) tokens[mapped] = token;\n }\n const defaultBaseUrl = creds.defaultBaseUrl\n ? migrateLegacyBaseUrl(creds.defaultBaseUrl)\n : creds.defaultBaseUrl;\n const changed =\n migratedFrom.size > 0 || defaultBaseUrl !== creds.defaultBaseUrl;\n if (!changed) return { creds, changed: false, migratedFrom: [] };\n return {\n creds: { tokens, defaultBaseUrl, defaultProjectId: creds.defaultProjectId },\n changed: true,\n migratedFrom: [...migratedFrom],\n };\n}\n\n/** Delete the legacy credentials file, then its dir too if that leaves it empty. */\nasync function removeLegacyCredentials(legacyFile: string): Promise<void> {\n await fs.unlink(legacyFile).catch(() => {});\n const dir = path.dirname(legacyFile);\n const entries = await fs.readdir(dir).catch(() => null);\n if (entries && entries.length === 0) {\n await fs.rmdir(dir).catch(() => {});\n }\n}\n\n/**\n * First call after upgrading: move `~/.sixseven/credentials` into\n * `~/.auracheck/credentials`. If `~/.auracheck` doesn't have one yet, the\n * legacy content is written there and read back to confirm it landed before\n * the old file is removed. If `~/.auracheck/credentials` already exists, it\n * wins — only hosts missing from it are merged in — and the old file is\n * removed once that merge is written. Either way the old file (and its now-\n * empty dir) is deleted only after the new one is verified to hold its data;\n * never deleted on a corrupt read, so a broken write can't lose a token with\n * no copy left anywhere.\n */\nasync function migrateCredentialsDirOnce(): Promise<void> {\n const legacyFile = legacyCredentialsFile();\n if (!legacyFile || !(await fileExists(legacyFile))) return;\n let legacyCreds: Credentials;\n try {\n legacyCreds = credentialsSchema.parse(\n JSON.parse(await fs.readFile(legacyFile, 'utf8')),\n );\n } catch {\n // Unreadable legacy file: nothing to carry forward, but don't let a\n // broken file block every future call from reaching this point again.\n await removeLegacyCredentials(legacyFile);\n return;\n }\n\n const file = credentialsFile();\n if (!(await fileExists(file))) {\n await fs.mkdir(credentialsDir(), { recursive: true, mode: 0o700 });\n await fs.writeFile(file, `${JSON.stringify(legacyCreds, null, 2)}\\n`, {\n mode: 0o600,\n });\n const verified = await fs\n .readFile(file, 'utf8')\n .then((raw) => credentialsSchema.parse(JSON.parse(raw)))\n .catch(() => null);\n if (\n !verified ||\n JSON.stringify(verified.tokens) !== JSON.stringify(legacyCreds.tokens)\n ) {\n return; // write/verify didn't land cleanly — leave the legacy file, retry next call\n }\n } else {\n const existing = await fs\n .readFile(file, 'utf8')\n .then((raw) => credentialsSchema.parse(JSON.parse(raw)))\n .catch(() => null);\n if (!existing) return; // corrupt new file — don't touch the old one yet\n // ~/.auracheck already has sign-ins: it wins. Only fill in hosts it's\n // missing; never overwrite a token already saved there.\n const mergedTokens = { ...legacyCreds.tokens, ...existing.tokens };\n if (\n Object.keys(mergedTokens).length !== Object.keys(existing.tokens).length\n ) {\n await writeCredentials({ ...existing, tokens: mergedTokens });\n }\n }\n\n await removeLegacyCredentials(legacyFile);\n // stderr only: `auracheck mcp`'s stdout is strict JSON-RPC. Never log the\n // token itself — just that the move happened.\n process.stderr.write(\n 'AuraCheck CLI: moved your sign-in from ~/.sixseven to ~/.auracheck.\\n',\n );\n}\n\nexport async function readCredentials(): Promise<Credentials> {\n await migrateCredentialsDirOnce();\n const file = credentialsFile();\n if (!(await fileExists(file))) {\n return { tokens: {} };\n }\n const raw = await fs.readFile(file, 'utf8');\n let creds: Credentials;\n try {\n creds = credentialsSchema.parse(JSON.parse(raw));\n } catch {\n return { tokens: {} };\n }\n const migration = migrateLegacyCredentials(creds);\n if (migration.changed) {\n await writeCredentials(migration.creds);\n // stderr only: `auracheck mcp`'s stdout is strict JSON-RPC.\n process.stderr.write(\n `AuraCheck CLI: your sign-in was saved for ${migration.migratedFrom.join(', ')}, which AuraCheck has moved off of. Switched it to ${DEFAULT_BASE_URL} — same account, nothing to redo.\\n`,\n );\n }\n return migration.creds;\n}\n\nexport async function writeCredentials(creds: Credentials): Promise<void> {\n await fs.mkdir(credentialsDir(), { recursive: true, mode: 0o700 });\n await fs.writeFile(credentialsFile(), `${JSON.stringify(creds, null, 2)}\\n`, {\n mode: 0o600,\n });\n}\n\nexport async function saveToken(\n baseUrl: string,\n token: string,\n opts: { makeDefault?: boolean; pasted?: boolean } = {},\n): Promise<void> {\n const creds = await readCredentials();\n const key = normalizeBaseUrl(baseUrl);\n // Drop look-alike keys (a stray control character pasted after the URL\n // once hid the working token behind a key nothing could match).\n for (const k of Object.keys(creds.tokens)) {\n if (k !== key && normalizeBaseUrl(k) === key) delete creds.tokens[k];\n }\n creds.tokens[key] = token;\n creds.pasted = (creds.pasted ?? []).filter(\n (k) => normalizeBaseUrl(k) !== key,\n );\n if (opts.pasted) creds.pasted.push(key);\n if (opts.makeDefault) creds.defaultBaseUrl = key;\n await writeCredentials(creds);\n}\n\n/** True when the token saved for this base URL was pasted with `--token`. */\nexport async function isPastedToken(baseUrl: string): Promise<boolean> {\n const creds = await readCredentials();\n const key = normalizeBaseUrl(baseUrl);\n return (creds.pasted ?? []).some((k) => normalizeBaseUrl(k) === key);\n}\n\nexport async function removeToken(baseUrl: string): Promise<boolean> {\n const creds = await readCredentials();\n const key = normalizeBaseUrl(baseUrl);\n creds.pasted = (creds.pasted ?? []).filter(\n (k) => normalizeBaseUrl(k) !== key,\n );\n let removed = false;\n for (const k of Object.keys(creds.tokens)) {\n if (normalizeBaseUrl(k) === key) {\n delete creds.tokens[k];\n removed = true;\n }\n }\n if (creds.defaultBaseUrl && normalizeBaseUrl(creds.defaultBaseUrl) === key) {\n creds.defaultBaseUrl = undefined;\n }\n if (removed) await writeCredentials(creds);\n return removed;\n}\n\n/**\n * Set the machine-wide default project (`auracheck.bind_project` when run\n * outside a bound repo). A per-repo `.sixseven/config.json` binding always\n * takes priority over this — see `resolveContext`.\n */\nexport async function setDefaultProjectId(projectId: string): Promise<void> {\n const creds = await readCredentials();\n creds.defaultProjectId = projectId;\n await writeCredentials(creds);\n}\n\nexport async function getToken(baseUrl: string): Promise<string | null> {\n const creds = await readCredentials();\n const key = normalizeBaseUrl(baseUrl);\n const exact = creds.tokens[key];\n if (exact) return exact;\n for (const [k, v] of Object.entries(creds.tokens)) {\n if (normalizeBaseUrl(k) === key) return v;\n }\n return null;\n}\n\n/** Trim whitespace, control characters and trailing slashes off a base URL. */\nexport function normalizeBaseUrl(u: string): string {\n return u\n .replace(/\\p{Cc}/gu, '')\n .trim()\n .replace(/\\/+$/, '');\n}\n\n/**\n * Resolve full runtime context: locate project config, load it, find matching\n * token. Throws with an actionable message when anything is missing.\n */\nexport async function loadContext(cwd: string): Promise<LoadedConfig> {\n const repoRoot = await findRepoRoot(cwd);\n if (!repoRoot) {\n throw new Error(\n `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent. Run \\`auracheck init\\` to create one.`,\n );\n }\n const config = await readProjectConfig(repoRoot);\n const token =\n process.env.AURACHECK_TOKEN?.trim() ||\n process.env.SIXSEVEN_TOKEN?.trim() ||\n (await getToken(config.baseUrl));\n if (!token) {\n throw new Error(\n `No saved token for ${config.baseUrl}. Run \\`auracheck login\\` first.`,\n );\n }\n return {\n config,\n configPath: path.join(repoRoot, PROJECT_CONFIG_FILENAME),\n repoRoot,\n token,\n };\n}\n\nexport interface ResolvedContext {\n /** The repo's .sixseven/config.json, when there is one. */\n config: ProjectConfig | null;\n configPath: string | null;\n /** Repo root for the code tools: the config's directory, else `cwd`. */\n repoRoot: string;\n baseUrl: string;\n /** Default project for project tools; null = pass projectId per call. */\n projectId: string | null;\n platform: ProjectConfig['platform'];\n token: string | null;\n tokenSource: 'env' | 'credentials' | null;\n}\n\nexport interface ContextOverrides {\n baseUrl?: string;\n projectId?: string;\n}\n\n/**\n * Resolve the runtime context WITHOUT requiring a project config or a token,\n * so the MCP server can start anywhere (a worktree, a home directory) and\n * explain what is missing from inside a tool call instead of exiting — an\n * exit shows up in Claude Code only as \"Failed to connect\".\n *\n * Base URL: override → AURACHECK_BASE_URL (deprecated: SIXSEVEN_BASE_URL) →\n * project config → last login → {@link DEFAULT_BASE_URL}. Project: override →\n * AURACHECK_PROJECT_ID (deprecated: SIXSEVEN_PROJECT_ID) → project config →\n * the machine-wide default set by `auracheck.bind_project`/`setDefaultProjectId`.\n * Token: AURACHECK_TOKEN (deprecated: SIXSEVEN_TOKEN) → ~/.auracheck/credentials\n * for that base URL.\n */\nexport async function resolveContext(\n cwd: string,\n overrides: ContextOverrides = {},\n): Promise<ResolvedContext> {\n const root = await findRepoRoot(cwd);\n const config = root ? await readProjectConfig(root) : null;\n const creds = await readCredentials();\n const rawBaseUrl = normalizeBaseUrl(\n overrides.baseUrl ||\n process.env.AURACHECK_BASE_URL ||\n process.env.SIXSEVEN_BASE_URL ||\n config?.baseUrl ||\n creds.defaultBaseUrl ||\n DEFAULT_BASE_URL,\n );\n const baseUrl = migrateLegacyBaseUrl(rawBaseUrl);\n if (baseUrl !== rawBaseUrl) {\n process.stderr.write(\n `AuraCheck CLI: ${rawBaseUrl} is retired; using ${baseUrl} instead.\\n`,\n );\n }\n const projectId =\n overrides.projectId ||\n process.env.AURACHECK_PROJECT_ID ||\n process.env.SIXSEVEN_PROJECT_ID ||\n config?.projectId ||\n creds.defaultProjectId ||\n null;\n const envToken =\n process.env.AURACHECK_TOKEN?.trim() ||\n process.env.SIXSEVEN_TOKEN?.trim() ||\n null;\n const savedToken = envToken ? null : await getToken(baseUrl);\n return {\n config,\n configPath: root ? path.join(root, PROJECT_CONFIG_FILENAME) : null,\n repoRoot: root ?? path.resolve(cwd),\n baseUrl,\n projectId,\n platform: config?.platform ?? 'web',\n token: envToken ?? savedToken,\n tokenSource: envToken ? 'env' : savedToken ? 'credentials' : null,\n };\n}\n\nexport { DEFAULT_EXCLUDE };\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport pc from 'picocolors';\nimport prompts from 'prompts';\nimport { AuraCheckApi } from '../api.js';\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_EXCLUDE,\n getToken,\n migrateLegacyBaseUrl,\n normalizeBaseUrl,\n projectConfigSchema,\n readCredentials,\n writeProjectConfig,\n} from '../config.js';\n\nexport interface InitOptions {\n baseUrl?: string;\n projectId?: string;\n nonInteractive?: boolean;\n}\n\nasync function suggestCodeRoots(cwd: string): Promise<string[]> {\n const candidates = ['src', 'app', 'apps', 'packages', 'lib', 'server'];\n const found: string[] = [];\n for (const c of candidates) {\n try {\n const stat = await fs.stat(path.join(cwd, c));\n if (stat.isDirectory()) found.push(c);\n } catch {\n // skip\n }\n }\n return found.length ? found : ['.'];\n}\n\nexport async function initCommand(opts: InitOptions): Promise<void> {\n const cwd = process.cwd();\n\n let baseUrl = opts.baseUrl;\n if (!baseUrl) {\n if (opts.nonInteractive) {\n const creds = await readCredentials();\n baseUrl = migrateLegacyBaseUrl(\n normalizeBaseUrl(creds.defaultBaseUrl || DEFAULT_BASE_URL),\n );\n }\n }\n if (!baseUrl) {\n const ans = await prompts({\n type: 'text',\n name: 'baseUrl',\n message: 'AuraCheck platform URL (not your app)',\n initial: 'https://space.auracheck.ai.id',\n });\n baseUrl = ans.baseUrl;\n }\n if (!baseUrl) throw new Error('Aborted.');\n\n const token = await getToken(baseUrl);\n if (!token) {\n throw new Error(\n `No saved token for ${normalizeBaseUrl(baseUrl)}. Run \\`auracheck login\\` first.`,\n );\n }\n\n const api = new AuraCheckApi({ baseUrl, token });\n\n let projectId = opts.projectId;\n if (!projectId) {\n process.stdout.write(pc.dim('Fetching projects...\\n'));\n const projects = await api.listProjects();\n if (!projects.length) {\n throw new Error('No projects accessible with this token.');\n }\n if (opts.nonInteractive) {\n throw new Error('--project-id required in non-interactive mode');\n }\n const ans = await prompts({\n type: 'select',\n name: 'projectId',\n message: 'Select AuraCheck project to bind this repo to',\n choices: projects.map((p) => ({\n title: p.name,\n description: p.id,\n value: p.id,\n })),\n });\n projectId = ans.projectId;\n }\n if (!projectId) throw new Error('Aborted.');\n\n const codeRoots = await suggestCodeRoots(cwd);\n const platformAns = opts.nonInteractive\n ? { platform: 'web' as const }\n : await prompts({\n type: 'select',\n name: 'platform',\n message: 'Default platform for testcases',\n choices: [\n { title: 'web', value: 'web' },\n { title: 'android', value: 'android' },\n { title: 'ios', value: 'ios' },\n ],\n initial: 0,\n });\n\n const cfg = projectConfigSchema.parse({\n baseUrl: normalizeBaseUrl(baseUrl),\n projectId,\n defaultFeatureId: null,\n codeRoots,\n exclude: DEFAULT_EXCLUDE,\n platform: platformAns.platform ?? 'web',\n });\n\n const written = await writeProjectConfig(cwd, cfg);\n process.stdout.write(pc.green(`✓ Wrote ${path.relative(cwd, written)}\\n`));\n process.stdout.write(pc.dim(` baseUrl: ${cfg.baseUrl}\\n`));\n process.stdout.write(pc.dim(` projectId: ${cfg.projectId}\\n`));\n process.stdout.write(pc.dim(` codeRoots: ${cfg.codeRoots.join(', ')}\\n`));\n process.stdout.write(pc.dim(` platform: ${cfg.platform}\\n`));\n process.stdout.write(\n `\\nNext: register the MCP server with Claude Code:\\n${pc.cyan(' claude mcp add auracheck -- npx -y @auracheck-ai/cli mcp\\n')}`,\n );\n}\n","import os from 'node:os';\nimport pc from 'picocolors';\nimport prompts from 'prompts';\nimport {\n ApiError,\n AuraCheckApi,\n listCliTokens,\n revokeCliToken,\n} from '../api.js';\nimport { browserLogin } from '../browser-login.js';\nimport {\n isPastedToken,\n normalizeBaseUrl,\n removeToken,\n resolveContext,\n saveToken,\n} from '../config.js';\n\nexport interface LoginOptions {\n baseUrl?: string;\n token?: string;\n /** Print the sign-in URL instead of opening a browser. */\n noBrowser?: boolean;\n label?: string;\n nonInteractive?: boolean;\n /** Ask for a pasted CI token instead of the browser sign-in. */\n promptToken?: boolean;\n}\n\n/** Base URL for login/logout/status: flag → env → repo config → last login → default. */\nasync function targetBaseUrl(flag?: string): Promise<string> {\n return (await resolveContext(process.cwd(), { baseUrl: flag })).baseUrl;\n}\n\n/** Only the first characters, the way the web app shows a token. */\nexport function tokenPreview(token: string): string {\n return `${token.slice(0, 12)}…`;\n}\n\nexport async function loginCommand(opts: LoginOptions): Promise<void> {\n const baseUrl = normalizeBaseUrl(await targetBaseUrl(opts.baseUrl));\n let token = opts.token?.trim();\n\n if (!token && opts.promptToken) {\n if (opts.nonInteractive)\n throw new Error('--token required in non-interactive mode');\n const ans = await prompts({\n type: 'password',\n name: 'token',\n message: 'CI token (starts with 67ci_)',\n validate: (v: string) =>\n v.startsWith('67ci_') ? true : 'must start with 67ci_',\n });\n token = ans.token;\n if (!token) throw new Error('Aborted.');\n }\n\n if (token) {\n // CI / headless path: a token made on a project's Integrations page.\n process.stdout.write(pc.dim(`Verifying token against ${baseUrl}...\\n`));\n const user = await new AuraCheckApi({ baseUrl, token }).me();\n await saveToken(baseUrl, token, { makeDefault: true, pasted: true });\n process.stdout.write(\n pc.green(`✓ Logged in as ${user.email} (role: ${user.role})\\n`),\n );\n process.stdout.write(\n pc.dim(`Saved token for ${baseUrl} to ~/.auracheck/credentials\\n`),\n );\n return;\n }\n\n if (opts.nonInteractive) {\n // A pipeline can't click \"Allow\" in a browser.\n throw new Error('--token required in non-interactive mode');\n }\n const label =\n opts.label?.trim() || `AuraCheck CLI · ${os.hostname() || 'unknown host'}`;\n process.stdout.write(pc.bold(`Signing in to ${baseUrl}\\n`));\n const result = await browserLogin({\n baseUrl,\n label,\n openBrowser: !opts.noBrowser,\n onUrl: (url) => {\n process.stdout.write(\n opts.noBrowser\n ? 'Open this link in a browser on this computer to sign in:\\n'\n : 'Your browser should open. If it does not, open this link:\\n',\n );\n process.stdout.write(` ${pc.cyan(url)}\\n`);\n process.stdout.write(pc.dim('Waiting for you to allow the CLI...\\n'));\n },\n });\n await saveToken(baseUrl, result.token, { makeDefault: true });\n process.stdout.write(\n pc.green(\n `✓ Signed in as ${result.user.email} (role: ${result.user.role})\\n`,\n ),\n );\n process.stdout.write(\n pc.dim(\n `Saved to ~/.auracheck/credentials as \"${result.label}\". Revoke it any time under Profile → Active devices, or with \\`auracheck logout\\`.\\n`,\n ),\n );\n}\n\nexport async function logoutCommand(opts: { baseUrl?: string }): Promise<void> {\n const ctx = await resolveContext(process.cwd(), { baseUrl: opts.baseUrl });\n if (ctx.tokenSource === 'env') {\n throw new Error(\n 'The token comes from AURACHECK_TOKEN/SIXSEVEN_TOKEN; unset it instead (nothing was changed).',\n );\n }\n if (!ctx.token) {\n process.stdout.write(`Not signed in to ${ctx.baseUrl}.\\n`);\n return;\n }\n if (await isPastedToken(ctx.baseUrl)) {\n // A token pasted with --token may be in use elsewhere (another laptop, CI);\n // signing out here only forgets it on this computer.\n await removeToken(ctx.baseUrl);\n process.stdout.write(\n pc.green(`✓ Signed out of ${ctx.baseUrl}`) +\n pc.dim(\n \"\\nThe token was pasted with --token, so it was only removed from this computer and still works elsewhere. Revoke it under Profile → Active devices (or the project's Integrations page) if you no longer need it.\\n\",\n ),\n );\n return;\n }\n let revoked = false;\n try {\n const { tokens } = await listCliTokens({\n baseUrl: ctx.baseUrl,\n token: ctx.token,\n });\n const current = tokens.find((t) => t.current);\n if (current) {\n await revokeCliToken(\n { baseUrl: ctx.baseUrl, token: ctx.token },\n current.id,\n );\n revoked = true;\n }\n } catch (err) {\n // 403 = a pipeline CI token (revoke it on the Integrations page);\n // 401 = already revoked/expired. Either way, forget it locally.\n if (!(err instanceof ApiError) || ![401, 403, 404].includes(err.status)) {\n throw err;\n }\n }\n await removeToken(ctx.baseUrl);\n process.stdout.write(\n pc.green(`✓ Signed out of ${ctx.baseUrl}`) +\n (revoked\n ? pc.dim(' (token revoked)\\n')\n : pc.dim(\n \"\\nThis was a project CI token; it still works until it's revoked on the project's Integrations page.\\n\",\n )),\n );\n}\n\nexport async function authStatusCommand(opts: {\n baseUrl?: string;\n}): Promise<void> {\n const ctx = await resolveContext(process.cwd(), { baseUrl: opts.baseUrl });\n process.stdout.write(pc.bold('AuraCheck CLI sign-in\\n'));\n process.stdout.write(` baseUrl: ${ctx.baseUrl}\\n`);\n process.stdout.write(\n ` project: ${ctx.projectId ?? pc.dim('none bound (MCP tools take a projectId)')}\\n`,\n );\n if (ctx.configPath) process.stdout.write(` config: ${ctx.configPath}\\n`);\n if (!ctx.token) {\n process.stdout.write(\n pc.red(' token: ✗ not signed in — run `auracheck login`\\n'),\n );\n process.exitCode = 1;\n return;\n }\n process.stdout.write(\n ` token: ${tokenPreview(ctx.token)} (${ctx.tokenSource === 'env' ? 'AURACHECK_TOKEN' : '~/.auracheck/credentials'})\\n`,\n );\n const api = new AuraCheckApi({ baseUrl: ctx.baseUrl, token: ctx.token });\n try {\n const user = (await api.me()) as Awaited<ReturnType<AuraCheckApi['me']>> & {\n companyName?: string | null;\n };\n process.stdout.write(\n pc.green(` user: ✓ ${user.email} (role: ${user.role})\\n`),\n );\n process.stdout.write(\n ` company: ${user.companyName ?? user.companyId ?? pc.dim('none')}\\n`,\n );\n } catch (err: any) {\n process.stdout.write(pc.red(` user: ✗ ${err.message}\\n`));\n process.exitCode = 1;\n return;\n }\n try {\n const { tokens } = await listCliTokens({\n baseUrl: ctx.baseUrl,\n token: ctx.token,\n });\n const current = tokens.find((t) => t.current);\n process.stdout.write(\n ` kind: ${current ? `personal CLI sign-in \"${current.label}\"` : 'personal CLI sign-in'}\\n`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 403) {\n process.stdout.write(\n ` kind: project CI token ${pc.dim('(only reaches its own project; `auracheck login` gives a personal sign-in)')}\\n`,\n );\n } else if (err instanceof ApiError && err.status === 404) {\n process.stdout.write(\n ` kind: CI token ${pc.dim('(server predates CLI sign-in)')}\\n`,\n );\n }\n }\n}\n","import { spawn } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport http from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { type CliExchangeResult, exchangeCliCode } from './api.js';\nimport { normalizeBaseUrl } from './config.js';\n\n/**\n * `auracheck login`: sign in through the browser, the same way the AuraCheck\n * desktop app does (OAuth 2.0 for native apps, RFC 8252, with PKCE).\n *\n * 1. Listen on a random loopback port (127.0.0.1 only) for this one sign-in.\n * 2. Open `<base>/desktop-login?…&client=cli` in the browser. The person signs\n * in there the normal web way (Clerk, Device Trust…) and allows the CLI.\n * 3. The page sends the browser to our loopback `/callback?code=…&state=…`.\n * 4. Check `state`, then trade the code + PKCE verifier at\n * POST /api/auth/cli/exchange for a personal CLI token (revocable under\n * Profile → Active devices).\n *\n * The verifier never leaves this process, so a code that leaks (browser\n * history, another local program) can't be redeemed by anyone else.\n */\n\nexport const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport function makePkce(): {\n state: string;\n verifier: string;\n challenge: string;\n} {\n const verifier = randomBytes(48).toString('base64url');\n return {\n state: randomBytes(24).toString('base64url'),\n verifier,\n challenge: createHash('sha256').update(verifier).digest('base64url'),\n };\n}\n\nexport function buildLoginUrl(\n baseUrl: string,\n p: { state: string; challenge: string; redirectUri: string },\n): string {\n const url = new URL('/desktop-login', `${normalizeBaseUrl(baseUrl)}/`);\n url.searchParams.set('state', p.state);\n url.searchParams.set('code_challenge', p.challenge);\n url.searchParams.set('code_challenge_method', 'S256');\n url.searchParams.set('redirect_uri', p.redirectUri);\n url.searchParams.set('client', 'cli');\n return url.toString();\n}\n\n/** Best effort: open `url` in the default browser. Never throws. */\nexport function openInBrowser(url: string): void {\n const [cmd, args] =\n process.platform === 'darwin'\n ? ['open', [url]]\n : process.platform === 'win32'\n ? ['cmd', ['/c', 'start', '\"\"', url]]\n : ['xdg-open', [url]];\n try {\n const child = spawn(cmd, args as string[], {\n stdio: 'ignore',\n detached: true,\n });\n child.on('error', () => undefined);\n child.unref();\n } catch {\n // The URL is printed too; the person can open it by hand.\n }\n}\n\nconst PAGE_STYLE =\n 'font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px;line-height:1.5';\nconst PAGE = (title: string, body: string) =>\n `<!doctype html><meta charset=\"utf-8\"><title>${title}</title><body style=\"${PAGE_STYLE}\"><h2>${title}</h2><p>${body}</p></body>`;\n\nexport interface BrowserLoginOptions {\n baseUrl: string;\n /** Shown under Active devices, e.g. \"AuraCheck CLI · my-laptop\". */\n label: string;\n /** Called with the sign-in URL once the listener is up. */\n onUrl: (url: string) => void;\n openBrowser?: boolean;\n timeoutMs?: number;\n /** Test seam. */\n exchange?: typeof exchangeCliCode;\n}\n\nexport async function browserLogin(\n opts: BrowserLoginOptions,\n): Promise<CliExchangeResult> {\n const pkce = makePkce();\n const exchange = opts.exchange ?? exchangeCliCode;\n const server = http.createServer();\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', () => resolve());\n });\n const { port } = server.address() as AddressInfo;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n\n try {\n return await new Promise<CliExchangeResult>((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n settled = true;\n reject(\n new Error(\n 'Timed out waiting for the browser sign-in. Run `auracheck login` again.',\n ),\n );\n }, opts.timeoutMs ?? LOGIN_TIMEOUT_MS);\n\n server.on('request', (req, res) => {\n const url = new URL(req.url ?? '/', redirectUri);\n if (url.pathname !== '/callback') {\n res.writeHead(404).end();\n return;\n }\n const send = (status: number, title: string, body: string) => {\n res.writeHead(status, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-store',\n });\n res.end(PAGE(title, body));\n };\n if (settled) {\n send(410, 'Sign-in already finished', 'You can close this tab.');\n return;\n }\n const code = url.searchParams.get('code');\n if (url.searchParams.get('state') !== pkce.state || !code) {\n // Not ours (or a stale tab): ignore it and keep waiting.\n send(\n 400,\n 'This sign-in link is not for this terminal',\n 'Go back to the terminal and run <code>auracheck login</code> again.',\n );\n return;\n }\n settled = true;\n clearTimeout(timer);\n exchange(opts.baseUrl, {\n code,\n codeVerifier: pkce.verifier,\n redirectUri,\n label: opts.label,\n }).then(\n (result) => {\n send(\n 200,\n 'Signed in to the AuraCheck CLI',\n 'You can close this tab and go back to your terminal.',\n );\n resolve(result);\n },\n (err: Error) => {\n send(\n 400,\n 'Sign-in failed',\n 'Go back to the terminal for details, then run <code>auracheck login</code> again.',\n );\n reject(err);\n },\n );\n });\n\n const loginUrl = buildLoginUrl(opts.baseUrl, {\n state: pkce.state,\n challenge: pkce.challenge,\n redirectUri,\n });\n opts.onUrl(loginUrl);\n if (opts.openBrowser !== false) openInBrowser(loginUrl);\n });\n } finally {\n server.close();\n server.closeAllConnections?.();\n }\n}\n","import { spawn, spawnSync } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport pc from 'picocolors';\nimport prompts from 'prompts';\nimport { AuraCheckApi } from '../api.js';\nimport { getToken, normalizeBaseUrl, readProjectConfig } from '../config.js';\nimport { initCommand } from './init.js';\nimport { loginCommand } from './login.js';\n\nexport interface SetupOptions {\n baseUrl?: string;\n token?: string;\n projectId?: string;\n skipMcp?: boolean;\n nonInteractive?: boolean;\n}\n\ntype McpTarget = 'claude-code' | 'cursor' | 'claude-desktop' | 'skip';\n\nfunction hasBinaryOnPath(bin: string): boolean {\n const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], {\n stdio: 'ignore',\n });\n return r.status === 0;\n}\n\nfunction resolveMcpInvocation(): {\n command: string;\n args: string[];\n display: string;\n} {\n if (hasBinaryOnPath('auracheck')) {\n return { command: 'auracheck', args: ['mcp'], display: 'auracheck mcp' };\n }\n const entry = process.argv[1];\n return {\n command: process.execPath,\n args: [entry, 'mcp'],\n display: `node ${entry} mcp`,\n };\n}\n\nasync function registerWithClaudeCode(\n invocation: ReturnType<typeof resolveMcpInvocation>,\n): Promise<boolean> {\n if (!hasBinaryOnPath('claude')) {\n process.stdout.write(\n pc.yellow(\n '! `claude` CLI not found on PATH — skipping auto-registration.\\n',\n ),\n );\n return false;\n }\n return await new Promise<boolean>((resolve) => {\n const child = spawn(\n 'claude',\n ['mcp', 'add', 'auracheck', '--', invocation.command, ...invocation.args],\n { stdio: 'inherit' },\n );\n child.on('exit', (code) => resolve(code === 0));\n child.on('error', () => resolve(false));\n });\n}\n\nfunction printManualSnippets(\n target: Exclude<McpTarget, 'skip' | 'claude-code'>,\n invocation: ReturnType<typeof resolveMcpInvocation>,\n): void {\n const argsJson = JSON.stringify(invocation.args);\n if (target === 'cursor') {\n process.stdout.write(\n `\\n${pc.bold('Add to')} ${pc.cyan('.cursor/mcp.json')}:\\n`,\n );\n process.stdout.write(\n `${pc.dim(\n JSON.stringify(\n {\n mcpServers: {\n auracheck: { command: invocation.command, args: invocation.args },\n },\n },\n null,\n 2,\n ),\n )}\\n`,\n );\n return;\n }\n if (target === 'claude-desktop') {\n process.stdout.write(\n `\\n${pc.bold('Add to Claude Desktop config')} (${pc.cyan('~/Library/Application Support/Claude/claude_desktop_config.json')} on macOS):\\n`,\n );\n process.stdout.write(\n `${pc.dim(\n JSON.stringify(\n {\n mcpServers: {\n auracheck: { command: invocation.command, args: invocation.args },\n },\n },\n null,\n 2,\n ),\n )}\\n`,\n );\n void argsJson;\n }\n}\n\nexport async function setupCommand(opts: SetupOptions): Promise<void> {\n const cwd = process.cwd();\n process.stdout.write(\n pc.bold('AuraCheck setup\\n') +\n pc.dim('Walks through: login → bind project → register MCP.\\n\\n'),\n );\n\n // 1. Login (skip if token already saved for this baseUrl)\n let baseUrl = opts.baseUrl;\n if (!baseUrl && !opts.nonInteractive) {\n const ans = await prompts({\n type: 'text',\n name: 'baseUrl',\n message: 'AuraCheck platform URL (not your app)',\n initial: 'https://space.auracheck.ai.id',\n validate: (v: string) =>\n /^https?:\\/\\//.test(v) ? true : 'must start with http(s)://',\n });\n baseUrl = ans.baseUrl;\n }\n if (!baseUrl) throw new Error('Aborted (no base URL).');\n\n const existingToken = await getToken(baseUrl);\n let tokenValid = false;\n if (existingToken) {\n try {\n const api = new AuraCheckApi({ baseUrl, token: existingToken });\n const user = await api.me();\n process.stdout.write(\n pc.green(\n `✓ Token already saved for ${normalizeBaseUrl(baseUrl)} (${user.email}). Skipping login.\\n`,\n ),\n );\n tokenValid = true;\n } catch {\n process.stdout.write(\n pc.yellow(\n `! Saved token for ${normalizeBaseUrl(baseUrl)} is invalid — re-login required.\\n`,\n ),\n );\n }\n }\n\n if (!tokenValid) {\n process.stdout.write(pc.bold('\\n[1/3] Login\\n'));\n await loginCommand({\n baseUrl,\n token: opts.token,\n nonInteractive: !!opts.nonInteractive,\n });\n }\n\n // 2. Init (skip / confirm if config already exists)\n process.stdout.write(pc.bold('\\n[2/3] Bind project\\n'));\n const existing = await readProjectConfig(cwd).catch(() => null);\n let shouldInit = true;\n if (existing) {\n process.stdout.write(\n pc.dim(\n ` Found existing .sixseven/config.json → projectId ${existing.projectId} on ${existing.baseUrl}\\n`,\n ),\n );\n if (opts.nonInteractive) {\n shouldInit = false;\n } else {\n const ans = await prompts({\n type: 'confirm',\n name: 'rebind',\n message: 'Re-bind this repo to a different project?',\n initial: false,\n });\n shouldInit = !!ans.rebind;\n }\n }\n if (shouldInit) {\n await initCommand({\n baseUrl,\n projectId: opts.projectId,\n nonInteractive: !!opts.nonInteractive,\n });\n } else {\n process.stdout.write(pc.dim(' Keeping existing binding.\\n'));\n }\n\n // 3. MCP registration\n process.stdout.write(pc.bold('\\n[3/3] Register MCP server\\n'));\n if (opts.skipMcp) {\n process.stdout.write(pc.dim(' --skip-mcp set, skipping.\\n'));\n return;\n }\n\n const invocation = resolveMcpInvocation();\n process.stdout.write(\n pc.dim(` MCP launch command: ${invocation.display}\\n\\n`),\n );\n\n let target: McpTarget;\n if (opts.nonInteractive) {\n target = 'claude-code';\n } else {\n const ans = await prompts({\n type: 'select',\n name: 'target',\n message: 'Where do you want to register the MCP server?',\n choices: [\n {\n title: 'Claude Code (auto via `claude mcp add`)',\n value: 'claude-code',\n },\n { title: 'Cursor (print .cursor/mcp.json snippet)', value: 'cursor' },\n {\n title: 'Claude Desktop (print config snippet)',\n value: 'claude-desktop',\n },\n { title: 'Skip — I will do it manually', value: 'skip' },\n ],\n initial: 0,\n });\n target = (ans.target as McpTarget) ?? 'skip';\n }\n\n if (target === 'claude-code') {\n const ok = await registerWithClaudeCode(invocation);\n if (ok) {\n process.stdout.write(\n pc.green(\n '\\n✓ Registered as MCP server \"auracheck\" with Claude Code.\\n',\n ),\n );\n } else {\n process.stdout.write(\n pc.yellow('\\n! Auto-registration failed. Run manually:\\n') +\n pc.cyan(\n ` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(' ')}\\n`,\n ),\n );\n }\n } else if (target === 'skip') {\n process.stdout.write(\n pc.dim(' Manual command:\\n') +\n pc.cyan(\n ` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(' ')}\\n`,\n ),\n );\n } else {\n printManualSnippets(target, invocation);\n }\n\n // Final summary\n const cfgPath = path.join(cwd, '.sixseven', 'config.json');\n const cfgExists = await fs\n .stat(cfgPath)\n .then(() => true)\n .catch(() => false);\n process.stdout.write(\n `\\n${pc.bold('Done.')} ${pc.dim('Next:')}\\n${pc.dim(\n ` • auracheck status — verify binding (${cfgExists ? 'config OK' : 'no config'})\\n`,\n )}${pc.dim(' • auracheck doctor — full diagnostics\\n')}${pc.dim(' • Open Claude Code and ask: \"list auracheck features\"\\n')}`,\n );\n}\n","import pc from 'picocolors';\nimport { AuraCheckApi } from '../api.js';\nimport { loadContext } from '../config.js';\n\nexport async function statusCommand(): Promise<void> {\n const ctx = await loadContext(process.cwd());\n const api = new AuraCheckApi({\n baseUrl: ctx.config.baseUrl,\n token: ctx.token,\n });\n\n process.stdout.write(pc.bold('AuraCheck CLI status\\n'));\n process.stdout.write(` config: ${ctx.configPath}\\n`);\n process.stdout.write(` repoRoot: ${ctx.repoRoot}\\n`);\n process.stdout.write(` baseUrl: ${ctx.config.baseUrl}\\n`);\n process.stdout.write(` projectId: ${ctx.config.projectId}\\n`);\n process.stdout.write(` platform: ${ctx.config.platform}\\n`);\n process.stdout.write(` codeRoots: ${ctx.config.codeRoots.join(', ')}\\n`);\n\n try {\n const user = await api.me();\n process.stdout.write(\n pc.green(\n ` token: ✓ valid (user: ${user.email}, role: ${user.role})\\n`,\n ),\n );\n } catch (err: any) {\n process.stdout.write(pc.red(` token: ✗ ${err.message}\\n`));\n process.exitCode = 1;\n return;\n }\n\n try {\n const features = await api.listFeatures(ctx.config.projectId);\n process.stdout.write(` features: ${features.length}\\n`);\n const tcs = await api.listTestCasesByProject(ctx.config.projectId);\n process.stdout.write(` testcases: ${tcs.length}\\n`);\n } catch (err: any) {\n process.stdout.write(pc.yellow(` warn: ${err.message}\\n`));\n }\n}\n","import { hostname } from 'node:os';\nimport {\n ALL_TOOLS,\n ApiError,\n AuraCheckApi,\n type Capability,\n type McpContext,\n PROMPTS,\n callTool,\n localName,\n serverInstructions,\n toStandardSchemaWithJSON,\n} from '@auracheck-ai/mcp-core';\nimport { McpServer } from '@modelcontextprotocol/server';\nimport { serveStdio } from '@modelcontextprotocol/server/stdio';\nimport { z } from 'zod';\nimport { browserLogin } from '../browser-login.js';\nimport {\n type ContextOverrides,\n DEFAULT_EXCLUDE,\n type ProjectConfig,\n type ResolvedContext,\n getToken,\n normalizeBaseUrl,\n readCredentials,\n readProjectConfig,\n removeToken,\n resolveContext,\n saveToken,\n setDefaultProjectId,\n writeProjectConfig,\n} from '../config.js';\nimport { SourceReader } from '../source-reader.js';\n\n// Build-time constant (tsup's `define`, see tsup.config.ts) — a runtime\n// createRequire('../../package.json') doesn't survive bundling into\n// dist/mcp/server.js alongside dist/bin.js (see bin.ts for the long version).\ndeclare const __CLI_VERSION__: string;\nconst CLI_VERSION = __CLI_VERSION__;\n\n/**\n * mcp-core's role filter assumes a caller whose capabilities came back from\n * `/api/mcp/context`. The local CLI never gated tool visibility or tool\n * calls on capability before this refactor (the server was always the\n * enforcement point; a local 403 just surfaced as an error). To keep that\n * \"no behaviour change\" promise — and to keep working today, before Part A\n * ships `/api/mcp/context` on prod — local always presents every\n * capability to mcp-core's gate. Real role/plan info (for display, and for\n * mapApiError's admin-aware wording) still comes from the account context\n * below when it's reachable.\n */\nconst LOCAL_ALL_CAPABILITIES: Capability[] = [\n 'viewProject',\n 'viewReports',\n 'manageTestCases',\n 'manageRuns',\n 'runTests',\n 'manageProjectSetup',\n 'manageBugs',\n];\n\n/** Benign stand-in for `/api/mcp/context` until Part A deploys it, or if it errors. */\nfunction fallbackAccountContext(\n user: {\n id: string;\n name: string | null;\n email: string;\n role: string;\n companyId: string | null;\n } | null,\n baseUrl: string,\n): McpContext {\n return {\n user: {\n id: user?.id ?? 'unknown',\n name: user?.name ?? null,\n email: user?.email ?? '',\n roleLabel: user?.role ?? 'unknown',\n capabilities: LOCAL_ALL_CAPABILITIES,\n },\n company: { id: user?.companyId ?? '', name: '' },\n projects: [],\n subscription: {\n status: 'unknown',\n planName: '',\n daysLeft: null,\n readOnly: false,\n inGrace: false,\n billingEnabled: false,\n runUsage: null,\n },\n adminContact: null,\n renewalUrl: `${baseUrl}/admin/billing`,\n minLocalMcp: CLI_VERSION,\n };\n}\n\nasync function resolveLocalAccount(\n api: AuraCheckApi,\n baseUrl: string,\n): Promise<McpContext> {\n try {\n const account = await api.mcpContext();\n // See LOCAL_ALL_CAPABILITIES above: real data for display, full access\n // for the gate, so this refactor cannot newly block a local call.\n return {\n ...account,\n user: { ...account.user, capabilities: LOCAL_ALL_CAPABILITIES },\n };\n } catch {\n const user = await api.me().catch(() => null);\n return fallbackAccountContext(user, baseUrl);\n }\n}\n\ninterface ToolCtxLocal {\n /**\n * For a NO_AUTH_TOOL (login/logout/whoami/bind_project) this is an unsafe\n * cast of `null` when not signed in — check `signedIn` before touching it,\n * the same convention CODE_TOOLS already uses for their no-API case.\n */\n api: AuraCheckApi;\n /** False only for a NO_AUTH_TOOL called before sign-in. True everywhere else. */\n signedIn: boolean;\n reader: SourceReader;\n baseUrl: string;\n tokenSource: ResolvedContext['tokenSource'];\n /** The repo's .sixseven/config.json contents, or null if unbound. */\n config: ProjectConfig | null;\n repoRoot: string;\n}\n\ninterface LocalToolDef {\n name: string;\n description: string;\n zod: z.ZodTypeAny;\n handler: (args: any, ctx: ToolCtxLocal) => Promise<unknown>;\n}\n\n/**\n * Android and iOS runs never execute on AuraCheck's servers: a person starts\n * them in the AuraCheck desktop app on their own device or emulator. The\n * server answers execute with 422 `run_from_desktop`; turn that into an\n * answer (not a tool error) that says what to do.\n */\nexport const MOBILE_RUN_NEXT_STEP =\n 'Ask the person to open this run in the AuraCheck desktop app with the Android device or emulator connected and click \"Run on local\" (iOS: macOS desktop app, \"Run on iOS\"). Then call auracheck.wait_for_run: it waits while the run is pending.';\n\nconst LOCAL_TOOLS: LocalToolDef[] = [\n // ---------- Whitebox: source code ----------\n {\n name: 'auracheck.read_code',\n description:\n 'Read a text file from the developer repo. Path is relative to repo root and must fall within configured codeRoots. Use to understand routes, components, validators, and fixtures before generating a testcase.',\n zod: z.object({ path: z.string().min(1) }),\n handler: async ({ path }, { reader }) => reader.readFile(path),\n },\n {\n name: 'auracheck.list_dir',\n description:\n 'List entries of a directory inside the developer repo. Path is relative to repo root.',\n zod: z.object({ path: z.string().default('.') }),\n handler: async ({ path }, { reader }) => reader.listDir(path),\n },\n {\n name: 'auracheck.search_code',\n description:\n 'Search developer repo (within codeRoots) for a substring or regex. Returns up to 200 matches with file + line + preview. Use to locate routes, handlers, components by name.',\n zod: z.object({\n query: z.string().min(1),\n regex: z.boolean().optional(),\n caseSensitive: z.boolean().optional(),\n maxResults: z.number().int().positive().max(1000).optional(),\n }),\n handler: async (args, { reader }) => reader.search(args.query, args),\n },\n\n // ---------- AuraCheck: project context & onboarding ----------\n {\n name: 'auracheck.whoami',\n description:\n 'Report sign-in status, the base URL, and the project this MCP session is bound to, plus a nextStep hint for what to do next (sign in, bind a project, or nothing — already set up). Safe to call first, before signing in.',\n zod: z.object({}).passthrough(),\n handler: async (\n _args,\n { api, signedIn, baseUrl, tokenSource }: ToolCtxLocal,\n ) => {\n const boundProjectId = await currentDefaultProjectId();\n if (!signedIn) {\n return {\n signedIn: false,\n baseUrl,\n cliVersion: CLI_VERSION,\n projectId: boundProjectId,\n nextStep: 'Not signed in — call auracheck.login.',\n };\n }\n const [user, project] = await Promise.all([\n api.me(),\n boundProjectId\n ? api.getProject(boundProjectId).catch(() => null)\n : Promise.resolve(null),\n ]);\n return {\n signedIn: true,\n user,\n baseUrl,\n tokenSource,\n cliVersion: CLI_VERSION,\n projectId: boundProjectId,\n project,\n nextStep: boundProjectId\n ? null\n : 'No project bound — call auracheck.list_projects, ask the person which one, then auracheck.bind_project({ projectId }).',\n };\n },\n },\n {\n name: 'auracheck.login',\n description:\n \"Sign in to AuraCheck through the browser (same OAuth/PKCE flow as `auracheck login` in a terminal) — no terminal needed. Opens the system browser and waits up to ~90s for the person to click Allow. If it times out before that, it returns the sign-in url and 'Not finished — call auracheck.login again to resume.'; calling it again starts a fresh attempt (no duplicate tokens are saved — a new sign-in simply replaces the old one for this baseUrl). On success the token is saved exactly like the CLI command, and tool calls that needed auracheck.login now work.\",\n zod: z.object({\n baseUrl: z.string().url().optional(),\n timeoutSec: z.number().int().positive().max(600).optional(),\n }),\n handler: async (args, { baseUrl: ctxBaseUrl }) => {\n const baseUrl = normalizeBaseUrl(args.baseUrl ?? ctxBaseUrl);\n let signInUrl = '';\n try {\n const result = await browserLogin({\n baseUrl,\n label: `AuraCheck MCP · ${hostname() || 'unknown host'}`,\n timeoutMs: (args.timeoutSec ?? 90) * 1000,\n openBrowser: process.env.AURACHECK_NO_BROWSER !== '1',\n onUrl: (url) => {\n signInUrl = url;\n },\n });\n await saveToken(baseUrl, result.token, { makeDefault: true });\n return {\n ok: true,\n baseUrl,\n user: result.user,\n message: `Signed in as ${result.user.email}.`,\n };\n } catch (err) {\n if (signInUrl) {\n return {\n ok: false,\n baseUrl,\n url: signInUrl,\n message:\n 'Not finished — the browser sign-in was not completed in time. Call auracheck.login again to resume (open the url yourself if the browser did not open).',\n };\n }\n throw err;\n }\n },\n },\n {\n name: 'auracheck.logout',\n description:\n 'Forget the locally saved sign-in for this baseUrl. Local only — does not revoke the token on the server (do that from Profile → Active devices if needed).',\n zod: z.object({ baseUrl: z.string().url().optional() }),\n handler: async (args, { baseUrl: ctxBaseUrl }) => {\n const baseUrl = normalizeBaseUrl(args.baseUrl ?? ctxBaseUrl);\n const removed = await removeToken(baseUrl);\n return { ok: true, baseUrl, removed };\n },\n },\n {\n name: 'auracheck.bind_project',\n description:\n 'Set the default AuraCheck project for this repo (if a .sixseven/config.json binding exists or can be created in the current working directory) or, otherwise, as this machine-wide default — the same fallback project tools use when no projectId is passed. Verifies the id against auracheck.list_projects when signed in. Onboarding order: auracheck.login → auracheck.list_projects → ask the person which one → auracheck.bind_project.',\n zod: z.object({ projectId: z.string().min(1) }),\n handler: async ({ projectId }, { api, signedIn, repoRoot, config }) => {\n if (signedIn) {\n const projects = await api.listProjects().catch(() => null);\n if (projects && !projects.some((p) => p.id === projectId)) {\n throw new Error(\n `${projectId} is not in the list of projects this sign-in can reach. Call auracheck.list_projects.`,\n );\n }\n }\n if (config) {\n const path = await writeProjectConfig(repoRoot, {\n ...config,\n projectId,\n });\n return { ok: true, scope: 'repo', projectId, configPath: path };\n }\n await setDefaultProjectId(projectId);\n return { ok: true, scope: 'global', projectId };\n },\n },\n\n // ---------- AuraCheck: get_screenshot (local keeps its own outPath arg) ----------\n {\n name: 'auracheck.get_screenshot',\n description:\n \"Download a run screenshot (or any authenticated blob) to a local file and return its path, so it can then be opened and looked at. Pass a `screenshotUrl` straight from auracheck.get_evidence — those are bare paths that cannot be fetched without the bound base URL and CI token, so this is the only way to actually SEE a step's screenshot. Reach for it whenever a failure's cause is visual: 'the page froze' is often disproved by two consecutive screenshots being identical, or by the page rendering fine with a control merely disabled.\",\n zod: z.object({\n url: z\n .string()\n .min(1)\n .describe(\n \"screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host.\",\n ),\n outPath: z\n .string()\n .optional()\n .describe(\n 'Where to write it. Defaults to a temp file named after the blob.',\n ),\n }),\n handler: async (args, { api }) => {\n const { tmpdir } = await import('node:os');\n const path = await import('node:path');\n const { mkdir, writeFile } = await import('node:fs/promises');\n const { bytes, contentType } = await api.downloadBlob(args.url);\n // Name the temp file after the blob so several screenshots from one\n // investigation stay tellable apart on disk.\n const base =\n path.basename(args.url.split('?')[0] || '').replace(/[^\\w.-]/g, '_') ||\n 'screenshot.png';\n const dest =\n args.outPath ?? path.join(tmpdir(), `auracheck-${Date.now()}-${base}`);\n await mkdir(path.dirname(dest), { recursive: true });\n await writeFile(dest, bytes);\n return {\n path: dest,\n bytes: bytes.length,\n contentType,\n hint: 'Open this path with your file-reading tool to view the image.',\n };\n },\n },\n];\n\n/** These work before sign-in: they do the onboarding itself. */\nconst NO_AUTH_TOOLS = new Set([\n 'auracheck.login',\n 'auracheck.logout',\n 'auracheck.whoami',\n 'auracheck.bind_project',\n]);\n\n/** These read the local repo only — never touch the API. */\nconst CODE_TOOLS = new Set([\n 'auracheck.read_code',\n 'auracheck.list_dir',\n 'auracheck.search_code',\n]);\n\nfunction logErr(msg: string): void {\n process.stderr.write(`[auracheck-mcp] ${msg}\\n`);\n}\n\nclass NotSignedInError extends Error {\n constructor(baseUrl: string) {\n super(\n `Not signed in to AuraCheck (${baseUrl}). Call auracheck.login (or run \\`auracheck login\\` in a terminal) — the MCP server picks up the new sign-in on the next call, no restart needed.`,\n );\n }\n}\n\nconst ONBOARDING_INSTRUCTIONS = `This server works before sign-in: auracheck.whoami, auracheck.login, auracheck.logout, auracheck.bind_project, and tools/list all work with no credentials. Every other tool needs a sign-in and a bound project.\n\nFirst-run order for a new user: 1) auracheck.whoami to check status. 2) If not signed in, auracheck.login — it opens the person's browser and waits up to ~90s for them to click Allow; if it times out, call it again. 3) auracheck.list_projects, ask the person which project, then auracheck.bind_project({ projectId }). 4) Proceed with the project tools (they fall back to the bound project when projectId is omitted).\n\n${serverInstructions('local')}`;\n\nfunction toolResultContent(result: unknown) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],\n };\n}\n\nfunction errorResultContent(err: unknown) {\n return {\n isError: true as const,\n content: [\n {\n type: 'text' as const,\n text: err instanceof Error ? err.message : String(err),\n },\n ],\n };\n}\n\nlet overridesRef: ContextOverrides = {};\nlet runtimeCtx: ResolvedContext;\n\n/**\n * The project tools fall back to, re-read fresh ONLY when nothing was\n * bound at boot: `auracheck.bind_project` can write a binding after the\n * server already started (that's the point — no restart needed), so a\n * boot-time-null default must be re-checked on every call.\n */\nasync function currentDefaultProjectId(): Promise<string | null> {\n if (overridesRef.projectId) return overridesRef.projectId;\n const envProjectId =\n process.env.AURACHECK_PROJECT_ID || process.env.SIXSEVEN_PROJECT_ID;\n if (envProjectId) return envProjectId;\n if (runtimeCtx.configPath) {\n const fresh = await readProjectConfig(runtimeCtx.repoRoot).catch(\n () => null,\n );\n if (fresh?.projectId) return fresh.projectId;\n }\n const creds = await readCredentials();\n return creds.defaultProjectId ?? null;\n}\n\n/**\n * Start the MCP server on stdio. It never exits for a missing project config\n * or sign-in: Claude Code would only show \"Failed to connect\". Instead every\n * tool call explains what is missing, and the saved token is re-read per call\n * so `auracheck login` takes effect without restarting the server.\n */\nexport async function runMcpServer(\n overrides: ContextOverrides = {},\n): Promise<void> {\n overridesRef = overrides;\n const ctx = await resolveContext(process.cwd(), overrides);\n runtimeCtx = ctx;\n const reader = new SourceReader({\n repoRoot: ctx.repoRoot,\n config: ctx.config ?? {\n baseUrl: ctx.baseUrl,\n projectId: ctx.projectId ?? '',\n defaultFeatureId: null,\n codeRoots: ['.'],\n exclude: DEFAULT_EXCLUDE,\n platform: ctx.platform,\n },\n });\n\n let cached: { token: string; api: AuraCheckApi } | null = null;\n async function currentApi(): Promise<AuraCheckApi> {\n const token =\n ctx.tokenSource === 'env' ? ctx.token : await getToken(ctx.baseUrl);\n if (!token) throw new NotSignedInError(ctx.baseUrl);\n if (cached?.token !== token) {\n cached = {\n token,\n api: new AuraCheckApi({\n baseUrl: ctx.baseUrl,\n token,\n signInHint: 'Run `auracheck login` in a terminal to sign in again.',\n }),\n };\n }\n return cached.api;\n }\n\n const server = new McpServer(\n { name: 'auracheck', version: CLI_VERSION },\n { instructions: ONBOARDING_INSTRUCTIONS },\n );\n\n // Local-only tools (fs, onboarding) — same handlers as before, now wired\n // through SDK v2's registerTool instead of a hand-rolled dispatch switch.\n for (const tool of LOCAL_TOOLS) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: toStandardSchemaWithJSON(tool.zod),\n },\n async (rawArgs: unknown) => {\n try {\n const parsed = tool.zod.parse(rawArgs ?? {});\n let api: AuraCheckApi;\n let signedIn: boolean;\n if (CODE_TOOLS.has(tool.name)) {\n api = null as unknown as AuraCheckApi;\n signedIn = false;\n } else if (NO_AUTH_TOOLS.has(tool.name)) {\n try {\n api = await currentApi();\n signedIn = true;\n } catch {\n api = null as unknown as AuraCheckApi;\n signedIn = false;\n }\n } else {\n api = await currentApi();\n signedIn = true;\n }\n const localCtx: ToolCtxLocal = {\n api,\n signedIn,\n reader,\n baseUrl: ctx.baseUrl,\n tokenSource: ctx.tokenSource === 'env' ? 'env' : 'credentials',\n config: ctx.config,\n repoRoot: ctx.repoRoot,\n };\n const result = await tool.handler(parsed, localCtx);\n return toolResultContent(result);\n } catch (err) {\n return errorResultContent(err);\n }\n },\n );\n }\n\n // mcp-core tools, registered under `auracheck.` + their local name alias\n // (§3.3 — e.g. `start_run` keeps advertising as `auracheck.execute_run`).\n for (const tool of ALL_TOOLS.filter((t) => t.surfaces.includes('local'))) {\n server.registerTool(\n `auracheck.${localName(tool)}`,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: toStandardSchemaWithJSON(tool.input),\n annotations: tool.annotations,\n },\n async (rawArgs: unknown) => {\n try {\n const api = await currentApi(); // throws NotSignedInError if not signed in — same as before.\n const account = await resolveLocalAccount(api, ctx.baseUrl);\n const defaultProjectId = await currentDefaultProjectId();\n const toolCtx = {\n api,\n surface: 'local' as const,\n appUrl: ctx.baseUrl,\n renewalUrl: account.renewalUrl,\n account,\n projectId: defaultProjectId,\n defaultPlatform: ctx.platform,\n onSetProject: async (projectId: string) => {\n if (ctx.config) {\n await writeProjectConfig(ctx.repoRoot, {\n ...ctx.config,\n projectId,\n });\n } else {\n await setDefaultProjectId(projectId);\n }\n },\n waitForRunMaxSec: 300,\n };\n const result = await callTool(tool.name, rawArgs, toolCtx);\n if (result.ok) return toolResultContent(result.result);\n return errorResultContent(new Error(result.error));\n } catch (err) {\n return errorResultContent(err);\n }\n },\n );\n }\n\n for (const prompt of PROMPTS) {\n server.registerPrompt(\n prompt.name,\n { title: prompt.name, description: prompt.description },\n () => ({\n messages: [\n {\n role: 'user' as const,\n content: { type: 'text' as const, text: prompt.text },\n },\n ],\n }),\n );\n }\n\n serveStdio(() => server, {\n // 2025-era clients (Claude Code's current MCP client, as of this\n // writing) open with the legacy `initialize` handshake; pin them to a\n // 2025-era instance from this same factory rather than rejecting them.\n legacy: 'serve',\n });\n logErr(\n `ready v${CLI_VERSION}. baseUrl=${ctx.baseUrl} project=${ctx.projectId ?? '(none bound)'} repo=${ctx.repoRoot}`,\n );\n\n currentApi()\n .then((api) => api.me())\n .then((u) => logErr(`signed in as ${u.email} (${u.role})`))\n .catch((err) =>\n logErr(\n `sign-in check failed: ${err instanceof ApiError || err instanceof NotSignedInError ? err.message : String(err)}`,\n ),\n );\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectConfig } from './config.js';\n\nconst DEFAULT_MAX_FILE_BYTES = 200_000;\nconst DEFAULT_MAX_SEARCH_RESULTS = 200;\nconst TEXT_EXT = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.json',\n '.yml',\n '.yaml',\n '.md',\n '.html',\n '.css',\n '.scss',\n '.less',\n '.toml',\n '.env',\n '.txt',\n '.py',\n '.go',\n '.rb',\n '.java',\n '.kt',\n '.swift',\n '.rs',\n '.php',\n '.cs',\n '.vue',\n '.svelte',\n '.sql',\n '.graphql',\n '.prisma',\n]);\n\nexport interface SourceReaderOptions {\n repoRoot: string;\n config: ProjectConfig;\n maxFileBytes?: number;\n}\n\nexport class SourceReader {\n private readonly repoRoot: string;\n private readonly roots: string[];\n private readonly excludeNames: Set<string>;\n private readonly excludeGlobs: string[];\n private readonly maxFileBytes: number;\n\n constructor(opts: SourceReaderOptions) {\n this.repoRoot = path.resolve(opts.repoRoot);\n this.roots = (\n opts.config.codeRoots.length ? opts.config.codeRoots : ['.']\n ).map((r) => path.resolve(this.repoRoot, r));\n const excludeNames = new Set<string>();\n const excludeGlobs: string[] = [];\n for (const e of opts.config.exclude) {\n if (e.includes('/') || e.includes('*')) excludeGlobs.push(e);\n else excludeNames.add(e);\n }\n this.excludeNames = excludeNames;\n this.excludeGlobs = excludeGlobs;\n this.maxFileBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;\n }\n\n /**\n * Resolve a user-supplied relative path. Rejects paths outside the repo root\n * and outside any configured codeRoot.\n */\n private resolveSafe(relPath: string): string {\n const cleaned = relPath.replace(/^[./\\\\]+/, '').replace(/\\\\/g, '/');\n const abs = path.resolve(this.repoRoot, cleaned);\n const repoRel = path.relative(this.repoRoot, abs);\n if (repoRel.startsWith('..') || path.isAbsolute(repoRel)) {\n throw new Error(`Path escapes repo root: ${relPath}`);\n }\n if (\n !this.roots.some(\n (root) => abs === root || abs.startsWith(root + path.sep),\n )\n ) {\n throw new Error(\n `Path is outside configured codeRoots (${this.roots\n .map((r) => path.relative(this.repoRoot, r))\n .join(', ')}): ${relPath}`,\n );\n }\n if (this.isExcluded(abs)) {\n throw new Error(`Path matches exclude pattern: ${relPath}`);\n }\n return abs;\n }\n\n private isExcluded(absPath: string): boolean {\n const rel = path.relative(this.repoRoot, absPath);\n const parts = rel.split(path.sep);\n if (parts.some((p) => this.excludeNames.has(p))) return true;\n for (const g of this.excludeGlobs) {\n if (rel.includes(g.replace(/\\*/g, ''))) return true;\n }\n return false;\n }\n\n async readFile(relPath: string): Promise<{\n path: string;\n bytes: number;\n content: string;\n truncated: boolean;\n }> {\n const abs = this.resolveSafe(relPath);\n const stat = await fs.stat(abs);\n if (!stat.isFile()) throw new Error(`Not a file: ${relPath}`);\n const ext = path.extname(abs).toLowerCase();\n if (ext && !TEXT_EXT.has(ext)) {\n throw new Error(\n `Refusing to read non-text file: ${relPath} (extension ${ext})`,\n );\n }\n const buf = await fs.readFile(abs);\n const truncated = buf.byteLength > this.maxFileBytes;\n const sliced = truncated ? buf.subarray(0, this.maxFileBytes) : buf;\n return {\n path: path.relative(this.repoRoot, abs),\n bytes: stat.size,\n content: sliced.toString('utf8'),\n truncated,\n };\n }\n\n async listDir(relPath: string): Promise<{\n path: string;\n entries: { name: string; type: 'file' | 'dir' }[];\n }> {\n const abs = this.resolveSafe(relPath || '.');\n const stat = await fs.stat(abs);\n if (!stat.isDirectory()) throw new Error(`Not a directory: ${relPath}`);\n const dirents = await fs.readdir(abs, { withFileTypes: true });\n const entries = dirents\n .filter((d) => !this.isExcluded(path.join(abs, d.name)))\n .map((d) => ({\n name: d.name,\n type: (d.isDirectory() ? 'dir' : 'file') as 'dir' | 'file',\n }))\n .sort((a, b) =>\n a.type === b.type\n ? a.name.localeCompare(b.name)\n : a.type === 'dir'\n ? -1\n : 1,\n );\n return { path: path.relative(this.repoRoot, abs), entries };\n }\n\n /**\n * Substring/regex search across configured codeRoots. Returns up to\n * maxResults matches (default 200). Walks the tree itself — no shell.\n */\n async search(\n query: string,\n opts: {\n regex?: boolean;\n caseSensitive?: boolean;\n maxResults?: number;\n } = {},\n ): Promise<{ file: string; line: number; preview: string }[]> {\n if (!query) return [];\n const maxResults = opts.maxResults ?? DEFAULT_MAX_SEARCH_RESULTS;\n const flags = opts.caseSensitive ? 'g' : 'gi';\n const re = opts.regex\n ? new RegExp(query, flags)\n : new RegExp(query.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags);\n\n const results: { file: string; line: number; preview: string }[] = [];\n\n const walk = async (dir: string): Promise<void> => {\n if (results.length >= maxResults) return;\n let dirents;\n try {\n dirents = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const d of dirents) {\n if (results.length >= maxResults) return;\n const abs = path.join(dir, d.name);\n if (this.isExcluded(abs)) continue;\n if (d.isDirectory()) {\n await walk(abs);\n } else if (d.isFile()) {\n const ext = path.extname(d.name).toLowerCase();\n if (ext && !TEXT_EXT.has(ext)) continue;\n let content: string;\n try {\n const buf = await fs.readFile(abs);\n if (buf.byteLength > this.maxFileBytes) continue;\n content = buf.toString('utf8');\n } catch {\n continue;\n }\n const lines = content.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (re.test(line)) {\n results.push({\n file: path.relative(this.repoRoot, abs),\n line: i + 1,\n preview: line.length > 240 ? `${line.slice(0, 240)}…` : line,\n });\n if (results.length >= maxResults) return;\n }\n re.lastIndex = 0;\n }\n }\n }\n };\n\n for (const root of this.roots) {\n await walk(root);\n if (results.length >= maxResults) break;\n }\n return results;\n }\n}\n"],"mappings":";;;AACA,OAAOA,WAAU;AACjB,SAAS,eAAe;AACxB,OAAOC,SAAQ;;;ACHf,OAAO,QAAQ;AACf,SAAS,SAAAC,cAAa;;;ACUhB,IAAO,WAAP,cAAwB,MAAK;EAEf;EACA;EAFlB,YACkB,QACA,UAChB,SAAe;AAEf,UAAM,OAAO;AAJG,SAAA,SAAA;AACA,SAAA,WAAA;AAIhB,SAAK,OAAO;EACd;;AAIK,IAAM,uBAAuB;AAQ9B,SAAU,SACd,QACA,aACA,aAAq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AA,CAAI,CAAC;AAChE,MAAI,QAAQ,IAAI,mBAAmB,QAAQ,IAAI,gBAAgB;AAC7D,YAAQ,OAAO,MAAM,GAAG,OAAO,KAAK,SAAS,EAAE,CAAC;AAAA,CAAI;AAAA,EACtD;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["path","pc","fetch","path","z","z","z","PROJECT_ID","z","z","PROJECT_ID","z","z","PROJECT_ID","z","z","PROJECT_ID","z","z","PROJECT_ID","z","z","PROJECT_ID","z","zodToJsonSchema","z","normalizeBaseUrl","fetch","fs","path","pc","fs","path","normalizeBaseUrl","pc","pc","prompts","normalizeBaseUrl","normalizeBaseUrl","prompts","pc","spawn","fs","path","pc","prompts","pc","spawn","prompts","normalizeBaseUrl","ok","path","fs","pc","pc","z","fs","path","z","path","normalizeBaseUrl","path","pc"]}